package com.xhkjedu.sapi.service.component;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.sapi.mapper.component.ComponentMapper;
import com.xhkjedu.sapi.mapper.gradeclass.ClassMapper;
import com.xhkjedu.sapi.mapper.subjectbook.SubjectMapper;
import com.xhkjedu.sapi.mapper.system.UserMapper;
import com.xhkjedu.sapi.model.subjectbook.TSubject;
import com.xhkjedu.sapi.utils.ApiUtil;
import com.xhkjedu.sapi.vo.analyze.work.SchoolWorkSubjectVo;
import com.xhkjedu.sapi.vo.component.ComponentParams;
import com.xhkjedu.sapi.vo.component.ExamInfoVo;
import com.xhkjedu.sapi.vo.component.PaperStudentQuestionVo;
import com.xhkjedu.sapi.vo.component.StudyStatisticVo;
import com.xhkjedu.sapi.vo.gradeclass.ClassVo;
import com.xhkjedu.sapi.vo.notice.NoticeVo;
import com.xhkjedu.sapi.vo.subjectbook.SubjectVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.exam.EPaperVo;
import com.xhkjedu.vo.paper.PaperClassVo;
import com.xhkjedu.vo.paper.PaperListVo;
import com.xhkjedu.vo.system.UserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description：组件内容
 * @Author: WN
 * @Date: 2024/7/19 15:33:43
 **/
@Service
public class ComponentService {
    @Resource
    private ComponentMapper componentMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private SubjectMapper subjectMapper;
    @Resource
    private ClassMapper classMapper;


    /*
     * @Description 待批作业
     * @Date 2024/7/19 16:16:49
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<com.xhkjedu.vo.paper.PaperListVo>
     **/
    public List<Map<String,Object>> listCorrectPages(Integer userid, Integer limitSize) {
        return componentMapper.listCorrectPages(userid, limitSize);
    }

    /*
     * @Description 作业-我的
     * @Date 2024/7/25 16:25:33
     * @Author WN
     * @Param [params]
     * @Return java.util.List<com.xhkjedu.vo.paper.PaperListVo>
     **/
    public List<Map<String,Object>> listPaperForMy(ComponentParams params) {
        Integer schoolid = userMapper.getSchoolIdByUserId(params.getUserid());
        params.setSchoolid(schoolid);
        return componentMapper.listPaperForMy(params);
    }

    public List<PaperListVo> setPaperListVo(List<PaperListVo> list) {
        for (PaperListVo p : list) {
            if (p.getPaperstate() == 21) {// 未布置
                p.setClasses(null);
                p.setChecklist(null);
            } else {
                List<Map> schools = p.getSchools();
                List<PaperClassVo> classes = new ArrayList<>();
                for (Map school : schools) {
                    List<PaperClassVo> classList = (List<PaperClassVo>) school.get("classes");
                    classes.addAll(classList);
                    for (PaperClassVo c : classList) {
                        if (!N_Utils.isEmptyInteger(c.getClassnum())) {
                            c.setWtjnum(c.getClassnum() - c.getYtjnum());
                        }
                    }
                }
                p.setClassnum(classes.stream().mapToInt(c -> c.getClassnum()).sum());
                p.setYtjnum(classes.stream().mapToInt(c -> c.getYtjnum()).sum());
                p.setYpgnum(classes.stream().mapToInt(c -> c.getYpgnum()).sum());
            }
        }
        return list;
    }

    /*
     * @Description 通知公告
     * @Date 2024/7/19 16:28:05
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<com.xhkjedu.sapi.vo.notice.NoticeVo>
     **/
    public List<NoticeVo> ListNotices(Integer userid, Integer limitSize) {
        return componentMapper.listNotices(userid, limitSize);
    }

