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 NodeContentSwitch from '@/pages/flowEditor/components/nodeContentSwitch';
import { defaultNodeTypes } from '@/components/FlowEditor/node/types/defaultType';

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

  // 获取节点选中状态 - 适配React Flow v12 API
  const isSelected = useStore((state) =>
    state.nodeLookup.get(id)?.selected || false
  );

  // 设置图标
  const setIcon = () => {
    return <DynamicIcon type="IconBranch" 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) => {
    if (!processedData) {
      return [];
    }
    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}
      </div>

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

export default SwitchNode;