import Vue from "vue";
import Router from "vue-router";
import { QUESTION_API } from "@/constants/constants.js";
import Home from "../modules/portal/views/home/Home.vue";
import portalRoutes from "../modules/portal/routes/routes";
import {
  menuRoutes as qmenuRoutes,
  otherRoutes as qotherRoutes,
} from "../modules/questions/routes/routes";
import {
  menuRoutes as cmenuRoutes,
  otherRoutes as cotherRoutes,
} from "../modules/card/router";
import {
  menuRoutes as pmenuRoutes,
  otherRoutes as potherRoutes,
} from "../modules/paper-export/router";

// ignore NavigationDuplicated. https://github.com/vuejs/vue-router/issues/2881
// const originalPush = Router.prototype.push;
// Router.prototype.push = function push(location, onResolve, onReject) {
//   if (onResolve || onReject)
//     return originalPush.call(this, location, onResolve, onReject);
//   try {
//     return originalPush.call(this, location).catch((err) => err);
//   } catch (error) {
//     console.log(error);
//   }
// };
// end ignore

Vue.use(Router);

let router = new Router({
  mode: "history",
  base: "/admin",
  routes: [
    {
      path: "/home", //首页
      meta: { auth: false },
      component: Home,
      children: [...qmenuRoutes, ...cmenuRoutes, ...pmenuRoutes],
    },
    ...qotherRoutes,
    ...cotherRoutes,
    ...potherRoutes,
    ...portalRoutes,
  ],
});

router.beforeEach((to, from, next) => {
  if (to.path) {
    window._hmt.push(["_trackPageview", "/admin" + to.fullPath]);
  }

  if (to.path.includes("/preview_paper/")) {
    next();
    return;
  }
  if (!to.meta.privilegeCodes) {
    next();
  } else {
    let params = new URLSearchParams();
    params.append("privilegeCodes", to.meta.privilegeCodes);
    Vue.prototype.$httpWithMsg
      .post(QUESTION_API + "/rolePrivilege/checkPrivileges?" + params)
      .then((response) => {
        if (Object.values(response.data).includes(true)) {
          next();
        } else {
          Vue.prototype.$alert("没有权限访问！", "提示");
          next(false);
        }
      });
  }
});

export default router;
