import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import { parseSearch } from "@/service/utils";
import { isXyqb } from "@/service/validation";
import { authByxyqb } from "@/api/user";
import localStorage from "@/service/localStorage";
Vue.use(VueRouter);

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,
  scrollBehavior() {
    return { x: 0, y: 0 };
  }
});

router.beforeEach((to, from, next) => {
  const urlParams = parseSearch(window.location.href);
  if (isXyqb()) getAuthInfo(urlParams.token);
  next();
});

async function getAuthInfo(xyqbToken) {
  const res = await authByxyqb({ xyqbToken });
  if (res) {
    localStorage.set("mongoToken", res.token);
    localStorage.set("xyqbUserInfo", res);
    localStorage.set("xyqbToken", xyqbToken);
  }
}
// router.afterEach(() => {});

export default router;