    /*
     * @Description 教学教研
     * @Date 2024/7/19 16:32:47
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listResearchs(Integer userid, Integer limitSize) {
        return componentMapper.listResearchs(userid, limitSize, N_Utils.getSecondTimestamp());
    }

    /*
     * @Description 我的空间
     * @Date 2024/7/19 16:57:17
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listMySpaces(Integer userid, Integer limitSize) {
        return componentMapper.listMySpaces(userid, limitSize);
    }

    /*
     * @Description 校本资源
     * @Date 2024/7/19 17:23:48
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listSchoolResources(Integer userid, Integer limitSize) {
        Integer schoolid = userMapper.getSchoolIdByUserId(userid);
        return componentMapper.listSchoolResources(userid, limitSize, schoolid);
    }

    /*
     * @Description 同步视频
     * @Date 2024/7/19 17:35:59
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listVideos(Integer userid, Integer limitSize) {
        Integer schoolid = userMapper.getSchoolIdByUserId(userid);
        return componentMapper.listVideos(userid, limitSize, schoolid);
    }

    /*
     * @Description 预习
     * @Date 2024/7/22 9:26:20
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listGuides(Integer userid, Integer limitSize) {
        return componentMapper.listGuides(userid, limitSize);
    }

    /*
     * @Description 背诵
     * @Date 2024/7/22 9:27:12
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listReciteds(Integer userid, Integer limitSize) {
        return componentMapper.listReciteds(userid, limitSize);
    }

    /*
     * @Description 课堂回顾
     * @Date 2024/7/22 10:15:44
     * @Author WN
     * @Param [userid, limitSize]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listClassrooms(Integer userid, Integer limitSize) {
        return componentMapper.listClassrooms(userid, limitSize);
    }


    /*
     * @Description 预习统计-班级
     * @Date 2024/7/22 12:28:24
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listGuidesStatisticClass(ComponentParams params) {
        // 设置参数
        setSchoolAndWeekTimeForStudy(params);
        List<ClassVo> teacherClassList = new ArrayList<>();
        if(params.getUsertype() == 1){
            //获取教师权限下班级
            teacherClassList = classMapper.listTeacherClass(params.getUserid(), params.getSchoolid());
            String classids = teacherClassList.stream().map(c -> String.valueOf(c.getClassid())).collect(Collectors.joining(","));
            params.setClassids(classids);
        }

        List<StudyStatisticVo> list = componentMapper.listGuidesStatisticClass(params);
        // 获取所有班级
        Map<Integer, List<StudyStatisticVo>> mapClass = list.stream().collect(Collectors.groupingBy(StudyStatisticVo::getClassid));

        List<Map<String, Object>> maps = new ArrayList<>();
        if(params.getUsertype() == 0){ //学校管理员
            for (Map.Entry<Integer, List<StudyStatisticVo>> entry : mapClass.entrySet()) {
                List<StudyStatisticVo> classList = entry.getValue();
                // 获取班级总数量
                Integer totalnum = classList.stream().mapToInt(StudyStatisticVo::getTotalnum).sum();
                Integer commitnum = classList.stream().mapToInt(StudyStatisticVo::getCommitnum).sum();
                double commitRate = N_Utils.getIntegerDivideAndMulitiply(commitnum, totalnum);// 预习率

                StudyStatisticVo firstVo = classList.get(0);
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("gradeid", firstVo.getGradeid());
                map.put("classid", firstVo.getClassid());
                map.put("classname", firstVo.getClassname());
                map.put("weeknum", classList.size());
                map.put("commitRate", commitRate);
                // 获取班级当天发布次数
                List<StudyStatisticVo> todayClassList =
                        classList.stream().filter(s -> ApiUtil.getLocalDateByStamp(s.getCreatetime()).equals(LocalDate.now())).collect(Collectors.toList());
                int daynum = 0;
                if (todayClassList.size() > 0) {
                    daynum = todayClassList.size();
                }
                map.put("daynum", daynum);
                maps.add(map);
            }
        }else {
            for(ClassVo classVo: teacherClassList){
                Integer totalnum = 0;
                Integer commitnum = 0;
                double commitRate = 0;
                int weeknum = 0;
                int daynum = 0;
                if(mapClass.containsKey(classVo.getClassid())){
                    List<StudyStatisticVo> classList = mapClass.get(classVo.getClassid());

                    weeknum = classList.size();
                    totalnum = classList.stream().mapToInt(StudyStatisticVo::getTotalnum).sum();
                    commitnum = classList.stream().mapToInt(StudyStatisticVo::getCommitnum).sum();
                    commitRate = N_Utils.getIntegerDivideAndMulitiply(commitnum, totalnum);// 预习率

                    // 获取班级当天发布次数
                    List<StudyStatisticVo> todayClassList =
                            classList.stream().filter(s -> ApiUtil.getLocalDateByStamp(s.getCreatetime()).equals(LocalDate.now())).collect(Collectors.toList());
                    if (todayClassList.size() > 0) {
                        daynum = todayClassList.size();
                    }
                }

                Map<String, Object> map = new LinkedHashMap<>();
                map.put("gradeid", classVo.getGradeid());
                map.put("classid", classVo.getClassid());
                map.put("classname", classVo.getClassname());
                map.put("weeknum", weeknum);
                map.put("daynum", daynum);
                map.put("commitRate", commitRate);
                maps.add(map);
            }
        }

        return maps;
    }

    /*
     * @Description 预习统计-科目
     * @Date 2024/7/22 14:20:29
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listGuidesStatisticSubject(ComponentParams params) {
        // 设置参数
        setSchoolAndWeekTimeForStudy(params);
        List<StudyStatisticVo> list = componentMapper.listGuidesStatisticSubject(params);
        // 获取所有科目
        Map<String, List<StudyStatisticVo>> mapSubject = list.stream().collect(Collectors.groupingBy(StudyStatisticVo::getSubjectid));
        // 获取学校科目
        TSubject subject = new TSubject();
        subject.setLevel(params.getSchoollevel());
        subject.setSchoolid(params.getSchoolid());
        List<SubjectVo> subjectVos = subjectMapper.listSubjectsForSel(subject);

        List<Map<String, Object>> maps = new ArrayList<>();
        for (SubjectVo subjectVo : subjectVos) {

            int totalnum = 0;
            int commitnum = 0;
            double commitRate = 0;
            int daynum = 0;
            int weeknum = 0;
            if (mapSubject.containsKey(subjectVo.getSubjectid())) {
                List<StudyStatisticVo> subjectList = mapSubject.get(subjectVo.getSubjectid());
                weeknum = subjectList.size();
                // 获取班级总数量
                totalnum = subjectList.stream().mapToInt(StudyStatisticVo::getTotalnum).sum();
                commitnum = subjectList.stream().mapToInt(StudyStatisticVo::getCommitnum).sum();
                commitRate = N_Utils.getIntegerDivideAndMulitiply(commitnum, totalnum);// 预习率
                // 获取班级当天发布次数
                List<StudyStatisticVo> todayClassList =
                        subjectList.stream().filter(s -> ApiUtil.getLocalDateByStamp(s.getCreatetime()).equals(LocalDate.now())).collect(Collectors.toList());
                if (todayClassList != null && todayClassList.size() > 0) {
                    daynum = todayClassList.size();
                }
            }

            Map<String, Object> map = new HashMap<>();
            map.put("subjectname", subjectVo.getSubjectname());
            map.put("weeknum", weeknum);
            map.put("daynum", daynum);
            map.put("commitRate", commitRate);
            maps.add(map);
        }
        return maps;
    }

    // 设置参数
    private void setSchoolAndWeekTimeForStudy(ComponentParams params) {
        // 获取用户学校及用户类型
        UserVo user = userMapper.getUserAndSchoolInfo(params.getUserid());
        params.setUsertype(user.getUsertype());
        params.setSchoolid(user.getSchoolid());
        params.setSchoollevel(user.getSchoollevel());
        // 获取当前日期所在周的起止时间（近一周）
        long[] dateWeek = ApiUtil.getNowWeekOfTimestamp();
        params.setStarttime(dateWeek[0]);
        params.setStoptime(dateWeek[1]);
    }

    /*
     * @Description 作业统计-班级
     * @Date 2024/7/22 15:32:13
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listPapersStatisticClass(ComponentParams params) {
        // 设置参数
        setSchoolAndWeekTimeForStudy(params);

        List<ClassVo> teacherClassList = new ArrayList<>();
        if(params.getUsertype() == 1){
            //获取教师权限下班级
            teacherClassList = classMapper.listTeacherClass(params.getUserid(), params.getSchoolid());
            String classids = teacherClassList.stream().map(c -> String.valueOf(c.getClassid())).collect(Collectors.joining(","));
            params.setClassids(classids);
        }

        List<StudyStatisticVo> list = componentMapper.listPapersStatisticClass(params);
        // 获取所有班级
        Map<Integer, List<StudyStatisticVo>> mapClass = list.stream().collect(Collectors.groupingBy(StudyStatisticVo::getClassid));

        List<Map<String, Object>> maps = new ArrayList<>();
        if(params.getUsertype() == 0){
            for (Map.Entry<Integer, List<StudyStatisticVo>> entry : mapClass.entrySet()) {
                List<StudyStatisticVo> classList = entry.getValue();
                // 获取班级总数量
                Integer totalnum = classList.stream().mapToInt(StudyStatisticVo::getTotalnum).sum();
                Integer commitnum = classList.stream().mapToInt(StudyStatisticVo::getCommitnum).sum();
                Integer checknum = classList.stream().mapToInt(StudyStatisticVo::getChecknum).sum();
                double commitRate = N_Utils.getIntegerDivideAndMulitiply(commitnum, totalnum);// 提交率
                double checkRate = N_Utils.getIntegerDivideAndMulitiply(checknum, commitnum);// 批改率

                StudyStatisticVo firstVo = classList.get(0);
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("gradeid", firstVo.getGradeid());
                map.put("classid", firstVo.getClassid());
                map.put("classname", firstVo.getClassname());
                map.put("weeknum", classList.size());
                map.put("commitRate", commitRate);
                map.put("checkRate", checkRate);
                // 获取班级当天发布次数
                List<StudyStatisticVo> todayClassList =
                        classList.stream().filter(s -> ApiUtil.getLocalDateByStamp(s.getCreatetime()).equals(LocalDate.now())).collect(Collectors.toList());
                int daynum = 0;
                if (todayClassList != null && todayClassList.size() > 0) {
                    daynum = todayClassList.size();
                }
                map.put("daynum", daynum);
                maps.add(map);
            }
        }else {
            for(ClassVo classVo: teacherClassList){
                double commitRate = 0;
                double checkRate = 0;
                int weeknum = 0;
                int daynum = 0;
                if(mapClass.containsKey(classVo.getClassid())){
                    List<StudyStatisticVo> classList = mapClass.get(classVo.getClassid());

                    weeknum = classList.size();
                    // 获取班级总数量
                    Integer totalnum = classList.stream().mapToInt(StudyStatisticVo::getTotalnum).sum();
                    Integer commitnum = classList.stream().mapToInt(StudyStatisticVo::getCommitnum).sum();
                    Integer checknum = classList.stream().mapToInt(StudyStatisticVo::getChecknum).sum();
                    commitRate = N_Utils.getIntegerDivideAndMulitiply(commitnum, totalnum);// 提交率
                    checkRate = N_Utils.getIntegerDivideAndMulitiply(checknum, commitnum);// 批改率

                    // 获取班级当天发布次数
                    List<StudyStatisticVo> todayClassList =
                            classList.stream().filter(s -> ApiUtil.getLocalDateByStamp(s.getCreatetime()).equals(LocalDate.now())).collect(Collectors.toList());
                    if (todayClassList.size() > 0) {
                        daynum = todayClassList.size();
                    }
                }

                Map<String, Object> map = new LinkedHashMap<>();
                map.put("gradeid", classVo.getGradeid());
                map.put("classid", classVo.getClassid());
                map.put("classname", classVo.getClassname());
                map.put("weeknum", weeknum);
                map.put("daynum", daynum);
                map.put("commitRate", commitRate);
                map.put("checkRate", checkRate);
                maps.add(map);
            }
        }

        return maps;
    }

    /*
     * @Description 作业统计-科目
     * @Date 2024/7/22 15:35:31
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listPapersStatisticSubject(ComponentParams params) {
        // 设置参数
        setSchoolAndWeekTimeForStudy(params);
        List<StudyStatisticVo> list = componentMapper.listPapersStatisticSubject(params);
        // 获取所有科目
        Map<String, List<StudyStatisticVo>> mapSubject = list.stream().collect(Collectors.groupingBy(StudyStatisticVo::getSubjectid));
        // 获取学校科目
        TSubject subject = new TSubject();
        subject.setLevel(params.getSchoollevel());
        subject.setSchoolid(params.getSchoolid());
        List<SubjectVo> subjectVos = subjectMapper.listSubjectsForSel(subject);

        List<Map<String, Object>> maps = new ArrayList<>();
        for (SubjectVo subjectVo : subjectVos) {

            int totalnum = 0;
            int commitnum = 0;
            double commitRate = 0;
            double checkRate = 0;
            int daynum = 0;
            int weeknum = 0;
            if (mapSubject.containsKey(subjectVo.getSubjectid())) {
                List<StudyStatisticVo> subjectList = mapSubject.get(subjectVo.getSubjectid());
                weeknum = subjectList.size();
                // 获取班级总数量
                totalnum = subjectList.stream().mapToInt(StudyStatisticVo::getTotalnum).sum();
                commitnum = subjectList.stream().mapToInt(StudyStatisticVo::getCommitnum).sum();
                int checknum = subjectList.stream().mapToInt(StudyStatisticVo::getChecknum).sum();
                commitRate = N_Utils.getIntegerDivideAndMulitiply(commitnum, totalnum);// 预习率
                checkRate = N_Utils.getIntegerDivideAndMulitiply(checknum, commitnum);
                // 获取班级当天发布次数
                List<StudyStatisticVo> todayClassList =
                        subjectList.stream().filter(s -> ApiUtil.getLocalDateByStamp(s.getCreatetime()).equals(LocalDate.now())).collect(Collectors.toList());
                if (todayClassList != null && todayClassList.size() > 0) {
                    daynum = todayClassList.size();
                }
            }

            Map<String, Object> map = new HashMap<>();
            map.put("subjectname", subjectVo.getSubjectname());
            map.put("weeknum", weeknum);
            map.put("daynum", daynum);
            map.put("commitRate", commitRate);
            map.put("checkRate", checkRate);
            maps.add(map);
        }
        return maps;
    }

    /*
     * @Description 直播巡课
     * @Date 2024/7/22 16:47:52
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public Map<String, Object> listLivePatrol(ComponentParams params) {
        // 获取用户学校及用户类型
        UserVo user = userMapper.getUserAndSchoolInfo(params.getUserid());
        params.setUsertype(user.getUsertype());
        params.setSchoolid(user.getSchoolid());

        // 获取教师任教班级
        if (user.getUsertype() == 1) {
            String classids = classMapper.listTeacherClassids(params.getUserid(), user.getSchoolid());
            params.setClassids(classids);
        }
        // 当前日期
        params.setTodayDate(LocalDate.now());
        Map<String, Object> map = componentMapper.listLivePatrol(params);
        if (map == null || map.isEmpty()) {
            map = new HashMap<>();
            map.put("timestr", params.getTodayDate());
            map.put("num", 0);
            map.put("wksnum", 0);
            map.put("jxznum", 0);
            map.put("yjsnum", 0);
            map.put("ygqnum", 0);
        }

        return map;
    }


    /*
     * @Description 教师直播
     * @Date 2024/7/22 17:20:35
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listLiveTeachers(ComponentParams params) {
        // 当前日期
        params.setTodayDatetime(LocalDateTime.now());
        return componentMapper.listLiveTeachers(params);
    }

    /*
     * @Description 班级错题集
     * @Date 2024/7/23 10:19:52
     * @Author WN
     * @Param [params]
     * @Return void
     **/
    public Map<String, Object> getClassErrorQuestion(ComponentParams params) {
        long[] yeartimestamp = ApiUtil.getNowhalfYearTimestamp();// 近半年
        params.setStarttime(yeartimestamp[0]);
        params.setStoptime(yeartimestamp[1]);

        // 获取当前教师班级最近一次已生成报告作业
        Integer lastError = componentMapper.getClassErrorQuesLastPaper(params);
        Map<String, Object> map = componentMapper.getClassErrorQuesAndExplain(params);
        if (map == null || map.isEmpty()) {
            map = new HashMap<>();
            map.put("quesnum", 0);
            map.put("explainnum", 0);
        }
        if (lastError == null) {
            lastError = 0;
        }
        map.put("lasterror", lastError);
        return map;
    }

