<template>
  <ul class="control-pano" :style="injectStyle">

    <li @click="onIsAutoRotate">
      <img :src="require(`@/assets/images/js_icon/${isAutoRotate ? 'auto_active.png' : 'auto.png'}`)"
        alt="" />
        <div>自动漫游</div>
    </li>

    <li @click="onIsShowList" v-if="!((metadata.catalogRoot && metadata.catalogRoot.length == 1) && scenes.length == 1 && secondaryList.length == 1)">
      <img :src="require(`@/assets/images/js_icon/${isShowScenesList ? 'daolan_active.png' : 'daolan.png'}`)"
        alt="" />
        <div>导览列表</div>
    </li>

    <li @click="onIsShowHotspotList">
      <img :src="require(`@/assets/images/js_icon/${isShowHotspotList ? 'hotspot_active.png' : 'hotspot.png'}`)"
        alt="" />
        <div>热点列表</div>
    </li>

    
    <li @click="onVR"
     v-if="currentScene.type == 'pano' || (fdkkCurrentVersion == 'v3') || (currentScene.type == '4dkk' && (fdkkmetadata.controls && fdkkmetadata.controls.showVR))">
      <img :src="require(`@/assets/images/js_icon/${isShowHotspotList ? 'vr_active.png' : 'vr.png'}`)"
        alt="" />
        <div>VR可视</div>
    </li>

  </ul>

  <teleport to='body'>
    <introduce v-if="showIntroduce" />
    <telephone v-if="showTelephone" />
    <clink v-if="showLink" />
    <hotspotList v-if="isShowHotspotList" />
    <div class="musicfix" v-if="metadata.backgroundMusic && metadata.backgroundMusic.id" @click="onIsBGM">
      <img :src="require(`@/assets/images/js_icon/${showMusicPlaying ? 'music.png' : 'music_active.png'}`)" alt="" />
    </div>
  </teleport>
</template>

<script setup>
import { ref, watch, computed, onMounted, defineProps, nextTick } from "vue";
import { useStore } from "vuex";
import { useApp } from "@/app";

import introduce from "./control/text";
import telephone from "./control/telephone";
import clink from "./control/link";
import hotspotList from "./control/hotspotList";
import { useMusicPlayer,useSoundPlayer } from '@/utils/sound'

const $iosGrantedTips = (cb) => {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf("like mac os x") > 0) {
    var reg = /os [\d._]*/gi;
    var verinfo = ua.match(reg);
    var version = (verinfo + "")
      .replace(/[^0-9|_.]/gi, "")
      .replace(/_/gi, ".");
    var arr = version.split(".");
    console.log(arr);

    if (arr[0] > 12 && arr[1] >= 0) {
      //对13.3以后的版本处理,包括13.3,
      DeviceMotionEvent && DeviceMotionEvent.requestPermission()
        .then((permissionState) => {
          if (permissionState == "granted") {
            cb({
              msg: '授权成功',
              code: 1
            })
            this.reload();
          } else {
            cb({
              msg: '授权失败',
              code: 0
            })
          }
        })
    }
    else {
      //13.3以前的版本
      cb({
        msg: '无需授权，直接成功',
        code: 1
      })
    }
  } else {
    cb({
      msg: '无需授权，直接成功',
      code: 1
    })
  }
}


const props = defineProps(['injectStyle'])

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

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

const store = useStore();

const metadata = computed(() => store.getters["scene/metadata"]);


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

const showTours = computed(() => store.getters["fdkk/isShowToursList"]);
const scenes = computed(() => store.getters["scene/list"]);
const secondaryList = computed(() => store.getters["scene/secondaryList"]);
const isShowScenesList = computed(() => store.getters["functions/isShowScenesList"]);

const fdkkmetadata = computed(() => store.getters["fdkk/metadata"]);
const fdkkCurrentVersion = computed(() => store.getters["scene/fdkkCurrentVersion"]);
const vrStatus = computed(() => store.getters["functions/vrStatus"]);



const showMusicPlaying = ref(musicPlayer.isPlay)

const showCommentaryPlaying = ref(soundPlayer.isPlay)

const onIsShowList = (data) => {
      if (showTours.value) {
            store.commit('fdkk/setShowToursList', false)
      }
      store.commit("functions/setShowScenesList", !isShowScenesList.value);
};


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

