import router from '@/router'

import store from '@/store'

import { getToken, getUserInfo, initGoPage } from '@/utils/auth'
// 获取用户信息
const userInfo = getUserInfo()
if (userInfo) {
  store.commit('user/SAVE_USER_INOF', userInfo)
}

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

// 路由拦截器
router.beforeEach(async(to, from, next) => {
  // 获取token
  const hasToken = getToken()
  if (hasToken) {
    // 如果是访问登录页面，强制跳转到首页
    if (to.path === '/login') {
      next({ path: initGoPage() })
    } else {
      // 加载国家列表
      store.dispatch('app/setCountry')
      // 角色判断
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          const roles = await store.dispatch('user/getRoles')
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (err) {
          store.dispatch('user/logout')
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})
