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

type FormState = {
  scrapNote: string,
  scrapNum: number,
};

const validate = object({
  scrapNum: number().typeError('请输入数字类型')
    .min(1, '废弃数量不能低于1个').required('请输入废弃数量'),
  scrapNote: string().required('请输入废弃原因'),
});

function useScrap(onFetch: () => void, onClose: () => void) {
  return useMutation(
    containerScrap,
    {
      onSuccess({msg}) {
        if (msg === '200') {
          message.success('报废成功');
          onFetch();
          onClose();
        }
      },
    },
  );
}

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

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

  const {isLoading, mutate} = useScrap(onFetch, onClose);
  const userId = useStore(userStore, state => state.id);
  const onSubmit = handleSubmit(function({scrapNote, scrapNum}) {
    mutate({
      scrapNum: String(scrapNum),
      scrapCause: scrapNote,
      userId: String(userId),
      id,
    });
  });

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