import { createRouter, createWebHashHistory } from 'vue-router'
import MainLayout from '@/layouts/MainLayout.vue'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: '首页',
    redirect: '/homePage',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '/homePage',
        name: '数据大屏',
        title: 'dataSummary',
        component: () => import('@/views/homePage/index.vue'),
        meta: { menuName: '数据大屏', icon: 'home' }
      },
      {
        path: '/projectManage',
        name: '项目管理',
        title: 'projectManage',
        component: () => import('@/views/managePage/projectManage.vue'),
        meta: { menuName: '项目管理', icon: 'Management' }
      },
      {
        path: '/addProject',
        name: '新增项目',
        title: 'addProject',
        component: () => import('@/views/managePage/addProject.vue'),
        meta: {
          menuName: '新增项目',
          showInMenu: false // 不在菜单中显示
        }
      }
    ]
  }
]

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

// 路由守卫 - 登录验证
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token') // 检查登录状态

  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router
