<template>
  <div id="pano" v-show="currentScene.type != '4dkk'" @click="handlePanoClick" @touchstart="handlePanoClick"></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, getLocale } from "@/i18n";
const { t } = useI18n({ useScope: "global" });
const store = useStore();
const isMobile = computed(() => browser.isMobile());
const lang = computed(() => config.lang);
const hotspots = computed(() => store.getters["tags/hotspots"]);
const currentScene = computed(() => store.getters["scene/currentScene"]);
const vrStatus = computed(() => store.getters["functions/vrStatus"]);
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).id);

  if (app.krpanoDom) {
    let { sceneCode, initVisual, someData } = currentScene;
    let currnetVisual = metadata.value.workVisualAngleList.find((item) => {
      return item.navigationId == currentScene.id;
    });
    app.krpanoDom.call(`skin_loadscene('scene_${sceneCode}',${currnetVisual ? currnetVisual.vlookat : "0"},${currnetVisual ? currnetVisual.hlookat : "0"})`);

    if (hotspots.value.length) {
      let currentHotspots = hotspots.value.filter((item) => item.navigationId == currentScene.id);

      if (currentHotspots.length) {
        // hotspots.forEach((item, index) => {
        //   if (item.content) {
        //     let hotSpotType = item.hotspotType;
        //     for (let key in hotspotTypeList.value) {
        //       let data = hotspotTypeList.value[key];
        //       if (key == hotSpotType && item.content[data]) {
        //         item[data] = item.content[data];
        //       } else if (data) {
        //         item[data] = dataType.value[data];
        //       }
        //     }

        //     let hotSpotIconType = item.hotspotIconType;
        //     for (let key in hotspotIconTypeList.value) {
        //       let data = hotspotIconTypeList.value[key];
        //       if (key == hotSpotIconType && item.content[data]) {
        //         item[data] = item.content[data];
        //       } else if (data) {
        //         item[data] = dataType.value[data];
        //       }
        //     }
        //   }
        // });
        app.Tags.initHotspot(currentHotspots, false);
      }
    }

    // const { vlookat, hlookat, vlookatmax, vlookatmin } =
    //   currentScene.initVisual;
    app.krpanoDom.set(`view.limitview`, "lookat");
    app.krpanoDom.set(`view.vlookat`, currnetVisual ? currnetVisual.vlookat : 0);
    app.krpanoDom.set(`view.hlookat`, currnetVisual ? currnetVisual.hlookat : 0);
    app.krpanoDom.set(`view.vlookatmin`, currnetVisual ? currnetVisual.vlookatmin : -90);
    app.krpanoDom.set(`view.vlookatmax`, currnetVisual ? currnetVisual.vlookatmax : 90);

    // console.log("customMasks", currentScene.customMask);
    // const { earth, sky } = currentScene.customMask;
    let customMask = metadata.value.workCustomMaskList.find((item) => item.navigationId == currentScene.id);

    if (!customMask) {
      customMask = {
        data: {
          earth: {
            antidistorted: true,
            fodderId: null,
            icon: "",
            isShow: false,
            navigationId: currentScene.id,
            scale: 1,
            type: "earth",
          },
          sky: {
            antidistorted: true,
            fodderId: null,
            icon: "",
            isShow: true,
            navigationId: currentScene.id,
            scale: 1,
            type: "sky",
          },
        },
        navigationId: currentScene.id,
      };
    }
    // const { sky, earth } = currentScene.value.customMask;
    const { sky, earth } = customMask.data;
    handleMasksUpdate(sky, earth, app);
  }
};

watch(
  currentScene,
  (newVal, oldVal) => {
    console.log(lang.value);
    const vlog = browser.getURLParam("vlog");
    history.replaceState(
      null,
      null,
      ""
        .concat(window.location.pathname, "?")
        .concat(`id=${metadata.value.workId}&vr=${newVal.sceneCode}&lang=${lang.value}`)
        .concat(`${vlog ? "&vlog=" + vlog : ""} `)
    );

    //默认版本是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, currentScene: currentScene.value }).then(async (data) => {
        hadGetInfo.value = true;

        let isVersion = 0;
        if (config.isOfflineMode) {
          if (unref(currentScene).version && unref(currentScene).version == "V4") {
            isVersion = isUpgradeAdapter(data.isUpgrade);
          } else {
            isVersion = isUpgradeAdapter(data && data.isUpgrade ? data.data.isUpgrade : 0);
          }
        } else {
          isVersion = isUpgradeAdapter(data.data && data.data.isUpgrade ? data.data.isUpgrade : 0);
        }
        console.log("当前-version", isVersion);
        store.dispatch("audio/setLock", true);
        store.commit("scene/setFdkkCurrentVersion", isVersion);
        // v3
        if (isVersion === "V3") {
          let flag = "";
          // 离线包模式，接口返回的是data，没有嵌套.data
          if (config.isOfflineMode) {
            flag = data.bgMusic && data.bgMusic != "0" && data.bgMusic != "Cheerful" && data.bgMusic != "noMusic";
          } else {
            flag = data.data.bgMusic && data.data.bgMusic != "0" && data.data.bgMusic != "Cheerful" && 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());
    let hotspot = hotspots.value.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.scene.id)
          );
          // store.commit("scene/setCurrentScenesList", sceneList);
          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");
    }
  });
});

const handleMasksUpdate = (skyMask, earthMask, app) => {
  const lang = getLocale();
  let defaultMask = `%SWFPATH%/skin/masking_${lang}.png`;
  if (skyMask) {
    if ("isShow" in skyMask) {
      app.krpanoDom.set(`hotspot[peaklogo].visible`, Boolean(skyMask.isShow));
    }

    if (skyMask.icon) {
      app.krpanoDom.set(`hotspot[peaklogo].url`, skyMask.icon);
    } else {
      app.krpanoDom.set(`hotspot[peaklogo].url`, defaultMask);
    }
    if ("scale" in skyMask) {
      app.krpanoDom.set(`hotspot[peaklogo].scale`, skyMask.scale);
    }
    if ("antidistorted" in skyMask) {
      app.krpanoDom.set(`hotspot[peaklogo].distorted`, skyMask.antidistorted);
      if (!skyMask.antidistorted) {
        app.krpanoDom.set(`hotspot[peaklogo].scale`, skyMask.scale * 0.9);
      }
    }
  }
  if (earthMask) {
    if ("isShow" in earthMask) {
      app.krpanoDom.set(`hotspot[nadirlogo].visible`, Boolean(earthMask.isShow));
    }
    if (earthMask.icon) {
      app.krpanoDom.set(`hotspot[nadirlogo].url`, earthMask.icon);
    } else {
      app.krpanoDom.set(`hotspot[nadirlogo].url`, defaultMask);
    }
    if ("scale" in earthMask) {
      app.krpanoDom.set(`hotspot[nadirlogo].scale`, earthMask.scale);
    }
    if ("antidistorted" in earthMask) {
      app.krpanoDom.set(`hotspot[nadirlogo].distorted`, earthMask.antidistorted);
      if (!earthMask.antidistorted) {
        app.krpanoDom.set(`hotspot[nadirlogo].scale`, earthMask.scale * 0.9);
      }
    }
  }
};
const handlePanoClick = () => {
  store.commit("functions/setShowScenesList", false);
};
</script>

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

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