import Vue from "vue";
import VueRouter from "vue-router";
import adminRoutes from "./adminRoutes";
Vue.use(VueRouter);

function queryStorage(location) {
  if (location instanceof Object && location.path) {
    let _location = {};
    _location.path = location.path;
    let _queryStorage = sessionStorage.getItem("_queryStorageAdmin");
    _queryStorage = _queryStorage ? JSON.parse(_queryStorage) : {};
    if (location.query) {
      _queryStorage[location.path] = location.query;
      _location.query = location.query;
    } else {
      if (
        _queryStorage[location.path] &&
        window.location.href.includes(location.path)
      ) {
        _location.query = _queryStorage[location.path];
      }
    }
    sessionStorage.setItem("_queryStorageAdmin", JSON.stringify(_queryStorage));
    return _location;
  }
  return location;
}
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  let newLocation = queryStorage(location);
  return routerPush.call(this, newLocation).catch((error) => error);
};
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  let newLocation = queryStorage(location);
  return originalReplace.call(this, newLocation).catch((err) => err);
};
const getRoutes = () => {
  return adminRoutes;
};

const createRouter = () =>
  new VueRouter({
    scrollBehavior: () => ({
      y: 0
    }),
    routes: getRoutes()
  });
const router = createRouter();
//写一个重置路由的方法，切换用户后，或者退出时清除动态加载的路由
function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // 新路由实例matcer，赋值给旧路由实例的matcher，（相当于replaceRouter）
  router.options.routes = newRouter.options.routes;
}
router.resetRouter = resetRouter;
/**
 * 路由守卫(拦截)
 */
router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    let u = localStorage.getItem("xhWebAdminUser");
    if (u) {
      next();
    } else {
      next({
        path: "/login",
        query: to.query
      });
    }
  }
});
export default router;
