import React, { useState, useEffect } from 'react';
import { Input, Select, Table, Button } from '@arco-design/web-react';
import { IconDelete } from '@arco-design/web-react/icon';

interface TableDataItem {
  key: number | string;
  id: string;
  apiOutId: string,
  lftVal: string,
  operator: string,
  valueType: string,
  rgtVal: string

  [key: string]: any; // 允许其他自定义字段
}


interface ConditionsTableProps {
  initialData: any;
  nodeData: any;
  onUpdateData: (data: any) => void;
  type?: string;
}

const dataTypeOptions = [
  { label: '字符串', value: 'string' },
  { label: '数字', value: 'number' },
  { label: '布尔值(真)', value: 'boolean-true' },
  { label: '布尔值(假)', value: 'boolean-false' },
  { label: '表达式', value: 'expression' }
];

const operationOptions = [
  { label: '==', value: '==' },
  { label: '!=', value: '!=' },
  { label: '>', value: '>' },
  { label: '<', value: '<' },
  { label: '>=', value: '>=' },
  { label: '<=', value: '<=' }
  // { label: '包含', value: 'contains' },
  // { label: '不包含', value: 'notContains' },
  // { label: '匹配正则表达式', value: 'matchRegex' },
  // { label: '不匹配正则表达式', value: 'notMatchRegex' },
  // { label: '为空', value: 'isEmpty' },
  // { label: '不为空', value: 'isNotEmpty' },
  // { label: '为真', value: 'isTrue' },
  // { label: '为假', value: 'isFalse' },
  // { label: '为空或为假', value: 'isEmptyOrFalse' },
  // { label: '不为空或为真', value: 'isNotEmptyOrTrue' }
];

