import {addQuality} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {AddQualityParams} from '@models';
import {useMutation} from '@tanstack/react-query';
import {useLatest} from 'ahooks';
import {message} from 'antd';
import dayjs, {Dayjs} from 'dayjs';
import {useEffect} from 'react';
import {useForm} from 'react-hook-form';
import {number, object, string} from 'yup';

type FormState = {
  /** 采购单id */
  poId: string;
  /** 采购单编号 */
  poNo: string;
  /** 公司编号 */
  companyNo: string;
  /** 供应商编号 */
  supplierNo: string;
  /** 订单日期 */
  poDate: Dayjs;
  /** wbs */
  WBS: string;
  /** 分录号 */
  entryNumber: string;
  /** 物料id */
  materialId: string;
  /** 计量单位id */
  measUnitId: string;
  /** 采购数量 */
  purchaseCount: number;
  /** 收货数量 */
  receiveCount: number;
  /** 本次合格品数量 */
  curOkCount: number;
  /** 本次不合格品数量 */
  curNgCount: number;
  /** 订单类型 */
  poType: string;
};

const validate = object({
  poId: string().required('请输入采购单ID'),
  poNo: string().required('请输入采购单编号'),
  companyNo: string().required('请选择公司'),
  supplierNo: string().required('请选择供应商'),
  entryNumber: string().required('请输入分录号'),
  materialId: string().required('请选择物料'),
  measUnitId: string().required('请选择计量单位'),
  purchaseCount: number()
    .typeError('请输入数字类型')
    .required('请输入采购数量')
    .min(1, '采购数量不能小于1个'),
  receiveCount: number()
    .typeError('请输入数字类型')
    .required('请输入收货数量')
    .min(1, '收货数量不能小于1个'),
  curOkCount: number()
    .typeError('请输入数字类型')
    .required('请输入合格品数量')
    .min(0, '合格品数量不能小于0个'),
  curNgCount: number()
    .typeError('请输入数字类型')
    .required('请输入不合格品数量')
    .min(0, '不合格品数量不能小于0个'),
  poType: string().required('请选择订单类型'),
});

function parseParams(state: FormState): AddQualityParams {
  const {
    poId,
    poNo,
    companyNo,
    supplierNo,
    poDate,
    entryNumber,
    materialId,
    measUnitId,
    purchaseCount,
    receiveCount,
    curOkCount,
    curNgCount,
    WBS,
    poType,
  } = state;

  const formatDate = poDate.format('YYYY-MM-DD');

  return [
    {
      poId,
      poNo,
      companyNo,
      supplierNo,
      poDate: formatDate,
      poType,
      sourceType: poType === 'NB' ? '5' : '6',
      moveType: '101',
      datalist: [
        {
          entryNumber,
          WBS,
          materialId,
          measUnitId,
          purchaseCount,
          receiveCount,
          curOkCount,
          curNgCount,
        },
      ],
    },
  ];
}

export function useFormState({
  visible,
  onFetch,
  onClose,
  onSearch,
}: {
  visible: boolean;
  onFetch: () => void;
  onClose: () => void;
  onSearch: () => void;
}) {
  const {control, handleSubmit, reset, clearErrors} = useForm<FormState>({
    resolver: yupResolver(validate),
    defaultValues: {
      poDate: dayjs(),
      poId: '',
      poNo: '',
      companyNo: '',
      supplierNo: '',
      WBS: '',
      entryNumber: '',
      materialId: '',
      measUnitId: '',
      purchaseCount: 0,
      receiveCount: 0,
      curOkCount: 0,
      curNgCount: 0,
      poType: '',
    },
  });

  const clearSearch = useLatest(onSearch);

  useEffect(
    function () {
      if (visible) {
        reset();
        clearErrors();
        clearSearch.current();
      }
    },
    [clearErrors, reset, visible, clearSearch],
  );

  const {isLoading, mutate} = useMutation({
    mutationFn: addQuality,
    onSuccess({status}) {
      if (status === '0000') {
        message.success('新增成功');
        onFetch();
        onClose();
      }
    },
  });
  const onSubmit = handleSubmit(function (val) {
    const params = parseParams(val);
    mutate(params);
  });

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