<template>
  <div ref="cropPagePopupRef" @mousedown.stop="" @touchstart.stop="">
    <div v-if="showPopup && cropPagePopup.length" class="crop-page-popup popup" :class="{ 'transform': isTranslateX }" :style="{ top: `${top}px`, left: `${left}px` }">
      <template v-for="(item, index) in cropPagePopup" :key="`${item.dataElement || new Date()}-${index}`">
        <CustomButton v-if="item.name === 'customButton' && !item.hidden" :item="item" :data-element="item.dataElement" />
        <Button v-else-if="item.type === 'cropPage' && !item.hidden" @click="cropPage" :title="$t('header.download')" :data-element="item.dataElement"><Download /></Button>
        <Button v-else-if="item.type === 'close' && !item.hidden" @click="handlePopup('close')" :title="$t('exit')" :data-element="item.dataElement"><CloseA /></Button>
        <div v-else-if="['spacer', 'divider'].includes(item.type)" :class="item.type"></div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import core from '@/core'
import { useViewerStore } from '@/stores/modules/viewer'
import { useDocumentStore } from '@/stores/modules/document'

const useViewer = useViewerStore()
const useDocument = useDocumentStore()

const cropPagePopup = computed(() => useViewer.getPopupItems('cropPagePopup'))

const showPopup = ref(false)
const top = ref(0)
const left = ref(0)
const cropPagePopupRef = ref(null)
const isTranslateX = ref(true)

let documentContainer
let pageNumber
let cropRect

const handlePopup = (action) => {
  core.handleCropPagePopup(action)
}

const updatePopupPosition = async (data) => {
  const { rect, pageIndex } = data

  showPopup.value = !!rect
  pageNumber = pageIndex + 1

  await nextTick()

  useViewer.setDisableHeader(showPopup.value)
  if (showPopup.value) useViewer.resetPanels()

  if (rect && showPopup.value) {
    const popup = cropPagePopupRef.value?.children[0]
    if (!popup) return

    cropRect = rect

    // 计算弹窗的初始位置
    let initialLeft = rect.left + (rect.right - rect.left) / 2
    let initialTop = rect.bottom

    const popupWidth = popup.offsetWidth
    const popupHeight = popup.offsetHeight + 10

    const windowWidth = window.innerWidth
    const windowHeight = window.innerHeight

    isTranslateX.value = true

    // 检查水平位置
    if (initialLeft - popupWidth / 2 < 0) {
      initialLeft = 0
      isTranslateX.value = false
    } else if (initialLeft + popupWidth / 2 > windowWidth) {
      initialLeft = windowWidth - popupWidth
      isTranslateX.value = false
    }

    // 检查垂直位置
    if (initialTop + popupHeight > windowHeight) {
      initialTop = Math.max(0, rect.top - popupHeight)
    }

    top.value = initialTop
    left.value = initialLeft
  }
}
core.addEvent('snipSelected', updatePopupPosition)

// 截取选中区域
const cropPage = async () => {
  const startPoint = getMouseLocation(cropRect.left, cropRect.top)
  const endPoint = getMouseLocation(cropRect.right, cropRect.bottom)
  
  const startPagePoint = core.windowToPage(startPoint, pageNumber)
  const endPagePoint = core.windowToPage(endPoint, pageNumber)

  const data = {
    pageNumber,
    left: startPagePoint.x,
    top: startPagePoint.y,
    right: endPagePoint.x,
    bottom: endPagePoint.y
  }
  const imageUrl = await core.getPageAreaImage(data)
  exportImage(imageUrl)

  handlePopup('close')
}

// 下载图片
const exportImage = (url, filename) => {
  const a = document.createElement('a')
  a.href = url
  a.download = filename || 'image'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

const getMouseLocation = (x, y) => {
  const scrollElement = core.getScrollViewElement()
  const scrollLeft = scrollElement.scrollLeft || 0
  const scrollTop = scrollElement.scrollTop || 0

  return {
    x: x + scrollLeft,
    y: y + scrollTop
  }
}

const scrollHandler = () => {
  if (showPopup.value) showPopup.value = false
}

onMounted(() => {
  documentContainer = document.querySelector('.document-container')
  if (documentContainer) documentContainer.addEventListener('scroll', scrollHandler)
})

onUnmounted(() => {
  if (documentContainer) documentContainer.removeEventListener('scroll', scrollHandler)
})
</script>
