import { LOGIN_URL } from '@/constants'
import router from '@/router'
import { useAuthStore, useUserStore } from '@/stores'
import type { RouteRecordRaw } from 'vue-router'

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

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

  try {
    if (authStore.isLoaded) return
    await authStore.setMenuList()
    await authStore.setLoaded()

    // 3.添加动态路由
    authStore.flatMenuListGet.forEach((item: Menu.MenuOptions) => {
      if (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) {
    userStore.setToken('')
    router.replace(LOGIN_URL)
    return Promise.reject(error)
  }
}
