package com.xhkjedu.sstudy.service.paper;

import com.xhkjedu.sstudy.mapper.gradeclass.ClassMapper;
import com.xhkjedu.sstudy.mapper.paper.PaperAnalyzeMapper;
import com.xhkjedu.sstudy.mapper.paper.PaperMapper;
import com.xhkjedu.sstudy.mapper.question.QuestionMapper;
import com.xhkjedu.sstudy.mapper.subjectbook.SubjectMapper;
import com.xhkjedu.sstudy.mapper.system.SchoolMapper;
import com.xhkjedu.sstudy.mapper.system.UserMapper;
import com.xhkjedu.sstudy.model.paper.TPaper;
import com.xhkjedu.sstudy.model.paper.TPaperAnalyze;
import com.xhkjedu.sstudy.model.paper.TPaperFile;
import com.xhkjedu.sstudy.model.paperstudent.TPaperClass;
import com.xhkjedu.sstudy.utils.StudyUtil;
import com.xhkjedu.sstudy.vo.gradeclass.CStudentVo;
import com.xhkjedu.sstudy.vo.paper.*;
import com.xhkjedu.sstudy.vo.paperstudent.StudentPaperTypeVo;
import com.xhkjedu.sstudy.vo.paperstudent.StudentPaperVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.paper.PaperListVo;
import org.springframework.stereotype.Service;

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

/**
 * @ClassName PaperAnalyzeService
 * Description TODO
 * Author WN
 * Date 2020/6/11 10:55
 **/
@Service
public class PaperAnalyzeService {
    @Resource
    private PaperAnalyzeMapper paperAnalyzeMapper;
    @Resource
    private PaperMapper paperMapper;
    @Resource
    private ClassMapper classMapper;
    @Resource
    private SchoolMapper schoolMapper;
    @Resource
    private SubjectMapper subjectMapper;
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 作业分析
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/6/10 14:46
     * @return com.xhkjedu.sstudy.model.paper.TPaperAnalyze
     **/
    public TPaperAnalyze getAnalyzeByPaperid(Integer paperid) {
        return paperAnalyzeMapper.getAnalyzeByPaperid(paperid);
    }

    /**
     * 获取作业分析
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/6/24 15:02
     * @return com.xhkjedu.sstudy.vo.paper.PaperAnalyzeVos
     **/
    public PaperAnalyzeVo getPaperAnalyze(Integer paperid, Integer papertype, Integer classid) {
        PaperAnalyzeVo paper = paperAnalyzeMapper.getPaperAnalyze(paperid, papertype, classid);
        List<AnalyzeStudentVo> students = paper.getStudents();
        int fbnum = students.size();
        paper.setFbnum(fbnum);
        int ytjnum = 0;
        int checknum = 0;
        for (AnalyzeStudentVo s : students) {
            Integer pschecked = s.getPschecked();
            if (pschecked == 1) {
                ytjnum++;
            } else if (pschecked == 2) {
                ytjnum++;
                checknum++;
            }
        }
        DoubleSummaryStatistics statistics = students.stream().mapToDouble(AnalyzeStudentVo::getUserscore).summaryStatistics();
        paper.setMaxscore(statistics.getMax());//本班本次作业最高分（无论是否批改）
        paper.setMinscore(statistics.getMin());//本班本次作业最低分（无论是否批改）
        paper.setAvgscore(N_Utils.formatDouble(statistics.getAverage(), 2));//学生得分总和除以收到作业总人数（无论是否批改）
        paper.setYtjnum(ytjnum);
        paper.setCommitrate(N_Utils.getIntegerDivideAndMulitiply(ytjnum, fbnum));//提交学生数量除以收到作业总人数（班级为单位）
        paper.setCheckrate(N_Utils.getIntegerDivideAndMulitiply(checknum, ytjnum));//批改学生数量除以提交学生数量
        Double paperscore = students.stream().mapToDouble(AnalyzeStudentVo::getPaperscore).sum();
        Double stuscore = students.stream().mapToDouble(AnalyzeStudentVo::getUserscore).sum();
        paper.setScorerate(N_Utils.getDoubleDivideAndMulitiply(stuscore, paperscore));//本班学生得分总和除以收到作业总人数的满分总分值
        paper.setStudents(null);
        return paper;
    }

