<template>
  <div class="pdf-reader">
    <div class="pdf-content" ref="contentRef">
      <div class="pdf-page-container">
        <div class="pdf-page-wrapper" ref="pdfWrapper" @mousedown="handleMouseDown" @mouseup="handleMouseUp">
          <div class="pdf-page" ref="pageRef" :style="{ transform: `scale(${scale})`, transformOrigin: 'top center' }">
            <iframe
              :src="pdfUrl"
              class="pdf-iframe"
              @load="onPdfLoad"
              ref="pdfIframe"
            ></iframe>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const props = defineProps({
  src: {
    type: String,
    required: true,
  },
  scale: {
    type: Number,
    default: 1.0,
  },
  highlights: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['update:scale', 'text-selected'])

const pdfUrl = ref('')
const contentRef = ref(null)
const pdfWrapper = ref(null)
const pageRef = ref(null)
const pdfIframe = ref(null)

function onPdfLoad() {
  nextTick(() => {
    // PDF加载完成
  })
}

function handleMouseDown() {
  // 鼠标按下时的处理
}

function handleMouseUp() {
  setTimeout(() => {
    let text = ''
    
    try {
      const selection = window.getSelection()
      if (selection.rangeCount) {
        text = selection.toString().trim()
      }
      
      if (!text && pdfIframe.value && pdfIframe.value.contentWindow) {
        const iframeSelection = pdfIframe.value.contentWindow.getSelection()
        if (iframeSelection.rangeCount) {
          text = iframeSelection.toString().trim()
        }
      }
    } catch (e) {
      console.error('获取选中文本失败:', e)
    }
    
    if (text) {
      emit('text-selected', text)
    }
  }, 10)
}

onMounted(() => {
  pdfUrl.value = props.src
  nextTick(() => {
    // 组件挂载完成
  })
})

watch(
  () => props.src,
  (newSrc) => {
    if (newSrc) {
      pdfUrl.value = newSrc
      nextTick(() => {
        // 源文件变化
      })
    }
  }
)
</script>

<style scoped>
.pdf-reader {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.pdf-content {
  flex: 1;
  overflow: auto;
  padding: 28px 24px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: linear-gradient(135deg, #f0f2f5 0%, #e6e9f0 100%);
  background-attachment: fixed;
}

.pdf-page-container {
  display: flex;
  justify-content: center;
}

.pdf-page-wrapper {
  position: relative;
}

.pdf-page {
  position: relative;
  background: #fff;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12), 0 0 0 1px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  transition: transform 0.2s ease;
}

.pdf-iframe {
  display: block;
  border: none;
  border-radius: 6px;
  width: 1200px;
  height: 1600px;
}
</style>
