package com.xhkjedu.sstudy.service.paper;

import com.xhkjedu.sstudy.mapper.paper.PaperMapper;
import com.xhkjedu.sstudy.mapper.paper.PaperTeaAppMapper;
import com.xhkjedu.sstudy.mapper.system.SchoolMapper;
import com.xhkjedu.sstudy.model.paper.TPaper;
import com.xhkjedu.sstudy.model.question.TQuestionClass;
import com.xhkjedu.sstudy.service.gradeclass.ClassService;
import com.xhkjedu.sstudy.vo.paper.*;
import com.xhkjedu.sstudy.vo.paperstudent.PaperSearchVo;
import com.xhkjedu.sstudy.vo.paperstudent.PaperStudentQuestionVo;
import com.xhkjedu.sstudy.vo.paperstudent.StudentVo;
import com.xhkjedu.utils.N_Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author ywx
 * @classname PaperTeacherAppService
 * @description 
 * @date 2020/10/12 15:08
 **/
@Service
@Slf4j
public class PaperTeaAppService {
    @Resource
    private PaperTeaAppMapper paperTeaAppMapper;
    @Resource
    private PaperMapper paperMapper;
    @Resource
    private SchoolMapper schoolMapper;
    @Resource
    private ClassService classService;

    public Map<String, String> getQxClassidsByTeacherid(Integer teacherid, Integer year) {
        return classService.getQxClassidsByTeacherid(teacherid, year);
    }

    //获取作业列表
    public List<PaperTeacherAppVo> list(PaperSearchVo paperSearch) {
        if (paperSearch.getPsstate().equals(21)) {//未布置作业列表
            return paperTeaAppMapper.listWbz(paperSearch);
        }
        List<PaperTeacherAppVo> list = paperTeaAppMapper.listTeacherApp(paperSearch);
        for (PaperTeacherAppVo p : list) {
            PClassVo pc = setNum(p.getStudents());
            p.setFbnum(pc.getFbnum());
            p.setCommitnum(pc.getCommitnum());
            p.setChecknum(pc.getChecknum());
            p.setWtjnum(pc.getFbnum() - pc.getCommitnum());
            p.setDpgnum(pc.getCommitnum() - pc.getChecknum());
            p.setStudents(null);
        }

        return list;
    }
    //获取作业列表--我的
    public List<PaperTeacherAppVo> listMy(PaperSearchVo paperSearch) {
        if (paperSearch.getPsstate().equals(21)) {//未布置作业列表
            return paperTeaAppMapper.listWbz(paperSearch);
        }
        List<PaperTeacherAppVo> list = paperTeaAppMapper.listMyTeacherApp(paperSearch);
        for (PaperTeacherAppVo p : list) {
            PClassVo pc = setNum(p.getStudents());
            p.setFbnum(pc.getFbnum());
            p.setCommitnum(pc.getCommitnum());
            p.setChecknum(pc.getChecknum());
            p.setWtjnum(pc.getFbnum() - pc.getCommitnum());
            p.setDpgnum(pc.getCommitnum() - pc.getChecknum());
            p.setStudents(null);
        }

        return list;
    }

    /**
     * 作业情况
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/10/15 9:09
     * @return java.util.List<com.xhkjedu.vo.teacherapp.PClassVo>
     **/
    public Map getPaperDetail(Integer paperid, Integer checkid,Integer schoolid) {
        Map map = new HashMap();
        TPaper paper = paperMapper.selectByPrimaryKey(paperid);
        Integer hashb = paper.getHashb();
        Map<String, String> cmap = getQxClassidsByTeacherid(checkid, paper.getYear());
        String classids;
        if (checkid.equals(paper.getCreateid())) {//自己发布的看所有班级
            classids = null;
        } else if (hashb == 1 && paper.getSchoolid().equals(schoolid)) {//有伙伴学校并且是本校发的
            classids = cmap.get("classids");
        } else {
            classids = cmap.get("bxclassids");
        }
        List<PClassVo> list = paperTeaAppMapper.getPaperDetail(paperid, classids, schoolid);
        for (PClassVo p : list) {
            PClassVo pc = setNum(p.getStudents());
            p.setFbnum(pc.getFbnum());
            p.setCommitnum(pc.getCommitnum());
            p.setWtjnum(pc.getWtjnum());
            p.setChecknum(pc.getChecknum());
            p.setStudents(null);
        }
        List<Map> schools = new ArrayList<>();
        if(N_Utils.isListNotEmpty(list)) {
            List<Integer> schoolids = list.stream().map(c -> c.getSchoolid()).distinct().collect(Collectors.toList());
            List<Map> schoolList = schoolMapper.listSchoolNameByIds(schoolids);//根据学校ids获取学校名称集合
            Map<Integer, Object> schoolMap = schoolList.stream().collect(
                    Collectors.toMap(s -> (Integer) s.get("schoolid"), s -> s.get("schoolname")));
            LinkedHashMap<Integer, List<PClassVo>> scollect = list.stream().collect(
                    Collectors.groupingBy(c -> c.getSchoolid(), LinkedHashMap::new, Collectors.toList()));
            for (Map.Entry<Integer, List<PClassVo>> entry : scollect.entrySet()) {
                schoolid = entry.getKey();
                Map s = new HashMap();
                s.put("schoolid", schoolid);
                s.put("schoolname", schoolMap.get(schoolid));
                s.put("classes", entry.getValue());
                schools.add(s);
            }
        }
        map.put("schools", schools);
        map.put("checktype", paper.getChecktype());
        map.put("hasreport", paper.getHasreport());
        map.put("createid", paper.getCreateid());
        return map;
    }

