<template>
  <div
    class="skww-view"
  >
    <div
      class="swkk-wrap"
    />

    <menu>
      <button
        :class="{active: isAutoMoving}"
        @click="onClickAutoMoving"
      >
        <img
          v-show="!isAutoMoving"
          src="@/assets\images\swkk\zidongmanyou.png"
          alt=""
          draggable="false"
        >
        <img
          v-show="isAutoMoving"
          src="@/assets\images\swkk\zidongmanyou_1.png"
          alt=""
          draggable="false"
        >

        <div>自动漫游</div>
      </button>
      <button
        :class="{active: isShowTourGuide}"
        @click="onClickCjdl"
      >
        <img
          v-show="!isShowTourGuide"
          src="@/assets\images\swkk\changjingdaolan.png"
          alt=""
          draggable="false"
        >
        <img
          v-show="isShowTourGuide"
          src="@/assets\images\swkk\changjingdaolan_1.png"
          alt=""
          draggable="false"
        >
        <div>场景导览</div>
      </button>
      <button
        :class="{active: mode === 2}"
        @click="onClickQjmy"
      >
        <img
          v-show="mode !== 2"
          src="@/assets\images\swkk\quanjingmanyou.png"
          alt=""
          draggable="false"
        >
        <img
          v-show="mode === 2"
          src="@/assets\images\swkk\quanjingmanyou_1.png"
          alt=""
          draggable="false"
        >
        <div>全景漫游</div>
      </button>
      <button
        :class="{active: mode === 3}"
        @click="onClickMnmx"
      >
        <img
          v-show="mode !== 3"
          src="@/assets\images\swkk\minimoxing.png"
          alt=""
          draggable="false"
        >
        <img
          v-show="mode === 3"
          src="@/assets\images\swkk\minimoxing_1.png"
          alt=""
          draggable="false"
        >
        <div>迷你模型</div>
      </button>
      <button
        :class="{active: mode === 4}"
        @click="onClickDbfs"
      >
        <img
          v-show="mode !== 4"
          src="@/assets\images\swkk\dingbufushi.png"
          alt=""
          draggable="false"
        >
        <img
          v-show="mode === 4"
          src="@/assets\images\swkk\dingbufushi_1.png"
          alt=""
          draggable="false"
        >
        <div>顶部俯视</div>
      </button>
    </menu>

    <!-- 右上地图 -->
    <div
      v-show="!isLoading && mode === 2"
      class="mini-map"
    >
      <div
        class="radio-wrap"
        :class="{ active: floor === '1' }"
        @click="changeFloor('1')"
      >
        <div class="radio" />
        <div class="rowrr">
          一层
        </div>
      </div>
      <div
        class="radio-wrap"
        :class="{ active: floor === '2' }"
        @click="changeFloor('2')"
      >
        <div class="radio" />
        <div class="rowrr">
          二层
        </div>
      </div>
    </div>

    <!-- 导览栏 -->
    <div
      v-show="isShowTourGuide"
      class="tour-guide-wrap"
      :style="{
        zIndex: $globalConfig.zIndex.swkkGuideBar.self
      }"
    >
      <ul
        v-if="tourList.length"
        class="tour-guide"
      >
        <li
          v-for="(item, index) in tourList"
          :key="item.sid"
          ref="scene-item"
          :class="{active: curSceneIdx === index}"
          @click="changeScene(index)"
        >
          <img
            :src="item.list[0].enter.cover"
            alt=""
            draggable="false"
          >
          <div
            v-show="isAutoMoving && (curSceneIdx === index)"
            class="progress"
            :style="{
              width: autoMovingProgress + '%',
            }"
          />
          <div class="title">
            {{ item.name }}
          </div>
        </li>
      </ul>
    </div>

    <HotspotDetail
      v-if="isShowDetail"
      class="hotspot-detail"
      :hotspot-list="relatedHotspotList"
      @close="isShowDetail = false"
    />
  </div>