    /*
     * @Description 我的班级 (classtype 1,2,3)
     * @Date 2024/7/23 10:51:25
     * @Author WN
     * @Param [params]
     * @Return java.util.Map<java.lang.String,java.lang.Integer>
     **/
    public Map<String, Integer> getClassForTeacher(ComponentParams params) {
        Integer schoolid = userMapper.getSchoolIdByUserId(params.getUserid());
        params.setSchoolid(schoolid);
        List<Integer> classids = componentMapper.listClassidsForTeacher(params);// 权限班级
        int classnum = 0;
        int stunum = 0;
        int groupnum = 0;
        if (classids != null && classids.size() > 0) {
            classnum = classids.size();
            String classidsStr = classids.stream()
                                         .map(Object::toString)
                                         .collect(Collectors.joining(","));
            List<Integer> stuGroups = componentMapper.listClassStuAndGroup(params.getUserid(), classidsStr);
            if (stuGroups != null && stuGroups.size() > 0) {
                stunum = stuGroups.get(0);
                groupnum = stuGroups.get(1);
            }
        }

        Map<String, Integer> map = new HashMap<>();
        map.put("classnum", classnum);
        map.put("stunum", stunum);
        map.put("groupnum", groupnum);
        return map;
    }

    /*
     * @Description 校本题库
     * @Date 2024/7/23 11:23:11
     * @Author WN
     * @Param [params]
     * @Return java.util.Map<java.lang.String,java.lang.Integer>
     **/
    public Map<String, Integer> getQuestionStatistic(ComponentParams params) {
        UserVo uservo = userMapper.getUserAndSchoolInfo(params.getUserid());
        params.setSchoolid(uservo.getSchoolid());
        params.setSchoollevel(uservo.getSchoollevel());

        Map<String, Integer> map = componentMapper.getQuestionStatistic(params);
        if (map == null || map.isEmpty()) {
            map = new HashMap<>();
            map.put("totalnum", 0);
            map.put("todaynum", 0);
        }
        // 获取当前学科试题数量
        Integer subjectnum = componentMapper.getQuestionStatisticSubejct(params);
        if (subjectnum == null) {
            subjectnum = 0;
        }
        map.put("subjectnum", subjectnum);

        return map;
    }

