<template>
  <teleport :to="tags$" v-if="tags$">
    <template v-for="tag 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)"
          :style="{ 'background-image': 'url(' + getUrl(tag.icon) + ')' }"
        ></span>
        <div class="content">
          <div
            class="trans"
            :class="{
              active: isShowTag(tag),
            }"
          >
            <template v-if="tag && !showLayer">
              <div class="arrow" :id="`arrow_${tag.sid}`">
                <i
                  @click.stop="closeTag"
                  v-if="isMobile"
                  class="iconfont ui-kankan-icon icon tip-h-center tip-v-bottom icon-close"
                ></i>
              </div>
              <ShowTag :show="isShowTag(tag)" :tag="tag" v-if="tag" @open="openLayer(tag)" />
            </template>
          </div>
        </div>

        <TagView :data="tag" v-if="showLayer && isShowTag(tag)" @close="closeLayer" />
      </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 TagView from './tag-view.vue';
  // import { getApp, useApp } from '@/app';
  // import { useStore } from 'vuex';
  import { changeUrl } from './common';
  import { watchEffect } from 'vue';

  import ShowTag from './show-tag.vue';
  const sceneStore = useSceneStore();
  const tags$ = ref('');
  const tags = computed(() => sceneStore.tags);

  const currentTag = ref<tagType | null>(null);
  const isClick = ref(false);
  const showLayer = ref(false);
  const emit = defineEmits(['setCurrentTag']);

  const isShowTag = computed(() => {
    return (tag: tagType) => {
      return currentTag.value ? currentTag.value.sid === tag.sid : false;
    };
  });
  const isMobile = computed(() => browser.isMobile());

  const openLayer = (tag: tagType) => {
    showLayer.value = true;
    currentTag.value = tag;
    emit('setCurrentTag', tag);
    console.error('open-layer');
  };
  const closeLayer = () => {
    showLayer.value = false;
    currentTag.value = null;
    emit('setCurrentTag', null);
    console.error('close-layer');
  };

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

  const goTag = (_, item: tagType) => {
    console.warn('gototag', item.sid);
    showLayer.value = false;
    if (unref(isClick)) {
      currentTag.value = null;
      isClick.value = false;
    } else {
      currentTag.value = item;
      isClick.value = true;
      try {
        focusTag(item);
      } catch (error) {
        console.log('error', error);
      }
    }
  };
  const onMouseLeave = (_, tag: tagType) => {
    if (
      !unref(isMobile) &&
      !unref(isClick) &&
      currentTag.value?.sid === tag.sid &&
      !unref(showLayer)
    ) {
      currentTag.value = null;
      sceneStore.setCurrentTag(null);
    }
  };
  const onMouseEnter = (_, tag: tagType) => {
    if (!unref(isMobile)) {
      sceneStore.setCurrentTag(tag);
      currentTag.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.Camera.on('flying.ended', ({ targetPano }) => {});
    await app.TagManager.tag();

    tags$.value = '[xui_tags]';

    if (unref(isMobile)) {
      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(() => {
      const app = getApp();
      // console.error('focusTag-1');
      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 = isMobile.value ? '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>