    //封装试卷发布、提交、批改数量
    public PClassVo setNum(List<StudentVo> students){
        int fbnum = students.size();
        int ytjnum = 0;
        int checknum = 0;
        for (StudentVo s : students) {
            Integer pschecked = s.getPschecked();
            if (pschecked == 1){
                ytjnum++;
            } else if (pschecked == 2){
                ytjnum++;
                checknum ++;
            }
        }
        PClassVo p = new PClassVo();
        p.setFbnum(fbnum);
        p.setCommitnum(ytjnum);
        p.setWtjnum(fbnum - ytjnum);
        p.setChecknum(checknum);
        return p;
    }

    /**
     * 作业报告
     * @Param [paper]
     * @Author ywx
     * @Date 2020/10/14 9:12
     * @return java.util.List<com.xhkjedu.vo.teacherapp.PaperTeacherReportVo>
     **/
    public List<PaperTeacherReportVo> getReport(TPaper paper) {
        List<PaperTeacherReportVo> list = paperTeaAppMapper.getReport(paper);
        /*for (PaperTeacherReportVo q : list) {
            List<StudentVo> students = q.getStudents();
            int ytjnum = students.size();
            int correctnum = 0;
            for (StudentVo s : students) {
                if (s.getPschecked() == 1){
                    correctnum ++;
                }
            }
            q.setCorrectrate(N_Utils.getIntegerDivideAndMulitiply(correctnum,ytjnum));
            q.setStudents(null);
        }*/
        return list;
    }

    /**
     * 未提交学生列表
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/10/14 15:07
     * @return java.util.List<com.xhkjedu.vo.teacherapp.PStudentVo>
     **/
    public List<PStudentVo> listWtjStudent(Integer paperid, Integer classid) {
        return paperTeaAppMapper.listWtjStudent(paperid, classid);
    }

    /**
     * 已提交学生列表
     * @Param [paper]
     * @Author ywx
     * @Date 2020/10/14 15:12
     * @return java.util.List<com.xhkjedu.vo.teacherapp.PStudentVo>
     **/
    public List<PStudentVo> listYtjStudent(TPaper paper) {
        return paperTeaAppMapper.listYtjStudent(paper);
    }

    /**
     * 获取学生答题卡
     * @Param [paper]
     * @Author ywx
     * @Date 2020/10/14 16:04
     * @return com.xhkjedu.vo.teacherapp.PStudentVo
     **/
    public Map getStudentScantron(PStudentVo paper){
        Map map = paperTeaAppMapper.getStudentScantron(paper);
        Integer papertype = Integer.parseInt(map.get("papertype").toString());
        if(papertype != 2){
            List<Map> questions = (List<Map>) map.get("questions");
            List<String> qids = new ArrayList<>();
            List<Map> rtnques = new ArrayList<>();
            for(Map q : questions){
                Integer qlevel = Integer.parseInt(q.get("qlevel").toString());
                if(qlevel == 1){
                    q.remove("questionpid");
                    q.remove("ctype");
                    q.remove("qscore");
                    q.remove("stuscore");
                    rtnques.add(q);
                }else{
                    String questionpid = q.get("questionpid").toString();
                    if(!qids.contains(questionpid)){
                        qids.add(questionpid);
                        List<Map> sonqmap = questions.stream().filter(s -> qlevel.equals(Integer.parseInt(s.get("qlevel").toString())) && questionpid.equals(s.get("questionpid").toString())).collect(Collectors.toList());
                        Double stuscore = sonqmap.stream().mapToDouble(s -> Double.parseDouble(s.get("stuscore").toString())).sum();
                        Double qscore = sonqmap.stream().mapToDouble(s -> Double.parseDouble(s.get("qscore").toString())).sum();
                        Double correctrate = N_Utils.getDoubleDivideAndMulitiply(stuscore,qscore);
                        Map mqmap = new TreeMap();
                        mqmap.put("qorder",sonqmap.get(0).get("qorder"));
                        mqmap.put("correctrate",correctrate);
                        mqmap.put("questionid",questionpid);
                        rtnques.add(mqmap);
                    }
                }
            }
            map.put("questions",rtnques);
        }
        return map;
    }

