import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { cancelRequest } from './utils/request'

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

const whiteList = ['/error'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  cancelRequest()
  // start progress bar
  NProgress.start()

  if (store.getters.isValid) {
    if (to.path === '/error') {
      // redirect to the home page
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      next()
    }
  } else if (whiteList.includes(to.path)) {
    // 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('/error')
    NProgress.done()
  }
})

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