import {addUser, editUser, getUserInfo} from '@apis';
import {yupResolver} from '@hookform/resolvers/yup';
import {usePutData, useQueryDataInfo} from '@hooks';
import {EditUserParams} from '@models';
import {useEffect} from 'react';
import {useForm, useFormContext} from 'react-hook-form';
import {object, string} from 'yup';

export type FormState = {
  userName: string;
  userPassword: string;
  userEmail: string;
  userPhone: string;
  userDepartment: string;
  userRole: string;
  userRealName: string;
};

const validate = object({
  userName: string().required('请输入用户名'),
  userPassword: string().required('请输入用户密码'),
  userDepartment: string().required('请选择部门'),
  userRole: string().required('请选择角色'),
  userRealName: string().required('请输入姓名'),
});

export function useFormState({
  onClose,
  onFetch,
  id,
  visible,
}: {
  onClose: () => void;
  onFetch: () => void;
  id: string;
  visible: boolean;
}) {
  const formInstance = useForm<FormState>({
    defaultValues: {
      userName: '',
      userPassword: '',
      userEmail: '',
      userPhone: '',
      userDepartment: '',
      userRole: '',
      userRealName: '',
    },
    resolver: yupResolver(validate),
  });
  const {handleSubmit, clearErrors} = formInstance;

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

  const [isLoading, {addMutate, editMutate}] = usePutData({
    addFn: addUser,
    editFn: editUser,
    onFetch,
    onClose,
  });

  const onSubmit = handleSubmit(function ({
    userName,
    userPassword,
    userEmail,
    userPhone,
    userDepartment,
    userRole,
    userRealName,
  }) {
    const params: Omit<EditUserParams, 'id' | 'modifyTime' | 'modifyUser'> = {
      userName,
      realName: userRealName,
      email: userEmail,
      phone: userPhone,
      department: userDepartment,
      role: userRole,
    };

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

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

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

export function useFetchUserInfo(id: string) {
  const data = useQueryDataInfo({
    queryFn: getUserInfo,
    params: [id],
    enabled: Boolean(id),
  });

  const {setValue} = useFormContext<FormState>();

  useEffect(
    function () {
      setValue('userName', data?.userName ?? '');
      setValue('userPassword', data?.password ?? '');
      setValue('userEmail', data?.email ?? '');
      setValue('userPhone', data?.phone ?? '');
      setValue('userRole', data?.roleId ?? '');
      setValue('userDepartment', data?.departmentId ?? '');
      setValue('userRealName', data?.realName ?? '');
    },
    [data, setValue],
  );
}
