import { GroupNodeModel } from '@logicflow/extension';
// 导入 Vue 相关方法，用于渲染组件
import { createApp, h, nextTick } from "vue";
import { HtmlNode, h as svgH } from "@logicflow/core";
import ElementPlus from "element-plus";
import Loop from './loop.vue';

class loopBodyModel extends GroupNodeModel {

  initNodeData(data) {
    super.initNodeData(data);
    this.children = new Set(data.children || [])
    this.zIndex = 0;
    this.isGroup = true;
    this.resizable = false;
  }

  // 保存组件实例引用
  setComponentInstance(instance) {
    this.componentInstance = instance;
  }

  // 递归获取所有有效子节点（包含多层嵌套 children）
  getAllValidChildren = (nodeIds, graphModel) => {
    const validNodes = [];
    // 遍历当前层节点 ID
    Array.from(nodeIds).forEach((id) => {
      const node = graphModel.getNodeModelById(id);
      if (node) {
        // 当前节点有效，加入结果
        validNodes.push(node);
        // 如果节点还有 children，递归获取下级节点
        if (node.children && node.children.size > 0) {
          const childNodes = this.getAllValidChildren(node.children, graphModel);
          validNodes.push(...childNodes);
        }
      } else {
        // 无效 ID，从集合中删除
        nodeIds.delete(id);
      }
    });
    return validNodes;
  };

  // 计算子节点的包围盒(包含所有子节点的最小矩形区域)
  getChildrenBBox() {
    const children = this.getAllValidChildren(this.children, this.graphModel)
    console.log('children', children)
    // Array.from(this.children).forEach((id) => {
    //   const node = this.graphModel.getNodeModelById(id)
    //   if (node) {
    //     children.push(this.graphModel.getNodeModelById(id))
    //   } else {
    //     this.children.delete(id)
    //   }
    // });

    let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
    nextTick(() => {
      children.forEach((node) => {
        let _width = node.type === 'loop' ? 500 : 320
        let _height = node.type === 'loop' ? 300 : 200
        let width = node.width === 0 ? _width : node.width
        let height = node.height === 0 ? _height : node.height
        minX = Math.min(minX, node.x - width / 2);
        maxX = Math.max(maxX, node.x + width / 2);
        minY = Math.min(minY, node.y - height / 2);
        maxY = Math.max(maxY, node.y + height / 2);
    });
    this.width = maxX - minX + 180; // 增加内边距
    this.height = maxY - minY + 300;
    this.x = (minX + maxX) / 2;
    this.y = (minY + maxY) / 2;
    const properties = lf.getProperties(this.id)
    this.setProperties({
      ...properties,
      width: this.width,
      height: this.height
    })
    this.getDefaultAnchor()
    })
  }

  updateSize() {
    const children = Array.from(this.children);
    if (children.length > 0) {
      this.getChildrenBBox();
    }
  }

   // 添加子节点时立即更新大小
  addChild(childId) {
    super.addChild(childId);
    this.updateSize();
  }

  // 移除子节点时更新大小
  removeChild(childId) {
    return false
  }

  // 定义节点只有左右两个锚点. 锚点位置通过中心点和宽度算出来。
  getDefaultAnchor() {
    let _a = this,
      x = _a.x,
      y = _a.y,
      width = _a.width,
      height = _a.height;
    return [
      {
        x: x + width / 2 ,
        y: y + height / 2,
        name: "right",
        id: "".concat(this.id, "_1"),
        properties: { connectionType: "source" },
      },
      {
        x: x - width / 2,
        y: y + height / 2,
        name: "left",
        id: "".concat(this.id, "_3"),
        properties: { connectionType: "target" },
      },
    ];
  }

  isAllowAppendIn() {
    return false;
  }
}

class loopBodyView extends HtmlNode {
  resizeObserver = null;
  isMounted; // 标记组件是否已挂载
  r; // 渲染函数
  app; // Vue 应用实例
  container = null;

