import { useDispatch, useSelector } from 'react-redux'
import { CLEAR_SESSIONKEY, CLEAR_TOKEN, CLEAR_USERINFO, SET_ADMINUSERINFO, SET_SESSIONKEY, SET_SORTCODE, SET_TOKEN, SET_USERINFO } from '@/constants/userInfo'
import type { DataParam, SortCodeParam, UserAdminParam, UserParam } from '@/reducers/userInfo'

export default () => {
  const userInfo = useSelector((state: DataParam) => state.userInfo) as DataParam
  const dispatch = useDispatch()

  const setToken = (token: string) => {
    dispatch({ type: SET_TOKEN, data: { token } })
  }

  const setSessionKey = (sessionkey: string) => {
    dispatch({ type: SET_SESSIONKEY, data: { session_key: sessionkey } })
  }

  const setUserInfo = (userInfo: UserParam) => {
    dispatch({ type: SET_USERINFO, data: { userInfo } })
  }

  const setAdminUserInfo = (adminUserInfo: UserAdminParam) => {
    dispatch({ type: SET_ADMINUSERINFO, data: { adminUserInfo } })
  }

  const setSortCode = (sortCode: SortCodeParam) => {
    dispatch({ type: SET_SORTCODE, data: { sort_code: sortCode } })
  }

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

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

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

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