import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'view-design'
import { setToken, getToken } from '@/libs/util'

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

// 修改原型对象中的push方法 用于路由重复报错
const originalPush = Router.prototype.push
const originalReplace = Router.prototype.replace
Router.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
Router.prototype.replace = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  if (!token && (!['login', LOGIN_PAGE_NAME, 'warning-list', 'check'].includes(to.name))) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME,
      query: {
        plcCode: sessionStorage.getItem('plcCode'),
        door: sessionStorage.getItem('door')
      }
    })
  } else if (!token && (['login', LOGIN_PAGE_NAME, 'warning-list', 'check'].includes(to.name))) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else {
    if (store.state.hasGetInfo) {
      next()
    } else {
      store.dispatch('getUserInfo').then(user => {
        next()
      }).catch(() => {
        setToken('')
        next({
          name: LOGIN_PAGE_NAME,
          query: {
            plcCode: sessionStorage.getItem('plcCode'),
            door: sessionStorage.getItem('door')
          }
        })
      })
    }
  }
})

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

export default router
