package com.xhkjedu.smarking.service.papercheck;

import com.xhkjedu.exception.ServiceException;
import com.xhkjedu.smarking.mapper.paper.MsPaperMapper;
import com.xhkjedu.smarking.mapper.papercheck.MsPaperCheckTeacherArbitrateMapper;
import com.xhkjedu.smarking.mapper.stupaper.*;
import com.xhkjedu.smarking.model.paper.MsPaper;
import com.xhkjedu.smarking.model.paper.MsPaperBlockQuestion;
import com.xhkjedu.smarking.model.papercheck.MsPaperCheckTeacher;
import com.xhkjedu.smarking.model.papercheck.MsPaperCheckTeacherArbitrate;
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.MsCheckParam;
import com.xhkjedu.smarking.vo.papercheck.MsPaperCheckVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Description 阅卷仲裁教师任务表 服务实现类
 * @Author auto
 * @Date 2024-11-19
 */
@Service
public class MsPaperCheckTeacherArbitrateService {
    @Resource
    private MsPaperCheckTeacherArbitrateMapper msPaperCheckTeacherArbitrateMapper;
    @Resource
    private MsPaperMapper msPaperMapper;
    @Resource
    private MsPaperStudentBlockMapper msPaperStudentBlockMapper;
    @Resource
    private MsPaperStudentQuestionMapper msPaperStudentQuestionMapper;
    @Resource
    private MsPaperStudentMapper msPaperStudentMapper;

    /**
     * @Description 教师阅卷-待/已仲裁列表
     * @Date 2024/11/15 16:00
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listArbitrate(MsCheckParam param) {
        return msPaperCheckTeacherArbitrateMapper.listArbitrate(param);
    }

    /**
     * @Description 教师阅卷-待/已仲裁详情
     * @Date 2024/11/18 15:57
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> detailArbitrate(MsCheckParam param) {
        MsPaper paper = msPaperMapper.selectByPrimaryKey(param.getMpid());
        param.setCorrecttype(paper.getCorrecttype());
        param.setSubjectid(paper.getSubjectid());
        return msPaperCheckTeacherArbitrateMapper.detailArbitrate(param);
    }

    /**
     * @Description 获取待仲裁任务
     * @Date 2024/11/18 17:24
     * @Author YWX
     * @Param [param]
     * @Return com.xhkjedu.vo.ResultVo
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo getCorrectArbitrate(MsCheckParam param) {
        Integer mpid = param.getMpid();
        MsPaper paper = msPaperMapper.selectByPrimaryKey(mpid);
        Integer correcttype = paper.getCorrecttype();
        if (!N_Utils.isTrueInteger(correcttype)) {
            throw new ServiceException("该试卷未设置批阅方式");
        }
        param.setCorrecttype(correcttype);
        param.setSubjectid(paper.getSubjectid());
        Map sq = msPaperCheckTeacherArbitrateMapper.getCorrectArbitrate(param);

        Integer totalNum = 0;
        Integer checkedNum = 0;
        if (sq != null) {
            Integer mblockid = N_Utils.obj2Int(sq.get("mblockid"));
            param.setMblockid(mblockid);
            MsPaperCheckTeacher teacher = msPaperCheckTeacherArbitrateMapper.getACheckNum(param);
            totalNum = teacher.getTasknum();
            checkedNum = teacher.getCheckednum();

            msPaperCheckTeacherArbitrateMapper.updateArbitrateState(param);

            //序号
            Integer taskorder = checkedNum + 1;
            sq.put("taskorder", taskorder);
            MsPaperCheckTeacherArbitrate arbitrate = new MsPaperCheckTeacherArbitrate();
            arbitrate.setMpid(mpid);
            arbitrate.setMblockid(mblockid);
            arbitrate.setTeacherid(param.getHandleid());
            Integer mpsbid = N_Utils.obj2Int(sq.get("mpsbid"));
            arbitrate.setMpsbid(mpsbid);
            arbitrate.setTaskorder(taskorder);
            arbitrate.setCheckstate(2);
            arbitrate.setCreatetime(N_Utils.getSecondTimestamp());
            msPaperCheckTeacherArbitrateMapper.save(arbitrate);
        }
        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/19 9:26
     * @Author YWX
     * @Param [param]
     * @Return java.util.Map
     **/
    public Map getPreArbitrate(MsCheckParam param) {
        return msPaperCheckTeacherArbitrateMapper.getPreArbitrate(param);
    }