</template>

<script>
import HotspotDetail from "@/components/HotspotDetail.vue"
export default {
  components: {
    HotspotDetail,
  },
  data() {
    //这里存放数据
    return {
      kankan: null,
      isLoading: true,

      floor: 0,

      canClickAutoMoving: false,
      isAutoMoving: false,
      isChangingAutoMovingStatus: false,
      autoMovingProgress: 0,

      isShowTourGuide: false,
      tourList: [],
      isChangingScene: false,
      curSceneIdx: null,

      mode: 2,

      baseHotData: null,
      isShowDetail: false,
    }
  },
  computed: {
    ...globalMapState([
      'isMuted',
    ])
  },
  watch: {
    isMuted: {
      handler(vNew) {
        if (!vNew) {
          this.stopAutoMoving()
        }
      }
    },
    isAutoMoving: {
      handler(vNew) {
        if (vNew) {
          this.isShowTourGuide = true
        } else {
        }
      }
    },
    isShowTourGuide: {
      handler(vNew) {
        if (vNew) {
          this.$msgCenter.publish('swkk-guide-bar-show')
        } else {
          this.$msgCenter.publish('swkk-guide-bar-hide')
        }
      }
    }
  },
  beforeCreate() {
  },
  beforeMount() {
  },
  mounted() {
    // setTimeout(() => {
    this.$msgCenter.publish('show-loading')
    let floor = this.$route.query.floor
    this.floor = floor
    let sceneCode = ''
    if (floor === "1") sceneCode = process.env.VUE_APP_SCENE_CODE_FLOOR_1
    else if (floor === "2") sceneCode = process.env.VUE_APP_SCENE_CODE_FLOOR_2
    console.assert(sceneCode, 'no sceneCode!')

    // 不等一秒，就会因为use了小地图而卡死？
    // setTimeout(() => {
    let kankan = new KanKan({
      dom: ".swkk-wrap",
      num: sceneCode,
    })

    kankan.use("MinMap", {
      theme: {
        camera_fillStyle: "#930909",
      },
    })

    kankan.use("TourPlayer").then((player) => {
      player.on("play", ({ partId, frameId }) => {
        this.isAutoMoving = true
        this.isChangingAutoMovingStatus = false
        this.mustMute()
      })
      player.on("pause", ({ partId, frameId }) => {
        this.isAutoMoving = false
        this.isChangingAutoMovingStatus = false
        this.cancelMustMute()
      })
      player.on("end", async () => {
        this.isAutoMoving = false
        this.isChangingAutoMovingStatus = false
        this.autoMovingProgress = 0
        this.frameId = null
        this.cancelMustMute()
      })

      player.on("progress", ({ partId, frameId, progress }) => {
        if (partId !== this.curSceneIdx) {
          this.curSceneIdx = partId
          this.autoMovingProgress = 0
          this.$refs['scene-item'][this.curSceneIdx].scrollIntoView()
        }
        this.autoMovingProgress = (frameId / this.tourList[partId].list.length + Number(progress).toFixed(5) / this.tourList[partId].list.length) * 100
      })
    })

    // 导览数据
    kankan.TourManager.on("loaded", (tours) => {
      try {
        this.tourList = tours
        setTimeout(() => {
          this.canClickAutoMoving = true
        }, 1000)
      } catch (e) {
        console.error('没拿到导览数据：', e)
        this.tourList = []
      }
      this.$msgCenter.publish('hide-loading')
    })

    // 全部热点数据
    kankan.store.on("tags", (tags) => {
      this.baseHotData = tags.tags.reverse()
      console.log('baseHotData: ', this.baseHotData)
    })

    // 热点
    kankan.use("TagView", {
      render(data) {
        let ifNeedShow = false
        // data.title如果没有“&”或者是“a&b&show”这样子，就要显示。
        let arrTitle = data.title.split("&")
        if (arrTitle[2] === 'show' || !data.title.includes("&")) {
          ifNeedShow = true
        }

        let title = data.title.split("&")[0]

        return `
              <span class="tag-icon animate" title=${title} style="${ifNeedShow ? "" : "display: none;"}; background-image: url({{icon}})"></span>
              <div class="tag-body"></div>
            `
      },
    }).then((TagView) => {
      // 监听手动点击事件
      TagView.on("click", (e) => {
        // // 点击热点的时候当前背景音乐的播放状态
        // let dom = document.querySelector("#bacMusic")
        // window.bacMusic = !dom.paused
        // setTimeout(() => {
        //   this.$refs.RbottomRef.opMusic(false)
        // }, 200)
        console.log(e.data)
        const example1 = {
          content: "<p>《胡乔木为他题词“浩气长存”》</p>",
          icon: "http://4dkk.4dage.com/v4/sdk/4.2.0/images/tag_icon_default.svg",
          media: {
            image: [
              { src: "q0AbKQ789922.jpeg" },
              { src: "kfhFHmL789632.jpeg" },
            ],
          },
          sid: "WfndN9Z789888",
          title: "陈处泰",
          type: "image",
        }

        const example2 = {
          content: "<p>汪裕先烈士狱中致姐姐的信</p>",
          media: {
            image: [
              { src: "q0AbKQ789922.jpeg" },
              { src: "kfhFHmL789632.jpeg" },
            ],
          },
          sid: "XQT0F8570262",
          title: "汪裕先&27&show",
          type: "image"
        }

        this.relatedHotspotList = []
        if (e.data.title.split("&")[1]) { // 如果是多个热点合并
          this.baseHotData.forEach((item) => {
            if (item.title.split("&")[1] === e.data.title.split("&")[1]) {
              this.relatedHotspotList.push(item)
            }
          })
          console.log(this.relatedHotspotList)
        } else { // 单个热点
          this.relatedHotspotList.push(e.data)
        }

        // 聚焦当前点击的热点
        TagView.focus(e.data.sid)

        this.isShowDetail = true
      })
    })

    // 球幕视频的播放与暂停影响背景音乐的播放状态
    kankan.Scene.on("panorama.videorenderer.startvideo", () => {
      console.log('startvideo')
      this.mustMute()
    })

    kankan.Scene.on("panorama.videorenderer.suspendrender", () => {
      console.log('suspend')
      this.cancelMustMute()
    })

    kankan.Scene.on("panorama.videorenderer.resumerender", () => {
      console.log('resume')
      this.mustMute()
    })

    kankan.Scene.on("loaded", () => {
      console.log('loaded!')
      this.isLoading = false
      //设置地面logo
      kankan.Scene.setFloorLogo({
        url: "./img/diBiao.png",
        size: 40,
      })
    })

    // 监听看看的模式
    kankan.Camera.on("mode.beforeChange", ({ toMode }) => {
      this.mode = {
        floorplan: 4,
        dollhouse: 3,
        panorama: 2,
      }[toMode]
    })

    kankan.render()
    this.kankan = kankan
    // }, 1000)
    // }, 500)
  },
  beforeDestroy() {
    this.stopAutoMoving()
  },
  methods: {
    ...globalMapMutations([
      'mustMute',
      'cancelMustMute',
    ]),
    // 切换楼层
    changeFloor(val) {
      let newHref = location.href.substring(0, location.href.length - 1) + val
      location.href = newHref
      location.reload()
    },
    onClickAutoMoving() {
      if (!this.canClickAutoMoving) {
        return
      }
      if (this.isAutoMoving) {
        this.stopAutoMoving()
      } else {
        this.startAutoMoving()
      }
    },
    async startAutoMoving() {
      if (this.isChangingAutoMovingStatus || this.isAutoMoving) {
        return
      }
      this.isChangingAutoMovingStatus = true
      let player = await this.kankan.TourManager.player
      player.play()
    },
    async stopAutoMoving() {
      if (this.isChangingAutoMovingStatus || !this.isAutoMoving) {
        return
      }
      this.isChangingAutoMovingStatus = true
      let player = await this.kankan.TourManager.player
      player.pause()
    },
    onClickCjdl() {
      this.isShowTourGuide = !this.isShowTourGuide
    },
    onClickQjmy() {
      this.kankan.Camera.panorama()
    },
    onClickMnmx() {
      this.stopAutoMoving()
      this.kankan.Camera.dollhouse()
    },
    onClickDbfs() {
      this.stopAutoMoving()
      this.kankan.Camera.floorplan()
    },
    async changeScene(index) {
      if (this.isChangingScene) {
        return
      }
      this.stopAutoMoving()

      this.isChangingScene = true
      this.curSceneIdx = index

      let player = await this.kankan.TourManager.player
      player.pause()
      await player.selectPart(index)
      this.isChangingScene = false
    },
  },
}
</script>

