import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

// 假设你有一个方法来检查用户是否已登录
import { isLoggedIn } from '@/utils/auth'

// 登录页面组件
const Login = () => import('@/views/LoginView.vue')

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/index',
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('@/views/index/user.vue'),
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    children: [
      {
        path: '/index',
        name: 'index',
        component: () => import('@/views/index/index.vue'),
        // 添加一个meta字段，表示此页面需要登录
        meta: { requiresAuth: true },
      },
    ],
  },
]

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

router.beforeEach((to, from, next) => {
  // 检查目标页面是否需要登录
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录
    if (isLoggedIn()) {
      // 用户已登录，允许访问
      next()
    } else {
      // 用户未登录，重定向到登录页面
      next({ path: '/login' })
    }
  } else {
    // 不需要登录，直接访问
    next()
  }
})

export default router