import { message } from 'antd';
import React from 'react';
import E from 'wangeditor';
import Bus from '../../../core/bus';
import SelectPrepareFileModal from '../../prepare-lesson/modal/SelectPrepareFileModal';
import './GraphicsEditor.less';

const { BtnMenu } = E;

class GraphicsEditor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      editorId: window.random_string(16),
      textLength: 0,
      showSelectImageModal: false,
      showSelectVideoModal: false,
      diskList: [],
    }
    this.editorInt = null;
  }

  componentDidMount() {
    this.renderEditor()
    this.resetIndex(true);
    this.initBus();
  }



  componentWillUnmount() {
    this.resetIndex();
    this.removeBus();
  }

  resetIndex = (bool) => {
    const topDom = document.querySelector('.top-container');
    const leftDom = document.querySelector('.left-container');
    topDom.style.zIndex = bool ? 'auto' : 112;
    leftDom.style.zIndex = bool ? 'auto' : 2;
  }

  renderEditor() {
    const { editorId } = this.state;
    const { detail, onChange, isIntro, maxLimit } = this.props;
    class ImageMenu extends BtnMenu {
      constructor(editor) {
        // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
        const $elem = E.$(
          `<div class="w-e-menu" data-title="图片">
                  <i class="w-e-icon-image"></i>
              </div>`
        )
        super($elem, editor)
      }
      // 菜单点击事件
      clickHandler() {
        Bus.trigger(`graphicsEditorImage${isIntro ? '' : 'Content'}`)
      }

      tryChangeActive() {

      }
    }

    class VideoMenu extends BtnMenu {
      constructor(editor) {
        // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
        const $elem = E.$(
          `<div class="w-e-menu" data-title="视频">
                  <i class="w-e-icon-play"></i>
              </div>`
        )
        super($elem, editor)
      }
      // 菜单点击事件
      clickHandler() {
        Bus.trigger('graphicsEditorVideo')
      }

      tryChangeActive() {

      }
    }

    this.editorInt = new E(`#editor${editorId}`);
    this.editorInt.config.focus = false;
    this.editorInt.config.showFullScreen = !isIntro
    this.editorInt.menus.extend('xmimage', ImageMenu);
    !isIntro && this.editorInt.menus.extend('xmvideo', VideoMenu);
    this.editorInt.config.menus = isIntro ?
      [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'foreColor',
        'backColor',
        'list',
        'justify',
        'emoticon',
        'xmimage',
      ]
      : [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'todo',
        'justify',
        'quote',
        'emoticon',
        'xmimage',
        'xmvideo',
        'table',
        'splitLine',
        'undo',
        'redo',
      ];

    this.editorInt.config.emotions = [
      {
        title: 'emoji',
        type: 'emoji',
        content: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '😊', '🙂', '🙃', '😉', '😓', '😅', '😪', '🤔', '😬', '🤐']
      }
    ]
    this.editorInt.config.zIndex = 1;
    this.editorInt.config.pasteFilterStyle = false;
    this.editorInt.config.pasteIgnoreImg = true;
    // 自定义处理粘贴的文本内容
    this.editorInt.config.pasteTextHandle = function (content) {
      if (content == '' && !content) return ''
      var str = content
      str = str.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
      str = str.replace(/<style>[\s\S]*?<\/style>/ig, '')
      str = str.replace(/[ | ]*\n/g, '\n')
      str = str.replace(/\&nbsp\;/ig, ' ')
      return str
    }
    this.editorInt.config.onchange = (html) => {
      const videoCount = ((html || '').match(/<iframe/g) || []).length;
      const imageCount = ((html || '').match(/<img/g) || []).length;
      const textLength = this.editorInt.txt.text().replace(/\&nbsp\;/ig, ' ').length + videoCount + imageCount;
      this.setState({ textLength }, () => {
        if (textLength > maxLimit) {
          // message.warning('超过字数限定');
        }
        onChange(html, this.state.textLength);
      })
    }
    this.editorInt.create();
    this.editorInt.txt.html(detail.content);
  }

  // 选择图文
  handleSelectVideo = (file) => {
    const { ossUrl } = file || {};
    if (!ossUrl) return null;
    this.setState({
      showSelectVideoModal: false
    })
    const { detail } = this.props;
    this.editorInt && this.editorInt.txt.html(`${detail.content}<p style="width: 100%;padding-top: 56.25%;position: relative;"><iframe style="position: absolute;width: 100%;height: 100%;top: 0;left: 0;" src="${ossUrl}"></iframe><br/></p><p><br/></p>`)
  }

  handleSelectImage = (file) => {
    const { ossUrl } = file || {};
    if (!ossUrl) return null;
    this.setState({
      showSelectImageModal: false
    })
    const { detail } = this.props;
    this.editorInt && this.editorInt.txt.html(`${detail.content}<p><img style="max-width: 100%;" src="${ossUrl}" /><br/><p>`)
  }

  initBus = () => {
    const { isIntro } = this.props;
    Bus.bind(`graphicsEditorImage${isIntro ? '' : 'Content'}`, this.uploadImage)
    !isIntro && Bus.bind('graphicsEditorVideo', this.uploadVideo)
  }

  removeBus = () => {
    const { isIntro } = this.props;
    Bus.unbind(`graphicsEditorImage${isIntro ? '' : 'Content'}`, this.uploadImage)
    !isIntro && Bus.unbind('graphicsEditorVideo', this.uploadVideo)
  }

  uploadImage = () => {
    this.setState({ showSelectImageModal: true })
  }

  uploadVideo = () => {
    this.setState({ showSelectVideoModal: true })
  }

  render() {
    const { 
      editorId, 
      textLength, 
      showSelectImageModal,
      showSelectVideoModal,
      diskList,
    } = this.state;
    const { limitLength = 1000, isIntro, maxLimit } = this.props;
    return <div className={`graphics-editor-container${isIntro ? ' introduce' : ''}  ${(textLength > maxLimit)&& 'warning'}`}>
      <div className="editor-box" id={`editor${editorId}`} ></div>
      <div className="editor-tips">( {(textLength > maxLimit) ? <span style={{ color: 'red' }} >{textLength}</span> : textLength}/{maxLimit || 100000})</div>
      {showSelectVideoModal &&
        <SelectPrepareFileModal
          operateType="select"
          selectTypeList={['MP4']}
          accept="video/mp4"
          confirm={{
            title: '文件过大，无法上传',
            content: '为保障学员的观看体验，上传的图文大小不能超过2G',
          }}
          tooltip={'格式支持mp4，大小不超过2G'}
          isOpen={showSelectVideoModal}
          diskList={diskList}
          addVideo={true}
          onClose={() => {
            this.setState({ showSelectVideoModal: false })
          }}
          onSelect={this.handleSelectVideo}
        />
      }
      {showSelectImageModal &&
        <SelectPrepareFileModal
          key="basic"
          operateType="select"
          multiple={false}
          accept="image/jpeg,image/png,image/jpg"
          selectTypeList={['JPG', 'JPEG', 'PNG']}
          tooltip='支持文件类型：jpg、jpeg、png'
          isOpen={showSelectImageModal}
          onClose={() => {
            this.setState({ showSelectImageModal: false })
          }}
          onSelect={this.handleSelectImage}
        />
      }
    </div>
  }
}

export default GraphicsEditor;
