<template>
  <div v-show="player.showWidgets" class="root-panel">
    <div class="guide-panel" :class="{ disable: disable }">
      <div class="g-con">
        <div class="swiper-container" id="sw-guide">
          <!-- <ul class="swiper-wrapper" v-if="tours.length > 1"> -->
          <ul class="swiper-wrapper">
            <li
              @click.stop="changeItem('part', index)"
              class="swiper-slide"
              :style="`background-image:url(${i.frameId ? common.changeUrl(i.list[i.frameId].enter.cover) : common.changeUrl(i.list[0].enter.cover)});`"
              :class="{ active: isPlay && partId == index }"
              v-for="(i, index) in tours"
              :key="index"
            >
              <div>{{ i.name }}</div>

              <span v-if="partId == index && progressNum > 0" class="bar" :style="{ '--w': progressNum + '%' }"></span>
            </li>
          </ul>
          <!-- <ul class="swiper-wrapper" v-else>
            <li
              @click.stop="changeItem('frame', index)"
              class="swiper-slide"
              :style="`background-image:url(${common.changeUrl(i.enter.cover)});`"
              :class="{ active: isPlay && frameId == index }"
              v-for="(i, index) in tours[0].list"
              :key="index"
            >
              <div>{{ i.name }}</div>

              <span v-if="frameId == index && progressNum > 0" class="bar" :style="{ '--w': progressNum + '%' }"></span>
            </li>
          </ul> -->
        </div>
        <div class="back">
          <div @click.stop="back">
            <ui-icon type="back"></ui-icon>
            <div>{{ $t('common.back') }}</div>
          </div>
          <div @click.stop="playTour">
            <ui-icon :type="isPlay ? 'pause' : 'preview'"></ui-icon>
            <div>{{ isPlay ? $t('common.pause') : $t('common.play') }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useStore } from 'vuex';
import common from '@/utils/common';
import { onMounted, watch, computed, ref, nextTick } from 'vue';
import { useApp, getApp } from '@/app';
import { useMusicPlayer } from '@/utils/sound';

import { useI18n, getLocale } from '@/i18n';
const { t } = useI18n({ useScope: 'global' });

let timer = null;

const store = useStore();
const musicPlayer = useMusicPlayer();
const isSelect = ref(false);
const disable = ref(false);

const isPlay = computed(() => {
  let status = store.getters['tour/isPlay'];
  let map = document.querySelector('.kankan-app div[xui_min_map]');
  if (map) {
    if (status) {
      map.classList.add('disabled');
    } else {
      map.classList.remove('disabled');
    }
  }
  return status;
});

const partId = computed(() => store.getters['tour/partId']);
const frameId = computed(() => store.getters['tour/frameId']);
const changeItem = async (type, id) => {
  disable.value = true;
  let player = await getApp().TourManager.player;
  if (type == 'part') {
    store.commit('tour/setData', {
      frameId: 0,
      partId: id,
    });
    progressNum.value = 0;

    player.selectPart(id).then(() => {
      disable.value = false;
      if (!isPlay.value) {
        return;
      }
      store.commit('tour/setData', {
        isPlay: true,
      });
      player.play(id);
    });
  } else {
    player.selectFrame(id).then(() => {
      disable.value = false;

      store.commit('tour/setData', {
        frameId: id,
      });
    });
  }
  // mySwiper.slideTo(id);
  // cancelTimer();
  // store.commit('tour/setData', { isPlay: false });

  // slideScroll()
};

const back = async () => {
  let player = await getApp().TourManager.player;
  if (isPlay.value) {
    store.commit('tour/setData', { isPlay: false });
    player.pause();
  }
  store.commit('tour/setData', {
    partId: 0,
    isHome: true,
  });
};
const playTour = async () => {
  progressNum.value = 0;
  let player = await getApp().TourManager.player;
  if (isPlay.value) {
    store.commit('tour/setData', { isPlay: false });
    player.pause();
  } else {
    store.commit('tour/setData', { isPlay: true });
    player.play(partId.value);
  }
};

const progressNum = ref(0);

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

const controls = computed(() => metadata.value.controls);

const player = computed(() => store.getters['player']);

const tours = computed(() => store.getters['tour/tours']);

const brandlist = ref([]);
let mySwiper = null;
const brandScroll = () => {
  nextTick(() => {
    let t = setTimeout(() => {
      clearTimeout(t);
      mySwiper = new Swiper('#sw-guide', {
        freeMode: true,
        slidesPerView: 'auto',
        spaceBetween: 6,

        on: {
          touchMove(swiper, e) {
            e.stopPropagation();
            e.preventDefault();
          },
        },
      });
    }, 100);
  });
};

const onClickHandler = async () => {
  console.log('onClickHandler');
  if (isPlay.value) {
    let player = await getApp().TourManager.player;
    player.pause();
    musicPlayer.resume();
  }
};
const cancelTimer = () => {
  if (timer) {
    KanKan.Animate.transitions.cancel(timer);
    timer = null;
  }
};

