<template>
  <LoadingLogo v-if="workEnable" />
  <template v-if="workEnable">
    <Opening
      :coverData="coverInfo"
      v-if="coverInfo.isShowCover && !hasPasswordLock"
    />
    <Password @pass="handlePass" />
    <Share />
    <div class="ui-view-layout" :class="{ show: show }">
      <Pano />
      <Tags />
      <UiGather />
      <TitieSlide />
    </div>
  </template>

  <Error v-else />
</template>

<script setup>
import Pano from "@/components/Pano";
import Tags from "@/components/assembly/MobileTags";
import Password from "@/components/assembly/Password";
import Share from "@/components/assembly/Share";
import Error from "@/components/assembly/Error";
import UiGather from "@/components/UIGather/mobile";
import TitieSlide from "@/components/assembly/titieSlide";
import Opening from "@/components/assembly/OpeningMobile";
import LoadingLogo from "@/components/assembly/Loading";
import { createApp } from "@/app";

import { ref, onMounted, computed, unref, watch, nextTick } from "vue";
import { getPanoInfo, checkWork } from "@/apis";
import { useStore } from "vuex";
import config from "@/utils/config";
import browser from "@/utils/browser";
import { useApp } from "@/app";
import { useI18n, getLocale } from "@/i18n";
const { t } = useI18n({ useScope: "global" });

const coverInfo = ref({});

const fixOpening = {
  小行星开场: 1,
  水平巡游开场: 2,
  小行星巡游开场: 3,
  水晶球开场: 4,
  小行星缩放开场: 5,
};

let noLittleIds = ['WK1656467989114929152','WK1656904911083814912','WK1656877437742497792']

const store = useStore();
const show = ref(false);
const workEnable = ref(true);
const lang = getLocale();
const hasPasswordLock = ref(false);

const currentScene = computed(() => store.getters["scene/currentScene"]);
const currentCatalogRoot = computed(
  () => store.getters["scene/currentCatalogRoot"]
);

const isAutoRotate = computed(() => store.getters["functions/isAutoRotate"]);

