<template>
  <div id="pano" v-show="currentScene.type != '4dkk'"></div>
  <Fdkk v-if="currentScene.type == '4dkk' && hadGetInfo" />
</template>

<script setup>
import {
  ref,
  onMounted,
  computed,
  watch,
  nextTick,
  unref,
  watchEffect,
} from "vue";
import { useStore } from "vuex";
import { useApp, getApp } from "@/app";
import Fdkk from "../Fdkk";
import { getFdkkInfo } from "@/apis";
import { isUpgradeAdapter } from "@/utils/fixVersion";
import browser from "@/utils/browser";
import config from "@/utils/config";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
const store = useStore();
const isMobile = computed(() => browser.isMobile());
const lang = computed(() => config.lang);

const currentScene = computed(() => store.getters["scene/currentScene"]);
const isHasNormalBGM = computed(() => store.getters["audio/isHasNormalBGM"]);
const scenesList = computed(() => store.getters["scene/list"]);
const metadata = computed(() => store.getters["scene/metadata"]);
const currentPlaying = computed(
  () => store.getters["functions/currentPlaying"]
);

const hadGetInfo = ref(false);

const loadScene = async (currentScene) => {
  let app = await getApp();
  // await new Promise((r) => setTimeout(r, 10000));
  console.error("loadScene", unref(currentScene));
  if (app.krpanoDom) {
    let { sceneCode, initVisual, someData } = currentScene;
    app.krpanoDom.call(
      `skin_loadscene('scene_${sceneCode}',${
        initVisual ? initVisual.vlookat : "0"
      },${initVisual ? initVisual.hlookat : "0"})`
    );
    console.log(sceneCode, someData);
    if (someData && someData.hotspots && someData.hotspots.length > 0) {
      app.Tags.initHotspot(someData.hotspots, false);
    }
  }
};

watch(
  currentScene,
  (newVal, oldVal) => {
    console.log(lang.value);

    history.replaceState(
      null,
      null,
      ""
        .concat(window.location.pathname, "?")
        .concat(
          `id=${metadata.value.id}&vr=${newVal.sceneCode}&lang=${lang.value}`
        )
    );

    //默认版本是v4
    store.commit("scene/setFdkkCurrentVersion", "V4");
    hadGetInfo.value = false;
    //恢复默认状态
    // store.commit("fdkk/setV3FdkkBGM", "");
    // store.commit("fdkk/setV3BGMStatus", "");
    if (newVal.type == "pano") {
      //如果当前背景音乐是v4则重置
      // console.log(store.getters["fdkk/fdkkBGM"]);
      // if (store.getters["fdkk/fdkkBGM"]) {
      //   store.commit("fdkk/setFdkkBGM", "");
      // }
      store.dispatch("audio/setLock", false);
      nextTick(() => {
        loadScene(newVal);
        console.log(newVal, "newVal");
      });
    } else {
      getFdkkInfo({ num: newVal.sceneCode }).then(async (data) => {
        hadGetInfo.value = true;

        const isVersion = isUpgradeAdapter(data.data.isUpgrade);
        console.log("当前-version", isVersion);
        store.dispatch("audio/setLock", true);
        store.commit("scene/setFdkkCurrentVersion", isVersion);
        // v3
        if (isVersion === "V3") {
          let flag =
            data.data.bgMusic &&
            data.data.bgMusic != "0" &&
            data.data.bgMusic != "noMusic";
          console.error("是否有V3--BGM", flag);
          store.commit("fdkk/setV3FdkkBGM", flag);
          store.dispatch("audio/initV3BGM", flag);
          if (!flag) {
            if (unref(isHasNormalBGM)) {
              console.log("不存在V3并存在普通bgm");
              // store.dispatch("audio/playBGM", 0);
              store.dispatch("audio/pauseBGM");
            }
          } else {
            setTimeout(() => store.dispatch("audio/pauseBGM"), 100);
          }
        }
      });
    }
  },
  {
    deep: true,
  }
);

const updateListPosi = () => {
  let catalog = metadata.value.catalogs.find(
    (item) => item.id == currentScene.value.category
  );

  // 查询初始场景的所在1级分组
  metadata.value.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);
};

useApp().then((app) => {
  app.Tags.on("clickHotspot", (data) => {
    let { id } = data;
    let hotspot = unref(currentScene).someData.hotspots.find(
      (item) => item.name.toLowerCase() === id.toLowerCase()
    );

    if (hotspot) {
      const isNotclickType = ["tag"];
      if (!isNotclickType.includes(hotspot.hotspotType)) {
        console.log("click", hotspot);
        // store.commit("functions/setPauseFrom", "");
        // store.dispatch("audio/pauseBGM");
        if (hotspot.hotspotType == "phone" && unref(isMobile)) {
          window.open(`tel:${hotspot.phoneInfo.phone}`, "_self");
          return;
        }
        if (hotspot.hotspotType == "scene") {
          store.commit(
            "scene/setCurrentScene",
            scenesList.value.find((item) => item.id == hotspot.secne.id)
          );
          updateListPosi();
        } else if (hotspot.hotspotType == "link") {
          if (hotspot.linkOpenType == "newTab") {
            window.open(hotspot.hyperlink, "_blank");
          } else {
            store.commit("tags/setCurrentTag", hotspot);
          }
        } else {
          store.commit("tags/setCurrentTag", hotspot);
          if (
            hotspot.hotspotType == "audio" ||
            hotspot.hotspotType == "imageText" ||
            hotspot.hotspotType == "video"
          ) {
            store.dispatch("audio/pauseBGM");
            // store.commit("functions/setPauseFrom", currentPlaying.value);
          }
        }
      }
    }
  });
});

onMounted(() => {
  watchEffect(() => {
    if (metadata.value.name === "") {
      document.title = t("common.no_title");
    }
  });
});
</script>

<style lang="scss" scoped>
#pano {
  width: 100%;
  height: 100%;
}

.novisible {
  opacity: 0;
  visibility: hidden;
}
</style>
