import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import emailRegistration from '../views/emailRegistration.vue'
import ActivateEmail from '../views/ActivateEmail.vue'
import activationSuccessful from '../views/activationSuccessful.vue'
import forgetPassword from '../views/forgetPassword.vue'
import resetPassword from '../views/resetPassword.vue'
import { setStorage , getStorage } from '@/utils/storage.js';
const routes = [
  {
    path: '/',
    name: 'login',
    component: HomeView
  },
  {
    path: '/emailRegistration',
    name: 'emailRegistration',
    component: emailRegistration
  },
  {
    path: '/ActivateEmail',
    name: 'ActivateEmail',
    component: ActivateEmail
  },
  {
    path: '/activationSuccessful',
    name: 'activationSuccessful',
    component: activationSuccessful
  },
  {
    path: '/forgetPassword',
    name: 'forgetPassword',
    component: forgetPassword
  },
  {
    path: '/resetPassword',
    name: 'resetPassword',
    component: resetPassword
  },

  {
    path: '/nav',
    name: 'nav',
    redirect: '/nav/PK', // 默认跳转
    component: () => import('../views/nav.vue'),
    children: [
      {
        path: 'PK',
        name: 'pk',
        component: () => import('../views/hosts/pk.vue')
      },
      {
        path: 'Forum',
        name: 'Forum',
        component: () => import('../views/hosts/Forum.vue')
      },
      {
        path: 'Message',
        name: 'Message',
        component: () => import('../views/hosts/Message.vue')
      },
      {
        path: 'Mine',
        name: 'Mine',
        component: () => import('../views/hosts/Mine.vue')
      },
    ]
  }
]
const router = createRouter({
  history: createWebHistory(),
  routes
})

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

  // 定义需要登录才能访问的路由
  const requiresAuth = ['nav', 'pk', 'Forum', 'Message', 'Mine'];

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

export default router

