import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';
import {yupResolver} from '@hookform/resolvers/yup';
import {useMutation, useQuery} from '@tanstack/react-query';
import {addDepartment, editDepartment, getDepartmentInfo} 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, id}:
  {
    visible: boolean,
    onClose: () => void,
    onFetch: () => void,
    id: string;
  },
) {
  const isEdit = Boolean(id);
  const formInstance = useForm<FormState>({
    defaultValues: {departmentName: ''},
    resolver: yupResolver(validate),
  });
  const {handleSubmit, clearErrors} = formInstance;
  const [isAddLoading, addMutate] = useAdd(onClose, onFetch);
  const [isEditLoading, editMutate] = useEdit(onClose, onFetch);

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

  const isLoading = isAddLoading || isEditLoading;

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

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

export function useField() {
  const {control} = useFormContext<FormState>();

  return [{control}] as const;
}

export function useFormValues(id: string) {
  const {setValue} = useFormContext<FormState>();

  const {data} = useQuery(
    [getDepartmentInfo.name, id, 'PDA'],
    async function() {
      const data = await getDepartmentInfo(id);

      if (data.msg === '200') {
        if (data.data.list.length) return data.data.list[0];

        throw new Error('未获取到部门信息');
      }

      throw new Error(data.errMsg);
    },
    {
      enabled: Boolean(id),
      suspense: true,
      cacheTime: 0,
    },
  );

  useEffect(function() {
    setValue('departmentName', data?.departmentName ?? '');
  }, [data, setValue]);
}
