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

/**
 * 例子：霓虹笔刷
 * 创建带有发光效果的霓虹笔刷
 */
export class NeonBrush extends BaseBrush {
  /**
   * 构造函数
   * @param {Object} canvas fabric画布实例
   * @param {Object} options 配置选项
   */
  constructor(canvas, options = {}) {
    super(canvas, {
      id: "neon",
      name: "霓虹笔",
      description: "带有发光效果的霓虹笔刷",
      category: "特效笔刷",
      icon: "neon",
      ...options,
    });

    // 霓虹笔特有属性
    this.glowIntensity = options.glowIntensity || 10;
    this.glowColor = options.glowColor || this.options.color || "#00ffff";
  }

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

    // 使用基础的铅笔笔刷
    this.brush = new fabric.PencilBrush(this.canvas);

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

    return this.brush;
  }

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

    // 设置基本属性
    if (options.color) {
      brush.color = options.color;
      // 更新发光颜色
      this.glowColor = options.glowColor || options.color;
    }

    if (options.width !== undefined) {
      brush.width = options.width;
    }

    if (options.opacity !== undefined) {
      brush.opacity = options.opacity;
    }

    // 霓虹特有设置 - 发光效果
    const glowSize = options.glowIntensity || this.glowIntensity;
    brush.shadow = new fabric.Shadow({
      color: this.glowColor,
      blur: glowSize,
      offsetX: 0,
      offsetY: 0,
    });

    // 设置线条连接方式，使连接处更圆滑
    brush.strokeLineCap = "round";
    brush.strokeLineJoin = "round";

    // 设置合成模式为"lighter"，使重叠部分更亮
    brush.globalCompositeOperation = "lighter";
  }

  /**
   * 设置发光强度
   * @param {Number} intensity 发光强度
   */
  setGlowIntensity(intensity) {
    this.glowIntensity = Math.max(0, Math.min(30, intensity));

    // 如果笔刷已创建，更新设置
    if (this.brush && this.brush.shadow) {
      this.brush.shadow.blur = this.glowIntensity;
      if (this.canvas) {
        this.canvas.renderAll();
      }
    }

    return this.glowIntensity;
  }

  /**
   * 设置发光颜色
   * @param {String} color 颜色值
   */
  setGlowColor(color) {
    this.glowColor = color;

    // 如果笔刷已创建，更新设置
    if (this.brush && this.brush.shadow) {
      this.brush.shadow.color = color;
      if (this.canvas) {
        this.canvas.renderAll();
      }
    }

    return this.glowColor;
  }

  /**
   * 获取笔刷可配置属性
   * @returns {Array} 可配置属性描述数组
   * @override
   */
  getConfigurableProperties() {
    // 获取基础属性
    const baseProperties = super.getConfigurableProperties();

    // 添加霓虹笔特有属性
    const neonProperties = [
      {
        id: "glowIntensity",
        name: "发光强度",
        type: "slider",
        defaultValue: 10,
        min: 1,
        max: 30,
        step: 1,
        description: "霓虹笔发光效果的强度",
        category: "特效",
        order: 100,
      },
      {
        id: "glowColor",
        name: "发光颜色",
        type: "color",
        defaultValue: this.glowColor,
        description: "发光效果的颜色",
        category: "特效",
        order: 110,
      },
    ];

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

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

    // 处理霓虹笔特有属性
    if (propId === "glowIntensity") {
      this.setGlowIntensity(value);
      return true;
    } else if (propId === "glowColor") {
      this.setGlowColor(value);
      return true;
    }

    return false;
  }
}

/**
 * 例子：彩虹笔刷
 * 创建随着绘制会变换颜色的彩虹效果笔刷
 */
export class RainbowBrush extends BaseBrush {
  /**
   * 构造函数
   * @param {Object} canvas fabric画布实例
   * @param {Object} options 配置选项
   */
  constructor(canvas, options = {}) {
    super(canvas, {
      id: "rainbow",
      name: "彩虹笔",
      description: "绘制时会自动变换颜色的彩虹笔",
      category: "特效笔刷",
      icon: "rainbow",
      ...options,
    });

    // 彩虹笔特有属性
    this.colorSpeed = options.colorSpeed || 10; // 颜色变化速度
    this.hue = 0; // 当前色相值
    this.colorUpdateInterval = null;
  }

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

