
import { GroupNodeModel, GroupNode } from '@logicflow/extension'
import { recursiveFilter } from "@/utils/convertNodeRedToLogicFlow";

class CustomGroupModel extends GroupNodeModel {
  initNodeData(data) {
    super.initNodeData(data);
    this.children = new Set(data.children || [])
    this.zIndex = 0;

    this.width = data.w  + 80; // 增加内边距
    this.height = data.h  + 80;
    this.x = data.x;
    this.y = data.y;

    setTimeout(() => {
      this.updateSize()
      const nodes = this.graphModel.nodes;
      const arr = recursiveFilter(nodes, this.id)
      arr.forEach((item) => {
        item.updateSize()
      })
    }, 0)
  }

  setAttributes() {
    this.text.editable = false;
  }

  getTextStyle() {
    const style = super.getTextStyle();
    style.fill = this.properties.style?.color || '#333';
    style.fontSize = 16;
    return style;
  }

  updateSize() {
    const children = []
    this.children.forEach((id) => {
      children.push(this.graphModel.getNodeModelById(id))
    });
    if (children.length === 0) return;

    let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
    children.forEach((node) => {
      minX = Math.min(minX, node.x - node.width / 2);
      maxX = Math.max(maxX, node.x + node.width / 2);
      minY = Math.min(minY, node.y - node.height / 2);
      maxY = Math.max(maxY, node.y + node.height / 2);
    });

    this.width = maxX - minX + 80; // 增加内边距
    this.height = maxY - minY + 80;
    this.x = (minX + maxX) / 2;
    this.y = (minY + maxY) / 2;
    this.setTextCoordinate(this.width, this.height, this.x, this.y)
  }

  setTextCoordinate(width, height, x, y) {
    const strategies = {
      "n": () => {
        this.text.x = x
        this.text.y = y - height / 2 + 20
      },
      "ne": () => {
        this.text.x = x + width / 2 - 20
        this.text.y = y - height / 2 + 20
      },
      "sw": () => {
        this.text.x = x - width / 2 + 20
        this.text.y = y + height / 2 - 20
      },
      "s": () => {
        this.text.x = x
        this.text.y = y + height / 2 - 20
      },
      "se": () => {
        this.text.x = x + width / 2 - 20
        this.text.y = y + height / 2 - 20
      },
      "default": () => {
        this.text.x = x - width / 2 + 20
        this.text.y = y - height / 2 + 20
      }
    };
    const labelPosition = this.properties.style?.['label-position'] || 'default'
    const action = strategies[labelPosition]
    action();
  }

  removeChild(id) {
    this.children.delete(id) // 现在可安全调用
  }
}

// 导出方法注册
export function registerCustomGroup(lf) {
  lf.register({
    type: "customGroup",
    view: GroupNode,
    model: CustomGroupModel
  })
}
