<template>
  <div class="pano-view">
    <div id="pano" />
    <button
      class="return-home"
      @click="router.push({
        name: 'HomeView',
      })"
    />
    <CameraDesc
      v-if="isShowCameraDesc"
      class="camera-desc"
      @close="isShowCameraDesc = false"
    />
    <CharacterDesc
      v-if="isShowCharacterDesc"
      class="character-desc"
      @close="isShowCharacterDesc = false"
    />
    <div
      class="character-wrap"
      draggable="false"
    >
      <button
        class="name"
        @click="isShowCharacterDesc = true"
      >
        <span>趙孟頫</span>
      </button>
      <div
        class="character-frames-wrapper"
        @click="onClickCharacter"
      >
        <img
          v-show="animationType === 1"
          class="frames frames-1"
          :class="{
            animating: isCharacterAnimating,
            state1: characterState === 0,
            state2: characterState === 1,
          }"
          src="@/assets/images/A1-min.png"
          alt=""
          draggable="false"
        >
        <img
          v-show="animationType === 2"
          class="frames frames-2"
          :class="{
            animating: isCharacterAnimating,
            state1: characterState === 0,
            state2: characterState === 1,
          }"
          src="@/assets/images/A2-min.png"
          alt=""
          draggable="false"
        >
        <img
          v-show="animationType === 3"
          class="frames frames-3"
          :class="{
            animating: isCharacterAnimating,
            state1: characterState === 0,
            state2: characterState === 1,
          }"
          src="@/assets/images/A3-min.png"
          alt=""
          draggable="false"
        >
      </div>
      <img
        class="btn-track"
        src="@/assets/images/people-btn-track.png"
        alt=""
        draggable="false"
      >
      <button
        class="one btn-on-track"
        @click="showingContentIdx = 1"
      >
        <span>{{ btnOnTrack1Name }}</span>
      </button>
      <button
        class="two btn-on-track"
        @click="showingContentIdx = 2"
      >
        <span>{{ btnOnTrack2Name }}</span>
      </button>
      <button
        class="three btn-on-track"
        @click="showingContentIdx = 3"
      >
        <span>{{ btnOnTrack3Name }}</span>
      </button>
      <button
        class="four btn-on-track"
        @click="router.push({
          name: 'RelicList',
          query: {
            sceneIdx: route.query.sceneIdx,
            cameraIdx: route.query.cameraIdx,
          }
        })"
      >
        <span>文物长卷</span>
      </button>
    </div>
    <div class="camera-list">
      <button
        v-for="(item, idx) in currentCameraList"
        :key="idx"
        class="camera-entry"
        :class="{
          active: idx === Number(route.query.cameraIdx)
        }"
        @click="router.push({
          name: route.name,
          query:{
            sceneIdx: route.query.sceneIdx,
            cameraIdx: idx,
          }
        })"
      >
        <span>{{ item.name }}</span>
        <img
          class="bg-normal"
          src="@/assets/images/camera-list-item-bg.png"
          alt=""
          draggable="false"
        >
        <img
          class="bg-active"
          src="@/assets/images/camera-list-item-bg-active.png"
          alt=""
          draggable="false"
        >
      </button>
      <button class="next-camera" />
    </div>
    <CameraContent1
      v-if="showingContentIdx === 1"
      class="camera-content"
      @close="showingContentIdx = 0"
    />
    <CameraContent2
      v-if="showingContentIdx === 2"
      class="camera-content"
      @close="showingContentIdx = 0"
    />
    <CameraContent3
      v-if="showingContentIdx === 3"
      class="camera-content"
      @close="showingContentIdx = 0"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue"
import { useRoute, useRouter, onBeforeRouteUpdate } from "vue-router"
import { useStore } from "vuex"
import * as krfn from "@/libs/pano-core/index.js"
import CameraDesc from '@/components/CameraDesc.vue'
import CharacterDesc from '@/components/CharacterDesc.vue'
import { defineAsyncComponent } from 'vue'

const CameraContent1 = defineAsyncComponent(() =>
  import(`@/components/CameraContent-${Number(route.query.sceneIdx) + 1}-${Number(route.query.cameraIdx) + 1}-1.vue`)
)
const CameraContent2 = defineAsyncComponent(() =>
  import(`@/components/CameraContent-${Number(route.query.sceneIdx) + 1}-${Number(route.query.cameraIdx) + 1}-2.vue`)
)
const CameraContent3 = defineAsyncComponent(() =>
  import(`@/components/CameraContent-${Number(route.query.sceneIdx) + 1}-${Number(route.query.cameraIdx) + 1}-3.vue`)
)


const {
  windowSizeInCssForRef,
  windowSizeWhenDesignForRef,
} = useSizeAdapt()

const route = useRoute()
const router = useRouter()
const store = useStore()