const ConditionsTable: React.FC<ConditionsTableProps> = ({
                                                           initialData,
                                                           nodeData,
                                                           onUpdateData,
                                                           type = 'LOOP'
                                                         }) => {
  const [data, setData] = useState<any[]>([]);
  const [rowData, setRowData] = useState<any>({});
  const [apiOutsList, setApiOutsList] = useState([]);
  const [leftList, setLeftList] = useState([]);

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (_: any, record: TableDataItem, i) => (
        <span>{i + 1}</span>
      )
    },
    {
      title: '逻辑出口',
      dataIndex: 'apiOutId',
      width: 100,
      render: (_: any, record: TableDataItem) => (
        <Input
          autoWidth={{ minWidth: 100, maxWidth: 500 }}
          value={record.apiOutId}
          onChange={(value) => {
            // 仅更新本地状态，不立即触发保存
            const newData = [...data];
            const index = newData.findIndex((item) => record.key === item.key);
            if (index >= 0) {
              newData.splice(index, 1, { ...newData[index], apiOutId: value });
              setData(newData);
            }
          }}
          onBlur={() => {
            // 失去焦点时才触发保存
            const currentRow = data.find(item => item.key === record.key);
            if (currentRow) {
              handleSave(currentRow);
            }
          }}
          onPressEnter={() => {
            // 按回车键时也触发保存
            const currentRow = data.find(item => item.key === record.key);
            if (currentRow) {
              handleSave(currentRow);
            }
          }}
          placeholder="请输入逻辑出口"
        />
      )
    },
    {
      title: '左值',
      dataIndex: 'lftVal',
      render: (_: any, record: TableDataItem) => (
        <Select
          autoWidth={{ minWidth: 200, maxWidth: 500 }}
          options={leftList}
          value={record.lftVal}
          onChange={(value) => {
            // 仅更新本地状态，不立即触发保存
            const newData = [...data];
            const index = newData.findIndex((item) => record.key === item.key);
            if (index >= 0) {
              newData.splice(index, 1, { ...newData[index], lftVal: value });
              setData(newData);
            }
          }}
          onBlur={() => {
            // 失去焦点时才触发保存
            const currentRow = data.find(item => item.key === record.key);
            if (currentRow) {
              handleSave(currentRow);
            }
          }}
          placeholder="请选择需要引用的出入参数"
        />
      )
    },
    {
      title: '运算/比较',
      dataIndex: 'operator',
      render: (_: any, record: TableDataItem) => (
        <Select
          autoWidth={{ minWidth: 80, maxWidth: 500 }}
          options={operationOptions}
          value={record.operator}
          onChange={(value) => {
            // 仅更新本地状态，不立即触发保存
            const newData = [...data];
            const index = newData.findIndex((item) => record.key === item.key);
            if (index >= 0) {
              newData.splice(index, 1, { ...newData[index], operator: value });
              setData(newData);
            }
          }}
          onBlur={() => {
            // 失去焦点时才触发保存
            const currentRow = data.find(item => item.key === record.key);
            if (currentRow) {
              handleSave(currentRow);
            }
          }}
          placeholder="请选择运算/比较符"
        />
      )
    },
    {
      title: '右值',
      dataIndex: 'valueType',
      render: (_: any, record: TableDataItem) => (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <Select
            autoWidth={{ minWidth: 200, maxWidth: 500 }}
            options={dataTypeOptions}
            value={record.valueType}
            onChange={(value) => {
              // 仅更新本地状态，不立即触发保存
              const newData = [...data];
              const index = newData.findIndex((item) => record.key === item.key);
              if (index >= 0) {
                newData.splice(index, 1, {
                  ...newData[index],
                  valueType: value,
                  // 如果类型不是string、number或expression，则清空rgtVal
                  rgtVal: ['string', 'number', 'expression'].includes(value) ? newData[index].rgtVal : ''
                });
                setData(newData);
              }
            }}
            onBlur={() => {
              // 失去焦点时才触发保存
              const currentRow = data.find(item => item.key === record.key);
              if (currentRow) {
                handleSave(currentRow);
              }
            }}
            placeholder="请选择右值类型"
          />
          {['string', 'number', 'expression'].includes(record.valueType) ? (
            <Input
              style={{ marginTop: 8 }}
              autoWidth={{ minWidth: 200, maxWidth: 500 }}
              value={record.rgtVal}
              onChange={(value) => {
                // 仅更新本地状态，不立即触发保存
                const newData = [...data];
                const index = newData.findIndex((item) => record.key === item.key);
                if (index >= 0) {
                  newData.splice(index, 1, { ...newData[index], rgtVal: value });
                  setData(newData);
                }
              }}
              onBlur={() => {
                // 失去焦点时才触发保存
                const currentRow = data.find(item => item.key === record.key);
                if (currentRow) {
                  handleSave(currentRow);
                }
              }}
              onPressEnter={() => {
                // 按回车键时也触发保存
                const currentRow = data.find(item => item.key === record.key);
                if (currentRow) {
                  handleSave(currentRow);
                }
              }}
              placeholder={'请输入'}
            />
          ) : (<span></span>)}
        </div>
      )
    },
    {
      title: '操作',
      dataIndex: 'op',
      render: (_: any, record: TableDataItem) => (
        <Button onClick={() => removeRow(record.key)} type="text" status="danger">
          <IconDelete />
        </Button>
      )
    }
  ];

  const convertData = (originData) => {
    const apiOutIds = apiOutsList;
    const conditions = originData.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}`;
      if (item.apiOutId && !apiOutIds.includes(item.apiOutId)) {
        apiOutIds.push(item.apiOutId);
      }
      return {
        apiOutId: item.apiOutId,
        valueType: item.valueType,
        expression: expression
      };
    });
    const customDef = {
      apiOutIds,
      conditions
    };
    // 只需要动态添加开始节点的NodeId， 循环开始的节点不允许编辑信息的，所以接口需要的信息会在节点实例的时候配置
    if (type === 'LOOP') customDef['loopStartNodeId'] = nodeData.component.loopStartNodeId;

    return {
      type: nodeData.type,
      customDef: JSON.stringify(customDef)
    };
  };

  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 [];
    }
  };

  // 提取apiIns和apiOuts中的name属性，合并成一个一维数组
  const extractApiNames = () => {
    const apiInsNames = nodeData.parameters?.apiIns?.map((item: any) => item.name) || [];
    const apiOutsNames = nodeData.parameters?.apiOuts?.map((item: any) => item.name) || [];
    if (type === 'LOOP') return [...apiInsNames, ...apiOutsNames];
    else return [...apiOutsNames];
  };

  // 提取dataIns中的属性，并构造成options结构
  const extractDataInsOptions = () => {
    const dataInsOptions = nodeData.parameters?.dataIns?.map((item: any) => ({
      value: item.id,
      label: item.id
    })) || [];
    return [...dataInsOptions];
  };

  const updateOriginData = (data) => {
    // 获取现有的apiOuts数组，确保我们保留所有原始数据
    const existingApiOuts = nodeData.parameters?.apiOuts || [];

    // 创建一个Map来存储当前表格中的数据，便于快速查找
    const tableDataMap = new Map();
    data.forEach(item => {
      if (item.apiOutId) {
        tableDataMap.set(item.apiOutId, item);
      }
    });

    // 更新现有的数据或标记需要删除的数据
    const updatedApiOuts = existingApiOuts.map(item => {
      // 如果在表格数据中存在，则更新它
      if (item.id && tableDataMap.has(item.id)) {
        const tableItem = tableDataMap.get(item.id);
        let expression = '';
        if (tableItem.valueType.includes('boolean')) {
          const splitStr = tableItem.valueType.split('-')[1];
          expression = `$.${tableItem.lftVal}${tableItem.operator}${splitStr}`;
        }
        else {
          expression = `$.${tableItem.lftVal}${tableItem.operator}${tableItem.rgtVal}`;
        }

        // 更新现有项，但保留原始属性
        return {
          ...item,
          name: tableItem.apiOutId,
          id: tableItem.apiOutId,
          desc: item.desc || '',
          defaultValue: tableItem.valueType,
          dataType: expression
        };
      }
      // 如果不在表格数据中，保持原样（可能是其他地方引用的数据）
      return item;
    });

    // 添加表格中有但原始数据中没有的新项
    const existingIds = new Set(existingApiOuts.map(item => item.id));
    const newItems = data
      .filter(item => item.apiOutId && !existingIds.has(item.apiOutId))
      .map(tableItem => {
        let expression = '';
        if (tableItem.valueType.includes('boolean')) {
          const splitStr = tableItem.valueType.split('-')[1];
          expression = `$.${tableItem.lftVal}${tableItem.operator}${splitStr}`;
        }
        else {
          expression = `$.${tableItem.lftVal}${tableItem.operator}${tableItem.rgtVal}`;
        }

        return {
          name: tableItem.apiOutId,
          id: tableItem.apiOutId,
          desc: '',
          defaultValue: tableItem.valueType,
          dataType: expression
        };
      });

    // 合并更新后的数据和新增数据
    return [...updatedApiOuts, ...newItems];
  };

  const handleSave = (row: TableDataItem) => {
    const newData = [...data];
    const index = newData.findIndex((item) => row.key === item.key);
    if (index >= 0) {
      newData.splice(index, 1, { ...newData[index], ...row });
    }
    else {
      newData.push(row);
    }
    setData(newData);
    // 重新构建数据结构
    const newApiOuts = updateOriginData(newData);
    const newComponentData = convertData(newData);
    onUpdateData({
      ...nodeData,
      parameters: {
        ...nodeData.parameters,
        apiOuts: newApiOuts
      },
      component: newComponentData
    });
  };

  const removeRow = (key: number | string) => {
    const newData = data.filter((item) => item.key !== key);
    setData(newData);
    // 重新构建数据结构
    const newApiOuts = updateOriginData(newData);
    const newComponentData = convertData(newData);
    onUpdateData({
      ...nodeData,
      parameters: {
        ...nodeData.parameters,
        apiOuts: newApiOuts
      },
      component: newComponentData
    });
  };

  const addRow = () => {
    const newKey = Date.now();
    const newRow = {
      key: newKey,
      id: '',
      apiOutId: '',
      lftVal: '',
      operator: '',
      valueType: '',
      rgtVal: ''
    };
    const newData = [...data, newRow];
    setData(newData);
    // 重新构建数据结构 添加新行时不更新
    // const newApiOuts = updateOriginData(newData);
    // const newComponentData = convertData(newData);
    // onUpdateData({
    //   ...nodeData,
    //   parameters: {
    //     ...nodeData.parameters,
    //     apiOuts: newApiOuts
    //   },
    //   component: newComponentData
    // });
  };

  // 监听nodeData.parameters.dataIns的变化，更新leftList
  useEffect(() => {
    if (nodeData.parameters?.dataIns) {
      setLeftList(extractDataInsOptions());
    }
  }, [nodeData.parameters?.dataIns]);


  useEffect(() => {
    try {
      console.log('nodeData:', nodeData);
      setApiOutsList(extractApiNames());
      setLeftList(extractDataInsOptions());
      setData(reverseDataStructure(initialData));
    } catch (e) {
      setApiOutsList([]);
      setLeftList([]);
      setData([]);
    }
  }, []);

  return (
    <>
      <Table columns={columns} data={data} pagination={false} />
      <Button
        style={{ height: 45 }}
        long
        type="outline"
        onClick={addRow}
      >
        + 添加
      </Button>
    </>
  );
};

export default ConditionsTable;