import React, { useState, useEffect } from 'react';
import { Form, Button, message } from 'antd';
import JSONEditor from 'jsoneditor';
import { findValueByNamePath } from '../../utils';
import 'jsoneditor/dist/jsoneditor.min.css';
import { PREFIX_CLS } from '../../config';
import './index.less';

const prefixCls = `${PREFIX_CLS}-json-editor`;
export default ({ node, propKey, config, onChangePathValue = () => {} }) => {
  const { label, name } = config;
  const [editor, setEditor] = useState();
  const handleSubmitCode = () => {
    let editorData;
    try {
      editorData = editor.get();
    } catch (e) {
      message.error('错误的数据格式!请使用标准的json格式!');
      return;
    }
    onChangePathValue({ path: name, value: editorData });
    message.success('确定成功!');
  };

  useEffect(() => {
    const nextValue = findValueByNamePath(name, node[propKey]);
    if (!editor) {
      const container = document.getElementById('jsoneditor');
      const options = {
        mode: 'code',
      };
      const jeditor = new JSONEditor(container, options);
      jeditor.set(nextValue || {});
      setEditor(jeditor);
    } else {
      editor.set(nextValue || {});
    }
  }, [node[propKey], name]);

  return (
    <Form.Item label={label} className={prefixCls}>
      <div id="jsoneditor" style={{ width: '100%', height: 300 }} />
      <div className={`${prefixCls}-code-buttons`}>
        <Button type="primary" onClick={handleSubmitCode}>
          确定
        </Button>
      </div>
    </Form.Item>
  );
};
