<template>
  <div 
    ref="popoverBoxRef" 
    id="popoverBox" 
    class="popoverBox el-popper is-light el-tooltip el-popover el-popover--plain"
    aria-hidden="false" 
    role="tooltip" 
    aria-label="Title" 
    data-popper-reference-hidden="false"
    data-popper-escaped="false" data-popper-placement="top"
  >
    <div class="el-popover__title" role="title" ref="titleRef"></div>
    <div class="el-popover__content" ref="contentRef" ></div>
    <span class="el-popper__arrow" data-popper-arrow="" style="position: absolute; left: 50%;"></span>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import * as Popper from '@popperjs/core'
import { getDetailByChunkId } from '@/servers/finyx/api/wendangfenduan'

const popoverBoxRef = ref<any>(null) // 弹窗容器
const hideTimeout = ref<any>(null) // 隐藏定时器
const currentDemo = ref<any>(null) // 当前激活的元素
const popperInstance = ref<any>(null) // Popper实例
const url = ref('')
const titleRef = ref<any>(null)
const contentRef = ref<any>(null)
const cacheChunkList = ref<any>({}) // 缓存分块数据

async function getDocumentId(chunkId: string) {
  const res = await getDetailByChunkId({chunkId})
  return res;
}

async function setContent(chunkId: string) {
   // 获取文档id-从缓存中获取 避免高频请求
   if (cacheChunkList.value[chunkId]  && cacheChunkList.value[chunkId] !== 'error') {
    // 缓存中存在数据，直接使用
    const chunk = cacheChunkList.value[chunkId]
    // url.value = `#/knowledge/dataset/viewParagraph?id=${chunk.documentId}&chunkId=${chunk.id}`
    url.value = `#/knowledge/dataset/traceabilityDetails?id=${chunk.documentId}&chunkId=${chunk.id}`
    // 设置tooltip内容
    const { content, name } = chunk
    titleRef.value.innerHTML = name
    contentRef.value.innerHTML = content
    titleRef.value.style.display = 'block'
  } else if (cacheChunkList.value[chunkId]  && cacheChunkList.value[chunkId] === 'error') {
    contentRef.value.innerHTML = '暂无溯源信息'
    titleRef.value.style.display = 'none'
  } else if (!cacheChunkList.value[chunkId]) {
    // 缓存中不存在数据，从接口获取
    getDocumentId(chunkId).then((res: any) => {
      // url.value = `#/knowledge/dataset/viewParagraph?id=${res.documentId}&chunkId=${res.id}`
      url.value = `#/knowledge/dataset/traceabilityDetails?id=${res.documentId}&chunkId=${res.id}`
      cacheChunkList.value[chunkId] = res
      // 设置tooltip内容
      const { content, name } = res
      titleRef.value.innerHTML = name
      contentRef.value.innerHTML = content
      titleRef.value.style.display = 'block'
    }).catch(() => {
      // MsgWarning('暂无溯源信息')
      cacheChunkList.value[chunkId] = 'error'
      titleRef.value.style.display = 'none'
      contentRef.value.innerHTML = '暂无溯源信息'
    })
  }
}
// 显示tooltip
function showTooltip(demoElement: any) {
  // 清除任何待处理的隐藏操作
  clearTimeout(hideTimeout.value);

  // 如果当前已经有激活的元素且是同一个，直接返回
  // if (currentDemo.value === demoElement) return;

  // 销毁现有的Popper实例
  if (popperInstance.value) {
    popperInstance.value.destroy();
    popperInstance.value = null;
  }

   // 清空之前的数据
  titleRef.value.innerHTML = ''
  titleRef.value.style.display = 'none'
  contentRef.value.innerHTML = '加载中...'
  url.value = ''

  // 更新当前激活的元素
  currentDemo.value = demoElement;
  const chunkId = currentDemo.value.attributes['data-id']?.value;
  // const contentText = currentDemo.value.attributes['data-content']?.value;
  if (!chunkId) {
    // 没有data-id或data-content属性，直接返回
    return
  }
  // 设置内容
  setContent(chunkId)

  // 显示tooltip
  popoverBoxRef.value.classList.add('show');

  // 创建新的Popper实例
  popperInstance.value = Popper.createPopper(demoElement, popoverBoxRef.value, {
    placement: 'top',
    modifiers: [
      {
        name: 'offset',
        options: {
          offset: [0, 10],
        },
      },
      {
        name: 'arrow',
        options: {
          element: '.tooltip-arrow',
        },
      },
    ],
  });
}

// 隐藏tooltip
function hideTooltip() {
    // 清除任何待处理的显示操作
    clearTimeout(hideTimeout.value);
    
    if (!popperInstance.value) return;
    
    // 设置延迟隐藏以实现平滑过渡
    hideTimeout.value = setTimeout(() => {
        popoverBoxRef.value.classList.remove('show');
        
        // 销毁Popper实例
        popperInstance.value.destroy();
        popperInstance.value = null;
        currentDemo.value = null;
    }, 300);
}

// 取消隐藏操作
function cancelHide() {
  clearTimeout(hideTimeout?.value);
}

/*事件委托处理鼠标进入 */
const handleMouseover = (e: any) => {
  const target = e.target;
  // 检查是否悬停在.custom-demo上
  if (target.classList.contains('custom-demo')) {
    cancelHide();
    showTooltip(target);
  }

  // 检查是否悬停在popoverBox上
  if (target.closest('#popoverBox')) {
    cancelHide();
  }
}

/*事件委托处理鼠标离开 */
const handelMouseout = (e: any) => {
  const target = e.target;
  const relatedTarget = e.relatedTarget;
  
  // 离开.custom-demo元素
  if (target.classList.contains('custom-demo')) {
    // 如果进入popoverBox，则不隐藏
    if (!relatedTarget || !popoverBoxRef.value.contains(relatedTarget)) {
      hideTooltip();
    }
  }
  
  // 离开popoverBox
  if (target.closest('#popoverBox')) {
    // 如果进入.custom-demo，则不隐藏
    if (!relatedTarget || !relatedTarget.classList.contains('custom-demo')) {
      hideTooltip();
    }
  }
}

onMounted(() => {
  const aiContent = document.querySelector('.ai-chat-content')
  /** 鼠标移入事件 */
  aiContent && aiContent.addEventListener('mouseover', handleMouseover)
  /** 鼠标移出事件 */
  aiContent && aiContent.addEventListener('mouseout', handelMouseout)

  contentRef.value.addEventListener('click', () => {
    if (url.value === '') {
      // MsgWarning('暂无溯源信息')
      return
    }
    window.open(url.value)
  })
})

onUnmounted(() => {
  const aiContent = document.querySelector('.ai-chat-content')
  /** 鼠标移入事件 */
  aiContent && aiContent.removeEventListener('mouseover', handleMouseover)
  /** 鼠标移出事件 */
  aiContent && aiContent.removeEventListener('mouseout', handelMouseout)
})


</script>

<style scoped lang="scss">
/** 对话页 弹框 自定样式 */
.popoverBox{
  display: none;
  max-width: 320px;
  .el-popover__title{
    color: rgba(0,0,0,0.85);
    font-weight: 500;
    font-size: 14px;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-box-orient: vertical;
    white-space: normal;
    cursor: pointer;
  }

  .el-popover__content{
    // margin-top: 6px;
    font-size: 12px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-box-orient: vertical;
    white-space: normal;
    color: rgba(0,0,0,0.35);
    cursor: pointer;
  }
}
.popoverBox.show{
  display: block;
}
</style>
