import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { message } from 'ant-design-vue';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/LoginView.vue'),
    meta: { requiresAuth: false, title: '登录' },
  },
  {
    path: '/admin',
    component: () => import('@/views/admin/LayoutView.vue'),
    meta: { requiresAuth: true, role: 'admin', title: '超管端' },
    children: [
      {
        path: '',
        redirect: '/admin/dashboard',
      },
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('@/views/admin/DashboardView.vue'),
        meta: { title: '数据看板' },
      },
      {
        path: 'packages',
        name: 'AdminPackages',
        component: () => import('@/views/admin/courses/CourseListView.vue'),
        meta: { title: '课程包管理' },
      },
      {
        path: 'packages/review',
        name: 'AdminPackageReview',
        component: () => import('@/views/admin/courses/CourseReviewView.vue'),
        meta: { title: '审核管理' },
      },
      {
        path: 'packages/:id',
        name: 'AdminPackageDetail',
        component: () => import('@/views/admin/courses/CourseDetailView.vue'),
        meta: { title: '课程包详情' },
      },
      {
        path: 'packages/create',
        name: 'AdminPackageCreate',
        component: () => import('@/views/admin/courses/CourseEditView.vue'),
        meta: { title: '创建课程包' },
      },
      {
        path: 'packages/:id/edit',
        name: 'AdminPackageEdit',
        component: () => import('@/views/admin/courses/CourseEditView.vue'),
        meta: { title: '编辑课程包' },
      },
      {
        path: 'packages/:id/stats',
        name: 'AdminPackageStats',
        component: () => import('@/views/admin/courses/CourseStatsView.vue'),
        meta: { title: '课程数据统计' },
      },
      {
        path: 'tenants',
        name: 'AdminTenants',
        component: () => import('@/views/admin/tenants/TenantListView.vue'),
        meta: { title: '租户管理' },
      },
      {
        path: 'resources',
        name: 'AdminResources',
        component: () => import('@/views/admin/resources/ResourceListView.vue'),
        meta: { title: '资源库管理' },
      },
      // V2 新增路由
      {
        path: 'collections',
        name: 'AdminCollections',
        component: () => import('@/views/admin/collections/CollectionListView.vue'),
        meta: { title: '套餐管理' },
      },
      {
        path: 'collections/create',
        name: 'AdminCollectionCreate',
        component: () => import('@/views/admin/collections/CollectionEditView.vue'),
        meta: { title: '创建套餐' },
      },
      {
        path: 'collections/:id',
        name: 'AdminCollectionDetail',
        component: () => import('@/views/admin/collections/CollectionDetailView.vue'),
        meta: { title: '套餐详情' },
      },
      {
        path: 'collections/:id/edit',
        name: 'AdminCollectionEdit',
        component: () => import('@/views/admin/collections/CollectionEditView.vue'),
        meta: { title: '编辑套餐' },
      },
      {
        path: 'themes',
        name: 'AdminThemes',
        component: () => import('@/views/admin/themes/ThemeListView.vue'),
        meta: { title: '主题字典' },
      },
      {
        path: 'settings',
        name: 'AdminSettings',
        component: () => import('@/views/admin/SettingsView.vue'),
        meta: { title: '系统设置' },
      },
      {
        path: 'profile',
        name: 'AdminProfile',
        component: () => import('@/views/profile/ProfileView.vue'),
        meta: { title: '个人信息' },
      },
    ],
  },
  {
    path: '/school',
    component: () => import('@/views/school/LayoutView.vue'),
    meta: { requiresAuth: true, role: 'school', title: '学校端' },
    children: [
      {
        path: '',
        redirect: '/school/dashboard',
      },
      {
        path: 'dashboard',
        name: 'SchoolDashboard',
        component: () => import('@/views/school/DashboardView.vue'),
        meta: { title: '数据看板' },
      },
      {
        path: 'teachers',
        name: 'SchoolTeachers',
        component: () => import('@/views/school/teachers/TeacherListView.vue'),
        meta: { title: '教师管理' },
      },
      {
        path: 'students',
        name: 'SchoolStudents',
        component: () => import('@/views/school/students/StudentListView.vue'),
        meta: { title: '学生管理' },
      },
      {
        path: 'parents',
        name: 'SchoolParents',
        component: () => import('@/views/school/parents/ParentListView.vue'),
        meta: { title: '家长管理' },
      },
      {
        path: 'classes',
        name: 'SchoolClasses',
        component: () => import('@/views/school/classes/ClassListView.vue'),
        meta: { title: '班级管理' },
      },
      {
        path: 'courses',
        name: 'SchoolCourses',
        component: () => import('@/views/school/courses-new/CourseCenterView.vue'),
        meta: { title: '课程中心' },
      },
      {
        path: 'courses/:id',
        name: 'SchoolCourseDetail',
        component: () => import('@/views/school/courses/CourseDetailView.vue'),
        meta: { title: '课程详情' },
      },
      {
        path: 'package',
        name: 'SchoolPackage',
        component: () => import('@/views/school/PackageView.vue'),
        meta: { title: '套餐管理' },
      },
      // V2 新增：校本课程包
      {
        path: 'school-courses',
        name: 'SchoolSchoolCourses',
        component: () => import('@/views/school/school-courses/SchoolCourseListView.vue'),
        meta: { title: '校本课程包' },
      },
      {
        path: 'school-courses/create',
        name: 'SchoolSchoolCourseCreate',
        component: () => import('@/views/school/school-courses/SchoolCourseEditView.vue'),
        meta: { title: '创建校本课程包' },
      },
      {
        path: 'school-courses/:id',
        name: 'SchoolSchoolCourseDetail',
        component: () => import('@/views/school/school-courses/SchoolCourseDetailView.vue'),
        meta: { title: '校本课程包详情' },
      },
      {
        path: 'school-courses/:id/edit',
        name: 'SchoolSchoolCourseEdit',
        component: () => import('@/views/school/school-courses/SchoolCourseEditView.vue'),
        meta: { title: '编辑校本课程包' },
      },
      {
        path: 'reports',
        name: 'SchoolReports',
        component: () => import('@/views/school/ReportView.vue'),
        meta: { title: '数据报表' },
      },
      {
        path: 'growth',
        name: 'SchoolGrowth',
        component: () => import('@/views/school/growth/GrowthRecordView.vue'),
        meta: { title: '成长档案' },
      },
      {
        path: 'tasks',
        name: 'SchoolTasks',
        component: () => import('@/views/school/tasks/TaskListView.vue'),
        meta: { title: '阅读任务' },
      },
      {
        path: 'task-templates',
        name: 'SchoolTaskTemplates',
        component: () => import('@/views/school/tasks/TaskTemplateView.vue'),
        meta: { title: '任务模板' },
      },
      {
        path: 'feedback',
        name: 'SchoolFeedback',
        component: () => import('@/views/school/feedback/FeedbackView.vue'),
        meta: { title: '课程反馈' },
      },
      {
        path: 'schedule',
        name: 'SchoolSchedule',
        component: () => import('@/views/school/schedule/index.vue'),
        meta: { title: '课程排期' },
      },
      {
        path: 'operation-logs',
        name: 'SchoolOperationLogs',
        component: () => import('@/views/school/settings/OperationLogView.vue'),
        meta: { title: '操作日志' },
      },
      {
        path: 'settings',
        name: 'SchoolSettings',
        component: () => import('@/views/school/settings/SettingsView.vue'),
        meta: { title: '系统设置' },
      },
      {
        path: 'profile',
        name: 'SchoolProfile',
        component: () => import('@/views/profile/ProfileView.vue'),
        meta: { title: '个人信息' },
      },
    ],
  },
  {
    path: '/teacher',
    component: () => import('@/views/teacher/LayoutView.vue'),
    meta: { requiresAuth: true, role: 'teacher', title: '教师端' },
    children: [
      {
        path: '',
        redirect: '/teacher/dashboard',
      },
      {
        path: 'dashboard',
        name: 'TeacherDashboard',
        component: () => import('@/views/teacher/DashboardView.vue'),
        meta: { title: '首页' },
      },
      {
        path: 'courses',
        name: 'TeacherCourses',
        component: () => import('@/views/teacher/courses-new/CourseCenterView.vue'),
        meta: { title: '课程中心' },
      },
      {
        path: 'courses/:id',
        name: 'TeacherCourseDetail',
        component: () => import('@/views/teacher/courses/CourseDetailView.vue'),
        meta: { title: '课程详情' },
      },
      {
        path: 'courses/:id/prepare',
        name: 'TeacherCoursePrepare',
        component: () => import('@/views/teacher/courses/PrepareModeView.vue'),
        meta: { title: '备课模式' },
      },
      {
        path: 'lessons',
        name: 'TeacherLessons',
        component: () => import('@/views/teacher/lessons/LessonListView.vue'),
        meta: { title: '上课记录' },
      },
      {
        path: 'lessons/:id',
        name: 'TeacherLesson',
        component: () => import('@/views/teacher/lessons/LessonView.vue'),
        meta: { title: '上课模式' },
      },
      {
        path: 'lessons/:id/records',
        name: 'TeacherLessonRecords',
        component: () => import('@/views/teacher/lessons/LessonRecordsView.vue'),
        meta: { title: '课后记录' },
      },
      {
        path: 'broadcast/thanks',
        name: 'TeacherBroadcastThanks',
        component: () => import('@/views/teacher/lessons/BroadcastThanksView.vue'),
        meta: { title: '谢谢观看' },
      },
      {
        path: 'broadcast/:id',
        name: 'TeacherBroadcast',
        component: () => import('@/views/teacher/lessons/BroadcastView.vue'),
        meta: { title: '展播模式' },
      },
      {
        path: 'classes',
        name: 'TeacherClasses',
        component: () => import('@/views/teacher/classes/ClassListView.vue'),
        meta: { title: '我的班级' },
      },
      {
        path: 'classes/:id/students',
        name: 'TeacherClassStudents',
        component: () => import('@/views/teacher/classes/ClassStudentsView.vue'),
        meta: { title: '班级学生' },
      },
      // V2 新增：校本课程包
      {
        path: 'school-courses',
        name: 'TeacherSchoolCourses',
        component: () => import('@/views/teacher/school-courses/SchoolCourseListView.vue'),
        meta: { title: '校本课程包' },
      },
      {
        path: 'school-courses/create',
        name: 'TeacherSchoolCourseCreate',
        component: () => import('@/views/teacher/school-courses/SchoolCourseEditView.vue'),
        meta: { title: '创建校本课程包' },
      },
      {
        path: 'school-courses/:id',
        name: 'TeacherSchoolCourseDetail',
        component: () => import('@/views/teacher/school-courses/SchoolCourseDetailView.vue'),
        meta: { title: '校本课程包详情' },
      },
      {
        path: 'school-courses/:id/edit',
        name: 'TeacherSchoolCourseEdit',
        component: () => import('@/views/teacher/school-courses/SchoolCourseEditView.vue'),
        meta: { title: '编辑校本课程包' },
      },
      {
        path: 'tasks',
        name: 'TeacherTasks',
        component: () => import('@/views/teacher/tasks/TaskListView.vue'),
        meta: { title: '阅读任务' },
      },
      {
        path: 'feedback',
        name: 'TeacherFeedback',
        component: () => import('@/views/teacher/feedback/FeedbackView.vue'),
        meta: { title: '课程反馈' },
      },
      {
        path: 'schedule',
        name: 'TeacherSchedule',
        component: () => import('@/views/teacher/schedule/ScheduleView.vue'),
        meta: { title: '我的课表' },
      },
      {
        path: 'growth',
        name: 'TeacherGrowth',
        component: () => import('@/views/teacher/growth/GrowthRecordView.vue'),
        meta: { title: '成长档案' },
      },
      {
        path: 'profile',
        name: 'TeacherProfile',
        component: () => import('@/views/profile/ProfileView.vue'),
        meta: { title: '个人信息' },
      },
    ],
  },
  {
    path: '/parent',
    component: () => import('@/views/parent/LayoutView.vue'),
    meta: { requiresAuth: true, role: 'parent', title: '家长端' },
    children: [
      {
        path: '',
        redirect: '/parent/dashboard',
      },
      {
        path: 'dashboard',
        name: 'ParentDashboard',
        component: () => import('@/views/parent/DashboardView.vue'),
        meta: { title: '首页' },
      },
      {
        path: 'children',
        name: 'ParentChildren',
        component: () => import('@/views/parent/children/ChildrenView.vue'),
        meta: { title: '我的孩子' },
      },
      {
        path: 'children/:id',
        name: 'ParentChildDetail',
        component: () => import('@/views/parent/children/ChildProfileView.vue'),
        meta: { title: '孩子详情' },
      },
      {
        path: 'lessons',
        name: 'ParentLessons',
        component: () => import('@/views/parent/lessons/LessonHistoryView.vue'),
        meta: { title: '阅读记录' },
      },
      {
        path: 'tasks',
        name: 'ParentTasks',
        component: () => import('@/views/parent/tasks/TaskListView.vue'),
        meta: { title: '阅读任务' },
      },
      {
        path: 'growth',
        name: 'ParentGrowth',
        component: () => import('@/views/parent/growth/GrowthRecordView.vue'),
        meta: { title: '成长档案' },
      },
      {
        path: 'profile',
        name: 'ParentProfile',
        component: () => import('@/views/profile/ProfileView.vue'),
        meta: { title: '个人信息' },
      },
    ],
  },
  {
    path: '/office/WebOffice',
    name: 'WebOffice',
    component: () => import('@/views/office/WebOffice.vue'),
    meta: { requiresAuth: true, title: '在线预览' },
  },
  {
    path: '/weboffice',
    redirect: '/office/WebOffice',
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/NotFoundView.vue'),
    meta: { title: '页面不存在' },
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const userRoleRaw = localStorage.getItem('role');
  // role 转为小写以匹配路由
  const userRole = userRoleRaw ? userRoleRaw.toLowerCase() : null;

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 少儿智慧阅读`;
  }

  // 需要认证但未登录
  if (to.meta.requiresAuth && !token) {
    message.warning('请先登录');
    next('/login');
    return;
  }

  // 已登录用户访问登录页，跳转到对应首页
  if (to.path === '/login' && token) {
    const defaultRoute = userRole ? `/${userRole}/dashboard` : '/admin/dashboard';
    next(defaultRoute);
    return;
  }

  // 角色权限检查
  if (to.meta.role && userRole !== to.meta.role) {
    message.error('没有权限访问该页面');
    next(`/${userRole}/dashboard`);
    return;
  }

  next();
});

export { router };
export default router;
