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: '/phoneLogin',
    name: 'phoneLogin',
    component: () => import('../views/login/phoneLogin.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: Layout,
    children: [
      {
        path: '',
        name: 'appointmentAndTodo',   //预约待办
        component: () => import('../views/appointmentAndTodo/index.vue')
      },
      {
        path: 'highSeasCustomer',
        name: 'highSeasCustomer',   //公海客户
        component: () => import('../views/highSeasCustomer/index.vue')
      },
      {
        path: 'myCustomer',
        name: 'myCustomer',   //我的客户
        component: () => import('../views/myCustomer/index.vue')
      },
      {
        path: 'customerFollowUp',
        name: 'customerFollowUp',   //客户跟进
        component: () => import('../views/customerFollowUp/index.vue')
      },
      {
        path: 'userPrivilegeManagement',
        name: 'userPrivilegeManagement',   //用户权限
        component: () => import('../views/userPrivilegeManagement/index.vue')
      },
      {
        path: 'parameterConfig',
        name: 'parameterConfig',   //参数配置
        component: () => import('../views/parameterConfig/index.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