import { createRouter, createWebHashHistory } from "vue-router"
import { constRoutes } from "./routers"
import NProgress from "@/plugins/nprogress"
import { ElMessage } from "element-plus"
import { getToken, CODE401 } from "@/libs/auth"
import userStore from "@/store/user"

const userStoreHook = userStore()

userStoreHook.login()

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: constRoutes,
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})
function isRegWhite(regs: RegExp[], path: string) {
  return (
    regs.findIndex(reg => {
      return reg.test(path)
    }) > -1
  )
}
const authWhiteList = ["/login"] // 不访问接口权限白名单
const regWhiteList: RegExp[] = [] //正则白名单(用于系统不需要权限的分享页面)

router.beforeEach((to, from, next) => {
  NProgress.start()
  const hasToken = getToken()
  //如果有token且不是白名单页面则加载info
  if (hasToken && !authWhiteList.includes(to.path)) {
    //有roles时候
    const hasRoles = userStoreHook.roles
    if (hasRoles) {
      next()
    } else {
      userStoreHook
        .getUserInfo()
        .then(() => {
          next()
        })
        .catch((err: apiResDataType) => {
          //退出 清空,当是登录权限问题时候 axios 里面会清空
          if (err.code !== CODE401) {
            //ElMessage.error(err.message)
            userStoreHook.resetUser()
          }
        })
    }
  } else {
    // 如果有token，并且是登录页 直接返回首页
    if (hasToken && to.path === "/login") {
      next({
        path: "/"
      })
      return
    }
    if (authWhiteList.includes(to.path) || isRegWhite(regWhiteList, to.path)) {
      next()
    } else {
      next({
        path: "/login"
      })
    }
  }
})

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

export default router
