import authApis  from '@/apis/auth';
import { createRouter, createWebHistory } from 'vue-router'
import {useStore} from "@/store";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 定义公共页面
    {
      path: "/404",
      component: () => import("@/views/404.vue")
    },
    {
      path: "/:catchAll(.*)",
      redirect: "/404"
    },

    // 登录与注册
    // {
    //   path: "/",
    //   redirect: () => {
    //     window.location.href = "https://p-nju.seec.seecoder.cn/login?from=https://air-nju.seec.seecoder.cn";
    //     // window.location.href = "http://localhost:8000/login?from=http://localhost:4000";
    //     // {本地门户首页地址}?from={本地eai首页地址}
    //     return "/"; // 占位返回值，实际不会执行
    // },
    // },
    {
      path: "/",
      redirect: "/login"
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginPage/LoginPage.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/LoginPage/RegisterPage.vue')
    },
    {
      path: '/passwordChange',
      name: 'passwordChange',
      component: () => import('../views/LoginPage/PasswordChangePage.vue')
    },
    // 用户相关界面
    {
      path: '/home',
      name: 'home',
      redirect: '/home/courseSquare',
      component: () => import('../layout/Layout/Layout.vue'),
      children: [
        {
          path: "/profile",
          name: "profile",
          component: () => import('@/views/Profile.vue')
        },
        {
          path: 'courseSquare',
          name: 'courseSquare',
          component: () => import("../views/CourseSquare/index.vue")
        },
        {
          path: 'courseDetail/:courseId',
          name: 'courseDetail',
          component: () => import("../views/CourseSquare/component/CourseDetails/index.vue")
        },
        {
          path: 'moreCourse',
          name: 'moreCourse',
          component: () => import("../views/CourseSquare/component/AllCourse/MoreCourse.vue"),
          props(route) {
            return route.query
          },
        },
        {
          path: 'myCourse',
          name: 'myCourse',
          component: () => import("../views/CoursePage/CoursePage.vue")
        },
        {
          path: 'myHomework',
          name: 'myHomework',
          component: () => import("@/views/HomeworkPage/index.vue")
        },
        {
          path: 'homeworkDetail/:assignmentId',
          name: 'homeworkDetail',
          component: () => import("@/views/HomeworkPage/component/HomeworkDetail.vue")
        },
        {
          path: 'assignment/:assignmentId/aispeaking',
          name: 'aispeaking',
          component: () => import('../views/AiSpeakingPage/SpeakingPage.vue'),
          props: (route) => ({
            assignmentId: Number(route.query.assignmentId)
          })
        },
        {
          path: 'assignment/:assignmentId/airecord',
          name: 'airecord',
          component: () => import('../views/AiSpeakingPage/SpeakingRecord.vue'),
          props: (route) => ({
            userId: Number(route.query.userId),
            assignmentId: Number(route.query.assignmentId),
            assignmentName: route.query.assignmentName || ''
          })
        },
        {
          path: 'assignment/:assignmentId/edit',
          name: 'edit',
          component: () => import('../views/EditPage/EditPage.vue')
        },
        {
          path: 'assignment/:assignmentId/AIEvaluation',
          name: 'AIEvaluation',
          component: () => import('../views/AIEvaluationPage/AIEvaluationPage.vue')
        },
        {
          path: 'assignment/:assignmentId/correct',
          name: 'correct',
          component: () => import('../views/CorrectPage/CorrectPage.vue')
        },
        {
          path: 'myCorrect/course',
          name: 'myCorrectWithCourse',
          component: () => import("@/views/CorrectPage/CoursePage.vue")
        },
        {
          path: 'myCorrect/assignment',
          name: 'myCorrectWithAssignment',
          component: () => import("@/views/CorrectPage/AssignmentPage.vue")
        },
        {
          path: 'myCorrect/assignment/:assignmentId',
          name: 'myCorrectWithAssignmentId',
          component: () => import("@/views/CorrectPage/CorrectAssignmentPage.vue")
        },
        {
          path: 'studentDetail',
          name: 'studentDetail',
          component: () => import("@/views/ClassPage/StudentDetail.vue")
        },
        {
          path: 'courseClass/:courseId',
          name: 'courseClass',
          component: () => import("@/views/ClassPage/CourseClass.vue")
        },
        {
          path: 'classDetail',
          name: 'classDetail',
          component: () => import("@/views/ClassPage/ClassDetail.vue"),
          children:[
            {
              path: "",
              name:"classDetail",
              redirect: "/home/classDetail/student"
            },
            {
              path: 'student',
              name: 'classStudent',
              component: () => import("@/views/ClassPage/ClassStudent.vue")
            },
            {
              path: 'homework',
              name: 'classHomework',
              component: () => import("@/views/ClassPage/ClassHomework.vue")
            },
          ]
        },
        {
          path:"behavior",
          name: "behavior",
          redirect: 'home/behavior/main',
          component: () => import("../views/BehaviorPage/BehaviorBoard.vue"),
          children:[
              {
                path: 'main',
                name: 'behaviorHome',
                component: () => import("../views/BehaviorPage/subPage/BehaviorHome.vue")
              },
            {
              path: 'total',
              name: 'total',
              component: () => import("../views/BehaviorPage/subPage/TotalAnalysis.vue")
            },
            {
              path: 'edit',
              name: 'editData',
              component: () => import("../views/BehaviorPage/subPage/EditAnalysis.vue")
            },
            {
              path: 'pause',
              name: 'pause',
              component: () => import("../views/BehaviorPage/subPage/PauseAnalysis.vue")
            },
            {
              path: 'process',
              name: 'process',
              component: () => import("../views/BehaviorPage/subPage/ProcessAnalysis.vue")
            },
          ]
        },
      ]
    },

    // 管理员相关界面
    {
      path: "/admin",
      redirect: '/admin/login',
    },
    {
      path: "/admin/login",
      name: 'adminLogin',
      component: () => import("../views/AdminPage/LoginPage/AdminLoginPage.vue"),
    },
    // {
    //   path: "/admin/login",
    //   name: 'adminLogin',
    //   component: () => import("../views/LoginPage/LoginPage.vue"),
    // },
    {
      path: "/manager",
      name: "manager",
      // redirect: '/manager/course',
      component: () => import("../layout/AdminLayout/AdminLayout.vue"),
      children: [
        {
          path: "course",
          name: "courseManage",
          component: () => import("../views/AdminPage/CourseManage/CourseManage.vue"),
          meta: {
            roles: ['ADMIN']
          }
        },
        {
          path: "user",
          name: "userManage",
          component: () => import("../views/AdminPage/UserManage/UserManage.vue"),
          meta: {
            roles: ['ADMIN']
          }
        },
        {
          path: "file",
          name: "fileManage",
          component: () => import("../views/AdminPage/FileManage/FileManage.vue"),
          meta: {
            roles: ['ADMIN']
          }
        },
      ]
    },
  ]
})

