import React, { Component } from 'react';
import 'regenerator-runtime/runtime';
import Events from '@ali/ice-events';
import Loading from '../../components/Loading';

window.editors = [];
@Events
export default class MonacoEditor extends Component {
  static displayName = 'MonacoEditor';

  static propTypes = {};

  static defaultProps = {
    code: '',
    type: 'jsx',
  };

  constructor(props) {
    super(props);
    this.state = {
      monacoReady: false,
    };
    this.uniqueId = props.type;
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.state.monacoReady !== nextState.monacoReady) {
      return true;
    }

    if (nextProps.code !== this.props.code) {
      // this.editor.setValue(nextProps.code);
    }
    return false;
  }

  onChange = (newValue) => {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      const { type } = this.props;
      this.emit('editor:onChange', { type, code: newValue });
    }, 1e3);
  };

  getIframeContent = (code) => {
    const { type } = this.props;
    const uniqueId = this.uniqueId;

    window['_monacoReady' + uniqueId] = (editor) => {
      this.editor = editor;
      window.editors.push({
        id: this.uniqueId, editor, type,
      });
      this.setState({ monacoReady: true });
    };
    window['_monacoChange' + uniqueId] = (str, evt) => {
      // debounce 在下面这个函数做
      this.onChange(str, evt);
    };
    return `
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
	<style>body { margin: 0; }</style>
</head>
<body>
<div id="container" style="width:100%;height:600px;"></div>
<script src="https://cdn.bootcss.com/monaco-editor/0.10.1/min/vs/loader.js"></script>
<script>
  window.editorId = '${uniqueId}';
  
  window.MonacoEnvironment = {
    getWorkerUrl() {
      var prefix = '';
      if (/github/.test(top.location.href)) {
        prefix = '/ice';
      }
      return prefix + '/monaco-editor-worker-loader-proxy.js';
    },
  };

  var cdn = 'https://cdn.bootcss.com/monaco-editor/0.10.1/min/vs';
  var container = document.getElementById('container');
	require.config({ paths: { vs: cdn }});
	require(['vs/editor/editor.main'], function() {
		var editor = window.editor = monaco.editor.create(container, {
			value: ${JSON.stringify(code)},
			language: '${type === 'jsx' ? 'javascript' : type}',
			theme: 'vs-dark',
			options: {
        selectOnLineNumbers: true,
        automaticLayout: true,
      },
		});
		// editor.trigger('', 'editor.action.triggerSuggest', {});
		editor.focus();
		editor.model.onDidChangeContent(function(event) {
		  var value = editor.getValue();
		  top['_monacoChange' + window.editorId] && top['_monacoChange' + window.editorId](value, event);
    });
		top['_monacoReady' + window.editorId] && top['_monacoReady' + window.editorId](editor);
	});
	window.onresize = function(e) {
    window.editor && window.editor.layout();
  };
</script>
</body>
</html>
`;
  };

  render() {
    const { monacoReady } = this.state;
    const { code } = this.props;

    return (
      <div
        className="monaco-editor-container"
        style={styles.monacoEditorContainer}
      >
        <div
          style={{
            ...styles.loadingOverlayer,
            display: !monacoReady ? 'block' : 'none',
          }}
        >
          <Loading text="编辑器加载中" size="small" />
        </div>
        <iframe
          className="monaco-editor-iframe"
          ref={(ref) => {
            this.iframe = ref;
          }}
          scrolling="no"
          style={{
            width: '100%',
            height: '600px',
            border: 'none',
            overflow: 'auto',
            borderRadius: '4px',
          }}
          sandbox="allow-scripts allow-same-origin allow-modals allow-popups allow-forms"
          srcDoc={this.getIframeContent(code)}
        />
      </div>
    );
  }
}

const styles = {
  monacoEditorContainer: {
    overflow: 'hidden',
    position: 'relative',
    width: '100%',
  },
  loadingOverlayer: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
  },
};
