import { createRouter, createWebHistory, createWebHashHistory  } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'

import {getUserInfo} from '@/api/login.ts'

// 示例路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: '',
    component: () => import('../views/login/login.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: Layout,
    children: [
      {
        path: '',
        name: 'surveyManagement',  //问卷管理
        component: () => import('@/views/surveyManagement/SurveyManagement.vue')
      },
      {
        path: 'createQuestionnaire',
        name: 'createQuestionnaire',    //创建问卷
        component: () => import('@/views/surveyManagement/CreateQuestionnaire.vue')
      },
      {
        path: 'previewQuestionnaire',
        name: 'previewQuestionnaire',  //预览问卷
        component: () => import('@/views/surveyManagement/PreviewQuestionnaire.vue')
      },
      
      {
        path: 'reviewManagement',
        name: 'reviewManagement',   //评价管理
        component: () => import('@/views/reviewManagement/ReviewManagement.vue')
      },
      {
        path: 'reviewManagementDetail/:stepRoute',
        name: 'reviewManagementDetail',   //评价管理详情页
        component: () => import('@/views/reviewManagement/ReviewManagementDetail.vue'),
      },
      
      {
        path: 'reviewAnalysis',
        name: 'reviewAnalysis',
        component: () => import('@/views/reviewAnalysis/ReviewAnalysis.vue')
      },
      {
        path: 'personalCenter',
        name: 'personalCenter',
        component: () => import('@/views/personalCenter/personalCenter.vue')
      },
    ]

  },
  {
    path: '/:pathMatch(.*)*', // 捕获所有未匹配路径
    name: 'NotFound',
    component: () => import('../views/login/login.vue') // 未匹配到路由跳转到登录页面
  }
]

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

// 添加一个路由守卫
router.beforeEach(async(to,from,next)=>{
  console.log('当前to的路由',to)
  console.log('当前from的路由',from)
  if (to.path === '/') {
    // const token = localStorage.getItem('token')
    // 查询用户信息
    const token = to?.query?.token
    const userType = to?.query?.loginRole   // 'student' : 'teacher'
    
    if(token){
      localStorage.setItem('token',token)
      localStorage.setItem('loginRole',userType)
      
      let userInfoRes = await  getUserInfo()
      console.log("获取用户信息返回",userInfoRes)
      if (userInfoRes?.code === 200) {
        // 存储用户信息到 localStorage 或 Pinia
        localStorage.setItem('userInfo', JSON.stringify(userInfoRes.data))
        next('/main')
        return
      }
    }
  }
  next()
})


export default router