package com.ruoyi.hezhi.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hezhi.domain.*;
import com.ruoyi.hezhi.domain.dto.MemberExamSimulateAllDTO;
import com.ruoyi.hezhi.mapper.*;
import com.ruoyi.hezhi.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 我的考试、模拟题目（做过）Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-11
 */
@Service
public class TbMemberExamSimulateAllServiceImpl implements ITbMemberExamSimulateAllService
{
    @Autowired
    private TbMemberExamSimulateAllMapper tbMemberExamSimulateAllMapper;
    @Autowired
    private ITbExamSubjectService tbExamSubjectService;
    @Autowired
    private ITbMemberSubjectWrongService tbMemberSubjectWrongService;
    @Autowired
    private ITbSubjectWarehouseClassService tbSubjectWarehouseClassService;
    @Autowired
    private ITbExamSubjectAnswerService tbExamSubjectAnswerService;
    @Autowired
    private ITbExamSubjectFormalService examSubjectFormalService;
    @Autowired
    private ITbExamService examService;
    @Autowired
    private TbExamSimulateInfoMapper tbExamSimulateInfoMapper;
    @Autowired
    private TbExamCourseMapper tbExamCourseMapper;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private TbExamBatchMapper tbExamBatchMapper;
    @Autowired
    private TbExamRegistrationMapper tbExamRegistrationMapper;
    @Autowired
    private TbMemberSubjectCollectMapper tbMemberSubjectCollectMapper;

    /**
     * 查询我的考试、模拟题目（做过）
     *
     * @param memberExamSimulateAllId 我的考试、模拟题目（做过）主键
     * @return 我的考试、模拟题目（做过）
     */
    @Override
    public TbMemberExamSimulateAll selectTbMemberExamSimulateAllByMemberExamSimulateAllId(Long memberExamSimulateAllId)
    {
        return tbMemberExamSimulateAllMapper.selectTbMemberExamSimulateAllByMemberExamSimulateAllId(memberExamSimulateAllId);
    }

    /**
     * 查询我的考试、模拟题目（做过）列表
     *
     * @param tbMemberExamSimulateAll 我的考试、模拟题目（做过）
     * @return 我的考试、模拟题目（做过）
     */
    @Override
    public List<TbMemberExamSimulateAll> selectTbMemberExamSimulateAllList(TbMemberExamSimulateAll tbMemberExamSimulateAll)
    {
        return tbMemberExamSimulateAllMapper.selectTbMemberExamSimulateAllList(tbMemberExamSimulateAll);
    }

    /**
     * 新增我的考试、模拟题目（做过）
     *
     * @param tbMemberExamSimulateAll 我的考试、模拟题目（做过）
     * @return 结果
     */
    @Override
    public int insertTbMemberExamSimulateAll(TbMemberExamSimulateAll tbMemberExamSimulateAll)
    {
        tbMemberExamSimulateAll.setCreateTime(DateUtils.getNowDate());
        return tbMemberExamSimulateAllMapper.insertTbMemberExamSimulateAll(tbMemberExamSimulateAll);
    }

    /**
     * 修改我的考试、模拟题目（做过）
     *
     * @param tbMemberExamSimulateAll 我的考试、模拟题目（做过）
     * @return 结果
     */
    @Override
    public int updateTbMemberExamSimulateAll(TbMemberExamSimulateAll tbMemberExamSimulateAll)
    {
        tbMemberExamSimulateAll.setUpdateTime(DateUtils.getNowDate());
        return tbMemberExamSimulateAllMapper.updateTbMemberExamSimulateAll(tbMemberExamSimulateAll);
    }

    /**
     * 批量删除我的考试、模拟题目（做过）
     *
     * @param memberExamSimulateAllIds 需要删除的我的考试、模拟题目（做过）主键
     * @return 结果
     */
    @Override
    public int deleteTbMemberExamSimulateAllByMemberExamSimulateAllIds(Long[] memberExamSimulateAllIds)
    {
        return tbMemberExamSimulateAllMapper.deleteTbMemberExamSimulateAllByMemberExamSimulateAllIds(memberExamSimulateAllIds);
    }

