package com.xhkjedu.smarking.service.papercheck;

import com.xhkjedu.exception.ServiceException;
import com.xhkjedu.smarking.mapper.paper.MsPaperMapper;
import com.xhkjedu.smarking.mapper.papercheck.MsPaperCheckMapper;
import com.xhkjedu.smarking.mapper.papercheck.MsPaperCheckTeacherTaskMapper;
import com.xhkjedu.smarking.mapper.stupaper.*;
import com.xhkjedu.smarking.mapper.system.UserMapper;
import com.xhkjedu.smarking.model.paper.MsPaper;
import com.xhkjedu.smarking.model.paper.MsPaperBlockQuestion;
import com.xhkjedu.smarking.model.papercheck.*;
import com.xhkjedu.smarking.model.stupaper.MsPaperStudentBlock;
import com.xhkjedu.smarking.model.stupaper.MsPaperStudentQuestion;
import com.xhkjedu.smarking.utils.MarkingUtil;
import com.xhkjedu.smarking.vo.papercheck.*;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import com.xhkjedu.vo.system.UserVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 阅卷批阅教师任务表 服务实现类
 * @Author auto
 * @Date 2024-10-15
 */
@Service
public class MsPaperCheckTeacherTaskService {
    @Resource
    private MsPaperCheckTeacherTaskMapper msPaperCheckTeacherTaskMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private MsPaperCheckMapper msPaperCheckMapper;
    @Resource
    private MsPaperMapper msPaperMapper;
    @Resource
    private MsPaperStudentBlockMapper msPaperStudentBlockMapper;
    @Resource
    private MsPaperStudentQuestionMapper msPaperStudentQuestionMapper;
    @Resource
    private MsPaperStudentMapper msPaperStudentMapper;


