import { BaseBrush } from "../BaseBrush";
import { fabric } from "fabric-with-all";
import texturePresetManager from "../TexturePresetManager";
import i18n from "@/lang/index.ts";
const {t} = i18n.global;

/**
 * 纹理笔刷
 * 使用图像纹理进行绘制的笔刷
 */
export class TextureBrush extends BaseBrush {
  /**
   * 构造函数
   * @param {Object} canvas fabric画布实例
   * @param {Object} options 配置选项
   */
  constructor(canvas, options = {}) {
    super(canvas, {
      id: "texture",
      name: "纹理笔刷",
      description: "使用图像纹理进行绘制的笔刷",
      category: "特效笔刷",
      icon: "texture",
      ...options,
    });

    // 纹理笔刷特有属性
    this.textureSource = options.textureSource || null;
    this.textureRepeat = options.textureRepeat || "repeat";
    this.textureScale = options.textureScale || 1;
    this.textureAngle = options.textureAngle || 0;
    this.opacity = options.opacity !== undefined ? options.opacity : 1;

    // 预设材质相关
    this.selectedTextureId = options.selectedTextureId || null;
    this.texturePresets = [];

    // 加载预设材质
    this._loadTexturePresets();

    // 当前选中的材质索引
    this.currentTextureIndex = options.currentTextureIndex || 0;

    // 从预设管理器加载自定义材质
    texturePresetManager.loadCustomTexturesFromStorage();
  }

  /**
   * 加载材质预设
   * @private
   */
  _loadTexturePresets() {
    // 从预设管理器获取所有材质
    this.texturePresets = texturePresetManager.getAllTextures();

    // 如果没有选中的材质ID，使用第一个预设材质
    if (!this.selectedTextureId && this.texturePresets.length > 0) {
      this.selectedTextureId = this.texturePresets[0].id;
      this.currentTextureIndex = 0;
    }
  }

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

    // 创建fabric原生纹理笔刷
    this.brush = new fabric.PatternBrush(this.canvas);

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

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

      // 应用点简化（如果PatternBrush支持）
      if (this.decimate && this._points) {
        this._points = this.decimatePoints(this._points, this.decimate);
      }

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

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

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

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

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

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

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

