/*
 * @Description:
 * @Author: Wang Minjie
 * @Date: 2020-01-04 11:48:57
 * @LastEditTime : 2020-01-14 15:27:52
 * @LastEditors  : Wang Minjie
 */
import Vue from 'vue'
import store from '@/store'
import Router from 'vue-router'
import routes from './routers'
import iView from 'iview'
import { asynRouters_copy } from '@/router/aysnRouters.js'
import { canTurnTo, setTitle } from '@/libs/util'

const baseUrl = process.env.NODE_ENV === 'production' ? '/platform/' : '/'

Vue.use(Router)
const router = new Router({
  routes,
  base: baseUrl,
  mode: 'history'
})

const checkToken = () => {
  let { token } = store.state.user
  if (token) {
    return true
  } else {
    return false
  }
}
// const REGISTER_PAGE_NAME = 'register'

// 判断是否为动态路由的页面
const IsAsynPath = (path) => {
  return canTurnTo(path, asynRouters_copy)
}

const turnTo = (to, next, access) => {
  if (canTurnTo(to.path, access)) {
    next() // 有权限，可访问
  } else if (IsAsynPath(to.path)) {
    next({ replace: true, name: 'error_401' }) // 地址正确但无权限，重定向到401页面
  } else {
    next({ replace: true, name: 'error_404' }) // 错误地址，重定向到404页面
  }
}

const whiteList = [
  'login',
  'register',
  'error_401',
  'error_404'
]

router.beforeEach((to, from, next) => {
  let hasToken = checkToken()
  if (hasToken) {
    // 判断是否获得路由权限
    if (!store.state.app.gotPermission) {
      store.dispatch('GetAccountData')
      store.dispatch('getPermission').then((asyn_routes) => {
        const newRoutes = routes.concat(asyn_routes)
        store.commit('setMenuList', newRoutes)
        router.options.routes = newRoutes
        router.addRoutes(asyn_routes)
        return newRoutes
      }).then(() => {
        // 通过刷新或者输入地址访问页面时，直接next()无法根据router访问， 需重新通过vueRouter跳转
        next({ path: to.path, query: to.query })
      })
    } else if (store.state.app.gotPermission) {
      if (to.name === 'login') {
        next({ replace: true, name: 'home' })
      } else if (to.name === 'home') {
        next()
      } else {
        const newRoutes = routes.concat(store.state.user.permission)
        turnTo(to, next, newRoutes)
      }
    }
  } else if (!hasToken) {
    if (whiteList.indexOf(to.name) !== -1) {
      next()
    } else {
      next({ replace: true, name: 'login' })
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
