/*
 * @Author: yuananting
 * @Date: 2021-07-05 10:47:19
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-02 17:54:13
 * @Description: 描述一下咯
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
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, editorType, placeholder = '请输入正文' } = 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.config.placeholder = placeholder;
    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 = (content) => {
      if (content == '' && !content) return '';
      var str = content; // 保留空格和换行的其他字符
      str = str.replace(/<xml>[\s\S]*?<\/xml>/gi, '');
      str = str.replace(/<style>[\s\S]*?<\/style>/gi, '');
      str = str.replace(/<\/?a.*?>/g, '');
      return str;
    };
    this.editorInt.config.onchange = (html) => {
      var str = this.editorInt.txt.text(); // 去除所有特殊字符
      str = str.replace(/<xml>[\s\S]*?<\/xml>/gi, '');
      str = str.replace(/<style>[\s\S]*?<\/style>/gi, '');
      str = str.replace(/<\/?[^>]*>/g, '');
      str = str.replace(/[ | ]*\n/g, '\n');
      str = str.replace(/\&nbsp\;/gi, ' ');
      str = str.replace(/[\r\n]/g, '');
      str = str.replace(/<\/?a.*?>/g, '');
      const videoCount = ((html || '').match(/<iframe/g) || []).length;
      const imageCount = ((html || '').match(/<img/g) || []).length;
      const textLength = str.length + videoCount + imageCount;
      this.setState({ textLength }, () => {
        if (textLength > maxLimit) {
          message.warning(`内容过长，不能超过${maxLimit}字`);
        }
        Bus.trigger('editorLimit', textLength, editorType);
        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 { 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 || 1000})
        </div>
        {textLength > maxLimit && (
          <div style={{ top: isIntro ? '245px' : '512px' }} className='editor-warning'>
            最多只能输入{maxLimit || 1000}字
          </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;
