import { store } from '../index'
import { defineStore } from 'pinia'
import { getAccessToken, removeToken } from '@/utils/auth'
import { CACHE_KEY } from '@/hooks/web/useCache'
import { getInfo, loginOut } from '@/api/login'

import cache from '@/plugins/cache'

interface UserVO {
  id: number
  avatar: string
  nickname: string
}
interface UserInfoVO {
  permissions: string[]
  roles: string[]
  isSetUser: boolean
  user: UserVO
}

export const useUserStore = defineStore('admin-user', {
  state: (): UserInfoVO => ({
    permissions: [],
    roles: [],
    isSetUser: false,
    user: {
      id: 0,
      avatar: '',
      nickname: ''
    }
  }),
  getters: {
    getPermissions(): string[] {
      return this.permissions
    },
    getRoles(): string[] {
      return this.roles
    },
    getIsSetUser(): boolean {
      return this.isSetUser
    },
    getUser(): UserVO {
      return this.user
    }
  },
  actions: {
    async setUserInfoAction() {
      if (!getAccessToken()) {
        this.resetState()
        return null
      }
      let userInfo = cache.local.get(CACHE_KEY.USER)
      if (!userInfo || !userInfo?.menus || userInfo.menus.length == 0) {
        userInfo = await getInfo({})
      }
      this.permissions = userInfo.permissions
      this.roles = userInfo.roles
      this.user = userInfo.user
      this.isSetUser = true
      cache.local.set(CACHE_KEY.USER, userInfo)
      cache.local.set(CACHE_KEY.ROLE_ROUTERS, userInfo.menus)
    },
    async loginOut() {
      await loginOut()
      removeToken()
      // cache.local.clear()
      this.resetState()
    },
    resetState() {
      this.permissions = []
      this.roles = []
      this.isSetUser = false
      this.user = {
        id: 0,
        avatar: '',
        nickname: ''
      }
      cache.local.delete(CACHE_KEY.USER)
    },
    refresh() {
      cache.local.delete(CACHE_KEY.USER)
      this.resetState()
      window.location.href = ''
    }
  }
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
