import { getStorage } from '@/utils/storage'
import router from '@/router'
const viewModules = import.meta.glob('@/views/**/index.vue')

export const handleRouter = (list: any[]):any[] => {
  let routerList:any[] = [];

  list.forEach(item => {
    if (item.son && item.son.length > 0) {
      routerList.push(...handleRouter(item.son))
    } else {
      const componentPath = `/src/views${item.path}/index.vue`
      routerList.push({
        path: item.path,
        name: item.name,
        component: viewModules[componentPath] || (() => import('@/views/404/index.vue')),
        meta: {
          title: item.name, // 左侧菜单显示的标题
          keepAlive: !!item.keepAlive,
        },
      })
    }
  });

  return routerList;
};

export const setRouter = () => {
  const menuList = (getStorage('menusInfo') as any[]) || []
  const token = getStorage('token')

  if (!token) return

  // 用 pathname 集合做幂等去重，避免 addRoute 重复添加同名路由导致匹配失败
  const existingPaths = new Set(router.getRoutes().map((r) => r.path))

  // 🌟 核心：无论什么角色，始终确保首页路由存在
  if (!existingPaths.has('/dashboard')) {
    router.addRoute('Layout', {
      path: '/dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index.vue'),
      meta: {
        title: '首页',
        keepAlive: false,
      },
    })
    existingPaths.add('/dashboard')
  }

  if (menuList.length > 0) {
    const routeList = handleRouter(menuList).filter(
      (item) => item.path && !existingPaths.has(item.path),
    )
    routeList.forEach((route) => {
      router.addRoute('Layout', route)
      existingPaths.add(route.path)
    })
  }
}
