import React, { Component } from "react";
import { message, Button } from "antd";
import UploadOss from "@/core/upload";
import "./CompletionStem.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 CompletionStem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleMediaBox: false,
      zIndex: 9,
      focusFlag: false,
      isShowSingleInput: true,
      contentLength: 0,
      errorInput: false,
      blanksList: [],
      originBlanksList: [],
    };
  }

  componentDidUpdate() {
    const stemInput = document.getElementById("editor-box_content");
    stemInput.addEventListener("DOMSubtreeModified", this.watchStemContent);
  }

  watchStemContent = () => {
    var _blanksList = [];
    const stemInput = document.getElementById("editor-box_content");
    stemInput.childNodes.forEach((item) => {
      if (item.nodeName === "SPAN") {
        _blanksList.push(item);
      }
    });
    this.setState({blanksList:_blanksList})
    this.handleStemStyle();
    this.props.changeBlankCount(this.state.blanksList);
  };

  /**
   * 插入占位符
   *
   * @memberof QuestionInputItem
   */

  insertBlanks = () => {
    document.getElementById("editor-box_content").focus();
    const _blanksList = this.state.blanksList;
    var blanks = document.createElement("span");
    blanks.className = "fill-line";
    blanks.innerHTML = "填空";
    blanks.id = window.random_string(16); // 填空id
    blanks.contentEditable = false;
    _blanksList.push(blanks);
    this.setState({ blanksList: _blanksList });
    var sel, range;
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      var el = document.createElement("div");
      el.appendChild(blanks);
      var frag = document.createDocumentFragment(),
        node,
        lastNode;
      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      range.insertNode(frag);
      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  };

  // 输入框样式
  handleStemStyle = () => {
    const stemInput = document.getElementById("editor-box_content");
    const textLength = stemInput.innerText.replace(/\&nbsp\;/gi, " ").length;
    const imgLength = stemInput.innerHTML.match(/<img/g)
      ? stemInput.innerHTML.match(/<img/g).length * 2
      : 0;
    const contentLength = imgLength + textLength;
    this.setState({ contentLength });
    const divHeight = document.getElementById("editor-box_content")
      .offsetHeight;
    if (divHeight > 22 || imgLength > 0) {
      this.setState({ isShowSingleInput: false });
    } else {
      this.setState({ isShowSingleInput: true });
    }
  };

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

  render() {
    const {
      visibleMediaBox,
      zIndex,
      focusFlag,
      contentLength,
      isShowSingleInput,
      errorInput,
    } = this.state;
    const {
      mediaBtn = ["VOICE", "RECORD", "PICTURE", "VIDEO"],
      limitLength = 1000,
    } = this.props;
    return (
      <div
        className="completion-question-edtior_box"
        style={{ zIndex }}
        onMouseEnter={() => {
          if (visibleMediaBox || focusFlag) return;
          const setZIndex = 101;
          this.setState({
            visibleMediaBox: true,
            zIndex: setZIndex,
          });
        }}
        onMouseLeave={() => {
          if (!visibleMediaBox || focusFlag) return;
          this.setState({
            visibleMediaBox: false,
            zIndex: 9,
          });
        }}
      >
        <div
          className={
            isShowSingleInput ? "editor-box-single " : "editor-box-multiple"
          }
          style={{
            border:
              this.props.validateStatus === "error" ? "1px solid red" : "",
          }}
        >
          <div
            placeholder="示例：党章规定，凡事有&nbsp;&nbsp;填空1&nbsp;&nbsp;
            人以上的&nbsp;&nbsp;填空2&nbsp;&nbsp;
            ，都应该成立党的基层组织"
            contentEditable
            suppressContentEditableWarning
            className="editor-box_content"
            id="editor-box_content"
          ></div>
          <div className="editor-limit">
            <span style={{ color: errorInput ? "red" : "" }}>
              {contentLength}
            </span>
            /{limitLength}
          </div>
        </div>
        <div className="editor-fill-info">
          在需要填写答案的地方
          <Button
            type="link"
            className="editor-fill-info_icon icon iconfont"
            onClick={this.insertBlanks}
          >
            &#xe7fd; 插入占位符
          </Button>
        </div>
        <div
          className={`editor-limit-tip${
            contentLength > limitLength ? " mt6" : ""
          }`}
          style={{ height: contentLength > limitLength ? 20 : 0 }}
        >
          最多只能输入1000字
        </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 CompletionStem;
