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.platToken) {
    if (to.path === '/login') {
      next({ path: '/systemSetting/project' })
      NProgress.done()
    } else {
      if (store.getters.menuList.length === 0) {
        store.dispatch('GetInfo').then(() => {
          return store.dispatch('GenerateRoutes', {})
        }).then(() => { // 根据roles权限生成可访问的路由表
          if (!router.__dynamicRoutesAdded) {
            router.addRoutes(store.getters.addRouters)
            router.__dynamicRoutesAdded = true
          }
          if (to.fullPath === '/error/404') {
            next({ path: store.getters.addRouters[0].path, replace: true })
            return
          }
          next({ ...to, replace: true }) // 确保权限路由状态已初始化
        }).catch((err) => {
          if (to.path === '/login') {
            next()
            return
          }
          store.dispatch('LogOut').finally(() => {
            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
})
