/*
 * @Author: yuananting
 * @Date: 2021-03-27 11:15:03
 * @LastEditors: yuananting
 * @LastEditTime: 2021-04-02 12:42:42
 * @Description: 助学工具-试卷-预览试卷
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import { Modal } from "antd";
import User from "@/common/js/user";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";
import "./PaperPreviewModal.less";
import ScanFileModal from "@/modules/resource-disk/modal/ScanFileModal";
import _ from "underscore";
import XMAudio from "../../components/XMAudio";
import { NUM_TO_WORD_MAP } from "@/common/constants/punchClock/punchClock";
const questionTypeList = {
  SINGLE_CHOICE: "单选题",
  MULTI_CHOICE: "多选题",
  JUDGE: "判断题",
  GAP_FILLING: "填空题",
  INDEFINITE_CHOICE: "不定项选择题",
};

class PaperPreviewModal extends Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      paperInfo: {
        paperName: null,
        questionList: [],
      },
    };
  }

  componentDidMount() {
    this.queryPaperDetail();
  }

  // 题目预览
  queryPaperDetail = () => {
    let query = {
      categoryId: this.props.categoryId,
      paperId: this.props.paperId,
      source: 0,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
    };
    AidToolService.viewPaper(query).then((res) => {
      const { result = [] } = res;
      this.setState({ paperInfo: result });
    });
  };

  // 查看图片或视频
  handleScanFile = (scanFileType, scanFileAddress) => {
    this.setState({
      showScanFile: true,
      scanFileAddress,
      scanFileType,
    });
  };

  renderStem = (questionStemList, questionType, score, questionIndex) => {
    const textContent = _.filter(questionStemList, (item) => {
      return item.type == "RICH_TEXT";
    });

    const mediaContent = _.filter(questionStemList, (item) => {
      return item.type !== "RICH_TEXT";
    });

    let content = textContent.length > 0 && textContent[0].content;
    if (questionType === "GAP_FILLING") {
      content = content.replace(
        /_/g,
        `<input
          class="add-fill-line"
          disabled
          correctAnswerList=""
          id=${window.random_string(16)}
          value="填空"
        />`
      );
    }

    let textDom = (
      <span
        key={0}
        className="input-box"
        dangerouslySetInnerHTML={{
          __html: content,
        }}
      />
    );

    return (
      <div className="stem-line__item">
        <div className="text">
          <span>{questionIndex + 1}.</span>
          <span>【{questionTypeList[questionType]}】</span>
          {textDom}
          <span>（{score}分）</span>
        </div>
        {this.renderMediaContent(mediaContent)}
      </div>
    );
  };

  renderOption = (optionItem, questionType) => {
    const { questionOptionContentList, optionSort } = optionItem;
    const textContent = _.filter(questionOptionContentList, (item) => {
      return item.type == "RICH_TEXT";
    });

    const mediaContent = _.filter(questionOptionContentList, (item) => {
      return item.type !== "RICH_TEXT";
    });

    let content = textContent.length > 0 && textContent[0].content;
    if (questionType !== "GAP_FILLING") {
      let textDom = (
        <span
          key={0}
          className="input-box"
          dangerouslySetInnerHTML={{
            __html: content,
          }}
        />
      );
      return (
        <div className="option-line__item">
          <div className="text">
            {NUM_TO_WORD_MAP[optionSort]}. {textDom}
          </div>
          {mediaContent.length > 0 && this.renderMediaContent(mediaContent)}
        </div>
      );
    }
  };

  renderAnswer = (optionList, gapFillingAnswerList, questionType) => {
    if (questionType === "GAP_FILLING") {
      {
        _.map(gapFillingAnswerList, (gapItem, gapIndex) => {
          console.log("gapFillingAnswerList", gapFillingAnswerList)
          const { correctAnswerList } = gapItem;
          return (
            <div>
              <span>【填空{gapIndex + 1}】</span>
              {_.map(correctAnswerList, (answerItem) => {
                return <span>{answerItem}</span>;
              })}
            </div>
          );
        });
      }
      // this.renderGapFillingAnswer(gapFillingAnswerList)
    } else {
      const correctAnswerOption = _.filter(
        optionList,
        (item) => item.isCorrectAnswer === 1
      );
      const correctOptionSort =
        correctAnswerOption.length > 0 &&
        correctAnswerOption.map((item) => {
          return NUM_TO_WORD_MAP[item.optionSort];
        });
      return (
        <div className="answer-line__item">
          <span>正确答案</span>
          <span>【{correctOptionSort.join("、")}】</span>
        </div>
      );
    }
  };

  renderMediaContent = (mediaContent) => {
    return (
      <div className="media">
        {_.map(mediaContent, (mediaItem, mediaIndex) => {
          let dom = "";
          let { type, content, size } = mediaItem;
          switch (type) {
            case "PICTURE":
              dom = (
                <div key={mediaIndex + 1} className="picture-box">
                  <img
                    src={content}
                    onClick={() => this.handleScanFile("JPG", content)}
                  />
                </div>
              );
              break;
            case "VOICE":
              dom = (
                <div key={mediaIndex + 1} className="voice-box">
                  <XMAudio
                    forbidParse
                    url={content}
                    getDuration={(durationSize) => {
                      size = durationSize;
                      this.setState({});
                    }}
                    index={mediaIndex + 1}
                    size={size || 1000}
                  />
                </div>
              );
              break;
            case "AUDIO":
              dom = (
                <div key={mediaIndex} className="voice-box">
                  <XMAudio
                    forbidParse
                    url={content}
                    getDuration={(durationSize) => {
                      size = durationSize;
                      this.setState({});
                    }}
                    index={mediaIndex}
                    size={size || 1000}
                  />
                </div>
              );
              break;
          }
          return dom;
        })}
      </div>
    );
  };

  render() {
    const { paperInfo } = this.state;
    const { paperName, questionList } = paperInfo;
    return (
      <div>
        <Modal
          className="paper-preview-modal"
          visible={true}
          title="试卷预览"
          width={560}
          centered={true}
          footer={null}
          onCancel={this.props.close}
        >
          <h2 style={{ textAlign: "center" }}>{paperName}</h2>
          <div className="question-list-box">
            {questionList.map((questionItem, questionIndex) => {
              const {
                questionStemList,
                optionList,
                gapFillingAnswerList,
                questionType,
                score,
              } = questionItem;
              console.log(optionList);
              return (
                <div className="question-info-item">
                  {this.renderStem(
                    questionStemList,
                    questionType,
                    score,
                    questionIndex
                  )}
                  {_.map(optionList, (optionItem, optionIndex) => {
                    return this.renderOption(optionItem, questionType);
                  })}
                  {this.renderAnswer(
                    optionList,
                    gapFillingAnswerList,
                    questionType
                  )}
                </div>
              );
            })}
          </div>
        </Modal>
      </div>
    );
  }
}
export default PaperPreviewModal;
