/*
 * @Author: WangQiBiao
 * @Date: 2019-09-18 09:37:48
 * @LastEditors: MoZhuangRu
 * @LastEditTime: 2019-11-21 17:40:56
 * @Description:
 */
import Vue from 'vue'
import Router from 'vue-router'
// import _import from './_import'
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) => {
  if (to.fullPath === '/index?demo=true' && to.query.demo) {
    localStorage.setItem('demo', to.query.demo)
  } else {
    if (to.fullPath === '/index' && localStorage.getItem('demo') === 'true') {
      localStorage.removeItem('demo')
    }
  }
  const { permisList } = store.state.menu
  const tk = to.query && to.query.tk
  const hasToken = localStorage.getItem('token') || tk
  if ((!hasToken) && !['/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
