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";
import goodsList from "@/api/goodsList.mock";

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);
  setTitle(to.meta.title, to.path, to.query);
  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 });
  localStorage.set("openId", res.openId);
}

function setTitle(title, path, query) {
  if (path === "/goods/detail") {
    const goods = goodsList.find(v => v.id === query.id);
    title = goods.title;
  }
  document.title = title;
}

export default router;
