/*
 * @Author: yuananting
 * @Date: 2021-02-25 14:34:29
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-13 20:09:55
 * @Description: 助学工具-题库-题目管理-新建题目Tab
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import { Form, Radio, message, Checkbox, Tag, Tooltip, Input } from "antd";
import "./NewQuestionTab.less";
import Upload from "@/core/upload";
import QuestionEditor from "./QuestionEditor";
import CompletionStem from "./CompletionStem";
import { PlusOutlined, CloseOutlined } from "@ant-design/icons";
import {
  NUM_TO_WORD_MAP,
  QUESTION_FILE_ACCEPT,
} from "@/common/constants/punchClock/punchClock";
import { defineOptionInfo } from "./model";
import UploadingProgress from "./UploadingProgress";
import XMAudio from "./XMAudio";
import XMRecord from "./XMRecord";
import ScanFileModal from "@/modules/resource-disk/modal/ScanFileModal";

class NewQuestionTab extends Component {
  constructor(props) {
    super(props);
    const { questionInfo = {} } = props;
    const {
      questionStemList,
      optionList,
      questionAnswerDescList,
      showBox,
    } = questionInfo;
    this.state = {
      stemContent: JSON.parse(JSON.stringify(questionStemList)), // 题干内容
      chooseOptions: JSON.parse(JSON.stringify(optionList)), // 单选多选不定项-选项列表
      questionAnswerDesc: JSON.parse(JSON.stringify(questionAnswerDescList)), // 答案解析
      accept: QUESTION_FILE_ACCEPT["PICTURE"], // 上传媒体类型
      fileType: "PICTURE", // 媒体枚举
      showRecord: false, // 录音弹窗
      showBox: showBox,
      completionOptions: [],
      blanksList: [], // 填空列表
      judgeOptions: [
        {
          // 判断-选项列表
          label: "正确",
          value: true,
          isCorrectAnswer: null,
        },
        {
          label: "错误",
          value: false,
          isCorrectAnswer: null,
        },
      ],
    };
    this.uploadInput = React.createRef();
    this.markKey = window.random_string(16);
  }

  componentDidMount() {
    const { chooseOptions } = this.state;
    if (chooseOptions.length === 0) {
      // 选择题（单选 多选 不定项）-插入4条默认选项
      for (var i = 0; i < 4; i++) {
        this.handleAddOption();
        this.setState({ [`optionsValidate_${i}`]: "success" });
        this.setState({ [`optionsText_${i}`]: "" });
      }
    }
    this.props.onRef(this);
  }

  handleLogger = (en, cn) => {
    const { onLogger } = this.props;
    onLogger && onLogger(en, cn);
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    // 控制录音组件展示
    if (nextProps.showBox && !prevState.showBox) {
      return {
        showRecord: false,
        showBox: nextProps.showBox,
      };
    }
    return {
      showBox: nextProps.showBox,
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      JSON.stringify(nextProps) !== JSON.stringify(this.props) ||
      JSON.stringify(nextState) !== JSON.stringify(this.state)
    );
  }

  _onSetState = (params = {}) => {
    this.setState({ ...params, updateKey: window.random_string(16) }, () => {
      this.props.onSetState({
        questionStemList: JSON.parse(JSON.stringify(this.state.stemContent)),
        optionList: JSON.parse(JSON.stringify(this.state.chooseOptions)),
        questionAnswerDescList: JSON.parse(
          JSON.stringify(this.state.questionAnswerDesc)
        ),
      });
    });
  };

  // 保存校验
  checkInput = () => {
    let validateError = 0;
    // 题干校验
    const stemContent = _.find(
      this.state.stemContent,
      (contentItem) => contentItem.type === "RICH_TEXT"
    );
    const stem = stemContent.content.replace(/<[^>]+>/g, "");
    if (stem.length === 0) {
      this.setState({ stemValidate: "error" });
      this.setState({ stemText: "请输入题干" });
      validateError++;
    } else {
      this.setState({ stemValidate: "success" });
      this.setState({ stemText: "" });
    }

    // 选项校验
    let optionUnChecked = 0;
    const { chooseOptions, judgeOptions } = this.state;
    const { questionTypeKey } = this.props;
    if (questionTypeKey === "JUDGE") {
      optionUnChecked = judgeOptions.filter(
        (item) => item.isCorrectAnswer === null
      ).length;
      if (optionUnChecked === judgeOptions.length) {
        this.setState({ radioValidate: "error" });
        this.setState({ radioText: "请选择正确答案" });
        validateError++;
      } else {
        this.setState({ radioValidate: "success" });
        this.setState({ radioText: "" });
      }
    } else {
      chooseOptions.forEach((item, index) => {
        const optionContent = item.questionOptionContentList;
        optionUnChecked = item.isCorrectAnswer
          ? optionUnChecked
          : optionUnChecked + 1;
        if (
          optionContent.length === 1 &&
          optionContent[0].type === "RICH_TEXT" &&
          optionContent[0].content.length === 0
        ) {
          this.setState({ [`optionsValidate_${index}`]: "error" });
          this.setState({ [`optionsText_${index}`]: "请输入选项" });
          validateError++;
        } else {
          this.setState({ [`optionsValidate_${index}`]: "success" });
          this.setState({ [`optionsText_${index}`]: "" });
        }
      });
      if (optionUnChecked === chooseOptions.length) {
        this.setState({ radioValidate: "error" });
        this.setState({ radioText: "请选择正确答案" });
        validateError++;
      } else {
        this.setState({ radioValidate: "success" });
        this.setState({ radioText: "" });
      }
      if (
        this.props.questionTypeKey === "MULTI_CHOICE" &&
        this.state.chooseOptions.length - optionUnChecked === 1
      ) {
        this.setState({ radioValidate: "error" });
        this.setState({ radioText: "最少选两个" });
        validateError++;
      }
    }
    return validateError;
  };

  /**
   * 预览
   *
   * @memberof QuestionInputItem
   */
  handleScanFile = (scanFileType, scanFileAddress) => {
    this.setState({
      showScanFile: true,
      scanFileAddress,
      scanFileType,
    });
  };

  /**
   * 添加选项
   *
   * @memberof QuestionInputItem
   */
  handleAddOption = (content) => {
    const { chooseOptions } = this.state;
    if (chooseOptions.length >= 20) {
      message.warning("最多添加20个选项");
    } else {
      chooseOptions.push(defineOptionInfo(content));
      this._onSetState();
    }
  };


  /**
   * 删除选项
   *
   * @memberof QuestionInputItem
   */
   handleDelOption = (optionIndex) => {
    const { chooseOptions } = this.state;
    this.handleLogger("delete_option", "删除选项");
    if (chooseOptions.length < 3) {
      message.warning("至少保留2个选项");
    } else {
      chooseOptions.splice(optionIndex, 1);
      this._onSetState();
    }
  };

  /**
   * 移动选项
   *
   * @memberof QuestionInputItem
   */
  handleMoveOption = (optionIndex, moveLength) => {
    const { chooseOptions } = this.state;
    const optionItem = chooseOptions.splice(optionIndex + moveLength, 1);
    this.handleLogger("sort_option", "选项排序");
    chooseOptions.splice(optionIndex, 0, optionItem[0]);
    this._onSetState();
  };
  /**
   * 选择上传文件类型
   *
   * @memberof QuestionInputItem
   */
  handleChangeMedia = (key, uploadItemTarget, inputType) => {
    const { mediaFirstType } = this.state;
    const mediaArr = _.filter(uploadItemTarget, (mediaItem) => {
      return mediaItem.type !== "RICH_TEXT";
    });
    if (mediaArr.length === 0) {
      this.setState({ mediaFirstType: key });
    }
    if (mediaArr.length > 0 && key !== mediaFirstType) {
      return message.warning("只能添加1种类型的多媒体文件");
    }
    switch (inputType) {
      case "stem":
        if (mediaFirstType === "PICTURE" && mediaArr.length > 8) {
          return message.warning("只能添加9张图片");
        }
        if (mediaFirstType === "VOICE" && mediaArr.length > 2) {
          return message.warning("只能添加3个音频");
        }
        if (mediaFirstType === "RECORD" && mediaArr.length > 2) {
          return message.warning("只能添加3个录音");
        }
        break;
      case "options":
        if (mediaArr.length > 0) {
          return message.warning("只能添加1个多媒体文件");
        }
        break;
      case "analysis":
        if (mediaFirstType === "PICTURE" && mediaArr.length > 8) {
          return message.warning("只能添加9张图片");
        }
        if (mediaFirstType === "VOICE" && mediaArr.length > 2) {
          return message.warning("只能添加3个音频");
        }
        if (mediaFirstType === "RECORD" && mediaArr.length > 2) {
          return message.warning("只能添加3个录音");
        }
        if (mediaFirstType === "VIDEO" && mediaArr.length > 2) {
          return message.warning("只能添加3个视频");
        }
        break;
      default:
        break;
    }

    this.setState(
      {
        uploadItemTarget,
      },
      () => {
        QUESTION_FILE_ACCEPT[key] &&
          this.setState(
            {
              accept: QUESTION_FILE_ACCEPT[key],
              fileType: key,
            },
            () => {
              this.uploadInput.current.value = "";
              this.uploadInput.current.click();
            }
          );

        // 录音
        if (key === "RECORD") {
          this.setState({
            showRecord: true,
          });
        }
      }
    );
  };

  async uploadFile(event) {
    const { fileType, uploadItemTarget } = this.state;
    const mediaFile = event.target.files[0];
    if (!mediaFile) return;
    if (fileType === "VOICE") {
      if (!QUESTION_FILE_ACCEPT.VOICE.split(",").includes(mediaFile.type)) {
        message.warning("文件格式不正确");
        return;
      }
      if (mediaFile.size > 30 * 1024 * 1024) {
        Modal.warning({
          title: "音频过大",
          content: "音频大小超过30M，请压缩后上传",
        });
        return;
      }
    }

    if (fileType === "PICTURE") {
      if (!QUESTION_FILE_ACCEPT.PICTURE.split(",").includes(mediaFile.type)) {
        message.warning("文件格式不正确");
        return;
      }
      if (mediaFile.size > 8 * 1024 * 1024) {
        Modal.warning({
          title: "图片过大",
          content: "图片大小超过8M，请压缩后上传",
        });
        return;
      }
    }

    if (fileType === "VIDEO") {
      if (!QUESTION_FILE_ACCEPT.VIDEO.split(",").includes(mediaFile.type)) {
        message.warning("文件格式不正确");
        return;
      }
      if (mediaFile.size > 1024 * 1024 * 1024) {
        Modal.warning({
          title: "视频过大",
          content: "视频大小超过1G，请压缩后上传",
        });
        return;
      }
    }
    const originArr = mediaFile.name.split(".");
    const originType = originArr[originArr.length - 1];

    const uploadObj = {
      contentType: "QUESTION_STEM",
      type: fileType,
      contentName: `${window.random_string(16)}.${originType}`, // 文件名
      fileType: originType, // 文件后缀
      mediaFile, // url
    };
    if (["VIDEO", "VOICE"].includes(fileType)) {
      try {
        await new Promise((resolve) => {
          const fileurl = URL.createObjectURL(mediaFile);
          const audioElement = new Audio(fileurl);
          audioElement.addEventListener("loadedmetadata", (_event) => {
            const duration = audioElement.duration;
            uploadObj.size = Math.ceil(duration) * 1000;
            resolve();
          });
        });
      } catch (error) {
        console.log(error);
      }
    } else if (fileType === "PICTURE") {
      uploadObj.size = mediaFile.size;
    }
    uploadItemTarget.push(uploadObj);
    this.setState({}, () => {
      this.handleReupload(uploadObj);
      this.uploadInput.current.value = "";
    });
  }

  changeBlankCount = (data) => {
    data.map((item) => {
      item.answerTagList = [];
      item.inputVisible = false;
      item.errorHold = false;
      item.editInput = false;
      return item;
    });
    this.setState({ blanksList: data });
  };

  addAnswerTag = (optionItem) => {
    const _blanksList = this.state.blanksList;
    _blanksList.forEach((item) => {
      if (item.id === optionItem.id) {
        item.inputVisible = true;
      }
    });
    this.setState({ blanksList: _blanksList });
  };

  handleInputConfirm = (optionItem, val) => {
    const _blanksList = this.state.blanksList;
    _blanksList.forEach((item) => {
      if (item.id === optionItem.id) {
        if (val) {
          optionItem.answerTagList.push(val);
          optionItem.inputVisible = false;
        } else {
          optionItem.errorHold = true;
        }
      }
    });
    this.setState({ blanksList: _blanksList });
  };

  handleInputClose = (optionItem, removedTag) => {
    const _blanksList = this.state.blanksList;
    _blanksList.forEach((item) => {
      if (item.id === optionItem.id) {
        optionItem = optionItem.answerTagList.filter(
          (tag) => tag !== removedTag
        );
      }
    });
    this.setState({ blanksList: _blanksList });
  };

  handleInputEdit = (optionItem, index) => {
    const _blanksList = this.state.blanksList;
    _blanksList.forEach((item) => {
      if (item.id === optionItem.id) {
        item.answerTagList.map();
      }
    });
    this.setState({ blanksList: _blanksList });
  };
  
  renderCompletionAnswer = (optionItem, optionIndex) => {
    return (
      <div className="completion-answer-box">
        <span className="completion-answer-label">
          {optionItem.innerHTML}
          {optionIndex + 1}.
        </span>
        <div className="completion-answer-content">
          {optionItem.answerTagList.map((tag, index) => {
            return optionItem.editInput ? (
              <Input
                placeholder={optionItem.errorHold ? "请输入" : ""}
                style={{
                  border: optionItem.errorHold && "1px solid #FF4F4F",
                }}
                value={tag}
                size="small"
                suffix={<CloseOutlined style={{ color: "#999999" }} />}
                onBlur={(e) =>
                  this.handleInputConfirm(optionItem, e.target.value, index)
                }
                onPressEnter={(e) =>
                  this.handleInputConfirm(optionItem, e.target.value, index)
                }
              />
            ) : (
              <Tag
                className="edit-tag"
                closable
                onClose={() => this.handleInputClose(optionItem, tag)}
                onDoubleClick={(e) => {
                  this.handleInputEdit(optionItem, index);
                  // e.preventDefault();
                }}
              >
                {tag}
              </Tag>
            );
          })}
          {optionItem.inputVisible && (
            <Input
              placeholder={optionItem.errorHold && "请输入"}
              style={{
                border: optionItem.errorHold && "1px solid #FF4F4F",
              }}
              size="small"
              suffix={<CloseOutlined style={{ color: "#999999" }} />}
              onBlur={(e) =>
                this.handleInputConfirm(optionItem, e.target.value, "save")
              }
              onPressEnter={(e) =>
                this.handleInputConfirm(optionItem, e.target.value, "save")
              }
            />
          )}
          <Tag
            style={{ color: "#5289FA", fontSize: 14 }}
            onClick={() => {
              this.addAnswerTag(optionItem);
            }}
          >
            <PlusOutlined /> 新增答案
          </Tag>
        </div>
      </div>
    );
  };

  /**
   * 渲染输入内容
   *
   * @memberof QuestionInputItem
   */
  renderContent = (
    contentList,
    placehold,
    mediaBtn,
    inputType,
    validateStatus
  ) => {
    const isCompletion = this.props.questionTypeKey === "COMPLETION";
    const editorContent = _.find(
      contentList,
      (contentItem) => contentItem.type === "RICH_TEXT"
    );
    return (
      <React.Fragment>
        <div>
          {isCompletion && inputType === "stem" ? (
            <CompletionStem
              placehold={placehold}
              validateStatus={validateStatus}
              detail={contentList}
              mediaBtn={mediaBtn}
              changeBlankCount={this.changeBlankCount.bind(this)}
              onUploadMedia={(key) => {
                this.handleChangeMedia(key, contentList, inputType);
              }}
            />
          ) : (
            <QuestionEditor
              markKey={this.markKey}
              placehold={placehold}
              validateStatus={validateStatus}
              detailInfo={contentList}
              mediaBtn={mediaBtn}
              bindChangeContent={(cb, textElemId) => {
                this.setState({ textElemId });
                editorContent.handleChangeContent = cb;
              }}
              onChange={(content, textLength) => {
                editorContent.content = content;
                editorContent.textLength = textLength;
                this._onSetState();
              }}
              onUploadMedia={(key) => {
                this.handleChangeMedia(key, contentList, inputType);
              }}
            />
          )}
        </div>
        {_.map(contentList, (contentItem, index) => {
          const { type, content, status } = contentItem;
          let dom = "";
          if (["init", "fail"].includes(status)) {
            return (
              <div className="mt12" key={index}>
                <UploadingProgress
                  fileDesc={contentItem}
                  canCancelUpload
                  onReupload={() => this.handleReupload(contentItem)}
                  onAbort={() => this.handleAbort(contentItem, index)}
                />
              </div>
            );
          }
          switch (type) {
            case "PICTURE":
              dom = (
                <div className="picture-box">
                  <img
                    className="img-box"
                    src={content}
                    onClick={() => this.handleScanFile("JPG", content)}
                  />
                </div>
              );
              break;
            case "VOICE":
              dom = (
                <div className="audio-box">
                  <XMAudio
                    forbidParse
                    url={contentItem.content}
                    getDuration={(size) => {
                      contentItem.size = size;
                      this.setState({});
                    }}
                    index={index}
                    size={contentItem.size || 1000}
                  />
                </div>
              );
              break;
            case "VIDEO":
              dom = (
                <div
                  className="video-box"
                  onClick={() => this.handleScanFile("MP4", content)}
                >
                  <img
                    className="video-box_content"
                    src={`${content}?x-oss-process=video/snapshot,t_0,m_fast`}
                  />
                  <img
                    className="video-box_btn"
                    src="https://image.xiaomaiketang.com/xm/r5H8cYm4ch.png"
                  />
                </div>
              );
              break;
          }
          return dom ? (
            <div
              className="question-item_question-content"
              style={{
                display: ["PICTURE", "VIDEO"].includes(type)
                  ? "inline-flex"
                  : "flex",
              }}
              key={index}
            >
              {dom}
              <span
                className={
                  ["PICTURE", "VIDEO"].includes(type)
                    ? "icon_arrow iconfont"
                    : "icon_sider iconfont"
                }
                onClick={() => {
                  contentList.splice(index, 1);
                  this._onSetState();
                }}
              >
                &#xe717;
              </span>
            </div>
          ) : null;
        })}
      </React.Fragment>
    );
  };

  /**
   * 重新上传
   *
   * @memberof QuestionInputItem
   */
  handleReupload = (uploadItem) => {
    uploadItem.status = "init";
    Upload.uploadToOSSEvent(
      uploadItem.mediaFile,
      uploadItem.contentName,
      (url, xhr) => {
        uploadItem.content = url;
        uploadItem.xhr = xhr;
      },
      (event) => {
        var percent = Math.floor((event.loaded / event.total) * 100);
        uploadItem.progress = percent;
        this._onSetState();
      },
      () => {
        uploadItem.status = "success";
        delete uploadItem.xhr;
        delete uploadItem.progress;
        delete uploadItem.mediaFile;
        this._onSetState();
      },
      () => {
        uploadItem.status = "fail";
        uploadItem.progress = 0;
        delete uploadItem.xhr;
        this._onSetState();
      }
    );
  };

  /**
   * 取消上传
   *
   * @memberof QuestionInputItem
   */
  handleAbort = (uploadItem, index) => {
    const { uploadItemTarget } = this.state;
    const { xhr } = uploadItem;
    xhr && xhr.abort && xhr.abort();
    uploadItemTarget.splice(index, 1);
    this._onSetState();
  };

  /**
   * 完成语音录制
   *
   * @memberof QuestionInputItem
   */
  handleFinishRecord = (mp3URL, duration) => {
    const { uploadItemTarget } = this.state;
    uploadItemTarget.push({
      contentType: "VOICE",
      type: "VOICE",
      content: mp3URL,
      size: duration,
    });
    this._onSetState({ showRecord: false });
  };

  /**
   * 取消录制
   *
   * @memberof QuestionInputItem
   */
  handleCancelRecord = () => {
    this.setState({ showRecord: false });
  };

  render() {
    const {
      stemContent,
      chooseOptions,
      judgeOptions,
      questionAnswerDesc,
      accept,
      showRecord,
      showScanFile,
      scanFileType,
      scanFileAddress,
      blanksList,
    } = this.state;
    const { stemValidate, stemText, radioValidate, radioText } = this.state;
    const isJudge = this.props.questionTypeKey === "JUDGE";
    const isCompletion = this.props.questionTypeKey === "COMPLETION";
    const placehold = isCompletion ? (
      <span>
        示例：党章规定，凡事有
        <span className="fill-line">&nbsp;&nbsp;填空1&nbsp;&nbsp;</span>
        人以上的
        <span className="fill-line">&nbsp;&nbsp;填空2&nbsp;&nbsp;</span>
        ，都应该成立党的基层组织
      </span>
    ) : (
      "必填（1000字以内，可粘贴小图）"
    );
    return (
      <div className="question-input-item_wrapper">
        {/* 题干 */}
        <Form>
          <Form.Item
            name="stemContent"
            label="题干"
            required
            validateStatus={stemValidate}
            help={stemText}
          >
            {this.renderContent(
              stemContent,
              placehold,
              ["VOICE", "RECORD", "PICTURE"],
              "stem",
              stemValidate
            )}
          </Form.Item>
          {isCompletion ? (
            <Form.Item
              name="answer"
              label={
                <span>
                  答案{" "}
                  {blanksList.length === 0 && (
                    <span
                      className="icon iconfont"
                      style={{ color: "#BFBFBF", fontSize: 14 }}
                    >
                      &#xe7c4;
                    </span>
                  )}
                </span>
              }
              required
              className="question-answer_control"
            >
              {blanksList.length === 0 ? (
                <span className="answer-tip">请在题干中插入答案占位符</span>
              ) : (
                _.map(blanksList, (item, index) => {
                  return this.renderCompletionAnswer(item, index);
                })
              )}
            </Form.Item>
          ) : (
            <Form.Item
              name="options"
              label="选项"
              required
              className="question-option_control"
            >
              <div
                className="question-item_options__list"
                data-label="正确答案"
              >
                {isJudge
                  ? _.map(judgeOptions, (optionItem, optionIndex) => {
                      return (
                        <div className="question-item_options__content">
                          <div className="question-item_options__setting">
                            <Form.Item
                              validateStatus={radioValidate}
                              help={
                                optionIndex === judgeOptions.length - 1
                                  ? radioText
                                  : ""
                              }
                            >
                              {/* 判断 */}
                              <Radio
                                checked={optionItem.isCorrectAnswer === 1}
                                onClick={() => {
                                  _.each(judgeOptions, (item) => {
                                    item.isCorrectAnswer = 0;
                                  });
                                  optionItem.isCorrectAnswer = 1;
                                  this._onSetState();
                                }}
                              />
                            </Form.Item>
                          </div>
                          <div className="question-item_options__sort mr12">
                            {NUM_TO_WORD_MAP[optionIndex]}.
                          </div>
                          <div className="question-item_options__input">
                            {optionItem.label}
                          </div>
                        </div>
                      );
                    })
                  : _.map(chooseOptions, (optionItem, optionIndex) => {
                      const {
                        questionOptionContentList,
                        isCorrectAnswer,
                      } = optionItem;
                      optionItem.optionSort = optionIndex;
                      const mediaBtn = ["VOICE", "RECORD", "PICTURE"];
                      const placeHold =
                        "必填（1000字以内，可粘贴小图；可以不输入文字，只添加音频或图片）";
                      return (
                        <div className="question-item_options__content" key={optionIndex}>
                          <div className="question-item_options__setting">
                            <Form.Item
                              validateStatus={radioValidate}
                              help={
                                optionIndex === chooseOptions.length - 1
                                  ? radioText
                                  : ""
                              }
                            >
                              {/* 单选 */}
                              {this.props.questionTypeKey ===
                                "SINGLE_CHOICE" && (
                                <Radio
                                  checked={isCorrectAnswer}
                                  onClick={() => {
                                    _.each(chooseOptions, (o) => {
                                      o.isCorrectAnswer = 0;
                                    });
                                    optionItem.isCorrectAnswer = 1;
                                    this._onSetState();
                                  }}
                                />
                              )}
                              {/* 多选 or 不定项 */}
                              {["INDEFINITE_SELECT", "MULTI_CHOICE"].includes(
                                this.props.questionTypeKey
                              ) && (
                                <Checkbox
                                  checked={isCorrectAnswer === 1}
                                  onChange={(e) => {
                                    const checked = e.target.checked ? 1 : 0;
                                    optionItem.isCorrectAnswer = checked;
                                    this._onSetState();
                                  }}
                                />
                              )}
                            </Form.Item>
                          </div>
                          <div className="question-item_options__sort mr12">
                            {NUM_TO_WORD_MAP[optionIndex]}.
                          </div>
                          <div className="question-item_options__input">
                            <Form.Item
                              validateStatus={
                                this.state[`optionsValidate_${optionIndex}`]
                              }
                              help={this.state[`optionsText_${optionIndex}`]}
                            >
                              {this.renderContent(
                                questionOptionContentList,
                                placeHold,
                                mediaBtn,
                                "options",
                                this.state[`optionsValidate_${optionIndex}`]
                              )}
                            </Form.Item>
                          </div>
                          <div className="question-item_options__extra">
                            <React.Fragment>
                              <span
                                className="option-operate_item__icon icon iconfont"
                                onClick={() =>
                                  this.handleDelOption(optionIndex)
                                }
                              >
                                &#xe81a;
                              </span>
                              {optionIndex > 0 && (
                                <span
                                  className="option-operate_item__icon icon iconfont"
                                  onClick={() =>
                                    this.handleMoveOption(optionIndex, 1)
                                  }
                                >
                                  &#xe74a;
                                </span>
                              )}
                              {optionIndex < chooseOptions.length - 1 && (
                                <span
                                  className="option-operate_item__icon icon iconfont"
                                  style={{
                                    transform: "rotate(180deg)",
                                    display: "inline-block",
                                  }}
                                  onClick={() =>
                                    this.handleMoveOption(optionIndex, -1)
                                  }
                                >
                                  &#xe74a;
                                </span>
                              )}
                            </React.Fragment>
                          </div>
                        </div>
                      );
                    })}
                {!isJudge && (
                  <div
                    className="question-item_options__add"
                    onClick={() => {
                      this.handleAddOption();
                    }}
                  >
                    + 增加选项
                  </div>
                )}
              </div>
            </Form.Item>
          )}
          <Form.Item name="analysis" label="答案解析">
            <div className="question-item_analysis__content">
              {this.renderContent(
                questionAnswerDesc,
                "1000字以内，可粘贴小图",
                ["VOICE", "RECORD", "PICTURE", "VIDEO"],
                "analysis"
              )}
            </div>
          </Form.Item>
        </Form>
        <input
          type="file"
          accept={accept}
          ref={this.uploadInput}
          style={{ display: "none" }}
          onChange={(event) => {
            this.uploadFile(event);
          }}
        />
        <div style={{ zIndex: 9999, position: "relative" }}>
          <XMRecord
            maxTime={600}
            visible={showRecord}
            onFinish={this.handleFinishRecord}
            onCancel={this.handleCancelRecord}
          />
        </div>
        {showScanFile && (
          <ScanFileModal
            modalTitle={scanFileType === "MP4" ? "视频播放" : "查看大图"}
            fileType={scanFileType}
            item={{
              ossAddress: scanFileAddress,
            }}
            close={() => {
              this.setState({ showScanFile: false });
            }}
          />
        )}
      </div>
    );
  }
}

export default NewQuestionTab;