<style lang="less" scoped>
.skww-view {
  position: relative;
  width: 100%;
  height: 100%;
  z-index: 0;
  .swkk-wrap {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
  }

  > menu {
    position: absolute;
    z-index: 1;
    top: 2rem;
    left: 1.75rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.83rem;
    > button {
      > img {
        width: 5rem;
        height: 5rem;
      }
      > div {
        color: #fff;
        text-shadow: 0px 0px 0.2rem rgba(255,255,255,0.6);
        margin-top: 0.17rem;
        font-size: 1.17rem;
      }
      &.active {
        > div {
          color: #930909;
          text-shadow: 0px 0px 0.2rem rgba(255,255,255,0.6);
        }
      }
    }
  }

  /deep/[xui_min_map] {
    top: 7rem;
    right: 1.67rem;
    width: 18rem;
    height: 18rem;
    border: 0.08rem solid #D8B275;
    background-color: rgba(81, 32, 32, 0.4);
    border-radius: 0 0 0.42rem 0.42rem;
  }
  .mini-map {
    position: absolute;
    z-index: 1;
    right: 1.67rem;
    top: 2.5rem;
    border: 0.08rem solid #d8b275;
    border-radius: 0.42rem 0.42rem 0 0;
    color: #fff;
    width: 18rem;
    height: 4.6rem;
    background-color: #930909;
    display: flex;
    justify-content: space-evenly;
    .radio-wrap {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 1.67rem;
      .radio {
        margin-right: 0.5rem;
        width: 2.2rem;
        height: 2.2rem;
        border-radius: 50%;
        border: 0.08rem solid #fff;
        position: relative;
      }
      .rowrr {
      }
    }
    .active {
      color: #d8b275;
      pointer-events: none;
      .radio {
        &::after {
          content: "";
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          border-radius: 50%;
          width: 1rem;
          height: 1rem;
          background-color: #d8b275;
        }
      }
    }
  }

  .tour-guide-wrap {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 13.75rem;
    background: rgba(216,178,117,0.6);
    padding: 1.17rem 1.17rem 1.92rem 1.17rem;
    .tour-guide {
      display: flex;
      align-items: center;
      gap: 0.83rem;
      overflow: auto;
      width: 100%;
      height: 100%;
      > li {
        flex: 0 0 auto;
        width: 12.5rem;
        height: 10.5rem;
        position: relative;
        > img {
          background: #D26868;
          width: 100%;
          height: 7.5rem;
          object-fit: cover;
        }
        > .progress {
          position: absolute;
          left: 0;
          top: 6.7rem;
          height: 0.5rem;
          background-color: #930909;
        }
        .title {
          margin-top: 0.5rem;
          text-align: center;
          font-size: 1.25rem;
          color: #FFFFFF;
          white-space: pre;
          word-break: break-all;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        &.active {
          > img {
            border: 0.33rem solid #930909;
          }
          .title {
            color: #930909;
          }
        }
      }
    }
  }
  .hotspot-detail {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
</style>