package com.xhkjedu.sclass.service.classroom;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.sclass.mapper.classroom.*;
import com.xhkjedu.sclass.model.classroom.*;
import com.xhkjedu.sclass.utils.ArithUtil;
import com.xhkjedu.sclass.vo.classroom.*;
import com.xhkjedu.sclass.vo.paper.CheckClassVo;
import com.xhkjedu.sclass.vo.room.DirectorVo;
import com.xhkjedu.sclass.vo.room.RoomPVo;
import com.xhkjedu.sclass.vo.room.RoomParamVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import com.xhkjedu.vo.system.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

@Slf4j
@Service
public class ClassroomService {
    @Resource
    private ClassroomAskteacherMapper classroomAskteacherMapper;
    @Resource
    private ClassroomActivestudentMapper classroomActivestudentMapper;
    @Resource
    private ClassroomAskstudentMapper classroomAskstudentMapper;
    @Resource
    private ClassroomMapper classroomMapper;
    @Resource
    private ClassroomPaperFileMapper classroomPaperFileMapper;
    @Resource
    private ClassroomPaperMapper classroomPaperMapper;
    @Resource
    private ClassroomPaperQtypeMapper classroomPaperQtypeMapper;
    @Resource
    private ClassroomPaperScantronMapper classroomPaperScantronMapper;
    @Resource
    private ClassroomPaperStudentMapper classroomPaperStudentMapper;
    @Resource
    private ClassroomPaperStudentScantronMapper classroomPaperStudentScantronMapper;
    private static Integer[] QTYPE = {1, 2, 4, 5, 6, 7, 8, 10};

    @Resource
    private ClassroomSignMapper classroomSignMapper;
    @Resource
    private ClassroomFileMapper classroomFileMapper;
    @Resource
    private ClassroomVideoMapper classroomVideoMapper;
    @Resource
    private ClassroomVoteMapper classroomVoteMapper;
    @Resource
    private ClassroomVoteStudentMapper classroomVoteStudentMapper;
    @Resource
    private ClassroomProfileMapper classroomProfileMapper;
    @Resource
    private ClassroomProfileStudentMapper classroomProfileStudentMapper;


    /**
     * 获取批阅信息
     *
     * @return com.xhkjedu.sclass.vo.classroom.RoomCorrectVo
     * @Param [roomid]
     * @Author ywx
     * @Date 2020/9/9 15:37
     **/
    public RoomCorrectVo listCorrect(Long roomid) {
        RoomCorrectVo correct = classroomMapper.listCorrect(roomid);
        List<RoomCorrectCallVo> calls = correct.getCalls();
        if (N_Utils.isListNotEmpty(calls)) {
            for (RoomCorrectCallVo call : calls) {
                call.setCorrectrate(N_Utils.getIntegerDivideAndMulitiply(call.getCorrectnum(), call.getStunum()));
            }
        }
        List<RoomCorrectExamVo> exams = correct.getExams();
        if (N_Utils.isListNotEmpty(exams)) {
            for (RoomCorrectExamVo exam : exams) {
                exam.setCorrectrate(N_Utils.getIntegerDivideAndMulitiply(exam.getCorrectnum(), exam.getStunum()));
            }
        }
        return correct;
    }

    /**
     * 获取提问批改学生列表
     *
     * @return com.xhkjedu.sclass.vo.paper.CheckClassVo
     * @Param [asktid]
     * @Author ywx
     * @Date 2020/9/9 16:38
     **/
    public CheckClassVo listStudentsByAskTid(Long asktid) {
        CheckClassVo classVo = classroomMapper.listStudentsByAskTid(asktid);
        return getCheckClassVo(classVo);
    }

    /**
     * 计算未提交数、批阅进度
     *
     * @return com.xhkjedu.sclass.vo.paper.CheckClassVo
     * @Param [classVo]
     * @Author ywx
     * @Date 2020/9/10 8:56
     **/
    private CheckClassVo getCheckClassVo(CheckClassVo classVo) {
        Integer ytjnum = classVo.getYtjnum();
        classVo.setWtjnum(classVo.getClassnum() - ytjnum);
        if (!N_Utils.isEmptyInteger(ytjnum)) {
            double scale = N_Utils.getIntegerDivideAndMulitiply(classVo.getYpynum(), ytjnum);
            classVo.setScale(scale);
        } else {
            classVo.setScale(0);
        }
        return classVo;
    }

