import { BaseBrush } from "../BaseBrush";

/**
 * 铅笔笔刷
 * fabric原生铅笔笔刷的包装类
 */
export class PencilBrush extends BaseBrush {
  /**
   * 构造函数
   * @param {Object} canvas fabric画布实例
   * @param {Object} options 配置选项
   */
  constructor(canvas, options = {}) {
	// console.log(options,'=-===========================')
    super(canvas, {
      id: "pencil",
      name: "铅笔",
      description: "基础铅笔工具，适合精细线条绘制",
      category: "基础笔刷",
      icon: "pencil",
	  t: options.t,
      ...options,
    });

    // 铅笔笔刷特有属性
    this.decimate = options.decimate || 0.4;
    this.strokeLineCap = options.strokeLineCap || "round";
    this.strokeLineJoin = options.strokeLineJoin || "round";
  }

  /**
   * 创建笔刷实例
   * @returns {Object} fabric.PencilBrush实例
   */
  create() {
    if (!this.canvas) {
      throw new Error("画布实例不存在");
    }

    // 创建fabric原生铅笔笔刷
    this.brush = new fabric.PencilBrush(this.canvas);

    // 重写 _finalizeAndAddPath 方法，使其调用 convertToImg 而不是创建 Path 对象
    const originalFinalizeAndAddPath = this.brush._finalizeAndAddPath.bind(this.brush);
    const self = this; // 保存外部this引用

    this.brush._finalizeAndAddPath = function () {
      console.log("PencilBrush: _finalizeAndAddPath called");
      const ctx = this.canvas.contextTop;
      ctx.closePath();

      // 应用点简化
      if (this.decimate) {
        this._points = this.decimatePoints(this._points, this.decimate);
      }

      console.log("PencilBrush: points count =", this._points ? this._points.length : 0);

      // 检查是否有有效的路径数据
      if (!this._points || this._points.length < 2) {
        // 如果点数不足，直接请求重新渲染
        console.log("PencilBrush: Not enough points, skipping");
        this.canvas.requestRenderAll();
        return;
      }

      const pathData = this.convertPointsToSVGPath(this._points);

      const isEmpty = self._isEmptySVGPath(pathData);
      console.log("PencilBrush: isEmpty =", isEmpty);

      if (isEmpty) {
        // 如果路径为空，直接请求重新渲染
        console.log("PencilBrush: Path is empty, skipping");
        this.canvas.requestRenderAll();
        return;
      }

      // 先触发事件，模拟原生行为
      const path = this.createPath(pathData);
      this.canvas.fire("before:path:created", { path: path });

      console.log("PencilBrush: Calling convertToImg");

      // 调用 convertToImg 方法将绘制内容转换为图片
      if (typeof this.convertToImg === "function") {
        // 确保在转换前设置正确的透明度
        const currentAlpha = ctx.globalAlpha;
        ctx.globalAlpha = this.opacity || 1;

        this.convertToImg();
        console.log("PencilBrush: convertToImg called successfully");

        // 恢复透明度
        ctx.globalAlpha = currentAlpha;
      } else {
        console.warn("convertToImg method not found, falling back to original behavior");
        // 如果没有convertToImg方法，回退到原始行为
        this.canvas.add(path);
        this.canvas.fire("path:created", { path: path });
        this.canvas.clearContext(this.canvas.contextTop);
      }

      // 重置阴影
      this._resetShadow();
    };

    // 配置笔刷
    this.configure(this.brush, this.options);

    return this.brush;
  }

  /**
   * 检查 SVG 路径是否为空
   * @private
   * @param {Array} pathData SVG 路径数据
   * @returns {Boolean} 是否为空路径
   */
  _isEmptySVGPath(pathData) {
    if (!pathData || pathData.length === 0) {
      return true;
    }

    // 检查路径是否只包含移动命令或者是一个点
    let hasDrawing = false;
    let moveCount = 0;

    for (let i = 0; i < pathData.length; i++) {
      const command = pathData[i];
      if (command[0] === "M") {
        moveCount++;
      } else if (command[0] === "L" || command[0] === "Q" || command[0] === "C") {
        hasDrawing = true;
        break;
      }
    }

    // 如果只有移动命令且超过1个，或者没有绘制命令，则认为是空路径
    return !hasDrawing || (moveCount > 0 && pathData.length <= moveCount);
  }

  /**
   * 配置笔刷
   * @param {Object} brush fabric.PencilBrush实例
   * @param {Object} options 配置选项
   */
  configure(brush, options = {}) {
    if (!brush) {
      return;
    }

    // 基础属性配置
    if (options.width !== undefined) {
      brush.width = options.width;
    }

    if (options.color !== undefined && options.opacity !== undefined) {
      // 使用RGBA颜色而不是设置globalAlpha
      brush.color = this._createRGBAColor(options.color, options.opacity);
    } else if (options.color !== undefined) {
      brush.color = options.color;
    } else if (options.opacity !== undefined) {
      // 如果只设置了透明度，基于当前颜色创建RGBA
      const currentColor = brush.color || "#000000";
      brush.color = this._createRGBAColor(currentColor, options.opacity);
    }

    // 确保不使用globalAlpha，避免圆圈绘制问题
    if (brush.canvas && brush.canvas.contextTop) {
      brush.canvas.contextTop.globalAlpha = 1;
      brush.canvas.contextTop.lineCap = "round";
      brush.canvas.contextTop.lineJoin = "round";
    }

    // 特殊属性配置
    options.decimate = 0;
    if (options.decimate !== undefined) {
      brush.decimate = options.decimate;
      this.decimate = options.decimate;
    }
    options.strokeLineCap = "round";
    if (options.strokeLineCap !== undefined) {
      brush.strokeLineCap = options.strokeLineCap;
      this.strokeLineCap = options.strokeLineCap;
    }
    options.strokeLineJoin = "round";
    if (options.strokeLineJoin !== undefined) {
      brush.strokeLineJoin = options.strokeLineJoin;
      this.strokeLineJoin = options.strokeLineJoin;
    }
  }

