import {getNoticeList, semiManufacturesAdd} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {NoticeListData} 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 {object, string} from 'yup';
import {useStore} from 'zustand';

type FormState = {
  /** 仓库id */
  warehouse: string;
  /** 库位id */
  location: string;
};

const validate = object({
  warehouse: string().required('请选择仓库'),
  location: string().required('请选择库位'),
});

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

  return useMemo(
    function () {
      const data = client.getQueryData<NoticeListData[]>([getNoticeList.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: '', location: ''},
    });

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

  const data = useData(id);

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

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

  const onSubmit = handleSubmit(function ({location}) {
    if (!data) return message.error('未获取到报工单信息');
    const {companyNumber, materialId, noticeId, wbs, wllbClass, wllbCode, num} =
      data;

    mutate({
      companyNumber,
      materialId,
      noticeId,
      wbs,
      wllbClass,
      wllbCode,
      userId,
      warehousingNum: num,
      storageLocationCode: location,
    });
  });

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