/**
 * @copyright chuzhixin 1204505056@qq.com
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import router from "../router"
import store from "../store"
import VabProgress from "nprogress"
import "nprogress/nprogress.css"
import { resetRouter } from "@/router"
import getPageTitle from "@/utils/pageTitle"
import {
  authentication,
  loginInterception,
  routesWhiteList,
  progressBar,
} from "@/config/settings"

import { Message } from "element-ui"
VabProgress.configure({
  easing: "ease",
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
})
router.beforeResolve(async (to, from, next) => {
  if (progressBar) VabProgress.start()
  let hasToken = store.getters["user/accessToken"]
  if (!loginInterception) hasToken = true
  if (hasToken) {
    if (to.path === "/home") {
      next({
        path: "/",
      })
      if (progressBar) VabProgress.done()
    } else if (routesWhiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      const userInfo = store.getters["user/userInfo"]
      if (userInfo) {
        console.log(to.path)
        next()
      } else {
        try {
          const menulist = await store.dispatch("user/getInfo")
          let accessRoutes = []
          if (authentication === "intelligence") {
            accessRoutes = await store.dispatch("routes/setRoutes")
          } else if (authentication === "all") {
            accessRoutes = await store.dispatch("routes/setAllRoutes", menulist)
          }
          router.addRoutes(accessRoutes)
          if (accessRoutes.length === 1) {
            Message({
              message: "暂无菜单权限，请联系管理员",
              type: "error",
              duration: 3000,
            })
            await store.dispatch("user/resetAccessToken")
            await resetRouter()
            next(`/home`)
            if (progressBar) VabProgress.done()
          } else {
            store.dispatch("dict/getDictData") //字典获取
            next({
              ...to,
              replace: true,
            })
          }
        } catch (error) {
          await store.dispatch("user/resetAccessToken")
          next(`/home?redirect=${to.path}`)
          if (progressBar) VabProgress.done()
        }
      }
    }
  } else {
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/home?redirect=${to.path}`)
      if (progressBar) VabProgress.done()
    }
  }
  document.title = getPageTitle(to.meta.title)
})
router.afterEach(() => {
  if (progressBar) VabProgress.done()
})
