import {editDictionary, getDictionaryInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {useQueryDataInfo} from '@hooks';
import {useMutation} from '@tanstack/react-query';
import {message} from 'antd';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {number, object, string} from 'yup';

type FormState = {
  goodsType: string;
  goodsSize: number;
  goodsMixin: string;
  goodsRecommend: string;
  goodsPartType: string;
  goodsMinNum: number;
  goodsMaxNum: number;
};

const validate = object({
  goodsType: string().required('请选择物料类型'),
  goodsSize: number()
    .typeError('请输入数字')
    .min(1, '不能小于1个')
    .required('请输入物料存储容量'),
  goodsMixin: string().required('请选择是否混合存储'),
  goodsRecommend: string().required('请选择是否推荐库位'),
  goodsPartType: string().required('请输入物料类别'),
  goodsMinNum: number()
    .required('请输入最小储存数量')
    .typeError('请输入数字类型')
    .min(0, '数量不能小于0个'),
  goodsMaxNum: number()
    .required('请输入最大头储存数量')
    .typeError('请输入数字类型')
    .min(0, '数量不能小于0个'),
});

export function useFormState({
  visible,
  id,
  onClose,
  onFetch,
}: {
  onClose: () => void;
  onFetch: () => void;
  visible: boolean;
  id: string;
}) {
  const formInstance = useForm<FormState>({
    defaultValues: {
      goodsType: '',
      goodsSize: 0,
      goodsMixin: '',
      goodsRecommend: '',
      goodsPartType: '',
      goodsMaxNum: 0,
      goodsMinNum: 0,
    },
    resolver: yupResolver(validate),
  });

  const {clearErrors, handleSubmit} = formInstance;

  useEffect(
    function () {
      visible && clearErrors();
    },
    [visible, clearErrors],
  );

  const {isLoading, mutate} = useMutation({
    mutationFn: editDictionary,
    onSuccess({msg}) {
      if (msg === '200') {
        onClose();
        onFetch();
        message.success('修改成功');
      }
    },
  });

  const onSubmit = handleSubmit(function ({
    goodsMixin,
    goodsSize,
    goodsType,
    goodsRecommend,
    goodsPartType,
    goodsMaxNum,
    goodsMinNum,
  }) {
    mutate({
      isNotDisable: goodsMixin,
      size: String(goodsSize),
      id,
      materialType: goodsType,
      isRecommend: goodsRecommend,
      partType: goodsPartType,
      minNum: String(goodsMinNum),
      maxNum: String(goodsMaxNum),
    });
  });

  return [{formInstance, isLoading}, {onSubmit}] as const;
}

export function useControl() {
  const {control} = useFormContext<FormState>();

  return control;
}

export function useWatchId(id: string) {
  const {setValue} = useFormContext<FormState>();
  const data = useQueryDataInfo({
    queryFn: getDictionaryInfo,
    params: ['物料字典', id],
    enabled: Boolean(id),
  });

  useEffect(
    function () {
      setValue('goodsType', data?.wllbClass ?? '');
      setValue('goodsSize', Number(data?.size ?? '0'));
      setValue('goodsMixin', data?.isNotDisable ?? '');
      setValue('goodsRecommend', data?.isRecommend ?? '');
      setValue('goodsPartType', data?.partType ?? '');
      setValue('goodsMaxNum', Number(data?.maxNum ?? '0'));
      setValue('goodsMinNum', Number(data?.minNum ?? '0'));
    },
    [data, setValue],
  );
}
