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

/**
 * 素描笔刷
 * 创建手绘素描效果，有不规则的线条和纹理
 */
export class SketchyBrush extends BaseBrush {
  /**
   * 构造函数
   * @param {Object} canvas fabric画布实例
   * @param {Object} options 配置选项
   */
  constructor(canvas, options = {}) {
    super(canvas, {
      id: "sketchy",
      name: "素描",
      description: "创建手绘素描效果，有不规则的线条和纹理",
      category: "绘画笔刷",
      icon: "sketchy",
      ...options,
    });

    // 素描笔刷特有属性
    this.roughness = options.roughness || 0.7;
    this.bowing = options.bowing || 0.5;
    this.stroke = options.stroke !== undefined ? options.stroke : true;
    this.hachureAngle = options.hachureAngle || 60;
    this.dashOffset = options.dashOffset || 0;
    this.dashArray = options.dashArray || [6, 2];
  }

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

    // 创建fabric原生素描笔刷
    this.brush = new fabric.SketchyBrush(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.width !== undefined) {
      brush.width = options.width;
    }

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

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

    // 素描笔刷特有属性
    if (options.roughness !== undefined) {
      this.roughness = options.roughness;

      // 如果原生笔刷支持此属性，则设置
      if (brush.roughness !== undefined) {
        brush.roughness = this.roughness;
      }
    }

    if (options.bowing !== undefined) {
      this.bowing = options.bowing;

      // 如果原生笔刷支持此属性，则设置
      if (brush.bowing !== undefined) {
        brush.bowing = this.bowing;
      }
    }

    if (options.stroke !== undefined) {
      this.stroke = options.stroke;

      // 如果原生笔刷支持此属性，则设置
      if (brush.stroke !== undefined) {
        brush.stroke = this.stroke;
      }
    }

    if (options.hachureAngle !== undefined) {
      this.hachureAngle = options.hachureAngle;

      // 如果原生笔刷支持此属性，则设置
      if (brush.hachureAngle !== undefined) {
        brush.hachureAngle = this.hachureAngle;
      }
    }

    if (options.dashOffset !== undefined) {
      this.dashOffset = options.dashOffset;

      // 如果原生笔刷支持此属性，则设置
      if (brush.dashOffset !== undefined) {
        brush.dashOffset = this.dashOffset;
      }
    }

    if (options.dashArray !== undefined) {
      this.dashArray = options.dashArray;

      // 如果原生笔刷支持此属性，则设置
      if (brush.dashArray !== undefined) {
        brush.dashArray = this.dashArray;
      }
    }

