<template>
  <div class="pdf-page-container" ref="pageContainerRef">
    <div
      ref="pageRef"
      class="pdf-page-wrapper"
      @mouseup="handleMouseUp"
    >
      <!-- 使用iframe直接加载PDF，确保与主内容宽度一致 -->
      <iframe
        v-if="typeof pdfSource === 'string' || (typeof pdfSource === 'object' && pdfSource.url)"
        :src="typeof pdfSource === 'string' ? pdfSource : pdfSource.url"
        class="pdf-iframe"
      />
      <vue-pdf-embed
        v-else
        :source="pdfSource"
        :page="pageNumber"
        :scale="scale"
        @rendered="handlePageLoadSuccess"
        class="pdf-embed"
      />
      
      <div
        v-for="highlight in pageHighlights"
        :key="highlight.id"
      >
        <div
          v-for="(position, index) in highlight.positions"
          :key="`${highlight.id}-${index}`"
          class="highlight-overlay"
          :class="{ selected: highlight.id === selectedHighlightId }"
          :style="{
            backgroundColor: highlight.color + '60',
            borderColor: highlight.color,
            left: position.x1 * scale + 'px',
            top: position.y1 * scale + 'px',
            width: position.width * scale + 'px',
            height: position.height * scale + 'px'
          }"
          @click="(e) => {
            e.stopPropagation()
            onHighlightClick(highlight, e)
          }"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'

const props = defineProps({
  pageNumber: {
    type: Number,
    required: true
  },
  scale: {
    type: Number,
    default: 1
  },
  highlights: {
    type: Array,
    default: () => []
  },
  selectedHighlightId: {
    type: String,
    default: null
  },
  onHighlightClick: {
    type: Function,
    required: true
  },
  onAddHighlight: {
    type: Function,
    required: true
  },
  onTextContent: {
    type: Function,
    default: null
  },
  readOnly: {
    type: Boolean,
    default: false
  },
  pdfSource: {
    type: [String, Object, ArrayBuffer],
    required: true
  }
})

const pageContainerRef = ref(null)
const pageRef = ref(null)

const pageHighlights = computed(() => {
  return props.highlights.filter(h => h.pageNumber === props.pageNumber)
})

const mergeRects = (rects, pageRect, scale) => {
  if (rects.length === 0) return []

  const groups = []
  let currentGroup = [rects[0]]
  const threshold = 5

  for (let i = 1; i < rects.length; i++) {
    const currentRect = rects[i]
    const lastRectInGroup = currentGroup[currentGroup.length - 1]

    const currentCenterY = (currentRect.top + currentRect.bottom) / 2
    const groupCenterY = (lastRectInGroup.top + lastRectInGroup.bottom) / 2

    if (Math.abs(currentCenterY - groupCenterY) < threshold) {
      currentGroup.push(currentRect)
    } else {
      groups.push(currentGroup)
      currentGroup = [currentRect]
    }
  }

  if (currentGroup.length > 0) {
    groups.push(currentGroup)
  }

  const mergedPositions = groups.map((group) => {
    const minX = Math.min(...group.map(r => r.left))
    const minY = Math.min(...group.map(r => r.top))
    const maxX = Math.max(...group.map(r => r.right))
    const maxY = Math.max(...group.map(r => r.bottom))

    const x1 = minX - pageRect.left
    const y1 = minY - pageRect.top
    const x2 = maxX - pageRect.left
    const y2 = maxY - pageRect.top

    return {
      x1: Math.max(0, x1) / scale,
      y1: Math.max(0, y1) / scale,
      x2: x2 / scale,
      y2: y2 / scale,
      width: (x2 - Math.max(0, x1)) / scale,
      height: (y2 - Math.max(0, y1)) / scale
    }
  })

  return mergedPositions
}

const handlePageLoadSuccess = (pdfPage) => {
  if (props.onTextContent) {
    pdfPage.getTextContent().then((textContent) => {
      props.onTextContent(props.pageNumber, textContent)
    }).catch((error) => {
      console.error('Error getting text content:', error)
    })
  }
}

const handleMouseUp = () => {
  if (props.readOnly) return

  const selection = window.getSelection()
  if (!selection || selection.toString().trim() === '') {
    return
  }

  const range = selection.getRangeAt(0)
  
  const pageRect = pageRef.value?.getBoundingClientRect()
  if (!pageRect) return

  const rects = range.getClientRects()
  if (rects.length === 0) {
    selection.removeAllRanges()
    return
  }

  const positions = mergeRects(Array.from(rects), pageRect, props.scale)

  const firstRect = rects[0]
  const screenPosition = {
    x: firstRect.left + firstRect.width / 2,
    y: firstRect.bottom + 10
  }

  const newHighlight = {
    type: 'text',
    pageNumber: props.pageNumber,
    positions,
    content: selection.toString(),
    color: '#ffeb3b',
    screenPosition
  }

  props.onAddHighlight(newHighlight)
  selection.removeAllRanges()
}
</script>

<style scoped>
@import './pdfReader.css';

.pdf-page-container {
  display: flex;
  justify-content: center;
  margin-bottom: var(--space-md);
  padding: var(--space-md);
  max-width: 1200px;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  background: var(--bg-card);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-light);
}

.pdf-page-wrapper {
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
}

.pdf-iframe {
  width: 100%;
  min-height: 98vh;
  height: auto;
  border: none;
  border-radius: var(--radius-md);
  background: var(--bg-card);
}

.pdf-embed {
  max-width: 100%;
  display: block;
  margin: 0 auto;
}

.highlight-overlay {
  position: absolute;
  pointer-events: auto;
  cursor: pointer;
  border-radius: var(--radius-sm);
  transition: all 0.3s ease;
  z-index: 10;
  border: 2px solid transparent;
}

.highlight-overlay.selected {
  border-style: solid;
}
</style>