<script setup lang="ts">
import { ref, toRefs } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'
import 'vue-pdf-embed/dist/styles/annotationLayer.css'
import 'vue-pdf-embed/dist/styles/textLayer.css'
import { debounce } from 'lodash'

/**
 * pdf预览组件
 * 支持高亮指定内容
 */
interface PDFViewProps {
  url: string // 文件地址
  highLightContent?: string // 需要高亮的内容
}

const props = defineProps<PDFViewProps>()
const { url, highLightContent } = toRefs(props)
const pdfViewerRef = ref<any>(null)

const handleScrollToView = debounce(
  (element: Element) => {
    element?.scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    })
  },
  1000,
  { leading: true, trailing: false }
)
const handlePdfLoaded = (): void => {
  // 加载完成后可操作PDF实例
  if (highLightContent.value) {
    const container = document.getElementById('pdfViewerRef')
    if (container == null) return
    // 获取所有span元素
    const spans = container.getElementsByTagName('span')
    Array.from(spans).forEach((span) => {
      const text = span?.textContent?.trim() ?? ''
      // 检查内容是否在highLightContent数组中
      if (
        (text?.length ?? 0) > 4 &&
        /[a-zA-Z\u4e00-\u9fa5]/.test(text) &&
        highLightContent.value?.includes(text)
      ) {
        try {
          handleScrollToView(span)
          span.style.backgroundColor = '#ff06' // 设置高亮背景色
        } catch (e) {
          console.log('handleScrollToView error: ', e)
        }
      }
    })
  }
}

const onProcess = (e) => {
  // console.log('onProcess: ', e)
}

const onLoaded = (doc: any) => {
  console.log('onLoaded: ', doc)
}
</script>

<template>
  <VuePdfEmbed
    id="pdfViewerRef"
    ref="pdfViewerRef"
    class="pdf-view"
    annotation-layer
    text-layer
    :source="url"
    @progress="onProcess"
    @loaded="onLoaded"
    @rendered="handlePdfLoaded"
  />
</template>

<style scoped lang="scss">
.pdf-view {
  width: 100%;
  height: 100%;
}
</style>
