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

const validate = object({
  transferNoticeOrderId: string().required('请输入移库通知单ID'),
  transferNoticeOrderNo: string().required('请输入移库通知单号'),
  requestWarehouseId: string().required('请选择要货仓库'),
  entryNo: string().required('请输入分录号'),
  supplyWarehouseId: string().required('请选择供货仓库'),
  materialId: string().required('请选择物料信息'),
  measUnitId: string().required('请选择计量单位'),
  accountSleeve: string().required('请选择所属公司'),
  orderCount: number()
    .typeError('请输入数字')
    .required('请输入移库数量')
    .min(1, '衣裤数量不能小于1个'),
});

function parseParams(state: FormState): AddRelcationParams {
  const {
    transferNoticeOrderId,
    transferNoticeOrderNo,
    requestWarehouseId,
    supplyWarehouseId,
    materialId,
    entryNo,
    measUnitId,
    accountSleeve,
    orderCount,
    WBS,
    docDate,
  } = state;

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

  return [
    {
      transferNoticeOrderId,
      transferNoticeOrderNo,
      requestWarehouseId,
      moveType: '345',
      docDate: date,
      datalist: [
        {
          supplyWarehouseId,
          materialId,
          entryNo,
          measUnitId,
          accountSleeve,
          orderCount,
          WBS,
          transferNoticeOrderId,
        },
      ],
    },
  ];
}

export function useFormState({
  visible,
  onClose,
  onFetch,
  onSearch,
}: {
  visible: boolean;
  onClose: () => void;
  onFetch: () => void;
  onSearch: (val: string) => void;
}) {
  const {clearErrors, reset, handleSubmit, control} = useForm<FormState>({
    resolver: yupResolver(validate),
    defaultValues: {
      transferNoticeOrderId: '',
      transferNoticeOrderNo: '',
      requestWarehouseId: '',
      supplyWarehouseId: '',
      materialId: '',
      entryNo: '',
      measUnitId: '',
      accountSleeve: '',
      orderCount: 0,
      WBS: '',
      docDate: dayjs(),
    },
  });

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

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

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

    mutate(params);
  });

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