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

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

const validate = object({
  requestOrderId: string().required('请输入要货申请单ID'),
  requestOrderNo: string().required('请输入要货申请单编号'),
  companyNo: string().required('请选择公司'),
  useDepartment: string().required('请选择领用部门'),
  entryNumber: string().required('请输入分录号'),
  prodOrderNo: string().required('请输入生产订单号'),
  materialId: string().required('请选择物料'),
  measUnitId: string().required('请选择计量单位'),
  orderCount: number()
    .typeError('请输入数字')
    .required('请输入数量')
    .min(1, '数量不能低于1个'),
  requestTypeNumber: string().required('请输入申请类型编号'),
  requestTypeName: string().required('请输入申请类型名称'),
  ifCommodity: string().required('请选择退换货类型'),
});

function parseParams(state: FormState): AddProductionRequisitionParams {
  const {
    requestOrderId,
    requestOrderNo,
    companyNo,
    useDepartment,
    entryNumber,
    prodOrderNo,
    materialId,
    WBS,
    measUnitId,
    orderCount,
    requestDate,
    requestTypeNumber,
    requestTypeName,
    ifCommodity,
  } = state;

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

  return [
    {
      requestOrderId,
      requestOrderNo,
      companyNo,
      useDepartment,
      requestDate: date,
      applicationDate: date,
      requestTypeNumber,
      requestTypeName,
      ifCommodity,
      sourceType: '8',
      moveType: '207',
      datalist: [
        {
          entryNumber,
          prodOrderNo,
          materialId,
          WBS,
          measUnitId,
          orderCount,
          requestOrderId,
        },
      ],
    },
  ];
}

export function useFormState({
  visible,
  onClose,
  onFetch,
  onSearch,
}: {
  visible: boolean;
  onClose: () => void;
  onFetch: () => void;
  onSearch: (val: string) => void;
}) {
  const {control, reset, clearErrors, handleSubmit} = useForm<FormState>({
    resolver: yupResolver(validate),
    defaultValues: {
      requestOrderId: '',
      requestOrderNo: '',
      companyNo: '',
      useDepartment: '',
      entryNumber: '',
      prodOrderNo: '',
      materialId: '',
      WBS: '',
      measUnitId: '',
      orderCount: 0,
      requestDate: dayjs(),
      ifCommodity: '',
      requestTypeNumber: '',
      requestTypeName: '',
    },
  });

  useEffect(
    function () {
      if (visible) {
        reset();
        clearErrors();
        onSearch('');
      }
    },
    [clearErrors, onSearch, reset, visible],
  );

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

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

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