import { createRouter, createWebHistory } from 'vue-router'

const Login = () => import('@/views/login/Login.vue');
const Home = () => import('@/components/Layout/Main.vue');
const Index = () => import('@/views/sys/index.vue'); 
const NotFound = () => import('@/views/sys/NotFound.vue');

// 1. 自动导入biz模块路由
const bizModules = import.meta.glob('../views/biz/**/*.vue')

// 2. 生成biz子路由（保留index后缀）
function buildBizRoutes() {
  return Object.entries(bizModules).map(([filePath, asyncComp]) => {
    let routePath = filePath
      .replace(/^..\/views/, '') // 保留biz及子目录
      .replace(/\.vue$/, ''); // 不移除index后缀
    
    // 处理路径开头的斜杠
    if (!routePath) routePath = '';
    else if (routePath.startsWith('/')) routePath = routePath.slice(1);

    const routeName = routePath
      .split('/')
      .filter(Boolean)
      .map(s => s.charAt(0).toUpperCase() + s.slice(1))
      .join('') || 'BizRoot'

    return {
      path: routePath,
      name: routeName,
      component: asyncComp,
      meta: { requiresAuth: true }
    }
  })
}

// 3. 路由配置（核心：将NotFound作为/index的子路由）
const routes = [
  { path: '/', redirect: '/login' },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/index', // 父路由
    name: 'Index',
    component: Index, // 包含内容区RouterView
    meta: { requiresAuth: true },
    children: [
      ...buildBizRoutes(), // 业务路由
      { path: 'console', component: Home, name: 'Console' },
      { path: '', redirect: 'console' },
      // 关键：NotFound作为子路由，匹配/index下的所有未定义路径
      { 
        path: ':pathMatch(.*)*', // 子路由通配符
        name: 'IndexNotFound', 
        component: NotFound 
      }
    ]
  },
  // 顶层通配符：将非/index的无效路径重定向到/index下的NotFound
  {
    path: '/:pathMatch(.*)*',
    redirect: to => {
      return `/index/${to.params.pathMatch.join('/')}`;
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

export default router
