import {addRole, editRole, getRoleInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {AddRoleParams} from '@models';
import {useMutation, useQuery} from '@tanstack/react-query';
import {message} from 'antd';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

type FormState = {
  roleName: string;
  roleRemarks: string;
};

const validate = object({
  roleName: string().required('请输入角色名称'),
});

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

  return [isLoading, mutate] as const;
}

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

  return [isLoading, mutate] as const;
}

export function useFormState(
  {visible, onFetch, onClose, id}:
  {
    visible: boolean, id: string,
    onFetch: () => void, onClose: () => void
  },
) {
  const formInstance = useForm<FormState>({
    defaultValues: {
      roleName: '',
      roleRemarks: '',
    },
    resolver: yupResolver(validate),
  });
  const {handleSubmit, clearErrors} = formInstance;

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

  const [addIsLoading, addMutate] = useAdd(onFetch, onClose);
  const [editIsLoading, editMutate] = useEdit(onFetch, onClose);
  const isLoading = addIsLoading || editIsLoading;

  const onSubmit = handleSubmit(function({roleName, roleRemarks}) {
    const params: AddRoleParams = {remarks: roleRemarks, roleName};

    id ? editMutate({id, ...params}) : addMutate(params);
  });

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

export function useField() {
  return useFormContext<FormState>();
}

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

  const {data} = useQuery(
    [getRoleInfo.name, id],
    async function() {
      const data = await getRoleInfo(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('roleName', data?.roleName ?? '');
    setValue('roleRemarks', data?.remarks ?? '');
  }, [data, setValue]);
}
