import { PipelineGlobalParam, PipelineNodeModelParameter } from '@/types';
import { parseJsonText } from '@/utils';
import { Graph, INode } from '@antv/g6';
import { type MenuProps } from 'antd';

// 找到节点所以的上游节点
export const findAllParentNodes = (graph: Graph, node: INode) => {
  const parentNodes: INode[] = [];
  let index = -1;
  let targetNode = node;
  while (targetNode) {
    const neighbors: INode[] = graph.getNeighbors(targetNode, 'source');
    for (const sourceNode of neighbors) {
      // 避免重复，也避免循环
      const idx = parentNodes.findIndex((item) => sourceNode.getID() === item.getID());
      if (idx === -1 && sourceNode.getID() !== node.getID()) {
        parentNodes.push(sourceNode);
      }
    }
    targetNode = parentNodes[++index];
  }

  return parentNodes;
};

// 判断并找到全局参数第一个重复项，有重复项时，全局参数不允许保存
export function findFirstDuplicate(params: PipelineGlobalParam[]): string | null {
  const seen = new Set();
  for (const item of params) {
    if (seen.has(item.param_name)) {
      return item.param_name;
    }
    seen.add(item.param_name);
  }
  return null;
}

// 创建参数下拉菜单
export function createMenuItems(
  params: PipelineGlobalParam[],
  parentNodes: INode[],
): MenuProps['items'] {
  const nodes: MenuProps['items'] = parentNodes.map((item) => {
    const model = item.getModel();
    const out_parameters = model.out_parameters as string | undefined | null;
    const out_parametersObj = parseJsonText(out_parameters);
    const outParametersList = Object.keys(out_parametersObj ?? {});
    return {
      key: model.id as string,
      label: model.label as string,
      children: outParametersList.map((key: string) => ({
        key: key as string,
        label: out_parametersObj[key].label,
      })),
    };
  });

  if (params.length > 0) {
    return [
      {
        key: 'global',
        label: '全局参数',
        children: params.map((item) => ({
          key: item.param_name,
          label: item.param_name,
        })),
      },
      ...nodes,
    ];
  } else {
    return [...nodes];
  }
}

export function getInParameterComponent(
  parameter: PipelineNodeModelParameter,
): React.ReactNode | null {
  if (parameter.value) {
  }

  return null;
}

// 判断是否允许输入
export function canInput(parameter: PipelineNodeModelParameter) {
  const { type, item_type } = parameter;
  return !(
    type === 'ref' &&
    (item_type === 'dataset' ||
      item_type === 'model' ||
      item_type === 'image' ||
      item_type === 'code')
  );
}
