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
import getPageTitle from '@/utils/get-page-title'
import { getALLRouter } from '@/utils'

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

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

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

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the userinfo has logged in
  const hasToken = store.getters.token

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const pa = to.path.split('/')[1]
      const pathMap = {
        'reagent': 'reagent',
        'user': 'user',
        'userinfo': store.getters.classification
      }
      const pat = pathMap[pa]
      if (to.name) {
        // 设置header栏样式根据主预览页面不同
        if (to.path === '/reagent/mainoverview/index') {
          store.commit('settings/CHANGE_SETTING', { key: 'isMain', value: true })
        } else {
          store.commit('settings/CHANGE_SETTING', { key: 'isMain', value: false })
        }
        store.commit('user/SET_CLASS', pat)
        next()
      } else {
        store.commit('user/SET_CLASS', pat)
        const { asyncRoutes } = getALLRouter(store.getters.roleData)
        resetRouter()
        router.addRoutes(asyncRoutes)
        next({ ...to, replace: true })
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // 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(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

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