import router from '@/router'
import useStore from '@/stores'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })

let loaded = false

// 白名单路由
const whiteList = ['/login', '/errorpage']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const { user, permission } = useStore()
  const hasToken = user.tokenValue
  if (hasToken) {
    // 登录成功，跳转到首页
    if (to.path === '/login') {
      loaded = false
      router.removeRoute('errorpage')
      next()
      NProgress.done()
    } else {
      if (!loaded) {
        try {
          const menuList = (await user.getUserRoleInfo()) as any[]
          const accessRoutes: any = await permission.generateRoutes(menuList)
          accessRoutes.forEach((route: any) => {
            router.addRoute(route)
          })
          next({ ...to, replace: true })
          loaded = true
        } catch (error) {
          console.warn(error)
          // 移除 token 并跳转登录页
          await user.onResetToken()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        next()
      }
    }
  } else {
    // 未登录可以访问白名单页面(登录页面)
    if (whiteList.indexOf(to.path) !== -1) {
      if (to.path === '/login') {
        loaded = false
        router.removeRoute('errorpage')
      }
      next()
    } else {
      loaded = false
      router.removeRoute('errorpage')
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

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