import router, {
  resetRouter
} from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({
  showSpinner: false
})
const whiteList = ['login', '404'] // 白名单

//全局前置路由，若无next()则不会进行下一步骤
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = localStorage.getItem('T_tokey')
  // 若token存在，则该用户已登录
  if (hasToken) {
    if (to.path === '/login') {
      // 若此时页面在登录页面，则跳转至首页
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      if (store.getters.roles.length != 0) {
        next()
      } else {
        store.dispatch('GetInfo').then(res => {
          // 若该用户之前未存储角色权限在store中，则前往store目录下的该路径，根据store存储过的token，获取并存储该用户的角色权限
          store.dispatch('GenerateRoutes', {
            hasToken
          }).then((res) => {
            const accessRoutes = res
            resetRouter()
            router.addRoutes(accessRoutes)
            next({
              ...to,
              replace: true
            })
          }).catch((err) => {
            next({
              ...to,
              replace: true
            })
          })
        }).catch(() => {
          // remove token and go to login page to re-login
          store.dispatch('Logout').then(() => {
            next('/login')
          })
          //这里会报个参数类型异常，所以将参数 由error 改为了 error.message
          Message.error(error.message || 'Has Error')
          NProgress.done()
        })
      }
    }
  } else {
    /* has no token*/
    if (whiteList.includes(to.name)) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
