import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import whiteList from './whiteList'
import {
  Message
} from 'element-ui'
import {
  Auth
} from '@/util/auth'
import store from '../store'
import {
  staticRoute,
  routeHandle
} from './staticRoute'
NProgress.configure({
  showSpinner: false
})

Vue.use(VueRouter)
//以下代码解决路由地址重复的报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'hash',
  routes: staticRoute
})

// 路由跳转前验证
router.beforeEach((to, from, next) => {

  // 开启进度条
  NProgress.start()
  // 判断是否传入token

  const token = to.query.token
  const _token = Auth.getLoginInfo()
  const routers = router.getRoutes()
  const menu = store.getters.menuMap
  const userInfo = store.getters.userInfo
  // console.log('router', routers)
  // console.log('token', token)
  // console.log('_token', _token)
  // console.log('userInfo', userInfo)
  // console.log('menu', menu)
  if ((token && token !== _token) || (_token && (routers.length === 9 || !menu || !userInfo))) { //新用户登或重新登录
    console.log('拉取用户数据')
    store.dispatch('LoginByToken', token || _token).then(res => {
      // const {
      //   menuMap
      // } = res
      // router.addRoutes(routeHandle(menuMap))
      next({
        ...to,
        replace: true
      })
    }).catch(err => {
      store.dispatch('clearStore')
      Message({
        type: 'error',
        message: '登录失败 请联系管理员！'
      })
      next({
        path: '/error/404',
        replace: true
      })
    })
  } else {
    if (whiteList.indexOf(to.path) >= 0) {
      console.log('该页面无需登录即可访问')
      next()
    } else {
      if (routers.length > 9 && _token && menu && userInfo) {
        console.log('有数据无需登录')
        next()
      } else {
        store.dispatch('clearStore')
        console.log('没数据没tonken 跳转404')
        next({
          path: '/error/404',
          replace: true
        })
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})

export default router
