<template>
  <transition name="fade">
    <div
      v-if="visible"
      class="preview-modal"
      @click.self="closePreview"
      ref="previewContainer"
    >

      <a-row>
        <a-col :span="4">
        </a-col>
        <a-col :span="16" class="preview-toolbar" style="padding-bottom: 0px; border-bottom: solid #0057FE;">
          <a-button type="primary" style="background-color: #0057FE; color:white ;">影像胶片</a-button>
        </a-col>
        <a-col :span="4">
          <!-- 顶部功能区 -->
          <div class="preview-toolbar">
            <button @click="zoomIn" title="放大">+</button>
            <button @click="zoomOut" title="缩小">-</button>
            <button @click="rotateLeft" title="左旋转">↺</button>
            <button @click="rotateRight" title="右旋转">↻</button>
            <button @click="resetTransform" title="重置">↻</button>
            <button @click="closePreview" title="关闭" class="close-btn">×</button>
          </div>
        </a-col>
      </a-row>
      <!-- 主图片区域 -->
      <div
        class="preview-content"
        @mousedown="startDrag"
        @mousemove="onDrag"
        @mouseup="stopDrag"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="stopDrag"
      >
        <div v-if="isLoading" class="loading-indicator">加载中...</div>
        <img
          :src="currentImage"
          :style="imageStyle"
          class="preview-image"
          @wheel.prevent="handleWheel"
          @load="isLoading = false"
          @error="handleImageError"
        />
      </div>

      <!-- 底部缩略图导航 -->
      <div class="thumbnail-navigation">
        <div
          v-for="(img, index) in imgList"
          :key="index"
          :class="['thumbnail-nav-item', { active: currentIndex === index }]"
          @click="switchImage(index)"
        >
          <img :src="img" class="thumbnail-nav-image" alt="缩略图" v-lazy="img" />
        </div>
      </div>
      <div class="thumbnail-description">
        <p>当前查看第<span class="thumbnail-description-sapn">{{ currentIndex + 1 }}</span>张胶片，共<span class="thumbnail-description-sapn">{{ imgList.length }}</span>张胶片</p>
      </div>
    </div>
  </transition>
</template>

<script>

