package com.xhkjedu.smarking.service.papercheck;

import com.xhkjedu.smarking.mapper.papercheck.MsPaperCheckMapper;
import com.xhkjedu.smarking.mapper.papercheck.MsPaperCheckTeacherTaskMapper;
import com.xhkjedu.smarking.mapper.stupaper.MsPaperStudentBlockMapper;
import com.xhkjedu.smarking.mapper.stupaper.MsPaperStudentQuestionMapper;
import com.xhkjedu.smarking.model.papercheck.*;
import com.xhkjedu.smarking.model.stupaper.MsPaperStudentBlock;
import com.xhkjedu.smarking.vo.papercheck.MsPaperCheckVo;
import com.xhkjedu.utils.N_Utils;
import org.springframework.stereotype.Service;

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

/**
 * @Description 题块批阅
 * @Author YWX
 * @Date 2024/10/29 17:32
 **/
@Service
public class MsBlockCheckService {
    @Resource
    private MsPaperCheckMapper msPaperCheckMapper;
    @Resource
    private MsPaperCheckTeacherTaskMapper taskMapper;
    @Resource
    private MsPaperStudentBlockMapper studentBlockMapper;
    @Resource
    private MsPaperStudentQuestionMapper studentQuestionMapper;

    //设置一个题块的批卷任务
    public void setOneBlockTask(MsPaperCheck check) {
        Integer dispenseway = check.getDispenseway();//分配方式1平均分配2效率优先3定量分配
        if (!N_Utils.isTrueInteger(dispenseway) || dispenseway.equals(2)) return;
        Integer checktype = check.getChecktype();//评卷方式1单评2双评
        Integer correcttype = check.getCorrecttype();//批阅设置：1按班设置2按题设置3按题块设置
        Integer numtype = check.getNumtype();//分配总数1已上传试卷数2报名学生总数
        Integer mblockid = check.getMblockid();
        Integer mpid = check.getMpid();
        List<MsPaperCheckTeacher> teachers = msPaperCheckMapper.listTeacherByMBlockId(mpid, mblockid);
        //如果没有分配教师，则不分配
        if (N_Utils.isListEmpty(teachers)) return;
        List<MsPaperCheckVo> students = null;
        if (correcttype.equals(2)) {
            students = msPaperCheckMapper.listStudentByMpsqId(mblockid, numtype);
        } else if (correcttype.equals(3)) {
            students = msPaperCheckMapper.listStudentByMBlockId(mblockid, numtype);
        }
        //如果没有学生，则不分配
        if (N_Utils.isListEmpty(students)) return;

        LinkedHashMap<Integer, Integer> ypMap = new LinkedHashMap<>();//一评集合
        LinkedHashMap<Integer, Integer> epMap = new LinkedHashMap<>();//二评集合
        for (MsPaperCheckVo student : students) {
            Integer mpsbid = student.getMpsbid();
            ypMap.put(mpsbid, student.getFirstcid());
            epMap.put(mpsbid, student.getSecondcid());
        }

        if (dispenseway.equals(1)) {//平均分配
            int stuNum = msPaperCheckMapper.getNeedCheckNum(mblockid, correcttype);//需要批改的数量
            if (checktype.equals(2)) {//双评
                stuNum = stuNum * 2;
            }
            int teacherNum = teachers.size();
            //平均分配任务数
            int avgTaskNum = stuNum / teacherNum;
            //余数分配任务数
            int remainderTaskNum = stuNum % teacherNum;
            for (MsPaperCheckTeacher teacher : teachers) {
                int taskNum = avgTaskNum;
                if (remainderTaskNum > 0) {
                    taskNum++;
                    remainderTaskNum--;
                }
                if (!N_Utils.isTrueInteger(taskNum)) continue;
                Integer checkednum = teacher.getCheckednum();
                if (checkednum.compareTo(taskNum) >= 0) {//如果教师已批阅的数量大于等于分配的数量，则不分配
                    teacher.setTasknum(checkednum);
                    //从ypMap获取教师指定的mpsbid集合
                    Integer teacherid = teacher.getTeacherid();
                    List<Integer> ids1 = students.stream().filter(s -> teacherid.equals(s.getFirstcid()) && !N_Utils.isTrueInteger(s.getFirstcime())).map(MsPaperCheckVo::getMpsbid).collect(Collectors.toList());
                    if (N_Utils.isListNotEmpty(ids1)) {
                        for (Integer mpsbid : ids1) {
                            ypMap.put(mpsbid, null);
                        }
                    }
                    if (checktype.equals(2)) {
                        List<Integer> ids2 = students.stream().filter(s -> teacherid.equals(s.getSecondcid()) && !N_Utils.isTrueInteger(s.getSecondctime())).map(MsPaperCheckVo::getMpsbid).collect(Collectors.toList());
                        if (N_Utils.isListNotEmpty(ids2)) {
                            for (Integer mpsbid : ids2) {
                                epMap.put(mpsbid, null);
                            }
                        }
                    }
                } else {
                    teacher.setTasknum(taskNum);
                    setTeacherTask(ypMap, epMap, checktype, correcttype, teacher);
                }
            }
        } else if (dispenseway.equals(3)) {//定量分配
            for (MsPaperCheckTeacher teacher : teachers) {
                int taskNum = teacher.getTasknum();
                if (!N_Utils.isTrueInteger(taskNum)) continue;
                setTeacherTask(ypMap, epMap, checktype, correcttype, teacher);
            }
        }
    }

