import {createRouter, createWebHistory} from 'vue-router'
import {getToken} from "@/utils/auth.ts"
import {logout} from "@/api/login.ts";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginPage.vue'),
      meta: {
        auth: false,
        loginTypes: ['password', 'sms', 'dingtalk', 'wecom']
      }
    },
    {
      path: '/sso',
      name: 'sso',
      component: () => import('../views/login/Sso.vue'),
      meta: { auth: false }
    }
  ]
})
const parseURL = (
    url: string | null | undefined
): { basePath: string; paramsObject: { [key: string]: string } } => {
  // 如果输入为 null 或 undefined，返回空字符串和空对象
  if (url == null) {
    return { basePath: '', paramsObject: {} }
  }

  // 找到问号 (?) 的位置，它之前是基础路径，之后是查询参数
  const questionMarkIndex = url.indexOf('?')
  let basePath = url
  const paramsObject: { [key: string]: string } = {}

  // 如果找到了问号，说明有查询参数
  if (questionMarkIndex !== -1) {
    // 获取 basePath
    basePath = url.substring(0, questionMarkIndex)

    // 从 URL 中获取查询字符串部分
    const queryString = url.substring(questionMarkIndex + 1)

    // 使用 URLSearchParams 遍历参数
    const searchParams = new URLSearchParams(queryString)
    searchParams.forEach((value, key) => {
      // 封装进 paramsObject 对象
      paramsObject[key] = value
    })
  }

  // 返回 basePath 和 paramsObject
  return { basePath, paramsObject }
}
router.beforeEach((to, from, next) => {
  if(to.path === '/logout'){
    logout().finally(window.location.href = to.query.redirect || import.meta.env.VITE_APP_DEFAULT_PAGE)
  }

  if (getToken()) {
    if (to.path === '/sso') {
      const redirectPath = from.query.redirect || to.path
      // 修复跳转时不带参数的问题
      const redirect = decodeURIComponent(redirectPath as string)
      const { paramsObject: query } = parseURL(redirect)
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect, query }
      console.log(nextData)
      next()
    }  else {
      next()
    }
  } else {
    if (to.path === '/sso') {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
    } else {
      next()
    }
  }
})

export default router