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

type FormState = Omit<
  AddProductionRequisitionParams[0],
  'datalist' | 'requestDate' | 'moveType' | 'sourceType'
> &
  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,
  type: '1' | '2',
): AddUnProductionRequisitionParams {
  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,
      sourceType: '8',
      moveType: type === '1' ? '207' : 'Z05',
      requestDate: date,
      applicationDate: date,
      ifCommodity,
      requestTypeNumber,
      requestTypeName,
      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 type = useContextSection(context, state => state[0].type);

  const {control, reset, clearErrors, handleSubmit} = useForm<FormState>({
    resolver: yupResolver(validate),
    defaultValues: {
      requestOrderId: '',
      requestOrderNo: '',
      companyNo: '',
      useDepartment: '',
      entryNumber: '',
      prodOrderNo: '',
      materialId: '',
      WBS: '',
      measUnitId: '',
      orderCount: 0,
      requestDate: dayjs(),
      requestTypeNumber: '',
      requestTypeName: '',
      ifCommodity: '',
    },
  });

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

  const [isLoading, mutate] = useMutateAddOrder(
    type === '1' ? addProductionRequisition : addUnProductionRequisition,
    onFetch,
    onClose,
  );

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

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