    /**
     * 学生答题卡单题详情
     * @Param [paper]
     * @Author ywx
     * @Date 2020/10/14 16:21
     * @return com.xhkjedu.vo.paperstudent.PaperStudentQuestionVo
     **/
    public PaperStudentQuestionVo getStudentQuestion(PaperStudentQuestionVo paper) {
        return paperTeaAppMapper.getStudentQuestion(paper);
    }

    /**
     * 试题详情
     * @Param [question]
     * @Author ywx
     * @Date 2020/10/15 11:11
     * @return com.xhkjedu.vo.teacherapp.PQuestionVo
     **/
    public PQuestionVo getQuestionDetail(TQuestionClass question) {
        List<PQuestionVo> qlist = paperTeaAppMapper.getQuestionDetail(question);
        PQuestionVo q = new PQuestionVo();
        if(qlist.size() == 1){
            q = qlist.get(0);
        }else{
            //说明该题是复合题
            List<PStudentVo> mstulist = new ArrayList<>();
            double mqscore  = 0;
            String qtypename = "";
            for(int i=0;i<qlist.size();i++ ){
                PQuestionVo sqvo = qlist.get(i);
                mqscore = N_Utils.getDoubleSum(mqscore,sqvo.getQscore());
                List<PStudentVo> sstulist = sqvo.getStudents();
                if(i==0){
                    qtypename = sqvo.getMqtypename();
                    mstulist.addAll(sstulist);
                }else{
                    for(PStudentVo pstuvo : sstulist){
                        PStudentVo mstuvo = mstulist.stream().filter(s -> s.getStudentid().equals(pstuvo.getStudentid())).findFirst().orElse(null);
                        if(mstuvo == null){
                            //说明还没有改学生
                            mstulist.add(pstuvo);
                        }else{
                            double sstuscore = N_Utils.getDoubleSum(mstuvo.getScorerate(),pstuvo.getScorerate());
                            mstuvo.setScorerate(sstuscore);
                            if(pstuvo.getPschecked() == 1){
                                mstuvo.setPschecked(1);
                            }
                        }
                    }
                }
            }
            q.setQtypename(qtypename);
            q.setStudents(mstulist);
            q.setQscore(mqscore);
        }

        Double qscore = q.getQscore();
        List<PStudentVo> students = q.getStudents();
        double stuscore = students.stream().collect(Collectors.summingDouble(PStudentVo::getScorerate));
        //20220421修改发布数量为收到作业的学生数量，如果作业提交了单题也应该是已提交
//        int fbnum = students.size();
        int fbnum = paperTeaAppMapper.getPaperstudentNum(question.getPaperid(), question.getClassid());
        int tjnum = students.size();
        int ytjnum = 0;
        for (PStudentVo s : students) {
            if (s.getPschecked() == 1) {
                ytjnum++;
            }
            s.setScorerate(N_Utils.getDoubleDivideAndMulitiply(s.getScorerate(), qscore));
        }
        q.setCommitrate(N_Utils.getIntegerDivideAndMulitiply(ytjnum, fbnum));
        q.setScorerate(N_Utils.getDoubleDivideAndMulitiply(stuscore, (qscore * tjnum)));//得分率为学生总得分，除以提交的作业中试题总分
        IntSummaryStatistics statistics = students.stream().mapToInt(PStudentVo::getCosttime).summaryStatistics();
        q.setAvgtime((int) Math.ceil(statistics.getAverage()));
        q.setMintime(statistics.getMin());
        return q;
    }

    /**
     * 作业学生列表
     *
     * @return java.util.List<com.xhkjedu.sstudy.vo.paper.PStudentVo>
     * @Param [paper]
     * @Author ywx
     * @Date 2022/5/31 10:17
     **/
    public Map listPaperStudent(TPaper paper) {
        Map map = new HashMap();
        List<PStudentVo> list = paperTeaAppMapper.listPaperStudent(paper);
        int classnum = list.size();//作业人数
        List<PStudentVo> wtjStus = list.stream().filter(s -> s.getPschecked().equals(0)).collect(Collectors.toList());
        List<PStudentVo> wpyStus = list.stream().filter(s -> s.getPschecked().equals(1)).collect(Collectors.toList());
        List<PStudentVo> ypyStus = list.stream().filter(s -> s.getPschecked().equals(2)).collect(Collectors.toList());

        map.put("classnum", classnum);
        map.put("wtjStus", wtjStus);
        map.put("wtjnum", wtjStus.size());
        map.put("wpyStus", wpyStus);
        map.put("wpynum", wpyStus.size());
        map.put("ypyStus", ypyStus);
        map.put("ypynum", ypyStus.size());

        Integer papertype = paperMapper.getPaperTypeById(paper.getPaperid());//根据作业id获取作业分类
        map.put("papertype", papertype);
        return map;
    }
}
