import Vue from "vue";
import Router from "vue-router";
import store from "./store";
import { SYS_ADMIN_NAME } from "@/constants/enumerate";

import Home from "./views/Home.vue";
import HomePage from "./views/home-page/HomePage.vue";
import NotFound from "./views/404.vue";

import login from "./modules/login/router";
// module-example
import base from "./modules/base/router";
import exam from "./modules/exam/router";
import print from "./modules/print/router";
import stmms from "./modules/stmms/router";
import analysis from "./modules/analysis/router";
import mark from "./modules/mark/router";
import course from "./modules/course/router";
import target from "./modules/target/router";
import statistics from "./modules/statistics/router";
// card part
import card from "./modules/card/router";
// admin
import admin from "./modules/admin/router";
// tool
import tool from "../tools/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);

/*
history模式 nginx配置
location / {
  try_files $uri $uri/ /index.html;
}
*/

const router = new Router({
  mode: "history",
  routes: [
    {
      path: "/",
      name: "Index",
      redirect: { name: "Login" },
    },
    {
      path: "/home/:nextRouter?",
      name: "Home",
      component: Home,
      children: [
        {
          path: "/home-page",
          name: "HomePage",
          component: HomePage,
        },
        ...base,
        ...exam,
        ...print,
        ...stmms,
        ...analysis,
        ...mark,
        ...course,
        ...target,
        ...statistics,
      ],
    },
    { ...login },
    { ...admin },
    ...card,
    ...tool,
    {
      path: "*",
      name: "NotFound",
      component: NotFound,
      meta: {
        noRequire: true,
      },
    },
    // [lazy-loaded] route level code-splitting
    // {
    //   path: "/about",
    //   name: "about",
    //   // this generates a separate chunk (about.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () =>
    //     import(/* webpackChunkName: "about" */ "./views/About.vue")
    // }
  ],
});

function getRouteType(routeMatched) {
  const typeData = routeMatched.find(
    (item) => item.name === "Home" || item.name === "Admin"
  );
  return typeData ? typeData.name : null;
}

// route interceptor
const whiteRoutes = ["CardRulePreview"];
router.beforeEach(async (to, from, next) => {
  const token = Vue.ls.get("token");
  if (to.meta.noRequire) {
    next();
    return;
  }

  if (!token) {
    // 登录失效的处理
    const returnUrl = Vue.ls.get("returnUrl");
    if (returnUrl) {
      window.location.href = returnUrl;
      return;
    }

    Vue.ls.clear();
    const paramDomainCode = window.sessionStorage.getItem("paramDomainCode");
    const routeDomainCode = window.sessionStorage.getItem("routeDomainCode");
    if (paramDomainCode) {
      next({ name: "Login", query: { code: paramDomainCode } });
    } else if (routeDomainCode) {
      next({ name: "Login", params: { code: routeDomainCode } });
    } else {
      next({ name: "Login" });
    }
    return;
  }

  const fromType = getRouteType(from.matched);
  const toType = getRouteType(to.matched);
  // 只有超管才可访问Admin
  const isSuperAdmin =
    Vue.ls.get("user", { loginName: "" }).loginName === SYS_ADMIN_NAME;
  if (toType === "Admin" && !isSuperAdmin) {
    next({ name: "NotFound" });
    return;
  }

  if (!store.state.app.privileges.length || fromType !== toType) {
    if (toType === "Home") {
      await store.dispatch("app/updatePrivilegeMap", isSuperAdmin);
    } else if (toType === "Admin") {
      store.dispatch("app/updateAdminPrivilegeMap");
    } else {
      store.commit("app/initStore");
    }
  }

  // console.log(fromType, toType);
  // console.log(store.state.app.validRoutes);
  // console.log(to.name);

  if (
    !whiteRoutes.includes(to.name) &&
    !store.state.app.validRoutes.includes(to.name)
  ) {
    next({ name: "NotFound" });
    return;
  }

  const privilegeMap = store.state.app.privilegeMap;
  Vue.ls.set(
    "privilegeId",
    privilegeMap[to.name] ? privilegeMap[to.name][0] : ""
  );

  next();
});

export default router;
