import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
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', '/config', '/', '/editor', '/posTool']// no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/index/dashboard' })
      NProgress.done()
    } else {
      // if (!store.getters.addRouters.length) {
      //   store.dispatch('GenerateRoutes', {}).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
      //   })
      // } else {
      //   next()
      // }
      // 根据权限加载路由
      if (!store.getters.addRouters.length) {
        store.dispatch('GetInfo').then(res => {
          store.dispatch('GenerateRoutes', res.data).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
})
