/*
 * @Author: xiejiang
 * @Date: 2024-11-05 10:14:56
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-03 16:59:32
 * @Description:
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
 */
import { defineStore } from 'pinia'
import { UserInfo, UserState } from '@/stores/interface'
import { getUserInfo } from '@/api/modules/login'
import { useAuthStore } from './auth'
import { localSet, localGet } from '@/utils'
// import menuTreeMoke from '@/utils/menuData'

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    token: localGet('token'),
    userInfo: null
  }),
  getters: {},
  actions: {
    // 设置token
    setToken(token: string) {
      this.token = token
      localSet('token', this.token)
    },
    async setAuthStore(userInfo: UserInfo) {
      // 设置可访问的菜单
      await useAuthStore().setAuthMenuList(userInfo.menuTree)
      // 自定义菜单
      // await useAuthStore().setAuthMenuList(menuTreeMoke)
      // 设置可访问的按钮
      await useAuthStore().setAuthButtonList(userInfo.menuButtonSigns)
      // 设置用户菜单权限的name集合
      useAuthStore().setRouteNameMap(useAuthStore().authMenuListGet)
    },
    // 设置userInfo
    async setUserInfo(userInfo?: UserInfo) {
      if (userInfo) {
        this.userInfo = userInfo
        await this.setAuthStore(userInfo)
      } else {
        // 获取用户信息
        try {
          const { data } = await getUserInfo()
          this.userInfo = data
          await this.setAuthStore(data)
        } catch {
          this.setToken('')
        }
      }
    }
  }
})
