<template>
  <div v-if="visible" class="preview-mask">
    <div class="preview-container">
      <img
        :src="imageSrc"
        :style="imgStyle"
        class="preview-img"
        @mousedown="startDrag"
        @error="handleImageError"
        draggable="false"
      />
      <div class="preview-actions">
        <a-button @click="zoomIn">放大</a-button>
        <a-button @click="zoomOut">缩小</a-button>
        <a-button @click="rotateLeft">左旋转</a-button>
        <a-button @click="rotateRight">右旋转</a-button>
        <a-button @click="close">关闭</a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

 const props = defineProps({
  src: {
    type: String,
    required: true
  },
  originalPath: {
    type: String,
    default: ''
  },
  visible: Boolean
})
const emits = defineEmits(['close', 'src-updated'])

const scale = ref(1)
const rotate = ref(0)
const offset = ref({ x: 0, y: 0 })
const dragging = ref(false)
const dragStart = ref({ x: 0, y: 0 })
const imageSrc = ref(props.src)
const isFixed = ref(false) // 标记是否已修复过路径

// 当src变化时，更新imageSrc（如果路径没有被修复过）
watch(() => props.src, (newSrc) => {
  if (!isFixed.value) {
    imageSrc.value = newSrc
  }
})

// 当visible变化时，如果是打开状态，重置imageSrc和修复标记
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    imageSrc.value = props.src
    isFixed.value = false
  }
})

const imgStyle = computed(() => ({
  transform: `scale(${scale.value}) rotate(${rotate.value}deg) translate(${offset.value.x}px, ${offset.value.y}px)`,
  cursor: dragging.value ? 'grabbing' : 'grab'
}))
// eslint-disable-next-line no-return-assign
const zoomIn = () => scale.value += 0.2
// eslint-disable-next-line no-return-assign
const zoomOut = () => scale.value = Math.max(0.2, scale.value - 0.2)
// eslint-disable-next-line no-return-assign
const rotateLeft = () => rotate.value -= 90
// eslint-disable-next-line no-return-assign
const rotateRight = () => rotate.value += 90
const close = () => emits('close')

const startDrag = (e) => {
  dragging.value = true
  dragStart.value = { x: e.clientX - offset.value.x, y: e.clientY - offset.value.y }
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}
const onDrag = (e) => {
  if (!dragging.value) return
  offset.value = {
    x: e.clientX - dragStart.value.x,
    y: e.clientY - dragStart.value.y
  }
}
const stopDrag = () => {
  dragging.value = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

const handleImageError = (event) => {
  if (!event.target || !props.originalPath) return
  
  const currentSrc = imageSrc.value || ''
  console.log('ImagePreview error - currentSrc:', currentSrc, 'originalPath:', props.originalPath)
  
  if (currentSrc.includes('/files/')) {
    console.log('ImagePreview: 已经是新格式，不再处理')
    return
  }
  if (!currentSrc.includes('/rs/image/file/')) {
    console.log('ImagePreview: 不是旧格式，不再处理')
    return
  }
  
  const baseUrl = `${window.location.protocol}//${window.location.host}`
  
  // 如果是本地文件路径，尝试新格式（保留目录结构）
  if (props.originalPath.match(/^[A-Za-z]:[/\\]/)) {
    const normalizedPath = props.originalPath.replace(/\\/g, '/')
    const filesIndex = normalizedPath.toLowerCase().indexOf('/files/')
    if (filesIndex !== -1) {
      const relativePath = normalizedPath.substring(filesIndex + 1)
      const newUrl = `${baseUrl}/${relativePath}`
      console.log('ImagePreview: 切换到新格式URL:', newUrl)
      imageSrc.value = newUrl
      isFixed.value = true // 标记已修复
      emits('src-updated', newUrl) // 通知父组件更新路径
    }
  }
}
</script>

<style scoped>
.preview-mask {
  position: fixed;
  z-index: 9999;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  align-items: center;
  justify-content: center;
}
.preview-container {
  position: relative;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
.preview-img {
  max-width: 80vw;
  max-height: 70vh;
  user-select: none;
  transition: transform 0.2s;
  display: block;
  margin: 0 auto;
}
.preview-actions {
  margin-top: 16px;
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>
