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')// 用户信息初始化 PS:token不存在 执行且执行一次
  const power = store.state.user.power
  const token = store.state.user.token
  if (token === null) {
    if (to.path === '/login') {
      next()
      NProgress.done()
    } else {
      next('/login')
      NProgress.done()
    }
  } else {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (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) {
  if (pageTitle) {
    return `${pageTitle} - ${store.state.settings.title}`
  } else {
    return store.state.settings.title
  }
}
