import React, { Component } from "react";
import E from "wangeditor";
import { message, Button } from "antd";
import UploadOss from "@/core/upload";
import "./QuestionEditor.less";
const MEDIA_MAP = [
  {
    title: "音频",
    icon: <React.Fragment>&#xe756;</React.Fragment>,
    key: "VOICE",
  },
  {
    title: "录音",
    icon: <React.Fragment>&#xe7bb;</React.Fragment>,
    key: "RECORD",
  },
  {
    title: "图片",
    icon: <React.Fragment>&#xe758;</React.Fragment>,
    key: "PICTURE",
  },
  {
    title: "视频",
    icon: <React.Fragment>&#xe755;</React.Fragment>,
    key: "VIDEO",
  },
];
class QuestionEditor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorId: window.random_string(16),
      visiblePlacehold: true,
      visibleMediaBox: false,
      zIndex: 9,
      focusFlag: false,
      isShowSingleInput: true,
      contentLength: 0,
      errorInput: false,
      isGapFilling: props.isGapFilling,
      contentType: props.contentType,
      detailInfo: props.detailInfo || {},
      gapFillingAnswer: props.gapFillingAnswer || [],
      blanksList: props.blanksList || [],
    };
  }

  componentDidMount() {
    this.renderEditor();
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    return {
      detailInfo: nextProps.detailInfo
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { detailInfo } = nextProps;
    if (this.state.detailInfo !== detailInfo) {
      this.setState({ detailInfo: nextProps.detailInfo }, () => {
        this.renderEditor();
      });
    }
    return true;
  }

  handleUploadMedia = (key) => {
    this.props.onUploadMedia && this.props.onUploadMedia(key);
  };

  getBoxDom = () => {
    const { markKey } = this.props;
    const domList = document.getElementsByClassName(
      `question-edtior_box__${markKey}`
    );
    let zIndex = 99;
    _.find(domList, (domItem, domIndex) => {
      if (domItem.getAttribute("editorid") === this.state.editorId) {
        zIndex = zIndex + domList.length - domIndex;
        return domItem;
      }
    });
    return zIndex;
  };

  handleChangeContent = (content) => {
    content &&
      this.editorRoot.txt.html(
        /^\<p/.test(content) ? content : `<p>${content}</p>`
      );
    this.editorRoot.change && this.editorRoot.change();
  };

  renderEditor() {
    const { editorId, detailInfo } = this.state;
    const { onChange, bindChangeContent } = this.props;
    const editorRoot = new E(
      `#editor${editorId}_tabbar`,
      `#editor${editorId}_content`
    );
    editorRoot.customConfig.menus = [];
    editorRoot.customConfig.uploadImgMaxSize = 1 * 1024 * 1024;
    editorRoot.customConfig.customAlert = function (info) {
      message.warning(/1M/.test(info) ? "图片大于1M，请使用图片上传" : info);
    };
    editorRoot.customConfig.customUploadImg = function (files, insert) {
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法
      UploadOss.uploadBlobToOSS(files[0], window.random_string(16)).then(
        (urlStr) => {
          insert(urlStr);
        }
      );
    };
    editorRoot.customConfig.zIndex = 999;
    editorRoot.customConfig.pasteFilterStyle = false;
    // 自定义处理粘贴的文本内容
    editorRoot.customConfig.pasteTextHandle = function (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(/<\/?[^>]*>/g, "");
      str = str.replace(/[ | ]*\n/g, "\n");
      str = str.replace(/\&nbsp\;/gi, " ");
      str = str.replace(/[\r\n]/g, "");
      if (str.length > 1000) {
        str = str.substring(0, 1000);
        message.error("内容过长，不能超过1000字");
      }
      return str;
    };

    editorRoot.customConfig.onchange = (html) => {
      const { focusFlag } = this.state;
      const textLength = editorRoot.txt.text().replace(/\&nbsp\;/gi, " ")
        .length;
      const imgLength = html.match(/<img/g)
        ? html.match(/<img/g).length * 2
        : 0;
      const contentLength = imgLength + textLength;
      const divHeight = document.getElementById(`editor${editorId}_content`)
        .firstChild.offsetHeight;
      if (divHeight > 30 || imgLength > 0) {
        this.setState({ isShowSingleInput: false });
      } else {
        this.setState({ isShowSingleInput: true });
      }
      if (this.state.isGapFilling) {
        this.props.changeBlankCount(this.state.blanksList);
      }
      this.setState(
        { contentLength, visiblePlacehold: contentLength === 0 && !focusFlag },
        () => {
          onChange && onChange(html, this.state.contentLength);
        }
      );
    };

    editorRoot.customConfig.onblur = (html) => {
      editorRoot.change && editorRoot.change();
      this.setState({
        focusFlag: false,
        visibleMediaBox: false,
        visiblePlacehold: _.isEmpty(html.replace(/\<\/?[\w]+\>/g, "")),
        zIndex: 9,
      });
    };

    editorRoot.customConfig.onfocus = () => {
      this.setState({
        focusFlag: true,
        visibleMediaBox: true,
        visiblePlacehold: false,
      });
    };

    editorRoot.create();
    this.editorRoot = editorRoot;

    // if (detailInfo && detailInfo.content) {
    const contentHtml = /^\<p/.test(detailInfo.content)
      ? detailInfo.content
      : `<p>${detailInfo.content}</p>`;
    editorRoot.txt.html(detailInfo.content);
    const textLength = editorRoot.txt.text().replace(/\&nbsp\;/gi, " ")
      .length;
    const imgLength = contentHtml.match(/<img/g)
      ? contentHtml.match(/<img/g).length * 2
      : 0;
    const contentLength = imgLength + textLength;
    this.setState(
      {
        contentLength,
        visiblePlacehold: contentLength === 0 && !this.state.focusFlag,
      },
      () => {
        onChange && onChange(contentHtml, this.state.contentLength);
      }
    );
    // }
    bindChangeContent && bindChangeContent(this.handleChangeContent);
  }

  insertBlank = (blanks) => {
    var blanks = `<input class="add-fill-line" disabled answerTagList="" id=${window.random_string(
      16
    )} value="填空"/>`;
    this.editorRoot.cmd.do("insertHTML", blanks);
    document.getSelection().collapseToEnd();
    var _blanksList = [];
    _blanksList = document.getElementsByClassName("add-fill-line");
    this.setState({ blanksList: _blanksList });
    this.setState({
      visiblePlacehold: false,
    });
    // this.props.changeBlankCount(_blanksList);
  };

  render() {
    const {
      editorId,
      visiblePlacehold,
      visibleMediaBox,
      zIndex,
      focusFlag,
      contentLength,
      isShowSingleInput,
      errorInput,
      isGapFilling,
      contentType,
    } = this.state;
    const {
      placehold,
      mediaBtn = ["VOICE", "RECORD", "PICTURE", "VIDEO"],
      limitLength = 1000,
      markKey,
    } = this.props;
    return (
      <div
        className={`question-edtior_box question-edtior_box__${markKey}`}
        editorid={editorId}
        style={{ zIndex }}
        onMouseEnter={() => {
          if (visibleMediaBox || focusFlag) return;
          const setZIndex = this.getBoxDom();
          this.setState({
            visibleMediaBox: true,
            zIndex: setZIndex,
          });
        }}
        onMouseLeave={() => {
          if (!visibleMediaBox || focusFlag) return;
          this.setState({
            visibleMediaBox: false,
            zIndex: 9,
          });
        }}
      >
        <div
          className="editor-box"
          id={`editor${editorId}_tabbar`}
          style={{ display: "none" }}
        ></div>
        <div
          className={
            isShowSingleInput ? "editor-box-single " : "editor-box-multiple"
          }
          style={{
            border:
              this.props.validateStatus === "error" ? "1px solid red" : "",
          }}
        >
          <div
            className="editor-box editor-box_content"
            id={`editor${editorId}_content`}
          ></div>
          <div className="editor-limit">
            <span style={{ color: errorInput ? "red" : "" }}>
              {contentLength}
            </span>
            /{limitLength}
          </div>
        </div>
        {isGapFilling && contentType === "QUESTION_STEM" && (
          <div className="editor-fill-info">
            在需要填写答案的地方
            <Button
              type="link"
              className="editor-fill-info_icon icon iconfont"
              onClick={this.insertBlank}
            >
              &#xe7fd; 插入占位符
            </Button>
          </div>
        )}
        <div
          className={`editor-limit-tip${contentLength > limitLength ? " mt6" : ""
            }`}
          style={{ height: contentLength > limitLength ? 20 : 0 }}
        >
          最多只能输入1000字
        </div>
        {visiblePlacehold && (
          <div className="editor-placehold">{placehold}</div>
        )}
        {visibleMediaBox && !_.isEmpty(mediaBtn) && (
          <div className="edtior-media_box">
            <div className="edtior-media_list">
              {_.map(mediaBtn, (mediaItem) => {
                const mediaBtnMap = _.find(
                  MEDIA_MAP,
                  (mapItem) => mapItem.key === mediaItem
                );
                return (
                  mediaBtnMap && (
                    <div
                      className="edtior-media_item"
                      key={mediaItem}
                      onClick={() => this.handleUploadMedia(mediaItem)}
                    >
                      <div className="edtior-media_item__icon icon iconfont">
                        {mediaBtnMap.icon}
                      </div>
                      <div className="edtior-media_item__name">
                        {mediaBtnMap.title}
                      </div>
                    </div>
                  )
                );
              })}
            </div>
          </div>
        )}
      </div>
    );
  }
}

export default QuestionEditor;