    /**
     * 获取考试批改学生列表
     *
     * @return com.xhkjedu.sclass.vo.paper.CheckClassVo
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/9/9 17:12
     **/
    public CheckClassVo listStudentsByPaperId(Long paperid) {
        CheckClassVo classVo = classroomMapper.listStudentsByPaperId(paperid);
        List<TClassroomPaperFile> files = classroomPaperFileMapper.listObjsByPaperid(paperid, 3);
        classVo.setFiles(files);
        return getCheckClassVo(classVo);
    }

    /**
     * 获取课堂提问客观题详情
     *
     * @return com.xhkjedu.sclass.vo.classroom.ObjectiveVo
     * @Param [asktid]
     * @Author ywx
     * @Date 2020/9/10 11:12
     **/
    public ObjectiveVo callObjective(Long asktid, Integer realstunum) {
        return classroomMapper.callObjective(asktid, realstunum);
    }

    /**
     * 获取课堂考试客观题详情
     *
     * @return com.xhkjedu.sclass.vo.classroom.ObjectiveVo
     * @Param [pscaid]
     * @Author ywx
     * @Date 2020/9/10 11:21
     **/
    public ObjectiveVo examObjective(Long pscaid, Integer realstunum) {
        return classroomMapper.examObjective(pscaid, realstunum);
    }

    /**
     * 获取课堂提问主客观题详情
     *
     * @return com.xhkjedu.sclass.vo.classroom.SubjectiveVo
     * @Param [asktid]
     * @Author ywx
     * @Date 2020/9/10 14:01
     **/
    public SubjectiveVo callSubjective(Long asktid, Integer realstunum) {
        return classroomMapper.callSubjective(asktid, realstunum);
    }

    /**
     * 获取课堂考试主客观题详情
     *
     * @return com.xhkjedu.sclass.vo.classroom.SubjectiveVo
     * @Param [pscaid]
     * @Author ywx
     * @Date 2020/9/10 14:25
     **/
    public SubjectiveVo examSubjective(Long pscaid, Integer realstunum) {
        return classroomMapper.examSubjective(pscaid, realstunum);
    }

    /**
     * 课堂提问批阅
     *
     * @return void
     * @Param [asksid, radiocorrect]
     * @Author ywx
     * @Date 2020/9/10 15:08
     **/
    public void correctCall(Integer asksid, Integer radiocorrect) {
        classroomMapper.correctCall(asksid, radiocorrect);
    }

    /**
     * 修改学生作答记录（教师添加批注）
     *
     * @return void
     * @Param [asksid, studentpic]
     * @Author ywx
     * @Date 2020/9/11 15:08
     **/
    public void updateStudentpic(Integer asksid, String studentpic) {
        classroomAskstudentMapper.updateStudentpic(asksid, studentpic);
    }

    /**
     * 学生课堂回顾列表(学生端)
     *
     * @return java.util.List<com.xhkjedu.sclass.vo.classroom.RoomVo>
     * @Param [room]
     * @Author ywx
     * @Date 2020/9/14 16:32
     **/
    public List<Map> listStuClass(TClassroom room) {
        List<Map> rooms = classroomMapper.listStuClass(room);
        classRoomForList(rooms,2);
        return rooms;
    }


    //学生课堂回顾
    public ResultVo getReportStu(Long roomid, Integer studentid) {
        Map room = classroomMapper.getReportStu(roomid, studentid);
        Integer signnum = classroomMapper.getRoomStudentSigin(roomid, studentid);
        int signstate = 0;
        if (signnum != null && signnum > 0) {
            signstate = 1;
        }
        if (room == null) room = new HashMap();
        room.put("signstate", signstate);
        room.put("videos", classroomVideoMapper.listByRoomId(roomid));
        room.put("votes",classroomVoteMapper.listVoteStuByRoomAndStuid(roomid,studentid));
        room.put("profiles",classroomProfileMapper.listProfileStuByRoomAndStuid(roomid,studentid));
        return new ResultVo(0, "获取学生课堂回顾详情成功", room);
    }

    /**
     * 获取教师指定章节下上过的课堂历史
     * @return java.util.List<com.xhkjedu.sclass.vo.classroom.RoomVo>
     * @Param [room]
     * @Author ywx
     * @Date 2020/6/15 9:19
     **/
    public List<Map> listClassByDirectorId(TClassroom room, UserVo userVo) {
        List<Map> rooms = classroomMapper.listClassByDirectorId(room,userVo);
        classRoomForList(rooms,1);
        return rooms;
    }

