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

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

router.beforeEach((to, from, next) => {
  if (to.path !== '/login' && to.meta.requiresAuth) {
    if (isLoggedIn()) {
      next();
    } else {
      next('/login');
    }
  } else {
    next();
  }
});

export default router