import { useDispatch } from 'react-redux'
import type { Dispatch } from 'redux'
import { UserInfoActionType } from '@/constants/userInfo'
import type { SortCodeParam, UserAdminParam, UserInfoAction, UserParam } from '@/reducers/userInfo'
import { useSelector } from '@/reducers/hooks'

export default () => {
  const userInfo = useSelector(state => state.userInfoData)
  const dispatch = useDispatch<Dispatch<UserInfoAction>>()

  const setToken = (token: string) => {
  // @ts-expect-error data 类型没有约束好
    dispatch({ type: UserInfoActionType.SET_TOKEN, data: { token } })
  }

  const setSessionKey = (sessionkey: string) => {
  // @ts-expect-error data 类型没有约束好
    dispatch({ type: UserInfoActionType.SET_SESSIONKEY, data: { session_key: sessionkey } })
  }

  const setUserInfo = (userInfoProp: UserParam) => {
  // @ts-expect-error data 类型没有约束好
    dispatch({ type: UserInfoActionType.SET_USERINFO, data: { userInfo: userInfoProp } })
  }

  const setAdminUserInfo = (adminUserInfo: UserAdminParam) => {
  // @ts-expect-error data 类型没有约束好
    dispatch({ type: UserInfoActionType.SET_ADMINUSERINFO, data: { adminUserInfo } })
  }

  const setSortCode = (sortCode: SortCodeParam) => {
  // @ts-expect-error data 类型没有约束好
    dispatch({ type: UserInfoActionType.SET_SORTCODE, data: { sort_code: sortCode } })
  }

  const removeUserInfo = () => {
    dispatch({ type: UserInfoActionType.CLEAR_USERINFO })
  }

  const removeToken = () => {
    dispatch({ type: UserInfoActionType.CLEAR_TOKEN })
  }

  const removeSessionKey = () => {
    dispatch({ type: UserInfoActionType.CLEAR_SESSIONKEY })
  }

  return {
    setToken,
    setUserInfo,
    setAdminUserInfo,
    setSessionKey,
    removeUserInfo,
    removeToken,
    removeSessionKey,
    setSortCode,
    userInfo, // 响应式数据返回
  }
}