    //教师端和学生端均使用方法处理数据
    private void classRoomForList(List<Map> rooms,int utype){
        if(!CollectionUtils.isEmpty(rooms)){
            for(Map r : rooms){
                //互动类型20抢答21随机点名30判断题31选择题32简答题40课堂小测
                List<RoomAskTeacherVo> hdlist = (List<RoomAskTeacherVo>) r.get("hdlist");
                int quesitonnum = 0;//课堂提问
                int callnum = 0;//点名次数
                int asknum = 0;//抢答次数
                if(!CollectionUtils.isEmpty(hdlist)){
                    Map<Integer,Long> hdMap = hdlist.stream().collect(Collectors.groupingBy(RoomAskTeacherVo::getAsktype,Collectors.counting()));

                    for (Map.Entry<Integer, Long> entry : hdMap.entrySet()) {
                        int fkey = entry.getKey();
                        if(fkey == 20){
                            asknum = Math.toIntExact(entry.getValue());
                        }else if(fkey == 21){
                            callnum = Math.toIntExact(entry.getValue());
                        }else{
                            quesitonnum = quesitonnum + Math.toIntExact(entry.getValue());
                        }
                    }
                }
                r.put("quesitonnum",quesitonnum);
                r.put("callnum",callnum);
                r.put("asknum",asknum);
                r.put("hdlist",null);
                if(utype==2){
                    Integer signstate = 0;//0代表学生未参与1代表已参与
                    if(r.get("signstate")!=null){
                        Integer signstate2 = Integer.parseInt(r.get("signstate").toString());
                        if(signstate2 !=null && signstate2 > 0){
                            signstate = 1;
                        }
                    }
                    r.put("signstate",signstate);
                }
            }
        }
    }

    /**
     * 课堂回顾详情
     *
     * @return com.xhkjedu.sclass.vo.ResultVo
     * @Param [roomid]
     * @Author ywx
     * @Date 2020/6/26 9:36
     **/
    public ResultVo getReport(Long roomid) {
        ReportRoomVo room = classroomMapper.getReport(roomid);
        //课堂提问列表
        List<Map> questions = classroomMapper.listQuestionReport(roomid);
        if (room == null) room = new ReportRoomVo();
        room.setQuestions(questions);
        for (Map mq : questions){
            Integer commitnum = Integer.parseInt(mq.get("commitnum").toString());
            Double commitrate = 0.00;
            if(room.getRealstunum() > 0){
                commitrate = N_Utils.getIntegerDivideAndMulitiply(commitnum, room.getRealstunum());
            }
            mq.put("commitrate",commitrate);
        }

        //课堂考试列表
        List<ReportExamVo> exams = classroomMapper.listPaper(roomid);
        if (N_Utils.isListNotEmpty(exams)) {
            List<Long> paperids = exams.stream().map(ReportExamVo::getPaperid).collect(Collectors.toList());
            List<TClassroomPaperFile> files = classroomPaperFileMapper.listFilepath(paperids);
            List<ReportEQuestionVo> questionList = classroomMapper.listExamReport(paperids, exams.get(0).getClassid());
            for (ReportExamVo exam : exams) {
                Integer realstunum = exam.getYtjnum();
                exam.setWtjnum(room.getRealstunum() - realstunum);
                Long paperid = exam.getPaperid();
                List<String> paperfiles = files.stream().filter(m -> m.getPaperid().equals(paperid)).map(TClassroomPaperFile::getFilepath).collect(Collectors.toList());
                exam.setPaperfiles(paperfiles);

                List<ReportEQuestionVo> equestions = questionList.stream().filter(q -> q.getPaperid().equals(paperid)).collect(Collectors.toList());
                for (ReportEQuestionVo equestion : equestions) {
                    Double correctrate = N_Utils.getDoubleDivideAndMulitiply(equestion.getCorrectrate(), realstunum);
                    equestion.setCorrectrate(correctrate);
                    equestion.setCommitrate(N_Utils.getDoubleDivideAndMulitiply(equestion.getCommitrate(), realstunum));
                }
                exam.setQuestions(equestions);
            }
        }
        room.setExams(exams);

        //课堂点名列表
        List<Map> calls = classroomMapper.listCallReport(roomid);
        room.setCalls(calls);

        //课堂抢答列表
        List<Map> asks = classroomMapper.listAskReport(roomid);
        room.setAsks(asks);

        //课堂截图列表
        List<TClassroomFile> files = classroomMapper.listFileReport(roomid);
        room.setFiles(files);

        //课堂学生列表
        List<Map> students = classroomSignMapper.listStudent(roomid);
        room.setStudents(students);
        room.setVideos(classroomVideoMapper.listByRoomId(roomid));

        //课堂投票
        List<Map<String,Object>> votes = classroomVoteMapper.listVoteByRoomid(roomid);
        room.setVotes(votes);

        //课堂资料
        List<Map<String,Object>> profiles = classroomProfileMapper.listProfileByRoomid(roomid);
        room.setProfiles(profiles);


        return new ResultVo(0, "获取课堂回顾详情成功", room);
    }