    // 使用铅笔笔刷
    this.brush = new fabric.PencilBrush(this.canvas);

    // 配置基本属性
    this.configure(this.brush, this.options);

    // 覆盖onMouseDown方法，开始颜色循环
    const originalMouseDown = this.brush.onMouseDown;
    this.brush.onMouseDown = (pointer, options) => {
      // 开始颜色循环
      this.startColorCycle();

      // 调用原始方法
      return originalMouseDown.call(this.brush, pointer, options);
    };

    // 覆盖onMouseUp方法，停止颜色循环
    const originalMouseUp = this.brush.onMouseUp;
    this.brush.onMouseUp = (options) => {
      // 停止颜色循环
      this.stopColorCycle();

      // 调用原始方法
      return originalMouseUp.call(this.brush, options);
    };

    return this.brush;
  }

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

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

    if (options.opacity !== undefined) {
      brush.opacity = options.opacity;
    }

    // 初始颜色
    brush.color = this.getCurrentColor();

    // 彩虹笔特有设置
    brush.strokeLineCap = "round";
    brush.strokeLineJoin = "round";

    // 设置笔刷颜色变化速度
    if (options.colorSpeed !== undefined) {
      this.colorSpeed = options.colorSpeed;
    }
  }

  /**
   * 开始颜色循环
   */
  startColorCycle() {
    // 停止之前的循环
    this.stopColorCycle();

    // 创建新的循环
    this.colorUpdateInterval = setInterval(() => {
      // 更新色相值
      this.hue = (this.hue + this.colorSpeed) % 360;

      // 更新笔刷颜色
      if (this.brush) {
        this.brush.color = this.getCurrentColor();
      }
    }, 50); // 每50ms更新一次颜色
  }

  /**
   * 停止颜色循环
   */
  stopColorCycle() {
    if (this.colorUpdateInterval) {
      clearInterval(this.colorUpdateInterval);
      this.colorUpdateInterval = null;
    }
  }

  /**
   * 获取当前HSL颜色
   * @returns {String} HSL颜色字符串
   */
  getCurrentColor() {
    return `hsl(${this.hue}, 100%, 50%)`;
  }

  /**
   * 设置颜色变化速度
   * @param {Number} speed 变化速度
   */
  setColorSpeed(speed) {
    this.colorSpeed = Math.max(1, Math.min(50, speed));
    return this.colorSpeed;
  }

  /**
   * 获取笔刷可配置属性
   * @returns {Array} 可配置属性描述数组
   * @override
   */
  getConfigurableProperties() {
    // 获取基础属性
    const baseProperties = super.getConfigurableProperties();

    // 添加彩虹笔特有属性
    const rainbowProperties = [
      {
        id: "colorSpeed",
        name: "颜色变化速度",
        type: "slider",
        defaultValue: this.colorSpeed,
        min: 1,
        max: 50,
        step: 1,
        description: "彩虹颜色变化的速度",
        category: "特效",
        order: 100,
      },
    ];

    // 移除基础属性中的颜色选择器，因为彩虹笔不需要颜色选择
    const filteredBaseProps = baseProperties.filter((prop) => prop.id !== "color");

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

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

    // 处理彩虹笔特有属性
    if (propId === "colorSpeed") {
      this.setColorSpeed(value);
      return true;
    }

    return false;
  }

  /**
   * 笔刷被选中
   */
  onSelected() {
    // 在笔刷被选中时可以做一些初始化工作
  }

  /**
   * 笔刷被取消选中
   */
  onDeselected() {
    // 停止所有循环
    this.stopColorCycle();
  }

  /**
   * 销毁笔刷实例
   */
  destroy() {
    this.stopColorCycle();
    super.destroy();
  }
}

/**
 * 自定义笔刷示例
 * 展示如何创建具有复杂特有属性的自定义笔刷
 */
