<template>
  <div v-if="props.modelValue" class="mask" @click.stop="emits('update:modelValue', false)">
    <div ref="imgBoxRef" class="img-box" @click.stop="false">
      <img :src="url || `${OSS_URL}/urm/book_bg.svg`" />
    </div>
  </div>
</template>

<script setup lang="ts">
import Hammer from 'hammerjs'

const props = withDefaults(
  defineProps<{
    modelValue: boolean
    url?: string
  }>(),
  {},
)
const emits = defineEmits(['update:modelValue'])

const OSS_URL = import.meta.env.VITE_OSS_URL

const imgBoxRef = ref()

const imgConfig = reactive({
  scaleIndex: 1,
  scaleCount: 1,
})

function init() {
  nextTick(() => {
    let x = 0
    let y = 0
    let _node = imgBoxRef.value // 获取之前在模板中设置的ref属性

    let hand = new Hammer(_node) // 创建一个新的Hammer实例，传入要进行手势操作的元素

    // 启用pinch手势
    hand.get('pinch').set({ enable: true })

    // 监听pinch手势的不同事件，用于实现缩放功能
    hand.on('pinchmove pinchstart pinchin pinchout', (e: anyObj) => {
      if (e.type === 'pinchstart') {
        imgConfig.scaleIndex = imgConfig.scaleCount || 1 // 记录当前的缩放比例
      }
      imgConfig.scaleCount = imgConfig.scaleIndex * e.scale // 计算新的缩放比例
      _node.style.transform = 'scale(' + imgConfig.scaleIndex * e.scale + ')' // 应用缩放效果
    })
    // 监听doubletap手势，双击重置缩放和位置
    // hand.on('doubletap', () => {
    //     x = 0;
    //     y = 0;
    //     imgConfig.scaleCount = 1; // 重置缩放比例为1
    //     _node.style.transform = 'translateX(0px) translateY(0px) scale(1)'; // 重置位置和缩放效果
    // });
    // 监听tap手势，单击
    hand.on('tap', () => {
      setTimeout(() => {
        emits('update:modelValue', false)
      }, 50)
    })

    // 监听pan手势，用于实现拖动功能
    hand.on('panright panleft panup pandown', (e: anyObj) => {
      _node.style.transform =
        'translateX(' +
        (e.deltaX + x) +
        'px)' +
        'translateY(' +
        (e.deltaY + y) +
        'px)' +
        'scale(' +
        imgConfig.scaleCount * e.scale +
        ')' // 应用拖动和缩放效果
    })

    // 监听panend手势，用于记录拖动的偏移量，以便在下一次拖动时保持连续性
    hand.on('panend', (e: anyObj) => {
      x = e.deltaX + x // 记录水平方向上的偏移量
      y = e.deltaY + y // 记录垂直方向上的偏移量
    })
  })
}

watch(
  () => props.modelValue,
  show => {
    if (show) {
      init()
    }
  },
  { immediate: true },
)
</script>

<style lang="scss" scoped>
.mask {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10000;
  width: 100vw;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.45);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  background-repeat: no-repeat;
  background-size: 100vw 623px;
  background-position: center;
  .img-box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      max-width: 100%;
      max-height: 100%;
      min-width: 300px;
      min-height: 16.67vh;
      object-fit: contain;
    }
  }
}
</style>
