import React, { useMemo } from 'react';
import styles from '@/components/FlowEditor/node/style/baseOther.module.less';
import { Handle, Position, useStore } from '@xyflow/react';
import { deserializeValue, isJSON } from '@/utils/common';

interface NodeContentData {
  parameters?: {
    dataIns?: any[];
    dataOuts?: any[];
    apiIns?: any[];
    apiOuts?: any[];
  };
  showFooter?: boolean;
  type?: string;
  component?: any;

  [key: string]: any;
}

// 定义通用的句柄样式
const handleStyles = {
  mainSource: {
    background: '#2290f6',
    width: '8px',
    height: '8px',
    border: '2px solid #fff',
    boxShadow: '0 0 4px rgba(0,0,0,0.2)'
  },
  mainTarget: {
    background: '#2290f6',
    width: '8px',
    height: '8px',
    border: '2px solid #fff',
    boxShadow: '0 0 4px rgba(0,0,0,0.2)'
  },
  data: {
    background: '#555',
    width: '6px',
    height: '6px',
    border: '1px solid #fff',
    boxShadow: '0 0 2px rgba(0,0,0,0.2)'
  }
};

// 渲染普通节点的句柄
const renderRegularNodeHandles = (dataIns: any[], dataOuts: any[], apiIns: any[], apiOuts: any[]) => {
  return (
    <>
      {apiOuts.map((_, index) => (
        <Handle
          key={`api-output-handle-${index}`}
          type="source"
          position={Position.Right}
          id={apiOuts[index].eventId || `output-${index}`}
          style={{
            ...handleStyles.mainSource,
            top: `${35 + index * 20}px`
          }}
        />
      ))}
      {apiIns.map((_, index) => (
        <Handle
          key={`api-input-handle-${index}`}
          type="target"
          position={Position.Left}
          id={apiIns[index].eventId || `input-${index}`}
          style={{
            ...handleStyles.mainTarget,
            top: `${35 + index * 20}px`
          }}
        />
      ))}

      {/* 输入参数连接端点 */}
      {dataIns.map((_, index) => (
        <Handle
          key={`data-input-handle-${index}`}
          type="target"
          position={Position.Left}
          id={dataIns[index].name || dataIns[index].id || `input-${index}`}
          style={{
            ...handleStyles.data,
            top: `${70 + (apiIns.length + index) * 20}px`
          }}
        />
      ))}

      {/* 输出参数连接端点 */}
      {dataOuts.map((_, index) => (
        <Handle
          key={`data-output-handle-${index}`}
          type="source"
          position={Position.Right}
          id={dataOuts[index].name || dataOuts[index].id || `output-${index}`}
          style={{
            ...handleStyles.data,
            top: `${70 + (apiOuts.length + index) * 20}px`
          }}
        />
      ))}
    </>
  );
};

// 检查是否为有效的API（非empty）
const isValidApi = (api: any) => {
  return api && !api.topic?.includes('**empty**') && !api.name?.includes('**empty**');
};

// 检查是否为有效的数据（非empty）
const isValidData = (data: any) => {
  return data && !data.topic?.includes('**empty**') && !data.name?.includes('**empty**');
};

// 为每组关联的数据定义颜色
const getGroupColor = (groupId: number) => {
  const colors = [
    '#1890ff', // 蓝色
    '#52c41a', // 绿色
    '#faad14', // 黄色
    '#f5222d', // 红色
    '#722ed1', // 紫色
    '#13c2c2', // 青色
    '#eb2f96', // 粉色
    '#a0d911', // 青绿色
    '#ff7a45', // 橙色
    '#9254de', // 深紫色
    '#40a9ff', // 浅蓝色
    '#ff4d4f', // 亮红色
    '#36cfc9', // 深青色
    '#fadb14', // 亮黄色
    '#c41d7f'  // 深粉色
  ];
  return colors[groupId % colors.length];
};

// 从customDef中提取事件分组信息
const useEventGroups = (component: any) => {
  return useMemo(() => {
    if (!component?.customDef) return {};

    try {
      const customDef = isJSON(component.customDef)
        ? JSON.parse(component.customDef)
        : component.customDef;

      const groups: Record<string, { event: any; color: string; index: number }> = {};
      let groupIndex = 0;

      // 处理eventListenes（对应apiOuts）
      if (Array.isArray(customDef.eventListenes)) {
        customDef.eventListenes
          .filter(event => event && !event.topic?.includes('**empty**'))
          .forEach(event => {
            groups[`eventListenes-${event.eventId}`] = {
              event,
              color: getGroupColor(groupIndex++),
              index: groupIndex - 1
            };
          });
      }

      // 处理eventSends（对应apiIns）
      if (Array.isArray(customDef.eventSends)) {
        customDef.eventSends
          .filter(event => event && !event.topic?.includes('**empty**'))
          .forEach(event => {
            groups[`eventSends-${event.eventId}`] = {
              event,
              color: getGroupColor(groupIndex++),
              index: groupIndex - 1
            };
          });
      }
      return groups;
    } catch (e) {
      console.error('解析customDef时出错:', e);
      return {};
    }
  }, [component?.customDef]);
};

