import { fabric } from "fabric-with-all";
import { createLayer, LayerType, OperationType } from "../utils/layerHelper.js";
import { BatchInitializeRedGreenModeCommand } from "../commands/RedGreenCommands.js";
import { nextTick } from "vue";

/**
 * 红绿图模式管理器
 * 利用已有图层结构，不清除现有图层
 */
export class RedGreenModeManager {
  constructor(options = {}) {
    this.canvas = options.canvas;
    this.layerManager = options.layerManager;
    this.toolManager = options.toolManager;
    this.canvasManager = options.canvasManager;
    this.commandManager = options.commandManager;

    // 红绿图模式状态
    this.isInitialized = false;
    this.normalLayerOpacity = 0.4; // 默认40%透明度 (0-1)

    // 图片URL
    this.clothingImageUrl = null;
    this.redGreenImageUrl = null;
    this.clothingImageOpts = options.clothingImageOpts || null;

    // 回调函数
    this.onImageGenerated = null;

    console.log("RedGreenModeManager 已创建");
  }

  /**
   * 初始化红绿图模式
   * @param {Object} options 配置选项
   * @param {String} options.clothingImageUrl 衣服底图URL
   * @param {String} options.redGreenImageUrl 红绿图URL
   * @param {Number} options.normalLayerOpacity 普通图层透明度 (0-1)
   * @param {Function} options.onImageGenerated 图片生成回调
   * @returns {Promise<boolean>} 是否初始化成功
   */
  async initialize(options = {}) {
    try {
      // 如果已经初始化，先清理状态
      if (this.isInitialized) {
        console.log("红绿图模式已初始化，重新初始化...");
      }

      // 更新配置
      this.clothingImageUrl = options.clothingImageUrl;
      this.redGreenImageUrl = options.redGreenImageUrl;
      this.onImageGenerated = options.onImageGenerated;

      // 设置透明度 (支持0-100的百分比值或0-1的小数值)
      if (typeof options.normalLayerOpacity === "number") {
        if (options.normalLayerOpacity > 1) {
          // 如果大于1，认为是百分比值(0-100)
          this.normalLayerOpacity =
            Math.max(0, Math.min(100, options.normalLayerOpacity)) / 100;
        } else {
          // 如果小于等于1，认为是小数值(0-1)
          this.normalLayerOpacity = Math.max(
            0,
            Math.min(1, options.normalLayerOpacity)
          );
        }
      }

      // 验证必需参数
      if (!this.clothingImageUrl || !this.redGreenImageUrl) {
        throw new Error("缺少必需的图片URL参数");
      }

      // 使用新的批量初始化命令，减少页面闪烁
      const initCommand = new BatchInitializeRedGreenModeCommand({
        canvas: this.canvas,
        layerManager: this.layerManager,
        toolManager: this.toolManager,
        clothingImageUrl: this.clothingImageUrl,
        redGreenImageUrl: this.redGreenImageUrl,
        clothingImageOpts: this.clothingImageOpts,
        normalLayerOpacity: this.normalLayerOpacity,
        onImageGenerated: this.onImageGenerated,
      });
      initCommand.undoable = false; // 不可撤销

      // 执行命令
      if (this.commandManager) {
        await this.commandManager.execute(initCommand);
      } else {
        await initCommand.execute();
      }

      // 标记为已初始化
      this.isInitialized = true;

      this.registerRedGreenMouseUpEvent();

      // 启用图层管理器的红绿图模式
      if (
        this.layerManager &&
        typeof this.layerManager.enableRedGreenMode === "function"
      ) {
        this.layerManager.enableRedGreenMode();
      }

      // 更新交互性
      await this.layerManager?.updateLayersObjectsInteractivity?.();

      // 重置工具管理器状态
      // 默认红色笔刷
      if (this.toolManager) {
        this.toolManager.isRedGreenMode = true;
      }

      console.log("红绿图模式初始化成功", {
        衣服底图: this.clothingImageUrl,
        红绿图: this.redGreenImageUrl,
        普通图层透明度: `${Math.round(this.normalLayerOpacity * 100)}%`,
        画布背景: "白色",
      });

      return true;
    } catch (error) {
      console.error("红绿图模式初始化失败:", error);
      this.isInitialized = false;
      throw error;
    }
  }

  // 注册鼠标抬起事件
  registerRedGreenMouseUpEvent() {
    this.canvas.on("mouse:up", (event) => {
      // 可以在这里添加更多逻辑，比如生成图片或更新状态
      nextTick(() => {
        requestIdleCallback(async () => {
          if (!this.isInitialized) {
            console.warn("红绿图模式未初始化，无法处理鼠标事件");
            return;
          }
          if (this.onImageGenerated) {
            const imageData = await this.canvasManager.exportImage({
              restoreOpacityInRedGreen: true, // 恢复红绿图模式下的透明度
            });
            this.onImageGenerated(imageData);
          }
        });
      });
    });
  }

  /**
   * 检查是否已初始化
   * @returns {boolean} 是否已初始化
   */
  isReady() {
    return this.isInitialized;
  }

