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";
// @ts-ignore
import SelectAreaNode from './selectAreaNode.vue';

class SelectAreaModel extends GroupNodeModel {

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

  getDefaultAnchor() {
    return []
  }

  isAllowAppendIn() {
    return false
  }
}

class SelectAreaView 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(SelectAreaNode, {
      model: props.model,
      graphModel: props.graphModel,
      properties: {
        ...props.model.getProperties(),
      }
    });

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

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

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

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


// 导出方法注册
export function registerSelectAreaNode(lf) {
  lf.register({
    type: "selectArea",
    view: SelectAreaView,
    model: SelectAreaModel,
  });
}