import {Graph} from '@antv/x6';
import {convertPortConfig} from '../constants';

/**
 * 添加节点到图形
 * @param isNew 是否为新节点
 * @param graph X6 Graph实例
 * @param currentNodeDefinition 工作流节点定义
 * @param allNodeDefinitions 工作流节点定义列表
 * @param position 新节点的位置（可选）
 * @returns 创建的节点实例
 */
export const addNodeToGraph = (
    isNew: boolean,
    graph: Graph,
    currentNodeDefinition: any,
    allNodeDefinitions: any,
    position?: { x: number; y: number }
) => {
    let nodeDefinition = allNodeDefinitions.find(def => def.nodeType === currentNodeDefinition.nodeType);
    let uiVariables = isNew ? nodeDefinition.uiVariables : currentNodeDefinition.uiVariables;
    // 根据形状类型设置正确的 shape
    let shape = 'rect';  // 默认使用矩形
    if (uiVariables.shape === 'circle') {
        shape = 'circle';
    } else if (uiVariables.shape === 'diamond') {
        shape = 'polygon';
    }

    // 创建节点配置
    const nodeConfig = {
        inherit: 'rect',
        width: uiVariables.size.width,
        height: uiVariables.size.height,
        attrs: {
            body: {
                ...uiVariables.style,
                ...(uiVariables.shape === 'diamond' ? {
                    refPoints: '0,10 10,0 20,10 10,20',
                } : {})
            },
            label: {
                text: isNew ? nodeDefinition.nodeName : currentNodeDefinition.nodeName
            },
        },
        shape,
        nodeType: isNew ? nodeDefinition.nodeType : currentNodeDefinition.nodeType,
        nodeCode: nodeDefinition.nodeCode,
        ports: convertPortConfig(uiVariables.ports)
    };

    const nodePosition = isNew ? position : currentNodeDefinition.uiVariables?.position;
    if (nodePosition) {
        Object.assign(nodeConfig, nodePosition);
    }
    return graph.addNode(nodeConfig);
}; 