    /*
     * @Description 教学统计
     * @Date 2024/7/23 12:19:54
     * @Author WN
     * @Param [params]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> getTeachingStatistic(ComponentParams params) {
        UserVo uservo = userMapper.getUserAndSchoolInfo(params.getUserid());
        params.setSchoolid(uservo.getSchoolid());
        params.setSchoollevel(uservo.getSchoollevel());
        params.setYear(uservo.getYear());

        // 近半年
        long[] yeartimestamp = ApiUtil.getNowhalfYearTimestamp();
        params.setStarttime(yeartimestamp[0]);
        params.setStoptime(yeartimestamp[1]);

        params.setTimestamp(N_Utils.getSecondTimestamp());

        Map<String, Object> map = componentMapper.getTeachingSchoolClassNum(params);// 班级总数量

        // 作业
        List<SchoolWorkSubjectVo> lst = componentMapper.listTeachingPapers(params);
        Integer paperTotalnum = 0;
        double paperCommitRate = 0;
        double paperCheckRate = 0;

        if (lst != null && lst.size() > 0) {
            for (SchoolWorkSubjectVo subject : lst) {
                subject.setCommitrate(N_Utils.getIntegerDivideAndMulitiply(subject.getCommitnum(), subject.getStunum()));
                subject.setCheckrate(N_Utils.getIntegerDivideAndMulitiply(subject.getChecknum(), subject.getCommitnum()));
                subject.setWorklist(new ArrayList<>());
            }

            paperTotalnum = lst.stream().mapToInt(SchoolWorkSubjectVo::getFabunum).sum();
            Integer totalcommit = lst.stream().mapToInt(SchoolWorkSubjectVo::getCommitnum).sum();
            Integer totalcheck = lst.stream().mapToInt(SchoolWorkSubjectVo::getChecknum).sum();
            Integer totalstunum = lst.stream().mapToInt(SchoolWorkSubjectVo::getStunum).sum();
            paperCommitRate = N_Utils.getIntegerDivideAndMulitiply(totalcommit, totalstunum);
            if (totalcommit > 0) {
                paperCheckRate = N_Utils.getIntegerDivideAndMulitiply(totalcheck, totalcommit);
            }
        }
        map.put("paperTotalnum", paperTotalnum);
        map.put("paperCommitRate", paperCommitRate);
        map.put("paperCheckRate", paperCheckRate);

        // 预习
        List<SchoolWorkSubjectVo> guideList = componentMapper.listTeachingGuides(params);
        Integer guideTotalnum = 0;
        double guideCommitRate = 0;
        if (guideList != null && guideList.size() > 0) {
            for (SchoolWorkSubjectVo subject : guideList) {
                subject.setCommitrate(N_Utils.getIntegerDivideAndMulitiply(subject.getCommitnum(), subject.getStunum()));

                subject.setWorklist(new ArrayList<>());
            }

            guideTotalnum = lst.stream().mapToInt(SchoolWorkSubjectVo::getFabunum).sum();
            Integer totalstunum = lst.stream().mapToInt(SchoolWorkSubjectVo::getStunum).sum();
            Integer totalcommit = lst.stream().mapToInt(SchoolWorkSubjectVo::getCommitnum).sum();
            if (totalcommit > 0) {
                guideCommitRate = N_Utils.getIntegerDivideAndMulitiply(totalcommit, totalstunum);
            }
        }
        map.put("guideTotalnum", guideTotalnum);
        map.put("guideCommitRate", guideCommitRate);

        // 背诵
        // List<SchoolWorkSubjectVo> reciteList = componentMapper.listTeachingRecites(params);
        // int reciteTotalnum = 0;
        // double reciteCommitRate = 0;
        // if(reciteList!=null && reciteList.size()>0){
        //     for(SchoolWorkSubjectVo subject : lst){
        //         subject.setCommitrate(N_Utils.getIntegerDivideAndMulitiply(subject.getCommitnum(),subject.getStunum()));
        //
        //         subject.setWorklist(new ArrayList<>());
        //     }
        //     reciteTotalnum = lst.stream().mapToInt(SchoolWorkSubjectVo::getFabunum).sum();
        //     Integer totalstunum = lst.stream().mapToInt(SchoolWorkSubjectVo::getStunum).sum();
        //     Integer totalcommit = lst.stream().mapToInt(SchoolWorkSubjectVo::getCommitnum).sum();
        //     if(totalcommit>0){
        //         reciteCommitRate = N_Utils.getIntegerDivideAndMulitiply(totalcommit,totalstunum);
        //     }
        // }
        // map.put("reciteTotalnum",reciteTotalnum);
        // map.put("reciteCommitRate",reciteCommitRate);

        return map;
    }

    /*
     * @Description 常用应用
     * @Date 2024/7/23 14:43:54
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listUserModules(ComponentParams params) {
        return componentMapper.listUserModules(params);
    }

    /*
     * @Description 考试-待出卷
     * @Date 2024/7/23 15:00:08
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listExamPaperGiv(ComponentParams params) {
        params.setTodayDatetime(LocalDateTime.now());
        return componentMapper.listExamPaperGiv(params);
    }

    /*
     * @Description 考试-待批阅
     * @Date 2024/7/23 15:12:24
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listExamPaperCheck(ComponentParams params) {
        return componentMapper.listExamPaperCheck(params);
    }

    /*
     * @Description 考试-待监考
     * @Date 2024/7/23 15:25:42
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> listExamInvigilate(ComponentParams params) {
        params.setTodayDatetime(LocalDateTime.now());
        Integer schoolid = userMapper.getSchoolIdByUserId(params.getUserid());

        List<Map<String, Object>> list = componentMapper.listExamInvigilate(params);
        for (Map map : list) {
            List<Map> classes = JSON.parseArray(map.get("classnames").toString(), Map.class);
            List<Map> classList = new ArrayList<>();
            Integer majored = (Integer) map.get("majored");
            if (majored == 1) {// 主监考
                classList.addAll(classes);
            } else {
                String[] classids2 = map.get("classids").toString().split(",");
                for (String classid : classids2) {
                    Map cmap = classes.stream().filter(c -> c.get("classid").toString().equals(classid)).findFirst().orElse(null);
                    if (cmap != null) classList.add(cmap);
                }
            }
            map.remove("classids");
            map.remove("classnames");
            List<Map> schools = new ArrayList<>();
            Map<Integer, List<Map>> collect = classList.stream().collect(Collectors.groupingBy(c -> (Integer) c.get("schoolid")));
            for (Map.Entry<Integer, List<Map>> entry : collect.entrySet()) {
                List<Map> clist = entry.getValue();
                Map school = new HashMap();
                school.put("schoolid", entry.getKey());
                for (int i = 0; i < clist.size(); i++) {
                    Map c = clist.get(i);
                    if (i == 0) {
                        school.put("schoolname", c.get("schoolname"));
                    }
                    c.remove("schoolid");
                    c.remove("schoolname");
                }
                school.put("classes", clist);
                schools.add(school);
            }
            if (schools.size() > 1) {
                // 把本校放在第一个位置
                for (int i = 0; i < schools.size(); i++) {
                    Map rtnMap = schools.get(i);
                    Integer schoolid2 = Integer.parseInt(rtnMap.get("schoolid").toString());
                    if (schoolid.equals(schoolid2)) {
                        Collections.swap(schools, i, 0);
                        break;
                    }
                }
            }
            map.put("schools", schools);
        }

        return list;
    }

    /*
     * @Description 考试-校级报告
     * @Date 2024/7/23 16:28:31
     * @Author WN
     * @Param [params]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> getExamReportSchool(ComponentParams params) {
        Integer schoolid = userMapper.getSchoolIdByUserId(params.getUserid());
        // 获取最新近一次有报告的考试
        Map<String, Object> map = componentMapper.getExamReportSchoolBase(schoolid);
        if (map != null && !map.isEmpty()) {
            Integer examstate = Integer.parseInt(map.get("examstate").toString());
            if (examstate == 3) {
                Integer examid = Integer.parseInt(map.get("examid").toString());
                List<Map<String, Object>> subjects = componentMapper.listExamReportSchoolStatistic(examid);
                map.put("subjects", subjects);
            }
            return map;
        } else {
            return null;
        }
    }

    /*
     * @Description 考试-班级报告
     * @Date 2024/7/23 17:57:54
     * @Author WN
     * @Param [params]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> getExamReportClass(ComponentParams params) {
        Integer schoolid = userMapper.getSchoolIdByUserId(params.getUserid());
        params.setSchoolid(schoolid);

        ExamInfoVo examInfoVo = componentMapper.getExamReportClassInfo(params);
        if (examInfoVo != null) {
            Map<String, Object>  map = new LinkedHashMap<>();
            if(examInfoVo.getExamstate() == 3){
                params.setSubjectid("zf");
                params.setShowrank(examInfoVo.getTeashowrank());
                params.setExamid(examInfoVo.getExamid());
                if (!N_Utils.isTrueInteger(params.getClassid())) {
                    params.setClassid(examInfoVo.getClassid());
                }

                map = componentMapper.getExamReportSingleBase(params);

                // 获取考试关联的班级信息
                List<Map<String, Object>> classList = componentMapper.listExamReportClass(examInfoVo.getExamid(), params.getUserid());
                map.put("classlist", classList);


                List<Map<String, Object>> subjectList = new ArrayList<>();
                if (examInfoVo.getTeashowrank() == 3) {
                    subjectList = componentMapper.listExamReportClassScore(params);
                }
                map.put("subjectlist", subjectList);
            }
            map.put("examid", examInfoVo.getExamid());
            map.put("examname", examInfoVo.getExamname());
            map.put("examstate",examInfoVo.getExamstate());
            map.put("teashowrank", examInfoVo.getTeashowrank());
            return map;
        } else {
            return null;
        }
    }

    /*
     * @Description 考试-单科报告
     * @Date 2024/7/23 17:23:57
     * @Author WN
     * @Param [params]
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> getExamReportSingle(ComponentParams params) {
        Integer schoolid = userMapper.getSchoolIdByUserId(params.getUserid());
        params.setSchoolid(schoolid);

        ExamInfoVo examInfoVo = componentMapper.getExamReportSingleInfo(params);

        if (examInfoVo != null) {
            Map<String, Object> map = new LinkedHashMap<>();
            if(examInfoVo.getExamstate() == 3){
                params.setSubjectid(examInfoVo.getSubjectid());
                params.setShowrank(examInfoVo.getTeashowrank());
                params.setExamid(examInfoVo.getExamid());

                if (!N_Utils.isTrueInteger(params.getClassid())) {
                    params.setClassid(examInfoVo.getClassid());
                }

                map = componentMapper.getExamReportSingleBase(params);

                // 获取考试关联的班级信息
                List<Map<String, Object>> classList = componentMapper.listExamReportClass(examInfoVo.getExamid(), params.getUserid());
                map.put("classlist", classList);

                List<Map<String, Object>> rankList = new ArrayList<>();
                if (examInfoVo.getTeashowrank() == 3) {
                    rankList = componentMapper.listExamReportSingleRank(params);
                }
                map.put("ranklist", rankList);
            }
            map.put("examid", examInfoVo.getExamid());
            map.put("examname", examInfoVo.getExamname());
            map.put("examstate",examInfoVo.getExamstate());
            map.put("teashowrank", examInfoVo.getTeashowrank());
            return map;
        } else {
            return null;
        }
    }

    /*
     * @Description 考试-阅卷进度
     * @Date 2024/7/24 10:49:22
     * @Author WN
     * @Param [params]
     * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public Map<String,Object> listExamCheckProgress(ComponentParams params) {
        UserVo userVo = userMapper.getUserAndSchoolInfo(params.getUserid());
        params.setSchoolid(userVo.getSchoolid());
        params.setUsertype(userVo.getUsertype());
        // 获取最新的一个考试阅卷
        ExamInfoVo examInfoVo = componentMapper.getExamCheckProgressBase(params);
        Map<String,Object> rtnMap = new LinkedHashMap();
        List<Map<String, Object>> mapList = new ArrayList<>();

        if (examInfoVo != null) {
            rtnMap.put("examid",examInfoVo.getExamid());
            rtnMap.put("examname",examInfoVo.getExamname());

            List<EPaperVo> papers = componentMapper.listExamCheckProgressPaper(examInfoVo.getExamid());
            String epids = papers.stream().map(p -> p.getEpid().toString()).collect(Collectors.joining(","));
            List<PaperStudentQuestionVo> questions = componentMapper.listExamCheckProgressStuQuestion(epids);// 获取考试学生试题

            for (EPaperVo paper : papers) {
                // 单科统计
                Integer epid = paper.getEpid();
                List<PaperStudentQuestionVo> qlist =
                        questions.stream().filter(q -> q.getEpid().equals(epid)).collect(Collectors.toList());

                List<Integer> qtlist = qlist.stream().filter(q -> !N_Utils.isObjectiveQuestion(q.getCtype()))
                                            .map(q -> q.getQorder()).distinct().collect(Collectors.toList());
                List<PaperStudentQuestionVo> zdlist =// 作答集合
                        qlist.stream().filter(q -> q.getAnswered().equals(1)).collect(Collectors.toList());
                List<PaperStudentQuestionVo> pylist =// 批阅集合
                        zdlist.stream().filter(q -> q.getChecked().equals(2)).collect(Collectors.toList());
                Integer zgtnum = qtlist.size();
                Integer stunum = zdlist.stream().map(q -> q.getStudentid()).distinct().collect(Collectors.toList()).size();
                Integer zpynum = pylist.size();// 试卷批阅试题数量

                Map<String, Object> map = new LinkedHashMap<>();

                map.put("subjectid", paper.getSubjectid());
                map.put("subjectname", paper.getSubjectname());
                map.put("examnum", examInfoVo.getExamnum());
                map.put("stunum", stunum);// 实际人数
                map.put("zgtnum", zgtnum);// 主观题数量
                map.put("pyrate", N_Utils.getIntegerDivideAndMulitiply(zpynum, zdlist.size()));// 批阅进度

                mapList.add(map);
            }
            rtnMap.put("subjectlist", mapList);
        }

        return rtnMap;
    }


}
