import router from './router'
import store from './store'
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', '/', '/loading']// no redirect whitelist

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

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