/*
 * @Author: yuananting
 * @Date: 2021-04-07 16:10:21
 * @LastEditors: wufan
 * @LastEditTime: 2021-04-26 10:21:19
 * @Description: 助学工具-考试-考试结果
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import User from '@/common/js/user';
import './TestDetailPage.less';
import Service from '@/common/js/service';
import { message } from 'antd';
import AnswerDescPage from '../components/AnswerDescPage';
import Breadcrumbs from '@/components/Breadcrumbs';

function TestDetailPage(props) {
  const examId = props.match.params.testId.replace(/\?.+/, '');
  const paperId = window.getParameterByName('paperId');
  const [examDetail, setExamDetail] = useState({
    answerAnalysis: '',
    resultShow: '',
    examDesc: '',
    examDuration: 0,
    examEndTime: '',
    examName: '',
    examStartTime: '',
    paperId: 0,
    passRate: 0,
    passScore: 0,
    resultContent: '',
    totalQuestionCount: 0,
    totalScore: 0,
    userCorrectQuestion: 0,
    userExamDuration: 0,
    userScore: 0,
  }); // 考试详情
  const [paperDetail, setPaperDetail] = useState({}); // 试卷详情
  const [questionList, setQuestionList] = useState([]); // 试卷题目列表
  const [userAnswerList, setUserAnswerList] = useState([]); // 用户答案列表
  const [isScrollShow, setIsScrollShow] = useState(false); // 是否展示回到顶部按钮

  const { answerAnalysis, resultContent, examName, totalScore, totalQuestionCount, passScore, examDuration, userExamDuration, userScore, userCorrectQuestion } =
    examDetail;

  useEffect(() => {
    bindScroll();
    getPaperDetail();
    getExamDetail();
  }, []);

  function bindScroll() {
    window.addEventListener('scroll', handleScroll, true);
  }

  function getExamDetail() {
    const params = {
      examId,
      source: 0,
      tenantId: User.getStoreId() || window.getParameterByName('id'),
      userId: User.getCustomerId(),
    };
    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,
      source: 0,
      readAnswer: true,
      tenantId: User.getStoreId() || window.getParameterByName('id'),
      userId: User.getCustomerId(),
    }).then((res) => {
      if (res.success) {
        const { paperDetailVO, userExamAnswerVO } = res.result;
        const userAnswerList = [...userExamAnswerVO];
        const { questionList } = paperDetailVO;
        setPaperDetail(paperDetail);
        setUserAnswerList(userAnswerList);
        setQuestionList(questionList || []);
      }
    });
  }

  function handleChangeShowErrorPage() {
    setIsShowErrorPage(true);
  }

  // 用户时长转换
  function formatTime(msTime) {
    let time = msTime / 1000;
    let hour = Math.floor(time / 60 / 60) % 24 > 9 ? Math.floor(time / 60 / 60) % 24 : '0' + (Math.floor(time / 60 / 60) % 24);
    let minute = Math.floor(time / 60) % 60 > 9 ? Math.floor(time / 60) % 60 : '0' + (Math.floor(time / 60) % 60);
    let second = time % 60 > 9 ? Math.round(time % 60) : '0' + Math.round(time % 60);
    return `${hour}:${minute}:${second}`;
  }

  // 快速跳转题目
  function handleQuickActiveQuestion(questionId) {
    let selectDom = document.getElementById(`${questionId}`);
    selectDom.scrollIntoView({
      block: 'center',
    });
  }

  // 回到顶部
  function handleGoTop() {
    window.scrollTo(0, 0);
  }

  // 监听滚动，200以后出现回到顶部按钮
  function handleScroll() {
    if (window.pageYOffset > 200) {
      setIsScrollShow(true);
    } else {
      setIsScrollShow(false);
    }
  }

  function renderResultInfo() {
    return (
      <div>
        <div className='exam-info'>
          {['PASS_AND_SCORE', 'ONLY_SCORE'].includes(resultContent) && (
            <div className='info-score item'>
              <div className='current-score'>
                {userScore}
                <img src='https://image.xiaomaiketang.com/xm/TsaApiPyxA.png' />
              </div>
              <div className='origin-data'>总分{totalScore}</div>
            </div>
          )}

          {['PASS_AND_SCORE', 'ONLY_PASS'].includes(resultContent) && (
            <div className='info-level item'>
              <div className='current-level'>{userScore < passScore ? '不及格' : '及格'}</div>
              <div className='origin-data'>及格分{passScore}</div>
            </div>
          )}

          <div className='info-correct item'>
            <div className='current-correct'>
              {userCorrectQuestion}
              <div className='text'>答对题数</div>
            </div>
            <div className='origin-data'>共{totalQuestionCount}题</div>
          </div>

          <div className='info-time item'>
            <div className='current-time'>
              {formatTime(Number(userExamDuration > examDuration ? examDuration : userExamDuration || 0))}
              <div className='text'>用时</div>
            </div>
            <div className='origin-data'>考试时长{(examDuration || 0) / 60 / 1000}分钟</div>
          </div>
        </div>
        {['ANALYSE_AND_RIGHT_OR_WRONG', 'RIGHT_OR_WRONG'].includes(answerAnalysis) && (
          <div className='exam-result'>
            <div className='result-title'>
              <div className='left-title'>答题情况</div>
              <div className='right-tip'>
                <span className='correct-num'>{userCorrectQuestion}</span>
                <span className='incorrect-num'>/{totalQuestionCount} </span>
                道正确
              </div>
            </div>
            <div className='result-content'>
              {sortedAnswerList.map((item, index) => {
                return (
                  <div
                    className='result-content__item'
                    onClick={() => {
                      console.log('item', item);
                      handleQuickActiveQuestion(item.questionId);
                    }}>
                    <img
                      className='icon'
                      src={item.isCorrect === 1 ? 'https://image.xiaomaiketang.com/xm/FwZa2Kaypc.png' : 'https://image.xiaomaiketang.com/xm/7tRHDf6ysA.png'}
                    />
                    <div className='result-content-box'>{index + 1}</div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
        <AnswerDescPage />
      </div>
    );
  }

  let sortedAnswerList = [];
  questionList.map((item) => {
    userAnswerList &&
      userAnswerList.map((answerItem) => {
        if (item.questionId === answerItem.questionId) {
          sortedAnswerList.push(answerItem);
        }
      });
  });

  return (
    <div className='exam-result-page page'>
      <Breadcrumbs navList={'答题详情'} goBack={props.history.goBack} />

      <div className='center'>
        <div className='box'>
          <div className='box-content'>
            <div
              className='exam-head'
              style={{
                padding: examName.length > 20 ? '8px 0 14px' : '16px 0 29px',
              }}>
              <div className={`exam-name ${examName.length > 20 ? 'many' : 'few'}`}>{examName}</div>
            </div>
            {renderResultInfo()}
          </div>
        </div>
      </div>
      {isScrollShow && <div className='go-top' onClick={handleGoTop}></div>}
    </div>
  );
}

export default withRouter(TestDetailPage);
