import { defineStore } from 'pinia'
import {
  PERMISSIONS_KEY,
  ROUTER_KEY,
  TOKEN_KEY,
  USER_INFO_KEY
} from '@/enums/cacheEnum'
import { getAuthCache, setAuthCache, clearAuthCache } from '@/utils/auth'
import { removeTabChangeListener } from '@/logics/mitt/routeChange'
import type { RouteLocationNormalized } from 'vue-router'

import { UserState, UserInfo } from './types'
// import useAppStore from '../app'

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    // 用户名
    userInfo: null,
    token: undefined,
    permissionsList: undefined, // 用户职务接口权限列表
    router: undefined
  }),

  getters: {
    // Get user's information
    getUserInfo(): UserInfo {
      return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {}
    },
    getToken(): string {
      return this.token || getAuthCache<string>(TOKEN_KEY)
    },
    getRouter(): RouteLocationNormalized {
      return this.router || getAuthCache<RouteLocationNormalized>(ROUTER_KEY)
    }
  },

  actions: {
    setRouter(r: RouteLocationNormalized) {
      this.router = r
      setAuthCache(ROUTER_KEY, r)
    },
    setToken(token: string | undefined) {
      this.token = token || '' // for null or undefined value
      setAuthCache(TOKEN_KEY, token)
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info
      setAuthCache(USER_INFO_KEY, info)
    },
    // Set permissions list
    setPermissionsList(list: Array<string> | []) {
      this.permissionsList = list
      setAuthCache(PERMISSIONS_KEY, list)
    },
    // Reset user's information
    resetInfo() {
      this.$reset()
    },

    logoutCallBack() {
      // const appStore = useAppStore()
      this.resetInfo()
      clearAuthCache()
      removeTabChangeListener()
    },
    // Logout
    async logout() {
      this.logoutCallBack()
    }
  }
})

export default useUserStore