    /**
     * 作业统计--按人
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/6/24 10:33
     * @return com.xhkjedu.sstudy.vo.paper.PaperAnalyzeVo
     **/
    public PaperAnalyzeVo getPeopleAnalyze(TPaper paper) {
        PaperAnalyzeVo paperAnalyze = getPaperAnalyze(paper.getPaperid(),paper.getPapertype(),paper.getClassid());
        return paperAnalyze;
    }

    //作业统计--按人--班级学生列表
    public List<AnalyzeStudentVo> listStu(TPaper paper) {
        List<AnalyzeStudentVo> students = paperAnalyzeMapper.getPeopleAnalyze(paper);
        return students;
    }

    /**
     * 作业统计--按题
     * @Param [paperid, papertype]
     * @Author ywx
     * @Date 2020/6/24 15:06
     * @return com.xhkjedu.sstudy.vo.paper.PaperAnalyzeVo
     **/
    public PaperAnalyzeVo getQuestionAnalyze(Integer paperid, Integer papertype, Integer classid) {
        PaperAnalyzeVo paperAnalyze = getPaperAnalyze(paperid, papertype, classid);
        List<AnalyzeQuestionVo> questions;
        if (papertype == 1 || papertype == 3) {//结构性试题/靶向作业
            questions = paperAnalyzeMapper.getQuestionAnalyze(paperid, papertype, classid);
        } else {//自定义答题卡
            questions = paperAnalyzeMapper.getSQuestionAnalyze(paperid, classid);
        }
        paperAnalyze.setQuestions(questions);
        return paperAnalyze;
    }

    /**
     * 作业统计--按题详情
     * @Param [paperid, questionid]
     * @Author ywx
     * @Date 2020/6/24 15:37
     * @return com.xhkjedu.sstudy.vo.paper.QuestionAnalyzeVo
     **/
    public QuestionAnalyzeVo getQuestionDetailAnalyze(AnalyzeQuestionVo question) {
        String questionpid = question.getQuestionpid();
        String questionid = question.getQuestionid();
        if(N_Utils.isEmpty(questionpid)) {
            question.setQuestionpid(questionid);
            questionpid=questionid;
        }
        QuestionAnalyzeVo analyze = paperAnalyzeMapper.getQuestionDetailAnalyze(question);
        if (!questionpid.equals(questionid)) {
            List<Map> sonqlist = questionMapper.listSonQuestionsForDetail(questionpid);
            analyze.setSonqlist(sonqlist);
        }
        return analyze;
    }

    //作业统计--按题详情--学生列表
    public List<AnalyzeStudentVo> listQuestionStu(Integer paperid, String questionid,Integer classid,Integer od) {
        return paperAnalyzeMapper.listQuestionStu(paperid, questionid,classid,od);
    }

    /**
     * 答题卡作业统计--按题详情
     * @Param [paperid, ptqorder]
     * @Author ywx
     * @Date 2020/6/27 16:55
     * @return com.xhkjedu.sstudy.vo.paper.QuestionAnalyzeVo
     **/
    public List<AnalyzeStudentVo> getSQuestionDetailAnalyze(Integer paperid, Integer ptqorder, Integer classid, Integer od) {
        List<AnalyzeStudentVo> analyze = paperAnalyzeMapper.getSQuestionDetailAnalyze(paperid, ptqorder, classid, od);
        return analyze;
    }

    /**
     * 作业统计--按人详情
     * @Param [psid]
     * @Author ywx
     * @Date 2020/6/28 10:06
     * @return com.xhkjedu.sstudy.vo.paperstudent.StudentPaperVo
     **/
    public StudentPaperVo getPeopleDetailAnalyze(Integer psid) {
        StudentPaperVo paper = paperAnalyzeMapper.getStudentPaperAnalyze(psid);
        List<StudentPaperTypeVo> types = paperAnalyzeMapper.listPeopleDetailAnalyze(psid);
        StudyUtil.setPaperQuestion(types, paperAnalyzeMapper);
        paper.setTypes(types);
        return paper;
    }

    public StudentPaperVo getPeopleSDetailAnalyze(Integer psid) {
        StudentPaperVo paper = paperAnalyzeMapper.getStudentPaperAnalyze(psid);
        List<StudentPaperTypeVo> types = paperAnalyzeMapper.listPeopleSDetailAnalyze(psid);
        paper.setTypes(types);
        List<TPaperFile> files = paperMapper.listPaperFile(paper.getPaperid(), 0);
        paper.setFiles(files);
        return paper;
    }

