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

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/system/Login.vue')
  },
  {
    path: '/',
    component: () => import('@/layouts/DefaultLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/system/Dashboard.vue')
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/system/UserManagement.vue')
      },
      {
        path: 'roles',
        name: 'RoleManagement',
        component: () => import('@/views/system/RoleManagement.vue')
      },
      {
        path: 'menus',
        name: 'MenuManagement',
        component: () => import('@/views/system/MenuManagement.vue')
      },
      {
        path: 'sys/config',
        name: 'ConfigManagement',
        component: () => import('@/views/config/ConfigManagement.vue')
      },
      {
        path: 'dict',
        name: 'DictManagement',
        component: () => import('@/views/config/DictManagement.vue')
      },
      {
        path: 'files',
        name: 'FileManagement',
        component: () => import('@/views/file/FileManagement.vue')
      },
      {
        path: 'notice',
        name: 'NoticeManagement',
        component: () => import('@/views/notify/NoticeManagement.vue')
      },
      {
        path: 'loginlog',
        name: 'LoginLog',
        component: () => import('@/views/audit/LoginLog.vue')
      },
      {
        path: 'oplog',
        name: 'OperationLog',
        component: () => import('@/views/audit/OperationLog.vue')
      },
      {
        path: 'exceptionlog',
        name: 'ExceptionLog',
        component: () => import('@/views/audit/ExceptionLog.vue')
      }
    ]
  }
]

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

router.beforeEach((to, from, next) => {
  try {
    const token = localStorage.getItem('token')
    
    if (to.path === '/login') {
      if (token) {
        next('/')
      } else {
        next()
      }
    } else {
      if (token) {
        next()
      } else {
        next('/login')
      }
    }
  } catch (error) {
    console.error('路由守卫错误:', error)
    next('/login')
  }
})

export default router