const sceneIdx = computed(() => {
  return Number(route.query.sceneIdx)
})
const cameraIdx = computed(() => {
  return Number(route.query.cameraIdx)
})

const characterState = ref(0)
const isCharacterAnimating = ref(false)
const animationType = ref(1)
const isShowCameraDesc = ref(false)
const isShowCharacterDesc = ref(false)
const showingContentIdx = ref(0)

function onClickCharacter() {
  isShowCameraDesc.value = true
  if (!isCharacterAnimating.value) {
    animationType.value = Math.floor(Math.random() * 3) + 1
    let duration = 0
    switch (animationType.value) {
    case 1:
      duration = 3000
      break
    case 2:
      duration = 2000
      break
    case 3:
      duration = 1500
      break
    default:
      break
    }
    setTimeout(() => {
      isCharacterAnimating.value = true
      characterState.value = 1
      setTimeout(() => {
        isCharacterAnimating.value = false
        characterState.value = 0
      }, duration)
    }, 200)
  }
}

const sceneList = ref([
  {
    sceneName: '大汗之城',
    cameraList: [
      {
        name: '雄伟帝都',
        panoCode: 'WK1730419346750099456',
        contentPageBtnNameList: [
          '整体设计与规划',
          '营都人员与机构',
          '史料中的元大都',
        ],
      },
      {
        name: '大都宫阙',
        panoCode: 'WK1730165377477955584',
        contentPageBtnNameList: [
          '皇城与宫城',
          '皇城内的建筑布局',
          '忽必烈召见赵孟頫',
        ],
      },
      {
        name: '大都览胜',
        panoCode: 'WK1730164600466362368',
        contentPageBtnNameList: [
          '大都城内的寺庙建筑',
          '大都城内的官署机构',
          '重要建筑构件',
        ],
      },
    ]
  },
  {
    sceneName: '河润大都',
    cameraList: [
      {
        name: '通惠河畅',
        contentPageBtnNameList: [
          '大运河的历史演变',
          '元大都用水水系',
          '水利专家及对通惠河段的治理',
        ],
      },
      {
        name: '舳舻蔽水',
        contentPageBtnNameList: [
          '菏泽沉船',
          '磁县漕船',
          '聊城古船',
        ],
      },
      {
        name: '繁华富庶',
        contentPageBtnNameList: [
          '造福百姓',
          '元代瓷器的发展',
          ' 商品贸易中的货币',
        ],
      },
    ]
  },
  {
    sceneName: '大都风华',
    cameraList: [
      {
        name: '文人雅集',
        contentPageBtnNameList: [
          '元代文化艺术的发展',
          '上流社会的雅集盛会',
          '百工精巧',
        ],
      },
      {
        name: '曲苑杂剧',
        contentPageBtnNameList: [
          '元曲的文化成就',
          '著名元曲作家与作品',
          '表演元曲的著名演员',
        ],
      },
    ]
  },
])
const currentCameraList = computed(() => {
  return sceneList.value[sceneIdx.value].cameraList
})

const btnOnTrack1ImgUrl = computed(() => {
  return `url(${process.env.VUE_APP_CLI_MODE === 'dev' ? '' : '../'}` + require(`@/assets/images/camera-btn-${sceneIdx.value + 1}-${cameraIdx.value + 1}-1.png`) + ')'
})
const btnOnTrack1ActiveImgUrl = computed(() => {
  return `url(${process.env.VUE_APP_CLI_MODE === 'dev' ? '' : '../'}` + require(`@/assets/images/camera-btn-${sceneIdx.value + 1}-${cameraIdx.value + 1}-1-active.png`) + ')'
})
const btnOnTrack2ImgUrl = computed(() => {
  return `url(${process.env.VUE_APP_CLI_MODE === 'dev' ? '' : '../'}` + require(`@/assets/images/camera-btn-${sceneIdx.value + 1}-${cameraIdx.value + 1}-2.png`) + ')'
})
const btnOnTrack2ActiveImgUrl = computed(() => {
  return `url(${process.env.VUE_APP_CLI_MODE === 'dev' ? '' : '../'}` + require(`@/assets/images/camera-btn-${sceneIdx.value + 1}-${cameraIdx.value + 1}-2-active.png`) + ')'
})
const btnOnTrack3ImgUrl = computed(() => {
  return `url(${process.env.VUE_APP_CLI_MODE === 'dev' ? '' : '../'}` + require(`@/assets/images/camera-btn-${sceneIdx.value + 1}-${cameraIdx.value + 1}-3.png`) + ')'
})
const btnOnTrack3ActiveImgUrl = computed(() => {
  return `url(${process.env.VUE_APP_CLI_MODE === 'dev' ? '' : '../'}` + require(`@/assets/images/camera-btn-${sceneIdx.value + 1}-${cameraIdx.value + 1}-3-active.png`) + ')'
})
const btnOnTrack4ImgUrl = computed(() => {
  return `url(${process.env.VUE_APP_CLI_MODE === 'dev' ? '' : '../'}` + require(`@/assets/images/camera-btn-${sceneIdx.value + 1}-${cameraIdx.value + 1}-4.png`) + ')'
})
const btnOnTrack4ActiveImgUrl = computed(() => {
  return `url(${process.env.VUE_APP_CLI_MODE === 'dev' ? '' : '../'}` + require(`@/assets/images/camera-btn-${sceneIdx.value + 1}-${cameraIdx.value + 1}-4-active.png`) + ')'
})

