import React, { Component } from 'react';
import classnames from 'classnames';
import AceEditor from '@easyv/react-ace';
import isEqual from 'lodash/isEqual';
import message from 'components/message';
export default class StaticData extends Component<{
  data: any;
  height?: string;
  onChange: (data: any) => any;
}> {
  editor: any;

  componentWillUnmount() {
    if (this.editor && this.editor.editor && this.editor.editor.getValue()) {
      try {
        let data = JSON.parse(this.editor.editor.getValue());
        if (Array.isArray(data)) {
          if (!isEqual(data, this.props.data)) {
            this.props.onChange({
              data
            });
          }
        } else {
          message.error('数据必须为数组');
        }
      } catch (error) {
        message.error('数据格式有误，请检查');
      }
    }
  }

  handleEditorBlur = (event, editor) => {
    event.stopPropagation();
    if (editor) {
      try {
        let data = JSON.parse(editor.getValue());
        if (Array.isArray(data)) {
          if (!isEqual(data, this.props.data)) {
            this.props.onChange({
              data
            });
          }
        } else {
          message.error('数据必须为数组');
        }
      } catch (error) {
        message.error('数据格式有误，请检查');
      }
    }
  };

  render() {
    const { data, height } = this.props;
    return (
      <AceEditor
        className={classnames(['dark'])}
        ref={(dom) => (this.editor = dom)}
        mode="json"
        theme="twilight"
        width="100%"
        height={height || '400px'}
        name="static"
        tabSize={2}
        value={JSON.stringify(data, null, '\t')}
        enableBasicAutocompletion={true}
        enableLiveAutocompletion={true}
        showGutter={true}
        editorProps={{ $blockScrolling: true }}
        setOptions={{ wrap: true }}
        onBlur={this.handleEditorBlur}
      />
    );
  }
}