const currentScene = computed(() => store.getters["scene/currentScene"]);

const customTelephone = computed(() => store.getters["scene/customTelephone"]);

const customLink = computed(() => store.getters["scene/customLink"]);

const showIntroduce = computed(() => store.getters["functions/showIntroduce"]);
const showTelephone = computed(() => store.getters["functions/showTelephone"]);
const showLink = computed(() => store.getters["functions/showLink"]);

const isFullscreen = ref(false)

const onIntroduce = () => {
  store.commit("functions/setShowIntroduce", true);
}


const onLink = () => {
  store.commit("functions/setShowLink", true);
}

const onIsBGM = () => {
  showMusicPlaying.value ? musicPlayer.pause() : musicPlayer.play()
}

const onIsAutoRotate = () => {
  store.commit("functions/setAutoRotate", !isAutoRotate.value);
};

const onVR = () => {
  $iosGrantedTips((data) => {
    console.log(data);
    if (data.code == 1) {
      store.commit("functions/setVrStatus", !vrStatus.value);
      if (currentScene.value.type == 'pano') {
        useApp().then((app) => {
          app.krpanoDom.call(vrStatus.value ? "webvr.enterVR()" : "webvr.exitVR()")
        });
      } else {
        if (fdkkCurrentVersion.value == 'v4') {
          document.querySelector('#fdkkifr') && document.querySelector('#fdkkifr').contentWindow.postMessage(
            {
              source: "qjkankan",
              event: "enterVr",
              params: {
                toggle: vrStatus.value
              }
            },
            "*"
          );
        } else {
          let ele = document.getElementById("showifr");
          ele && ele.contentWindow.postMessage(
            {
              source: "mingyuan",
              event: vrStatus.value ? "vr-in" : "vr-out",
            },
            "*"
          );
        }
      }
    } else {
      alert('运动和方向访问失败，您需要完全关闭此应用，然后再次打开，并允许访问运动与方向')
    }
  });

};


const onIsShowHotspotList = () => {
  store.commit("functions/setShowHotspotList", !isShowHotspotList.value);
};



const onIsCommentary = (data) => {
  showCommentaryPlaying.value ? soundPlayer.pause() : soundPlayer.play()
};

const onShare = () => {
  store.commit("functions/setShareUrl", true);
};

const staticList = ref([
  {
    id: "cruise",
    name: "巡游开关",
    icon: "rotation@2x.png",
    icondisabled: "rotation_disabled@2x.png",
  },
  {
    id: "vr",
    name: "VR",
    icon: "vr@2x.png",
  },
  {
    id: "share",
    name: "分享",
    icon: "share@2x.png",
  },
  {
    id: "full",
    name: "全屏",
    icon: "fullscreen@2x.png",
    icondisabled: "rotation_disabled@2x.png",
  },
]);


onMounted(() => {
  let events = ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange']
  events.forEach((item, index) => {
    window.addEventListener(item, () => {
      isFullscreen.value = !isFullscreen.value
    })
  })
})

musicPlayer.on('play', () => {
  showMusicPlaying.value = true
  soundPlayer.pause()
})
musicPlayer.on('pause', () => (showMusicPlaying.value = false))

soundPlayer.on('play', () => {
  showCommentaryPlaying.value = true
  musicPlayer.pause()
})
soundPlayer.on('pause', () => (showCommentaryPlaying.value = false))
</script>

<style lang="scss" scoped>
.control-pano {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  transition: 0.3s ease all;
  width: 100%;
  margin: 0 auto;
  background-image: url('@/assets/images/js_icon/line.png');
  background-position:  0 6px;
  background-size: 100% auto;
  background-repeat: no-repeat;
  >li {
    margin: 0 8px;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex-shrink: 0;
    img {
      width: 34px;
      height: 34px;
    }
    >div{
      font-size: 12px;
      margin-top: 4px;
    }
    
    &:last-of-type{
      margin-right: 10px;
    }
    &:first-of-type{
      margin-left: 10px;
    }
  }
}

.musicfix {
  position: fixed;
  right: 16px;
  top: 320px;
  transform: translateY(-50%);
  z-index: 999;
  width: 40px;
  >img{
    width: 100%;
  }
}
</style>