      // 调用 convertToImg 方法将绘制内容转换为图片
      if (typeof this.convertToImg === "function") {
        this.convertToImg();
        console.log("TextureBrush: convertToImg called successfully");
      } 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);

    // 如果有选中的材质，则设置纹理
    if (this.selectedTextureId) {
      this.setTextureById(this.selectedTextureId);
    } else if (this.textureSource) {
      this.setTexture(this.textureSource);
    }

    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.color !== undefined) {
      brush.color = options.color;
    }

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

    // 纹理笔刷特有属性
    if (options.textureRepeat !== undefined) {
      this.textureRepeat = options.textureRepeat;
      // 需要重新应用纹理以应用重复模式
      if (this.selectedTextureId) {
        this.setTextureById(this.selectedTextureId);
      } else if (this.textureSource) {
        this.setTexture(this.textureSource);
      }
    }

    if (options.textureScale !== undefined) {
      this.textureScale = options.textureScale;
      // 需要重新应用纹理以应用缩放
      if (this.selectedTextureId) {
        this.setTextureById(this.selectedTextureId);
      } else if (this.textureSource) {
        this.setTexture(this.textureSource);
      }
    }

    if (options.textureAngle !== undefined) {
      this.textureAngle = options.textureAngle;
      // 需要重新应用纹理以应用旋转角度
      if (this.selectedTextureId) {
        this.setTextureById(this.selectedTextureId);
      } else if (this.textureSource) {
        this.setTexture(this.textureSource);
      }
    }

    if (options.opacity !== undefined) {
      this.opacity = options.opacity;
      // 需要重新应用纹理以应用透明度
      if (this.selectedTextureId) {
        this.setTextureById(this.selectedTextureId);
      } else if (this.textureSource) {
        this.setTexture(this.textureSource);
      }
    }
  }

  /**
   * 根据材质ID设置纹理
   * @param {String} textureId 材质ID
   * @returns {Promise} 加载完成的Promise
   */
  setTextureById(textureId) {
    const texture = texturePresetManager.getTextureById(textureId);
    if (!texture) {
      return Promise.reject(new Error(`材质 ${textureId} 不存在`));
    }

    this.selectedTextureId = textureId;

    // 更新当前材质索引
    const allTextures = texturePresetManager.getAllTextures();
    this.currentTextureIndex = allTextures.findIndex((t) => t.id === textureId);

    return this.setTexture(texture.path);
  }

  /**
   * 设置纹理
   * @param {String|Object} source 纹理源（URL或Image对象）
   * @returns {Promise} 加载完成的Promise
   */
  setTexture(source) {
    this.textureSource = source;

    if (!this.brush) {
      return Promise.reject(new Error("笔刷实例不存在"));
    }

    return new Promise((resolve, reject) => {
      if (typeof source === "string") {
        // 如果是URL，加载图像
        fabric.util.loadImage(source, (img) => {
          if (!img) {
            reject(new Error("纹理加载失败"));
            return;
          }
          this._applyTextureToPatternBrush(img);
          resolve(img);
        });
      } else if (source instanceof Image || source instanceof HTMLCanvasElement) {
        // 如果已经是Image或Canvas对象，直接使用
        this._applyTextureToPatternBrush(source);
        resolve(source);
      } else {
        reject(new Error("无效的纹理源"));
      }
    });
  }

  /**
   * 将纹理应用到PatternBrush
   * @param {Object} img 图像对象
   * @private
   */
  _applyTextureToPatternBrush(img) {
    if (!this.brush || !img) return;

    // 创建Canvas来处理纹理
    const canvasTexture = document.createElement("canvas");
    const ctx = canvasTexture.getContext("2d");

    // 根据缩放设置Canvas大小
    const width = img.width * this.textureScale;
    const height = img.height * this.textureScale;
    canvasTexture.width = width;
    canvasTexture.height = height;

    // 应用纹理透明度设置 - 仅控制纹理的透明度
    if (this.opacity < 1) {
      ctx.globalAlpha = this.opacity;
    }

    // 绘制前应用旋转
    if (this.textureAngle !== 0) {
      ctx.save();
      ctx.translate(width / 2, height / 2);
      ctx.rotate((this.textureAngle * Math.PI) / 180);
      ctx.translate(-width / 2, -height / 2);
      ctx.drawImage(img, 0, 0, width, height);
      ctx.restore();
    } else {
      ctx.drawImage(img, 0, 0, width, height);
    }

    // 缓存处理后的纹理图像
    this._processedTextureCanvas = canvasTexture;

    // 使用fabric.js 5.x正确的API方式设置PatternBrush
    // 直接设置source属性，这是PatternBrush的标准用法
    this.brush.source = canvasTexture;

    this.brush.canvas.opacity = this.opacity; // 确保画布不透明

    // 设置笔刷颜色为完全透明的RGBA，避免重复绘制时的叠加效果
    // 笔刷的透明度通过RGBA颜色控制，而不是通过globalAlpha
    const brushOpacity = this.brush.opacity || 1;
    this.brush.color = `rgba(0, 0, 0, ${brushOpacity})`;

    // 确保画布上下文使用完整的透明度，避免圆圈重叠问题
    // if (this.canvas && this.canvas.contextTop) {
    //   this.canvas.contextTop.globalAlpha = 1;
    // }

    // 通知画布重绘
    if (this.canvas && this.canvas.requestRenderAll) {
      this.canvas.requestRenderAll();
    }
  }

  /**
   * 设置纹理重复模式
   * @param {String} mode 重复模式：'repeat', 'repeat-x', 'repeat-y', 'no-repeat'
   * @returns {String} 设置后的重复模式
   */
  setTextureRepeat(mode) {
    const validModes = ["repeat", "repeat-x", "repeat-y", "no-repeat"];
    if (validModes.includes(mode)) {
      this.textureRepeat = mode;

      // 重新应用纹理以更新重复模式
      if (this.selectedTextureId) {
        this.setTextureById(this.selectedTextureId);
      } else if (this.textureSource) {
        this.setTexture(this.textureSource);
      }
    }

    return this.textureRepeat;
  }

  /**
   * 设置纹理缩放比例
   * @param {Number} scale 缩放比例
   * @returns {Number} 设置后的缩放比例
   */
  setTextureScale(scale) {
    this.textureScale = Math.max(0.1, scale);

    // 重新应用纹理以更新缩放
    if (this.selectedTextureId) {
      this.setTextureById(this.selectedTextureId);
    } else if (this.textureSource) {
      this.setTexture(this.textureSource);
    }

    return this.textureScale;
  }

  /**
   * 设置纹理旋转角度
   * @param {Number} angle 旋转角度（度）
   * @returns {Number} 设置后的旋转角度
   */
  setTextureAngle(angle) {
    this.textureAngle = angle % 360;

    // 重新应用纹理以更新旋转角度
    if (this.selectedTextureId) {
      this.setTextureById(this.selectedTextureId);
    } else if (this.textureSource) {
      this.setTexture(this.textureSource);
    }

    return this.textureAngle;
  }

  /**
   * 设置纹理透明度
   * @param {Number} opacity 透明度
   * @returns {Number} 设置后的透明度
   */
  setopacity(opacity) {
    this.opacity = Math.min(1, Math.max(0, opacity));

    // 重新应用纹理以更新透明度
    if (this.selectedTextureId) {
      this.setTextureById(this.selectedTextureId);
    } else if (this.textureSource) {
      this.setTexture(this.textureSource);
    }

    return this.opacity;
  }

  /**
   * 切换到下一个预设材质
   * @returns {Promise} 切换完成的Promise
   */
  nextTexture() {
    const textures = texturePresetManager.getAllTextures();
    if (textures.length === 0) return Promise.resolve();

    this.currentTextureIndex = (this.currentTextureIndex + 1) % textures.length;
    const nextTexture = textures[this.currentTextureIndex];

    return this.setTextureById(nextTexture.id);
  }

  /**
   * 切换到上一个预设材质
   * @returns {Promise} 切换完成的Promise
   */
  previousTexture() {
    const textures = texturePresetManager.getAllTextures();
    if (textures.length === 0) return Promise.resolve();

    this.currentTextureIndex =
      this.currentTextureIndex === 0 ? textures.length - 1 : this.currentTextureIndex - 1;
    const prevTexture = textures[this.currentTextureIndex];

    return this.setTextureById(prevTexture.id);
  }

  /**
   * 使用索引切换纹理
   * @param {Number} index 纹理索引
   */
  switchTexture(index) {
    const textures = texturePresetManager.getAllTextures();
    if (index >= 0 && index < textures.length) {
      this.currentTextureIndex = index;
      const texture = textures[index];
      return this.setTextureById(texture.id);
    }
    return Promise.reject(new Error("无效的纹理索引"));
  }

  /**
   * 获取当前选中的材质信息
   * @returns {Object|null} 材质信息
   */
  getCurrentTexture() {
    if (this.selectedTextureId) {
      return texturePresetManager.getTextureById(this.selectedTextureId);
    }
    return null;
  }

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

    // 获取所有可用材质
    const allTextures = texturePresetManager.getAllTextures();
    const textureOptions = allTextures.map((texture, index) => ({
      value: texture.id,
      label: texture.name,
      preview: texturePresetManager.getTexturePreviewUrl(texture),
      category: texture.category,
    }));

    // 定义纹理笔刷特有属性
    const textureProperties = [
      {
        id: "textureSelector",
        name: t('Canvas.TextureSelector'),
        type: "texture-grid",
        defaultValue: this.selectedTextureId,
        options: textureOptions,
        description: t('Canvas.selectTexture'),
        category: t('Canvas.TextureSettings'),
        order: 100,
        hidden: allTextures.length === 0,
      },
      // {
      //   id: "textureRepeat",
      //   name: "纹理重复模式",
      //   type: "select",
      //   defaultValue: this.textureRepeat,
      //   options: [
      //     { value: "repeat", label: "双向重复" },
      //     { value: "repeat-x", label: "水平重复" },
      //     { value: "repeat-y", label: "垂直重复" },
      //     { value: "no-repeat", label: "不重复" },
      //   ],
      //   description: "设置纹理的重复模式",
      //   category: "纹理设置",
      //   order: 110,
      // },
      // {
      //   id: "textureScale",
      //   name: "纹理缩放",
      //   type: "slider",
      //   defaultValue: this.textureScale,
      //   min: 0.1,
      //   max: 5,
      //   step: 0.1,
      //   description: "调整纹理的缩放比例",
      //   category: "纹理设置",
      //   order: 120,
      // },
      // {
      //   id: "textureAngle",
      //   name: "纹理旋转",
      //   type: "slider",
      //   defaultValue: this.textureAngle,
      //   min: 0,
      //   max: 360,
      //   step: 5,
      //   description: "调整纹理的旋转角度",
      //   category: "纹理设置",
      //   order: 130,
      // },
      // {
      //   id: "opacity",
      //   name: "纹理透明度",
      //   type: "slider",
      //   defaultValue: this.opacity,
      //   min: 0,
      //   max: 1,
      //   step: 0.05,
      //   description: "调整纹理的透明度",
      //   category: "纹理设置",
      //   order: 140,
      // },
      // {
      //   id: "uploadTexture",
      //   name: "上传纹理",
      //   type: "file",
      //   action: "uploadTexture",
      //   description: "上传自定义纹理",
      //   category: "纹理设置",
      //   order: 150,
      // },
      // {
      //   id: "texturePreview",
      //   name: "纹理预览",
      //   type: "preview",
      //   description: "当前纹理预览",
      //   category: "纹理设置",
      //   order: 160,
      //   getValue: () => {
      //     const currentTexture = this.getCurrentTexture();
      //     return currentTexture
      //       ? texturePresetManager.getTexturePreviewUrl(currentTexture)
      //       : null;
      //   },
      // },
    ];

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

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

    // 处理纹理笔刷特有属性
    if (propId === "textureSelector") {
      this.setTextureById(value);
      return true;
    } else if (propId === "textureRepeat") {
      this.setTextureRepeat(value);
      return true;
    } else if (propId === "textureScale") {
      this.setTextureScale(value);
      return true;
    } else if (propId === "textureAngle") {
      this.setTextureAngle(value);
      return true;
    } else if (propId === "opacity") {
      this.setopacity(value);
      return true;
    } else if (propId === "uploadTexture") {
      // 触发上传纹理事件
      // 这里通常由外部处理，返回true表示属性被处理
      return true;
    }

    return false;
  }

  /**
   * 添加自定义材质
   * @param {Object} textureData 材质数据
   * @returns {String} 材质ID
   */
  addCustomTexture(textureData) {
    const textureId = texturePresetManager.addCustomTexture(textureData);

    // 重新加载材质预设
    this._loadTexturePresets();

    // 保存到本地存储
    texturePresetManager.saveCustomTexturesToStorage();

    return textureId;
  }

  /**
   * 删除自定义材质
   * @param {String} textureId 材质ID
   * @returns {Boolean} 是否删除成功
   */
  removeCustomTexture(textureId) {
    const success = texturePresetManager.removeCustomTexture(textureId);

    if (success) {
      // 如果删除的是当前选中的材质，切换到第一个可用材质
      if (this.selectedTextureId === textureId) {
        const allTextures = texturePresetManager.getAllTextures();
        if (allTextures.length > 0) {
          this.setTextureById(allTextures[0].id);
        } else {
          this.selectedTextureId = null;
          this.currentTextureIndex = 0;
        }
      }

      // 重新加载材质预设
      this._loadTexturePresets();

      // 保存到本地存储
      texturePresetManager.saveCustomTexturesToStorage();
    }

    return success;
  }

  /**
   * 获取预览图
   * @returns {String} 预览图URL
   */
  getPreview() {
    const currentTexture = this.getCurrentTexture();
    if (currentTexture) {
      return texturePresetManager.getTexturePreviewUrl(currentTexture);
    }

    // 返回默认纹理预览
    return "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj48ZGVmcz48cGF0dGVybiBpZD0icGF0dGVybiIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgd2lkdGg9IjEwIiBoZWlnaHQ9IjEwIj48cmVjdCB3aWR0aD0iNSIgaGVpZ2h0PSI1IiBmaWxsPSIjZGRkIi8+PHJlY3QgeD0iNSIgeT0iNSIgd2lkdGg9IjUiIGhlaWdodD0iNSIgZmlsbD0iI2RkZCIvPjwvcGF0dGVybj48L2RlZnM+PHJlY3Qgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiIGZpbGw9InVybCgjcGF0dGVybikiLz48L3N2Zz4=";
  }

  /**
   * 笔刷被选中时调用
   * @override
   */
  onSelected() {
    // 重新加载材质预设（可能有新的自定义材质）
    this._loadTexturePresets();
  }

  /**
   * 销毁笔刷实例并清理资源
   * @override
   */
  destroy() {
    super.destroy();
    this.textureSource = null;
    this.selectedTextureId = null;
    this.texturePresets = [];
  }

  /**
   * 设置材质属性
   * @param {String} property 属性名称
   * @param {any} value 属性值
   * @returns {Boolean} 是否设置成功
   */
  setTextureProperty(property, value) {
    switch (property) {
      case "scale":
        return this.setTextureScale(value);
      case "opacity":
        return this.setopacity(value);
      case "repeat":
        return this.setTextureRepeat(value);
      case "angle":
        return this.setTextureAngle(value);
      default:
        return false;
    }
  }

  /**
   * 获取材质属性
   * @param {String} property 属性名称
   * @returns {any} 属性值
   */
  getTextureProperty(property) {
    switch (property) {
      case "scale":
        return this.textureScale;
      case "opacity":
        return this.opacity;
      case "repeat":
        return this.textureRepeat;
      case "angle":
        return this.textureAngle;
      case "textureId":
        return this.selectedTextureId;
      default:
        return undefined;
    }
  }

  /**
   * 应用材质预设
   * @param {String|Object} preset 预设ID或预设对象
   * @returns {Boolean} 是否应用成功
   */
  applyTexturePreset(preset) {
    let presetData = null;

    if (typeof preset === "string") {
      // 如果是预设ID，从预设管理器获取
      presetData = texturePresetManager.applyTexturePreset(preset);
    } else if (typeof preset === "object") {
      // 如果是预设对象，直接使用
      presetData = preset;
    }

    if (!presetData) {
      console.warn("无效的材质预设:", preset);
      return false;
    }

    // 应用预设设置
    if (presetData.textureId) {
      this.setTextureById(presetData.textureId);
    }

    if (presetData.scale !== undefined) {
      this.setTextureScale(presetData.scale);
    }

    if (presetData.opacity !== undefined) {
      this.setopacity(presetData.opacity);
    }

    if (presetData.repeat !== undefined) {
      this.setTextureRepeat(presetData.repeat);
    }

    if (presetData.angle !== undefined) {
      this.setTextureAngle(presetData.angle);
    }

    // 如果预设包含笔刷属性，也一并应用
    if (presetData.brushSize !== undefined && this.brush) {
      this.brush.width = presetData.brushSize;
    }

    if (presetData.brushOpacity !== undefined && this.brush) {
      this.brush.opacity = presetData.brushOpacity;
    }

    if (presetData.brushColor !== undefined && this.brush) {
      this.brush.color = presetData.brushColor;
    }

    return true;
  }

  /**
   * 获取当前材质状态
   * @returns {Object} 当前材质状态
   */
  getCurrentTextureState() {
    return {
      textureId: this.selectedTextureId,
      scale: this.textureScale,
      opacity: this.opacity,
      repeat: this.textureRepeat,
      angle: this.textureAngle,
      // 包含笔刷状态
      brushSize: this.brush ? this.brush.width : this.options.width,
      brushOpacity: this.brush ? this.brush.opacity : this.options.opacity,
      brushColor: this.brush ? this.brush.color : this.options.color,
    };
  }

  /**
   * 恢复材质状态
   * @param {Object} state 要恢复的状态
   * @returns {Boolean} 是否恢复成功
   */
  restoreTextureState(state) {
    if (!state) return false;

    try {
      // 恢复材质属性
      if (state.textureId) {
        this.setTextureById(state.textureId);
      }

      if (state.scale !== undefined) {
        this.setTextureScale(state.scale);
      }

      if (state.opacity !== undefined) {
        this.setopacity(state.opacity);
      }

      if (state.repeat !== undefined) {
        this.setTextureRepeat(state.repeat);
      }

      if (state.angle !== undefined) {
        this.setTextureAngle(state.angle);
      }

      // 恢复笔刷属性
      if (this.brush) {
        if (state.brushSize !== undefined) {
          this.brush.width = state.brushSize;
        }

        if (state.brushOpacity !== undefined) {
          this.brush.opacity = state.brushOpacity;
        }

        if (state.brushColor !== undefined) {
          this.brush.color = state.brushColor;
        }
      }

      return true;
    } catch (error) {
      console.error("恢复材质状态失败:", error);
      return false;
    }
  }

  /**
   * 创建材质预设
   * @param {String} name 预设名称
   * @returns {String} 预设ID
   */
  createTexturePreset(name) {
    const currentState = this.getCurrentTextureState();
    return texturePresetManager.createTexturePreset(name, currentState);
  }

  /**
   * 获取可用的材质分类
   * @returns {Array} 分类数组
   */
  getTextureCategories() {
    return texturePresetManager.getCategories();
  }

  /**
   * 根据分类获取材质
   * @param {String} category 分类名称
   * @returns {Array} 材质数组
   */
  getTexturesByCategory(category) {
    return texturePresetManager.getTexturesByCategory(category);
  }

  /**
   * 搜索材质
   * @param {String} query 搜索关键词
   * @returns {Array} 匹配的材质数组
   */
  searchTextures(query) {
    return texturePresetManager.searchTextures(query);
  }

  /**
   * 预加载材质图像
   * @param {String} textureId 材质ID
   * @returns {Promise<HTMLImageElement>} 图像对象
   */
  preloadTexture(textureId) {
    return texturePresetManager.loadTextureImage(textureId);
  }

  /**
   * 批量预加载材质
   * @param {Array} textureIds 材质ID数组
   * @returns {Promise<Array>} 加载结果数组
   */
  preloadTextures(textureIds) {
    const loadPromises = textureIds.map((id) =>
      this.preloadTexture(id).catch((error) => ({ id, error }))
    );
    return Promise.all(loadPromises);
  }

  /**
   * 获取材质统计信息
   * @returns {Object} 统计信息
   */
  getTextureStats() {
    return texturePresetManager.getStats();
  }

  /**
   * 检查 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);
  }
}
