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

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'HomeFilled' }
      },
      {
        path: 'school',
        name: 'School',
        component: () => import('@/views/school/index.vue'),
        meta: { title: '学校管理', icon: 'School' }
      },
      {
        path: 'member',
        name: 'Member',
        component: () => import('@/views/member/index.vue'),
        meta: { title: '会员管理', icon: 'User' }
      },
      {
        path: 'student',
        name: 'Student',
        component: () => import('@/views/student/index.vue'),
        meta: { title: '学生管理', icon: 'UserFilled' }
      },
      {
        path: 'application',
        name: 'Application',
        component: () => import('@/views/application/index.vue'),
        meta: { title: '应用管理', icon: 'Grid' }
      },
      {
        path: 'base/grade',
        name: 'Grade',
        component: () => import('@/views/base/grade/index.vue'),
        meta: { title: '年级管理', icon: 'Collection' }
      },
      {
        path: 'base/class',
        name: 'Class',
        component: () => import('@/views/base/class/index.vue'),
        meta: { title: '班级管理', icon: 'Files' }
      },
      {
        path: 'base/subject',
        name: 'Subject',
        component: () => import('@/views/base/subject/index.vue'),
        meta: { title: '学科管理', icon: 'Reading' }
      },
      {
        path: 'base/region',
        name: 'Region',
        component: () => import('@/views/base/region/index.vue'),
        meta: { title: '区域管理', icon: 'Location' }
      }
    ]
  }
]

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

// 路由守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title ? `${to.meta.title} - 盘古用户平台` : '盘古用户平台'
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
