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: 'platform' }
      },
      {
        path: '/projectManage',
        name: 'projectManage',
        title: '项目管理',
        component: () => import('@/views/managePage/projectManage.vue'),
        meta: { menuName: '项目管理', icon: 'Management' }
      },
      {
        path: '/addProject',
        name: 'addProject',
        title: '新增项目',
        component: () => import('@/views/managePage/addProject.vue'),
        meta: {
          menuName: '新增项目',
          showInMenu: false // 不在菜单中显示
        }
      },
      {
        path: '/systemManage',
        name: '系统管理',
        title: 'systemManage',
        meta: { menuName: '系统管理', icon: 'tools' },
        children: [
          {
            path: '/systemManage/departManage',
            name: '部门管理',
            title: 'departManage',
            component: () => import('@/views/systemManage/departManage.vue'),
            meta: { menuName: '部门管理',}
          },
          {
            path: '/systemManage/userManage',
            name: '用户管理',
            title: 'userManage',
            component: () => import('@/views/systemManage/userManage.vue'),
            meta: { menuName: '用户管理',}
          },
          {
            path: '/systemManage/roleManage',
            name: '角色管理',
            title: 'roleManage',
            component: () => import('@/views/systemManage/roleManage.vue'),
            meta: { menuName: '角色管理',}
          },
          {
            path: '/systemManage/menuManage',
            name: '菜单管理',
            title: 'menuManage',
            component: () => import('@/views/systemManage/menuManage.vue'),
            meta: { menuName: '菜单管理',}
          }
        ]
      },
    ]
  }
]

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
