<template>
  <div class="labeling-page-container">
    <!-- 顶部操作栏：仅保留图片切换、缩放、重置按钮 -->
    <div class="labeling-header">
      <div class="header-left">
        <el-button-group>
          <el-button icon="el-icon-arrow-left" @click="prevImage" title="上一张" :disabled="imageList.length <= 1"></el-button>
          <el-button icon="el-icon-arrow-right" @click="nextImage" title="下一张" :disabled="imageList.length <= 1"></el-button>
          <el-button icon="el-icon-zoom-in" @click="zoomIn" title="放大"></el-button>
          <el-button icon="el-icon-zoom-out" @click="zoomOut" title="缩小"></el-button>
          <el-button icon="el-icon-refresh" @click="resetZoom" title="重置视图"></el-button>
        </el-button-group>
      </div>
      <div class="header-right"></div>
    </div>

    <!-- 主体内容区：保留图片拖拽/缩放，新增无效数据提示，展示标注结果 -->
    <div class="labeling-main-wrapper">
      <div class="labeling-main">
        <!-- 左侧图片展示区：保留拖拽、缩放核心交互 -->
        <div class="labeling-image-area">
          <div v-if="imageLoading" class="image-loading">
            <el-skeleton :rows="10" animated />
          </div>
          <div v-else ref="labelContainer" class="image-container"
               @wheel.prevent="handleWheelZoom"
               @mousedown="handleImageMouseDown"
               @mousemove="handleImageMouseMove"
               @mouseup="handleImageMouseUp"
               @mouseleave="handleImageMouseUp">
            <!-- 无效数据提示：醒目展示 -->
            <div v-if="currentImage.isInvalidData === '0'" class="invalid-data-tip">无效数据</div>
            <img
              ref="labelImage"
              :src="currentImage.filePath"
              alt="分类标注图片"
              class="label-image"
              @load="onImageLoad"
              @error="onImageError"
              @mousedown.prevent
            />
          </div>
          <!-- 图片分页/缩放信息 -->
          <div class="image-pagination" v-if="!imageLoading">
            第 {{ currentImageIndex + 1 }} 张/共 {{ imageList.length }} 张 | 缩放比例：{{ Math.round(zoomScale * 100) }}%
          </div>
        </div>

        <!-- 右侧标注结果展示区：固定展示，显示当前图片的分类标签 -->
        <div class="label-result-area">
          <div class="result-title">分类标注结果</div>
          <div class="result-content">
            <div v-if="getSelectedLabelNames().length === 0 && currentImage.isInvalidData !== '0'" class="no-result">暂无分类标注</div>
            <div v-if="currentImage.isInvalidData === '0'" class="invalid-result">已标为无效数据</div>
            <div class="result-tag" v-for="label in getSelectedLabelNames()" :key="label.id">
              {{ label.name }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 引入详情接口和标签树接口
import {
  getLabelingTaskLabelTreeAPI,
  getLabelPicturesDetailAPI
} from '@/api/data/labeling'
import { decryptWithSM4 } from "@/utils/sm";

export default {
  name: 'LabelingClassifyDetail',
  data() {
    return {
      // 图片相关
      imageList: [],
      currentImageIndex: 0,
      currentImage: {},
      imageLoading: false,
      imageLoaded: false,
      // 标签相关
      labelGroups: [],
      labelLoading: false,
      // 缩放/拖拽核心参数（完整保留）
      zoomScale: 1.0,
      imgOffsetX: 0,
      imgOffsetY: 0,
      dragState: {
        isDragging: false,
        startX: 0,
        startY: 0,
        startImgX: 0,
        startImgY: 0
      },
      // 任务参数
      labelingTaskId: this.convertToNumber(decryptWithSM4(this.$route.query.labelingTaskId || '')),
      labelingTemplate: decryptWithSM4(this.$route.query.labelingTemplate || '')
    }
  },
  mounted() {
    // 并行加载图片详情和标签树，提升体验
    Promise.all([this.loadImageDetail(), this.loadLabelTreeData()]).then(() => {
      if (this.imageList.length > 0) {
        this.currentImage = this.imageList[this.currentImageIndex]
      }
    })
  },
  methods: {
    // 数字转换工具方法
    convertToNumber(value) {
      if (!value || value === '' || value === 'undefined' || value === 'null') {
        return '';
      }
      const num = Number(value);
      return isNaN(num) ? '' : num;
    },

    // 加载分类标注详情图片数据（核心：解析接口返回的分类标注数据）
    async loadImageDetail() {
      try {
        this.imageLoading = true
        if (!this.labelingTaskId) {
          this.$message.warning('分类任务ID不能为空');
          return;
        }
        // 调用标注详情接口
        const res = await getLabelPicturesDetailAPI({ labelingTaskId: this.labelingTaskId })
        if (res.code === 200 && res.data && Array.isArray(res.data)) {
          // 解析扁平的接口数据，按图片分组（适配分类标注的labelingDataList结构）
          const imageMap = {}
          res.data.forEach(item => {
            const key = item.labelingSampleId
            if (!imageMap[key]) {
              imageMap[key] = {
                id: item.labelingSampleId,
                datasetSampleId: item.datasetSampleId,
                filePath: item.filePath,
                isInvalidData: item.isInvalidData, // 无效数据标记 0=无效 1=有效
                selectedLabelIds: [] // 分类标注核心：保存该图片的选中标签ID
              }
            }
            // 解析分类标注的标签ID（labelingCoordinate存储的是分类标签信息，或直接取labelId）
            try {
              const labelingData = JSON.parse(item.labelingCoordinate || '{}')
              // 兼容两种返回格式：直接取labelId / 从labelingDataList取
              const labelId = labelingData.labelId || item.labelId
              if (labelId && !imageMap[key].selectedLabelIds.includes(labelId)) {
                imageMap[key].selectedLabelIds.push(labelId)
              }
            } catch (e) {
              // 兜底：直接取接口的labelId
              if (item.labelId && !imageMap[key].selectedLabelIds.includes(item.labelId)) {
                imageMap[key].selectedLabelIds.push(item.labelId)
              }
            }
          })
          // 转换为数组并赋值
          this.imageList = Object.values(imageMap)
          if (this.imageList.length === 0) {
            this.$message.info('暂无分类标注图片数据')
          }
        } else {
          this.$message.warning('图片详情加载失败：' + (res.msg || '接口返回异常'))
          this.imageList = []
        }
      } catch (error) {
        console.error('加载图片详情失败：', error)
        this.$message.error('图片详情加载失败，请刷新重试')
        this.imageList = []
      } finally {
        this.imageLoading = false
      }
    },

    // 加载标签树数据（仅用于回显标签名称）
    async loadLabelTreeData() {
      try {
        this.labelLoading = true
        if (!this.labelingTaskId) return;
        const res = await getLabelingTaskLabelTreeAPI({ labelingTaskId: this.labelingTaskId })
        if (res.code === 200 && res.data) {
          this.labelGroups = res.data.map(group => ({
            ...group,
            expanded: true,
            labels: group.labels || []
          }))
        } else {
          this.$message.warning('标签数据加载失败：' + (res.msg || '接口返回异常'))
          this.labelGroups = []
        }
      } catch (error) {
        console.error('加载标签树失败：', error)
        this.$message.error('标签数据加载失败，请刷新重试')
        this.labelGroups = []
      } finally {
        this.labelLoading = false
      }
    },

    // 图片加载完成：初始化缩放和画布
    onImageLoad() {
      this.imageLoaded = true
      this.calcFitScale() // 计算适配缩放（完整保留）
      this.imgOffsetX = 0
      this.imgOffsetY = 0
      this.initImageCanvas() // 初始化画布绘制图片
    },

    // 初始化画布（承载图片，实现拖拽/缩放的视觉效果）
    initImageCanvas() {
      const container = this.$refs.labelContainer
      const image = this.$refs.labelImage
      if (!container || !image) return

      // 移除旧画布
      const oldCanvas = container.querySelector('.image-canvas')
      if (oldCanvas) oldCanvas.remove()

      // 创建新画布
      const canvas = document.createElement('canvas')
      canvas.className = 'image-canvas'
      canvas.style.cssText = 'position:absolute;top:0;left:0;pointer-events:none;z-index:10;width:100%;height:100%;'
      canvas.width = container.offsetWidth
      canvas.height = container.offsetHeight
      container.appendChild(canvas)
      this.updateImageCanvas() // 重绘图片
    },

    // 重绘画布：核心，实现图片的缩放和拖拽视觉效果
    updateImageCanvas() {
      const container = this.$refs.labelContainer
      const image = this.$refs.labelImage
      const canvas = container.querySelector('.image-canvas')
      if (!container || !image || !canvas) return

      const ctx = canvas.getContext('2d')
      canvas.width = container.offsetWidth
      canvas.height = container.offsetHeight
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.save()

      // 核心绘制逻辑：居中 + 缩放 + 拖拽偏移
      ctx.translate(
        container.offsetWidth / 2 + this.imgOffsetX,
        container.offsetHeight / 2 + this.imgOffsetY
      )
      ctx.scale(this.zoomScale, this.zoomScale)
      ctx.translate(-image.naturalWidth / 2, -image.naturalHeight / 2)

      // 绘制图片
      ctx.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight)
      ctx.restore()
    },

    // 计算适配缩放比例：让图片完整显示在容器中
    calcFitScale() {
      const container = this.$refs.labelContainer
      const image = this.$refs.labelImage
      if (!container || !image) return

      const containerW = container.clientWidth
      const containerH = container.clientHeight
      const imgW = image.naturalWidth
      const imgH = image.naturalHeight

      const scaleW = containerW / imgW
      const scaleH = containerH / imgH
      this.zoomScale = Math.min(scaleW, scaleH)
      this.zoomScale = Math.max(0.1, Math.min(2.0, this.zoomScale))
    },

    // 图片加载失败提示
    onImageError() {
      this.$message.error(`图片加载失败：${this.currentImage.filePath}`)
      this.imageLoaded = false
    },

    // 滚轮缩放：完整保留
    handleWheelZoom(e) {
      e.preventDefault()
      const delta = e.deltaY > 0 ? -0.1 : 0.1
      this.zoomScale = Math.max(0.1, Math.min(2.0, this.zoomScale + delta))
      this.updateImageCanvas()
    },

    // 鼠标按下：开启拖拽
    handleImageMouseDown(e) {
      e.preventDefault()
      this.dragState = {
        isDragging: true,
        startX: e.clientX,
        startY: e.clientY,
        startImgX: this.imgOffsetX,
        startImgY: this.imgOffsetY
      }
      this.$refs.labelContainer.style.cursor = 'move'
    },

    // 鼠标移动：处理拖拽
    handleImageMouseMove(e) {
      e.preventDefault()
      if (!this.dragState.isDragging) return
      const moveX = e.clientX - this.dragState.startX
      const moveY = e.clientY - this.dragState.startY
      this.imgOffsetX = this.dragState.startImgX + moveX
      this.imgOffsetY = this.dragState.startImgY + moveY
      this.updateImageCanvas()
    },

    // 鼠标松开/离开：结束拖拽
    handleImageMouseUp() {
      if (this.dragState.isDragging) {
        this.dragState.isDragging = false
        this.$refs.labelContainer.style.cursor = 'default'
      }
    },

    // 放大图片
    zoomIn() {
      this.zoomScale = Math.min(2.0, this.zoomScale + 0.1)
      this.updateImageCanvas()
    },

    // 缩小图片
    zoomOut() {
      this.zoomScale = Math.max(0.1, this.zoomScale - 0.1)
      this.updateImageCanvas()
    },

    // 重置视图：恢复适配缩放，清空拖拽偏移
    resetZoom() {
      this.calcFitScale()
      this.imgOffsetX = 0
      this.imgOffsetY = 0
      this.updateImageCanvas()
    },

    // 获取当前图片选中的标签名称（用于回显）
    getSelectedLabelNames() {
      const selectedLabels = []
      const { selectedLabelIds } = this.currentImage
      if (!selectedLabelIds || selectedLabelIds.length === 0) {
        return selectedLabels
      }
      this.labelGroups.forEach(group => {
        group.labels.forEach(label => {
          if (selectedLabelIds.includes(label.id + '')) { // 也可以用 String(label.id)
            selectedLabels.push(label)
          }
        })
      })
      return selectedLabels
    },

    // 上一张图片
    prevImage() {
      if (this.currentImageIndex > 0) {
        this.switchImage(this.currentImageIndex - 1)
      } else {
        this.$message.info('已是第一张！')
      }
    },

    // 下一张图片
    nextImage() {
      if (this.currentImageIndex < this.imageList.length - 1) {
        this.switchImage(this.currentImageIndex + 1)
      } else {
        this.$message.info('已是最后一张！')
      }
    },

    // 切换图片：重置视图，重新绘制图片
    switchImage(index) {
      this.currentImageIndex = index
      this.currentImage = this.imageList[index]
      this.imageLoaded = false
      this.imgOffsetX = 0
      this.imgOffsetY = 0
      this.zoomScale = 1.0
      // 重新初始化画布和缩放
      this.$nextTick(() => {
        if (this.$refs.labelImage) {
          this.calcFitScale()
          this.initImageCanvas()
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
// 全局容器
.labeling-page-container {
  width: 100%;
  height: 90vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

// 顶部操作栏
.labeling-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  flex-shrink: 0;
  z-index: 100;

  .header-left {
    display: flex;
    align-items: center;
  }
}

// 主体内容外层容器
.labeling-main-wrapper {
  height: 100%;
  overflow: hidden;
  padding: 15px;
}

// 主体内容区：图片+标注结果展示
.labeling-main {
  display: flex;
  gap: 15px;
  height: 100%;
  min-height: 0;

  // 左侧图片展示区：保留拖拽/缩放样式
  .labeling-image-area {
    flex: 2;
    background-color: #fff;
    border-radius: 4px;
    padding: 15px;
    display: flex;
    flex-direction: column;

    .image-loading {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
    }

    .image-container {
      flex: 1;
      position: relative;
      overflow: hidden;
      border: 1px solid #e6e6e6;
      border-radius: 4px;
      min-height: 400px;
      cursor: default;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f0f0f0;
      padding: 0;
      box-sizing: border-box;

      // 无效数据提示样式：醒目、不遮挡操作
      .invalid-data-tip {
        position: absolute;
        top: 20px;
        left: 20px;
        z-index: 99;
        background-color: rgba(255, 59, 48, 0.9);
        color: #fff;
        padding: 8px 16px;
        font-size: 16px;
        font-weight: 600;
        border-radius: 6px;
        pointer-events: none;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      }

      // 画布承载图片，图片本身隐藏（通过画布绘制）
      .label-image {
        display: none;
      }
    }

    .image-pagination {
      margin-top: 10px;
      font-size: 14px;
      color: #666;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  // 右侧分类标注结果展示区
  .label-result-area {
    width: 280px;
    background-color: #fff;
    border-radius: 4px;
    padding: 15px;
    border: 1px solid #e6e6e6;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;

    .result-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 15px;
      padding-bottom: 8px;
      border-bottom: 1px solid #e6e6e6;
    }

    .result-content {
      flex: 1;
      overflow-y: auto;
      padding: 5px 0;

      .no-result, .invalid-result {
        text-align: center;
        padding: 30px 0;
        font-size: 14px;
      }

      .no-result {
        color: #999;
      }

      .invalid-result {
        color: #ff3b30;
        font-weight: 500;
      }

      .result-tag {
        padding: 8px 12px;
        background-color: #e6f7ff;
        border-radius: 4px;
        margin-bottom: 10px;
        font-size: 14px;
        color: #1890ff;
      }
    }
  }
}

// 滚动条样式优化
::v-deep .el-scrollbar__bar {
  width: 6px;
  height: 6px;
}

::v-deep .el-scrollbar__thumb {
  background-color: #ccc;
  border-radius: 3px;
}
</style>
