<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import Hammer from 'hammerjs'
import VueLazyload from 'vue-lazyload'

// 组件属性
const props = defineProps({
  // 图片URL
  imageUrl: {
    type: String,
    required: true
  },
  // 图片描述
  description: {
    type: String,
    default: ''
  },
  // 是否自动加载
  autoLoad: {
    type: Boolean,
    default: true
  },
  // 初始缩放比例
  initialZoom: {
    type: Number,
    default: 1
  },
  // 最小缩放比例
  minZoom: {
    type: Number,
    default: 0.5
  },
  // 最大缩放比例
  maxZoom: {
    type: Number,
    default: 3
  }
})

// 组件事件
const emit = defineEmits(['load', 'error', 'zoom', 'pan', 'click'])

// 图片加载状态
const imageLoaded = ref(false)
const imageError = ref(false)
const loading = ref(props.autoLoad)

// 图片尺寸
const imageWidth = ref(0)
const imageHeight = ref(0)

// 缩放和平移状态
const scale = ref(props.initialZoom)
const x = ref(0)
const y = ref(0)
const lastScale = ref(1)
const lastX = ref(0)
const lastY = ref(0)

// 查看器容器引用
const viewerContainer = ref(null)
const imageElement = ref(null)

// 计算图片显示尺寸
const displayWidth = computed(() => {
  return imageWidth.value * scale.value
})

const displayHeight = computed(() => {
  return imageHeight.value * scale.value
})

// 计算图片样式
const imageStyle = computed(() => {
  return {
    width: `${displayWidth.value}px`,
    height: `${displayHeight.value}px`,
    transform: `translate3d(${x.value}px, ${y.value}px, 0) scale3d(${scale.value}, ${scale.value}, 1)`,
    transition: 'transform 0.1s ease-out'
  }
})

// 图片加载完成处理
const handleImageLoad = (e) => {
  const img = e.target
  imageWidth.value = img.naturalWidth
  imageHeight.value = img.naturalHeight
  imageLoaded.value = true
  loading.value = false
  emit('load', { width: imageWidth.value, height: imageHeight.value })
}

// 图片加载失败处理
const handleImageError = (e) => {
  imageError.value = true
  loading.value = false
  emit('error', e)
  uni.showToast({title: '图片加载失败', duration: 2000})
}

// 重新加载图片
const reloadImage = () => {
  imageError.value = false
  loading.value = true
  if (imageElement.value) {
    imageElement.value.src = props.imageUrl + '?' + new Date().getTime()
  }
}

// 重置查看器状态
const resetViewer = () => {
  scale.value = props.initialZoom
  x.value = 0
  y.value = 0
  lastScale.value = 1
  lastX.value = 0
  lastY.value = 0
}

// 计算边界限制
const calculateBounds = () => {
  if (!viewerContainer.value) return { minX: 0, maxX: 0, minY: 0, maxY: 0 }
  
  const containerWidth = viewerContainer.value.clientWidth
  const containerHeight = viewerContainer.value.clientHeight
  
  const minX = Math.max(containerWidth - displayWidth.value, 0)
  const maxX = Math.min(0, containerWidth - displayWidth.value)
  const minY = Math.max(containerHeight - displayHeight.value, 0)
  const maxY = Math.min(0, containerHeight - displayHeight.value)
  
  return { minX, maxX, minY, maxY }
}

// 限制平移范围
const constrainTranslation = () => {
  const bounds = calculateBounds()
  
  x.value = Math.max(bounds.minX, Math.min(bounds.maxX, x.value))
  y.value = Math.max(bounds.minY, Math.min(bounds.maxY, y.value))
}

// 处理缩放
const handleZoom = (newScale, centerX = 0, centerY = 0) => {
  const oldScale = scale.value
  const deltaScale = newScale / oldScale
  
  // 调整平移位置以保持缩放中心
  x.value = centerX - (centerX - x.value) * deltaScale
  y.value = centerY - (centerY - y.value) * deltaScale
  
  scale.value = Math.max(props.minZoom, Math.min(props.maxZoom, newScale))
  constrainTranslation()
  
  emit('zoom', { scale: scale.value, centerX, centerY })
}

// 处理平移
const handlePan = (deltaX, deltaY) => {
  x.value = lastX.value + deltaX
  y.value = lastY.value + deltaY
  constrainTranslation()
  
  emit('pan', { x: x.value, y: y.value, deltaX, deltaY })
}

// 双击放大/缩小
const handleDoubleTap = (e) => {
  if (scale.value > props.initialZoom) {
    resetViewer()
  } else {
    const rect = viewerContainer.value.getBoundingClientRect()
    const centerX = e.center.x - rect.left
    const centerY = e.center.y - rect.top
    handleZoom(props.initialZoom * 2, centerX, centerY)
  }
}

// 点击事件
const handleClick = () => {
  emit('click')
}

// 初始化Hammer.js手势识别
const initGestureRecognizer = () => {
  if (!viewerContainer.value) return
  
  const hammer = new Hammer.Manager(viewerContainer.value)
  
  // 添加手势识别器
  const pan = new Hammer.Pan({ threshold: 0, pointers: 0 })
  const pinch = new Hammer.Pinch({ threshold: 0 })
  const tap = new Hammer.Tap()
  const doubleTap = new Hammer.Tap({ taps: 2 })
  
  // 配置手势识别器
  tap.recognizeWith(doubleTap)
  doubleTap.requireFailure(tap)
  
  // 将手势识别器添加到管理器
  hammer.add([pan, pinch, tap, doubleTap])
  
  // 启用多点触摸
  pan.set({ enable: true })
  pinch.set({ enable: true })
  
  // 手势事件处理
  hammer.on('pinchstart', (e) => {
    lastScale.value = scale.value
  })
  
  hammer.on('pinchmove', (e) => {
    const newScale = lastScale.value * e.scale
    handleZoom(newScale, e.center.x, e.center.y)
  })
  
  hammer.on('panstart', (e) => {
    lastX.value = x.value
    lastY.value = y.value
  })
  
  hammer.on('panmove', (e) => {
    handlePan(e.deltaX, e.deltaY)
  })
  
  hammer.on('panend', () => {
    lastX.value = x.value
    lastY.value = y.value
  })
  
  hammer.on('tap', handleClick)
  hammer.on('doubletap', handleDoubleTap)
  
  return hammer
}

