import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import { parseSearch } from "@/service/utils";
import { isXyqb, isWeixinBrower } from "@/service/validation";
import cfg from "@/config";
import { authByxyqb, getwxOpenId } 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);
  if (isWeixinBrower) getWxOpenId(urlParams.code);
  next();
});

async function getAuthInfo(xyqbToken) {
  if (localStorage.get("xyqbToken")) return;
  const res = await authByxyqb({ xyqbToken });
  if (res) {
    localStorage.set("mongoToken", res.token);
    localStorage.set("xyqbUserInfo", res);
    localStorage.set("xyqbToken", xyqbToken);
  }
}

async function getWxOpenId(code) {
  if (localStorage.get("openId")) return;
  const res = await getwxOpenId({ code, appId: cfg.wxAppId });
  this.openId = res.openId;
  localStorage.set("openId", res.openId);
}
// router.afterEach(() => {});

export default router;
