import { type App } from 'vue'
import { createRouter, type RouteRecordRaw } from 'vue-router'
import { createRouterGuards } from './guards'
import baseRoutes from './modules/base'
import { getHistoryMode, menuFilterSort } from './utils'

/** 原始静态路由（未做任何处理） */
const routes: RouteRecordRaw[] = []

/* 自动导入全部静态路由，无需再手动引入! */
const modules: Record<string, any> = import.meta.glob(['./modules/**/*.ts', '!./modules/**/base.ts'], {
  eager: true,
})

;(function () {
  const routesDraft: RouteRecordRaw[] = []

  Object.keys(modules).forEach((key) => {
    routesDraft.push(modules[key].default)
  })

  routesDraft.forEach((routesItem) => {
    Array.isArray(routesItem) ? routes.push(...routesItem) : routes.push(routesItem)
  })
})()

/** 导出处理后的静态路由（三级及以上的路由全部拍成二级） */
// export const constantRoutes: RouteRecordRaw[] = formatTwoStageRoutes(
//   formatFlatteningRoutes(ascending(routes.flat(Infinity))),
// )

/** 用于渲染菜单，保持原始层级 */
// export const constantMenus: RouteRecordRaw[] = ascending(routes.flat(Infinity)).concat(...baseRoutes)

export const sidebarMenus: any[] = menuFilterSort([...routes])

export const router = createRouter({
  history: getHistoryMode(import.meta.env.VITE_ROUTER_MODE),
  routes: [...routes, ...baseRoutes],
  strict: true,
  scrollBehavior(_to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        return savedPosition
      } else {
        if (from.meta.saveScrollTop) {
          const top: number = document.documentElement.scrollTop || document.body.scrollTop
          resolve({ left: 0, top })
        }
      }
    })
  },
})

export async function setupRouter(app: App) {
  app.use(router)

  // 创建路由守卫
  createRouterGuards(router)

  await router.isReady()
}