    //删除课堂图片
    public void delFile(Integer rfid) {
        classroomFileMapper.deleteByPrimaryKey(rfid);
    }

    //班级学生列表
    public List<Map> listStudent(Integer classid, String lsbid) {
        return classroomMapper.listStudent(classid, lsbid);
    }

    /**
     * 批量保存课堂数据
     *
     * @return com.xhkjedu.vo.ResultVo
     * @Param [startclassList, stopclassList, savefileList, askteacherList, askstudentList, signList
     * , paperList, stupaperList, paperFileList, paperQtypeList, paperScantronList]
     * @Author ywx
     * @Date 2022/6/28 16:51
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo batchSaveClass(List<RoomPVo> rooms,List<TClassroom> startclassList, List<TClassroom> stopclassList
            , List<TClassroomFile> savefileList
            , List<TClassroomAskteacher> askteacherList, List<TClassroomAskstudent> askstudentList
            , List<TClassroomSign> signList
            , List<TClassroomPaper> paperList,String nodename, List<TClassroomPaperStudent> stupaperList
            , List<TClassroomPaperFile> paperFileList, List<TClassroomPaperQtype> paperQtypeList
            , List<TClassroomPaperScantron> paperScantronList
            ,List<TClassroomVote> voteList,List<TClassroomVoteStudent> votestuList
            ,List<TClassroomProfile> profileList,List<TClassroomProfileStudent> profileStudentList) {
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(1);
        try {
            if (N_Utils.isListEmpty(startclassList)) return new ResultVo(1, "开始课程数据不能为空");
            List<Integer> classids = startclassList.stream().map(TClassroom::getClassid).distinct().collect(Collectors.toList());
            List<TClassroom> classList = classroomMapper.listStudentNumByClassIds(classids);//根据班级ids获取学生数量
            Map<Integer, Integer> classMap = classList.stream().collect(Collectors.toMap(TClassroom::getClassid, TClassroom::getClassnum));
            startclassList.forEach(r -> r.setClassnum(classMap.get(r.getClassid())));
            classroomMapper.batchSave(startclassList);//批量保存课堂
            if (N_Utils.isListNotEmpty(signList)) classroomSignMapper.insertList(signList);//批量保存学生签到

            if (N_Utils.isListNotEmpty(askteacherList)) classroomAskteacherMapper.batchSave(askteacherList);//批量保存教师互动信息
            if (N_Utils.isListNotEmpty(askstudentList))
                classroomAskstudentMapper.insertList(askstudentList);//批量保存学生互动信息

            if (N_Utils.isListNotEmpty(savefileList)) classroomFileMapper.insertList(savefileList);//批量保存课堂图片

            if (N_Utils.isListNotEmpty(paperList)) classroomPaperMapper.batchSave(paperList);//批量保存堂测
            if (N_Utils.isListNotEmpty(paperFileList)) classroomPaperFileMapper.insertList(paperFileList);//批量保存堂测附件
            if (N_Utils.isListNotEmpty(paperQtypeList)) classroomPaperQtypeMapper.batchSave(paperQtypeList);//批量保存堂测答题卡
            if (N_Utils.isListNotEmpty(paperScantronList))
                classroomPaperScantronMapper.batchSave(paperScantronList);//批量保存堂测答题卡--题型试题

            if (N_Utils.isListNotEmpty(stupaperList)) {
                classroomPaperStudentMapper.insertList(stupaperList);//批量保存堂测--学生作答详情
                List<TClassroomPaperStudentScantron> studentScantronList = new ArrayList<>();//堂测--学生作答详情
                List<TClassroomPaperStudent> studentScoreList = new ArrayList<>();//堂测--学生得分
                setPaperStudentScantron(stupaperList, studentScantronList, studentScoreList, nodename);
                classroomPaperStudentScantronMapper.insertList(studentScantronList);//批量保存堂测--学生作答详情
                classroomPaperStudentMapper.batchUpdateScantronStuScoreAndChecked(studentScoreList);//批量修改学生得分和批改状态
            }

            if(N_Utils.isListNotEmpty(voteList)){
                classroomVoteMapper.insertList(voteList);//投票
            }
            if(N_Utils.isListNotEmpty(votestuList)){
                classroomVoteStudentMapper.insertList(votestuList);//投票--学生投票结果
            }
            if(N_Utils.isListNotEmpty(profileList)){
                classroomProfileMapper.insertList(profileList);
            }

            if(N_Utils.isListNotEmpty(profileStudentList)){
                classroomProfileStudentMapper.insertList(profileStudentList);
            }

            if (N_Utils.isListNotEmpty(stopclassList)) classroomMapper.batchEndClass(stopclassList);//批量结束课堂

            List<Long> roomids = startclassList.stream().map(TClassroom::getRoomid).collect(Collectors.toList());
            classroomMapper.updateBatchRoomRealStunum(roomids);//批量更新班级实际签到学生数量
            for (TClassroom c : startclassList) {
                saveStuActive(c.getRoomid(), c.getClassid(), c.getSchoolid());
            }

            classroomMapper.updateBatchRoomState(classids);//批量结束之前班级的课堂状态
            resultVo.setCode(0);
            resultVo.setMsg("保存成功");
        } catch (Exception e) {
            log.error("批量保存课堂数据失败：" + e.getMessage());
            log.error(JSON.toJSONString(rooms));
            resultVo.setMsg("保存失败");
            throw new RuntimeException(e.getMessage());
        }
        return resultVo;
    }

    //学生作答详情
    private void setPaperStudentScantron(List<TClassroomPaperStudent> stupaperList, List<TClassroomPaperStudentScantron> studentScantronList
            , List<TClassroomPaperStudent> studentScoreList, String nodename) {
        for (TClassroomPaperStudent student : stupaperList) {
            Integer psid = student.getId();
            Double userscore = 0.0;
            Integer checknum = 0;
            List<TClassroomPaperStudentScantron> scantrons = student.getScantrons();
            List<Long> pscaids = scantrons.stream().map(TClassroomPaperStudentScantron::getPscaid).collect(Collectors.toList());
            List<TClassroomPaperScantron> scantronList = classroomPaperScantronMapper.listByIds(pscaids);

            int qorder = 1;//试题序号
            for (TClassroomPaperStudentScantron s : scantrons) {
                if(s.getPaperid() == null || s.getPaperid() == 0){
                    s.setPaperid(student.getPaperid());
                }

                s.setPsid(psid);
                s.setQorder(qorder);
                qorder++;
                //获取原试题情况
                Double qscore = s.getQscore();
                TClassroomPaperScantron scantronBean = scantronList.stream().filter(q -> q.getPscaid().equals(s.getPscaid())).findFirst().orElse(null);
                //判断是否作答1.提交但未作答设置零分，2.作答设置答题状态为2，3.选择题提交为空判错
                String useranswer = s.getUseranswer();
                List<String> userAnswers = JSON.parseArray(useranswer, String.class);
                String psanswer = scantronBean.getPsanswer();
                List<String> psanswers = JSON.parseArray(psanswer, String.class);
                //计算用户得分
                Double userScore = 0.0;
                if (N_Utils.isListEmpty(userAnswers)) {
                    s.setStuscore(userScore);
                    s.setChecked(1);
                    s.setCheckid(0);
                    s.setChecktime(N_Utils.getSecondTimestamp());
                    s.setAnswered(0);
                    checknum++;
                } else {
                    s.setAnswered(1);
                    //自动批改判断得分
                    Integer ctype = scantronBean.getCtype();
                    if (Arrays.asList(QTYPE).contains(ctype)) {
                        checknum++;
                        if (ctype == 1) {//单选
                            if (useranswer.equalsIgnoreCase(psanswer)) {
                                userScore = qscore;
                            }
                        } else if (ctype == 2) {//多选
                            //多选不得分,或者选错不得分，不用处理
                            if (useranswer.length() <= psanswer.length()) {
                                String[] qanswerList = psanswers.get(0).split("");
                                String[] userAnswerList = userAnswers.get(0).split("");
                                int rightNum = 0;//选对个数
                                for (String userAnswer : userAnswerList) {
                                    int right = 0;
                                    for (String qanswer : qanswerList) {
                                        if (qanswer.equals(userAnswer)) {
                                            right = 1;
                                            rightNum += 1;
                                        }
                                    }
                                    if (right == 0) {//选错直接0分，结束循环
                                        rightNum = 0;
                                        break;
                                    }
                                }
                                if (rightNum > 0) {//选对计算得分
                                    if (qanswerList.length == rightNum) {//1.全选对满分
                                        userScore = qscore;
                                    } else if (qanswerList.length > rightNum) {//2.少选得一半分
                                        userScore = ArithUtil.div(qscore, 2, 1);
                                    }
                                }
                            }
                        } else if (ctype == 4 || ctype == 5 || ctype == 6) {
                            //判断题
                            if (useranswer.equalsIgnoreCase(psanswer)) {
                                userScore = qscore;
                            }
                        } else if (ctype == 7 || ctype == 8 || ctype == 10) {//完型填空、阅读理解、任务型阅读
                            //计算每小题分数
                            Double score = ArithUtil.div(qscore, psanswers.size());
                            Double userScoreDouble = 0D;
                            for (int j = 0; j < psanswers.size(); j++) {
                                if (psanswers.get(j).equalsIgnoreCase(userAnswers.get(j))) {
                                    userScoreDouble = ArithUtil.add(userScoreDouble, score);
                                }
                            }
                            userScore = ArithUtil.round(userScoreDouble, 1);
                        }
                        // else if (N_Utils.isNotEmpty(nodename)) {
                        //     List<String> newUserAnswers = new ArrayList<>();
                        //     for (String userAnswer : userAnswers) {
                        //         if(N_Utils.isNotEmpty(userAnswer)){
                        //             userAnswer = nodename + "/" + userAnswer;
                        //         }
                        //         newUserAnswers.add(userAnswer);
                        //     }
                        //     s.setUseranswer(JSON.toJSONString(newUserAnswers));
                        // }
                        if (userScore.compareTo(qscore) == 1) {
                            userScore = qscore;
                        }
                        s.setStuscore(userScore);
                        s.setChecked(1);
                        s.setCheckid(0);
                        s.setChecktime(N_Utils.getSecondTimestamp());
                    }else{
                        if(N_Utils.isNotEmpty(nodename)){
                            List<String> newUserAnswers = new ArrayList<>();
                            for (String userAnswer : userAnswers) {
                                if(N_Utils.isNotEmpty(userAnswer)){
                                    userAnswer = nodename + "/" + userAnswer;
                                }
                                newUserAnswers.add(userAnswer);
                            }
                            s.setUseranswer(JSON.toJSONString(newUserAnswers));
                        }
                    }
                }
                studentScantronList.add(s);

                userscore = ArithUtil.add(userscore, userScore);
            }
            Integer pschecked = 0;
            if (checknum == scantrons.size()) {//如果自动批改试题数量等于试题总量，批改状态改为1已批改
                pschecked = 1;
            }
            TClassroomPaperStudent ps = new TClassroomPaperStudent();
            ps.setPsid(psid);
            ps.setStuscore(userscore);
            ps.setPschecked(pschecked);
            studentScoreList.add(ps);
        }
    }

    /**
     * 保存单个课堂数据
     *
     * @return com.xhkjedu.vo.ResultVo
     * @Param [startclass, stopclass, savefileList, askteacherList, askstudentList, signList
     * , paperList, stupaperList, paperFileList, paperQtypeList, paperScantronList]
     * @Author ywx
     * @Date 2022/6/30 11:12
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo saveClass(RoomPVo r,TClassroom startclass, TClassroom stopclass, List<TClassroomFile> savefileList
            , List<TClassroomAskteacher> askteacherList, List<TClassroomAskstudent> askstudentList, List<TClassroomSign> signList
            , List<TClassroomPaper> paperList, String nodename
            , List<TClassroomPaperStudent> stupaperList, List<TClassroomPaperFile> paperFileList
            , List<TClassroomPaperQtype> paperQtypeList, List<TClassroomPaperScantron> paperScantronList
            , List<TClassroomVote> voteList, List<TClassroomVoteStudent> votestuList
            , List<TClassroomProfile> profileList, List<TClassroomProfileStudent> profileStudentList) {

        ResultVo resultVo = new ResultVo();
        resultVo.setCode(1);
        try {
            if (startclass == null) return new ResultVo(1, "开始课程数据不能为空");
            Integer classid = startclass.getClassid();
            Long roomid = startclass.getRoomid();
            Integer schoolid = startclass.getSchoolid();
            Integer num = classroomMapper.getStudentNumById(classid);//根据班级id获取学生数量
            startclass.setClassnum(num);
            classroomMapper.save(startclass);//批量保存课堂
            if (N_Utils.isListNotEmpty(signList)) classroomSignMapper.insertList(signList);//批量保存学生签到

            if (N_Utils.isListNotEmpty(askteacherList)) classroomAskteacherMapper.batchSave(askteacherList);//批量保存教师互动信息
            if (N_Utils.isListNotEmpty(askstudentList))
                classroomAskstudentMapper.insertList(askstudentList);//批量保存学生互动信息

            if (N_Utils.isListNotEmpty(savefileList)) classroomFileMapper.insertList(savefileList);//批量保存课堂图片

            if (N_Utils.isListNotEmpty(paperList)) classroomPaperMapper.batchSave(paperList);//批量保存堂测
            if (N_Utils.isListNotEmpty(paperFileList)) classroomPaperFileMapper.insertList(paperFileList);//批量保存堂测附件
            if (N_Utils.isListNotEmpty(paperQtypeList)) classroomPaperQtypeMapper.batchSave(paperQtypeList);//批量保存堂测答题卡
            if (N_Utils.isListNotEmpty(paperScantronList))
                classroomPaperScantronMapper.batchSave(paperScantronList);//批量保存堂测答题卡--题型试题

            if (N_Utils.isListNotEmpty(stupaperList)) {
                classroomPaperStudentMapper.insertList(stupaperList);//批量保存堂测--学生作答详情
                List<TClassroomPaperStudentScantron> studentScantronList = new ArrayList<>();//堂测--学生作答详情
                List<TClassroomPaperStudent> studentScoreList = new ArrayList<>();//堂测--学生得分
                setPaperStudentScantron(stupaperList, studentScantronList, studentScoreList, nodename);
                classroomPaperStudentScantronMapper.insertList(studentScantronList);//批量保存堂测--学生作答详情
                classroomPaperStudentMapper.batchUpdateScantronStuScoreAndChecked(studentScoreList);//批量修改学生得分和批改状态
            }

            if(N_Utils.isListNotEmpty(voteList)){
                classroomVoteMapper.insertBatch(voteList);//投票
            }
            if(N_Utils.isListNotEmpty(votestuList)){
                classroomVoteStudentMapper.insertList(votestuList);//投票--学生投票结果
            }

            if(N_Utils.isListNotEmpty(profileList)){
                classroomProfileMapper.insertBatch(profileList);
            }

            if(N_Utils.isListNotEmpty(profileStudentList)){
                classroomProfileStudentMapper.insertList(profileStudentList);
            }

            if (stopclass != null) classroomMapper.endClass(stopclass);//批量结束课堂

            classroomMapper.updateBatchRoomRealStunum(Arrays.asList(roomid));//批量更新班级实际签到学生数量
            classroomActivestudentMapper.saveStuActive(roomid, classid, schoolid, N_Utils.getSecondTimestamp());//更新学生活跃度

            classroomMapper.updateBatchRoomState(Arrays.asList(classid));//批量结束之前班级的课堂状态
            resultVo.setCode(0);
            resultVo.setMsg("保存成功");
        } catch (Exception e) {
            log.error("批量保存课堂数据失败：" + e.getMessage());
            log.error(JSON.toJSONString(r));
            resultVo.setMsg("保存失败");
            throw new RuntimeException("保存失败");
        }
        return resultVo;
    }

    //更新学生活跃度 2022/10/17 课堂活跃度最后统一计算
    public void saveStuActive(Long roomid, Integer classid, Integer schoolid) {
        String asktids = classroomActivestudentMapper.getAsktidsByRoomId(roomid);
        List<TClassroomActivestudent> students = classroomActivestudentMapper.listRoomStu(roomid, classid, asktids);
        if(N_Utils.isListEmpty(students)) return;
        Map<Integer, Integer> rank=new HashMap<>();
        setRank(students,rank);//计算排名
        int timestamp = N_Utils.getSecondTimestamp();
        students.forEach(s -> {
            s.setRoomid(roomid);
            s.setSchoolid(schoolid);
            s.setActiverank(rank.get(s.getActivenum()));
            s.setCreatetime(timestamp);
        });
        classroomActivestudentMapper.insertList(students);
    }

    //计算排名
    private void setRank(List<TClassroomActivestudent> students, Map<Integer, Integer> rank) {
        List<Map.Entry<Integer, List<TClassroomActivestudent>>> gslist2 = students.stream()
                .collect(Collectors.groupingBy(TClassroomActivestudent::getActivenum)).entrySet()
                .stream().sorted((s1, s2) -> -Double.compare(s1.getKey(), s2.getKey())).collect(Collectors.toList());
        Integer index = 1;
        for (Map.Entry<Integer, List<TClassroomActivestudent>> entry : gslist2) {
            for (TClassroomActivestudent cs : entry.getValue()) {
                rank.put(cs.getActivenum(), index);
            }
            index = index + entry.getValue().size();
        }
    }

    /**
     * 根据课堂id获取课堂名称
     *
     * @return java.lang.String
     * @Param [roomid]
     * @Author ywx
     * @Date 2022/6/30 11:21
     **/
    public String getNameById(Long roomid) {
        return classroomMapper.getNameById(roomid);
    }