  /**
   * 创建RGBA颜色字符串
   * @private
   * @param {String} color 十六进制颜色或已有颜色
   * @param {Number} opacity 透明度 (0-1)
   * @returns {String} RGBA颜色字符串
   */
  _createRGBAColor(color, opacity) {
    // 如果已经是rgba颜色，先提取RGB部分
    if (color.startsWith("rgba")) {
      const rgbaMatch = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
      if (rgbaMatch) {
        const [, r, g, b] = rgbaMatch;
        return `rgba(${r}, ${g}, ${b}, ${opacity})`;
      }
    }

    // 如果是rgb颜色，提取RGB部分
    if (color.startsWith("rgb")) {
      const rgbMatch = color.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
      if (rgbMatch) {
        const [, r, g, b] = rgbMatch;
        return `rgba(${r}, ${g}, ${b}, ${opacity})`;
      }
    }

    // 处理十六进制颜色
    if (color.startsWith("#")) {
      const hex = color.replace("#", "");
      let r, g, b;

      if (hex.length === 3) {
        r = parseInt(hex[0] + hex[0], 16);
        g = parseInt(hex[1] + hex[1], 16);
        b = parseInt(hex[2] + hex[2], 16);
      } else if (hex.length === 6) {
        r = parseInt(hex.substring(0, 2), 16);
        g = parseInt(hex.substring(2, 4), 16);
        b = parseInt(hex.substring(4, 6), 16);
      } else {
        // 无效的十六进制颜色，使用默认
        r = g = b = 0;
      }

      return `rgba(${r}, ${g}, ${b}, ${opacity})`;
    }

    // 如果是其他格式的颜色，尝试转换（例如颜色名称）
    // 这里简化处理，实际项目中可以使用更复杂的颜色解析
    return color; // fallback到原颜色
  }

  /**
   * 获取笔刷可配置属性
   * @returns {Array} 可配置属性描述数组
   * @override
   */
  getConfigurableProperties() {
    // 获取基础属性
    const baseProperties = super.getConfigurableProperties();
    // 定义铅笔笔刷特有属性
    const pencilProperties = [
      // {
      //   id: "decimate",
      //   name: "精细度",
      //   type: "slider",
      //   defaultValue: this.decimate,
      //   min: 0,
      //   max: 1,
      //   step: 0.1,
      //   description: "控制笔触路径的简化程度，值越小路径越精细",
      //   category: "铅笔设置",
      //   order: 100,
      // },
      // {
      //   id: "strokeLineCap",
      //   name: "线条端点",
      //   type: "select",
      //   defaultValue: this.strokeLineCap,
      //   options: [
      //     { value: "round", label: "圆形" },
      //     { value: "butt", label: "平直" },
      //     { value: "square", label: "方形" },
      //   ],
      //   description: "线条端点的形状",
      //   category: "铅笔设置",
      //   order: 110,
      // },
      // {
      //   id: "strokeLineJoin",
      //   name: "线条连接",
      //   type: "select",
      //   defaultValue: this.strokeLineJoin,
      //   options: [
      //     { value: "round", label: "圆角" },
      //     { value: "bevel", label: "斜角" },
      //     { value: "miter", label: "尖角" },
      //   ],
      //   description: "线条拐角的连接方式",
      //   category: "铅笔设置",
      //   order: 120,
      // },
      // {
      //   id: "smoothingEnabled",
      //   name: "启用平滑",
      //   type: "checkbox",
      //   defaultValue: false,
      //   description: "是否对线条进行平滑处理",
      //   category: "铅笔设置",
      //   order: 130,
      // },
      // {
      //   id: "smoothingFactor",
      //   name: "平滑程度",
      //   type: "slider",
      //   defaultValue: 0.5,
      //   min: 0,
      //   max: 1,
      //   step: 0.05,
      //   description: "线条平滑的强度",
      //   category: "铅笔设置",
      //   order: 140,
      //   // 只有当smoothingEnabled为true时才显示
      //   visibleWhen: { smoothingEnabled: true },
      // },
    ];

    // 合并并返回所有属性
    return [...baseProperties, ...pencilProperties];
  }

  /**
   * 更新笔刷属性
   * @param {String} propId 属性ID
   * @param {any} value 属性值
   * @returns {Boolean} 是否更新成功
   * @override
   */
  updateProperty(propId, value) {
    // 先检查基类能否处理此属性
    if (super.updateProperty(propId, value)) {
      return true;
    }

    // 处理铅笔特有属性
    if (propId === "decimate") {
      this.decimate = value;
      if (this.brush) {
        this.brush.decimate = value;
        return true;
      }
    } else if (propId === "strokeLineCap") {
      this.strokeLineCap = value;
      if (this.brush) {
        this.brush.strokeLineCap = value;
        return true;
      }
    } else if (propId === "strokeLineJoin") {
      this.strokeLineJoin = value;
      if (this.brush) {
        this.brush.strokeLineJoin = value;
        return true;
      }
    } else if (propId === "smoothingEnabled") {
      this.smoothingEnabled = value;
      // 实现平滑逻辑...
      return true;
    } else if (propId === "smoothingFactor") {
      this.smoothingFactor = value;
      // 实现平滑度调整...
      return true;
    }

    return false;
  }

  /**
   * 获取预览图
   * @returns {String} 预览图URL
   */
  getPreview() {
    // 实际项目中可以返回一个实际的预览图URL
    return "data:image/svg+xml;base64,..."; // 示例SVG
  }
}
