import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index';

// 路由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 main from '@views/main'
import error404 from '@views/404'
import login from '@views/login'

// 子路由
import yRouter from '@router/ylf';
import lRouter from '@router/lzx';
import zRouter from '@router/zm';

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    meta: {
      requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
    },
    component: main,
    children: [
      { // 首页
        path: '/',
        component: r => require.ensure([], () => r(require('@views/index/index')), 'indexM')
      },
      ...yRouter,
      ...lRouter,
      ...zRouter
    ]
  },
  {
    path: '/404', // 页面不存在的情况下会跳到404页面
    meta: {
      requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的  /进路由勾子函数beforeEach
    },
    name: 'error404',
    component: error404,
  },
  {
    path: '/login',
    meta: {
      requireAuth: true,
    },
    name: 'login',
    component: login,
  }
  // { // 健康评价报告 - 临时  /部署单页面
  //   path:'/healthAssessmentDetailed2',
  //   component: r => require.ensure([], () => r(require('@views/healthManagement/healthAssessmentDetailed')), 'healthManagement')
  // },
]

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

/**
 * 路由的钩子函数，处理是否登录的判断
 * **/
router.beforeEach((to, from, next) => {
  // 登录后登录处理办法
  // if (to.path === '/login' && store.getters.authToken) {
  //   next({ path: '/' })
  // } else
   if (to.matched.some(m => m.meta.requireAuth)) {    // 需要登录
    if (window.localStorage.authToken) {
      next()
    } else if (to.path !== '/login') {
      let token = localStorage.getItem('authToken');
      if (token === null || token === '' || token === undefined) {
        next({ path: '/login' })
      } else { next() }
    } else {
      next()
    }
  } else {   // 不需要登录
    next()
  }
  if (to.matched.length === 0) { // 如果未匹配到路由
    // sessionStorage.removeItem("btrh_sxsd_locationHref");
    next('/404')   // 如果上级也未匹配到路由则跳转登录页面，如果上级能匹配到则转上级路由
  }
})

export default router
