import router from './router'
import store from '@/store/index.js'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
// import { getToken } from '@/utils/auth' // getToken from cookie

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login', '/', '/demo', '/404', '/loading']// no redirect whitelist

router.beforeEach((to, from, next) => {
  console.log('%c [ to ]-13', 'font-size:13px; background:pink; color:#bf2c9f;', to)
  NProgress.start() // start progress bar
  if (localStorage.mgt_token) {
    if (to.path === '/login') {
      next({ name: 'dashboard' })
      NProgress.done()
    } else {
      if (store.getters.menuList.length === 0) {
        store.dispatch('GetInfo').then(res => {
          const extraInfo = res.extraInfo
          store.dispatch('GenerateRoutes', extraInfo).then(() => { // 根据roles权限生成可访问的路由表
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          }).catch((err) => {
            store.dispatch('LogOut').then(() => {
              Message.error(err || 'Verification failed, please login again')
              next({ path: '/login' })
            })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next({ path: '/login' })
      NProgress.done()
    }
  }
})

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