    //分配阅卷任务
    private void setTeacherTask(LinkedHashMap<Integer, Integer> ypMap, LinkedHashMap<Integer, Integer> epMap
            , Integer checktype, Integer correcttype, MsPaperCheckTeacher teacher) {
        List<MsPaperCheckTeacherTask> tasks = new ArrayList<>();
        List<MsPaperStudentBlock> blocks = new ArrayList<>();

        assignTeacherTask(ypMap, epMap, checktype, teacher, tasks, blocks);//分配阅卷任务
        if (N_Utils.isListNotEmpty(tasks)) {
            taskMapper.batchSave(tasks);
        }
        if (N_Utils.isListNotEmpty(blocks)) {
            if (correcttype.equals(2)) {//按题设置
                studentQuestionMapper.batchUpdateCheckId(blocks);
            } else if (correcttype.equals(3)) {//按题块设置
                studentBlockMapper.batchUpdateCheckId(blocks);
            }
        }
    }

    //设置教师任务
    public void setTeacherTask(Integer teacherid, List<Integer> ids1, Integer type
            , List<MsPaperCheckTeacherTask> tasks, List<MsPaperStudentBlock> blocks) {
        for (Integer mpsbid : ids1) {
            MsPaperCheckTeacherTask task = new MsPaperCheckTeacherTask();
            task.setMpsbid(mpsbid);
            task.setTeacherid(teacherid);
            task.setChecktype(type);
            tasks.add(task);
            MsPaperStudentBlock block = blocks.stream().filter(m -> mpsbid.equals(m.getMpsbid())).findFirst().orElse(null);
            if (block == null) {
                //blocks是否有mpsbid对应的对象
                block = new MsPaperStudentBlock();
                block.setMpsbid(mpsbid);
                blocks.add(block);
            }
            if (type.equals(1)) {
                block.setFirstcid(teacherid);
            } else {
                block.setSecondcid(teacherid);
            }
        }
    }

