import React, { useCallback, useEffect, useState } from 'react';
import { Select } from '@arco-design/web-react';
import CodeMirror from '@uiw/react-codemirror';
import { java } from '@codemirror/lang-java';
import { python } from '@codemirror/lang-python';
import { githubLight } from '@uiw/codemirror-theme-github';

const Option = Select.Option;

interface TableDataItem {
  key: number | string;
  id: string;
  dataType: string;
  arrayType: string;
  desc: string;
  defaultValue: string;

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

interface CodeMirrorProps {
  initialData: TableDataItem[],
  onUpdateData: (data) => void,
}

const extensions = [java(), python(), githubLight];
const options = ['java', 'python'];
const defaultCode = {
  'java': '/**\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' +
    '}',
  'python': '# main函数是启动函数，参数类型、个数、返回类型不可更改\n' +
    'def main(a:dict)->dict:\n' +
    '  return {\'b\': a.get(\'a\')+[4,5]}'
};
const nameToCode = {
  'java': '63',
  'python': '70'
};


const CodeMirrorComp: React.FC<CodeMirrorProps> = ({
                                                     initialData,
                                                     onUpdateData
                                                   }) => {
  const [value, setValue] = useState('console.log(\'hello world!\');');
  const [language, setLanguage] = useState('java');

  const onChange = useCallback((val, viewUpdate) => {
    setValue(val);
    const data = {
      customDef: {
        languageId: nameToCode[language],
        sourceCode: val
      }
    };
    console.log('data:', data);
    onUpdateData(data);
  }, []);

  useEffect(() => {
    setValue(defaultCode[language]);
  }, []);
  return (
    <>
      <Select
        defaultValue={'java'}
        placeholder="请选择语言"
        style={{ width: 154 }}
        onChange={(value) => {
          setLanguage(value);
          setValue(defaultCode[value]);
        }}
      >
        {options.map((option, index) => (
          <Option key={option} disabled={index === 3} value={option}>
            {option}
          </Option>
        ))}
      </Select>
      <CodeMirror
        value={value}
        height="300px"
        extensions={extensions}
        onChange={onChange} />
    </>
  );
};

export default CodeMirrorComp;