import Vue from "vue";
import Router from "vue-router";
import { PCMenu } from "../config/menu";
import { checkLogin, canEdit } from "@/api";
// getPanoInfo
import config from "../config";

import { $alert } from "@/components/shared/message";
import store from "../Store";

let vue = new Vue();

import { LoginDetector, OnlineDetector } from "@/utils/starter";
Vue.use(Router);

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

let routes = [];
PCMenu.forEach((item) => {
  routes.push({
    name: item.name,
    path: `${item.link}`,
    meta: {
      loading: null,
      loadScene: !item.hidescene,
    },
    component: () => import(`../views/${item.name}/index.vue`),
  });
});

LoginDetector.register(
  (detector) => new Promise((resolve) => detector.resolve(resolve))
);

OnlineDetector.register(
  (detector) => new Promise((resolve) => detector.resolve(resolve))
);

checkLogin().then((response) => {
  if (response.code == 0) {
    LoginDetector.valid();
    canEdit().then((response) => {
      let view = parseInt(config.isView);
      if (response.data) {
        store.commit("UpdateIsShowState", true);
      }

      if (view) {
        OnlineDetector.valid();
        vue.$bus.emit("canLoad", true);
        vue.$bus.emit("justview", true);
        Vue.prototype.$justview = true;
        return;
      }

      if (!response.data) {
        return $alert({
          content: "该VR不可编辑。",
        });
      } else {
        vue.$bus.emit("canLoad", true);
        vue.$bus.emit("justview", false);
        Vue.prototype.$justview = false;
        OnlineDetector.valid();
      }
    });
  }
});

const router = new Router({
  routes: routes,
});

router.beforeEach(async (to, from, next) => {
  await LoginDetector.listener();
  await OnlineDetector.listener();

  if (to.path == "/") {
    return next({ path: "/information" });
  }

  next();
});

export default router;