const btnOnTrack1Name = computed(() => {
  return currentCameraList.value[cameraIdx.value].contentPageBtnNameList[0]
})
const btnOnTrack2Name = computed(() => {
  return currentCameraList.value[cameraIdx.value].contentPageBtnNameList[1]
})
const btnOnTrack3Name = computed(() => {
  return currentCameraList.value[cameraIdx.value].contentPageBtnNameList[2]
})


/**
 * 全景图
 */
let __krfn = krfn.default
window.__krfn = __krfn

let scene = null

function loadScene(sceneIdx, cameraIdx) {
  scene = store.getters.catalogTopology[sceneIdx].children[0].children[Number(cameraIdx)]

  $("#pano").empty()
  window.vrInitFn = () => {
    // eslint-disable-next-line no-undef
    // $smallWaiting.hide()
    var krpano = document.getElementById("krpanoSWFObject")
    __krfn.utils.initHotspot(krpano, scene.someData, false)
  }
  window.vrViewFn = () => {
    try {
      let tmp = scene.initVisual || {}
      var krpano = document.getElementById("krpanoSWFObject")
      krpano.set("view.vlookat", tmp.vlookat || 0)
      krpano.set("view.hlookat", tmp.hlookat || 0)
      krpano.set("autorotate.enabled", Boolean(store.state.panoData.isAuto))
    } catch (error) {
      console.log(error)
    }
  }
  let settings = {
    "events[skin_events].onxmlcomplete": "js(window.vrViewFn());",
    "events[skin_events].onloadcomplete": "js(window.vrInitFn());",
  }
  // eslint-disable-next-line no-undef
  removepano("#pano")
  // eslint-disable-next-line no-undef
  embedpano({
    xml: `https://4dkk.4dage.com/720yun_fd_manage/${sceneList.value[sceneIdx].cameraList[cameraIdx].panoCode}/tour.xml`,
    swf: `${process.env.BASE_URL}static/template/tour.swf`, // 文件名tour.swf没看出来有啥作用，不写也行。但它的路径决定了 %SWFPATH% 的值。
    target: "pano",
    html5: "auto",
    mobilescale: 1,
    vars: settings,
    passQueryParameters: true,
  })
}

onMounted(() => {
  console.log()
  api.fetchPanoData(sceneList.value[sceneIdx.value].cameraList[cameraIdx.value].panoCode).then((res) => {
    // fixPanoData(res)
    store.commit('setPanoData', res)
    console.log('catalogTopology', store.getters.catalogTopology)
    loadScene(Number(sceneIdx.value), Number(cameraIdx.value))
  })
})

onBeforeRouteUpdate((to, from) => {
  console.log('to: ', to)
  if (to.name === route.name) {
    api.fetchPanoData(sceneList.value[to.query.sceneIdx].cameraList[to.query.cameraIdx].panoCode).then((res) => {
      // fixPanoData(res)
      store.commit('setPanoData', res)
      console.log('catalogTopology', store.getters.catalogTopology)
      loadScene(Number(to.query.sceneIdx), Number(to.query.cameraIdx))
    })
  }
})
</script>