    // 为笔刷设置手绘效果
    const originalOnMouseMove = brush.onMouseMove;
    brush.onMouseMove = function (pointer, options) {
      // 添加微小随机偏移，模拟手绘效果
      const jitter = (this.width / 4) * this.roughness;
      pointer.x += (Math.random() - 0.5) * jitter;
      pointer.y += (Math.random() - 0.5) * jitter;

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

  /**
   * 设置粗糙度
   * @param {Number} value 粗糙度值(0-1)
   */
  setRoughness(value) {
    this.roughness = Math.max(0, Math.min(1, value));

    if (this.brush && this.brush.roughness !== undefined) {
      this.brush.roughness = this.roughness;
    }

    return this.roughness;
  }

  /**
   * 设置弯曲度
   * @param {Number} value 弯曲度值(0-1)
   */
  setBowing(value) {
    this.bowing = Math.max(0, Math.min(1, value));

    if (this.brush && this.brush.bowing !== undefined) {
      this.brush.bowing = this.bowing;
    }

    return this.bowing;
  }

  /**
   * 设置是否描边
   * @param {Boolean} value 是否描边
   */
  setStroke(value) {
    this.stroke = value;

    if (this.brush && this.brush.stroke !== undefined) {
      this.brush.stroke = this.stroke;
    }

    return this.stroke;
  }

  /**
   * 设置素描线条角度
   * @param {Number} value 角度值(0-180)
   */
  setHachureAngle(value) {
    this.hachureAngle = Math.max(0, Math.min(180, value));

    if (this.brush && this.brush.hachureAngle !== undefined) {
      this.brush.hachureAngle = this.hachureAngle;
    }

    return this.hachureAngle;
  }

  /**
   * 设置虚线偏移量
   * @param {Number} value 偏移量
   */
  setDashOffset(value) {
    this.dashOffset = value;

    if (this.brush && this.brush.dashOffset !== undefined) {
      this.brush.dashOffset = this.dashOffset;
    }

    return this.dashOffset;
  }

  /**
   * 设置虚线数组
   * @param {Array} value 虚线数组[线长, 间隔]
   */
  setDashArray(value) {
    if (Array.isArray(value) && value.length >= 2) {
      this.dashArray = value;

      if (this.brush && this.brush.dashArray !== undefined) {
        this.brush.dashArray = this.dashArray;
      }
    }

    return this.dashArray;
  }

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

    // 定义素描笔刷特有属性
    const sketchyProperties = [
      {
        id: "roughness",
        name: "粗糙度",
        type: "slider",
        defaultValue: this.roughness,
        min: 0,
        max: 1,
        step: 0.05,
        description: "控制素描线条的粗糙程度",
        category: "素描设置",
        order: 100,
      },
      {
        id: "bowing",
        name: "弯曲度",
        type: "slider",
        defaultValue: this.bowing,
        min: 0,
        max: 1,
        step: 0.05,
        description: "控制素描线条的弯曲程度",
        category: "素描设置",
        order: 110,
      },
      {
        id: "stroke",
        name: "描边",
        type: "checkbox",
        defaultValue: this.stroke,
        description: "是否使用描边",
        category: "素描设置",
        order: 120,
      },
      {
        id: "hachureAngle",
        name: "线条角度",
        type: "slider",
        defaultValue: this.hachureAngle,
        min: 0,
        max: 180,
        step: 5,
        description: "控制素描线条的角度",
        category: "素描设置",
        order: 130,
      },
      {
        id: "dashOffset",
        name: "虚线偏移",
        type: "slider",
        defaultValue: this.dashOffset,
        min: 0,
        max: 10,
        step: 1,
        description: "控制虚线的偏移量",
        category: "素描设置",
        order: 140,
      },
      {
        id: "dashArray",
        name: "虚线模式",
        type: "select",
        defaultValue: JSON.stringify(this.dashArray),
        options: [
          { value: JSON.stringify([0]), label: "实线" },
          { value: JSON.stringify([6, 2]), label: "短虚线" },
          { value: JSON.stringify([10, 5]), label: "长虚线" },
          { value: JSON.stringify([2, 2]), label: "点线" },
          { value: JSON.stringify([10, 5, 2, 5]), label: "点划线" },
        ],
        description: "设置虚线的模式",
        category: "素描设置",
        order: 150,
        parseValue: (value) => JSON.parse(value),
      },
    ];

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

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

    // 处理素描笔刷特有属性
    if (propId === "roughness") {
      this.setRoughness(value);
      return true;
    } else if (propId === "bowing") {
      this.setBowing(value);
      return true;
    } else if (propId === "stroke") {
      this.setStroke(value);
      return true;
    } else if (propId === "hachureAngle") {
      this.setHachureAngle(value);
      return true;
    } else if (propId === "dashOffset") {
      this.setDashOffset(value);
      return true;
    } else if (propId === "dashArray") {
      let parsedValue = value;
      if (typeof value === "string") {
        try {
          parsedValue = JSON.parse(value);
        } catch (e) {
          console.error("Invalid dashArray value:", e);
          return false;
        }
      }
      this.setDashArray(parsedValue);
      return true;
    }

    return false;
  }

  /**
   * 获取预览图
   * @returns {String} 预览图URL
   */
  getPreview() {
    return "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj48cGF0aCBkPSJNMjMgMzBDMjUgMjggNTIgMzggNzUgMzciIHN0cm9rZT0iIzAwMCIgc3Ryb2tlLXdpZHRoPSIzIiBmaWxsPSJub25lIiBzdHJva2UtbGluZWNhcD0icm91bmQiLz48cGF0aCBkPSJNMjIgNDBDMjIgMzggNTkgNDYgNzYgNDMiIHN0cm9rZT0iIzAwMCIgc3Ryb2tlLXdpZHRoPSIyIiBmaWxsPSJub25lIiBzdHJva2UtbGluZWNhcD0icm91bmQiLz48cGF0aCBkPSJNMjAgNTBDMjIgNDggNTYgNTYgNzYgNTIiIHN0cm9rZT0iIzAwMCIgc3Ryb2tlLXdpZHRoPSIyIiBmaWxsPSJub25lIiBzdHJva2UtbGluZWNhcD0icm91bmQiLz48cGF0aCBkPSJNMjQgNjBDMjMgNTggNDYgNjQgNzUgNjQiIHN0cm9rZT0iIzAwMCIgc3Ryb2tlLXdpZHRoPSIyLjgiIGZpbGw9Im5vbmUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIvPjxwYXRoIGQ9Ik0yNiA3MkMyNyA2OSA0OSA3NCA3NSA3MiIgc3Ryb2tlPSIjMDAwIiBzdHJva2Utd2lkdGg9IjIuNCIgZmlsbD0ibm9uZSIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+PC9zdmc+";
  }
}
