import router from '@/router/index'
import { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import { removeToken } from '@/utils'
import { StrAnyObj } from '@/typings'

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob('@/views/**/*.vue')

const LOGIN_URL = import.meta.env.VITE_LOGIN_URL

/**
 * @description 初始化动态路由
 */
export const initDynamicRouter = async (data: StrAnyObj) => {
  const userStore = useUserStore()

  try {
    await userStore.setSuperAdmin(data.superAdmin)
    await userStore.setUserId(data.userId)
    await userStore.setUsername(data.username)
    await userStore.setNickname(data.nickname)
    await userStore.setRouters(data.routers)
    await userStore.setPermissions(data.permissions)

    // 添加动态路由
    userStore.getFlatMenus.forEach((item) => {
      item.children && delete item.children
      if (item.component && typeof item.component == 'string') {
        item.component = modules['/src/views' + item.component + '.vue']
      }
      if (item.meta.isFull) {
        router.addRoute(item as unknown as RouteRecordRaw)
      } else {
        router.addRoute('layout', item as unknown as RouteRecordRaw)
      }
    })
  } catch (error) {
    // 当按钮 || 菜单请求出错时，重定向到登陆页
    removeToken()
    await router.replace(LOGIN_URL)
    return Promise.reject(error)
  }
}
