import {addSell} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {useMutateAddOrder} from '@hooks';
import {AddSellParams} from '@models';
import {useLatest} from 'ahooks';
import dayjs, {Dayjs} from 'dayjs';
import {useEffect} from 'react';
import {useForm} from 'react-hook-form';
import {number, object, string} from 'yup';

type FormState = Omit<
  AddSellParams[0],
  'datalist' | 'docDate' | 'sourceType' | 'moveType' | 'operationType'
> & {
  docDate: Dayjs;
} & AddSellParams[0]['datalist'][0];

const validate = object({
  deliveryOrderId: string().required('请输入销售单ID'),
  deliveryOrderNo: string().required('请输入销售单编号'),
  companyNumber: string().required('请选择公司'),
  customerNo: string().required('请选择客户'),
  deloveryGoodsType: string().required('请选择交货类型'),
  entryNumber: string().required('请输入分录号'),
  materialId: string().required('请选择物料'),
  measUnitId: string().required('请选择计量单位'),
  gsDeliveryCount: number()
    .typeError('请输入数字')
    .required('请输入交货数量')
    .min(1, '交货数量不能小于1'),
  gsCancelDeliveryCount: number()
    .typeError('请输入数字')
    .required('请输入交货数量')
    .min(0, '取消交货数量不能小于1'),
});

function parseParams(state: FormState): AddSellParams {
  const {
    deliveryOrderId,
    deliveryOrderNo,
    companyNumber,
    customerNo,
    entryNumber,
    materialId,
    measUnitId,
    gsDeliveryCount,
    gsCancelDeliveryCount,
    docDate,
    WBS,
    deloveryGoodsType,
  } = state;

  const date = docDate.format('YYYY-MM-DD');

  return [
    {
      deliveryOrderId,
      deliveryOrderNo,
      companyNumber,
      customerNo,
      deloveryGoodsType,
      sourceType: deloveryGoodsType === 'DE' ? '1' : 'U',
      moveType: '201',
      operationType: '1',
      docDate: date,
      datalist: [
        {
          deliveryOrderId,
          entryNumber,
          materialId,
          measUnitId,
          gsDeliveryCount,
          gsCancelDeliveryCount,
          WBS,
        },
      ],
    },
  ];
}

export function useFormState({
  visible,
  onClose,
  onFetch,
  onSearch,
}: {
  visible: boolean;
  onClose: () => void;
  onFetch: () => void;
  onSearch: () => void;
}) {
  const {clearErrors, reset, control, handleSubmit} = useForm<FormState>({
    resolver: yupResolver(validate),
    defaultValues: {
      deliveryOrderId: '',
      deliveryOrderNo: '',
      companyNumber: '',
      customerNo: '',
      entryNumber: '',
      materialId: '',
      measUnitId: '',
      gsDeliveryCount: 0,
      gsCancelDeliveryCount: 0,
      docDate: dayjs(),
      WBS: '',
      deloveryGoodsType: '',
    },
  });

  const clearSearch = useLatest(onSearch);

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

  const [isLoading, mutate] = useMutateAddOrder(addSell, onFetch, onClose);

  const onSubmit = handleSubmit(function (state) {
    const params = parseParams(state);

    mutate(params);
  });

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