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

    <h1 v-if="!$isMobile">
      安徽省纪录小康工程数据库云展馆
    </h1>

    <menu
      :style="{
        bottom: isShowTourGuide ? 'calc(183px + 30px)' : '',
      }"
    >
      <button
        id="auto-moving"
        @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
        id="tour-guide"
        :class="{active: isShowTourGuide}"
        @click="onClickChangjingdaolan"
      >
        <img
          src="@/assets\images\swkk\changjingdaolan.png"
          alt=""
          draggable="false"
        >
        <!-- <div>场景导览</div> -->
      </button>
      <button
        v-if="!$isMobile"
        id="qjmy"
        :class="{active: mode === 2}"
        @click="onClickQuanjingmanyou"
      >
        <img
          src="@/assets\images\swkk\quanjingmanyou.png"
          alt=""
          draggable="false"
        >
        <!-- <div>全景漫游</div> -->
      </button>
      <button
        v-if="!$isMobile"
        id="overlook"
        :class="{active: mode === 3}"
        @click="onClickDingbufushi"
      >
        <img
          src="@/assets\images\swkk\dingbufushi.png"
          alt=""
          draggable="false"
        >
        <!-- <div>顶部俯视</div> -->
      </button>
      <button
        v-if="!$isMobile"
        id="mini-model"
        :class="{active: mode === 4}"
        @click="onClickMinimoxing"
      >
        <img
          src="@/assets\images\swkk\minimoxing.png"
          alt=""
          draggable="false"
        >
        <!-- <div>迷你模型</div> -->
      </button>
      <!-- <button
        id="hotspot-list"
        :class="{active: isShowHotspotList}"
        @click="isShowHotspotList = true"
      >
        <img
          v-show="!isShowHotspotList"
          src="@/assets\images\swkk\hotspot-list.png"
          alt=""
          draggable="false"
        >
        <img
          v-show="isShowHotspotList"
          src="@/assets\images\swkk\hotspot-list-active.png"
          alt=""
          draggable="false"
        >
        <div>热点列表</div>
      </button> -->
    </menu>

    <!-- 右上地图 -->
    <div
      v-show="!isLoading && mode === 2"
      id="mini-map"
      class="mini-map"
    >
      <img
        class="mini-map-top"
        :src="require(`@/assets/images/swkk/mini-map-${$isMobile ? 'mobile' : 'pc'}.png`)"
        alt=""
        draggable="false"
      >
      <div class="selector">
        <div
          v-if="$isMobile"
          class="bottom-bar"
        >
          <button
            class="plain"
            @click="onClickDingbufushi"
          >
            <img
              class=""
              src="@/assets/images/swkk/dingbufushi-mobile.png"
              alt=""
              draggable="false"
            >
            <span>平面</span>
          </button>
          <button
            class="model"
            @click="onClickMinimoxing"
          >
            <img
              class=""
              src="@/assets/images/swkk/minimoxing-mobile.png"
              alt=""
              draggable="false"
            >
            <span>三维</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 导览栏 -->
    <div
      v-show="isShowTourGuide"
      class="tour-guide-wrap swiper-root"
      :style="{
        zIndex: $globalConfig.zIndex.swkkGuideBar.self
      }"
    >
      <ul
        v-if="tourList.length"
        class="tour-guide swiper-wrapper"
      >
        <li
          v-for="(item, index) in tourList"
          :key="item.sid"
          ref="scene-item"
          class="swiper-slide"
          :class="{active: curSceneIdx === index}"
          @click="changeScene(index)"
        >
          <img
            :src="item.list[0].enter.cover"
            alt=""
            draggable="false"
          >
          <div class="mask" />
          <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"
      :style="{
        zIndex: $globalConfig.zIndex.swkkHotspotDetail.self
      }"
      :hotspot-list="relatedHotspotList"
      :scene-code="sceneCode"
      @close="isShowDetail = false"
    />

    <HotspotList
      v-if="isShowHotspotList"
      class="hotspot-list"
      :style="{
        zIndex: $globalConfig.zIndex.swkkHotspotList.self
      }"
      :hotspot-data="baseHotData"
      @back="isShowHotspotList = false"
      @click-hotspot="onClickHotspot"
    />
  </div>
</template>

<script>
import HotspotDetail from "@/components/HotspotDetail.vue"
import HotspotList from "@/components/HotspotList.vue"

import Swiper from 'swiper/swiper-bundle.esm.js'
import 'swiper/swiper-bundle.css'