    /**
     * @Description 阅卷进度-按题块
     * @Date 2024/10/30 10:23
     * @Author YWX
     * @Param [mpid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listByBlock(Integer mpid) {
        return msPaperCheckTeacherTaskMapper.listByBlock(mpid);
    }

    /**
     * @Description 阅卷进度-按题块-查看详情
     * @Date 2024/10/30 10:44
     * @Author YWX
     * @Param [mblockid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> detailByBlock(Integer mpid, Integer mblockid) {
        MsPaperCheck check = msPaperCheckMapper.findByMBlockId(mpid, mblockid);
        if (check == null) {
            throw new ServiceException("该题块不存在");
        }
        Integer dispenseway = check.getDispenseway();
        return msPaperCheckTeacherTaskMapper.detailByBlock(mpid, mblockid, dispenseway, check.getChecktype());
    }

    //计算题块/试题的总数和未批阅的数量
    private List<Map> setListNum(Integer dispenseway, List<Map> list) {
        if (dispenseway.equals(2)) {
            int totalNum = N_Utils.obj2Int(list.get(0).get("totalNum"));
            int totalCheckedNum = list.stream().mapToInt(m -> N_Utils.obj2Int(m.get("checkedNum"))).sum();
            int uncheckedNum = totalNum - totalCheckedNum;
            for (Map m : list) {
                m.put("totalNum", totalNum);
                m.put("uncheckedNum", uncheckedNum);
            }
        }
        return list;
    }

    /**
     * @Description 阅卷进度-按教师
     * @Date 2024/10/30 10:52
     * @Author YWX
     * @Param [mpid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listByTeacher(Integer mpid) {
        Integer correcttype = msPaperMapper.getCorrectTypeByMpId(mpid);
        if (!N_Utils.isTrueInteger(correcttype)) {
            throw new ServiceException("该试卷未设置批阅方式");
        }
        return msPaperCheckTeacherTaskMapper.listByTeacher(mpid, correcttype);
    }

    /**
     * @Description 教师阅卷-待/已阅卷列表
     * @Date 2024/10/30 14:41
     * @Author YWX
     * @Param [handleid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listCorrect(MsCheckParam param) {
        return msPaperCheckTeacherTaskMapper.listCorrect(param);
    }

    //设置查询参数
    public void setParam(MsCheckParam param) {
        UserVo vo = userMapper.getUserInfoForHandleLog(param.getHandleid());
        param.setSchoolid(vo.getSchoolid());
        param.setUsertype(vo.getUsertype());
    }

    /**
     * @Description 教师阅卷-待阅卷详情
     * @Date 2024/10/30 16:02
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listPendingBlock(MsCheckParam param) {
        MsPaper paper = msPaperMapper.selectByPrimaryKey(param.getMpid());
        param.setCorrecttype(paper.getCorrecttype());
        param.setSubjectid(paper.getSubjectid());
        return msPaperCheckTeacherTaskMapper.listPendingBlock(param);
    }

    /**
     * @Description 教师阅卷-题块列表
     * @Date 2024/10/31 9:49
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listTeacherBlock(MsCheckParam param) {
        return msPaperCheckTeacherTaskMapper.listTeacherBlock(param);
    }

    /**
     * @Description 教师阅卷-试题列表
     * @Date 2024/11/13 17:59
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listTeacherQuestion(MsCheckParam param) {
        Integer correcttype = msPaperMapper.getCorrectTypeByMpId(param.getMpid());
        param.setCorrecttype(correcttype);
        return msPaperCheckTeacherTaskMapper.listTeacherQuestion(param);
    }

    /**
     * @Description 教师阅卷-班级列表
     * @Date 2024/11/14 9:41
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listTeacherClass(MsCheckParam param) {
        return msPaperCheckTeacherTaskMapper.listTeacherClass(param);
    }

    /**
     * @Description 获取待批题块
     * @Date 2024/10/31 11:01
     * @Author YWX
     * @Param [param]
     * @Return java.util.Map
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo getCorrectBlock(MsCheckParam param) {
        Integer correcttype = msPaperMapper.getCorrectTypeByMpId(param.getMpid());
        if (!N_Utils.isTrueInteger(correcttype)) {
            throw new ServiceException("该试卷未设置批阅方式");
        }
        MsPaperCheckVo sq = null;
        Integer dispenseway = null;
        Integer type = null;//评卷方式1单评2双评
        Integer handleid = param.getHandleid();
        MsPaperCheck paperCheck = null;
        if (correcttype.equals(3)) {//按题块批阅
            List<MsPaperCheck> checks = msPaperCheckTeacherTaskMapper.listBlockCheck(param);
            if (N_Utils.isListEmpty(checks)) throw new ServiceException("暂无要批阅的题块");
            for (MsPaperCheck check : checks) {
                check.setTeacherid(handleid);
                sq = msPaperCheckTeacherTaskMapper.getCorrectBlock(check);
                if (sq != null) {
                    paperCheck = check;
                    break;
                }
            }
        } else if (correcttype.equals(2)) {//按试题批阅
            List<MsPaperCheck> checks = msPaperCheckTeacherTaskMapper.listQuestionCheck(param);
            if (N_Utils.isListEmpty(checks)) throw new ServiceException("暂无要批阅的试题");
            for (MsPaperCheck check : checks) {
                check.setTeacherid(handleid);
                sq = msPaperCheckTeacherTaskMapper.getCorrectQuestion(check);
                if (sq != null) {
                    paperCheck = check;
                    break;
                }
            }
        } else {//按班级批阅
            List<MsPaperCheck> checks = msPaperCheckTeacherTaskMapper.listClassCheck(param);
            if (N_Utils.isListEmpty(checks)) throw new ServiceException("暂无要批阅的班级");
            for (MsPaperCheck check : checks) {
                check.setTeacherid(handleid);
                check.setMptqid(param.getMptqid());
                sq = msPaperCheckTeacherTaskMapper.getCorrectClassQuestion(check);
                if (sq != null) {
                    paperCheck = check;
                    paperCheck.setMptqid(sq.getMptqid());
                    break;
                }
            }
        }

        if (paperCheck != null) {
            dispenseway = paperCheck.getDispenseway();
            type = paperCheck.getChecktype();
        }
        Integer totalNum = 0;
        Integer checkedNum = 0;
        if (sq != null) {
            sq.setMpid(param.getMpid());
            MsPaperCheckTeacher teacher = msPaperCheckTeacherTaskMapper.getCheckNum(paperCheck);
            totalNum = teacher.getTasknum();
            checkedNum = teacher.getCheckednum();
            Integer checktype = sq.getChecktype();
            Integer firstcid = sq.getFirstcid();
            if (!N_Utils.isTrueInteger(checktype)) {
                if (type.equals(1)) {
                    checktype = 1;
                } else if (N_Utils.isTrueInteger(firstcid) && !handleid.equals(firstcid)) {
                    checktype = 2;
                } else {
                    checktype = 1;
                }
            }
            if (!dispenseway.equals(2)) {
                //更新教师阅卷任务状态
                msPaperCheckTeacherTaskMapper.updateCheckStatus(sq.getMpid(), sq.getMpsbid(), handleid, 2);
            } else {
                //序号
                Integer taskorder = checkedNum + 1;
                sq.setTaskorder(taskorder);
                MsPaperCheckTeacherTask task = new MsPaperCheckTeacherTask();
                task.setMpid(sq.getMpid());
                task.setMblockid(sq.getMblockid());
                task.setMptqid(sq.getMptqid());
                task.setTeacherid(handleid);
                task.setTaskorder(taskorder);
                task.setMpsbid(sq.getMpsbid());
                task.setCheckstate(2);
                task.setChecktype(checktype);
                task.setCreatetime(N_Utils.getSecondTimestamp());
                msPaperCheckTeacherTaskMapper.save(task);
            }
            if (correcttype.equals(3)) {//按题块批阅
                MsPaperStudentBlock block = new MsPaperStudentBlock();
                block.setMpsbid(sq.getMpsbid());
                if (checktype.equals(1)) {
                    block.setFirstcid(handleid);
                } else {
                    block.setSecondcid(handleid);
                }
                block.setChecked(1);
                msPaperStudentBlockMapper.updateByPrimaryKeySelective(block);
            } else {//按试题/班级批阅
                MsPaperStudentQuestion question = new MsPaperStudentQuestion();
                question.setMpsqid(sq.getMpsbid());
                question.setChecked(2);
                if (checktype.equals(1)) {
                    question.setFirstcid(handleid);
                } else {
                    question.setSecondcid(handleid);
                }
                msPaperStudentQuestionMapper.updateByPrimaryKeySelective(question);
            }
            sq.setChecktype(checktype);
            sq.setMpid(paperCheck.getMpid());
        }
        Map map = new HashMap();
        map.put("sq", sq);
        map.put("totalNum", totalNum);
        map.put("checkedNum", checkedNum);
        String msg = "获取成功";
        return new ResultVo(0, msg, map);
    }

    /**
     * @Description 阅卷进度-按试题
     * @Date 2024/11/8 16:18
     * @Author YWX
     * @Param [mpid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listByQuestion(Integer mpid) {
        Integer correcttype = msPaperMapper.getCorrectTypeByMpId(mpid);
        if (!N_Utils.isTrueInteger(correcttype)) {
            throw new ServiceException("该试卷未设置批阅方式");
        }
        return msPaperCheckTeacherTaskMapper.listByQuestion(mpid, correcttype);
    }

    /**
     * @Description 阅卷进度-按试题-查看详情
     * @Date 2024/11/11 9:24
     * @Author YWX
     * @Param [mpid, mblockid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> detailByQuestion(Integer mpid, Integer mblockid) {
        MsPaperCheck check = msPaperCheckMapper.findByMBlockId(mpid, mblockid);
        if (check == null) {
            throw new ServiceException("该试题不存在");
        }
        Integer dispenseway = check.getDispenseway();
        return msPaperCheckTeacherTaskMapper.detailByQuestion(mpid, mblockid, dispenseway, check.getChecktype());
    }

    /**
     * @Description 阅卷进度-按班级
     * @Date 2024/11/15 17:09
     * @Author YWX
     * @Param [mpid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listByClass(Integer mpid) {
        MsPaper paper = msPaperMapper.selectByPrimaryKey(mpid);
        if (!N_Utils.isTrueInteger(paper.getCorrecttype())) {
            throw new ServiceException("该试卷未设置批阅方式");
        }
        return msPaperCheckTeacherTaskMapper.listByClass(mpid, paper.getSubjectid());
    }

    /**
     * @Description 阅卷进度-按班级-查看详情
     * @Date 2024/11/15 17:55
     * @Author YWX
     * @Param [mpid, mblockid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> detailByClass(Integer mpid, Integer mblockid) {
        MsPaperCheck check = msPaperCheckMapper.findByMBlockId(mpid, mblockid);
        if (check == null) {
            throw new ServiceException("该班级不存在");
        }
        Integer dispenseway = check.getDispenseway();
        List<Map> list = msPaperCheckTeacherTaskMapper.detailByClass(mpid, mblockid, dispenseway);
        return setListNum(dispenseway, list);
    }

    /**
     * @Description 批阅
     * @Date 2024/11/12 10:02
     * @Author YWX
     * @Param [param]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void correct(MsPaperCheckVo param) {
        MsPaperCheck check = msPaperCheckMapper.findByMBlockId(param.getMpid(), param.getMblockid());
        if (check == null) {
            throw new ServiceException("该阅卷任务不存在");
        } else if (check.getCheckstate().equals(0)) {
            throw new ServiceException("该阅卷任务未开始");
        } else if (check.getCheckstate().equals(2)) {
            throw new ServiceException("该阅卷任务已暂停");
        }
        Integer checktype = check.getChecktype();
        Integer correcttype = check.getCorrecttype();
        Integer mpsbid = param.getMpsbid();
        Integer hasgood = param.getHasgood();
        Integer hasbad = param.getHasbad();
        Integer hasproblem = param.getHasproblem();
        Integer problemtype = param.getProblemtype();
        String problemcomm = param.getProblemcomm();
        Integer handleid = param.getHandleid();
        Integer probleid = null;
        if (hasproblem.equals(1)) {
            probleid = handleid;
        }
        Double qscore = param.getQscore();
        List<MsPaperBlockQuestion> questions = param.getQuestions();
        int checked = 2;
        Double arbitratescore = param.getArbitratescore();
        String checkscore;
        //仲裁状态0默认1待仲裁2已仲裁
        Integer arbitratestate = null;
        param.setCorrecttype(correcttype);
        MsCheckVo result = msPaperCheckTeacherTaskMapper.getCheckResult(param);
        Integer mpsid = result.getMpsid();
        String stumerge = param.getStumerge();
        if (checktype.equals(1)) {//单评
            if (hasproblem.equals(0)) {
                checked = 3;
            }
            if (correcttype.equals(3)) {//按题块批阅
                checkscore = questions.stream().map(q -> q.getStuscore().toString()).collect(Collectors.joining(";"));
                //题块批阅信息
                MsPaperStudentBlock block = new MsPaperStudentBlock();
                block.setMpsbid(mpsbid);
                block.setChecked(checked);
                block.setFirstcid(handleid);
                block.setFirstcime(N_Utils.getSecondTimestamp());
                String stuscores = questions.stream().map(q -> q.getStuscore().toString()).collect(Collectors.joining(";"));
                block.setFirstccores(stuscores);
                block.setFirstccore(arbitratescore);
                block.setHasgood(hasgood);
                block.setHasbad(hasbad);
                block.setHasproblem(hasproblem);
                block.setProblemtype(problemtype);
                block.setProblemcomm(problemcomm);
                block.setProbleid(probleid);
                block.setStumerge(stumerge);
                msPaperStudentBlockMapper.updateByPrimaryKeySelective(block);
                block.setMpsid(mpsid);
                block.setMblockid(param.getMblockid());

                List<MsPaperStudentQuestion> studentQuestions = new ArrayList<>();
                for (MsPaperBlockQuestion question : questions) {
                    Double stuscore = question.getStuscore();
                    if (N_Utils.isTrueInteger(question.getMptqid())) {
                        MsPaperStudentQuestion studentQuestion = new MsPaperStudentQuestion();
                        studentQuestion.setMptqid(question.getMptqid());
                        studentQuestion.setFirstccore(stuscore);
                        studentQuestion.setStuscore(stuscore);
                        studentQuestions.add(studentQuestion);
                    } else {
                        String[] mptqids = question.getMergeqid().split(",");
                        String[] mergescores = question.getMergescore().split(",");
                        double[] scores = setStuScore(mergescores, stuscore);//计算学生小题得分
                        for (int i = 0; i < mptqids.length; i++) {
                            MsPaperStudentQuestion studentQuestion = new MsPaperStudentQuestion();
                            studentQuestion.setMptqid(N_Utils.obj2Int(mptqids[i]));
                            studentQuestion.setFirstccore(scores[i]);
                            studentQuestion.setStuscore(scores[i]);
                            studentQuestions.add(studentQuestion);
                        }
                    }
                }
                msPaperStudentQuestionMapper.checkByMptqidAndStudentId(studentQuestions, block);//更新学生单题批阅信息
            } else {//按试题批阅
                checkscore = arbitratescore.toString();
                MsPaperStudentQuestion question = new MsPaperStudentQuestion();
                question.setMpsqid(mpsbid);
                question.setChecked(checked);
                question.setFirstcid(handleid);
                question.setFirstcime(N_Utils.getSecondTimestamp());
                question.setFirstccore(arbitratescore);
                question.setHasgood(hasgood);
                question.setHasbad(hasbad);
                question.setHasproblem(hasproblem);
                question.setProblemtype(problemtype);
                question.setProblemcomm(problemcomm);
                question.setProbleid(probleid);
                question.setStuscore(arbitratescore);
                question.setStumerge(stumerge);
                msPaperStudentQuestionMapper.updateByPrimaryKeySelective(question);
            }
        } else {//双评
            Integer firstcime = result.getFirstcime();
            Integer secondcime = result.getSecondctime();
            Double firstccore = result.getFirstccore();
            Double secondcscore = result.getSecondcscore();
            Integer type = param.getChecktype();//批阅情况1一评2二评
            if (type.equals(1)) {
                firstccore = arbitratescore;
            } else {
                secondcscore = arbitratescore;
            }
            boolean corrected = false;
            if ((type.equals(1) && N_Utils.isTrueInteger(secondcime))
                    || (type.equals(2) && N_Utils.isTrueInteger(firstcime))) {
                checked = 3;
                corrected = true;
            }
            Double diffscore = check.getDiffscore();//仲裁分差
            Integer scoreway = check.getScoreway();//分差计算方式1题块总分值2任一给分点
            Integer finalscore = check.getFinalscore();//最终得分取值1不取整(保留2位小数) 2取整-向上取值 3取整-向下取值
            Double roundvalue = check.getRoundvalue();//取整取值间隔
            Double endscore = null;
            if (checked == 3 && hasproblem.equals(0)) {//分差计算方式为题块总分值
                double scoreDiff = MarkingUtil.scoreDiff(firstccore, secondcscore);
                if (scoreway.equals(1) && diffscore.compareTo(scoreDiff) < 0) {//分差大于仲裁分差
                    arbitratestate = 1;
                    checked = 2;
                } else if (scoreway.equals(1)) {
                    double addScore = MarkingUtil.add(firstccore, secondcscore);
                    endscore = getUserScore(finalscore, addScore, roundvalue);
                    if (endscore.compareTo(qscore) > 0) {
                        endscore = qscore;
                    }
                }
            }
            if (correcttype.equals(3)) {//按题块批阅
                //题块批阅信息
                MsPaperStudentBlock block = new MsPaperStudentBlock();
                block.setMpsbid(mpsbid);
                String stuscores = questions.stream().map(q -> q.getStuscore().toString()).collect(Collectors.joining(";"));
                String[] cores = new String[0];
                if (type.equals(1)) {
                    block.setFirstcid(handleid);
                    block.setFirstcime(N_Utils.getSecondTimestamp());
                    block.setFirstccore(arbitratescore);
                    block.setFirstccores(stuscores);
                    if (corrected) cores = result.getSecondcscores().split(";");
                } else {
                    block.setSecondcid(handleid);
                    block.setSecondctime(N_Utils.getSecondTimestamp());
                    block.setSecondcscore(arbitratescore);
                    block.setSecondcscores(stuscores);
                    if (corrected) cores = result.getFirstccores().split(";");
                }
                List<MsPaperStudentQuestion> studentQuestions = new ArrayList<>();
                for (int j = 0; j < questions.size(); j++) {
                    MsPaperBlockQuestion question = questions.get(j);
                    Double stuscore = question.getStuscore();
                    Double bqscore = question.getBqscore();
                    if (N_Utils.isTrueInteger(question.getMptqid())) {
                        MsPaperStudentQuestion studentQuestion = new MsPaperStudentQuestion();
                        studentQuestion.setMptqid(question.getMptqid());
                        if (type.equals(1)) {
                            studentQuestion.setFirstccore(stuscore);
                        } else {
                            studentQuestion.setSecondcscore(stuscore);
                        }
                        if (corrected && hasproblem.equals(0)) {
                            double scoreDiff = MarkingUtil.scoreDiff(stuscore, cores[j]);
                            if (scoreway.equals(2) && diffscore.compareTo(scoreDiff) < 0) {//分差大于仲裁分差
                                arbitratestate = 1;
                                checked = 2;
                                corrected = false;
                            } else if (scoreway.equals(2)) {
                                double addScore = MarkingUtil.add(stuscore, cores[j]);
                                endscore = getUserScore(finalscore, addScore, roundvalue);
                                if (endscore.compareTo(bqscore) > 0) {
                                    endscore = bqscore;
                                }
                                studentQuestion.setStuscore(endscore);
                            }
                        }
                        studentQuestions.add(studentQuestion);
                    } else {
                        String[] mptqids = question.getMergeqid().split(",");
                        String[] mergescores = question.getMergescore().split(",");
                        double[] scores = setStuScore(mergescores, stuscore);//计算学生小题得分
                        String[] cores2 = new String[0];
                        if (corrected) cores2 = cores[j].split(",");
                        for (int i = 0; i < mptqids.length; i++) {
                            MsPaperStudentQuestion studentQuestion = new MsPaperStudentQuestion();
                            studentQuestion.setMptqid(N_Utils.obj2Int(mptqids[i]));
                            if (type.equals(1)) {
                                studentQuestion.setFirstccore(scores[i]);
                            } else {
                                studentQuestion.setSecondcscore(scores[i]);
                            }
                            if (corrected && hasproblem.equals(0)) {
                                double scoreDiff = MarkingUtil.scoreDiff(scores[i], cores2[i]);
                                if (scoreway.equals(2) && diffscore.compareTo(scoreDiff) < 0) {//分差大于仲裁分差
                                    arbitratestate = 1;
                                    checked = 2;
                                    corrected = false;
                                } else if (scoreway.equals(2)) {
                                    double addScore = MarkingUtil.add(scores[i], cores2[i]);
                                    endscore = getUserScore(finalscore, addScore, roundvalue);
                                    double mqscore = Double.parseDouble(mergescores[i]);
                                    if (endscore.compareTo(mqscore) > 0) {
                                        endscore = mqscore;
                                    }
                                    studentQuestion.setStuscore(endscore);
                                }
                            }
                            studentQuestions.add(studentQuestion);
                        }
                    }
                }

                block.setChecked(checked);
                block.setHasgood(hasgood);
                block.setHasbad(hasbad);
                block.setHasproblem(hasproblem);
                block.setProblemtype(problemtype);
                block.setProblemcomm(problemcomm);
                block.setProbleid(probleid);
                block.setMpsid(mpsid);
                block.setMblockid(param.getMblockid());
                block.setArbitratestate(arbitratestate);
                block.setStumerge(stumerge);
                msPaperStudentBlockMapper.updateByPrimaryKeySelective(block);

                msPaperStudentQuestionMapper.checkByMptqidAndStudentId(studentQuestions, block);//更新学生单题批阅信息
                checkscore = stuscores;
            } else {//按试题批阅
                MsPaperStudentQuestion question = new MsPaperStudentQuestion();
                question.setChecked(checked);
                checkscore = arbitratescore.toString();
                if (type.equals(1)) {
                    question.setFirstcid(handleid);
                    question.setFirstcime(N_Utils.getSecondTimestamp());
                    question.setFirstccore(arbitratescore);
                } else {
                    question.setSecondcid(handleid);
                    question.setSecondctime(N_Utils.getSecondTimestamp());
                    question.setSecondcscore(arbitratescore);
                }
                question.setHasgood(hasgood);
                question.setHasbad(hasbad);
                question.setHasproblem(hasproblem);
                question.setProblemtype(problemtype);
                question.setProblemcomm(problemcomm);
                question.setProbleid(probleid);
                question.setStuscore(endscore);
                question.setMpsqid(mpsbid);
                question.setArbitratestate(arbitratestate);
                question.setStumerge(stumerge);
                msPaperStudentQuestionMapper.updateByPrimaryKeySelective(question);
            }
        }
        param.setHasproblem(hasproblem);
        param.setProblemtype(problemtype);
        param.setProblemcomm(problemcomm);
        param.setCheckscore(checkscore);
        msPaperCheckTeacherTaskMapper.correct(param);

        if (checked == 3) msPaperStudentMapper.updateStudentPaperScoreByMpsId(mpsid);//更新学生总分
    }

    //计算学生小题得分
    private double[] setStuScore(String[] mergescores, Double stuscore) {
        double totalScore = 0;
        for (String mergescore : mergescores) {
            totalScore = MarkingUtil.add(mergescore, totalScore);
        }
        double[] scores = new double[mergescores.length];
        for (int i = 0; i < mergescores.length; i++) {
            scores[i] = MarkingUtil.mul(stuscore, MarkingUtil.div(mergescores[i], totalScore));
        }
        return scores;
    }

    //最终得分计算
    private Double getUserScore(Integer finalscore, double addScore, Double roundvalue) {
        double score;
        if (finalscore.equals(1)) {
            score = MarkingUtil.div(addScore, 2);
        } else if (finalscore.equals(2)) {
            score = MarkingUtil.roundUp(addScore, roundvalue);
        } else {
            score = MarkingUtil.roundDown(addScore, roundvalue);
        }
        return score;
    }

    /**
     * @Description 教师阅卷-上一份
     * @Date 2024/11/14 10:35
     * @Author YWX
     * @Param [param]
     * @Return java.util.Map
     **/
    public Map getPreCorrect(MsCheckParam param) {
        setCorrectType(param);//设置批阅类型
        return msPaperCheckTeacherTaskMapper.getPreCorrect(param);
    }

