import Vue from "vue";
import VueRouter from "vue-router";
import routeConfig from "./routes";
import store from "@/store/index";

Vue.use(VueRouter);
Vue.use(store);

const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch((err) => err);
};
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes: routeConfig,
});
router.beforeEach((to, from, next) => {
  let islogin = store.getters["user/token"];
  // let routerPath = store.getters["user/routerList"];
  // let toRootPathArr = to.matched.map((v) => v.path);
  // let bol = hasIntersection(toRootPathArr, routerPath);
  if (islogin) {
    next();
    // if (routerPath.includes(to.path) || bol) {
    //   next();
    // }
  } else {
    // 再次判断防止死循环
    if (to.path === "/") {
      next();
    } else {
      next({ path: "/" });
    }
  }
});

// function hasIntersection(arr1, arr2) {
//   return arr1.some((item) => arr2.includes(item));
// }

router.afterEach((to, from, next) => {
  window.scrollTo(0, 0);
});

export default router;