<style lang="less" scoped>
*{
  user-select: none;
}
.pano-view{
  position: relative;
  height: 100%;
  >#pano{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }
  >button.return-home{
    position: absolute;
    width: 77px;
    height: 77px;
    top: 43px;
    right: 51px;
    background-image: url(@/assets/images/btn-return-home.png);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
    &:hover{
      background-image: url(@/assets/images/btn-return-home-active.png);
    }
  }
  >.camera-desc{
    z-index: 5;
  }
  >.character-desc{
    z-index: 5;
  }
  >.character-wrap{
    position: absolute;
    left: 40px;
    bottom: 0;
    width: 300px;
    height: 452px;
    >button.name{
      position: absolute;
      top: 50px;
      left: 0;
      transform: translateX(-50%);
      width: 36px;
      height: 178px;
      z-index: 3;
      font-size: 23px;
      font-family: Source Han Serif SC, Source Han Serif SC;
      font-weight: 400;
      color: #43310E;
      line-height: 27px;
      letter-spacing: 7px;
      writing-mode: vertical-lr;
      background-image: url(@/assets/images/people-name-bg.png);
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center center;
      >span{
        position: absolute;
        left: 45%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
    }
    @frame-width: 256px;
    @frame-height: 512px;
    @duration-1: 3s;
    @frame-num-1: 72;
    @duration-2: 2s;
    @frame-num-2: 48;
    @duration-3: 1.5s;
    @frame-num-3: 36;
    >.character-frames-wrapper {
      position: absolute;
      left: 0;
      top: -60px;
      height: @frame-height;
      width: @frame-width;
      overflow: hidden;
      z-index: 1;
      cursor: pointer;
      >.frames {
        position: absolute;
        height: 100%;
        transition-property: none;
        &.animating{
          transition-property: left;
        }
        &.state1 {
          left: 0;
        }
      }
      >.frames-1{
        transition-duration: @duration-1;
        transition-timing-function: steps(@frame-num-1 - 1, jump-end);
        &.state2 {
          left: calc(-100% * (@frame-num-1 - 1));
        }
      }
      >.frames-2{
        transition-duration: @duration-2;
        transition-timing-function: steps(@frame-num-2 - 1, jump-end);
        &.state2 {
          left: calc(-100% * (@frame-num-2 - 1));
        }
      }
      >.frames-3{
        transition-duration: @duration-3;
        transition-timing-function: steps(@frame-num-3 - 1, jump-end);
        &.state2 {
          left: calc(-100% * (@frame-num-3 - 1));
        }
      }
    }
    >img.btn-track{
      position: absolute;
      width: 598px;
      height: 598px;
      left: -150px;
      bottom: -101px;
    }
    >button.btn-on-track{
      position: absolute;
      width: 78px;
      height: 78px;
      background-size: cover;
      background-repeat: no-repeat;
      background-position: center center;
      text-align: left;
      z-index: 3;
      >span{
        margin-left: 120px;
        display: none;
        font-size: 23px;
        font-family: Source Han Serif SC, Source Han Serif SC;
        font-weight: 600;
        color: #FFF1BE;
        line-height: 27px;
        letter-spacing: 5px;
      }
      &:hover{
        width: 397px;
        height: 91px;
        transform: translate(-13px, -5px);
        >span{
          display: initial;
        }
      }
    }
    >button.one{
      left: 210px;
      top: -42px;
      background-image: v-bind(btnOnTrack1ImgUrl);
      &:hover{
        background-image: v-bind(btnOnTrack1ActiveImgUrl);
      }
    }
    >button.two{
      left: 336px;
      top: 62px;
      background-image: v-bind(btnOnTrack2ImgUrl);
      &:hover{
        background-image: v-bind(btnOnTrack2ActiveImgUrl);
      }
    }
    >button.three{
      left: 385px;
      top: 205px;
      background-image: v-bind(btnOnTrack3ImgUrl);
      &:hover{
        background-image: v-bind(btnOnTrack3ActiveImgUrl);
      }
    }
    >button.four{
      left: 352px;
      top: 353px;
      background-image: v-bind(btnOnTrack4ImgUrl);
      &:hover{
        background-image: v-bind(btnOnTrack4ActiveImgUrl);
      }
    }
  }
  >div.camera-list{
    position: absolute;
    bottom: 0;
    right: 0;
    width: calc(1346 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    height: calc(161 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    background-image: url(@/assets/images/camera-list-bg.png);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: calc(10 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    padding-right: calc(204 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    >button.camera-entry{
      width: calc(198 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      height: calc(41 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      font-size: calc(21 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      font-family: Source Han Serif SC, Source Han Serif SC;
      font-weight: 600;
      color: #FFED87;
      line-height: calc(25 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      letter-spacing: calc(9 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      position: relative;
      z-index: 0;
      >img.bg-normal{
        display: initial;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: calc(198/ v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        height: calc(55 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        z-index: -1;
      }
      >img.bg-active{
        display: none;
        position: absolute;
        left: 50%;
        top: 0%;
        transform: translate(-50%, -50%);
        width: calc(230 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
        height: auto;
        z-index: -1;
      }
    }
    >button.camera-entry.active{
      font-size: calc(21 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      font-family: Source Han Serif SC, Source Han Serif SC;
      font-weight: 600;
      color: #794A00;
      line-height: calc(25 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      letter-spacing: calc(9 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      >img.bg-normal{
        display: none;
      }
      >img.bg-active{
        display: initial;
      }
    }
    >button.next-camera{
      position: absolute;
      top: calc(30 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      right: calc(45 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      width: calc(70 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
      height: calc(100 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));
    }
  }
  >.camera-content{
    z-index: 10;
  }
}
</style>