const hanlderTour = async () => {
  let player = await getApp().TourManager.player;
  player.on('play', (data) => {
    progressNum.value = 0;
    musicPlayer.pause(true);

    // if (tours.value.length > 1) {
    //     let time = getPartTime(data.partId)
    //     hanlderTourPartPlay(time)
    // }
  });
  player.on('pause', (tours) => {
    // console.log('pause', player);
    musicPlayer.resume();
    currProgress = 0;
    currFrameProgress = 0;
    progressNum.value = 0;
    cancelTimer();
    store.commit('tour/setData', { isPlay: false });
  });
  player.on('end', (tours) => {
    musicPlayer.resume();
    progressNum.value = 100;
    currProgress = 0;
    currFrameProgress = 0;
    store.commit('tour/setData', { isPlay: false });
    cancelTimer();
  });
  let currPartId = null;
  let currFrameId = null;
  let currProgress = 0;
  let FrameLength = 0;
  let currFrameProgress = 0;
  // player.on('progress', (data) => {
  //   // if (tours.value.length == 1) {
  //   //   progressNum.value = data.progress * 100;
  //   // } else {

  //   if (currPartId != data.partId) {
  //     mySwiper.slideTo(data.partId);
  //     currPartId = data.partId;
  //     FrameLength = Math.max(tours.value[data.partId].list.length - 1, 1);
  //     currProgress = 0;
  //   } else {
  //     console.log(FrameLength);
  //     currProgress += data.progress / FrameLength;
  //     if (currProgress >= 100) {
  //       currProgress = 100;
  //     }

  //     console.log(currProgress);

  //     progressNum.value = currProgress;
  //   }
  //   // }

  //   store.commit('tour/setData', { partId: data.partId, frameId: data.frameId, isPlay: true });
  // });

  player.on('progress', (data) => {
    // if (tours.value.length == 1) {
    //     progressNum.value = data.progress * 100
    // } else {
    // let time = getPartTime(data.partId)

    // hanlderTourPartPlay(time)

    if (currPartId != data.partId) {
      mySwiper.slideTo(data.partId);
      currPartId = data.partId;
      FrameLength = tours.value[data.partId].list.length;
      currProgress = 0;
      currFrameProgress = 0;
    } else {
      FrameLength = tours.value[data.partId].list.length;
      let precent = (data.frameId + 1) / FrameLength;

      if (currFrameId != data.frameId) {
        currFrameId = data.frameId;
        currFrameProgress = currProgress;
      } else {
        currProgress = (data.progress / FrameLength) * 100 + currFrameProgress;
      }
      // currProgress = data.progress / FrameLength;

      // console.log(currFrameProgress);

      if (currProgress >= 100) {
        currProgress = 100;
      }

      progressNum.value = currProgress;
    }
    // }

    store.commit('tour/setData', {
      partId: data.partId,
      frameId: data.frameId,
      isPlay: true,
    });
  });

  // nextTick(() => {
  //     editorMain.value = document.querySelector('.ui-editor-main')
  // })
};
onMounted(() => {
  useApp().then(async (sdk) => {
    hanlderTour();
    brandScroll();
  });
  nextTick(() => {
    let player = document.querySelector('.player[name="main"]');
    player.addEventListener('touchstart', onClickHandler);
    player.addEventListener('click', onClickHandler);
  });
});
</script>

<style lang="scss" scoped>
.root-panel {
  position: absolute;
  bottom: 46px;
  left: 0;
  right: 0;
  z-index: 99;
  width: 100%;
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  .guide-panel {
    width: 100%;
    position: relative;
    &.disable {
      opacity: 0.8;
      pointer-events: none;
    }
    .g-con {
      background: rgba(0, 0, 0, 0.3);
      border-radius: 4px;
      border: 1px solid rgba(255, 255, 255, 0.2);
      width: 100%;
      height: 100%;
      margin: 0 auto;
      padding: 6px 10px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      flex-direction: column;
      .back {
        text-align: center;
        width: 100%;
        font-size: 0;
        margin-right: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-top: solid 1px rgba(255, 255, 255, 0.2);
        height: 48px;

        > div {
          font-size: 14px;
          margin-left: 20px;
        }
      }
      #sw-guide {
        width: 100%;
        flex: auto;
        overflow: hidden;
        padding-right: 2px;
        position: relative;
        padding-bottom: 6px;
        > ul {
          > li {
            border-radius: 2px;
            position: relative;
            font-size: 0;
            width: 154px;
            height: 82px;
            overflow: hidden;
            background-size: cover;
            > img {
              width: 100%;
            }
            > div {
              width: 100%;
              position: absolute;
              font-size: 12px;
              left: 50%;
              top: 50%;
              transform: translate(-50%, -50%);
              text-overflow: ellipsis;
              white-space: nowrap;
              overflow: hidden;
              text-align: center;
              padding: 0 4px;
              box-sizing: border-box;
              word-break: break-all;
            }
            &.active {
              &::before {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                content: '';
                display: inline-block;
                background: rgba(24, 24, 24, 0.5);
              }
              color: var(--editor-main-color);

              .bar {
                display: inline-block;
                width: 70%;
                height: 2px;
                background: rgba(0, 0, 0, 0.5);
                border-radius: 2px;
                position: absolute;
                z-index: 9;
                bottom: 10%;
                left: 50%;
                transform: translateX(-50%);
                &::after {
                  content: '';
                  width: var(--w);
                  background: var(--editor-main-color);
                  height: 100%;
                  position: absolute;
                  left: 0;
                  top: 0;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