    /**
     * @Description 作业统计--按人详情
     * @Param [psid]
     * @Author ywx
     * @Date 2023/5/6 10:14
     * @return com.xhkjedu.sstudy.vo.paperstudent.StudentPaperVo
     **/
    public StudentPaperVo getStuDetailAnalyze(Integer psid) {
        StudentPaperVo paper = paperAnalyzeMapper.getStudentPaperAnalyze(psid);
        Integer papertype = paper.getPapertype();
        List<StudentPaperTypeVo> types;
        if (papertype == 2) {//附件作业
            types = paperAnalyzeMapper.listStuDetailAnalyze(psid);
            List<TPaperFile> files = paperMapper.listPaperFile(paper.getPaperid(), 0);
            paper.setFiles(files);
        } else {
            types = paperAnalyzeMapper.listPeopleDetailAnalyze(psid);
            StudyUtil.setPaperQuestion(types, paperAnalyzeMapper);//处理母子题
        }
        paper.setTypes(types);
        return paper;
    }

    /**
     * 获取作业提交情况
     * @Param [papernum, createid]
     * @Author ywx
     * @Date 2020/7/9 11:11
     * @return java.util.List<com.xhkjedu.sstudy.vo.paper.PaperCAnalyzeVo>
     **/
    public List<PaperCAnalyzeVo> listCommitAnalyze(Integer papernum, Integer createid) {
        return paperAnalyzeMapper.listCommitAnalyze(papernum , createid);
    }

    /**
     * 获取作业班级列表
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/9/23 16:58
     * @return java.util.List<com.xhkjedu.sstudy.vo.gradeclass.ClassVo>
     **/
    public List<Map> listPaperClass(Integer paperid, Integer schoolid, Integer createid) {
        TPaper paper = paperMapper.selectByPrimaryKey(paperid);
        Integer hashb = paper.getHashb();
        String classids;
        Integer usertype = userMapper.getUsertypeByUserid(createid);
        if (createid.equals(paper.getCreateid()) || usertype.equals(0)) {//自己发布的或管理员看所有班级
            classids = null;
        } else {
            List<Map> classlist = classMapper.listQxClassByTeacherid(createid, paper.getYear());
            Map<String, String> cmap = StudyUtil.setQxClass(classlist);
            if (hashb == 1 && paper.getSchoolid().equals(schoolid)) {//有伙伴学校并且是本校发的
                classids = cmap.get("classids");
            } else {
                classids = cmap.get("bxclassids");
            }
        }
        return paperAnalyzeMapper.listPaperClass(paperid, schoolid, classids);
    }

    /**
     * 作业班级学生列表
     * @Param [paper]
     * @Author ywx
     * @Date 2020/9/24 10:10
     * @return java.util.Map
     **/
    public Map listPaperClassStudent(TPaperClass paper) {
        Map map = new HashMap();
        List<CStudentVo> list = paperAnalyzeMapper.listPaperClassStudent(paper);
        List<String> ytjstus = new ArrayList<>();
        List<String> wtjstus = new ArrayList<>();
        for (CStudentVo s : list) {
            String studentname = s.getStudentname();
            if (s.getStudentid() == 0){
                wtjstus.add(studentname);
            } else {
                ytjstus.add(studentname);
            }
        }
        map.put("ytjstus",ytjstus);
        map.put("wtjstus",wtjstus);
        return map;
    }

    /**
     * 获取年级下作业统计列表
     * @Param [paper]
     * @Author ywx
     * @Date 2020/9/28 10:21
     * @return java.util.List<com.xhkjedu.sstudy.vo.paper.PaperGAnalyzeVo>
     **/
    public List<PaperGAnalyzeVo> listPaperGrade(AnalyzeSearchVo paper) {
        //setYear(paper);
        setClassIds(paper);//设置教师权限班级
        paper.setTimestamp(N_Utils.getSecondTimestamp());
        List<PaperGAnalyzeVo> list = paperAnalyzeMapper.listUser(paper);
        List<PaperGAnalyzeVo> teapapers = paperAnalyzeMapper.getPaperGrade(paper);//发布作业的教师发布作业情况

        if(teapapers!=null && teapapers.size()>0){
            //处理有作业的教师的发布情况
            for(PaperGAnalyzeVo pga : teapapers){
                PaperGAnalyzeVo teacher = list.stream().filter(t -> t.getTeacherid().equals(pga.getTeacherid())).findFirst().orElse(null);
                if(teacher != null){
                    Integer ytjnum = pga.getYtjnum();
                    Integer commitnum = pga.getCommitnum();
                    Integer checknum = pga.getChecknum();
                    teacher.setFbnum(pga.getFbnum());
                    teacher.setYtjnum(ytjnum);
                    teacher.setCommitnum(commitnum);
                    teacher.setChecknum(checknum);
                    teacher.setCommitrate(N_Utils.getIntegerDivideAndMulitiply(commitnum,ytjnum));
                    teacher.setCheckrate(N_Utils.getIntegerDivideAndMulitiply(checknum, commitnum));
                }
            }
        }

        return list.stream().sorted(Comparator.comparing(PaperGAnalyzeVo::getFbnum).reversed()
                .thenComparing(PaperGAnalyzeVo::getTeachername)).collect(Collectors.toList());
    }