  static reusePool = new Map(); // 节点复用池

  /**
   * 构造函数
   * @param props 传递给节点的属性，包括模型、图模型等
   */
  constructor(props) {
    super(props);
    this.initVueApp(props);
  }

  initVueApp(props) {
    this.isMounted = false;

    this.hideAnchor = false;
    this.autoExpand = true; // 防止锚点被折叠
    this.anchorsPreset = "default"; // 重置锚点预设
    // 创建 元素的渲染函数
    this.r = h(Loop, {
      model: props.model,
      graphModel: props.graphModel,
      properties: {
        ...props.model.getProperties(),
      },
      onAddToGroup: this.addChild.bind(this),
      onContentChange: this.handleContentChange.bind(this),
      onBindRef: this.handleComponentInstance.bind(this)
    });

    // 创建 Vue 应用实例，并指定渲染函数
    this.app = createApp({
      render: () => this.r,
    });
  }

  addChild(data) {
    this.addToGroup(data);
  }

  handleComponentInstance(data) {
    // 将组件实例保存到节点模型
    this.props.model.setComponentInstance(data)
  }

  handleContentChange() {
    // 内容变化时强制更新尺寸
    this.props.model.updateSize();
  }

  // 关键修改：重写getShape方法
  getShape() {
    const { model } = this.props;
    const { x, y, width, height } = model;
    
    // 创建自定义HTML内容
    const html = super.getShape();
    // 创建SVG组，包含HTML内容和锚点
    return svgH('g', {}, [
      // 绘制组节点背景
      svgH('rect', {
        x: x - width / 2,
        y: y - height / 2,
        width,
        height,
        stroke: '#88f',
        strokeWidth: 0,
        strokeDasharray: '5,5',
        fill: 'rgba(136, 136, 255, 0.1)',
        rx: 4,
        ry: 4
      }),
      
      // 添加HTML内容
      html,
      
      // 渲染锚点
      this.getAnchorShapes()
    ]);
  }

  // 创建锚点元素
  getAnchorShapes() {
    const { model } = this.props;
    const anchors = model.anchors || [];
    
    const anchorShapes = anchors.map((offset, index) => {
      const {x, y } = offset
      
      return svgH('circle', {
        cx: x,
        cy: y,
        r: 7,
        hover: { fill: "#FF5722" }, // 禁用悬停变色
        fill: '#FF5722',
        stroke: '#FF5722',
        strokeWidth: 0,
        className: 'lf-node-anchor',
        cursor: 'crosshair',
        'data-anchor-id': `anchor_${index}`
      });
    });
    
    return svgH('g', {}, anchorShapes);
  }

  /**
   * 将 HTML 内容设置到指定的根元素上
   * @param rootEl 根元素
   */
  async setHtml(rootEl) {
    const nodeId = this.props.model.id;
    if (loopBodyView.reusePool.has(nodeId)) {
      rootEl.appendChild(loopBodyView.reusePool.get(nodeId));
      return;
    }

    if (!this.isMounted) {
      this.isMounted = true;
      this.container = document.createElement("div");
      // this.container.style.display = "inline-block"; // 关键：确保容器自适应内容
      this.container.style.width = "100%"; // 关键：确保容器自适应内容
      this.container.style.height = "100%"; // 关键：确保容器自适应内容

      rootEl.appendChild(this.container);
      this.app.use(ElementPlus); // 关键：单独注册ElementPlus
      this.app.mount(this.container);
      loopBodyView.reusePool.set(nodeId, this.container);
    } else {
      this.r.component.props.properties = this.props.model.getProperties();
    }
  }

  addToGroup(childId) {
   const groupModel = lf.getNodeModelById(this.props.model.id);
   groupModel.addChild(childId);
   groupModel.updateSize()
  }
}


// 导出方法注册
export function registerLoopBodyNode(lf) {
  lf.register({
    type: "loop",
    view: loopBodyView,
    model: loopBodyModel,
  });
}