  /**
   * 更新普通图层透明度
   * @param {Number} opacity 透明度值 (0-100的百分比值或0-1的小数值)
   * @returns {boolean} 是否更新成功
   */
  updateNormalLayerOpacity(opacity) {
    if (!this.isInitialized) {
      console.warn("红绿图模式未初始化，无法更新透明度");
      return false;
    }

    try {
      // 处理透明度值
      let normalizedOpacity;
      if (opacity > 1) {
        // 如果大于1，认为是百分比值(0-100)
        normalizedOpacity = Math.max(0, Math.min(100, opacity)) / 100;
      } else {
        // 如果小于等于1，认为是小数值(0-1)
        normalizedOpacity = Math.max(0, Math.min(1, opacity));
      }

      // // 创建透明度更新命令
      // const opacityCommand = new UpdateNormalLayerOpacityCommand({
      //   canvas: this.canvas,
      //   layerManager: this.layerManager,
      //   opacity: normalizedOpacity,
      // });

      // // 执行命令
      // if (this.commandManager) {
      //   this.commandManager.execute(opacityCommand);
      // } else {
      //   opacityCommand.execute();
      // }

      // 更新内部状态
      this.normalLayerOpacity = normalizedOpacity;

      console.log(
        `普通图层透明度已更新为: ${Math.round(normalizedOpacity * 100)}%`
      );
      return true;
    } catch (error) {
      console.error("更新普通图层透明度失败:", error);
      return false;
    }
  }

  /**
   * 获取当前普通图层透明度
   * @param {boolean} asPercentage 是否返回百分比值(0-100)，默认返回小数值(0-1)
   * @returns {Number} 透明度值
   */
  getNormalLayerOpacity(asPercentage = false) {
    if (asPercentage) {
      return Math.round(this.normalLayerOpacity * 100);
    }
    return this.normalLayerOpacity;
  }

  /**
   * 重新加载图片
   * @param {Object} options 配置选项
   * @param {String} options.clothingImageUrl 新的衣服底图URL (可选)
   * @param {String} options.redGreenImageUrl 新的红绿图URL (可选)
   * @returns {Promise<boolean>} 是否重新加载成功
   */
  async reloadImages(options = {}) {
    if (!this.isInitialized) {
      console.warn("红绿图模式未初始化，无法重新加载图片");
      return false;
    }

    try {
      // 更新图片URL
      if (options.clothingImageUrl) {
        this.clothingImageUrl = options.clothingImageUrl;
      }
      if (options.redGreenImageUrl) {
        this.redGreenImageUrl = options.redGreenImageUrl;
      }

      // 重新初始化
      await this.initialize({
        clothingImageUrl: this.clothingImageUrl,
        redGreenImageUrl: this.redGreenImageUrl,
        normalLayerOpacity: this.normalLayerOpacity,
        onImageGenerated: this.onImageGenerated,
      });

      console.log("图片重新加载成功");
      return true;
    } catch (error) {
      console.error("重新加载图片失败:", error);
      return false;
    }
  }

  /**
   * 获取当前状态信息
   * @returns {Object} 状态信息
   */
  getStatus() {
    return {
      isInitialized: this.isInitialized,
      clothingImageUrl: this.clothingImageUrl,
      redGreenImageUrl: this.redGreenImageUrl,
      normalLayerOpacity: this.normalLayerOpacity,
      normalLayerOpacityPercentage: Math.round(this.normalLayerOpacity * 100),
    };
  }

  /**
   * 获取图层信息
   * @returns {Object} 图层信息
   */
  getLayerInfo() {
    if (!this.layerManager || !this.layerManager.layers) {
      return null;
    }

    const layers = this.layerManager.layers.value || [];
    const backgroundLayer = layers.find((layer) => layer.isBackground);
    const fixedLayer = layers.find((layer) => layer.isFixed);
    const normalLayers = layers.filter(
      (layer) => !layer.isBackground && !layer.isFixed
    );

    return {
      backgroundLayer:
        backgroundLayer &&
        Object.assign(
          {
            hasObject: !!backgroundLayer.fabricObject,
          },
          backgroundLayer
        ),
      fixedLayer:
        fixedLayer &&
        Object.assign(
          {
            hasObject: !!fixedLayer.fabricObject,
          },
          fixedLayer
        ),
      normalLayers: normalLayers.map((layer) => ({
        id: layer.id,
        name: layer.name,
        visible: layer.visible,
        opacity: layer.opacity,
        objectCount: layer.fabricObjects ? layer.fabricObjects.length : 0,
      })),
    };
  }

  /**
   * 清理红绿图模式
   * 注意：这不会删除图层，只是清理红绿图模式的特定内容
   */
  cleanup() {
    try {
      // 禁用图层管理器的红绿图模式
      if (
        this.layerManager &&
        typeof this.layerManager.disableRedGreenMode === "function"
      ) {
        this.layerManager.disableRedGreenMode();
      }

      // 重置工具管理器
      if (this.toolManager && this.toolManager.isRedGreenMode) {
        this.toolManager.isRedGreenMode = false;
      }

      // 重置状态
      this.isInitialized = false;
      this.clothingImageUrl = null;
      this.redGreenImageUrl = null;
      this.onImageGenerated = null;

      console.log("红绿图模式已清理");
    } catch (error) {
      console.error("清理红绿图模式失败:", error);
    }
  }

  /**
   * 销毁管理器
   */
  dispose() {
    this.cleanup();

    // 清除引用
    this.canvas = null;
    this.layerManager = null;
    this.toolManager = null;
    this.commandManager = null;

    console.log("RedGreenModeManager 已销毁");
  }
}
