<template>
  <div class="simple-img-viewer">
    <!-- 缩略图 -->
    <img
      :src="src"
      :alt="alt"
      :width="width"
      :height="height"
      class="thumbnail"
      @click="openViewer"
      :title="title || '点击查看图片'"
    >

    <!-- 全屏查看器 -->
    <div
      class="viewer-overlay"
      v-if="isOpen"
      @click="closeViewer"
    >
      <!-- 添加一个完全不透明的背景层 -->
      <div class="absolute-overlay"></div>

      <div
        class="img-wrapper"
        @click.stop
        ref="imgWrapper"
        @wheel.prevent="handleWheel($event)"
      >
        <div
          class="img-container"
          :style="transformStyle"
          ref="imgContainer"
        >
          <img
            :src="src"
            :alt="alt"
            class="viewer-img"
            ref="viewerImg"
            @mousedown.prevent="startDrag($event)"
            @dblclick="resetImage"
          >
        </div>
      </div>
      <div class="ui-layer">
        <div class="zoom-info" v-show="showZoomInfo">{{ Math.round(scale * 100) }}%</div>
        <div class="controls">
          <div class="control-btn" @click.stop="zoomIn">+</div>
          <div class="control-btn" @click.stop="zoomOut">-</div>
          <div class="control-btn" @click.stop="rotateLeft">↺</div>
          <div class="control-btn" @click.stop="rotateRight">↻</div>
          <div class="control-btn" @click.stop="resetImage">⟲</div>
        </div>
        <div class="close-btn" @click.stop="closeViewer">×</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true
    },
    width: {
      default: 60
    },
    height: {
      default: 60
    },
    alt: {
      default: '图片'
    },
    title: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      isOpen: false,
      scale: 1,
      rotation: 0,
      posX: 0,
      posY: 0,
      isDragging: false,
      startX: 0,
      startY: 0,
      showZoomInfo: false,
      zoomInfoTimeout: null,
      boundMouseMove: null,
      boundMouseUp: null,
      boundKeyDown: null,
      overlayElement: null
    }
  },

  computed: {
    transformStyle() {
      return {
        transform: `translate(${this.posX}px, ${this.posY}px) scale(${this.scale}) rotate(${this.rotation}deg)`,
        transition: this.isDragging ? 'none' : 'transform 0.1s ease-out'
      }
    }
  },

  methods: {
    openViewer() {
      this.isOpen = true
      document.body.style.overflow = 'hidden'

      // 创建一个全屏遮罩元素并添加到body
      this.overlayElement = document.createElement('div');
      this.overlayElement.className = 'global-img-viewer-overlay';
      document.body.appendChild(this.overlayElement);

      // 重置图片状态
      this.scale = 1
      this.rotation = 0
      this.posX = 0
      this.posY = 0

      // 在下一个渲染周期添加事件监听
      this.$nextTick(() => {
        // 使用bind确保this绑定正确
        this.boundMouseMove = this.handleMouseMove.bind(this)
        this.boundMouseUp = this.handleMouseUp.bind(this)
        this.boundKeyDown = this.handleKeyDown.bind(this)

        document.addEventListener('mousemove', this.boundMouseMove)
        document.addEventListener('mouseup', this.boundMouseUp)
        document.addEventListener('keydown', this.boundKeyDown)

        if (this.$refs.viewerImg) {
          this.$refs.viewerImg.style.cursor = 'grab'
        }

        // 将查看器移动到body下，确保它在最顶层
        if (this.$el.querySelector('.viewer-overlay')) {
          const viewerOverlay = this.$el.querySelector('.viewer-overlay');
          document.body.appendChild(viewerOverlay);
        }
      })
    },

    closeViewer() {
      this.isOpen = false
      document.body.style.overflow = ''

      // 移除全局遮罩
      if (this.overlayElement && this.overlayElement.parentNode) {
        this.overlayElement.parentNode.removeChild(this.overlayElement);
      }

      // 移除事件监听
      if (this.boundMouseMove) {
        document.removeEventListener('mousemove', this.boundMouseMove)
      }
      if (this.boundMouseUp) {
        document.removeEventListener('mouseup', this.boundMouseUp)
      }
      if (this.boundKeyDown) {
        document.removeEventListener('keydown', this.boundKeyDown)
      }

      // 将查看器元素移回原位
      this.$nextTick(() => {
        const overlay = document.querySelector('.viewer-overlay');
        if (overlay && this.$el) {
          this.$el.appendChild(overlay);
        }
      });
    },

    // 滚轮缩放
    handleWheel(e) {
      // 阻止默认滚动行为
      e.preventDefault()

      // 计算缩放因子
      const delta = e.deltaY < 0 ? 1.1 : 0.9
      const newScale = this.scale * delta

      // 限制缩放范围
      if (newScale >= 0.1 && newScale <= 10) {
        // 获取视口尺寸
        const viewportWidth = window.innerWidth
        const viewportHeight = window.innerHeight

        // 视口中心点
        const centerX = viewportWidth / 2
        const centerY = viewportHeight / 2

        // 计算鼠标位置相对于视口中心的偏移
        const mouseOffsetX = e.clientX - centerX
        const mouseOffsetY = e.clientY - centerY

        // 计算当前图片中心点相对于视口中心的偏移
        const currentOffsetX = this.posX
        const currentOffsetY = this.posY

        // 计算新的位置
        // 当缩小时，让图片更倾向于回到中心位置
        // 当放大时，保持以鼠标位置为中心
        let newPosX, newPosY

        if (delta < 1) { // 缩小
          // 缩小时，逐渐将图片拉回中心
          const pullFactor = Math.max(0.2, newScale / 2) // 拉力因子，随着缩放比例减小而增大
          newPosX = currentOffsetX * delta + (mouseOffsetX * (1 - delta) * pullFactor)
          newPosY = currentOffsetY * delta + (mouseOffsetY * (1 - delta) * pullFactor)
        } else { // 放大
          // 放大时，以鼠标位置为中心
          newPosX = currentOffsetX * delta - mouseOffsetX * (delta - 1)
          newPosY = currentOffsetY * delta - mouseOffsetY * (delta - 1)
        }

        // 更新位置和缩放比例
        this.posX = newPosX
        this.posY = newPosY
        this.scale = newScale

        // 显示缩放信息
        this.showZoomInfo = true
        clearTimeout(this.zoomInfoTimeout)
        this.zoomInfoTimeout = setTimeout(() => {
          this.showZoomInfo = false
        }, 1000)
      }
    },

    // 开始拖动
    startDrag(e) {
      if (e.button !== 0) return // 只响应左键

      this.isDragging = true
      this.startX = e.clientX - this.posX
      this.startY = e.clientY - this.posY

      if (this.$refs.viewerImg) {
        this.$refs.viewerImg.style.cursor = 'grabbing'
      }

      // 阻止默认行为和冒泡
      e.stopPropagation()
    },

    // 拖动中
    handleMouseMove(e) {
      if (!this.isDragging) return

      this.posX = e.clientX - this.startX
      this.posY = e.clientY - this.startY
    },

    // 结束拖动
    handleMouseUp() {
      if (this.isDragging) {
        this.isDragging = false
        if (this.$refs.viewerImg) {
          this.$refs.viewerImg.style.cursor = 'grab'
        }
      }
    },

    // 缩放控制
    zoomIn() {
      this.scale = Math.min(this.scale * 1.2, 10)

      this.showZoomInfo = true
      clearTimeout(this.zoomInfoTimeout)
      this.zoomInfoTimeout = setTimeout(() => {
        this.showZoomInfo = false
      }, 1000)
    },

    zoomOut() {
      this.scale = Math.max(this.scale * 0.8, 0.1)

      this.showZoomInfo = true
      clearTimeout(this.zoomInfoTimeout)
      this.zoomInfoTimeout = setTimeout(() => {
        this.showZoomInfo = false
      }, 1000)
    },

    // 旋转控制
    rotateLeft() {
      this.rotation -= 90
    },

    rotateRight() {
      this.rotation += 90
    },

    // 重置图片
    resetImage() {
      this.scale = 1
      this.rotation = 0
      this.posX = 0
      this.posY = 0

      // 显示缩放信息
      this.showZoomInfo = true
      clearTimeout(this.zoomInfoTimeout)
      this.zoomInfoTimeout = setTimeout(() => {
        this.showZoomInfo = false
      }, 1000)
    },

    // 键盘事件处理
    handleKeyDown(e) {
      if (!this.isOpen) return

      switch (e.key) {
        case 'Escape':
          this.closeViewer()
          break
        case 'ArrowLeft':
          this.rotateLeft()
          break
        case 'ArrowRight':
          this.rotateRight()
          break
        case '+':
        case '=':
          this.zoomIn()
          break
        case '-':
          this.zoomOut()
          break
        case '0':
          this.resetImage()
          break
      }
    }
  },

  beforeDestroy() {
    // 确保清理事件监听
    if (this.boundMouseMove) {
      document.removeEventListener('mousemove', this.boundMouseMove)
    }
    if (this.boundMouseUp) {
      document.removeEventListener('mouseup', this.boundMouseUp)
    }
    if (this.boundKeyDown) {
      document.removeEventListener('keydown', this.boundKeyDown)
    }

    // 清除定时器
    if (this.zoomInfoTimeout) {
      clearTimeout(this.zoomInfoTimeout)
    }

    // 移除全局遮罩
    if (this.overlayElement && this.overlayElement.parentNode) {
      this.overlayElement.parentNode.removeChild(this.overlayElement);
    }
  }
}
</script>

