import { AUTHKEYNAME } from "@sud-web/utils"
import { ElMessage } from "element-plus"
import NProgress from "nprogress"
import { getAuthCode } from "@/api/login"
import asyncRouteSettings from "@/config/async-route"
import { routerWhiteList, whiteList } from "@/config/white-list"
import router from "@/router"
import { usePermissionStoreHook } from "@/store/modules/permission"
import { useUserStoreHook } from "@/store/modules/user"
import { redirectToLogin } from "@/utils/auth-redirect"
import { getCsrfToken } from "@/utils/cache/cookies"
import "nprogress/nprogress.css"

NProgress.configure({ showSpinner: false })

function getLatestAuthCode(value: unknown): string {
  const codes = Array.isArray(value) ? value : [value]
  for (let i = codes.length - 1; i >= 0; i--) {
    const code = codes[i]
    if (typeof code === "string" && code) return code
  }
  return ""
}

router.beforeEach(async (to, _from, next) => {
  NProgress.start()
  const hasAuthCodeQuery = Object.prototype.hasOwnProperty.call(to.query, AUTHKEYNAME)
  const sudAuthCode = getLatestAuthCode(to.query[AUTHKEYNAME])

  if (hasAuthCodeQuery && !sudAuthCode) {
    const query = { ...to.query }
    delete query[AUTHKEYNAME]
    return next({ path: to.path, query, hash: to.hash, replace: true })
  }

  // 携带 code（SSO 回跳）则去兑换登录态
  if (sudAuthCode) {
    try {
      const res = await getAuthCode(sudAuthCode)
      if (res) {
        // 兑换成功后，从 query 中剔除 code 并替换历史记录
        const query = { ...to.query }
        delete query[AUTHKEYNAME]
        return next({ path: to.path, query, hash: to.hash, replace: true })
      }
      // 没有响应则重新跳回 SSO
      redirectToLogin()
      return
    } catch {
      redirectToLogin()
      return
    }
  }

  const userStore = useUserStoreHook()
  const permissionStore = usePermissionStoreHook()

  // 不做用户信息认证的路由直接通过
  if (routerWhiteList.includes(to.path)) {
    next()
    return
  }

  // 判断该用户是否登录（CSRF Token 存在即视为已登录）
  if (getCsrfToken()) {
    // 检查用户是否已获得其权限角色
    if (userStore.roles.length === 0) {
      try {
        if (asyncRouteSettings.open) {
          // 注意：角色必须是一个数组！ 例如: ['admin'] 或 ['developer', 'editor']
          await userStore.getInfo()
          const roles = userStore.roles
          // 根据角色生成可访问的 Routes（可访问路由 = 常驻路由 + 有访问权限的动态路由）
          permissionStore.setRoutes(roles)
        } else {
          // 没有开启动态路由功能，则启用默认角色
          userStore.setRoles(asyncRouteSettings.defaultRoles)
          permissionStore.setRoutes(asyncRouteSettings.defaultRoles)
        }
        // 将'有访问权限的动态路由' 添加到 Router 中
        permissionStore.dynamicRoutes.forEach((route) => {
          router.addRoute(route)
        })
        // 确保添加路由已完成；replace: true 不留历史记录
        next({ ...to, replace: true })
      } catch (err: any) {
        // 过程中发生任何错误，都直接重置 Token，并重定向到 SSO 登录
        userStore.resetToken()
        ElMessage.error(err ? (err.message || "路由跳转发生错误") : "路由守卫过程发生错误")
        redirectToLogin()
      }
    } else {
      next()
    }
  } else {
    // 没有登录态
    if (whiteList.includes(to.path)) {
      next()
    } else {
      redirectToLogin()
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
