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 currentBlanksList = this.saveCurrentBlanks(); // 获取当前填空列表
    console.log("originBlanksList:", this.state.originBlanksList);
    console.log("currentBlanksList:", currentBlanksList);
    // console.log(JSON.stringify(currentBlanksList)===JSON.stringify(this.state.originBlanksList))
    if (
      JSON.stringify(currentBlanksList) !==
      JSON.stringify(this.state.originBlanksList)
    ) {
      console.log("修改")
      this.setState({ originBlanksList: this.saveCurrentBlanks() }); // 保存修改前的填空列表
      this.sortBlanks();
    }
    this.handleStemStyle();
    this.props.changeBlankCount(currentBlanksList);
  };

  sortBlanks = () => {
    const _blanksList = JSON.parse(JSON.stringify(this.saveCurrentBlanks()));
    _blanksList.map((item, index) => {
      item.innerHTML = "填空" + (index + 1);
      return item;
    });
    this.setState({ blanksList: _blanksList });
  };

  saveCurrentBlanks = () => {
    var currentBlanksList = [];
    var stemInput = document.getElementById("editor-box_content");
    stemInput.childNodes.forEach((item) => {
      if (item.nodeName === "SPAN") {
        currentBlanksList.push(item);
      }
    });
    return currentBlanksList;
  };

  handleInsertBlanks = (id) => {
    document.getElementById("editor-box_content").focus();
    const { blanksList } = this.state;
    blanksList.map((item, index) => {
      item.innerHTML = "填空" + (index + 1);
    });
    var templateBlanks = blanksList.filter((item) => item.id === id);
    var insertBlanks = document.createElement("span");
    insertBlanks.className = "fill-line";
    insertBlanks.innerHTML = templateBlanks[0].innerHTML;
    insertBlanks.id = templateBlanks[0].id; // 填空id;
    insertBlanks.contentEditable = false;
    var sel, range;
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      var el = document.createElement("div");
      el.appendChild(insertBlanks);
      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);
      }
    }
  };

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

  insertBlanks = () => {
    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 });
    this.handleInsertBlanks(blanks.id);
  };

  // 输入框样式
  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;
