import { createRouter, createWebHistory } from "vue-router";
import { getIsLoggedIn } from "@/utils/auth";
const Home = () => import('@/views/home/index.vue')
const DataLibrary = () => import('@/views/dataLibrary/index.vue')

// 自动导入所有模块路由
const modules = import.meta.glob('./modules/*.js', { eager: true })

const fileRoutes = Object.keys(modules).reduce((acc, path) => {
  const module = modules[path].default
  acc.push(...module)
  return acc
}, [])

// 自动导入所有资源库模块路由
const datas = import.meta.glob('./dataLibrary/*.js', { eager: true })

const dataRoutes = Object.keys(datas).reduce((acc, path) => {
  const module = datas[path].default
  acc.push(...module)
  return acc
}, [])

const routes = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
    meta: {
      title: "登录"
    }
  },
  {
    path: "/",
    name: "Home",
    component: Home,
    children: [
      ...fileRoutes,
      {
        path: "/dataLibrary",
        name: "DataLibrary",
        redirect: "./dataLibrary/countryBill",
        component: DataLibrary,
        meta: {
          title: '数据资源库',
          isShowHeader: true
        },
        children: [
          ...dataRoutes
        ]
      },
    ]
  },

  // {
  //   path: "/dataLibrary",
  //   name: "DataLibrary",
  //   component: DataLibrary,
  //   meta: {
  //     title: '数据资源库'
  //   },
  //   children: [
  //     ...dataRoutes
  //   ]
  // },


];

console.log('路由', routes)
const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫 - 设置页面标题
router.beforeEach((to, from, next) => {
  // 登录态：同一次前端服务 BOOT_ID 内跨刷新/跨新标签有效；服务重启后自动失效
  const isAuthed = getIsLoggedIn();

  const isLoginRoute = to.name === "Login" || /^\/login\/?$/.test(String(to.path || ""));

  if (!isLoginRoute && !isAuthed) {
    next({
      path: "/login",
      query: { redirect: to.fullPath }
    });
    return;
  }

  if (to.meta.title) {
    if (to.meta.dynamicTitle) {
      console.log('to', to);
      const storageKey = to.meta.titleStorageKey || "curTabName";
      // 新开页签时 sessionStorage 不共享，优先用 query 带过来的 title/name
      const queryTitle = (to.query && (to.query.title || to.query.name)) ? String(to.query.title || to.query.name) : "";
      if (!to.path.startsWith('/decreeLayout/')) {
        document.title = queryTitle || window.sessionStorage.getItem(storageKey) || to.meta.title;
      }
    } else {
      document.title = to.meta.title

    }
  }
  next();
});


export default router;
