import Vue from 'vue'
import VueRouter from 'vue-router'

// 路由3+版本的异常处理
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace (location) {
  return originalReplace.call(this, location).catch(err => err);
}

// 公共页面
import search from '@pages/search';
import lineChart from '@pages/lineChart';
import test from '@pages/test';

// 子路由

Vue.use(VueRouter)

const routes = [
  {
    path: '/search',
    component: search
  }, {
    path: '/lineChart',
    component: lineChart
  }, {
    path: '/test',
    component: test
  }, {
    path: '/',
    redirect: '/search'
  }
]

const router = new VueRouter({
  mode: 'history',
  // base: '/report/', / 部署单页面 404 history  带井号解决（去掉history 放web-inf）
  base: '/',
  routes
})

/**
 * 路由的钩子函数，处理是否登录的判断
 * **/
router.beforeEach((to, from, next) => {
  // 路由地址不存在的处理办法
  if (to.matched.length === 0) { // 如果未匹配到路由
    // sessionStorage.removeItem("btrh_sxsd_locationHref");
    next('/404')   // 如果上级也未匹配到路由则跳转登录页面，如果上级能匹配到则转上级路由
  }

  if (to.matched.some(r => r.meta.requireAuth)) {

    let userinfo = JSON.parse(sessionStorage.getItem("btrh_sxsd_userinfo"));
    userinfo = "";
    if (userinfo !== null) {
      // if(to.path !== "/"){
      //   // 判断当前菜单是否有权限打开，如果无权限，自动退出
      //   routerCheck(userinfo.roleId, to.path, next);
      // }else{
      //   next();
      // }
      next();
      return;
    }
    next("/login");
  } else {
    next();
  }
})

export default router