export default {
  components: {
    HotspotDetail,
    HotspotList,
  },
  data() {
    return {
      // 四维看看库相关
      kankan: null,
      tagView: null,
      mode: 2,

      isLoading: true,

      // 楼层
      floor: 0,
      sceneCode: '',

      // 自动巡游相关
      canClickAutoMoving: false,
      isAutoMoving: false,
      isChangingAutoMovingStatus: false,
      autoMovingProgress: 0,

      // 自动导览与切换场景相关
      isShowTourGuide: false,
      tourList: [],
      isChangingScene: false,
      curSceneIdx: null,

      // 热点相关
      baseHotData: null,
      isShowDetail: false,
      isShowHotspotList: 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('tour-guide-show')
        } else {
          this.$msgCenter.publish('tour-guide-hide')
        }
      }
    }
  },
  beforeCreate() {
  },
  beforeMount() {
    if (this.$route.query.isMuted === 'false') {
      this.setIsMuted(false)
      let newHref = location.href.substring(0, location.href.length - 14)
      location.href = newHref
    } else if (this.$route.query.isMuted === 'true') {
      this.setIsMuted(true)
      let newHref = location.href.substring(0, location.href.length - 13)
      location.href = newHref
    }
  },
  mounted() {
    // setTimeout(() => {
    //   const haveShownSwkkGuide = localStorage.getItem('haveShownSwkkGuide')
    //   if (!haveShownSwkkGuide) {
    //     localStorage.setItem('haveShownSwkkGuide', '1')
    //     this.$root.userGuide.beginGuide([
    //       {
    //         selector: '#auto-moving',
    //         title: '自动漫游',
    //         content: '自动游览线上场馆',
    //       },
    //       {
    //         selector: '#tour-guide',
    //         title: '场景导览',
    //         content: '查看场景内所有镜头点位',
    //       },
    //       {
    //         selector: '#qjmy',
    //         title: '全景漫游',
    //         content: '手动自主漫游',
    //       },
    //       {
    //         selector: '#mini-model',
    //         title: '迷你模型',
    //         content: '查看场景3D模型',
    //       },
    //       {
    //         selector: '#overlook',
    //         title: '顶部俯视',
    //         content: '查看场景平面图',
    //       },
    //       {
    //         selector: '#hotspot-list',
    //         title: '热点列表',
    //         content: '查看场景内所有交互热点',
    //       },
    //       {
    //         selector: '#bottom-bar',
    //         title: '更多',
    //         content: '可回到首页，关闭/开启声音，点赞和分享等',
    //       },
    //       {
    //         selector: '#mini-map',
    //         title: '地图',
    //         content: '可切换楼层，或查看场景3D模型',
    //         customWidth: '18rem',
    //         customHeight: '18rem + 4.6rem',
    //       },
    //     ])
    //   }
    // }, 500)
    this.$msgCenter.publish('show-loading')
    let floor = this.$route.query.floor
    this.floor = floor
    if (floor === "1") this.sceneCode = process.env.VUE_APP_SCENE_CODE_FLOOR_1
    else if (floor === "2") this.sceneCode = process.env.VUE_APP_SCENE_CODE_FLOOR_2
    console.assert(this.sceneCode, 'no sceneCode!')

    let kankan = new KanKan({
      dom: ".swkk-wrap",
      num: this.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
        console.log('tour list: ', this.tourList)
        setTimeout(() => {
          new Swiper('.swiper-root', {
            slidesPerView: 'auto',
            freeMode: true,
            mousewheel: true,
            grabCursor: true,
            // If we need pagination
            // pagination: {
            //   el: '.swiper-pagination',
            // },

            // Navigation arrows
            // navigation: {
            //   nextEl: '.swiper-button-next',
            //   prevEl: '.swiper-button-prev',
            // },
          })
        }, 0)
        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
      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) => {
      this.tagView = TagView

      // 监听手动点击事件
      TagView.on("click", (e) => {

        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)
            }
          })
        } 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: "./static-swkk/diBiao.png",
        size: 40,
      })
    })

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

    kankan.render()
    this.kankan = kankan
  },
  beforeDestroy() {
    this.stopAutoMoving()
  },
  methods: {
    ...globalMapMutations([
      'mustMute',
      'cancelMustMute',
      'setIsMuted',
    ]),
    changeFloor(val) {
      let newHref = location.href.substring(0, location.href.length - 1) + val + `&isMuted=${this.isMuted}`
      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()
    },
    onClickChangjingdaolan() {
      this.isShowTourGuide = !this.isShowTourGuide
    },
    onClickQuanjingmanyou() {
      this.kankan.Camera.panorama()
    },
    onClickMinimoxing() {
      this.stopAutoMoving()
      this.kankan.Camera.dollhouse()
    },
    onClickDingbufushi() {
      this.stopAutoMoving()
      this.kankan.Camera.floorplan()
    },
    async changeScene(index) {
      if (this.isChangingScene) {
        return
      }
      this.stopAutoMoving()

      this.isChangingScene = true
      this.curSceneIdx = index

      this.$refs['scene-item'][this.curSceneIdx].scrollIntoView()

      let player = await this.kankan.TourManager.player
      player.pause()
      await player.selectPart(index)
      this.isChangingScene = false
    },
    onClickHotspot(hotspot) {
      this.isShowHotspotList = false
      this.relatedHotspotList = []
      if (hotspot.title.split("&")[1]) { // 如果是多个热点合并
        this.baseHotData.forEach((item) => {
          if (item.title.split("&")[1] === hotspot.title.split("&")[1]) {
            this.relatedHotspotList.push(item)
          }
        })
      } else { // 单个热点
        this.relatedHotspotList.push(hotspot)
      }

      // 聚焦当前点击的热点
      this.tagView && this.tagView.focus(hotspot.sid)

      this.isShowDetail = true
    }
  },
}
</script>

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

  > h1 {
    position: absolute;
    z-index: 1;
    top: 23px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0,0,0,0.45);
    border-radius: 33px;
    font-size: 16px;
    color: #FFFFFF;
    padding: 9px 29px;
  }

  > menu {
    position: absolute;
    z-index: 1;
    bottom: 30px;
    display: flex;
    align-items: center;
    pointer-events: none;
    > button {
      pointer-events: initial;
      margin-left: 30px;
      opacity: 0.7;
      &:hover {
        opacity: 1;
      }
      > img {
        width: 50px;
        height: 50px;
      }
      > div {
        color: #fff;
        text-shadow: 0px 0px 0.2rem rgba(255,255,255,0.6);
        margin-top: 0.17rem;
        font-size: 1.17rem;
      }
      &.active {
        opacity: 1;
        > div {
          color: #930909;
          text-shadow: 0px 0px 0.2rem rgba(255,255,255,0.6);
        }
      }
    }
  }

  /deep/[xui_min_map] {
    top: 28px;
    right: 20px;
    width: 237px;
    height: 149px;
    border: none;
    background: rgba(86,86,86,0.2);
    border-radius: 0;
    backdrop-filter: blur(10px);
  }
  .mini-map {
    position: absolute;
    z-index: 1;
    right: 12px;
    top: 10px;
    width: 254px;
    height: 18px;
    > img {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }
  }

  .tour-guide-wrap {
    ::-webkit-scrollbar { width: 0; height: 5px; } /*宽度是对垂直滚动条而言，高度是对水平滚动条而言*/
    ::-webkit-scrollbar-track {
      background: #fff;
    }
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    background: rgba(133, 119, 69, 0.50);
    backdrop-filter: blur(10px);
    .tour-guide {
      height: 100%;
      padding: 24px 0;
      width: fit-content !important;
      > li {
        margin-right: 10px;
        &:first-child {
          margin-left: 46px;
        }
        &:last-child {
          margin-right: 46px;
        }
        width: 187px;
        height: 135px;
        position: relative;
        > img {
          background: #D26868;
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        > .mask {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          background: rgba(0,0,0,0.5);
        }
        > .progress {
          position: absolute;
          left: 0;
          bottom: 0;
          height: 10px;
          background-color: #930909;
        }
        .title {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          font-size: 16px;
          color: #FFFFFF;
          white-space: pre;
          word-break: break-all;
          overflow: hidden;
          text-overflow: ellipsis;
          pointer-events: none;
          user-select: none;
        }
        &.active {
          > .mask {
            border: 4px solid #A10E0C;
            background: linear-gradient(180deg, rgba(0, 0, 0, 0) 70%, rgba(0, 0, 0, 0.5) 100%);
          }
          .title {
            top: initial;
            bottom: 12px;
            transform: translateX(-50%);
          }
        }
      }
    }
  }
  .hotspot-detail {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}

.mobile {
  .skww-view {
    > menu {
      width: 50%;
      justify-content: space-around;
      > button {
        margin-left: initial;
        &:hover {
          opacity: 0.7;
        }
        &:active {
          opacity: 1;
        }
      }
    }

    /deep/[xui_min_map] {
      top: 25px;
      right: 10px;
      width: 160px;
      height: 137px;
      backdrop-filter: initial;
      background: initial;
    }
    .mini-map {
      position: absolute;
      z-index: 9;
      right: 5px;
      top: 12px;
      width: 170px;
      height: calc(12px + 137px + 44px);
      background: transparent;
      > img {
        height: 12px;
      }
      > .selector {
        position: absolute;
        left: 50%;
        top: 12px;
        transform: translateX(-50%);
        width: 160px;
        height: calc(137px + 44px);
        background: rgba(86, 86, 86, 0.2);
        backdrop-filter: blur(10px);
        > .bottom-bar {
          position: absolute;
          left: 0;
          bottom: 12px;
          width: 100%;
          display: flex;
          justify-content: space-around;
          align-items: center;
          > button.plain {
            display: flex;
            align-items: center;
            > img {
              width: 19px;
              height: 19px;
              margin-right: 4px;
            }
            > span {
              font-size: 16px;
              color: #FFF0BD;
            }
          }
          > button.model {
            display: flex;
            align-items: center;
            > img {
              width: 23px;
              height: 22px;
              margin-right: 4px;
            }
            > span {
              font-size: 16px;
              color: #FFF0BD;
            }
          }
        }
      }
    }
  }
}
</style>