// 根据数据ID查找关联的事件分组
const findRelatedEventGroup = (dataItem: any, eventGroups: Record<string, any>, eventType: string) => {
  if (!dataItem || !eventGroups) return null;

  // 查找与数据项关联的事件
  for (const key in eventGroups) {
    const group = eventGroups[key];
    const eventDataIns = group.event?.dataIns || [];
    const eventDataOuts = group.event?.dataOuts || [];

    // 检查数据项是否属于当前事件的数据输入或输出
    if (eventType === 'eventListenes' && eventDataIns.some((input: any) => input.id === dataItem.id)) {
      return group;
    }

    if (eventType === 'eventSends' && eventDataOuts.some((output: any) => output.id === dataItem.id)) {
      return group;
    }
  }

  return null;
};

// 根据topic查找API关联的事件分组
const findApiGroupByTopic = (apiItem: any, eventGroups: Record<string, any>) => {
  if (!apiItem || !apiItem.topic || !eventGroups) return null;

  // 查找与API项topic关联的事件
  for (const key in eventGroups) {
    const group = eventGroups[key];
    if (group.event.topic === apiItem.topic) {
      return group;
    }
  }

  return null;
};

const NodeContent = ({ data }: { data: NodeContentData }) => {
  const apiIns = data.parameters?.apiIns || [];
  const apiOuts = data.parameters?.apiOuts || [];
  const dataIns = data.parameters?.dataIns || [];
  const dataOuts = data.parameters?.dataOuts || [];
  // 获取事件分组信息
  const eventGroups = useEventGroups(data.component);

  return (
    <>
      {/*content栏-api部分*/}
      <div className={styles['node-api-box']}>

        <div className={styles['node-content-api']}>
          {/*{apiIns.length > 0 && (*/}
          <div className={styles['node-inputs']}>
            {apiIns.map((input, index) => {
              // 查找关联的事件分组
              const group = findApiGroupByTopic(input, eventGroups);
              return (
                <div
                  key={input.eventId || `input-${index}`}
                  className={styles['node-input-label']}
                  style={{
                    color: group ? group.color : '#000'
                  }}
                >
                  {isValidApi(input) ? input.name : ''}
                </div>
              );
            })}
          </div>
          {/*)}*/}

          {apiOuts.length > 0 && (
            <div className={styles['node-outputs']}>
              {apiOuts.map((output, index) => {
                // 查找关联的事件分组
                const group = findApiGroupByTopic(output, eventGroups);
                return (
                  <div
                    key={output.eventId || `output-${index}`}
                    className={styles['node-input-label']}
                    style={{
                      color: group ? group.color : '#000'
                    }}
                  >
                    {isValidApi(output) ? output.name : ''}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
      {(dataIns.length > 0 || dataOuts.length > 0) && (
        <>
          {/*分割*/}
          <div className={styles['node-split-line']}></div>

          {/*content栏-data部分*/}
          <div className={styles['node-data-box']}>
            <div className={styles['node-content']}>
              {/*{dataIns.length > 0 && (*/}
              <div className={styles['node-inputs']}>
                {dataIns.map((input, index) => {
                  // 查找关联的事件分组
                  const group = findRelatedEventGroup(input, eventGroups, 'eventSends');
                  return (
                    <div
                      key={input.id || `input-${index}`}
                      className={styles['node-input-label']}
                      style={{
                        color: group ? group.color : '#000'
                      }}
                    >
                      {isValidData(input) ? `${input.name || input.id} ${input?.dataType}` : ''}
                    </div>
                  );
                })}
              </div>
              {/*)}*/}

              {dataOuts.length > 0 && (
                <div className={styles['node-outputs']}>
                  {dataOuts.map((output, index) => {
                    // 查找关联的事件分组
                    const group = findRelatedEventGroup(output, eventGroups, 'eventListenes');

                    return (
                      <div
                        key={output.id || `output-${index}`}
                        className={styles['node-input-label']}
                        style={{
                          color: group ? group.color : '#000'
                        }}
                      >
                        {isValidData(output) ? `${output.dataType} ${output.name || output.id}` : ''}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </>
      )}

      {/*footer栏*/}
      {/*{showFooter && (*/}
      {/*  <div className={styles['node-footer']}>*/}
      {/*    {formatFooter(footerData)}*/}
      {/*  </div>*/}
      {/*)}*/}

      {/* 根据节点类型渲染不同的句柄 */}
      {renderRegularNodeHandles(dataIns, dataOuts, apiIns, apiOuts)}
    </>
  );
};

export default NodeContent;