    /**
     * 获取年级下教师发布作业列表
     * @Param [paper]
     * @Author ywx
     * @Date 2020/9/28 15:12
     * @return java.util.List<com.xhkjedu.sstudy.vo.paper.PaperListVo>
     **/
    public List<PaperListVo> listPaper(AnalyzeSearchVo paper) {
        List<PaperListVo> list = paperMapper.listPaper(paper);
        return StudyUtil.getPaperListVo(list);
    }

    //设置教师权限班级
    public void setClassIds(AnalyzeSearchVo paper) {
        if (paper.getUsertype() == 1 && N_Utils.isEmptyInteger(paper.getClassid())) {
            String classIds = classMapper.getClassIds(paper);//获取教师任教行政和提高班id
            paper.setClassids(classIds);
        }
    }

    //获取作业导出数据
    public Map exportPaperAnalyze(TPaper paper) {
        Map map = new HashMap();
        //按人统计结果
        List<AnalyzeStudentVo> students = listStu(paper);
        map.put("students", students);

        //按题统计结果
        Integer papertype = paper.getPapertype();
        Integer paperid = paper.getPaperid();
        Integer classid = paper.getClassid();
        List<AnalyzeQuestionVo> questions;
        if (papertype == 1 || papertype == 3) {//结构性试题/靶向作业
            questions = paperAnalyzeMapper.getQuestionAnalyze(paperid, papertype, classid);
        } else {//自定义答题卡
            questions = paperAnalyzeMapper.getSQuestionAnalyze(paperid, classid);
        }
        map.put("questions", questions);
        return map;
    }

    //设置年份
    public void setYear(AnalyzeSearchVo paper) {
        Integer year;
        if (paper.getSchoolid() != null) {
            year = schoolMapper.getYearById(paper.getSchoolid());
        } else {
            Integer studentid = paper.getStudentid();
            Integer teacherid = paper.getTeacherid();
            Integer userid = studentid == null ? teacherid : studentid;
            year = schoolMapper.getYearByUserId(userid);
        }
        paper.setYear(year);
    }

    //作业统计--按学生列表
    public List<AStudentPaperVo> listPaperStuGrade(AnalyzeSearchVo paper) {
        /*List<Map> list = paperAnalyzeMapper.listPaperStuGrade(paper);
        for (Map map : list) {
            Integer studentid = (Integer) map.get("studentid");
            Map cmap = classMapper.getClassByStuId(studentid);
            if (cmap != null) {
                map.put("gradeid", cmap.get("gradeid").toString());
                map.put("classname", cmap.get("classname".toString()));
            }
        }*/

        List<AStudentPaperVo> list = classMapper.listStu(paper);//班级学生
        List<AStudentPaperVo> stupapers = paperAnalyzeMapper.listPaperAllClassStu(paper);//年级下所有学生关联的作业
        for (AStudentPaperVo student : list) {
            Integer studentid = student.getStudentid();
            paper.setStudentid(studentid);
//            List<AStudentPaperVo> papers = paperAnalyzeMapper.listPaperStuExport(paper);
            List<AStudentPaperVo> papers = stupapers.stream().filter(o -> o.getStudentid().equals(studentid)).collect(Collectors.toList());
                    //按学生统计
            setRate(student, papers);//设置学生作业比例
        }

        list = list.stream().sorted(Comparator
                .comparing(AStudentPaperVo::getCommitnum).reversed()
                .thenComparing(AStudentPaperVo::getStudentid)
        ).collect(Collectors.toList());


        return list;
    }