    //设置批阅类型
    private void setCorrectType(MsCheckParam param) {
        Integer correcttype = msPaperMapper.getCorrectTypeByMpId(param.getMpid());
        if (correcttype.equals(1) && !N_Utils.isTrueInteger(param.getMptqid())) {
            throw new ServiceException("考试试题表id不能为空");
        }
        param.setCorrecttype(correcttype);
    }

    /**
     * @Description 教师阅卷-阅卷历史
     * @Date 2024/11/14 14:13
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listCorrectHistory(MsCheckParam param) {
        return msPaperCheckTeacherTaskMapper.listCorrectHistory(param);
    }

    /**
     * @Description 教师阅卷-历史详情
     * @Date 2024/11/14 17:33
     * @Author YWX
     * @Param [param]
     * @Return java.util.Map
     **/
    public Map detailHistory(MsCheckParam param) {
        return msPaperCheckTeacherTaskMapper.detailHistory(param);
    }

    /**
     * @Description 教师阅卷-平均分
     * @Date 2024/11/15 9:11
     * @Author YWX
     * @Param [param]
     * @Return java.util.Map
     **/
    public Map avgScore(MsCheckParam param) {
        setCorrectType(param);//设置批阅类型
        return msPaperCheckTeacherTaskMapper.avgScore(param);
    }

    /**
     * @Description 教师阅卷-待处理数量
     * @Date 2024/11/15 10:01
     * @Author YWX
     * @Param [param]
     * @Return java.util.Map
     **/
    public Map getPendingNum(MsCheckParam param) {
        setParam(param);
        Map map = new HashMap();
        map.put("correctNum", msPaperCheckTeacherTaskMapper.getPendingCorrectNum(param));
        map.put("arbitrateNum", msPaperCheckTeacherTaskMapper.getPendingArbitrateNum(param));
        return map;
    }
}
