import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
import TokenService from '@/utils/token'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/home/index.vue')
    },
    {
      path: '/login',
      name: 'LOGIN',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/user',
      name: 'USER',
      component: () => import('@/views/user/index.vue')
    },
    {
      path:"/search",
      component:()=>import('@/views/search/index.vue')
    }
  ]
})
// 定义全局前置守卫
router.beforeEach((to, from, next) => {
  // 假设 token 存储在 store 中
  const hasToken =TokenService.hasToken();

  if (to.path === '/login') {
    // 如果目标是登录页面，则允许访问
    next()
  } else if (hasToken) {
    // 如果用户有 token，则允许访问其他页面
    next()
  } else {
    // 如果用户没有 token，则重定向到登录页面
    next('/login')
  }
})
export default router
