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: '数据资源库'
        },
        children: [
          ...dataRoutes
        ]
      },
    ]
  },

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


];


const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫 - 设置页面标题
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    if (to.meta.dynamicTitle) {
      console.log('to', to);
      document.title = window.sessionStorage.getItem("curTabName") || to.meta.title;
    } else {
      document.title = to.meta.title

    }
  }
  next();
});


export default router;