    /**
     * @Description 提问、堂测、抢答、点名、保存黑板图片、保存批注图片、课堂录制、扫码签到。
     * 以上互动类型只要有一个，即保存课堂回顾
     * @Param [params]
     * @Author ywx
     * @Date 2023/3/9 15:45
     * @return boolean
     **/
    public boolean isSave(List<RoomParamVo> params,Long roomid) {
        String[] rypeList = new String[]{"askteacher", "savefile", "sign"};
        boolean save = false;
        for (String rtype : rypeList) {
            for (RoomParamVo param : params) {
                if (rtype.equals(param.getRtype())) {
                    save = true;
                    break;
                }
            }
            if (save) break;
        }
        if (!save) {
            Integer vnum = classroomVideoMapper.getNumByRoomId(roomid);//课堂录制视频个数
            if (vnum != 0) save = true;
        }
        return save;
    }

    //获取学校年份
    public Integer getSchoolYearBySchoolid(Integer schoolid){
        return classroomMapper.getSchoolYearBySchoolid(schoolid);
    }

    /**
     * @Description 删除
     * @Date 2023/11/17 14:25
     * @Author YWX
     * @Param [roomid]
     * @Return void
     **/
    public void deleteById(Long roomid) {
        classroomMapper.deleteByPrimaryKey(roomid);
    }