<style scoped>
.simple-img-viewer {
  display: inline-block;
}

.thumbnail {
  cursor: pointer;
  transition: transform 0.2s;
}

.thumbnail:hover {
  transform: scale(1.05);
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
}

.viewer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: transparent;
  z-index: 999999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.absolute-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 999998;
}

.img-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  z-index: 1000000;
}

.img-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  transform-origin: center;
  will-change: transform;
}

.viewer-img {
  max-width: 90vw;
  max-height: 90vh;
  user-select: none;
  -webkit-user-drag: none;
  cursor: grab;
}

/* 新增UI层，用于放置所有控制元素 */
.ui-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none; /* 默认不接收鼠标事件，让事件穿透到下层 */
  z-index: 1000001;
}

.controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 20px;
  padding: 5px;
  height: 50px;
  pointer-events: auto; /* 控制按钮需要接收鼠标事件 */
}

.control-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  margin: 0 5px;
  transition: background-color 0.3s;
}

.control-btn:hover {
  background-color: rgba(255, 255, 255, 0.4);
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.3s;
  pointer-events: auto; /* 关闭按钮需要接收鼠标事件 */
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.4);
}

.zoom-info {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 14px;
  pointer-events: none; /* 缩放信息不需要接收鼠标事件 */
  height: auto; /* 自适应内容高度 */
  line-height: 1.2; /* 合理的行高 */
  display: inline-block; /* 使元素宽度自适应内容 */
  white-space: nowrap; /* 防止文本换行 */
}
</style>

<style>
/* 全局遮罩样式 */
.global-img-viewer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.4; /* 降低不透明度，使其更透明 */
  z-index: 999997;
  pointer-events: auto;
}

/* 确保图片查看器始终在最顶层 */
.viewer-overlay {
  position: fixed !important;
  z-index: 999999 !important;
}

.ui-layer {
  z-index: 1000001 !important;
}
</style>
