import router, {
  resetRouter
} from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({
  showSpinner: false
})

const allowList = ['login', 'newInquiry','WaybillInquiry', 'FourOhFour'] // no redirect allowList

//全局前置路由，若无next()则不会进行下一步骤
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = localStorage.getItem('T_tokey')
  // 若token存在，则该用户已登录
  if (hasToken) {
    localStorage.setItem("activePath", to.path);
    if (to.path === '/login') {
      // 若此时页面在登录页面，则跳转至首页
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      if (store.getters.roles.length != 0 || allowList.includes(to.name)) {
        next()
      } else {
        store.dispatch('GetInfo').then(value => {
          const deptId = value
          store.dispatch('GenerateRoutes', {
            deptId
          }).then((res) => {
            const accessRoutes = res
            resetRouter()
            router.addRoutes(accessRoutes)
            next({
              ...to,
              replace: true
            })
          }).catch(() => {
            store.dispatch('Logout').then(() => {
              next('/login')
            })
          })
        }).catch(() => {
          store.dispatch('Logout').then(() => {
            next('/login')
          })
          Message.error(error.message || 'Has Error')
          NProgress.done()
        })
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next()
    } else {
      next('/login')
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

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