/*
  路由守卫
 */
  router.beforeEach(async (to) => {
    const store = useStore();
    const publicPaths = [ '/register', '/passwordChange', '/admin/login','/login' ];
    // 1. 检查URL中的token
    const urlToken = new URLSearchParams(window.location.search).get('token');
    if (urlToken) {
      try {
        // 等待 token 验证完成
        const res = await authApis.authToken(urlToken || store.token);
        const data = res.data.data;
        // 存储用户状态
        store.setUser(data);
        store.setToken(data?.token);
        localStorage.setItem('Authorization', data?.token);
        localStorage.setItem('User', JSON.stringify(data));
        // 清除 URL 中的 token
        if (urlToken) {
            window.history.replaceState({}, '', to.path);
        }

        // 如果当前路径是公开路径，允许继续；否则跳转到首页
        // if (!publicPaths.includes(to.path)) {
        //     return '/home';
        // }
    } catch (error) {
        console.error('Token验证失败:', error);
        // 验证失败，清除无效的 token
        store.setUser(null);
        store.setToken(null);
        localStorage.removeItem('Authorization');
        localStorage.removeItem('User');
    }
    }

    if (publicPaths.includes(to.path)) return true;

    if (!store.user?.role) {
      return '/';
    }

    if (to.meta?.roles && !(to.meta.roles as any[]).includes(store.user.role)) {
      return '/home';
    }

    return true;
  });

export default router