import { createRouter, createWebHistory } from "vue-router";
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: "/",
    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) => {
  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;