const earthMask = computed(() => store.getters["scene/earthMask"]);
const skyMask = computed(() => store.getters["scene/skyMask"]);
const isShowOpeningAnimation = ref(0);
onMounted(async () => {
  // if (!browser.isMobile()) {
  //   window.location.href = window.location.href.replace(
  //     "showMobile.html",
  //     "show.html"
  //   );
  //   return;
  // }
  let res = await checkWork();
  if (!res.data) {
    workEnable.value = res.data;
    return;
  }
  getPanoInfo().then(async (data) => {
    isShowOpeningAnimation.value = Number(data.isShowOpeningAnimation);
    store.commit("scene/setScenes", data.scenes);
    store.commit(
      "scene/setPassword",
      data.password === "" ? false : data.password
    );
    if (data.password.length > 0) {
      hasPasswordLock.value = true;
    }
    store.commit("scene/setMetaData", data);
    document.title = data.name || t("common.no_title");

    
    //所有热点
    let temphotspots = [];

    data.scenes.forEach(item=>{
      if (item.someData) {
        temphotspots = temphotspots.concat(typeof item.someData == "string"
          ? JSON.parse(item.someData).hotspots
          : item.someData.hotspots)
    }
    })

    store.commit("tags/setAllHotList", temphotspots);


    let firstScene = "";

    if (config.sceneNum) {
      console.log(config.sceneNum);
      firstScene = data.scenes.find(
        (item) => item.sceneCode == config.sceneNum
      );
    } else if (data.firstScene) {
      firstScene = data.scenes.find(
        (item) => item.sceneCode == data.firstScene.sceneCode
      );
    }

    store.commit("scene/setCurrentScene", firstScene || data.scenes[0]);

    // 过滤空分组
    let ttt = data.catalogRoot.filter((item) => {
      let flag = "";

      if (item.children) {
        item.children.some((sub) => {
          flag = data.scenes.some((son) => {
            // console.log(String(son.category).toLowerCase(), String(sub).toLowerCase());
            return (
              String(son.category).toLowerCase() == String(sub).toLowerCase()
            );
          });
          return flag;
        });
      }
      return flag;
    });

    data.catalogRoot = ttt;

    let catalog = data.catalogs.find(
      (item) => item.id == currentScene.value.category
    );

    // 查询初始场景的所在1级分组
    data.catalogRoot.forEach((item) => {
      let temp =
        item.children && item.children.find((sub) => sub == catalog.id);
      if (temp) {
        store.commit("scene/setCurrentCatalogRoot", item);
        return;
      }
    });

    // 查询初始场景的所在2级分组
    store.commit("scene/setCurrentSecondary", catalog);

    store.commit("functions/setAutoRotate", !!data.isAuto);

    show.value = true;

    let isHavePano = data.scenes.some((item) => item.type == "pano");
    document.body.setAttribute("is-mobile", true);

    const app = createApp({
      // xml: "%HTMLPATH%/static/template/tour.xml",
      xml: `${process.env.VUE_APP_CDN}/720yun_fd_manage/${
        config.projectNum
      }/tour.xml?rnd=${Math.random()}`,
      swf: "%HTMLPATH%/showviewer/lib/krpano/tour.swf",
      target: "pano",
      html5: "auto",
      mobilescale: 1,
      isHavePano,
      vars: {
        startscene: "scene_" + currentScene.value.sceneCode,
        "view.vlookat": currentScene.value.initVisual
          ? currentScene.value.initVisual.vlookat
          : 0,
        "view.hlookat": currentScene.value.initVisual
          ? currentScene.value.initVisual.hlookat
          : 0,

        "autorotate.enabled": !!data.isAuto,
        "skin_settings.littleplanetintro":
          fixOpening[data.openingAnimationType || "小行星开场"],
        // "skin_settings.lptswitch": unref(isShowOpeningAnimation),
        "skin_settings.lptswitch": !noLittleIds.includes(config.projectNum),
      },
      passQueryParameters: true,
    });
    coverInfo.value = data.coverInfo || {};
    app.Scene.lock();
    //如果不需要开场封面就直接渲染
    if (!coverInfo.value?.isShowCover) {
      app.render();
    }

    if (isHavePano) {
      app.Scene.on("sceneReady", () => {
        if (app.krpanoDom) {
          let defaultMask = `%SWFPATH%/skin/masking_${lang}.png`;
          if (noLittleIds.includes(config.projectNum)) {
            app.krpanoDom.set(`view.vlookatmin`, 0);
            app.krpanoDom.set(`view.vlookatmax`, 0);
            app.krpanoDom.set(`view.limitview`, 'lookat');
            app.krpanoDom.set(`view.fovmax`, 140);
          }
 
          if (earthMask.value) {
            app.krpanoDom.set(`hotspot[nadirlogo].url`, defaultMask);
            app.krpanoDom.set(
              `hotspot[nadirlogo].visible`,
              Boolean(earthMask.value.isShow)
            );


            if (earthMask.value.icon) {
              app.krpanoDom.set(`hotspot[nadirlogo].url`, earthMask.value.icon);
            }
          }

          if (skyMask.value) {
            app.krpanoDom.set(`hotspot[peaklogo].url`, defaultMask);
            app.krpanoDom.set(
              `hotspot[peaklogo].visible`,
              Boolean(skyMask.value.isShow)
            );
            if (skyMask.value.icon) {
              app.krpanoDom.set(`hotspot[peaklogo].url`, skyMask.value.icon);
            }
          }

          app.krpanoDom.set(
            `layer[webvr_exitbutton].html`,
            t("common.exit_vr")
          );
        }

        let hotspots = [];
        if (currentScene.value.someData) {
          hotspots =
            typeof currentScene.value.someData == "string"
              ? JSON.parse(currentScene.value.someData).hotspots
              : currentScene.value.someData.hotspots;
        }
        app.Tags.initHotspot(hotspots, false);
      });
    }
  });
});
const handlePass = () => {
  hasPasswordLock.value = false;
};
</script>

<style lang="scss" scoped>
.ui-view-layout {
  position: relative;
}
</style>