export default {
  name: 'ImagePreview',
  props: {
    visible: { type: Boolean, default: false },
    imgList: { type: Array, default: () => [] },
    initialIndex: { type: Number, default: 0 }
  },
  data () {
    return {
      currentIndex: this.initialIndex,
      scale: 1,
      rotate: 0,
      position: { x: 0, y: 0 },
      isDragging: false,
      startDragPosition: { x: 0, y: 0 },
      touchStartX: 0,
      touchStartY: 0,
      initialDistance: null,
      isLoading: true,
      maxDragX: 0,
      maxDragY: 0
    }
  },
  computed: {
    currentImage () {
      return this.imgList[this.currentIndex] || ''
    },
    imageStyle () {
      return {
        transform: `scale(${this.scale}) rotate(${this.rotate}deg) translate(${this.position.x}px, ${this.position.y}px)`,
        transition: this.isDragging ? 'none' : 'transform 0.3s ease',
        cursor: this.isDragging ? 'grabbing' : 'grab'
      }
    }
  },
  watch: {
    visible (newVal) {
      if (newVal) {
        document.body.style.overflow = 'hidden'
        document.addEventListener('keydown', this.handleKeyDown)
        // 计算最大拖拽边界
        this.$nextTick(() => {
          const container = this.$refs.previewContainer
          if (container) {
            this.maxDragX = (container.clientWidth * this.scale - container.clientWidth) / 2
            this.maxDragY = (container.clientHeight * this.scale - container.clientHeight) / 2
          }
        })
      } else {
        document.body.style.overflow = ''
        document.removeEventListener('keydown', this.handleKeyDown)
      }
    },
    scale (newScale) {
      // 缩放时更新拖拽边界
      this.$nextTick(() => {
        const container = this.$refs.previewContainer
        if (container) {
          this.maxDragX = (container.clientWidth * newScale - container.clientWidth) / 2
          this.maxDragY = (container.clientHeight * newScale - container.clientHeight) / 2
          // 确保图片位置在边界内
          this.position.x = Math.max(-this.maxDragX, Math.min(this.maxDragX, this.position.x))
          this.position.y = Math.max(-this.maxDragY, Math.min(this.maxDragY, this.position.y))
        }
      })
    }
  },
  methods: {
    // 变换控制
    zoomIn () {
      this.scale = Math.min(5, this.scale + 0.2)
    },
    zoomOut () {
      this.scale = Math.max(0.2, this.scale - 0.2)
    },
    rotateLeft () {
      this.rotate -= 90
    },
    rotateRight () {
      this.rotate += 90
    },
    resetTransform () {
      this.scale = 1
      this.rotate = 0
      this.position = { x: 0, y: 0 }
    },

    // 图片导航
    switchImage (index) {
      this.currentIndex = index
      this.resetTransform()
      this.isLoading = true // 切换图片时显示加载状态
    },
    prevImage () {
      this.currentIndex = (this.currentIndex - 1 + this.imgList.length) % this.imgList.length
      this.resetTransform()
    },
    nextImage () {
      this.currentIndex = (this.currentIndex + 1) % this.imgList.length
      this.resetTransform()
    },

    // 拖拽控制
    startDrag (e) {
      this.isDragging = true
      const clientX = e.clientX || e.touches?.[0]?.clientX
      const clientY = e.clientY || e.touches?.[0]?.clientY
      this.startDragPosition = {
        x: clientX - this.position.x,
        y: clientY - this.position.y
      }
    },
    onDrag (e) {
      if (!this.isDragging || e.touches?.length > 1) return
      const clientX = e.clientX || e.touches?.[0]?.clientX
      const clientY = e.clientY || e.touches?.[0]?.clientY
      if (clientX === undefined || clientY === undefined) return
      const newX = clientX - this.startDragPosition.x
      const newY = clientY - this.startDragPosition.y
      // 限制拖拽边界
      this.position = {
        x: Math.max(-this.maxDragX, Math.min(this.maxDragX, newX)),
        y: Math.max(-this.maxDragY, Math.min(this.maxDragY, newY))
      }
    },
    stopDrag () {
      this.isDragging = false
      this.initialDistance = null // 重置双指距离
    },

    // 触摸支持
    handleTouchStart (e) {
      if (e.touches.length === 1) {
        this.touchStartX = e.touches[0].clientX
        this.touchStartY = e.touches[0].clientY
        this.startDrag(e)
      } else if (e.touches.length === 2) {
        // 双指触摸开始，记录初始距离
        this.initialDistance = Math.hypot(
          e.touches[1].clientX - e.touches[0].clientX,
          e.touches[1].clientY - e.touches[0].clientY
        )
      }
    },
    handleTouchMove (e) {
      if (e.touches.length === 1) {
        // 单指拖动
        this.onDrag(e)
      } else if (e.touches.length === 2 && this.initialDistance) {
        // 双指缩放
        e.preventDefault()
        const currentDistance = Math.hypot(
          e.touches[1].clientX - e.touches[0].clientX,
          e.touches[1].clientY - e.touches[0].clientY
        )
        const scaleFactor = currentDistance / this.initialDistance
        this.scale = Math.max(0.2, Math.min(5, this.scale * scaleFactor))
        this.initialDistance = currentDistance // 更新距离基准
      }
    },

    // 键盘支持
    handleKeyDown (e) {
      switch (e.key) {
        case 'Escape': this.closePreview(); break
        case 'ArrowLeft':
          e.shiftKey ? this.rotateLeft() : this.prevImage()
          break
        case 'ArrowRight':
          e.shiftKey ? this.rotateRight() : this.nextImage()
          break
        case '+': this.zoomIn(); break
        case '-': this.zoomOut(); break
        case 'r': this.resetTransform(); break
      }
    },

    // 滚轮缩放
    handleWheel (e) {
      e.preventDefault()
      const delta = e.deltaY > 0 ? -0.1 : 0.1
      this.scale = Math.max(0.2, Math.min(5, this.scale + delta))
    },

    // 图片加载失败处理
    handleImageError () {
      console.error('图片加载失败:', this.currentImage)
      this.isLoading = false
    },

    // 关闭预览
    closePreview () {
      this.$emit('close')
    }
  },
  beforeUnmount () {
    document.removeEventListener('keydown', this.handleKeyDown)
  }
}
</script>

<style scoped>
/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}

/* 预览模态框 */
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  touch-action: none; /* 禁用浏览器默认触摸行为 */
}

/* 顶部工具栏 */
.preview-toolbar {
  padding: 15px;
  display: flex;
  justify-content: center;
  gap: 4px;
  z-index: 1001;
  flex-wrap: wrap;
}
.preview-toolbar button {
  padding: 2px 10px;
  min-width: 24px;
  min-height: 24px;
  margin: 0px;
  background: #E5E9F0;
  color: #5D5C5C;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  transition: background 0.3s;
}
.preview-toolbar button:hover {
  color: #3362DA;
}
.close-btn {
  color: #94979E !important;
}

/* 主图片区域 */
.preview-content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
}
.preview-image {
  max-width: 95%;
  max-height: 80vh;
  object-fit: contain;
  transform-origin: center center;
  will-change: transform; /* 优化动画性能 */
}
.loading-indicator {
  position: absolute;
  color: white;
  font-size: 1.2rem;
  z-index: 10;
}

/* 底部缩略图导航 */
.thumbnail-navigation {
  display: flex;
  justify-content: center;
  padding: 15px 0;
  overflow-x: auto;
  gap: 10px;
}
.thumbnail-nav-item {
  width: 60px;
  height: 60px;
  border: 2px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  opacity: 0.6;
  transition: all 0.3s;
  flex-shrink: 0;
}
.thumbnail-nav-item:hover, .thumbnail-nav-item.active {
  opacity: 1;
  border-color: #1890ff;
}
.thumbnail-nav-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
/* 底部描述 */
.thumbnail-description {
  color: #9E9E9E;
  margin: auto;
}
.thumbnail-description-sapn {
  color: #3362DA;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .preview-toolbar {
    padding: 10px;
    gap: 8px;
  }
  .preview-toolbar button {
    padding: 10px 16px;
    font-size: 16px;
  }
}
</style>
