/*
 * @Author: yuananting
 * @Date: 2021-03-27 11:15:03
 * @LastEditors: yuananting
 * @LastEditTime: 2021-06-01 17:28:21
 * @Description: 助学工具-试卷-预览试卷
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import { Modal, ConfigProvider, Empty } from "antd";
import User from "@/common/js/user";
import AidToolService from "@/domains/aid-tool-domain/AidToolService";
import "./PreviewPaperModal.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";
import previewEmpty from '../../../lottie/previewEmpty/data.json';
const questionTypeList = {
  SINGLE_CHOICE: "单选题",
  MULTI_CHOICE: "多选题",
  JUDGE: "判断题",
  GAP_FILLING: "填空题",
  INDEFINITE_CHOICE: "不定项选择题",
};

class PreviewPaperModal extends Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      paperInfo: {},
    };
  }

  componentDidMount() {
    const { previewPage, paperInfo } = this.props;
    if (previewPage === "paper-list") {
      this.queryPaperDetail();
    } else if (previewPage === "paper-operate") {
      this.setState({ paperInfo });
    }
  }

  // 题目预览
  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 = "";
    if (textContent.length > 0) {
      content = textContent[0].content;
      if (questionType === "GAP_FILLING") {
        content = content.replace(
          /_/g,
          `<input
          class="add-fill-line"
          disabled
          correctAnswerList=""
          id=${window.random_string(16)}
          value="  "
        />`
        );
        content = content.replace(/value="填空"/g, "value='  '");
      }
    }

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

    return (
      <div className="stem-line-item">
        <div className="text">
          <div className="question-tip">
            <span className="question-sort">第{questionIndex + 1}题</span>
            <span className="question-type-score">
              ({questionTypeList[questionType]} | {score}分)
            </span>
          </div>
          {textDom}
        </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") {
      {
        return (
          <div className="answer-line-item">
            <div style={{ marginBottom: 8 }}>正确答案: </div>
            {_.map(gapFillingAnswerList, (gapItem, gapIndex) => {
              const { correctAnswerList } = gapItem;
              return (
                <div className="gap-list">
                  <span>[填空{gapIndex + 1}] </span>
                  {_.map(correctAnswerList, (answerItem, answerIndex) => {
                    return (
                      <span>
                        {answerItem}
                        {answerIndex < correctAnswerList.length - 1 && (
                          <span>、</span>
                        )}
                      </span>
                    );
                  })}
                  <span>; </span>
                </div>
              );
            })}
          </div>
        );
      }
    } else {
      const correctAnswerOption = _.filter(
        optionList,
        (item) => item.isCorrectAnswer === 1
      );
      const correctOptionSort = correctAnswerOption.map((item) => {
        return NUM_TO_WORD_MAP[item.optionSort];
      });
      return (
        <div className="answer-line-item">
          <div style={{ marginBottom: 8 }}>正确答案: </div>
          <span style={{ lineHeight: "20px", color: "#666666" }}>
            {correctOptionSort.length > 0 && 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>
    );
  };

  // 自定义空状态
  customizeRenderEmpty = () => {
    const defaultOptions = {
      loop: true,
      autoplay: true,
      animationData: previewEmpty,
      rendererSettings: {
        preserveAspectRatio: 'xMidYMid slice'
      }
    }
    return (
      <Empty
        image={<div style={{ marginTop: 24 }}>
        <Lottie
          options={defaultOptions}
          height={150}
          width={150}
          isStopped={false}
          isPaused={false}
        />
      </div>}
        imageStyle={{
          height: 100,
        }}
        description={"暂无内容"}
      ></Empty>
    );
  };

  render() {
    const {
      paperInfo,
      showScanFile,
      scanFileType,
      scanFileAddress,
    } = 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}
        >
          {paperName && <div className="paper-title">{paperName.length > 40 ? paperName.substring(0, 40) : paperName}</div>}
          {questionList && questionList.length > 0 ? (
            <div className="question-list-box">
              {_.map(questionList, (questionItem, questionIndex) => {
                const {
                  questionStemList,
                  optionList,
                  gapFillingAnswerList,
                  questionType,
                  score,
                } = questionItem;
                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>
          ) : (
            this.customizeRenderEmpty()
          )}
        </Modal>
        {showScanFile && (
          <ScanFileModal
            fileType={scanFileType}
            item={{
              ossAddress: scanFileAddress,
            }}
            close={() => {
              this.setState({ showScanFile: false });
            }}
          />
        )}
      </div>
    );
  }
}
export default PreviewPaperModal;
