<template>
  <div v-if="visible">
    <!-- 提示框本体 -->
    <div ref="tipsBoxRef" class="chart-tips-box" @click.stop @mousedown="handleMouseDown">
      <!-- 标题栏 - 可拖拽区域 -->
      <div class="tips-header drag-handle" @mousedown="handleDragStart">
        <span class="tips-title">{{ data.title }}</span>
        <button class="close-btn" @click="$emit('close')">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
          </svg>
        </button>
      </div>

      <!-- 数据列表 -->
      <div class="tips-content">
        <div v-for="(item, index) in data.items" :key="index" class="tips-item"
          :class="{ 'is-summary': item.name.includes('汇总') }">
          <div class="item-left">
            <div class="color-indicator" :style="{ backgroundColor: item.color }"></div>
            <span class="item-name">{{ item.name }}</span>
          </div>
          <div class="item-right">
            <span class="item-value">{{ formatNumber(item.value) }}</span>
            <span class="item-percent">{{ item.percent }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({
      title: '',
      items: []
    })
  }
})

// Emits
const emit = defineEmits(['close'])

// 拖拽相关
const tipsBoxRef = ref(null)
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })
const position = ref({ x: 0, y: 0 })

// 全局点击关闭处理
const handleGlobalClick = (event) => {
  if (!props.visible) return

  // 如果点击的是提示框内部，不关闭
  if (tipsBoxRef.value && tipsBoxRef.value.contains(event.target)) {
    return
  }

  // 点击外部区域，关闭提示框
  emit('close')
}

// 生命周期
onMounted(() => {
  // 监听全局点击事件
  document.addEventListener('click', handleGlobalClick, true)
})



// 格式化数字
function formatNumber(value) {
  if (typeof value !== 'number') return value
  return value.toLocaleString()
}

// 拖拽开始
function handleDragStart(event) {
  if (!tipsBoxRef.value) return

  isDragging.value = true
  const rect = tipsBoxRef.value.getBoundingClientRect()
  dragOffset.value = {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top
  }

  // 阻止默认的文本选择行为
  event.preventDefault()

  // 添加全局鼠标事件监听
  document.addEventListener('mousemove', handleDragMove)
  document.addEventListener('mouseup', handleDragEnd)
}

// 拖拽移动
function handleDragMove(event) {
  if (!isDragging.value || !tipsBoxRef.value) return

  // 计算新位置
  let newX = event.clientX - dragOffset.value.x
  let newY = event.clientY - dragOffset.value.y

  // 获取窗口尺寸和弹窗尺寸
  const windowWidth = window.innerWidth
  const windowHeight = window.innerHeight
  const boxRect = tipsBoxRef.value.getBoundingClientRect()

  // 限制拖拽范围，确保弹窗不会超出视窗
  newX = Math.max(0, Math.min(newX, windowWidth - boxRect.width))
  newY = Math.max(0, Math.min(newY, windowHeight - boxRect.height))

  position.value = { x: newX, y: newY }

  // 应用位置
  tipsBoxRef.value.style.left = `${newX}px`
  tipsBoxRef.value.style.top = `${newY}px`
  tipsBoxRef.value.style.transform = 'none'
}

// 拖拽结束
function handleDragEnd() {
  isDragging.value = false

  // 移除全局事件监听
  document.removeEventListener('mousemove', handleDragMove)
  document.removeEventListener('mouseup', handleDragEnd)
}

// 重置位置
function resetPosition() {
  if (tipsBoxRef.value) {
    position.value = { x: 0, y: 0 }
    tipsBoxRef.value.style.left = '50%'
    tipsBoxRef.value.style.top = '15vh'
    tipsBoxRef.value.style.transform = 'translateX(-50%)'
  }
}

// 监听visible变化，重置位置
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 延迟重置位置，确保DOM已渲染
    nextTick(() => {
      resetPosition()
    })
    // 添加键盘事件监听
    document.addEventListener('keydown', handleKeyDown)
  } else {
    // 移除键盘事件监听
    document.removeEventListener('keydown', handleKeyDown)
  }
})

// 处理键盘事件
function handleKeyDown(event) {
  // ESC 键关闭提示框
  if (event.key === 'Escape') {
    emit('close')
  }
}

// 处理鼠标按下事件（阻止冒泡）
function handleMouseDown(event) {
  // 只有在标题栏区域才允许拖拽
  if (event.target.closest('.drag-handle')) {
    return
  }
  // 阻止事件冒泡，但不阻止页面其他区域的点击
  event.stopPropagation()
}

// 组件卸载时清理事件监听
const cleanup = () => {
  document.removeEventListener('mousemove', handleDragMove)
  document.removeEventListener('mouseup', handleDragEnd)
  document.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('click', handleGlobalClick, true)
}

onUnmounted(() => {
  cleanup()
})
</script>

<style scoped>
/* 移除遮罩层样式，不再需要 */

.chart-tips-box {
  background: #1a1a1a;
  border-radius: 8px;
  min-width: 400px;
  max-width: 600px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
  overflow: hidden;
  animation: slideDown 0.3s ease-out;
  position: fixed;
  z-index: 10001;

  /* 默认居中位置 */
  left: 50%;
  top: 15vh;
  transform: translateX(-50%);
}

/* 拖拽时的样式 */
.chart-tips-box.dragging {
  user-select: none;
  cursor: grabbing;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.tips-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #1a1a1a;
  border-bottom: 1px solid #333;
  cursor: grab;
  user-select: none;
}

.tips-header:active {
  cursor: grabbing;
}

.tips-title {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
}

.tips-content {
  padding: 8px 0;
  max-height: 400px;
  overflow-y: auto;
}

.tips-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  transition: background-color 0.2s;
}

.tips-item:hover {
  background: rgba(255, 255, 255, 0.05);
}

.tips-item.is-summary {
  border-top: 1px solid #333;
  background: rgba(255, 255, 255, 0.02);
}

.item-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.color-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 12px;
  flex-shrink: 0;
}

.item-name {
  color: #fff;
  font-size: 14px;
  line-height: 1.4;
}

.item-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.item-value {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  min-width: 80px;
  text-align: right;
}

.item-percent {
  color: #4ade80;
  font-size: 14px;
  font-weight: 500;
  min-width: 60px;
  text-align: right;
  background: rgba(74, 222, 128, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  border: 1px solid rgba(74, 222, 128, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-tips-box {
    min-width: 90vw;
    max-width: 90vw;
    left: 50%;
    transform: translateX(-50%);
  }

  .tips-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .item-right {
    width: 100%;
    justify-content: space-between;
  }

  .item-value,
  .item-percent {
    min-width: auto;
  }
}

/* 滚动条样式 */
.tips-content::-webkit-scrollbar {
  width: 6px;
}

.tips-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.tips-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.tips-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>