/*
 * @Author: WangQiBiao
 * @Date: 2019-09-18 09:37:48
 * @LastEditors: mozhuangru
 * @LastEditTime: 2019-10-12 10:31:46
 * @Description:
 */
import Vue from 'vue'
import Router from 'vue-router'
import whiteList from './white-list'
import { filtersPermisList } from './permis-list'
import store from '@/store'

Vue.use(Router)

const router = new Router({
  // mode: 'history',
  base: '/screen/',
  routes: [
    ...whiteList
  ]
})

let isFlag = false // 是否第一次添加权限路由表，默认不是；【没有会导致路由无限死循环】

router.beforeEach(async (to, from, next) => {
  const { permisList } = store.state.menu
  if ((!sessionStorage.getItem('token')) && !['/login', '/no-login'].includes(to.path)) {
    next('/no-login')
    return
  }
  if (whiteList.map(item => item.path).indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
    next()
  } else if (permisList.length) {
    if (!isFlag) {
      isFlag = true
      await filtersPermisList(permisList).then(newRouter => {
        router.addRoutes(newRouter)
        next({ ...to, replace: true })
      })
    } else {
      next()
    }
  } else {
    next()
  }
})
export default router
