<template>
  <teleport :to="tags$" v-if="tags$">
    <template v-for="(tag, index) in tags" :key="tag.sid">
      <div
        :tag-sid="tag.sid"
        @mouseleave.prevent="onMouseLeave($event, tag)"
        :style="{
          transform: `translate3d(${tag.x}px,${tag.y}px,0)`,
          'z-index': isShowTag(tag) ? 1 : 0,
        }"
        :class="{
          visible: tag.visible,
        }"
      >
        <span
          class="point zoom"
          @mouseenter.prevent="onMouseEnter($event, tag)"
          @click.stop="goTag($event, tag, index)"
          :style="{ 'background-image': 'url(' + getUrl(tag.icon) + ')' }"
        ></span>
        <div class="content">
          <div
            class="trans"
            :class="{
              active: isShowTag(tag),
            }"
          >
            <!-- :class="{
              fixed: isPlay,
              active:
                (isFixed && hotData && tag.sid == hotData.sid) ||
                (showInfo && hotData && tag.sid == hotData.sid),
            }" -->
            <template v-if="tag && !showMsg">
              <div class="arrow" :id="`arrow_${tag.sid}`">
                <i
                  @click.stop="closeTag"
                  class="iconfont ui-kankan-icon icon tip-h-center tip-v-bottom icon-close"
                ></i>
              </div>
              <ShowTag @click.stop="" :tag="tag" v-if="tag" @open="openInfo" />
            </template>
          </div>
        </div>

        <!-- <TagView @click.stop="" v-if="showMsg && toggleIndex == index" @close="closeInfo" /> -->
      </div>
    </template>
  </teleport>
</template>
<script setup lang="ts">
  import { ref, onMounted, nextTick, unref } from 'vue';
  import { useSceneStore, tagType } from '/@/store/modules/scene';
  import { computed } from 'vue';
  import { getApp, useApp } from '/@/hooks/userApp';
  import browser from '/@/utils/browser';
  // import { getApp, useApp } from '@/app';
  // import { useStore } from 'vuex';
  import { changeUrl } from './common';
  import { watchEffect } from 'vue';
  // import TagView from './tag-view.vue';
  import ShowTag from './show-tag.vue';
  const sceneStore = useSceneStore();
  const tags$ = ref('');
  const tags = computed(() => sceneStore.tags);

  const showInfo = ref<tagType | null>(null);
  const isClick = ref(false);
  const showMsg = ref(false);
  const isShowTag = computed(() => {
    return (tag: tagType) => {
      return showInfo.value && showInfo.value.sid === tag.sid;
    };
  });
  // const toggleIndex = ref(null)
  const openInfo = () => {
    showMsg.value = true;
    // store.commit('tag/setData', { isFixed: false, isClick: true });
    showInfo.value = null;
  };
  const closeInfo = () => {};

  const closeTag = async () => {
    showInfo.value = null;
    isClick.value = false;
  };

  const goTag = async (_, item: tagType) => {
    // const app = await useApp();
    if (unref(isClick)) {
      showInfo.value = null;
      isClick.value = false;
    } else {
      isClick.value = true;
      focusTag(item);
    }
  };
  const onMouseLeave = (_, tag: tagType) => {
    if (!unref(isClick) && showInfo.value?.sid === tag.sid) {
      showInfo.value = null;
    }
  };
  const onMouseEnter = (_, tag: tagType) => {
    showInfo.value = tag;
  };

  onMounted(async () => {
    const app = await useApp();
    app.TagManager.on('loaded', (data: any) => {
      console.log('data', data);
      sceneStore.loadTags(data);
    });
    watchEffect(() => {
      if (tags.value?.length) {
        app.TagManager.load(tags.value);
        app.TagManager.updatePosition(tags.value);
      }
    });
    app.Camera.on('flying.started', (pano) => {});
    // app.Scene.on('loadeddata', () => {
    //   if (browser.hasURLParam('t_id')) {
    //     let t_id = browser.getURLParam('t_id');
    //     for (let i = 0; i < tags.value.length; i++) {
    //       if (tags.value[i].sid == t_id) {
    //         goTag({}, tags.value[i], i);
    //       }
    //     }
    //   }
    // });
    // app.Camera.on('flying.ended', ({ targetPano }) => {
    // })
    await app.TagManager.tag();

    tags$.value = '[xui_tags]';

    if (app.config.mobile) {
      nextTick(() => {
        // let player = document.querySelector('.player')
        // player.addEventListener('touchstart', onClickHandler)
      });
    } else {
      // window.addEventListener('click', onClickHandler)
    }
  });
  const getUrl = (icon) => {
    let url =
      icon == '' || !icon ? getApp().resource.getAppURL('images/tag_icon_default.svg') : icon;
    // debugger;
    return changeUrl(url);
  };

  const focusTag = (tag: tagType) => {
    nextTick(async () => {
      const app = await useApp();
      let t = setTimeout(() => {
        clearTimeout(t);
        let tagBox = document.getElementById(`tagBox_${tag.sid}`);
        let arrowBox = document.getElementById(`arrow_${tag.sid}`);
        try {
          let tagBox_w = tagBox ? tagBox.getBoundingClientRect().width : 0;
          let tagBox_h = tagBox ? tagBox.getBoundingClientRect().height : 0;
          let arrowBox_w = arrowBox ? arrowBox.getBoundingClientRect().width : 0;
          let arrowBox_h = arrowBox ? arrowBox.getBoundingClientRect().height : 0;
          let params = {
            sid: tag.sid,
            tagBox: {
              width: tagBox_w,
              height: tagBox_h,
            },
            arrowBox: {
              width: arrowBox_w,
              height: arrowBox_h,
            },
          };

          let position = getApp().config.mobile ? 'center' : 'left';
          app.TagManager.focus(params, 'board', position);
        } catch (err) {}
      }, 300);
    });
  };
</script>

<style lang="scss">
  [is-mobile] .ui-view-layout [xui_tags] .content .trans {
    padding: 0;
  }
</style>
