/*
 * @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 { Route, withRouter } from 'react-router-dom';
import User from '@/common/js/user';
import './TestDetailPage.less';
import Service from '@/common/js/service';
import { message, Empty } from 'antd';
import moment from 'moment';
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 [customerId, setCustomerId] = useState('');
  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,
    userExamState: 'INIT',
    userScore: 0,
  }); // 考试详情
  const [testState, setTestState] = useState({
    isDelete: false,
  }); // 考试状态
  const [paperDetail, setPaperDetail] = useState({}); // 试卷详情
  const [questionList, setQuestionList] = useState([]); // 试卷题目列表
  const [userAnswerList, setUserAnswerList] = useState([]); // 用户答案列表
  const [isScrollShow, setIsScrollShow] = useState(false); // 是否展示回到顶部按钮

  const {
    answerAnalysis,
    resultContent,
    resultShow,
    examName,
    examStartTime,
    examEndTime,
    totalScore,
    totalQuestionCount,
    passScore,
    examDuration,
    examDesc,
    userExamDuration,
    userExamState,
    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);
    setTestState({
      isDelete: 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() {
    console.log('userExamState====>', userExamState);
    if (userExamState !== 'INIT') {
      if (userExamState === 'FINISH_EXAM') {
        if (resultShow === 'IMMEDIATELY' || (resultShow === 'AFTER_EXAM_END' && Date.now() > examEndTime)) {
          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>
              )}
              {!testState.isDelete &&
                userExamState !== 'LACK_EXAM' &&
                (resultShow === 'IMMEDIATELY' || (resultShow === 'AFTER_EXAM_END' && Date.now() > examEndTime)) &&
                answerAnalysis === 'ANALYSE_AND_RIGHT_OR_WRONG' && <AnswerDescPage />}
            </div>
          );
        } else if (resultShow === 'AFTER_EXAM_END') {
          return customizeRenderEmpty('after');
        }
      } else {
        return customizeRenderEmpty('lack');
      }
    }
  }

  function customizeRenderEmpty(status) {
    return (
      <div className='empty-result'>
        <Empty
          image={status === 'lack' ? 'https://image.xiaomaiketang.com/xm/7xi4YTXmHK.png' : 'https://image.xiaomaiketang.com/xm/bhGtST27Hf.png'}
          imageStyle={{
            height: '100px',
          }}
          description={
            status === 'lack' ? (
              <div className='lack-desc'>
                <div className='title'>缺考</div>
                <div className='content'>你没有成功交卷哦</div>
              </div>
            ) : (
              <div className='after-desc'>
                <div className='title'>恭喜你完成考试！</div>
                <div className='after-show-box'>
                  <div>本次考试用时 {window.formatHourTime(Number(userExamDuration || 0))}</div>
                  <div>
                    考试结果会在
                    <span style={{ color: '#333333' }}>
                      {moment(Number(examEndTime)).format('YYYY.MM.DD HH:mm')}
                      公布哦
                    </span>
                  </div>
                </div>
              </div>
            )
          }></Empty>
      </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);
