import {useEffect} from 'react';
import {useForm} from 'react-hook-form';
import {object, string} from 'yup';
import {yupResolver} from '@hookform/resolvers/yup';
import {useMutation} from '@tanstack/react-query';
import {addDepartment, editDepartment} from '@apis';
import {message} from 'antd';

type FormState = {
  departmentName: string;
};

const validate = object({
  departmentName: string().required('请输入部门名称'),
});

function useAdd(onClose: () => void, onFetch: () => void) {
  const {isLoading, mutate} = useMutation(
    addDepartment,
    {
      onSuccess(data) {
        if (data.msg === '200') {
          onClose();
          onFetch();
          message.success('新增成功');
        }
      },
    });

  return [isLoading, mutate] as const;
}

function useEdit(onClose: () => void, onFetch: () => void) {
  const {isLoading, mutate} = useMutation(
    editDepartment,
    {
      onSuccess(data) {
        if (data.msg === '200') {
          onClose();
          onFetch();
          message.success('修改成功');
        }
      },
    });

  return [isLoading, mutate] as const;
}

export function useFormState(
  {visible, onClose, onFetch, name, id}:
  {
    visible: boolean,
    onClose: () => void,
    onFetch: () => void,
    name?: string,
    id?: string;
  },
) {
  const isEdit = id && name;
  const {control, setValue, handleSubmit, clearErrors} = useForm<FormState>({
    defaultValues: {departmentName: ''},
    resolver: yupResolver(validate),
  });
  const [isAddLoading, addMutate] = useAdd(onClose, onFetch);
  const [isEditLoading, editMutate] = useEdit(onClose, onFetch);

  const isLoading = isAddLoading || isEditLoading;

  useEffect(function() {
    if (visible) {
      setValue('departmentName', isEdit ? name : '');
      clearErrors();
    }
  }, [clearErrors, setValue, visible, name, isEdit]);

  const onSubmit = handleSubmit(function({departmentName}) {
    isEdit ? editMutate({id, name: departmentName}) : addMutate(departmentName);
  });

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