import React from 'react';
import { networkUtils, config } from '@utils';
import Uid from './uid';

const { ueditorUrl, ueditorConfigUrl } = config;
const UEDITOR_LOADED_KEY = '__BEE_UEDITOR_LOADED_STATUS__';

// ueditor 默认值
const initConfig = {
  autoClearinitialContent: false,
  autoFloatEnabled: true, // 是否保持 toolbar 滚动时不动
  focus: false,
  wordCount: false,
  elementPathEnabled: false,
  pasteplain: false, // 是否默认为纯文本粘贴。false为不使用纯文本粘贴，true为使用纯文本粘贴
  initialFrameWidth: '100%', // 初始化编辑器宽度
  initialFrameHeight: 200,
  maximumWords: 10000
};

export default class RichText extends React.Component {
  static defaultProps = {
    value: '',
    readOnly: false,
    onChange: () => {},
    ueditorUrl,
    ueditorConfigUrl,
    ueditorHomeUrl: '',
    ueditorIframeUrl: '',
    editorConfig: {}, // ueditor 默认值
    className: '',
    prefix: 'bee'
  };

  constructor(props) {
    super(props);
    this.uuid = `bee-${Uid()}`;
  }

  componentDidMount() {
    this.contractVarFetchData();
    let timer = null;
    if (window.UE) {
      this.initRichText();
    } else {
      timer = setInterval(() => {
        const status = window[UEDITOR_LOADED_KEY];
        if (status === 2) {
          clearInterval(timer);
          this.registerContractVar();
          this.initRichText();
        } else if (status !== 1) {
          this.loadUEditorScript();
        }
      }, 50);
    }
  }

  componentWillUnmount() {
    if (!this.editor) return;
    this.editor.destroy();
    // 以下是因为没有解决：已创建UE对象的异步请求的问题，所以销毁时置空。
    window.UE = null;
    window[UEDITOR_LOADED_KEY] = undefined;
  }

  componentWillReceiveProps({ value, list }) {
    if (value !== this.props.value && this.editor) {
      this.editor.setContent(value);
    }
  }

  loadUEditorScript() {
    if (window[UEDITOR_LOADED_KEY] !== undefined) {
      return;
    }
    window[UEDITOR_LOADED_KEY] = 1; // 加载中
    let {
      ueditorHomeUrl,
      ueditorIframeUrl,
      ueditorUrl,
      ueditorConfigUrl
    } = this.props;

    window.UEDITOR_HOME_URL = ueditorHomeUrl;
    window.UEDITOR_IFRAME_URL = ueditorIframeUrl;

    this.createScriptDom(ueditorConfigUrl, () => {
      this.createScriptDom(ueditorUrl, () => {
        window[UEDITOR_LOADED_KEY] = 2; // 加载完成
      });
    });
  }

  createScriptDom(url, callback) {
    const scriptDom = document.createElement('script');
    scriptDom.type = 'text/javascript';
    scriptDom.async = true;
    scriptDom.src = url;

    scriptDom.onload = function() {
      callback();
    };
    document.body.appendChild(scriptDom);
  }

  initRichText = () => {
    const UE = window.UE;
    const target = document.getElementById(this.uuid);
    if (!UE || !target) {
      return false;
    }

    let { value, readOnly, editorConfig } = this.props;
    let conf = { ...initConfig, ...editorConfig, ...{ readonly: readOnly } };
    let editor = new UE.ui.Editor(conf);
    this.editor = editor;

    editor.addListener('blur contentChange', () => {
      this.onChange();
    });
    editor.render(target);
    editor.ready(() => {
      editor.setContent(value);
    });
  };

  onChange = () => {
    const value = this.editor.getContent();
    this.props.onChange && this.props.onChange(value);
  };

  //---------- 合同变量 ----------//
  // 拉去变量列表
  contractVarFetchData() {
    networkUtils
      .request({ method: 'get', url: '/api/contract-mgmt/contract-tmpls/var' })
      .then(data => {
        if (data.success) {
          this.setState({
            contractVarOptions: data.data
          });
        } else {
          throw data;
        }
      });
  }
  // 注册变量组件
  registerContractVar() {
    const UE = window.UE;
    const target = document.getElementById(this.uuid);
    if (!UE || !target) {
      return false;
    }
    const _this = this;
    const { contractVarOptions } = this.state;
    const { contractVarCfg } = this.props;
    UE.registerUI('contractVar', function(editor, uiName) {
      var items = contractVarOptions.map(item => {
        return {
          label: item.contractVarName,
          value: item.contractVarName,
          renderLabelHtml: function() {
            return (
              '<div class="edui-label %%-label" style="line-height:2;">' +
              (this.label || '') +
              '</div>'
            );
          }
        };
      });

      var contractVarCombox = new UE.ui.Combox({
        title: contractVarCfg.title,
        initValue: contractVarCfg.title,
        editor: editor,
        items: items,
        onselect: function(t, index) {
          const contractVal = this.items[index].value;
          const selected = contractVarOptions.find(
            d => d.contractVarName === contractVal
          );
          // 直接使用父组件props，实现动态参数
          _this.props.contractVarCfg.onselect(selected);
        }
      });

      editor.addListener('selectionchange', function(type, causeByUi, uiReady) {
        if (!uiReady) {
          contractVarCombox.setValue(contractVarCfg.title);
          // 直接使用父组件props，实现动态参数
          contractVarCombox.setDisabled(_this.props.readOnly);
        }
      });
      return contractVarCombox;
    });
  }
  //---------- 合同变量 ----------//

  render() {
    const { prefix, className } = this.props;
    return (
      <div className={`${prefix}-richtext ${className}`}>
        <div id={this.uuid} />
      </div>
    );
  }
}
