// Note_RectangleRoiTool.js
import * as cornerstoneTools from 'cornerstone-tools';

export default class Note_RectangleRoiTool extends cornerstoneTools.RectangleRoiTool {
  constructor(props = {}) {
    const defaultProps = {
      name: 'Note_RectangleRoi',
      configuration: {
        fillColor: 'rgba(255, 255, 0, 0.3)',  // 默认填充颜色：半透明黄色
        strokeColor: 'yellow',                 // 边框颜色
        lineWidth: 2,                          // 边框宽度
        drawHandles: true,                     // 是否绘制控制点
        handleColor: 'white',                  // 控制点颜色
      }
    };
    super({ ...defaultProps, ...props });
  }

  renderToolData(evt) {
    const eventData = evt.detail;
    const { element } = eventData;

    // 获取工具状态
    const toolData = cornerstoneTools.getToolState(element, this.name);

    if (!toolData || !toolData.data || !toolData.data.length) {
      return;
    }

    const canvas = eventData.canvasContext.canvas;
    const context = canvas.getContext('2d');

    context.save();

    // 获取配置
    const fillColor = this.configuration.fillColor || 'rgba(255, 255, 0, 0.3)';
    const strokeColor = this.configuration.strokeColor || 'yellow';
    const lineWidth = this.configuration.lineWidth || 2;
    const drawHandles = this.configuration.drawHandles !== false;

    // 遍历所有矩形标注
    toolData.data.forEach((measurement) => {
      if (!measurement.handles?.start || !measurement.handles?.end) {
        return;
      }

      const start = measurement.handles.start;
      const end = measurement.handles.end;

      // 计算矩形坐标和尺寸
      const x = Math.min(start.x, end.x);
      const y = Math.min(start.y, end.y);
      const width = Math.abs(end.x - start.x);
      const height = Math.abs(end.y - start.y);

      // 1. 绘制填充
      if (fillColor) {
        context.fillStyle = fillColor;
        context.fillRect(x, y, width, height);
      }

      // 2. 绘制边框
      context.strokeStyle = strokeColor;
      context.lineWidth = lineWidth;
      context.strokeRect(x, y, width, height);

      // 3. 绘制控制点（可选）
      if (drawHandles) {
        this.drawHandles(context, measurement, eventData);
      }
    });

    context.restore();
  }

  /**
   * 绘制控制点
   */
  drawHandles(context, measurement, eventData) {
    const handles = measurement.handles;
    const handleColor = this.configuration.handleColor || 'white';

    // 绘制所有控制点
    Object.keys(handles).forEach(key => {
      const handle = handles[key];
      if (handle && typeof handle.x === 'number' && typeof handle.y === 'number') {
        context.beginPath();
        context.arc(handle.x, handle.y, 5, 0, 2 * Math.PI);
        context.fillStyle = handleColor;
        context.fill();
        context.strokeStyle = 'black';
        context.lineWidth = 1;
        context.stroke();
      }
    });
  }
}