import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'login',
    component: HomeView
  },
  {
    path: '/nav',
    name: 'nav',
    redirect: '/nav/home', // 默认跳转
    component: () => import( '../views/nav.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        component: () => import( '../views/hosts/Home.vue'),
      },
      {
        path: 'scriptManagement',
        name: 'scriptManagement',
        component: () => import( '../views/hosts/ai/scriptManagement.vue'),
      },
      {
        path: 'LanguageManagement',
        name: 'LanguageManagement',
        component: () => import( '../views/hosts/ai/LanguageManagement.vue'),
      },
      {
        path: 'miniAM',
        name: 'miniAM',
        component: () => import( '../views/hosts/mini/miniAM.vue'),
      },
      {
        path: 'miniIntegral',
        name: 'miniIntegral',
        component: () => import( '../views/hosts/mini/miniIntegral.vue'),
      },
    ]
  }
]
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加导航守卫
router.beforeEach((to, from, next) => {
  // 假设你有一个方法来检查用户是否已登录
  const isAuthenticated = () => {
    return localStorage.getItem('token') == 1;
  };

  // 定义需要登录才能访问的路由
  const requiresAuth = ['nav','home', 'scriptManagement', 'LanguageManagement', 'miniAM', 'miniIntegral'];

  // 如果需要登录且用户未登录，则重定向到登录页面
  if (requiresAuth.includes(to.name) && !isAuthenticated()) {
    next({ name: 'login' });
  } else {
    next();
  }
});

export default router
