import router from './router'
import store from './store'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条 style

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

/**
 * @description: 路由守卫
 */
router.beforeEach((to, from, next) => {
  // start 进度条
  NProgress.start()
  // 设置title
  document.title = getPageTitle(to.meta.title)

  store.commit('user/initUser') // 用户信息初始化
  const power = store.state.user.power
  const token = store.state.user.token

  if (!token) {
    if (to.path === '/login') {
      next()
    } else {
      next('/login') // 直接调用 next('/login')
    }
  } else {
    if (to.path === '/login') {
      next('/')
    } else {
      if (to.meta.roles && to.meta.roles.indexOf(power) >= 0) { // 确保 roles 存在
        next()
      } else {
        next('/')
      }
    }
  }

  NProgress.done()
})

/**
 * @description: 路由完成 结束进度条
 */
router.afterEach(() => {
  NProgress.done() // 结束进度条
})

/**
 * @description: mateTile 和 全局title 组合
 * @return: title
 * @param {*} pageTitle 路由mate.tiele
 */
function getPageTitle (pageTitle) {
  return pageTitle ? `${pageTitle} - ${store.state.settings.title}` : store.state.settings.title
}
