import {useForm} from 'react-hook-form';
import {yupResolver} from '@hookform/resolvers/yup';
import {object, string} from 'yup';
import {useMutation} from '@tanstack/react-query';
import {userLogin} from '@apis';
import {useBoolean, useLocalStorageState} from 'ahooks';
import {message} from 'antd';
import {useStore} from 'zustand';
import {userStore} from '@stores';
import {useNavigate} from 'react-router-dom';
import {HOME_PATH} from '@routes';
import {
  MEMO_USER_STORAGE,
  USER_ALL_LOGIN_STORAGE,
  USER_NAME_LOGIN_STORAGE,
  USER_TOKEN_STORAGE,
} from '@utils';

type FormState = {
  name: string;
  password: string;
  type: string;
};

const validate = object({
  name: string().required('请输入账号'),
  password: string().required('请输入密码'),
  type: string().required('请选择系统'),
});

function useLogin({user, all}: {user: boolean; all: boolean}) {
  const [state, {set}] = useBoolean();
  const userStoreDispatch = useStore(userStore, state => state.init);
  const navigate = useNavigate();

  const mutation = useMutation(
    async function (params: {name: string; password: string}) {
      const {name, password} = params;
      return userLogin(name, password);
    },
    {
      onSuccess(data, {name, password}) {
        if (data.msg === '200') {
          localStorage.setItem(
            MEMO_USER_STORAGE,
            `{"userName": "${user || all ? name : ''}", "password": "${
              all ? password : ''
            }"}`,
          );

          message.success('登录成功');
          sessionStorage.setItem(USER_TOKEN_STORAGE, JSON.stringify(data.data));
          set(true);
          userStoreDispatch(data.data);
          navigate(HOME_PATH, {replace: true});
        }
      },
    },
  );

  return {...mutation, isDisable: state};
}

export function useFormState(memo: {user: boolean; all: boolean}) {
  const [{userName, password}] = useLocalStorageState(MEMO_USER_STORAGE, {
    defaultValue: {userName: '', password: ''},
  });

  const {
    handleSubmit,
    formState: {errors},
    control,
  } = useForm<FormState>({
    resolver: yupResolver(validate),
    defaultValues: {
      type: '1',
      name: userName,
      password,
    },
  });
  const {isLoading, mutate, isDisable} = useLogin(memo);

  const onSubmit = handleSubmit(function (val) {
    const {name, password} = val;
    mutate({name, password});
  });

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

export function useUserMemo() {
  const [memoUserName, {set: setMemoUserName}] = useBoolean(
    Boolean(localStorage.getItem(USER_NAME_LOGIN_STORAGE)),
  );
  const [memoAll, {set: setMemoAll}] = useBoolean(
    Boolean(localStorage.getItem(USER_ALL_LOGIN_STORAGE)),
  );

  function onChange(key: 'userName' | 'all') {
    return function (val: boolean) {
      const storageKey =
        key === 'userName' ? USER_NAME_LOGIN_STORAGE : USER_ALL_LOGIN_STORAGE;
      const setFn = key === 'userName' ? setMemoUserName : setMemoAll;

      localStorage.setItem(storageKey, val ? '1' : '');
      setFn(val);
    };
  }

  return [{memoUserName, memoAll}, onChange] as const;
}
