/*
 * @Author: yuananting
 * @Date: 2021-04-08 15:50:52
 * @LastEditors: wufan
 * @LastEditTime: 2021-04-24 15:55:19
 * @Description: 助学工具-考试-答案详情
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect, useRef } from 'react';
import { Route, withRouter } from 'react-router-dom';
import User from '@/common/js/user';
import Service from '@/common/js/service';
import Lottie from 'lottie-web';
import './AnswerDescPage.less';
import { message } from 'antd';
import XMAudio from './XMAudio';
import ScanFileModal from '@/modules/prepare-lesson/modal/ScanFileModal';
const NUM_TO_WORD_MAP = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

function AnswerDescPage(props) {
  const examId = props.match.params.testId.replace(/\?.+/, '');
  const paperId = window.getParameterByName('paperId');
  const [customerId, setCustomerId] = useState('');
  const [examDetail, setExamDetail] = useState({
    examDesc: '',
    examDuration: 0,
    examEndTime: '',
    examName: '',
    examStartTime: '',
    paperId: 0,
    passRate: 0,
    passScore: 0,
    resultContent: '',
    resultShow: '',
    totalQuestionCount: 0,
    totalScore: 0,
    userCorrectQuestion: 0,
    userExamDuration: 0,
    userExamState: '',
    userScore: 0,
  });
  const [paperDetail, setPaperDetail] = useState({}); // 试卷详情
  const [userAnswerList, setUserAnswerList] = useState([]); // 用户当前答案列表
  const [allUserAnswerList, setAllUserAnswerList] = useState([]); // 用户所有答案列表
  const [errorUserAnswerList, setErrorUserAnswerList] = useState([]); // 用户错误答案列表

  const [questionList, setQuestionList] = useState([]); // 用户当前题目列表
  const [allQuestionList, setAllQuestionList] = useState([]); // 用户所有题目列表
  const [errorQuestionList, setErrorQuestionList] = useState([]); // 用户错误题目列表
  const [errorCount, setErrorCount] = useState(0);

  const [onlyError, setOnlyError] = useState(true); // 只显示错题
  const [activeIndex, setActiveIndex] = useState(0); // 当前答题索引
  const [activeOrderIndex, setActiveOrderIndex] = useState(0); // 当前答题序号
  const [isShowQuestionCard, setIsShowQuestionCard] = useState(false); // 答题卡是否展开
  const [isShowErrorPage, setIsShowErrorPage] = useState(false); // 是否展示异常提示页面

  // 是否打开预览文件弹框
  const [showScanFile, setShowScanFile] = useState(false);
  const [scanFileAddress, setScanFileAddress] = useState(false);
  const [scanFileType, setScanFileType] = useState(false);

  const questionTypeList = {
    SINGLE_CHOICE: '单选题',
    MULTI_CHOICE: '多选题',
    JUDGE: '判断题',
    GAP_FILLING: '填空题',
    INDEFINITE_CHOICE: '不定项选择题',
  };

  useEffect(() => {
    getPaperDetail();
    getExamDetail();
  }, []);
  useEffect(() => {
    Lottie.loadAnimation({
      path: 'https://image.xiaomaiketang.com/xm/AcQWnGATCM.json',
      name: 'test',
      renderer: 'svg',
      loop: true,
      autoplay: true,
      container: document.getElementById('lottie-box'),
    });
  }, []);
  // 获取考试详情
  function getExamDetail() {
    const params = {
      examId,
      source: 0,
      tenantId: User.getStoreId() || window.getParameterByName('id'),
      userId: props.userId,
    };
    Service.Hades('public/customerHades/queryUserExamResult', params, {
      reject: true,
    })
      .then((res) => {
        const data = { ...res.result };
        setExamDetail(data);
      })
      .catch((res) => {
        if (res.code === 'EXAM_IS_NOT_EXIST') {
          handleChangeShowErrorPage();
        } else {
          message.error(res.message);
        }
      });
  }

  // 获取试卷详情
  function getPaperDetail() {
    Service.Hades('public/customerHades/queryUserExamAnswer', {
      examId,
      paperId,
      readAnswer: true,
      source: 0,
      tenantId: User.getStoreId() || window.getParameterByName('id'),
      userId: props.userId,
    }).then((res) => {
      const { paperDetailVO, userExamAnswerVO } = res.result;
      const paperDetail = { ...paperDetailVO };
      const allUserAnswerList = [...userExamAnswerVO];
      let allQuestionList = [...paperDetail.questionList];
      allQuestionList = allQuestionList.map((item, index) => {
        item.orderIndex = index;
        return item;
      });

      const errorUserAnswerList = _.filter(allUserAnswerList, (item) => {
        return item.isCorrect === 0;
      });

      let errorQuestionList = [];
      let userAnswerMap = {};
      errorUserAnswerList.forEach((item) => {
        userAnswerMap[item.questionId] = true;
      });

      allQuestionList.forEach((item) => {
        if (userAnswerMap[item.questionId]) {
          errorQuestionList.push(item);
        }
      });
      setActiveOrderIndex(errorQuestionList.length > 0 ? errorQuestionList[0].orderIndex : 0);
      setPaperDetail(paperDetail);
      setAllUserAnswerList(allUserAnswerList);
      setErrorUserAnswerList(errorUserAnswerList);
      setErrorCount(errorUserAnswerList.length);
      setUserAnswerList(errorUserAnswerList);
      setAllQuestionList(allQuestionList);
      setErrorQuestionList(errorQuestionList);
      setQuestionList(errorQuestionList);
    });
  }

  function handleChangeShowErrorPage() {
    setIsShowErrorPage(true);
  }

  function handleChangeActiveIndex(isPre) {
    if (onlyError) {
      if (isPre && activeOrderIndex !== errorQuestionList[0].orderIndex) {
        setActiveOrderIndex(errorQuestionList[activeIndex - 1].orderIndex);
        setActiveIndex(activeIndex - 1);
      } else if (!isPre && activeOrderIndex !== errorQuestionList[errorCount - 1].orderIndex) {
        setActiveOrderIndex(errorQuestionList[activeIndex + 1].orderIndex);
        setActiveIndex(activeIndex + 1);
      }
    } else {
      if (isPre && activeOrderIndex !== 0) {
        setActiveOrderIndex(activeIndex - 1);
        setActiveIndex(activeIndex - 1);
      } else if (!isPre && activeOrderIndex !== questionList.length - 1) {
        setActiveOrderIndex(activeIndex + 1);
        setActiveIndex(activeIndex + 1);
      }
    }
  }

  function renderFooterText() {
    if (onlyError && errorCount > 0) {
      // 只看错题
      return (
        <div className='footer-btn'>
          <div className='pre-next'>
            <div
              className={`${activeOrderIndex === (errorQuestionList.length > 0 ? errorQuestionList[0].orderIndex : 0) ? 'disabled' : ''} pre`}
              onClick={() => handleChangeActiveIndex(true)}>
              <span className='icon iconfont'>&#xe79c;</span>
              <div className='text'>上一题</div>
            </div>
            <div
              className={`${activeOrderIndex === (errorQuestionList.length > 0 ? errorQuestionList[errorCount - 1].orderIndex : 0) ? 'disabled' : ''} next`}
              onClick={() => handleChangeActiveIndex(false)}>
              <div className='text'>下一题</div>
              <span className='icon iconfont'>&#xe79b;</span>
            </div>
          </div>
        </div>
      );
    } else if (!onlyError) {
      return (
        <div className='footer-btn'>
          <div className='pre-next'>
            <div className={`${activeOrderIndex === 0 ? 'disabled' : ''} pre`} onClick={() => handleChangeActiveIndex(true)}>
              <span className='icon iconfont'>&#xe79c;</span>
              <div className='text'>上一题</div>
            </div>
            <div className={`${activeOrderIndex === questionList.length - 1 ? 'disabled' : ''} next`} onClick={() => handleChangeActiveIndex(false)}>
              <div className='text'>下一题</div>
              <span className='icon iconfont'>&#xe79b;</span>
            </div>
          </div>
        </div>
      );
    }
  }

  function handleRenderQuestionItem() {
    return _.map(questionList, (questionItem, questionIndex) => {
      const { questionStemList, optionList, gapFillingAnswerList, questionAnswerDescList, questionType, score, questionId, orderIndex } = questionItem;
      return (
        <div className={`question-info-item`}>
          {renderStem(questionItem, questionStemList, questionType, score, orderIndex, questionId, gapFillingAnswerList)}
          {questionType !== 'GAP_FILLING' &&
            _.map(optionList, (optionItem, optionIndex) => {
              return renderOption(optionItem, optionIndex, questionId);
            })}
          {renderAnswerCompare(questionId, questionType, optionList, gapFillingAnswerList)}
          {/* {renderAnswerDesc(questionAnswerDescList)} */}
        </div>
      );
    });
  }

  // 查看图片或视频
  function handleScanFile(scanFileType, scanFileAddress) {
    setShowScanFile(true);
    setScanFileAddress(scanFileAddress);
    setScanFileType(scanFileType);
  }

  // 渲染多媒体内容
  function renderMediaContent(mediaContent) {
    return (
      <div className='media-container'>
        {_.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={() => handleScanFile('JPG', content)} />
                </div>
              );
              break;
            case 'VOICE':
              dom = (
                <div key={mediaIndex + 1} className='voice-box'>
                  <XMAudio
                    url={content}
                    getDuration={(durationSize) => {
                      size = durationSize;
                    }}
                    index={mediaIndex + 1}
                    size={size || 1000}
                  />
                </div>
              );
              break;
            case 'AUDIO':
              dom = (
                <div key={mediaIndex} className='voice-box'>
                  <XMAudio
                    url={content}
                    getDuration={(durationSize) => {
                      size = durationSize;
                    }}
                    index={mediaIndex}
                    size={size || 1000}
                  />
                </div>
              );
              break;
          }
          return dom;
        })}
      </div>
    );
  }

  // 渲染题干
  function renderStem(questionItem, questionStemList, questionType, score, orderIndex, questionId, gapFillingAnswerList) {
    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 : '';

    const userAnswerItem = _.filter(userAnswerList, (item) => {
      return item.questionId === questionId;
    });

    // 填空题题干渲染
    if (questionType === 'GAP_FILLING' && userAnswerItem.length > 0) {
      let userAnswer = [];
      if (userAnswerItem[0].answer) {
        userAnswer = userAnswerItem[0].answer;
      } else {
        gapFillingAnswerList.forEach((item, index) => {
          userAnswer.push('');
        });
      }

      gapFillingAnswerList.map((gapItem, gapIndex) => {
        let gapValue = gapItem.correctAnswerList.includes(userAnswer[gapIndex])
          ? `<img src="https://image.xiaomaiketang.com/xm/FwZa2Kaypc.png" />`
          : `<img src="https://image.xiaomaiketang.com/xm/7tRHDf6ysA.png" />`;
        content = content.replace(
          /(_)|(<input.*?>)/,
          `<div class="gap-line"><span>${userAnswer[gapIndex] === '@X#$' ? '' : userAnswer[gapIndex]} </span>${gapValue}</div>`
        );
      });
    }

    let textDom = (
      <div
        key={0}
        className='text-dom'
        dangerouslySetInnerHTML={{
          __html: content,
        }}
      />
    );

    return (
      <div className='stem-line__item' id={questionItem.questionId}>
        <div className='text'>
          <img
            className='answer-icon'
            src={userAnswerItem[0].isCorrect === 1 ? 'https://image.xiaomaiketang.com/xm/FwZa2Kaypc.png' : 'https://image.xiaomaiketang.com/xm/7tRHDf6ysA.png'}
          />
          <span className='question-index'>第{orderIndex + 1}题</span>
          <span className='steam-line_type'>（{`${questionTypeList[questionType]} | ${score}分`}）</span>
          {textDom}
        </div>
        {renderMediaContent(mediaContent)}
      </div>
    );
  }

  // 渲染选项
  function renderOption(optionItem, optionIndex, questionId) {
    const { questionOptionContentList, optionSort, isCorrectAnswer, id } = 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 : '';
    let textDom = (
      <span
        key={0}
        className='text-dom'
        dangerouslySetInnerHTML={{
          __html: content,
        }}
      />
    );

    const userAnswerItem = _.filter(userAnswerList, (item) => {
      return item.questionId === questionId;
    });

    let userAnswer = [];
    if (userAnswerItem.length > 0) {
      if (userAnswerItem[0].answer) {
        userAnswer = userAnswerItem[0].answer;
      }
    }

    let optionStatus = '';
    if (userAnswer.includes(id)) {
      // 选中
      optionStatus = 'answered';
    }

    let answerStatusIcon = 'default';

    if (isCorrectAnswer) {
      answerStatusIcon = 'https://image.xiaomaiketang.com/xm/FwZa2Kaypc.png';
    } else if (userAnswer.includes(id)) {
      answerStatusIcon = 'https://image.xiaomaiketang.com/xm/7tRHDf6ysA.png';
    } else {
      answerStatusIcon = 'default';
    }

    return (
      <div className='option-line__item'>
        <div className={`text ${optionStatus}`}>
          <div className='option-sort'>{NUM_TO_WORD_MAP[optionSort]}</div>
          <div className='option-content'>
            <div className='text-dom'>{textDom}</div>
            {mediaContent.length > 0 && renderMediaContent(mediaContent)}
          </div>
        </div>
        {answerStatusIcon !== 'default' && <img className='icon' src={answerStatusIcon} />}
      </div>
    );
  }

  // 渲染答案对比
  function renderAnswerCompare(questionId, questionType, optionList, gapFillingAnswerList) {
    const userAnswerItem = _.filter(userAnswerList, (item) => {
      return item.questionId === questionId;
    });
    const userAnswer = userAnswerItem.length > 0 && userAnswerItem[0].answer;

    if (questionType === 'GAP_FILLING') {
      return (
        <div className='answer-compare-box'>
          <div className='answer-info' style={{ marginBottom: '0.16rem' }}>
            <div className='title'>考试作答是</div>
            {userAnswer &&
              userAnswer.map((item, index) => {
                return (
                  <div className='content'>
                    <span>[填空{index + 1}]</span>
                    <span
                      dangerouslySetInnerHTML={{
                        __html: item === '@X#$' ? '' : item,
                      }}
                    />
                    <span>;</span>
                  </div>
                );
              })}
          </div>
          <div className='answer-info'>
            <div className='title'>正确答案是</div>
            {gapFillingAnswerList.map((item, index) => {
              return (
                <div className='content' style={{ color: '#20CECD' }}>
                  <span>[填空{index + 1}]</span>
                  {_.map(item.correctAnswerList, (childItem, childIndex) => {
                    return (
                      <span
                        dangerouslySetInnerHTML={{
                          __html: childItem,
                        }}
                      />
                    );
                  })}
                  <span>;</span>
                </div>
              );
            })}
          </div>
        </div>
      );
    } else {
      // 正确答案序号
      const rightOptionSort = _.filter(optionList, (item) => {
        return item.isCorrectAnswer === 1;
      }).map((sortItem) => {
        return sortItem.optionSort;
      });

      const userAnswerSort = _.filter(optionList, (item) => {
        if (userAnswer) {
          return userAnswer.includes(item.id);
        }
      }).map((sortItem) => {
        return sortItem.optionSort;
      });

      return (
        <div className='answer-compare-box'>
          <div className='answer-info'>
            <div className='title'>考试作答是</div>
            <div className='content'>
              {userAnswerSort.map((item) => {
                return <span>{NUM_TO_WORD_MAP[item]} </span>;
              })}
            </div>
          </div>
          <div className='answer-info'>
            <div className='title'>正确答案是</div>
            <div className='content' style={{ color: '#20CECD' }}>
              {rightOptionSort.map((item) => {
                return <span>{NUM_TO_WORD_MAP[item]} </span>;
              })}
            </div>
          </div>
        </div>
      );
    }
  }

  // 渲染答案解析
  function renderAnswerDesc(questionAnswerDescList) {
    const textContent = _.filter(questionAnswerDescList, (item) => {
      return item.type === 'RICH_TEXT';
    });

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

    let content = textContent.length > 0 ? `${textContent[0].content}：` : '';

    let textDom = (
      <div
        key={0}
        className='text-dom'
        dangerouslySetInnerHTML={{
          __html: content,
        }}
      />
    );

    return (
      <div className='desc-line__item'>
        {textDom}
        {renderAnswerDescMedia(mediaContent)}
      </div>
    );
  }

  // 渲染答案解析的多媒体
  function renderAnswerDescMedia(mediaContent) {
    const pictureMediaList = _.filter(mediaContent, (mediaItem) => {
      return mediaItem.type === 'PICTURE';
    });
    const voiceMediaList = _.filter(mediaContent, (mediaItem) => {
      return mediaItem.type === 'VOICE';
    });
    const audioMediaList = _.filter(mediaContent, (mediaItem) => {
      return mediaItem.type === 'AUDIO';
    });
    const videoMediaList = _.filter(mediaContent, (mediaItem) => {
      return mediaItem.type === 'VIDEO';
    });

    return (
      <div className='desc-media-container'>
        {pictureMediaList.length > 0 && (
          <div className='desc-picture-box'>
            {_.map(pictureMediaList, (pictureItem, pictureIndex) => {
              let { content } = pictureItem;
              return (
                <div className='picture-box' key={pictureIndex}>
                  <img className='img-box' src={content} onClick={() => handleScanFile('JPG', content)} />
                </div>
              );
            })}
          </div>
        )}
        {audioMediaList.length > 0 && (
          <div className='desc-audio-box'>
            {_.map(audioMediaList, (audioItem, audioIndex) => {
              let { content, size } = audioItem;
              return (
                <div className='audio-box' key={audioIndex}>
                  <XMAudio
                    forbidParse
                    url={content}
                    getDuration={(durationSize) => {
                      size = durationSize;
                    }}
                    index={audioIndex}
                    size={size || 1000}
                  />
                </div>
              );
            })}
          </div>
        )}
        {voiceMediaList.length > 0 && (
          <div className='desc-audio-box'>
            {_.map(voiceMediaList, (voiceItem, voiceIndex) => {
              let { content, size } = voiceItem;
              return (
                <div className='audio-box' key={voiceIndex}>
                  <XMAudio
                    forbidParse
                    url={content}
                    getDuration={(durationSize) => {
                      size = durationSize;
                    }}
                    index={voiceIndex}
                    size={size || 1000}
                  />
                </div>
              );
            })}
          </div>
        )}
        {videoMediaList.length > 0 && (
          <div className='desc-video-box'>
            {_.map(videoMediaList, (videoItem, videoIndex) => {
              let { content } = videoItem;
              return (
                <div className='video-box' key={videoIndex}>
                  <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' onClick={() => handleScanFile('MP4', content)} />
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  // 答题卡展开和收起
  function handleToggleQuestionCardShow() {
    setIsShowQuestionCard(!isShowQuestionCard);
  }

  // 快速跳转题目
  function handleQuickActiveQuestion(orderIndex, answerIndex) {
    setActiveOrderIndex(orderIndex);
    setActiveIndex(answerIndex);
    setIsShowQuestionCard(false);
  }

  // 只选错题
  function chooseErrorAnswer() {
    setOnlyError(!onlyError);
    setActiveOrderIndex(!onlyError ? (errorCount > 0 ? errorQuestionList[0].orderIndex : 0) : 0);
    setActiveIndex(0);
    setUserAnswerList(!onlyError ? errorUserAnswerList : allUserAnswerList);
    setQuestionList(!onlyError ? errorQuestionList : allQuestionList);
  }

  const { totalQuestionCount, userCorrectQuestion } = examDetail;

  let sortedAnswerList = [];
  let userAnswerMap = {};
  userAnswerList.forEach((item) => {
    userAnswerMap[item.questionId] = item;
  });

  questionList.forEach((item) => {
    if (userAnswerMap[item.questionId]) {
      sortedAnswerList.push({
        ...userAnswerMap[item.questionId],
        orderIndex: item.orderIndex,
      });
    }
  });

  return (
    <div className='answer-desc-page'>
      <div className='center'>
        <div className='box-content'>
          <div className='answer-desc-header'>
            <div className='desc-header-container'>
              <div className='desc-title'>答案详情</div>
              <div className='choose-error-box'>
                <img
                  onClick={() => {
                    chooseErrorAnswer();
                  }}
                  src={onlyError ? 'https://image.xiaomaiketang.com/xm/FwZa2Kaypc.png' : 'https://image.xiaomaiketang.com/xm/crtyKFjcAm.png'}
                />
                <span>只看错题</span>
              </div>
            </div>
          </div>
        </div>
        {errorCount === 0 && onlyError ? (
          <div className='empty'>
            <div className='img-box' id='lottie-box'></div>
            <div className='empty-text'>本次考试无错题</div>
          </div>
        ) : (
          <div className='answer-desc-content'>
            <div className='question-list-box'>{handleRenderQuestionItem()}</div>
          </div>
        )}
        {/* {renderFooterText()} */}
      </div>
      {showScanFile && (
        <ScanFileModal
          fileType={scanFileType}
          item={{
            ossAddress: scanFileAddress,
          }}
          close={() => {
            setShowScanFile(false);
          }}
        />
      )}
    </div>
  );
}

export default withRouter(AnswerDescPage);
