import {addRole, editRole, getRoleList} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {useContextSection} from '@hooks';
import {AddRoleParams, RoleListData} from '@models';
import {context, pageContext} from '@pages/role/context';
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';

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;
}

function useEditData(id: string, isEdit: boolean) {
  const client = useQueryClient();
  const {page, pageSize} = useContextSection(pageContext, state => state[0]);
  const name = useContextSection(context, state => state[0].name);

  const data = useMemo(function() {
    if (!isEdit) return null;
    const state = client.getQueryData<RoleListData[]>([getRoleList.name, page, pageSize, name]);

    return state?.find(val => String(val.id) === id);
  }, [client, id, isEdit, name, page, pageSize]);

  return data;
}

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

  useEffect(
    function() {
      if (visible) {
        setValue('roleName', editData?.roleName ?? '');
        setValue('roleRemarks', editData?.remarks ?? '');
        clearErrors();
      }
    },
    [clearErrors, editData?.remarks, editData?.roleName, setValue, 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.length ? editMutate({id, ...params}) : addMutate(params);
  });

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