import React, { useEffect, useState } from 'react';
import { useStore } from '@xyflow/react';
import styles from '@/components/FlowEditor/node/style/baseOther.module.less';
import DynamicIcon from '@/components/DynamicIcon';
import { Handle, Position } from '@xyflow/react';
import NodeContentLoop from '@/pages/flowEditor/components/nodeContentLoop';
import { defaultNodeTypes } from '@/components/FlowEditor/node/types/defaultType';
import NodeStatusIndicator, { NodeStatus } from '@/components/FlowEditor/NodeStatusIndicator';
import { useStore as useFlowStore } from '@xyflow/react';

// 循环节点组件，用于显示循环开始和循环结束节点
const LoopNode = ({ data, id }: { data: defaultNodeTypes; id: string }) => {
  const [newData, setNewData] = useState<any[]>([]);
  const title = data.title || '循环节点';
  const isStartNode = data.type === 'LOOP_START';

  // 获取节点选中状态 - 适配React Flow v12 API
  const isSelected = useStore((state) =>
    state.nodeLookup.get(id)?.selected || false
  );
  
  // 获取节点运行状态
  const nodeStatus: NodeStatus = useFlowStore((state) => 
    (state.nodeLookup.get(id)?.data?.status as NodeStatus) || 'waiting'
  );
  
  // 获取运行状态可见性
  const isStatusVisible = useFlowStore((state) => 
    !!state.nodeLookup.get(id)?.data?.isStatusVisible
  );

  // 设置图标
  const setIcon = () => {
    if (isStartNode) {
      return <DynamicIcon type="IconPlayArrow" style={{ fontSize: '16px', marginRight: '5px' }} />;
    }
    else {
      return <DynamicIcon type="IconStop" style={{ fontSize: '16px', marginRight: '5px' }} />;
    }
  };

  const getOperator = (expr: string) => {
    let operator;
    if (expr.includes('==')) {
      operator = '==';
    }
    else if (expr.includes('>=')) {
      operator = '>=';
    }
    else if (expr.includes('<=')) {
      operator = '<=';
    }
    else if (expr.includes('<')) {
      operator = '<';
    }
    else if (expr.includes('>')) {
      operator = '>';
    }
    else {
      operator = '!=';
    }
    return operator;
  };

  const reverseDataStructure = (processedData: any) => {
    try {
      const parsedCustomDef = JSON.parse(processedData.customDef);
      if (!parsedCustomDef.conditions) {
        return [];
      }

      return parsedCustomDef.conditions.map((condition: any, index: number) => {
        // 解析表达式以获取左值、操作符和右值
        let lftVal = '';
        let operator = '';
        let rgtVal = '';
        const valueType = condition.valueType || '';

        if (condition.expression) {
          // 处理布尔值表达式
          if (valueType.includes('boolean')) {
            const splitStr = valueType.split('-')[1];
            operator = getOperator(condition.expression);
            const pattern = new RegExp(`\\$\\.(.+)(${operator})${splitStr}`);
            const match = condition.expression.match(pattern);
            if (match) {
              lftVal = match[1];
              operator = match[2];
            }
          }
          // 处理其他类型的表达式
          else {
            // 简单的解析逻辑，可能需要根据实际表达式格式进行调整
            const match = condition.expression.match(/\$\.([^=!<>]+)(==|!=|>=|<=|>|<)(.+)/);
            if (match) {
              lftVal = match[1];
              operator = match[2];
              rgtVal = match[3];
            }
          }
        }

        return {
          key: index,
          id: Date.now(),
          apiOutId: condition.apiOutId || '',
          lftVal,
          operator,
          valueType,
          rgtVal
        };
      });
    } catch (e) {
      console.error('Error parsing customDef:', e);
      return [];
    }
  };

  useEffect(() => {
    if (data) {
      const reverseData = reverseDataStructure(data.component);
      if (reverseData.length > 0) {
        const list = reverseData.map(item => {
          let expression = '';
          if (item.valueType.includes('boolean')) {
            const splitStr = item.valueType.split('-')[1];
            expression = `$.${item.lftVal}${item.operator}${splitStr}`;
          }
          else expression = `$.${item.lftVal}${item.operator}${item.rgtVal}`;
          return {
            name: item.apiOutId,
            id: item.apiOutId,
            desc: '',
            defaultValue: item.valueType,
            dataType: expression
          };
        });

        // 合并list数组与data.parameters.apiOuts数组
        const apiOuts = data.parameters?.apiOuts || [];
        const mergedApiOuts = [...apiOuts];
        setNewData(mergedApiOuts);
      }
      else {
        // 如果没有reverseData，则直接使用原始apiOuts
        setNewData(data.parameters?.apiOuts || []);
      }
    }
  }, [data]);

  // 创建包含额外apiOuts的新data对象
  const modifiedData = {
    ...data,
    parameters: {
      ...data.parameters,
      apiOuts: newData
    }
  };

  return (
    <div className={`${styles['node-container']} ${isSelected ? styles.selected : ''}`}>
      <div className={styles['node-header']} style={{ backgroundColor: '#1890ff' }}>
        {setIcon()}
        {title}
        <NodeStatusIndicator status={nodeStatus} isVisible={isStatusVisible} />
      </div>

      {/* 顶部连接点，用于标识循环开始和结束节点是一组 */}
      <Handle
        type={id.includes('END') ? 'target' : 'source'}
        position={Position.Top}
        id={`${id}-group`}
        style={{
          background: '#2290f6',
          width: '8px',
          height: '8px',
          border: '2px solid #fff',
          boxShadow: '0 0 4px rgba(0,0,0,0.2)',
          top: '-4px'
        }}
      />

      <NodeContentLoop data={modifiedData} />
    </div>
  );
};

export default LoopNode;