    //分配阅卷任务
    public void assignTeacherTask(LinkedHashMap<Integer, Integer> ypMap, LinkedHashMap<Integer, Integer> epMap
            , Integer checktype, MsPaperCheckTeacher teacher, List<MsPaperCheckTeacherTask> tasks, List<MsPaperStudentBlock> blocks) {
        Integer teacherid = teacher.getTeacherid();
        int taskNum = teacher.getTasknum();
        //优先分配以前分配给自己未批的任务，在分配未分配的任务
        if (checktype.equals(1)) {//单评
            //从ypMap获取教师指定的mpsbid集合
            List<Integer> ids1 = ypMap.keySet().stream().filter(s -> teacherid.equals(ypMap.get(s))).collect(Collectors.toList());
            int num1 = ids1.size();
            if (taskNum > num1) {
                //从ypMap获取taskNum-num1个值为null的集合
                List<Integer> ids2 = ypMap.keySet().stream().filter(s -> ypMap.get(s) == null).limit(taskNum - num1).collect(Collectors.toList());
                for (Integer mpsbid : ids2) {
                    ypMap.put(mpsbid, teacherid);
                }
            } else if (taskNum < num1) {
                for (int i = taskNum - 1; i < ids1.size(); i++) {
                    Integer mpsbid = ids1.get(i);
                    ypMap.put(mpsbid, null);
                }
            }
        } else {//双评
            //先从ypMap获取教师指定的mpsbid集合，不够的话从epMap获取教师指定的mpsbid集合；还不够的话从ypMap获取剩余的mpsbid集合，还不够的话从epMap获取剩余的mpsbid集合
            List<Integer> ids1 = ypMap.keySet().stream().filter(s -> teacherid.equals(ypMap.get(s))).collect(Collectors.toList());
            List<Integer> ids2 = epMap.keySet().stream().filter(s -> teacherid.equals(epMap.get(s))).collect(Collectors.toList());
            int num1 = ids1.size();
            int num2 = ids2.size();
            if (taskNum > num1 + num2) {
                //从ypMap获取taskNum-num1-num2个值为null的集合
                int num3 = taskNum - num1 - num2;
                //ypMap排除ids2的集合
                LinkedHashMap<Integer, Integer> ypMap2 = new LinkedHashMap<>(ypMap);
                ids2.forEach(ypMap2.keySet()::remove);
                List<Integer> ids3 = ypMap2.keySet().stream().filter(s -> ypMap.get(s) == null).limit(num3).collect(Collectors.toList());
                for (Integer mpsbid : ids3) {
                    ypMap.put(mpsbid, teacherid);
                }
                int num4 = num3 - ids3.size();
                if (num4 > 0) {
                    //epMap排除ids1、ids3的集合
                    LinkedHashMap<Integer, Integer> epMap2 = new LinkedHashMap<>(epMap);
                    ids1.forEach(epMap2.keySet()::remove);
                    ids3.forEach(epMap2.keySet()::remove);
                    List<Integer> ids4 = epMap2.keySet().stream().filter(s -> epMap.get(s) == null).limit(num4).collect(Collectors.toList());
                    for (Integer mpsbid : ids4) {
                        epMap.put(mpsbid, teacherid);
                    }
                }
            } else if (taskNum < num1) {
                setYpAndEpMap(ypMap, epMap, taskNum, ids1, ids2);
            } else if (taskNum < num2) {
                setYpAndEpMap(epMap, ypMap, taskNum, ids2, ids1);
            } else if (taskNum < num1 + num2) {
                int size2 = ids2.size();
                for (int i = size2 - (taskNum - num1) - 1; i < size2; i++) {
                    Integer mpsbid = ids2.get(i);
                    epMap.put(mpsbid, null);
                }
            }
        }

        List<Integer> ids1 = ypMap.keySet().stream().filter(s -> teacherid.equals(ypMap.get(s))).collect(Collectors.toList());
        setTeacherTask(teacherid, ids1, 1, tasks, blocks);
        if (checktype.equals(2)) {//双评
            List<Integer> ids2 = epMap.keySet().stream().filter(s -> teacherid.equals(epMap.get(s))).collect(Collectors.toList());
            setTeacherTask(teacherid, ids2, 2, tasks, blocks);
        }

        if (N_Utils.isListNotEmpty(tasks)) {
            Integer mpid = teacher.getMpid();
            Integer mblockid = teacher.getMblockid();
            Integer assignednum = teacher.getAssignednum();
            int timestamp = N_Utils.getSecondTimestamp();
            for (MsPaperCheckTeacherTask task : tasks) {
                task.setMpid(mpid);
                task.setMblockid(mblockid);
                assignednum++;
                task.setTaskorder(assignednum);
                task.setCreatetime(timestamp);
            }
        }
    }

    //设置ypMap和epMap
    private void setYpAndEpMap(LinkedHashMap<Integer, Integer> ypMap, LinkedHashMap<Integer, Integer> epMap, int taskNum, List<Integer> ids1, List<Integer> ids2) {
        for (int i = taskNum - 1; i < ids1.size(); i++) {
            Integer mpsbid = ids1.get(i);
            ypMap.put(mpsbid, null);
        }
        for (Integer mpsbid : ids2) {
            epMap.put(mpsbid, null);
        }
    }
}