    /*
     * @Description 投票详情
     * @Date 2024/6/11 14:31:33
     * @Author WN
     * @Param [voteid]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String,Object>> getVoteDetail(Long voteid){
        List<Map<String,Object>> list = new ArrayList<>();

        List<TClassroomVoteStudent> stuList = classroomVoteMapper.listVoteStus(voteid);

        //获取所有内容
        List<String> voteContList = stuList.stream().map(v -> v.getStuvote().trim()).collect(Collectors.toList());
        voteContList = voteContList.stream().distinct().collect(Collectors.toList());
        int total = stuList.size();
        for(String str : voteContList){
            Map<String,Object> map = new HashMap<>();
            map.put("stuvote",str);

            List<TClassroomVoteStudent> voteList = stuList.stream().filter(v -> str.equals(v.getStuvote().trim())).collect(Collectors.toList());
            int votenum = voteList.size();
            Double rate = N_Utils.getIntegerDivideAndMulitiply(votenum, total);
            map.put("votenum",votenum);
            map.put("rate",rate);
            List<String> stuNames = voteList.stream().map(TClassroomVoteStudent::getUsername).collect(Collectors.toList());
            map.put("stus",stuNames);
            list.add(map);
        }
        return list;
    }

    //获取章节信息
    public DirectorVo getDirectorById(String directorid){
        return classroomMapper.getDirectorById(directorid);
    }
}
