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')
  const token = getStorage('token')
  if (token && menuList.length > 0) {
    const routeList = handleRouter(menuList).filter(
      (item) => item.path && item.path !== '/dashboard',
    )
    routeList.forEach((route) => router.addRoute('Layout', route))
  }

  router.getRoutes().forEach((route) => {
    console.log(`路径: ${route.path}, 名称: ${route.name || '无'}`)
  })
}
