import { getAllBreadcrumbList, getFlatMenuList, getShowMenuList } from '@/utils/useAuth'
import { MenuOptions, UserState } from '@/stores/typings/userType'

const HOME_URL = import.meta.env.VITE_HOME_URL

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    superAdmin: false,
    userId: '',
    username: '',
    nickname: '',
    avatar: '',
    permissions: [],
    routers: [],
    routeName: ''
  }),
  getters: {
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    getShowMenus: (state) => getShowMenuList(state.routers),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    getFlatMenus: (state) => getFlatMenuList(state.routers),
    // 递归处理后的所有面包屑导航列表
    getBreadcrumbs: (state) => getAllBreadcrumbList(state.routers)
  },
  actions: {
    setSuperAdmin(superAdmin: boolean) {
      this.superAdmin = superAdmin
    },
    setUserId(suerId: string) {
      this.userId = suerId
    },
    setUsername(username: string) {
      this.username = username
    },
    setNickname(nickname: string) {
      this.nickname = nickname
    },
    setPermissions(permissions: string[]) {
      this.permissions = permissions
    },
    setRouters(authMenuList: MenuOptions[]) {
      this.routers = authMenuList
      this.routers.unshift({
        path: HOME_URL,
        name: 'home',
        component: HOME_URL,
        meta: {
          title: '首页',
          icon: 'dashboard',
          isAffix: true,
          isFull: false,
          isHide: false,
          isKeepAlive: true
        }
      })
    },
    setRouteName(name: string) {
      this.routeName = name
    }
  }
})