export class CustomBrushExample extends BaseBrush {
  /**
   * 构造函数
   * @param {Object} canvas fabric画布实例
   * @param {Object} options 配置选项
   */
  constructor(canvas, options = {}) {
    super(canvas, {
      id: "custom_example",
      name: "特效笔刷",
      description: "一个具有多种特效的自定义笔刷",
      category: "效果笔刷",
      icon: "magic",
      ...options,
    });

    // 特有属性初始化
    this.effectType = options.effectType || "neon";
    this.patternType = options.patternType || "solid";
    this.particleCount = options.particleCount || 10;
    this.particleSize = options.particleSize || 3;
    this.dashPattern = options.dashPattern || [0, 0]; // 实线
    this.noiseAmount = options.noiseAmount || 0;
    this.gradientEnabled = options.gradientEnabled || false;
    this.gradientColors = options.gradientColors || ["#ff0000", "#ffff00", "#00ff00"];
    this.angle = options.angle || 0;

    // 材质相关属性
    this.textureEnabled = options.textureEnabled || false;
    this.texturePath = options.texturePath || "";
    this.textureScale = options.textureScale || 1;
    this.textureOpacity = options.textureOpacity || 1;

    // 动画相关
    this.animationEnabled = options.animationEnabled || false;
    this.animationType = options.animationType || "none";
    this.animationSpeed = options.animationSpeed || 1;

    // 缓存的渐变和材质对象
    this._gradient = null;
    this._texture = null;
  }

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

    // 根据效果类型选择合适的基础笔刷
    switch (this.effectType) {
      case "neon":
        this.brush = new fabric.PencilBrush(this.canvas);
        break;
      case "spray":
        this.brush = new fabric.SprayBrush(this.canvas);
        break;
      case "pattern":
        this.brush = new fabric.PatternBrush(this.canvas);
        break;
      case "custom":
        // 创建完全自定义的笔刷
        this.brush = this._createCustomBrush();
        break;
      default:
        this.brush = new fabric.PencilBrush(this.canvas);
    }

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