    /**
     * @Description 教师阅卷-仲裁
     * @Date 2024/11/19 14:11
     * @Author YWX
     * @Param [param]
     * @Return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void arbitrate(MsPaperCheckVo param) {
        Integer correcttype = param.getCorrecttype();
        Integer mpsbid = param.getMpsbid();
        Integer handleid = param.getHandleid();
        Double qscore = param.getQscore();
        Double arbitratescore = param.getArbitratescore();
        Integer finalreason = param.getFinalreason();
        Integer hasgood = param.getHasgood();
        Integer hasbad = param.getHasbad();
        Integer mpsid;
        String stumerge = param.getStumerge();
        if (correcttype.equals(3)) {//按题块批阅
            MsPaperStudentBlock block = msPaperStudentBlockMapper.selectByPrimaryKey(mpsbid);
            mpsid = block.getMpsid();
            String firstccores = block.getFirstccores();
            String secondcscores = block.getSecondcscores();
            Double firstccore = block.getFirstccore();
            Double secondcscore = block.getSecondcscore();
            String useScores;
            if (N_Utils.isNotEmpty(firstccores) && N_Utils.isEmpty(secondcscores)) {
                useScores = firstccores;
            } else if (N_Utils.isEmpty(firstccores) && N_Utils.isNotEmpty(secondcscores)) {
                useScores = secondcscores;
            } else {
                double scoreDiff1 = MarkingUtil.scoreDiff(firstccore, arbitratescore);
                double scoreDiff2 = MarkingUtil.scoreDiff(secondcscore, arbitratescore);
                // 根据差值计算得分
                if (scoreDiff1 < scoreDiff2) {
                    // 如果一评的差值小于二评，则使用一评分
                    useScores = firstccores;
                } else if (scoreDiff1 > scoreDiff2) {
                    // 如果二评的差值小于一评，则使用二评分
                    useScores = secondcscores;
                } else {
                    // 如果差值相同，使用一评和二评中的较高分
                    if (firstccore.compareTo(secondcscore) > 0) {
                        useScores = firstccores;
                    } else {
                        useScores = secondcscores;
                    }
                }
            }
            String[] cores = useScores.split(";");
            List<MsPaperBlockQuestion> questions = param.getQuestions();
            List<MsPaperStudentQuestion> studentQuestions = new ArrayList<>();
            for (int j = 0; j < questions.size(); j++) {
                MsPaperBlockQuestion question = questions.get(j);
                Double stuscore = question.getStuscore();
                if (N_Utils.isTrueInteger(question.getMptqid())) {
                    MsPaperStudentQuestion studentQuestion = new MsPaperStudentQuestion();
                    studentQuestion.setMptqid(question.getMptqid());
                    studentQuestion.setStuscore(MarkingUtil.avg(stuscore, cores[j]));
                    studentQuestion.setArbitratescore(stuscore);
                    studentQuestions.add(studentQuestion);
                } else {
                    String[] mptqids = question.getMergeqid().split(",");
                    String[] mergestuscore = question.getMergestuscore().split(",");
                    double[] scores = new double[mergestuscore.length];
                    int last = mergestuscore.length - 1;
                    double score = 0;
                    for (int i = 0; i < mergestuscore.length; i++) {
                        scores[i] = MarkingUtil.mul(MarkingUtil.div(mergestuscore[i], qscore), stuscore);
                        score = MarkingUtil.add(score, scores[i]);
                        if (i == last) {
                            scores[i] = MarkingUtil.sub(stuscore, score);
                        }
                    }
                    String[] cores2 = cores[j].split(",");
                    for (int i = 0; i < mptqids.length; i++) {
                        MsPaperStudentQuestion studentQuestion = new MsPaperStudentQuestion();
                        studentQuestion.setMptqid(N_Utils.obj2Int(mptqids[i]));
                        studentQuestion.setStuscore(MarkingUtil.avg(scores[i], cores2[i]));
                        studentQuestion.setArbitratescore(scores[i]);
                        studentQuestions.add(studentQuestion);
                    }
                }
            }

            //更新仲裁结果
            MsPaperStudentBlock psq = new MsPaperStudentBlock();
            psq.setMpsbid(mpsbid);
            psq.setChecked(3);
            psq.setArbitrateid(handleid);
            psq.setArbitratetime(N_Utils.getSecondTimestamp());
            psq.setArbitratescore(arbitratescore);
            psq.setArbitratestate(3);
            psq.setHasfinal(1);
            psq.setFinalreason(finalreason);
            psq.setHasgood(hasgood);
            psq.setHasbad(hasbad);
            psq.setStumerge(stumerge);
            msPaperStudentBlockMapper.updateByPrimaryKeySelective(psq);
            msPaperStudentQuestionMapper.checkByMptqidAndStudentId(studentQuestions, psq);
        } else {
            MsPaperStudentQuestion question = msPaperStudentQuestionMapper.selectByPrimaryKey(mpsbid);
            mpsid = question.getMpsid();
            Double firstccore = question.getFirstccore();
            Double secondcscore = question.getSecondcscore();
            double scoreDiff1 = MarkingUtil.scoreDiff(firstccore, arbitratescore);
            double scoreDiff2 = MarkingUtil.scoreDiff(secondcscore, arbitratescore);
            double finalScore;
            // 根据差值计算得分
            if (scoreDiff1 < scoreDiff2) {
                // 如果一评的差值小于二评，则返回一评和仲裁分的平均分
                finalScore = MarkingUtil.avg(arbitratescore, firstccore);
            } else if (scoreDiff1 > scoreDiff2) {
                // 如果二评的差值小于一评，则返回二评和仲裁分的平均分
                finalScore = MarkingUtil.avg(arbitratescore, secondcscore);
            } else {
                // 如果差值相同，选取一评和二评中的较高分与仲裁分的平均分
                double higherScore = Math.max(firstccore, secondcscore);
                finalScore = MarkingUtil.avg(arbitratescore, higherScore);
            }

            //更新仲裁结果
            MsPaperStudentQuestion psq = new MsPaperStudentQuestion();
            psq.setMpsqid(mpsbid);
            psq.setChecked(3);
            psq.setArbitrateid(handleid);
            psq.setArbitratetime(N_Utils.getSecondTimestamp());
            psq.setArbitratescore(arbitratescore);
            psq.setStuscore(finalScore);
            psq.setArbitratestate(3);
            psq.setHasfinal(1);
            psq.setFinalreason(finalreason);
            psq.setHasgood(hasgood);
            psq.setHasbad(hasbad);
            psq.setStumerge(stumerge);
            msPaperStudentQuestionMapper.updateByPrimaryKeySelective(psq);
        }
        msPaperCheckTeacherArbitrateMapper.correct(param);

        msPaperStudentMapper.updateStudentPaperScoreByMpsId(mpsid);//更新学生总分
    }

    /**
     * @Description 待仲裁列表
     * @Date 2024/11/19 16:02
     * @Author YWX
     * @Param [mpid, handleid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listPendingArbitrate(Integer mpid, Integer handleid, Integer usertype) {
        MsCheckParam param = new MsCheckParam();
        param.setMpid(mpid);
        param.setHandleid(handleid);
        param.setUsertype(usertype);
        Integer correctType = msPaperMapper.getCorrectTypeByMpId(param.getMpid());
        if (correctType.equals(3)) {
            return msPaperCheckTeacherArbitrateMapper.listBlockArbitrate(param);//学科组长-待仲裁题块列表
        } else {
            return msPaperCheckTeacherArbitrateMapper.listQuestionArbitrate(param);//学科组长-待仲裁试题列表
        }
    }

    /**
     * @Description 学科组长-获取待仲裁任务
     * @Date 2024/11/19 16:15
     * @Author YWX
     * @Param [param]
     * @Return com.xhkjedu.vo.ResultVo
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo getCorrectLeaderArbitrate(MsCheckParam param) {
        Integer mpid = param.getMpid();
        MsPaper paper = msPaperMapper.selectByPrimaryKey(mpid);
        Integer correcttype = paper.getCorrecttype();
        if (!N_Utils.isTrueInteger(correcttype)) {
            throw new ServiceException("该试卷未设置批阅方式");
        }
        param.setCorrecttype(correcttype);
        param.setSubjectid(paper.getSubjectid());
        Map sq = msPaperCheckTeacherArbitrateMapper.getCorrectLeaderArbitrate(param);

        Integer totalNum = 0;
        Integer checkedNum = 0;
        if (sq != null) {
            Integer mblockid = N_Utils.obj2Int(sq.get("mblockid"));
            param.setMblockid(mblockid);
            MsPaperCheckTeacher teacher = msPaperCheckTeacherArbitrateMapper.getACheckNum(param);
            totalNum = teacher.getTasknum();
            checkedNum = teacher.getCheckednum();
            msPaperCheckTeacherArbitrateMapper.updateArbitrateState(param);

            //序号
            Integer taskorder = checkedNum + 1;
            sq.put("taskorder", taskorder);
            MsPaperCheckTeacherArbitrate task = new MsPaperCheckTeacherArbitrate();
            task.setMpid(mpid);
            task.setMblockid(mblockid);
            task.setTeacherid(param.getHandleid());
            task.setTaskorder(taskorder);
            task.setMpsbid(N_Utils.obj2Int(sq.get("mpsbid")));
            task.setCheckstate(2);
            task.setCreatetime(N_Utils.getSecondTimestamp());
            msPaperCheckTeacherArbitrateMapper.save(task);
        }
        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/19 16:42
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listArbitrateHistory(MsCheckParam param) {
        return msPaperCheckTeacherArbitrateMapper.listArbitrateHistory(param);
    }

    /**
     * @Description 仲裁历史详情
     * @Date 2024/11/20 9:13
     * @Author YWX
     * @Param [param]
     * @Return java.util.Map
     **/
    public Map detailHistory(MsCheckParam param) {
        return msPaperCheckTeacherArbitrateMapper.detailHistory(param);
    }

    /**
     * @Description 初评分
     * @Date 2024/11/20 9:31
     * @Author YWX
     * @Param [param]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> getScore(MsCheckParam param) {
        List<Map> score = msPaperCheckTeacherArbitrateMapper.getScore(param);
        for (Map map : score) {
            double diffscore1 = 0;
            double diffscore2 = 0;
            if (map.get("scoreway").equals(2)) {
                Object qscore = map.get("qscore");
                Object diffscore = map.get("diffscore");
                double scoreDiff1 = MarkingUtil.scoreDiff(map.get("firstccore"), qscore);
                double scoreDiff2 = MarkingUtil.scoreDiff(map.get("secondcscore"), qscore);
                diffscore1 = MarkingUtil.sub(diffscore, scoreDiff1);
                diffscore2 = MarkingUtil.sub(diffscore, scoreDiff2);
            }
            map.put("diffscore1", diffscore1);
            map.put("diffscore2", diffscore2);
        }
        return score;
    }
}
