import {addReporting} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {useMutateAddOrder} from '@hooks';
import {AddReportingParams} 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<
  AddReportingParams[0],
  'datalist' | 'noticeDate' | 'sourceType' | 'moveType'
> &
  AddReportingParams[0]['datalist'][0] & {noticeDate: Dayjs};

const validate = object({
  stockInNoticeId: string().required('请输入报工单ID'),
  stockInNoticeNo: string().required('请输入报工单编号'),
  companyNo: string().required('请选择公司'),
  entryNumber: string().required('请输入分录号'),
  prodOrderNo: string().required('请输入生产订单号'),
  materialId: string().required('请选择物料'),
  measUnitId: string().required('请选择计量单位'),
  orderCount: number()
    .typeError('请输入数字')
    .required('请输入数量')
    .min(1, '数量不能小于1个'),
  notificationTypeNumber: string().required('请输入通知类型编号'),
  notificationTypeName: string().required('请输入通知类型名称'),
});

function parseParams(state: FormState): AddReportingParams {
  const {
    stockInNoticeId,
    stockInNoticeNo,
    companyNo,
    entryNumber,
    prodOrderNo,
    materialId,
    WBS,
    measUnitId,
    orderCount,
    noticeDate,
    notificationTypeNumber,
    notificationTypeName,
  } = state;

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

  return [
    {
      stockInNoticeId,
      stockInNoticeNo,
      companyNo,
      sourceType: 'G',
      moveType: '104',
      noticeDate: date,
      notificationTypeNumber,
      notificationTypeName,
      datalist: [
        {
          entryNumber,
          prodOrderNo,
          materialId,
          WBS,
          measUnitId,
          orderCount,
          stockInNoticeId,
        },
      ],
    },
  ];
}

export function useFormState({
  visible,
  onClose,
  onFetch,
  onSearch,
}: {
  visible: boolean;
  onClose: () => void;
  onFetch: () => void;
  onSearch: (val: string) => void;
}) {
  const {control, handleSubmit, reset, clearErrors} = useForm<FormState>({
    resolver: yupResolver(validate),
    defaultValues: {
      stockInNoticeId: '',
      stockInNoticeNo: '',
      companyNo: '',
      entryNumber: '',
      prodOrderNo: '',
      materialId: '',
      WBS: '',
      measUnitId: '',
      orderCount: 0,
      noticeDate: dayjs(),
      notificationTypeNumber: '',
      notificationTypeName: '',
    },
  });

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

  const [isLoading, mutate] = useMutateAddOrder(addReporting, onFetch, onClose);
  const onSubmit = handleSubmit(function (state) {
    const params = parseParams(state);

    mutate(params);
  });

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