import { App } from 'vue';
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import { RedirectRoute } from '@/router/base';
import { PageEnum } from '@/enums/pageEnum';
import { createRouterGuards } from './router-guards';
import { disasterPreventionRoute, HOME_PAGE, RootRoute } from './full-routes';
import { asyncImportRoute, routerGenerator } from './generator-routers';

const modules: any = import.meta.glob('./modules/**/*.ts', { eager: true });

const routeModuleList: RouteRecordRaw[] = [];

Object.keys(modules).forEach((key) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

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

routeModuleList.sort(sortRoute);

const { children, ...disasterPreventionTopRoute } = disasterPreventionRoute;
const navRoutes = [RootRoute, HOME_PAGE, disasterPreventionTopRoute, RedirectRoute];

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

const routeList = routerGenerator(navRoutes);
asyncImportRoute(routeList);

//普通路由 无需验证权限
export const constantRouter: any[] = routeList;

export const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRouter,
  strict: true,
  scrollBehavior(to) {
    if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth',
      };
    }
  },
});

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

export default router;
