import * as React from 'react';
import {Button, Dialog, Message} from '@alifd/next';
import MonacoEditor from '@alilc/lowcode-plugin-base-monaco-editor';

interface JSXSetterProps {
  value: { source: string };
  type: string;
  defaultValue: string;
  placeholder: string;
  hasClear: boolean;
  onChange: (code: object) => undefined;
  removeProp: () => undefined;
  icons: string[];
}

export default class JSXSetter extends React.PureComponent<JSXSetterProps> {
  static displayName = 'JSXSetter';

  private datasourceCode = '';

  state = {
    isVisible: false,
    source: this.props.value.source,
  };

  openModal = () => {
    const {source} = this.state;
    this.setState({
      isVisible: true,
    });

    this.datasourceCode = source;
  };

  closeModal = () => {
    this.setState({
      isVisible: false,
    });
  };

  componentWillReceiveProps(nextProps: JSXSetterProps) {
    let nextValue = nextProps.value.source;
    if (nextValue !== this.state.source) {
      this.setState({
        source: nextValue,
      });
    }
  }

  compileSource = (value: string) => {
    // @ts-ignore
    return window.Babel.transform(value, {
      presets: [
        [
          'react',
          {
            runtime: 'classic',
          },
        ],
      ],
    }).code;

  };

  /**
   * 渲染按钮
   */
  renderButton = () => {
    return (
      <Button
        size="small"
        type="primary"
        style={{width: '100%'}}
        onClick={this.openModal}>
        编辑代码
      </Button>
    );
  };

  updateCode = (newCode: string) => {
    this.datasourceCode = newCode;
  };

  onConfirm = () => {
    const {onChange, removeProp} = this.props;
    if (this.datasourceCode && this.datasourceCode != '') {
      try {
        const compile = this.compileSource(this.datasourceCode);
        onChange({
          source: this.datasourceCode,
          compile: compile,
        });
        this.closeModal();
      } catch (e) {
        Message.warning({
          title: '数据保存失败',
          content: e.message,
        });
      }
    } else {
      removeProp();
      this.closeModal();
    }
  };

  render() {
    const {source} = this.state;
    const {isVisible} = this.state;
    return (
      <div>
        {this.renderButton()}
        {
          <Dialog
            visible={isVisible}
            title="JSX代码编辑"
            onCancel={this.closeModal}
            onClose={this.closeModal}
            onOk={this.onConfirm}>
            <MonacoEditor
              value={source}
              height={400}
              width={600}
              language="javascript"
              onChange={(newCode) => this.updateCode(newCode)}
            />
          </Dialog>
        }
      </div>
    );
  }
}
