import React, { Component } from 'react';
import E from 'wangeditor'

class RichTextEditor extends Component {

    constructor(props) {
        super(props);
        this.state = ({
            _html: props.content
        });
    }

    render() {
        return (
            <div className='richtexteditor' ref="editorElem"></div>
        );
    }
    componentDidMount() {
        const { content, onContentChange } = this.props;
        const elem = this.refs.editorElem;
        const editor = new E(elem);
        editor.customConfig.onchange = (html) => {
            const { _html } = this.state;
            if(_html !== html) { // 只有实际内容发生改变才触发model的修改
                onContentChange(html);
            }
        }; // 使用 onchange 函数监听内容的变化
        editor.customConfig.onfocus = () => {
            this.setState({
                _html: editor.txt.html()
            });
            let boardEl = document.getElementsByClassName('react-grid-layout')[0]; // 看板容器组件
            let viewEl = elem.parentElement.parentElement; // chart/richText组件
            let toolbarEl = elem.getElementsByClassName('w-e-toolbar')[0]; // 工具栏组件

            toolbarEl.style.display = 'flex';
            viewEl.style.zIndex = 2; // 使工具栏组件置于其他chat/richText组件上层

            let boardElLayout = boardEl.getBoundingClientRect(); // 看板容器组件layout
            let viewElLayout = viewEl.getBoundingClientRect(); // chart/richText组件layout
            let toolbarElLayout = toolbarEl.getBoundingClientRect(); // 工具栏组件layout
            
            
            console.log(toolbarEl);
            let viewElX = viewElLayout.left; // chart/richText组件左起位置
            let toolbarWidth = toolbarElLayout.width; // 工具栏组件宽度
            let boardWidth = boardElLayout.width; // 看板容器宽度

            console.log(viewElX, toolbarWidth, boardWidth);
            if((viewElX + toolbarWidth) > boardWidth) { // 工具栏超出容器组件右边
                toolbarEl.style.left = -(viewElX + toolbarWidth - boardWidth + 62) + 'px';
            }else {
                toolbarEl.style.left = '0px';
            }
            
        }; // 获得焦点时显示工具栏（需要计算位置）
        editor.customConfig.onblur = function (html) {
            let toolbar = elem.getElementsByClassName('w-e-toolbar')[0];
            toolbar.style.display = 'none';
            let viewEl = elem.parentElement.parentElement;
            viewEl.style.zIndex = 1;
        }
        editor.customConfig.uploadImgShowBase64 = true; // 上传图片（base64）
        editor.create()
        // editor.blur();
        editor.txt.html(content);
    }
}

export default RichTextEditor;