<template>
  <div class="image-annotation-container">
    <!-- 控制面板 -->
    <div class="control-panel">
      <button @click="setMode('point')" :class="{ active: mode === 'point' }">
        绘制点
      </button>
      <button @click="setMode('rect')" :class="{ active: mode === 'rect' }">
        绘制矩形
      </button>
      <button @click="clearAll" class="clear-btn">清除所有</button>

      <div class="config-options" v-if="mode">
        <label v-if="mode === 'point'">
          点大小:
          <input type="range" v-model.number="pointSize" min="3" max="15" />
        </label>
        <label v-if="mode === 'rect'">
          线宽:
          <input type="range" v-model.number="lineWidth" min="1" max="10" />
        </label>
        <!-- <label>
          颜色: <input type="color" v-model="drawColor">
        </label> -->
      </div>
    </div>
    <!-- 图片和画布容器 -->
    <div class="image-wrapper" ref="imageWrapper">
      <img
        :src="imageSrc"
        alt="标注图片"
        ref="image"
        @load="initCanvas"
        @mousedown="handleMouseDown"
        @mousemove="handleMouseMove"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseUp"
      />
      <canvas ref="canvas"></canvas>
    </div>
    <!-- 标注信息面板 -->
    <!-- <div class="annotation-panel">
      <h3>标注信息 (共{{ annotations.length }}个)</h3>
      <div class="annotation-list">
        <div
          v-for="(annotation, index) in annotations"
          :key="index"
          class="annotation-item"
          :class="annotation.type"
          @click="highlightAnnotation(index)"
        >
          <div class="annotation-header">
            <span class="annotation-type">
              {{ annotation.type === 'point' ? '点' : '矩形' }} {{ index + 1 }}
            </span>
            <button @click.stop="removeAnnotation(index)" class="small-btn">
              删除
            </button>
          </div>

        </div>
      </div>
    </div> -->
  </div>
</template>

