<template>
  <div class="panocon">
    <div id="pano"></div>
    <ifr v-if="store.currentScene.type != 'pano'" :src="fdkk_link" frameborder="0"></ifr>
    <template v-if="loadFinish">
      <mblist v-if="isMobile" />
      <list v-else />
    </template>
</div>
</template>

<script setup>




import { ref, onMounted, computed, watch, onUnmounted, nextTick } from "vue";
import list from "./list.vue";
import mblist from "./mblist.vue";
import ifr from "./ifr.vue";

import Tags from "@/utils/Tag";
import Scene from "@/utils/Scene";
import emitter from "@/mitt/index";
import { useRouter, useRoute } from "vue-router";
import browser from '@/utils/browser'

import appStore from '@/store/index';
import { scene,order } from "@/data";

const store = appStore();
const isMobile = computed(() => browser.isMobile())

const loadFinish = ref(false)

const route = useRoute();

let number = 'WK1597972789485113344'

let gdBgm = new Audio();

gdBgm.src = ''


const fdkk_link = computed(() => {
  let url = ''

  if (store.currentScene.type == '4dkk') {
    url = browser.isMobile() ?
      `https://www.4dkankan.com/embed.html?from=mingyuan&m=${store.currentScene.sceneCode}`
      : `https://www.4dkankan.com/spc.html?m=${store.currentScene.sceneCode}`
  }
  else if (store.currentScene.type == 'oldfdkk') {
    url = `https://www.4dkankan.com/spc.html?m=${store.currentScene.sceneCode}`
  }
  else if (store.currentScene.type == 'bigscene') {
    url = `https://www.4dmodel.com/SuperTwo/index.html?m=${store.currentScene.sceneCode}`
  }
  else {
    url = ``
  }

  return url
})


const loadScene = (currentScene) => {
  if (window.krpanoDom) {
    let { sceneCode, initVisual, someData } = currentScene;
    if (window.krpanoDom.get('xml.scene').toLowerCase() == `scene_${sceneCode}`.toLowerCase()) {
      return
    }

    window.krpanoDom.call(`skin_loadscene('scene_${sceneCode}',${initVisual ? initVisual.vlookat : '0'},${initVisual ? initVisual.hlookat : '0'})`);
    if (someData && someData.hotspots && someData.hotspots.length > 0) {
      window.__sdk.Tags.initHotspot(someData.hotspots, false);
    }
  }
};



const updateListPosi = () => {

  let catalog = store.metadata.catalogs.find((item) => item.id == store.currentScene.category);
  // 查询初始场景的所在1级分组
  store.metadata.catalogRoot.forEach((item) => {
    let temp = item.children && item.children.find((sub) => sub == catalog.id);
    if (temp) {
      store.setCurrentCatalogRoot(item);
      return;
    }
  });
  // 查询初始场景的所在2级分组
  store.setCurrentSecondary(catalog);
}

store.$subscribe((mutation, state) => {
  if (state.currentScene) {
    nextTick(() => {
      loadScene(state.currentScene);
    });
  }
})

onUnmounted(() => {
  removepano("#pano");
}),

  onMounted(() => {
    window.krpanoDom = null
    $.ajax({
      method: 'get',
      url: `${process.env.VUE_APP_CDN}/720yun_fd_manage/${number}/someData.json?_=${Math.random()}`,
      dataType: 'json',
      success(data) {
        store.metadata = data
        store.list = (scene.concat(data.scenes)).sort((a,b)=>{
          return order.indexOf(a.sceneTitle) - order.indexOf(b.sceneTitle)
        })

        let firstScene = store.list.find((item) => item.sceneCode == route.params.id);
        store.currentScene = firstScene || data.scenes[0]

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

          if (item.children) {
            item.children.some((sub) => {
              flag = store.list.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 == store.currentScene.category);

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

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

        loadFinish.value = true
        window.onPanoReady = () => {
          if (!window.krpanoDom) {
            window.krpanoDom = document.getElementById("krpanoSWFObject");
            let app = {
              krpanoDom: window.krpanoDom
            }
            window.__sdk = {
              Tags: '',
              Scene
            }
            window.__sdk.Tags = new Tags(app)
            window.__sdk.Scene = new Scene(app)
            let { someData } = store.currentScene
            window.__sdk.Scene.on("sceneReady", (data) => {
              if (someData && someData.hotspots && someData.hotspots.length > 0) {
                window.__sdk.Tags.initHotspot(someData.hotspots, false);
              }
            })
            window.__sdk.Tags.on("clickHotspot", (data) => {
              let { id } = data;
              let tt = store.currentScene.someData.hotspots.find((item) => item.name == id);
              if (tt.hotspotType == 'scene') {
                store.currentScene = store.list.find(item => item.id == tt.secne.id)
                // store.commit("scene/setCurrentScene", scenesList.value.find(item => item.id == tt.secne.id));
                updateListPosi()
              }
            });
          }
        };

        window.onRemovepano = () => {
          console.log('result:onRemovepano');
        }

        let settings = {
          "events[skin_events].onloadcomplete": "js(window.onPanoReady());",
          "events[skin_events].onremovepano": "js(window.onRemovepano());",

        };
        removepano("#pano");
        $("#pano").empty();

        embedpano({
          // xml: `showviewer/lib/krpano/tour.xml?rnd=${Math.random()}`,
          xml: `${process.env.VUE_APP_CDN}/720yun_fd_manage/${number}/tour.xml?rnd=${Math.random()}`,
          swf: "%HTMLPATH%/resource/js/lib/krpano/tour.swf" + `?rnd=${Math.random()}`,
          target: "pano",
          html5: "auto",
          mobilescale: 1,
          vars: {
            startscene: "scene_" + store.currentScene.sceneCode,
            "view.vlookat": store.currentScene.initVisual ? store.currentScene.initVisual.vlookat : 0,
            "view.hlookat": store.currentScene.initVisual ? store.currentScene.initVisual.hlookat : 0,
            "skin_settings.littleplanetintro": 1,
            "autorotate.enabled": true,
            ...settings
          },
        });


      },
      error() {

      }   //请求失败后的回调函数
    })
  })


</script>

<style lang="scss" scoped>
.panocon {
  width: 100%;
  height: 100%;

  #pano {
    width: 100%;
    height: 100%;
  }
}
</style>