import {getSemiManufacturesDrawList, semiManufacturesOut} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {SemiDrawListData} from '@models';
import {userStore} from '@stores';
import {useMutation, useQueryClient} from '@tanstack/react-query';
import {message} from 'antd';
import {useEffect, useMemo} from 'react';
import {useForm} from 'react-hook-form';
import {number, object, string} from 'yup';
import {useStore} from 'zustand';

type FormState = {
  /** 仓库id */
  warehouse: string;
  /** 库位id */
  location: string;
  /** 出库数量 */
  outNum: number;
};

const validate = object({
  warehouse: string().required('请选择仓库'),
  location: string().required('请选择库位'),
  outNum: number()
    .typeError('请输入数字')
    .required('请输入出库数量')
    .min(1, '出库数量不能小于1个'),
});

function useData(id: string) {
  const client = useQueryClient();

  return useMemo(
    function () {
      const data = client.getQueryData<SemiDrawListData[]>(
        [getSemiManufacturesDrawList.name],
        {
          exact: false,
        },
      );
      if (!data) return void 0;

      return data.find(val => val.id === id);
    },
    [client, id],
  );
}

export function useFormState({
  visible,
  onClose,
  onFetch,
  id,
}: {
  id: string;
  visible: boolean;
  onClose: () => void;
  onFetch: () => void;
}) {
  const {control, handleSubmit, reset, clearErrors, watch, setValue} =
    useForm<FormState>({
      resolver: yupResolver(validate),
      defaultValues: {warehouse: '', outNum: 0, location: ''},
    });

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

  const data = useData(id);

  const {isLoading, mutate} = useMutation({
    mutationFn: semiManufacturesOut,
    onSuccess({msg}) {
      if (msg === '200') {
        onClose();
        onFetch();
        message.success('出库完成');
      }
    },
  });

  const userId = useStore(userStore, state => String(state.id));

  const onSubmit = handleSubmit(function ({location, outNum}) {
    if (!data) return message.error('未获取到领料单信息');

    const {companyNumber, wbs, materialId, askGoodsId, materialCode} = data;

    mutate({
      companyNumber,
      wbs,
      materialId,
      warehousingNum: String(outNum),
      askGoodsId,
      wllbCode: materialCode,
      storageLocationCode: location,
      userId,
    });
  });

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