import React from 'react';
import { getBezierPath } from '@xyflow/react';
import { getHandleType } from '@/utils/flowCommon';

const CustomConnectionLine = ({ fromNode, fromX, fromY, toX, toY, fromHandle }) => {
  // 查找源节点的事件信息
  let eventData = null;
  let isApiHandle = false;

  if (fromNode && fromNode.data) {
    const params = fromNode.data.parameters || {};

    // 判断是否为API类型的句柄
    isApiHandle = getHandleType(fromHandle.id, params) === 'api';

    // 只有在API句柄上才查找事件信息
    if (isApiHandle) {
      const apiOuts = params.apiOuts || [];

      // 查找匹配的输出API
      for (const api of apiOuts) {
        // 检查api的name或id是否与fromHandle匹配
        if (api.name || api.id) {
          eventData = api;
          break;
        }
      }
    }
  }

  const [path] = getBezierPath({
    sourceX: fromX,
    sourceY: fromY,
    targetX: toX,
    targetY: toY,
    curvature: 0.2// 调整这个值可以改变曲线的弯曲程度
  });

  return (
    <g>
      <path
        d={path}
        stroke="#b1b1b7"
        strokeWidth={1}
        className="animated-stroke"
        fill="none"
      />
      {/* 只有在API类型的句柄上拖拽时才显示事件提示 */}
      {isApiHandle && eventData && eventData.topic && !eventData.topic.includes('**empty**') && (
        <text x={(fromX + toX) / 2} y={(fromY + toY) / 2 - 10} fill="#000" fontSize={12}>
          {`连接事件: ${eventData.eventName}`}
        </text>
      )}
    </g>
  );
};

export default CustomConnectionLine;