    /**
     * 删除我的考试、模拟题目（做过）信息
     *
     * @param memberExamSimulateAllId 我的考试、模拟题目（做过）主键
     * @return 结果
     */
    @Override
    public int deleteTbMemberExamSimulateAllByMemberExamSimulateAllId(Long memberExamSimulateAllId)
    {
        return tbMemberExamSimulateAllMapper.deleteTbMemberExamSimulateAllByMemberExamSimulateAllId(memberExamSimulateAllId);
    }

    /**
     * 正式考试点击确定开始答题
     *
     * @param memberExamSimulateAllDTO
     * @return ok
     */
    @Override
    public AjaxResult subjectFormalClickOK(MemberExamSimulateAllDTO memberExamSimulateAllDTO) {
        TbExamSimulateInfo examSimulateInfo = tbExamSimulateInfoMapper.selectTbExamSimulateInfoByExamSimulateInfoId(memberExamSimulateAllDTO.getExamSimulateInfoId());
        if (examSimulateInfo.getPassStatus() != 0) {
            return AjaxResult.error("您已交卷");
        }
        String endTime = examSimulateInfo.getEndTime();
        if (StringUtils.isBlank(examSimulateInfo.getStartTime()) || StringUtils.isBlank(examSimulateInfo.getEndTime())) {
            String nowTime = DateUtils.getTime();
            examSimulateInfo.setStartTime(nowTime);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            try {
                calendar.setTime(sdf.parse(nowTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            calendar.add(Calendar.MINUTE, examSimulateInfo.getExamMinute()); // 添加分钟数

            String endTimeFormat = sdf.format(calendar.getTime());
//            TbExam exam = examService.selectTbExamByExamId(examSimulateInfo.getExamId());
            //根据考试ID和学员ID搜出最近的一场考试批次 [考试报名表和考试批次表联表查批次表]
            TbExamBatch tbExamBatch = tbExamBatchMapper.selectTbExamBatchByExamIdAndUserId(examSimulateInfo.getExamId(),examSimulateInfo.getMemberUserId());
            if (tbExamBatch != null) {
                Date examEndTimeA = tbExamBatch.getExamEndTime();//考试设置的结束
                String endTimeA = sdf.format(calendar.getTime());//本次考试计算出来的结束时间

                Date examEndTimeACompare = examEndTimeA;;
                Date endTimeACompare = null;

                try {
                    endTimeACompare = sdf.parse(endTimeA);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                // 比较时间
                if (endTimeACompare.after(examEndTimeACompare)) {
                    // 直接格式化Date对象
                    endTimeFormat = sdf.format(examEndTimeA);
                }
            }
            examSimulateInfo.setEndTime(endTimeFormat);

            endTime = endTimeFormat;
            tbExamSimulateInfoMapper.updateTbExamSimulateInfo(examSimulateInfo);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("endTime", endTime);
        return AjaxResult.success(map);
    }

    /**
     * 模拟考试答题
     *
     * @param memberExamSimulateAllDTO
     * @return ok
     */
    @Override
    public AjaxResult subjectSimulateAnswer(MemberExamSimulateAllDTO memberExamSimulateAllDTO) {
        Long memberUserId = memberExamSimulateAllDTO.getMemberUserId();
        Long examSimulateInfoId = memberExamSimulateAllDTO.getExamSimulateInfoId();
        Long examSubjectId = memberExamSimulateAllDTO.getExamSubjectId();
        String myAnswer = memberExamSimulateAllDTO.getMyAnswer();
        Long location = memberExamSimulateAllDTO.getLocation();

        Long courseId = memberExamSimulateAllDTO.getCourseId();

        // 查询当前题目
        TbExamSubject tbExamSubject = tbExamSubjectService.selectTbExamSubjectByExamSubjectId(memberExamSimulateAllDTO.getExamSubjectId());
        if (tbExamSubject == null) {
            return AjaxResult.error("题目信息异常");
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("memberUserId", memberUserId);
        params.put("examSubjectId", examSubjectId);

        // 正确答案
        String answer = tbExamSubject.getAnswer();
        if (tbExamSubject.getSubjectType() == 3) {
            if ("正确".equals(answer)) {
                answer = "A";
            }
            if ("错误".equals(answer)) {
                answer = "B";
            }
        }

        BigDecimal score = new BigDecimal(0);
        // 题目分数
        TbExamCourse examCourseDetail = tbExamCourseMapper.getSubjectWarehouseClassIdByCourseId(courseId);
        if (ObjectUtils.isEmpty(examCourseDetail)){
            throw new ServiceException("管理员未上传该题库信息");
        }
        TbSubjectWarehouseClass subjectWarehouseClass = tbSubjectWarehouseClassService.selectTbSubjectWarehouseClassBySubjectWarehouseClassId(examCourseDetail.getSubjectWarehouseClassId());
        if (tbExamSubject.getSubjectType() == 1) {
            score = subjectWarehouseClass.getSingleSelectScore();
        } else if (tbExamSubject.getSubjectType() == 2) {
            score = subjectWarehouseClass.getManySelectScore();
        } else if (tbExamSubject.getSubjectType() == 3) {
            score = subjectWarehouseClass.getJudgeScore();
        } else if (tbExamSubject.getSubjectType() == 4) {
            score = subjectWarehouseClass.getDiscussScore();
        }

        TbMemberExamSimulateAll memberExamSimulateAll = new TbMemberExamSimulateAll();
        memberExamSimulateAll.setExamSimulateInfoId(examSimulateInfoId);
        memberExamSimulateAll.setExamSubjectId(examSubjectId);
        memberExamSimulateAll.setMemberUserId(memberUserId);
        memberExamSimulateAll.setLocation(location);
        memberExamSimulateAll.setMyAnswer(myAnswer);
        memberExamSimulateAll.setAnswer(answer);
        memberExamSimulateAll.setSubjectType(tbExamSubject.getSubjectType());
        memberExamSimulateAll.setExamType(2);

        if (tbExamSubject.getSubjectType() != 4) {
            if (myAnswer.equals(answer)) {
                memberExamSimulateAll.setStatus(1);
                memberExamSimulateAll.setScore(score);
            } else {
                memberExamSimulateAll.setStatus(2);
                memberExamSimulateAll.setScore(new BigDecimal(0));
//                String finalAnswer = answer;
                threadPoolTaskExecutor.execute(()->{
                    //添加错题
                    TbMemberSubjectCollect memberSubjectCollect = tbMemberSubjectCollectMapper.selectTbMemberSubjectCollectByMemberUserIdSubjectId(
                            memberUserId,
                            examSubjectId,
                            courseId);
                    if (ObjectUtils.isEmpty(memberSubjectCollect)){
                        TbMemberSubjectCollect subjectCollect = new TbMemberSubjectCollect();
                        subjectCollect.setMemberUserId(memberUserId);
                        subjectCollect.setExamSubjectId(examSubjectId);
                        subjectCollect.setCourseId(courseId);
                        subjectCollect.setCreateTime(DateUtils.getNowDate());
                        tbMemberSubjectCollectMapper.insertTbMemberSubjectCollect(subjectCollect);
                    }
                });
//                threadPoolTaskExecutor.execute(()->{
//                    //添加错题
//                    int count = tbMemberSubjectWrongService.countByParams(params);
//                    if (count == 0){
//                        TbMemberSubjectWrong wrong = new TbMemberSubjectWrong();
//                        wrong.setMemberUserId(memberUserId);
//                        wrong.setExamSubjectId(examSubjectId);
//                        wrong.setStatus(2);
//                        wrong.setMyAnswer(myAnswer);
//                        wrong.setAnswer(finalAnswer);
//                        wrong.setLocation(location);
//                        tbMemberSubjectWrongService.insertTbMemberSubjectWrong(wrong);
//                    }
//                });
            }
        } else {
            // 论述
            BigDecimal discussScore = tbExamSubjectAnswerService.getDiscussScore(tbExamSubject.getExamSubjectNo(), myAnswer);
            if (discussScore.compareTo(score) > 0) {
                memberExamSimulateAll.setScore(score);
            } else {
                memberExamSimulateAll.setScore(discussScore);
            }
            memberExamSimulateAll.setStatus(3);
        }


        params.put("examSimulateInfoId", examSimulateInfoId);
        params.put("examType", 2);
        params.put("location", location);
        TbMemberExamSimulateAll simulateAll = tbMemberExamSimulateAllMapper.queryMemberExamSimulateAllByParam(params);
        if (simulateAll == null) {
            tbMemberExamSimulateAllMapper.insertTbMemberExamSimulateAll(memberExamSimulateAll);
        } else {
            memberExamSimulateAll.setMemberExamSimulateAllId(simulateAll.getMemberExamSimulateAllId());
            tbMemberExamSimulateAllMapper.updateTbMemberExamSimulateAll(memberExamSimulateAll);
        }
        return AjaxResult.success().put("data", memberExamSimulateAll);
    }

    /**
     * 正式考试答题
     *
     * @param memberExamSimulateAllDTO
     * @return ok
     */
    @Override
    public AjaxResult subjectFormalAnswer(MemberExamSimulateAllDTO memberExamSimulateAllDTO) {
        Long memberUserId = memberExamSimulateAllDTO.getMemberUserId();
        Long examSimulateInfoId = memberExamSimulateAllDTO.getExamSimulateInfoId();
        Long examSubjectId = memberExamSimulateAllDTO.getExamSubjectId();
        String myAnswer = memberExamSimulateAllDTO.getMyAnswer();
        Long location = memberExamSimulateAllDTO.getLocation();
        Long examId = memberExamSimulateAllDTO.getExamId();

        // 查询当前题目
        TbExamSubject tbExamSubject = tbExamSubjectService.selectTbExamSubjectByExamSubjectId(memberExamSimulateAllDTO.getExamSubjectId());
        if (tbExamSubject == null) {
            return AjaxResult.error("题目信息异常");
        }

        TbExamSimulateInfo tbExamSimulateInfo = tbExamSimulateInfoMapper.selectTbExamSimulateInfoByExamSimulateInfoId(examSimulateInfoId);
        TbExam exam = examService.selectTbExamByExamId(examId);
        TbExamRegistration tbExamRegistration = tbExamRegistrationMapper.selectTbExamRegistrationByUserIdExamId(memberUserId, examId);

        TbExamBatch tbExamBatch = tbExamBatchMapper.getByExamIdBatchIndex(examId, tbExamRegistration.getExamBatchIndex());

        // 获取当前时间
        Date currentTime = new Date();
        // 定义时间格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = tbExamSimulateInfo.getEndTime();// 做题结束时间字符串
        // 将字符串转换为Date
        Date endTimeCompare = null;
        Date examEndTimeCompare = tbExamBatch.getExamEndTime();
        try {
            endTimeCompare = dateFormat.parse(endTime);
            // 比较时间
//            if (currentTime.after(endTimeCompare)) {
//                return AjaxResult.error("做题时间【" + tbExamSimulateInfo.getStartTime() + "至" + tbExamSimulateInfo.getEndTime() + "】，考试已结束");
//            }
            if (currentTime.after(examEndTimeCompare)) {
                return AjaxResult.error("考试时间【" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", tbExamBatch.getExamStartTime()) + "至" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", tbExamBatch.getExamEndTime()) + "】，考试已结束");
            }
        }catch (Exception e){
            e.printStackTrace();
        }



        // 正确答案
        String answer = tbExamSubject.getAnswer();
        if (tbExamSubject.getSubjectType() == 3) {
            if ("正确".equals(answer)) {
                answer = "A";
            }
            if ("错误".equals(answer)) {
                answer = "B";
            }
        }

        BigDecimal score = new BigDecimal(0);
        // 题目分数
        if (tbExamSubject.getSubjectType() == 1) {
            score = exam.getSingleSelectScore();
        } else if (tbExamSubject.getSubjectType() == 2) {
            score = exam.getManySelectScore();
        } else if (tbExamSubject.getSubjectType() == 3) {
            score = exam.getJudgeScore();
        } else if (tbExamSubject.getSubjectType() == 4) {
            score = exam.getDiscussScore();
        }

        /* 根据考试、人员、题目ID查询该题是否存在 */
        TbMemberExamSimulateAll examSimulateAll = new TbMemberExamSimulateAll();
        examSimulateAll.setExamSimulateInfoId(examSimulateInfoId);
        examSimulateAll.setExamSubjectId(examSubjectId);
        examSimulateAll.setMemberUserId(memberUserId);
        List<TbMemberExamSimulateAll> examSimulateAllList = tbMemberExamSimulateAllMapper.selectTbMemberExamSimulateAllList(examSimulateAll);
        if (!examSimulateAllList.isEmpty()) {

        }

        TbMemberExamSimulateAll memberExamSimulateAll = new TbMemberExamSimulateAll();
        memberExamSimulateAll.setExamSimulateInfoId(examSimulateInfoId);
        memberExamSimulateAll.setExamSubjectId(examSubjectId);
        memberExamSimulateAll.setMemberUserId(memberUserId);
        memberExamSimulateAll.setLocation(location);
        memberExamSimulateAll.setMyAnswer(myAnswer);
        memberExamSimulateAll.setAnswer(answer);
        memberExamSimulateAll.setSubjectType(tbExamSubject.getSubjectType());
        memberExamSimulateAll.setExamType(1);

        if (tbExamSubject.getSubjectType() != 4) {
            if (myAnswer.equals(answer)) {
                memberExamSimulateAll.setStatus(1);
                memberExamSimulateAll.setScore(score);
            } else {
                memberExamSimulateAll.setStatus(2);
                memberExamSimulateAll.setScore(new BigDecimal(0));
            }
        } else {
            // 论述
            BigDecimal discussScore = tbExamSubjectAnswerService.getDiscussScore(tbExamSubject.getExamSubjectNo(), myAnswer);
            if (discussScore.compareTo(score) > 0) {
                memberExamSimulateAll.setScore(score);
            } else {
                memberExamSimulateAll.setScore(discussScore);
            }
            memberExamSimulateAll.setStatus(3);
        }

        HashMap<String, Object> params = new HashMap<>();
        params.put("memberUserId", memberUserId);
        params.put("examSubjectId", examSubjectId);
        params.put("examSimulateInfoId", examSimulateInfoId);
        params.put("examType", 1);
//        params.put("location", location);
        TbMemberExamSimulateAll simulateAll = tbMemberExamSimulateAllMapper.queryMemberExamSimulateAllByParam(params);
        if (ObjectUtils.isEmpty(simulateAll)) {
            tbMemberExamSimulateAllMapper.insertTbMemberExamSimulateAll(memberExamSimulateAll);
        } else {
            memberExamSimulateAll.setMemberExamSimulateAllId(simulateAll.getMemberExamSimulateAllId());
            tbMemberExamSimulateAllMapper.updateTbMemberExamSimulateAll(memberExamSimulateAll);
        }
        return AjaxResult.success();
    }
}
