import React, { Component } from 'react'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'

export default class index extends Component {
    state = {
        editorState: '',
        outputHTML: '',
    }

    /**
     * mount后回调
     */
    componentDidMount() {
        this.isLivinig = true
        this.toParent()
    }
    componentWillUnmount() {
        this.isLivinig = false
    }
    handleChange = editorState => {
        const outputHTML = editorState.toHTML()

        const { onChange } = this.props

        this.setState({
            editorState: editorState,
            outputHTML,
        })

        onChange && onChange(outputHTML)
    }

    setEditorContentAsync = () => {
        this.isLivinig &&
            this.setState({
                editorState: BraftEditor.createEditorState(this.props.value),
            })
    }

    //给父控件 调用这个方法  因为只有父控件才能掌握页面加载完的时间
    toParent = () => {
        this.props.parent.getChildrenMsg(this.setEditorContentAsync)
    }
    render() {
        const { editorState } = this.state
        const controls = ['bold', 'italic', 'underline', 'text-color', 'separator']

        return (
            <BraftEditor
                value={editorState}
                controls={controls}
                onChange={this.handleChange}
                placeholder={'请输入内容'}
            />
        )
    }
}
