import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import basicRoutes from './basic-router'
import coreRoutes from './core-router'
import iView from 'view-design'
import {
  setToken,
  getToken,
  setTitle,
  sessionSave,
  sessionRead
} from '@/libs/base/util'

// 引入加载菜单
import {loadMenu} from '@/libs/base/router-util'

/**
 * 重写路由的push方法
 * 解决，相同路由跳转时，报错
 * 添加，相同路由跳转时，触发watch (针对el-menu，仅限string方式传参，形如"view?id=5")
 */
// 保存原来的push函数
// const routerPush = Router.prototype.push
// // 重写push函数
// Router.prototype.push = function push(location) {
//   console.log('333',JSON.stringify(location))
//   // 这个if语句在跳转相同路径的时候，在路径末尾添加新参数（一些随机数字）
//   // 用来触发watch
//   if (typeof (location) == "string") {
//     let Separator = "&";
//     if (location.indexOf('?') == -1) {
//       Separator = '?';
//     }
//     location = location + Separator + "random=" + Math.random();
//   }else if (typeof (location) == "object") {
//     let Separator = "&";
//     let path = location.path;
//     if(path){
//       if (path.indexOf('?') == -1) {
//         Separator = '?';
//       }
//       path = path + Separator + "random=" + Math.random();
//       console.log('343432',this,JSON.stringify(location))
//       return routerPush.call(this, path)
//     }
//   }
//   // 这个语句用来解决报错
//   // 调用原来的push函数，并捕获异常
//   return routerPush.call(this, location)
// }
Vue.use(Router)
const router = new Router({
  //todo basicRoutes临时添加基础数据路由  ...loadMenu(),
  routes: [...routes, ...loadMenu()],
  mode: 'history'
})

// router.addRoutes(loadMenu())


const NO_AUTH_NAME = ['error_500', 'login', 'login_hegii', 'auth', 'test', 'qv-login', 'wx-print', 'approval_waiting_for_approval', 'approval_waiting_for_approval_detail', 'log_report_export']

const NO_APP_AUTH_NAME = ['app-login','test']
router.beforeEach((to, from, next) => {
  // console.log('to',to,from,next)
  iView.LoadingBar.start()
  let token = sessionStorage.getItem('token')
  // console.log('dd',token)
  /* 先看你是不是登陆了 */
  if (token) {
    next()
  } else {
    /* 未登陆有两种情况
    * 1：你请求无需授权的页面
    * 2：你请求需要授权的页面
    * */
    if (NO_AUTH_NAME.some(item => {
      return item === to.name
    })) {
      next()
    } else if (NO_APP_AUTH_NAME.some(item => {
      // console.log(item, to)
      return item === to.name
    })) {
      next()
    } else if (to.name != null && to.name.indexOf("/app") > 0) {
      next({
        name: 'app-login' // 跳转到登录页
      })
    } else {
      next({
        name: 'login' // 跳转到登录页
      })
    }
  }

})

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

export function resetRouter() {
  const newRouter = new Router({
    routes: routes
  })
  router.matcher = newRouter.matcher
}

export default router