// 组件挂载后初始化
onMounted(() => {
  // 初始化手势识别
  const hammer = initGestureRecognizer()
  
  // 监听窗口大小变化
  const handleResize = () => {
    constrainTranslation()
  }
  
  window.addEventListener('resize', handleResize)
  
  // 清理函数
  onUnmounted(() => {
    if (hammer) {
      hammer.destroy()
    }
    window.removeEventListener('resize', handleResize)
  })
})

// 监听图片URL变化
watch(() => props.imageUrl, () => {
  imageLoaded.value = false
  imageError.value = false
  loading.value = true
  resetViewer()
})

// 全屏查看状态
const isFullscreen = ref(false)

// 打开全屏查看
const openFullscreen = () => {
  if (!imageLoaded.value) {
    uni.showToast({title: '图片加载中，请稍候...', duration: 2000})
    return
  }
  isFullscreen.value = true
}

// 关闭全屏查看
const closeFullscreen = () => {
  isFullscreen.value = false
}

// 阻止 iOS 滚动穿透
const handleTouchMove = (e) => {
  e.preventDefault()
}
</script>

<template>
  <div class="long-image-viewer" ref="viewerContainer" @click="handleClick">
    <!-- 加载状态 -->
    <div class="loading-overlay" v-if="loading">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
    
    <!-- 错误状态 -->
    <div class="error-overlay" v-else-if="imageError">
      <div class="error-icon">❌</div>
      <div class="error-text">图片加载失败</div>
      <button class="reload-btn" @click="reloadImage">重试</button>
    </div>
    
    <!-- 图片容器 -->
    <div class="image-container" v-else-if="imageLoaded">
      <img
        ref="imageElement"
        v-lazy="imageUrl"
        class="long-image"
        :style="imageStyle"
        @load="handleImageLoad"
        @error="handleImageError"
      />
    </div>
    
    <!-- 图片描述 -->
    <div class="image-description" v-if="description">
      {{ description }}
    </div>
    
    <!-- 操作按钮 -->
    <div class="action-buttons">
      <button class="action-btn" @click="reloadImage" v-if="imageLoaded">
        🔄
      </button>
      <button class="action-btn" @click="resetViewer" v-if="imageLoaded">
        🔍
      </button>
      <button class="action-btn" @click="openFullscreen" v-if="imageLoaded">
        🖼️
      </button>
    </div>
  </div>
  
  <!-- 全屏查看模态框 -->
  <uni-popup v-model="isFullscreen" mode="full" closeable="false">
    <div class="fullscreen-container" @click="closeFullscreen" @touchmove="handleTouchMove">
      <div class="fullscreen-header">
        <h2>查看图片</h2>
        <button class="close-btn" @click.stop="closeFullscreen">关闭</button>
      </div>
      <div class="fullscreen-content">
        <img
          :src="imageUrl"
          class="fullscreen-image"
        />
      </div>
    </div>
  </uni-popup>
</template>

<style scoped>
.long-image-viewer {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #f5f5f5;
  touch-action: pan-y;
  user-select: none;
  -webkit-user-drag: none;
}

.image-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.long-image {
  position: absolute;
  top: 0;
  left: 0;
  max-width: none;
  max-height: none;
  transform-origin: center center;
  will-change: transform;
}

.loading-overlay,
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
}

.loading-spinner {
  width: 0.6rem;
  height: 0.6rem;
  border: 0.08rem solid #ff6b35;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 0.2rem;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text,
.error-text {
  font-size: 0.28rem;
  color: #666;
  margin-top: 0.1rem;
}

.error-icon {
  font-size: 0.8rem;
  margin-bottom: 0.2rem;
}

.reload-btn {
  margin-top: 0.3rem;
  padding: 0.15rem 0.3rem;
  font-size: 0.28rem;
  color: #fff;
  background-color: #ff6b35;
  border: none;
  border-radius: 0.15rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.reload-btn:hover {
  background-color: #ff5216;
}

.image-description {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0.2rem;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 0.28rem;
  text-align: center;
  z-index: 5;
}

.action-buttons {
  position: absolute;
  top: 0.2rem;
  right: 0.2rem;
  display: flex;
  flex-direction: column;
  gap: 0.1rem;
  z-index: 5;
}

.action-btn {
  width: 0.6rem;
  height: 0.6rem;
  border: none;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  font-size: 0.32rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.action-btn:hover {
  background-color: #fff;
  transform: scale(1.1);
}

/* 全屏查看模态框样式 */
.fullscreen-container {
  width: 100vw;
  height: 100vh;
  background-color: #000;
  color: #fff;
}

.fullscreen-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 100;
}

.fullscreen-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.close-btn {
  background-color: transparent;
  color: #fff;
  border: 1px solid #fff;
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

.fullscreen-content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
  padding: 80px 20px 20px;
  box-sizing: border-box;
}

.fullscreen-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style>