<script>
export default {
  name: "ImageAnnotation",
  props: {
    imageSrc: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      mode: null, // 当前模式: 'point' 或 'rect'
      isDrawing: false, // 是否正在绘制
      startX: 0, // 绘制起点X
      startY: 0, // 绘制起点Y
      annotations: [], // 所有标注
      drawColor: "red", // 绘制颜色
      pointSize: 6, // 点大小
      lineWidth: 2, // 线宽
      canvas: null, // canvas元素
      ctx: null, // canvas上下文
      imgElement: null, // img元素
      all_data: [],
    };
  },
  watch: {
    imageSrc() {
      this.clearAll();
      this.$nextTick(() => {
        if (this.imgElement.complete) {
          this.initCanvas();
        }
      });
    },
  },
  mounted() {
    // this.annotations = [];
    // this.all_data = [];
    this.imgElement = this.$refs.image;
    this.canvas = this.$refs.canvas;
    this.ctx = this.canvas.getContext("2d");
    // 如果图片已经加载完成
    if (this.imgElement.complete) {
      this.initCanvas();
    }
  },
  methods: {
    // 初始化画布
    initCanvas() {
      this.canvas.width = this.imgElement.width;
      this.canvas.height = this.imgElement.height;
      localStorage.setItem(
        "imgElement",
        JSON.stringify({
          width: this.imgElement.width,
          height: this.imgElement.height,
        })
      );
      this.redrawAll();
    },

    // 设置绘制模式
    setMode(mode) {
      this.mode = mode;
      this.imgElement.ondragstart = function () {
        return false;
      };
    },

    // 鼠标按下事件
    handleMouseDown(e) {
      if (!this.mode || e.button !== 0) return; // 只响应左键
      const rect = this.imgElement.getBoundingClientRect();
      this.startX = e.clientX - rect.left;
      this.startY = e.clientY - rect.top;

      if (this.mode === "point") {
        this.addPoint(this.startX, this.startY);
      } else if (this.mode === "rect") {
        this.isDrawing = true;
      }
    },

    // 鼠标移动事件
    handleMouseMove(e) {
      if (!this.isDrawing) return;

      const rect = this.imgElement.getBoundingClientRect();
      const currentX = e.clientX - rect.left;
      const currentY = e.clientY - rect.top;

      // 清除并重绘
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.redrawAll();

      // 绘制当前矩形
      this.drawRect(
        this.startX,
        this.startY,
        currentX - this.startX,
        currentY - this.startY,
        this.drawColor,
        this.lineWidth,
        true // 临时绘制
      );
    },

    // 鼠标释放事件
    handleMouseUp(e) {
      if (!this.isDrawing) return;

      this.isDrawing = false;
      const rect = this.imgElement.getBoundingClientRect();
      const endX = e.clientX - rect.left;
      const endY = e.clientY - rect.top;

      // 确保矩形有一定大小
      if (
        Math.abs(endX - this.startX) > 5 &&
        Math.abs(endY - this.startY) > 5
      ) {
        this.addRectangle(
          this.startX,
          this.startY,
          endX - this.startX,
          endY - this.startY,
          endX,
          endY
        );
      }
      this.redrawAll();
    },

    // 添加点
    addPoint(x, y) {
      var point_object = { firstX: Math.round(x), firstY: Math.round(y) };
      this.all_data.push(point_object);
      localStorage.setItem("drawData", JSON.stringify(this.all_data));
      this.annotations.push({
        type: "point",
        x,
        y,
        color: this.drawColor,
        size: this.pointSize,
      });
      this.redrawAll();
    },
    // 添加矩形
    addRectangle(x, y, width, height, endX, endY) {
      // 存储矩形的起点和终点
      var point_object = {
        firstX: Math.round(x),
        firstY: Math.round(y),
        secondX: Math.round(endX),
        secondY: Math.round(endY),
      };
      this.all_data.push(point_object);
      // 存储数据给父组件用
      localStorage.setItem("drawData", JSON.stringify(this.all_data));

      this.annotations.push({
        type: "rect",
        x,
        y,
        width,
        height,
        color: this.drawColor,
        lineWidth: this.lineWidth,
      });
    },

    // 绘制点
    drawPoint(x, y, color, size) {
      this.ctx.fillStyle = color;
      this.ctx.beginPath();
      this.ctx.arc(x, y, size, 0, 2 * Math.PI);
      this.ctx.fill();

      // 添加中心点
      this.ctx.fillStyle = "red";
      this.ctx.beginPath();
      this.ctx.arc(x, y, size / 2, 0, 2 * Math.PI);
      this.ctx.fill();
    },

    // 绘制矩形
    drawRect(x, y, width, height, color, lineWidth, isTemporary = false) {
      this.ctx.strokeStyle = color;
      this.ctx.lineWidth = lineWidth;
      this.ctx.strokeRect(x, y, width, height);

      if (!isTemporary) {
        // 半透明填充
        this.ctx.fillStyle = "rgba(0, 0, 255, 0)"; //不填充
        // this.ctx.fillStyle = color.replace(')', ', 0)').replace('rgb', 'rgba');
        this.ctx.fillRect(x, y, width, height);
      }
    },

    // 重绘所有标注
    redrawAll() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.annotations.forEach((annotation) => {
        if (annotation.type === "point") {
          this.drawPoint(
            annotation.x,
            annotation.y,
            annotation.color,
            annotation.size
          );
        } else {
          this.drawRect(
            annotation.x,
            annotation.y,
            annotation.width,
            annotation.height,
            annotation.color,
            annotation.lineWidth
          );
        }
      });
    },

    // 删除标注
    removeAnnotation(index) {
      this.all_data = [];
      this.annotations.splice(index, 1);
      this.redrawAll();
    },

    // 高亮标注
    highlightAnnotation(index) {
      const annotation = this.annotations[index];

      // 先清除画布
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

      // 绘制其他标注（半透明）
      this.annotations.forEach((item, i) => {
        if (i !== index) {
          const alphaColor = item.color
            .replace(")", ", 0.3)")
            .replace("rgb", "rgba");
          if (item.type === "point") {
            this.drawPoint(item.x, item.y, alphaColor, item.size);
          } else {
            this.drawRect(
              item.x,
              item.y,
              item.width,
              item.height,
              alphaColor,
              item.lineWidth
            );
          }
        }
      });

      // 绘制选中的标注（高亮）
      if (annotation.type === "point") {
        this.drawPoint(
          annotation.x,
          annotation.y,
          annotation.color,
          annotation.size * 1.5
        );
      } else {
        this.drawRect(
          annotation.x,
          annotation.y,
          annotation.width,
          annotation.height,
          annotation.color,
          annotation.lineWidth * 2
        );
      }

      // 3秒后恢复
      setTimeout(() => {
        this.redrawAll();
      }, 3000);
    },

    // 清除所有标注
    clearAll() {
      this.annotations = [];
      this.all_data = [];
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },

    // 导出标注数据
    exportAnnotations() {
      const data = {
        imageWidth: this.imgElement.width,
        imageHeight: this.imgElement.height,
        annotations: this.annotations,
      };
      return data;
    },

    // 导入标注数据
    importAnnotations(data) {
      if (
        data.imageWidth === this.imgElement.width &&
        data.imageHeight === this.imgElement.height
      ) {
        this.annotations = data.annotations;
        this.redrawAll();
        return true;
      }
      return false;
    },
  },
};
</script>

<style scoped>
.image-annotation-container {
  font-family: var(--app-font-family);
  max-width: 1000px;
  height: 550px;
  margin: 0 auto;
  padding: 20px;
  overflow: scroll;
}

.control-panel {
  margin: 15px 0;
  padding: 15px;
  /* background: #f5f5f5; */
  border-radius: 5px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  border: 1px solid #555;
}

button {
  padding: 8px 15px;
  background: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

button:hover {
  background: #45a049;
}

button.active {
  background: #2e7d32;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
}

.clear-btn {
  background: #f44336;
}

.clear-btn:hover {
  background: #d32f2f;
}

.small-btn {
  padding: 3px 8px;
  font-size: 12px;
  background: #f44336;
}

.config-options {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-left: auto;
}

.config-options label {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.image-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 20px;
  border: 1px solid #555;
}

img {
  display: block;
  max-width: 100%;
  max-height: 100%;
}

canvas {
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
  /* width: 100%;
  height: 100%; */
  /* width:780px;
  height:445px; */
}

.annotation-panel {
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 5px;
  background: #f9f9f9;
}

.annotation-list {
  max-height: 300px;
  overflow-y: auto;
  margin-top: 10px;
}

.annotation-item {
  padding: 10px;
  margin-bottom: 8px;
  background: white;
  border-radius: 4px;
  border-left: 4px solid #4caf50;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.annotation-item:hover {
  transform: translateX(3px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.annotation-item.point {
  border-left-color: #2196f3;
}

.annotation-item.rect {
  border-left-color: #ff9800;
}

.annotation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.annotation-type {
  font-weight: bold;
}

.annotation-details {
  font-size: 14px;
  color: #555;
}

.empty-message {
  color: #777;
  font-style: italic;
  text-align: center;
  padding: 10px;
}
</style>
