import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import { RouteRecordDetailRaw } from './routes.d';
import { app_ready, app_routes } from '~/store/app';

// import localRoutes from './routes/xdjx';
// import localRoutes from './routes/xdjy';
// import localRoutes from './routes/xdhq';

// !auto switch routes way 1:
// !build error
// const localRoutes = (await import(`./routes/${import.meta.env.MODE}.ts`))['default'] as RouteRecordDetailRaw[]

const currentRouteModule = import.meta.glob(`./routes/*.ts`, { eager: true })[`./routes/${import.meta.env.MODE}.ts`] as { title: string, default: RouteRecordDetailRaw[] }
document.title = currentRouteModule['title']
const localRoutes = currentRouteModule['default']

console.log('localRoutes :>> ', localRoutes);

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: () => import("~/layout/loading/index.vue")
    },
    {
      path: '/routes',
      name: '-ROUTES',
      props: true,
      meta: {
        hidden: false,
        sort: -1,
        title: "组织机构与权限"
      },
      component: () => import("~/router/routes.vue")
    }
  ]
})
export default router

async function handleFilterRoutes<R extends RouteRecordDetailRaw[]>(routes: R): Promise<Partial<R>> {
  console.log(' handleFilterRoutes ');
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(routes)
    }, 0);
  })
  return [...routes] as Partial<R>
}

const routes = await handleFilterRoutes(localRoutes)
sessionStorage.setItem('routes', JSON.stringify(routes.concat([{
  path: '/routes',
  name: '-ROUTES',
  meta: {
    hidden: false,
    sort: -1,
    title: "组织机构与权限"
  },
  component: () => import("~/router/routes.vue")
}])))
routes.forEach(filteredRoute => router.addRoute(filteredRoute as RouteRecordRaw))
app_ready.value = true
app_routes.value = (routes as RouteRecordDetailRaw[])

router.beforeEach((to, from) => {
  console.groupCollapsed(`%c${from.name?.toString()} => ${to.name?.toString()}`, 'color:#0ff');
  console.log(`%c${from.meta.title} => ${to.meta.title}`, 'color:#0cc');
  console.groupEnd();
})