    return this.brush;
  }

  /**
   * 创建完全自定义的笔刷
   * @private
   * @returns {Object} 自定义笔刷对象
   */
  _createCustomBrush() {
    // 这里可以实现完全自定义的笔刷逻辑
    // 例如通过继承fabric.BaseBrush并覆盖其方法

    // 示例：简单的自定义笔刷，这里只是概念演示
    const customBrush = new fabric.PencilBrush(this.canvas);

    // 覆盖绘制方法来实现自定义效果
    const originalOnMouseMove = customBrush.onMouseMove;
    customBrush.onMouseMove = (pointer, options) => {
      // 添加自定义效果，比如随机抖动
      if (this.noiseAmount > 0) {
        pointer.x += (Math.random() - 0.5) * this.noiseAmount;
        pointer.y += (Math.random() - 0.5) * this.noiseAmount;
      }

      // 调用原始方法
      originalOnMouseMove.call(customBrush, pointer, options);
    };

    return customBrush;
  }

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

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

    if (options.color !== undefined) {
      brush.color = options.color;
    }

    if (options.opacity !== undefined) {
      brush.opacity = options.opacity;
    }

    // 根据效果类型应用不同的配置
    switch (this.effectType) {
      case "neon":
        this._configureNeonEffect(brush);
        break;
      case "spray":
        this._configureSprayEffect(brush);
        break;
      case "pattern":
        this._configurePatternEffect(brush);
        break;
      case "custom":
        this._configureCustomEffect(brush);
        break;
    }

    // 配置虚线效果
    if (this.patternType === "dashed" && Array.isArray(this.dashPattern)) {
      brush.strokeDashArray = this.dashPattern;
    } else {
      brush.strokeDashArray = null;
    }

    // 配置渐变
    if (this.gradientEnabled) {
      this._configureGradient(brush);
    }

    // 配置材质
    if (this.textureEnabled && this.texturePath) {
      this._loadTextureImage();
    }

    // 配置动画
    if (this.animationEnabled) {
      this._configureAnimation(brush);
    }
  }

  /**
   * 配置霓虹灯效果
   * @private
   * @param {Object} brush 笔刷实例
   */
  _configureNeonEffect(brush) {
    // 霓虹灯效果 - 添加阴影效果
    brush.shadow = new fabric.Shadow({
      color: brush.color,
      blur: 15,
      offsetX: 0,
      offsetY: 0,
    });

    // 增加笔刷的不透明度
    brush.opacity = Math.min(1, brush.opacity * 1.2);
  }

  /**
   * 配置喷枪效果
   * @private
   * @param {Object} brush 笔刷实例
   */
  _configureSprayEffect(brush) {
    if (brush.density !== undefined) {
      brush.density = this.particleCount;
    }

    if (brush.dotWidth !== undefined) {
      brush.dotWidth = this.particleSize;
    }

    if (brush.randomOpacity !== undefined) {
      brush.randomOpacity = true;
    }
  }

  /**
   * 配置图案效果
   * @private
   * @param {Object} brush 笔刷实例
   */
  _configurePatternEffect(brush) {
    // 如果有纹理，则使用纹理作为图案
    if (this._texture) {
      brush.source = this._texture;
    } else {
      // 否则创建简单的图案
      const patternCanvas = document.createElement("canvas");
      patternCanvas.width = 20;
      patternCanvas.height = 20;
      const ctx = patternCanvas.getContext("2d");

      ctx.fillStyle = brush.color;

      switch (this.patternType) {
        case "dots":
          // 绘制圆点
          ctx.beginPath();
          ctx.arc(10, 10, 5, 0, Math.PI * 2);
          ctx.fill();
          break;
        case "lines":
          // 绘制线条
          ctx.lineWidth = 2;
          ctx.beginPath();
          ctx.moveTo(0, 10);
          ctx.lineTo(20, 10);
          ctx.stroke();
          break;
        default:
          // 实心
          ctx.fillRect(0, 0, 20, 20);
      }

      brush.source = patternCanvas;
    }
  }

  /**
   * 配置自定义效果
   * @private
   * @param {Object} brush 笔刷实例
   */
  _configureCustomEffect(brush) {
    // 实现自定义效果...
    brush.globalCompositeOperation = "source-over";
  }

  /**
   * 配置渐变
   * @private
   * @param {Object} brush 笔刷实例
   */
  _configureGradient(brush) {
    // 创建线性渐变
    const gradient = new fabric.Gradient({
      type: "linear",
      coords: {
        x1: 0,
        y1: 0,
        x2: 100,
        y2: 0,
      },
      colorStops: this.gradientColors.map((color, i) => {
        return {
          offset: i / (this.gradientColors.length - 1),
          color: color,
        };
      }),
      gradientAngle: this.angle,
    });

    // 存储渐变
    this._gradient = gradient;

    // 在这里无法直接将渐变应用到笔刷
    // 需要在实际绘制时使用...
  }

  /**
   * 配置动画
   * @private
   * @param {Object} brush 笔刷实例
   */
  _configureAnimation(brush) {
    // 动画需要在画布上持续更新
    // 这里只是示例，实际实现需要更复杂的处理
    if (!this._animationID) {
      this._startAnimation();
    }
  }

  /**
   * 开始动画
   * @private
   */
  _startAnimation() {
    let phase = 0;

    const animate = () => {
      phase += 0.05 * this.animationSpeed;

      // 执行动画效果
      switch (this.animationType) {
        case "pulse":
          // 脉冲效果 - 改变大小
          if (this.brush) {
            const baseWidth = this.options.width || 5;
            this.brush.width = baseWidth + Math.sin(phase) * baseWidth * 0.3;
          }
          break;
        case "rainbow":
          // 彩虹效果 - 改变颜色
          if (this.brush) {
            const hue = (phase * 30) % 360;
            this.brush.color = `hsl(${hue}, 100%, 50%)`;
          }
          break;
      }

      // 请求下一帧
      this._animationID = requestAnimationFrame(animate);
    };

    this._animationID = requestAnimationFrame(animate);
  }

  /**
   * 停止动画
   * @private
   */
  _stopAnimation() {
    if (this._animationID) {
      cancelAnimationFrame(this._animationID);
      this._animationID = null;
    }
  }

  /**
   * 加载材质图片
   * @private
   * @returns {Promise} Promise对象
   */
  _loadTextureImage() {
    return new Promise((resolve, reject) => {
      if (!this.texturePath) {
        this._texture = null;
        reject(new Error("未指定材质路径"));
        return;
      }

      const img = new Image();
      img.crossOrigin = "anonymous";

      img.onload = () => {
        // 创建缩放后的图案
        const patternCanvas = document.createElement("canvas");
        const patternContext = patternCanvas.getContext("2d");

        // 调整图案大小
        const scale = this.textureScale || 1;
        const width = img.width * scale;
        const height = img.height * scale;

        patternCanvas.width = width;
        patternCanvas.height = height;

        // 应用透明度
        if (this.textureOpacity < 1) {
          patternContext.globalAlpha = this.textureOpacity;
        }

        // 绘制缩放后的图像
        patternContext.drawImage(img, 0, 0, width, height);

        this._texture = patternCanvas;

        // 如果当前是图案模式，重新配置笔刷
        if (this.effectType === "pattern" && this.brush) {
          this.brush.source = patternCanvas;
        }

        resolve(img);
      };

      img.onerror = () => {
        this._texture = null;
        reject(new Error(`加载材质图片失败: ${this.texturePath}`));
      };

      img.src = this.texturePath;
    });
  }

  /**
   * 获取笔刷可配置属性
   * @returns {Array} 可配置属性描述数组
   * @override
   */
  getConfigurableProperties() {
    // 获取基础属性
    const baseProperties = super.getConfigurableProperties();

    // 特效类型选择
    const effectTypeProperty = {
      id: "effectType",
      name: "特效类型",
      type: "select",
      defaultValue: this.effectType,
      options: [
        { value: "neon", label: "霓虹灯" },
        { value: "spray", label: "喷枪" },
        { value: "pattern", label: "图案" },
        { value: "custom", label: "自定义" },
      ],
      description: "选择笔刷特效类型",
      category: "特效设置",
      order: 100,
    };

    // 定义基于特效类型的动态属性
    const dynamicProperties = [
      // 喷枪效果特有属性
      {
        id: "particleCount",
        name: "粒子数量",
        type: "slider",
        defaultValue: this.particleCount,
        min: 1,
        max: 50,
        step: 1,
        description: "喷枪效果的粒子密度",
        category: "特效设置",
        order: 110,
        visibleWhen: { effectType: "spray" },
      },
      {
        id: "particleSize",
        name: "粒子大小",
        type: "slider",
        defaultValue: this.particleSize,
        min: 1,
        max: 20,
        step: 1,
        description: "喷枪效果的粒子大小",
        category: "特效设置",
        order: 120,
        visibleWhen: { effectType: "spray" },
      },

      // 图案效果特有属性
      {
        id: "patternType",
        name: "图案类型",
        type: "select",
        defaultValue: this.patternType,
        options: [
          { value: "solid", label: "实心" },
          { value: "dots", label: "圆点" },
          { value: "lines", label: "线条" },
          { value: "dashed", label: "虚线" },
        ],
        description: "选择图案类型",
        category: "特效设置",
        order: 130,
        visibleWhen: (values) => values.effectType === "pattern" || values.patternType === "dashed",
      },

      // 虚线特有属性
      {
        id: "dashPattern1",
        name: "虚线长度",
        type: "slider",
        defaultValue: this.dashPattern[0] || 5,
        min: 1,
        max: 20,
        step: 1,
        description: "虚线段的长度",
        category: "特效设置",
        order: 140,
        visibleWhen: { patternType: "dashed" },
      },
      {
        id: "dashPattern2",
        name: "虚线间隔",
        type: "slider",
        defaultValue: this.dashPattern[1] || 5,
        min: 1,
        max: 20,
        step: 1,
        description: "虚线段之间的间隔",
        category: "特效设置",
        order: 150,
        visibleWhen: { patternType: "dashed" },
      },

      // 自定义效果特有属性
      {
        id: "noiseAmount",
        name: "噪点强度",
        type: "slider",
        defaultValue: this.noiseAmount,
        min: 0,
        max: 20,
        step: 0.5,
        description: "添加随机噪点的强度",
        category: "特效设置",
        order: 160,
        visibleWhen: { effectType: "custom" },
      },
    ];

    // 渐变相关属性
    const gradientProperties = [
      {
        id: "gradientEnabled",
        name: "启用渐变",
        type: "checkbox",
        defaultValue: this.gradientEnabled,
        description: "使用渐变色代替纯色",
        category: "渐变设置",
        order: 200,
      },
      {
        id: "gradientColor1",
        name: "渐变颜色 1",
        type: "color",
        defaultValue: this.gradientColors[0] || "#ff0000",
        description: "渐变的起始颜色",
        category: "渐变设置",
        order: 210,
        visibleWhen: { gradientEnabled: true },
      },
      {
        id: "gradientColor2",
        name: "渐变颜色 2",
        type: "color",
        defaultValue: this.gradientColors[1] || "#ffff00",
        description: "渐变的中间颜色",
        category: "渐变设置",
        order: 220,
        visibleWhen: { gradientEnabled: true },
      },
      {
        id: "gradientColor3",
        name: "渐变颜色 3",
        type: "color",
        defaultValue: this.gradientColors[2] || "#00ff00",
        description: "渐变的结束颜色",
        category: "渐变设置",
        order: 230,
        visibleWhen: { gradientEnabled: true },
      },
      {
        id: "angle",
        name: "渐变角度",
        type: "slider",
        defaultValue: this.angle,
        min: 0,
        max: 360,
        step: 5,
        description: "渐变的方向角度",
        category: "渐变设置",
        order: 240,
        visibleWhen: { gradientEnabled: true },
      },
    ];

    // 材质相关属性
    const textureProperties = [
      {
        id: "textureEnabled",
        name: "启用材质",
        type: "checkbox",
        defaultValue: this.textureEnabled,
        description: "使用图片材质",
        category: "材质设置",
        order: 300,
      },
      {
        id: "texturePath",
        name: "材质图片",
        type: "file",
        defaultValue: this.texturePath,
        description: "上传或选择要用作笔刷的图片材质",
        category: "材质设置",
        order: 310,
        accept: "image/*",
        visibleWhen: { textureEnabled: true },
      },
      {
        id: "textureScale",
        name: "材质缩放",
        type: "slider",
        defaultValue: this.textureScale,
        min: 0.1,
        max: 5.0,
        step: 0.1,
        description: "调整材质图片的大小",
        category: "材质设置",
        order: 320,
        visibleWhen: { textureEnabled: true },
      },
      {
        id: "textureOpacity",
        name: "材质透明度",
        type: "slider",
        defaultValue: this.textureOpacity,
        min: 0.1,
        max: 1.0,
        step: 0.05,
        description: "调整材质图片的透明度",
        category: "材质设置",
        order: 330,
        visibleWhen: { textureEnabled: true },
      },
      {
        id: "presetTextures",
        name: "预设材质",
        type: "texture-grid",
        defaultValue: "",
        options: [
          {
            value: "/textures/brush1.png",
            preview: "/textures/brush1_thumb.png",
            label: "纹理1",
          },
          {
            value: "/textures/brush2.png",
            preview: "/textures/brush2_thumb.png",
            label: "纹理2",
          },
        ],
        description: "选择预设材质图案",
        category: "材质设置",
        order: 340,
        visibleWhen: { textureEnabled: true },
        // 动态选项加载（示例）
        dynamicOptions: (values) => {
          // 这里可以根据其他属性值动态加载不同的材质选项
          // 例如从服务器获取，或者根据effectType显示不同的材质集
          const defaultOptions = [
            {
              value: "/textures/brush1.png",
              preview: "/textures/brush1_thumb.png",
              label: "纹理1",
            },
            {
              value: "/textures/brush2.png",
              preview: "/textures/brush2_thumb.png",
              label: "纹理2",
            },
          ];

          if (values.effectType === "neon") {
            defaultOptions.push({
              value: "/textures/neon_glow.png",
              preview: "/textures/neon_glow_thumb.png",
              label: "霓虹光晕",
            });
          }

          return defaultOptions;
        },
      },
    ];

    // 动画相关属性
    const animationProperties = [
      {
        id: "animationEnabled",
        name: "启用动画",
        type: "checkbox",
        defaultValue: this.animationEnabled,
        description: "为笔刷添加动态动画效果",
        category: "动画设置",
        order: 400,
      },
      {
        id: "animationType",
        name: "动画类型",
        type: "select",
        defaultValue: this.animationType,
        options: [
          { value: "none", label: "无" },
          { value: "pulse", label: "脉冲" },
          { value: "rainbow", label: "彩虹" },
        ],
        description: "选择动画效果类型",
        category: "动画设置",
        order: 410,
        visibleWhen: { animationEnabled: true },
      },
      {
        id: "animationSpeed",
        name: "动画速度",
        type: "slider",
        defaultValue: this.animationSpeed,
        min: 0.1,
        max: 5,
        step: 0.1,
        description: "调整动画播放速度",
        category: "动画设置",
        order: 420,
        visibleWhen: { animationEnabled: true },
      },
    ];

    // 合并并返回所有属性
    return [
      ...baseProperties,
      effectTypeProperty,
      ...dynamicProperties,
      ...gradientProperties,
      ...textureProperties,
      ...animationProperties,
    ];
  }

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

    // 处理特效笔刷特有属性
    switch (propId) {
      case "effectType":
        this.effectType = value;
        // 需要重新创建笔刷
        if (this.canvas) {
          this.destroy();
          this.brush = this.create();
        }
        return true;

      case "patternType":
        this.patternType = value;
        this.configure(this.brush, {});
        return true;

      case "particleCount":
        this.particleCount = value;
        if (this.effectType === "spray" && this.brush) {
          this.brush.density = value;
        }
        return true;

      case "particleSize":
        this.particleSize = value;
        if (this.effectType === "spray" && this.brush) {
          this.brush.dotWidth = value;
        }
        return true;

      case "dashPattern1":
      case "dashPattern2": {
        // 更新虚线模式
        const idx = propId === "dashPattern1" ? 0 : 1;
        this.dashPattern[idx] = value;
        if (this.patternType === "dashed" && this.brush) {
          this.brush.strokeDashArray = this.dashPattern;
        }
        return true;
      }

      case "noiseAmount":
        this.noiseAmount = value;
        return true;

      case "gradientEnabled":
        this.gradientEnabled = value;
        if (value && this.brush) {
          this._configureGradient(this.brush);
        }
        return true;

      case "gradientColor1":
      case "gradientColor2":
      case "gradientColor3": {
        const colorIdx = parseInt(propId.slice(-1)) - 1;
        this.gradientColors[colorIdx] = value;
        if (this.gradientEnabled && this.brush) {
          this._configureGradient(this.brush);
        }
        return true;
      }

      case "angle":
        this.angle = value;
        if (this.gradientEnabled && this.brush) {
          this._configureGradient(this.brush);
        }
        return true;

      case "textureEnabled":
        this.textureEnabled = value;
        if (value && this.texturePath) {
          this._loadTextureImage();
        }
        return true;

      case "texturePath":
        this.texturePath = value;
        if (this.textureEnabled && value) {
          this._loadTextureImage();
        }
        return true;

      case "textureScale":
        this.textureScale = value;
        if (this.textureEnabled && this.texturePath) {
          this._loadTextureImage();
        }
        return true;

      case "textureOpacity":
        this.textureOpacity = value;
        if (this.textureEnabled && this.texturePath) {
          this._loadTextureImage();
        }
        return true;

      case "animationEnabled":
        this.animationEnabled = value;
        if (value) {
          this._startAnimation();
        } else {
          this._stopAnimation();
        }
        return true;

      case "animationType":
        this.animationType = value;
        return true;

      case "animationSpeed":
        this.animationSpeed = value;
        return true;
    }

    return false;
  }

  /**
   * 获取预览图
   * @returns {String} 预览图URL
   */
  getPreview() {
    // 根据效果类型返回不同的预览图
    switch (this.effectType) {
      case "neon":
        return "data:image/svg+xml;base64,..."; // 示例图
      case "spray":
        return "data:image/svg+xml;base64,..."; // 示例图
      case "pattern":
        if (this._texture) {
          // 返回材质图
          return this._texture.toDataURL();
        }
        return "data:image/svg+xml;base64,..."; // 示例图
      default:
        return "data:image/svg+xml;base64,..."; // 示例图
    }
  }

  /**
   * 笔刷被选中时调用
   * @override
   */
  onSelected() {
    // 如果启用了动画，开始动画循环
    if (this.animationEnabled) {
      this._startAnimation();
    }
  }

  /**
   * 笔刷被取消选中时调用
   * @override
   */
  onDeselected() {
    // 停止动画
    this._stopAnimation();
  }

  /**
   * 销毁笔刷实例并清理资源
   * @override
   */
  destroy() {
    // 停止动画
    this._stopAnimation();

    // 清理资源
    this._gradient = null;
    this._texture = null;

    // 调用基类销毁方法
    super.destroy();
  }
}

// 导出函数，用于注册这些自定义笔刷
export function registerCustomBrushes() {
  // 注册霓虹笔刷
  brushRegistry.register("neon", NeonBrush, {
    name: "霓虹笔",
    description: "带有发光效果的霓虹笔刷",
    category: "特效笔刷",
  });

  // 注册彩虹笔刷
  brushRegistry.register("rainbow", RainbowBrush, {
    name: "彩虹笔",
    description: "绘制时会自动变换颜色的彩虹笔",
    category: "特效笔刷",
  });

  console.log("已注册自定义笔刷");
}
