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);
};
VueRouter.prototype.replace = 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();
});

// 路由异常错误处理，尝试解析一个异步组件时发生错误，重新渲染目标页面
// router.onError(error => {
//   console.log("router error:", error.message);
//   const pattern = /Loading chunk (\d)+ failed/g;
//   const isChunkLoadFailed = error.message.match(pattern);
//   const targetPath = router.history.pending.fullPath;
//   if (isChunkLoadFailed) {
//     router.replace(targetPath);
//   }
// });

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) {
  const res = await getwxOpenId({ code, appId: cfg.wxAppId });
  if (localStorage.get("openId") && res.openId !== localStorage.get("openId")) {
    console.log("切换账号");
    localStorage.clear();
  }
  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;