    //作业统计--按学生详情
    public Map listPaperStuDetail(AnalyzeSearchVo paper) {
        setClassIds(paper);//设置教师权限班级
        Map map = new HashMap();
        List<AStudentPaperVo> subjects = paperAnalyzeMapper.listPaperStuDetail(paper);
        Integer sdnum = subjects.stream().mapToInt(AStudentPaperVo::getSdnum).sum();
        map.put("sdnum",sdnum);
        Integer commitnum = subjects.stream().mapToInt(AStudentPaperVo::getCommitnum).sum();
        map.put("commitnum",commitnum);
        map.put("commitrate", N_Utils.getIntegerDivideAndMulitiply(commitnum,sdnum));
        Double paperscore = subjects.stream().mapToDouble(AStudentPaperVo::getPaperscore).sum();
        Double userscore = subjects.stream().mapToDouble(AStudentPaperVo::getUserscore).sum();
        map.put("scorerate", N_Utils.getDoubleDivideAndMulitiply(userscore,paperscore));
        map.put("subjects",subjects);
        return map;
    }


    //作业统计--按学生导出
    public Map listPaperStuExport(AnalyzeSearchVo paper) {
        Map map = new HashMap();
        Integer schoolid = paper.getSchoolid();
        //TSchool school = schoolMapper.selectByPrimaryKey(schoolid);
        //paper.setYear(school.getYear());
        setClassIds(paper);//设置教师权限班级
        List<AStudentPaperVo> subjects = new ArrayList<>();
        List<AStudentPaperVo> students = classMapper.listStu(paper);
        List<AStudentPaperVo> stupapers = paperAnalyzeMapper.listPaperAllClassStu(paper);//年级下所有学生关联的作业
        Map<String, String> subjectMap = new HashMap<>();//科目集合
        if (N_Utils.isListNotEmpty(stupapers)) {
            List<String> subjectids =
                    stupapers.stream().map(AStudentPaperVo::getSubjectid).distinct().collect(Collectors.toList());
            List<Map<String, String>> subjectNames = subjectMapper.listNameByIds(subjectids);//根据科目ids获取名称列表
            for (Map<String, String> subject : subjectNames) {
                subjectMap.put(subject.get("subjectid"), subject.get("subjectname"));
            }
        }

        for (AStudentPaperVo student : students) {
            Integer studentid = student.getStudentid();
            paper.setStudentid(studentid);
            List<AStudentPaperVo> papers = stupapers.stream().filter(o -> o.getStudentid().equals(studentid)).collect(Collectors.toList());
            //按学生统计
            setRate(student, papers);//设置学生作业比例

            //按科目统计
            Map<String, List<AStudentPaperVo>> scollect = papers.stream().collect(Collectors.groupingBy(AStudentPaperVo::getSubjectid));
            for (Map.Entry s : scollect.entrySet()) {
                List<AStudentPaperVo> subjects2 = (List<AStudentPaperVo>) s.getValue();
                AStudentPaperVo subject = subjects2.get(0);
                setRate(subject, subjects2);//设置学生作业比例
                String subjectid = subject.getSubjectid();
                subject.setSubjectname(subjectMap.get(subjectid));
                subject.setStudentname(student.getStudentname());
                subject.setLoginname(student.getLoginname());
                subject.setGradeid(student.getGradeid());
                subject.setClassname(student.getClassname());
                subjects.add(subject);
            }
        }
        students = students.stream().sorted(Comparator
                .comparing(AStudentPaperVo::getCommitnum).reversed()
                .thenComparing(AStudentPaperVo::getStudentid)
        ).collect(Collectors.toList());
        map.put("students", students);
        map.put("subjects", subjects);
        return map;
    }

    //设置学生作业比例
    private void setRate(AStudentPaperVo student, List<AStudentPaperVo> papers) {
        Integer sdnum = papers.size();
        student.setSdnum(sdnum);
        Integer commitnum = papers.stream().filter(p->StudyUtil.tjlist.contains(p.getPsstate())).collect(Collectors.toList()).size();
        student.setCommitnum(commitnum);
        student.setCommitrate(N_Utils.getIntegerDivideAndMulitiply(commitnum,sdnum));
        Double paperscore = papers.stream().mapToDouble(AStudentPaperVo::getPaperscore).sum();
        Double userscore = papers.stream().mapToDouble(AStudentPaperVo::getUserscore).sum();
        student.setScorerate(N_Utils.getDoubleDivideAndMulitiply(userscore,paperscore));
    }
}
