<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 } from "vue";
import { useStore } from "vuex";
import { useApp, getApp } from "@/app";
import Fdkk from "../Fdkk";
import { getFdkkInfo } from "@/apis";
import { useMusicPlayer, useSoundPlayer } from "@/utils/sound";
import browser from "@/utils/browser";
import config from "@/utils/config";

//背景音乐
const musicPlayer = useMusicPlayer();

//解说音乐
const soundPlayer = useSoundPlayer();

const store = useStore();
const isMobile = computed(() => browser.isMobile());
const lang = computed(() => config.lang);

const currentScene = computed(() => store.getters["scene/currentScene"]);
const scenesList = computed(() => store.getters["scene/list"]);
const metadata = computed(() => store.getters["scene/metadata"]);
const hotspots = computed(() => store.getters["tags/allTags"]);

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

const hadGetInfo = ref(false);

const loadScene = async (currentScene) => {
  let app = await getApp();
  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", "");
        useMusicPlayer.player.watchPlay(true);
        if (isMobile.value) {
          console.log(
            useMusicPlayer.player.isPlay,
            "useMusicPlayer.player.isPlay"
          );
          if (useMusicPlayer.player.isPlay) {
            setTimeout(() => {
              musicPlayer.play();
            }, 50);
          }
        }
      }

      nextTick(() => {
        loadScene(newVal);
        console.log(newVal, "newVal");
      });
    } else {
      getFdkkInfo({ num: newVal.sceneCode }).then((data) => {
        hadGetInfo.value = true;
        if (data.data.isUpgrade != void 0) {
          store.commit(
            "scene/setFdkkCurrentVersion",
            data.data.isUpgrade !== 0 ? "v4" : "v3"
          );

          // v3
          if (data.data.isUpgrade === 0) {
            musicPlayer.pauseFromOther = true;
            if (!browser.isMobile()) {
              musicPlayer.pause();
            } else {
              let flag =
                data.data.bgMusic &&
                data.data.bgMusic != "0" &&
                data.data.bgMusic != "noMusic";
              store.commit("fdkk/setV3FdkkBGM", flag);
              // 该v3场景有背景音乐
              if (flag) {
                musicPlayer.pause();
              }
              // console.log(data.data.bgMusic && data.data.bgMusic != '0' && data.data.bgMusic != 'noMusic','==========');
            }
          }
        }

        // else{
        //   useMusicPlayer.player.watchPlay(true)
        // }

        //上一个场景如果是四维看看场景且当前场景是v4
        // if (oldVal.type == '4dkk' && data.data.isUpgrade !== 0) {
        //   store.commit('fdkk/setFdkkBGM', '')
        //   musicPlayer.pause()
        //   useMusicPlayer.player.watchPlay(true)
        // }
      });
    }
  },
  {
    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(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", "");
        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 == "video"
          ) {
            store.commit("functions/setPauseFrom", currentPlaying.value);
            musicPlayer.pause();
            soundPlayer.pause();
          }
        }
      }
    }
  });
});
</script>

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

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