import type { App } from "vue";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

import { createRouterGuards } from "./router-guards";
import { HttpErrorPage, LoginRoute, ErrorPageRoute } from "@/router/base";

// import modules from "@/router/modules";
import type { IModuleType } from "./types";

const modules = import.meta.glob<IModuleType>("./modules/**/*router.ts", {
  eager: true,
});

const routeModuleList: RouteRecordRaw[] = Object.keys(modules).reduce<
  RouteRecordRaw[]
>((list, key) => {
  const mod = modules[key].default ?? {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  return [...list, ...modList];
}, []);

function sortRoute(a, b) {
  return (a.meta?.sort ?? 0) - (b.meta?.sort ?? 0);
}

routeModuleList.sort(sortRoute);

export const RootRoute: RouteRecordRaw = {
  path: "/",
  name: "Root",
  redirect: "/system",
  meta: {
    title: "Root",
  },
};

//需要验证权限
export const asyncRoutes = [...routeModuleList];

const constantRouter: any[] = [
  LoginRoute,
  RootRoute,
  ...asyncRoutes,
  ErrorPageRoute,
  ...HttpErrorPage,
];

/**
 * 创建路由
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRouter,
  strict: true,
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

export function setupRouter(app: App) {
  app.use(router);
  // 创建路由守卫
  createRouterGuards(router);
}

export default router;
