<template>
  <template v-if="workEnable">
    <LoadingLogo />
    <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 { debounce } from "lodash-es";

const _ = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ {
  constructor(callback) {
    callback = debounce(callback, 100);
    super(callback);
  }
};

import Pano from "@/components/Pano";
import Tags from "@/components/assembly/Tags";
import Password from "@/components/assembly/Password";
import Share from "@/components/assembly/Share";
import Error from "@/components/assembly/Error";
import TitieSlide from "@/components/assembly/titieSlide";

import UiGather from "@/components/UIGather/";

import LoadingLogo from "@/components/assembly/Loading";
import Opening from "@/components/assembly/Opening";
import { createApp } from "@/app";
import { Dialog } from "@/global_components";

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

const store = useStore();
const show = ref(false);
const workEnable = ref(true);
const coverInfo = ref({});
const hasPasswordLock = ref(false);

const lang = getLocale();

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 hotspotTypeList = computed(() => store.getters["tags/hotspotTypeList"]);
const hotspotIconTypeList = computed(() => store.getters["tags/hotspotIconTypeList"]);
const dataType = computed(() => store.getters["tags/dataType"]);
const hotspots = computed(() => store.getters["tags/hotspots"]);

const isShowOpeningAnimation = ref(0);

onMounted(async () => {
  if (browser.isMobile()) {
    window.location.href = window.location.href.replace("show.html", "showMobile.html");
    return;
  }

  const idRes = await exchangeId({
    id: config.projectNum,
  });
  const { id, num, calcStatus } = idRes.data;
  config.projectNum = id;

  if (calcStatus === 0) {
    Dialog.alert({
      title: t("common.tips"),
      content: t("common.calcing"),
      okText: t("common.confirm"),
    });
    return;
  }

  let res = await checkWork();

  if (!res.data) {
    workEnable.value = res.data;
    return;
  }
  // getWorkInfo().then((res) => {
  //   console.error(res);
  // });
  // getPanoInfo().then(async (data) => {
  getWorkInfo().then(async (res) => {
    let data = res.data;
    let { workOpeningAnimation, work, navigationTrees, workVisualAngleList, workCustomMaskList, workHotList } = data;

    store.commit("tags/setData", { hotspots: workHotList });
    isShowOpeningAnimation.value = workOpeningAnimation && workOpeningAnimation?.isShowOpeningAnimation ? Number(workOpeningAnimation?.isShowOpeningAnimation) : 0;
    //TODO 兼容1.2.0或以下数据
    if (workOpeningAnimation && !("isShowOpeningAnimation" in workOpeningAnimation) && "openingAnimationType" in workOpeningAnimation && workOpeningAnimation.openingAnimationType.length > 0) {
      console.log("小行星没有开关,但有openingAnimationType强制开启");
      isShowOpeningAnimation.value = 1;
    }
    let scenes = [];
    navigationTrees.forEach((item) => {
      item.children.forEach((s_item) => {
        if (s_item.type != "group") {
          scenes.push(s_item);
        }
        s_item.children.forEach((t_item) => {
          if (t_item.type != "group") {
            scenes.push(t_item);
          }
        });
      });
    });
    store.commit("scene/setScenes", scenes);
    store.commit("scene/setPassword", work.password === "" ? false : work.password);
    if (work.password.length > 0) {
      hasPasswordLock.value = true;
    }
    store.commit("scene/setMetaData", data);
    // document.title = data.name || t("common.no_title");

    let firstScene = "";
    if (config.sceneNum) {
      firstScene = scenes.find((item) => item.sceneCode == config.sceneNum);
    } else if (data.firstScene) {
      firstScene = scenes.find((item) => item.sceneCode == data.firstScene.sceneCode);
    }
    // 所有audio入口

    const currentSceneData = firstScene || scenes[0];

    store.dispatch("audio/initNormalBGM", data.workBackgroundMusic ? data.workBackgroundMusic.ossPath : "");
    store.commit("scene/setCurrentScene", currentSceneData);
    console.error(currentSceneData);
    let activeScene = null;
    navigationTrees.forEach((item, index) => {
      activeScene = item.children.find((pano) => pano.id == currentSceneData.id);

      if (activeScene) {
        store.commit("scene/setCurrentScenesList", item.children);
        store.commit("scene/setData", { currentSecondId: null, currentRootId: item.id });
        // throw new Error("LoopTerminated");
      }
      item = item.children.forEach((s_item, s_index) => {
        activeScene = s_item.children.find((pano) => pano.id == currentSceneData.id);

        if (activeScene) {
          store.commit("scene/setCurrentScenesList", s_item.children);
          store.commit("scene/setData", { currentSecondId: s_item.id, currentRootId: item.id });
          // throw new Error("LoopTerminated");
        }
        s_item = s_item.children.forEach((t_item, t_index) => {
          activeScene = t_item.children.find((pano) => pano.id == currentSceneData.id);

          if (activeScene) {
            store.commit("scene/setCurrentScenesList", s_item.children);
            store.commit("scene/setData", { currentSecondId: s_item.id, currentRootId: item.id });
            // throw new Error("LoopTerminated");
          }
        });
      });
    });

    // 过滤空分组
    // 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", !!work.isAuto);

    show.value = true;

    let isHavePano = scenes.some((item) => item.type == "pano");

    let currnetVisual = workVisualAngleList.find((item) => item.navigationId == currentScene.value.id);
    // if (!currnetVisual) {
    //   currnetVisual = {
    //     hlookat: 0,
    //     icon: currentScene.value.icon,
    //     vlookat: 0,
    //     vlookatmax: 90,
    //     vlookatmin: -90,
    //     navigationId: currentScene.value.id,
    //   };
    // }
    // store.commit("scene/setCurrnetVisual", currnetVisual);
    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.org_vlookat": currnetVisual ? currnetVisual.vlookat : 0,
        "view.org_hlookat": currnetVisual ? currnetVisual.hlookat : 0,
        "view.vlookat": currnetVisual ? currnetVisual.vlookat : 0,
        "view.hlookat": currnetVisual ? currnetVisual.hlookat : 0,
        "autorotate.enabled": !!work.isAuto,
        "skin_settings.littleplanetintro": typeof workOpeningAnimation && workOpeningAnimation?.openingAnimationType === "number" ? workOpeningAnimation?.openingAnimationType : 1,
        "skin_settings.lptswitch": unref(isShowOpeningAnimation),
      },
      passQueryParameters: true,
    });
    if (app) {
      coverInfo.value = data.workCoverType || {};
      app.Scene.lock();
      //如果不需要开场封面就直接渲染
      if (!coverInfo.value?.isShowCover) {
        app.render();
      }

      if (isHavePano) {
        console.error("isHavePano", hotspots.value);
        app.Scene.on("sceneReady", () => {
          if (app.krpanoDom) {
            let customMask = workCustomMaskList.find((item) => item.navigationId == currentScene.value.id);
            // const { sky, earth } = currentScene.value.customMask;
            const { sky, earth } = customMask.data;
            handleMasksUpdate(sky, earth, app);
            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;
          // }
          console.error("sceneReady", hotspots.value);
          let currentHotspots = hotspots.value.filter((item) => item.navigationId == currentScene.value.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);
          }
          // app.Tags.initHotspot(hotspots, false);
          handleVisualLimit(app, currentScene.value, workVisualAngleList);
        });
      }

      const { initDefaultAudio } = useAudio();
      initDefaultAudio();
    }
  });
});
const handlePass = () => {
  hasPasswordLock.value = false;
};
const handleVisualLimit = (app, currentScene, workVisualAngleList) => {
  let currnetVisual = workVisualAngleList.find((item) => item.navigationId == currentScene.id);
  // const { vlookatmax, vlookatmin } = currentScene.initVisual;
  // console.log('initVisual',currentScene.initVisual)
  console.error("视角", currnetVisual.vlookatmin, currnetVisual.vlookatmax);

  app.krpanoDom.set(`view.limitview`, "lookat");
  app.krpanoDom.set(`view.vlookatmin`, currnetVisual.vlookatmin || -90);
  app.krpanoDom.set(`view.vlookatmax`, currnetVisual.vlookatmax || 90);
};

const handleMasksUpdate = (skyMask, earthMask, app) => {
  const lang = getLocale();
  let defaultMask = `%SWFPATH%/skin/masking_${lang}.png`;
  console.log("defaultMask", defaultMask);
  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.5);
      }
    }
  }
  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);
    }
    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.5);
      }
    }
  }
};
</script>

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