import { createRouter, createWebHistory } from "vue-router";
import guard from "./guard";

// 导入views文件夹下的所有组件
const modules = import.meta.glob("../views/**/index.vue");
// 匹配到的文件名数组
let aotuRoutes: any[] = [];
//根据名字查找路由项目
const aotuRoutesFind = (name: String) => {
  let list: any = [];
  //递归查询所有路由,子路由;添加至list
  const recursionPush = (routes: any) => {
    routes.forEach((item: any) => {
      list.push(item);
      recursionPush(item.children);
    });
  };
  recursionPush(aotuRoutes);
  //返回查找到的路由
  return list.find((route: any) => route.name == name);
};
for (const path in modules) {
  //提取路由信息
  let nameArr = path.split("/");
  //子路由循环时有作用
  let aotuRoutesItem = aotuRoutes;
  //子路由层次标识
  let index = 0;
  //判断是否是子路由
  for (let i = 0; i < nameArr.length - 4; i = i + 2) {
    aotuRoutesItem = aotuRoutesItem.find(
      (route: any) => route.name == nameArr[i + 2]
    ).children;
    index++;
  }
  //路径生成
  let routePath = "";
  for (let i = 0; i <= index; i++) {
    routePath += "/" + nameArr[i * 2 + 2];
  }
  //设置文件夹名带有-default的子路由为默认路由
  if (nameArr[index * 2 + 2].includes("-default")) {
    aotuRoutesFind(nameArr[index * 2]).redirect = routePath;
  }
  //添加路由信息
  aotuRoutesItem.push({
    name: nameArr[index * 2 + 2],
    path: routePath,
    component: modules[path],
    children: [],
  });
}

// 创建路由实例并传递 `routes` 配置
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      redirect: "/home/test",
    },
    ...aotuRoutes,
  ],
});

//注入路由守卫
guard(router);

export default router;
