import React, { useState, useEffect, useCallback } from 'react';
import { NodeEditorProps } from '@/components/FlowEditor/nodeEditors';
import { Typography } from '@arco-design/web-react';
import { IconUnorderedList } from '@arco-design/web-react/icon';
import ParamsTable from './ParamsTable';
import CodeMirror from '@/components/FlowEditor/nodeEditors/components/CodeMirror';


const CodeEditor: React.FC<NodeEditorProps> = ({ nodeData, updateNodeData }) => {
  const [codeComponent, setCodeComponent] = useState(nodeData.component || {});

  // 当组件加载时，主动触发 CodeMirror 的 onUpdateData 方法
  useEffect(() => {
    // 如果是新创建的节点，没有默认的 component 数据，则设置默认值
    if (!nodeData.component || Object.keys(nodeData.component).length === 0) {
      const defaultData = {
        customDef: {
          languageId: '63', // 默认 Java
          sourceCode: '/**\n' +
            'ExecClass类main 方法是固定的启动函数，参数个数、类型、返回类型不可更改\n' +
            '当前版本gson-2.10.1.jar的文档地址：\n' +
            'https://www.javadoc.io/doc/com.google.code.gson/gson/2.10.1/index.html\n' +
            '*/\n' +
            'import com.google.gson.JsonObject;\n' +
            'class ExecClass{  \n' +
            '  public JsonObject main(JsonObject args){\n' +
            '    return args;\n' +
            '  }\n' +
            '}'
        },
        type: 'CODE'
      };

      // 更新节点数据
      updateNodeData('component', defaultData);
      setCodeComponent(defaultData);
    }
    else {
      // 如果已有 component 数据，则使用现有数据
      setCodeComponent(nodeData.component);
    }
  }, []);

  return (
    <>
      <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />输入参数</Typography.Title>
      <ParamsTable
        initialData={nodeData.parameters.dataIns || []}
        onUpdateData={(data) => {
          updateNodeData('parameters', {
            ...nodeData.parameters,
            dataIns: data
          });
        }}
      />
      <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />输出参数</Typography.Title>
      <ParamsTable
        initialData={nodeData.parameters.dataOuts || []}
        onUpdateData={(data) => {
          updateNodeData('parameters', {
            ...nodeData.parameters,
            dataOuts: data
          });
        }}
      />
      <Typography.Title heading={5}><IconUnorderedList style={{ marginRight: 5 }} />代码段</Typography.Title>
      <CodeMirror
        initialData={codeComponent}
        onUpdateData={(data) => {
          setCodeComponent(data);
          updateNodeData('component', {
            ...data
          });
        }}
      />
    </>
  );
};

export default CodeEditor;