package com.xhkjedu.sstudy.service.paper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xhkjedu.sstudy.listener.MessageSender;
import com.xhkjedu.sstudy.mapper.gradeclass.ClassMapper;
import com.xhkjedu.sstudy.mapper.paper.*;
import com.xhkjedu.sstudy.mapper.paperstudent.PaperStudentMapper;
import com.xhkjedu.sstudy.model.paper.*;
import com.xhkjedu.sstudy.model.paperstudent.TPaperStudent;
import com.xhkjedu.sstudy.vo.paper.*;
import com.xhkjedu.sstudy.vo.paperstudent.PaperSearchVo;
import com.xhkjedu.sstudy.vo.question.QuestionVo;
import com.xhkjedu.sstudy.vo.subjectbook.PointVo;
import com.xhkjedu.utils.N_Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

/**
 * @ClassName PaperService
 * Description 作业
 * Author WN
 * Date 2020/6/8 16:14
 **/
@Slf4j
@Service
public class PaperService {
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private PaperFileService paperFileService;
    @Autowired
    private PaperScantronQtypeMapper paperScantronQtypeMapper;
    @Autowired
    private PaperScantronMapper paperScantronMapper;
    @Resource
    private PaperQtypeMapper paperQtypeMapper;
    @Resource
    private PaperQtypeQuestionMapper paperQtypeQuestionMapper;
    @Resource
    private PaperAnalyzeMapper paperAnalyzeMapper;
    @Resource
    private PaperStudentMapper paperStudentMapper;
    @Autowired
    private MessageSender messageSender;
    @Resource
    private ClassMapper classMapper;

    /**
     * 功能描述  答题卡作业--保存
     *
     * @param *      @param paper
     * @param qtypes
     * @return boolean
     * @author WN
     * @date 2020/6/9
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer saveScantronPaper(TPaper paper, List<TPaperScantronQtype> qtypes) throws Exception {
        Integer paperid = 0;
        try {
            paper.setPapertype(2); //作业类型1结构性试题2自定义答题卡

            //答题卡中试题
            List<TPaperScantron> scanlist = new ArrayList<>();
            qtypes.forEach(t->{
                scanlist.addAll(t.getScantrons());
            });
            paper.setPapernum(scanlist.size());
            Double paperscore = scanlist.stream().collect(Collectors.summingDouble(TPaperScantron::getPsscore));
            paper.setPaperscore(paperscore);
            paperid = savePaper(paper);//保存作业
            paper.setPaperid(paperid);

            //保存作业关联信息
            List<TPaperFile> lst = paper.getPfiles();
            if(lst==null || lst.size()==0 || scanlist ==null || scanlist.size()==0){
            }else{
                //保存作业附件
                savePaperScantronFile(paper);
                //保存答题卡信息
                savePaperScantronQtype(paper,qtypes);
                //保存分析
                //savePaperScantronAnalyze(paperid,paper.getSchoolid());
            }

        }catch (Exception e){
            log.error("保存答题卡作业失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("保存答题卡作业失败");
        }

        return paperid;
    }

    /**
     *功能描述  答题卡作业--修改
     * @author WN
     * @date 2020/6/11
     * @param  * @param paper
     * @param qtypes
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateScantronPaper(TPaper paper, List<TPaperScantronQtype> qtypes) throws Exception {
        boolean rtn = false;
        try {

            //答题卡中试题
            List<TPaperScantron> scanlist = new ArrayList<>();
            qtypes.forEach(t->{
                scanlist.addAll(t.getScantrons());
            });
            paper.setPapernum(scanlist.size());
            Double paperscore = scanlist.stream().collect(Collectors.summingDouble(TPaperScantron::getPsscore));
            paper.setPaperscore(paperscore);
            paper.setPapertype(2);

            //修改作业基本信息
            paperMapper.updatePaper(paper);

            //保存作业关联信息
            List<TPaperFile> lst = paper.getPfiles();
            if (lst == null || lst.size() == 0 || scanlist == null || scanlist.size() == 0) {
                rtn = false;
            } else {
                //删除作业附件后重新保存
                paperFileService.deleteByPaperid(paper.getPaperid());
                savePaperScantronFile(paper);    //保存作业附件
                //删除作业答题卡信息
                paperScantronQtypeMapper.deleteByPaperid(paper.getPaperid());   //保存答题卡信息
                savePaperScantronQtype(paper, qtypes);
                //删除分析信息
                //paperAnalyzeMapper.deleteByPaperid(paper.getPaperid());
                //savePaperScantronAnalyze(paper.getPaperid(), paper.getSchoolid());  //保存分析

                rtn = true;
            }
        }catch (Exception e){
            log.error("修改答题卡作业失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("修改答题卡作业失败");
        }
        return rtn;
    }



    /**
     * 保存作业
     * @Param [paper]
     * @Author ywx
     * @Date 2020/6/10 10:29
     * @return void
     **/
    private Integer savePaper(TPaper paper) {
        paper.setPaperstate(21);//作业状态：21未布置 22 已布置
        paper.setCreatetime(N_Utils.getSecondTimestamp());
        paper.setChecktype(0);
        String directorid = paper.getDirectorid();
        if (directorid != null && (directorid.equals("0") || directorid.equals(""))) {
            paper.setDirectorid(null);
        }
        paperMapper.insertUseGeneratedKeys(paper);
        return paper.getId();
    }

    //答题卡--保存作业附件信息
    private void savePaperScantronFile(TPaper paper){
        int fileorder = 1;
        List<TPaperFile> lst = paper.getPfiles();
        for(TPaperFile pf : lst){
            pf.setCreateid(paper.getCreateid());
            pf.setCreatetime(N_Utils.getSecondTimestamp());
            pf.setSchoolid(paper.getSchoolid());
            pf.setFileorder(fileorder);
            pf.setPaperid(paper.getPaperid());
            fileorder++;
        }
        paperFileService.addBatch(lst);
    }

    //答题卡--保存答题卡-题型-知识点
    private void savePaperScantronQtype(TPaper paper, List<TPaperScantronQtype> qtypes) {
        int sorder = 1;//答题卡试题序号
        int qtypeorder = 1;//答题卡题型序号
        //处理答题卡--题型--试题
        List<TPaperScantron> savescan = new ArrayList<>();
        for (TPaperScantronQtype qtype : qtypes) {
            List<TPaperScantron> scanlst = qtype.getScantrons();//题型下试题
            qtype.setCreateid(paper.getCreateid());
            qtype.setCreatetime(N_Utils.getSecondTimestamp());
            qtype.setSchoolid(paper.getSchoolid());
            qtype.setPstnum(scanlst.size());
            Double qtypescore = scanlst.stream().collect(Collectors.summingDouble(TPaperScantron::getPsscore));
            qtype.setPstscore(qtypescore);
            qtype.setPaperid(paper.getPaperid());
        }

        paperScantronQtypeMapper.insertList(qtypes);//批量保存答题卡题型
        for (TPaperScantronQtype qtype : qtypes) {
            for (TPaperScantron sc : qtype.getScantrons()) {
                sc.setCreateid(paper.getCreateid());
                sc.setCreatetime(N_Utils.getSecondTimestamp());
                sc.setSchoolid(paper.getSchoolid());
                sc.setPaperid(paper.getPaperid());
                sc.setPsqtypeid(qtype.getId());
                savescan.add(sc);
            }
        }
        paperScantronMapper.insertList(savescan);//批量保存答题卡
    }

    //保存答题卡分析
    private Integer savePaperScantronAnalyze(Integer paperid,Integer schoolid){
        List<Map<String, Object>> list = paperScantronMapper.listQtypeAnalyze(paperid);

        TPaperAnalyze paperAnalyze = new TPaperAnalyze();
        paperAnalyze.setPaperid(paperid);
        paperAnalyze.setQtypejson(JSON.toJSONString(list));

        paperAnalyze.setSchoolid(schoolid);
        paperAnalyzeMapper.insertUseGeneratedKeys(paperAnalyze);
        return paperAnalyze.getId();
    }

    /**
     *功能描述  删除作业
     * @author WN
     * @date 2020/6/9
     * @param  * @param paper
     * @return void
     */
    public Integer delPaper(TPaper paper){
        List<TPaperFile> pfilelist = paperFileService.listObjsByPaperid(paper.getPaperid());//获取作业文件夹
        int result =  paperMapper.delPaper(paper.getPaperid());
        if (N_Utils.isListNotEmpty(pfilelist)) {
            List<String> resourceUrls = new ArrayList<>();
            for (int i = 0; i < pfilelist.size(); i++) {
                TPaperFile pf = pfilelist.get(i);
                resourceUrls.add(pf.getFilepath());

                if(!resourceUrls.contains(pf.getSourcepath())){
                    resourceUrls.add(pf.getSourcepath());
                }
            }
            messageSender.resourceDel(resourceUrls);//给文件服务器发送mq删除文件
        }
        return result;
    }

    /**
     * 结构性试题作业--保存
     * @Param [paper, qtypes]
     * @Author ywx
     * @Date 2020/6/10 8:11
     * @return boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    public Integer saveQuestionPaper(TPaper paper, List<TPaperQtype> qtypes) throws Exception {
        Integer paperid = 0;
        try {
            setPaperScoreAndNum(paper, qtypes);//设置作业分值和试题数量
            paperid = savePaper(paper);//保存作业
            paper.setPaperid(paperid);
            savePaperQtype(paper, qtypes);//保存作业题型信息
            //generatePaperAnalyze(paperid, paper.getSchoolid());//生成作业分析
        }catch (Exception e){
            log.error("保存结构性试题作业失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("保存结构性试题作业失败");
       }
        return paperid;
    }

    /**
     * 设置作业分值和试题数量
     * @Param [paper, qtypes]
     * @Author ywx
     * @Date 2020/6/28 18:05
     * @return void
     **/
    private void setPaperScoreAndNum(TPaper paper, List<TPaperQtype> qtypes) {
        List<QuestionVo> questionList = new ArrayList<>();
        qtypes.forEach(t -> {
            questionList.addAll(t.getQuestions());
        });
        Double paperscore = questionList.stream().collect(Collectors.summingDouble(QuestionVo::getScore));
        paper.setPaperscore(paperscore);
        paper.setPapernum(questionList.size());
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updateQuestionPaper(TPaper paper, List<TPaperQtype> qtypes) throws Exception {
        boolean rtn = false;
        try {
            setPaperScoreAndNum(paper, qtypes);//设置作业分值和试题数量
            //修改作业基本信息
            paperMapper.updatePaper(paper);
            paperQtypeMapper.deleteByPaperid(paper.getPaperid());//删除作业题型信息
            savePaperQtype(paper, qtypes);//保存作业题型信息
            //paperAnalyzeMapper.deleteByPaperid(paper.getPaperid());//删除分析信息
            //generatePaperAnalyze(paper.getPaperid(), paper.getSchoolid());//生成作业分析
            rtn = true;
        }catch (Exception e){
            log.error("保存结构性试题作业失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception("保存结构性试题作业失败");
        }
        return rtn;
    }

    /**
     * 保存作业题型信息
     * @Param [paper, qtypes]
     * @Author ywx
     * @Date 2020/6/28 17:58
     * @return void
     **/
    private void savePaperQtype(TPaper paper, List<TPaperQtype> qtypes) {
        Integer paperid = paper.getPaperid();
        Integer createid = paper.getCreateid();
        Integer schoolid = paper.getSchoolid();

        int qorder = 1;//试题序号
        int ptorder = 1;//题型序号
        //处理答题卡--题型--试题
        List<TPaperQtypeQuestion> ptqs = new ArrayList<>();
        for (TPaperQtype qtype : qtypes) {
            if("tlt".equals(qtype.getQtypeid())){
                qtype.setQtypeid(null);
            }
            List<QuestionVo> questions = qtype.getQuestions();//题型下试题
            qtype.setCreateid(createid);
            qtype.setCreatetime(N_Utils.getSecondTimestamp());
            qtype.setSchoolid(schoolid);
            qtype.setPtnum(questions.size());
            Double ptscore = questions.stream().collect(Collectors.summingDouble(QuestionVo::getScore));
            qtype.setPtscore(ptscore);
            qtype.setPtorder(ptorder);
            qtype.setPaperid(paperid);
            ptorder++;
        }
        paperQtypeMapper.insertList(qtypes);//批量保存答题卡题型
        for (TPaperQtype qtype : qtypes) {
            for (QuestionVo q : qtype.getQuestions()) {
                List<Map> sonqlist = q.getSonqlist();
                if (N_Utils.isListEmpty(sonqlist)) {
                    TPaperQtypeQuestion ptq = new TPaperQtypeQuestion();
                    ptq.setPtid(qtype.getId());
                    ptq.setPaperid(paperid);
                    ptq.setQuestionid(q.getQuestionid());
                    ptq.setPtqscore(q.getScore());
                    ptq.setPtqorder(qorder);
                    ptq.setCreateid(createid);
                    ptq.setCreatetime(N_Utils.getSecondTimestamp());
                    ptq.setSchoolid(schoolid);
                    ptqs.add(ptq);
                } else {
                    for (Map sq : sonqlist) {
                        TPaperQtypeQuestion ptq = new TPaperQtypeQuestion();
                        ptq.setPtid(qtype.getId());
                        ptq.setPaperid(paperid);
                        ptq.setQuestionid(sq.get("questionid").toString());
                        ptq.setPtqscore(Double.valueOf(sq.get("score").toString()));
                        ptq.setPtqorder(qorder);
                        ptq.setCreateid(createid);
                        ptq.setCreatetime(N_Utils.getSecondTimestamp());
                        ptq.setSchoolid(schoolid);
                        ptqs.add(ptq);
                    }
                }
                qorder++;
            }
        }
        paperQtypeQuestionMapper.insertList(ptqs);//批量保存答题卡
    }

    /**
     * 生成作业分析
     * @Param [paperid, schoolid]
     * @Author ywx
     * @Date 2020/6/10 9:57
     * @return java.lang.Integer
     **/
    private Integer generatePaperAnalyze(Integer paperid, Integer schoolid) {
        //1.题型统计
        List<Map<String, Object>> rateList = paperQtypeQuestionMapper.paperTypeAnalyze(paperid);
        //2.难易度统计
        List<Map<String, Object>> complexityRateList = paperQtypeQuestionMapper.complexityRateAnalyze(paperid);
        //3.知识点统计
        List<Map<String, Object>> pointRateList = paperQtypeQuestionMapper.pointRateAnalyze(paperid);
        TPaperAnalyze paperAnalyze = new TPaperAnalyze();
        paperAnalyze.setPaperid(paperid);
        paperAnalyze.setQtypejson(JSON.toJSONString(rateList));
        paperAnalyze.setComplexityjson(JSON.toJSONString(complexityRateList));
        paperAnalyze.setPointjson(JSON.toJSONString(pointRateList));
        paperAnalyze.setSchoolid(schoolid);
        paperAnalyzeMapper.insertUseGeneratedKeys(paperAnalyze);
        return paperAnalyze.getId();
    }

    /**
     *功能描述  详情--答题卡
     * @author WN
     * @date 2020/6/11
     * @param  * @param paperid
     * @return com.xhkjedu.vo.paper.PaperScantronVo
     */
    public PaperScantronVo getPaperScantronDetial(Integer paperid){
        PaperVo paper = paperMapper.findById(paperid);
        PaperScantronVo ps = new PaperScantronVo();
        ps.setPaperid(paperid);
        ps.setPapername(paper.getPapername());
        ps.setPapertype(paper.getPapertype());
        ps.setCreatename(paper.getCreatename());
        ps.setCreatetime(paper.getCreatetime());
        ps.setComm(paper.getComm());
        ps.setPapernum(paper.getPapernum());
        ps.setPaperscore(paper.getPaperscore());
        ps.setPaperclass(paper.getPaperclass());
        ps.setDirectorid(paper.getDirectorid());
        ps.setDirectorname(paper.getDirectorname());
        ps.setShowtype(paper.getShowtype());
        ps.setHearfile(paper.getHearfile());

        List<TPaperFile> fils = paperFileService.listObjsByPaperid(paperid);
        ps.setPfiles(fils);
        //获取题型下试题
        List<PaperScantronQtypeVo> lst = paperScantronQtypeMapper.listQtypeScans(paperid);
        ps.setQtypes(lst);

        return ps;

    }

    /**
     * 作业详情--结构性试题
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/6/10 14:33
     * @return com.xhkjedu.vo.paper.PaperVo
     **/
    public PaperVo findById(Integer paperid) {
        PaperVo paper = paperMapper.findById(paperid);
        List<PaperQtypeVo> types = paperMapper.listPaperType(paperid);//获取作业题型列表
        if (paper.getPapertype() == 3 && paper.getPaperstate() == 22) {//靶向作业获取试题发布对象
            List<Map> students = paperStudentMapper.listStudent(paperid);
            List<Integer> classids = students.stream().map(m -> (Integer) m.get("classid")).distinct().collect(Collectors.toList());
            List<Map> classList = classMapper.listByClassIds(classids);//获取班级基本信息列表
            Map<Integer, Map> classMap = classList.stream().collect(Collectors.toMap(m -> (Integer) m.get("classid"), m -> m));
            for (PaperQtypeVo type : types) {
                List<QuestionVo> questions = type.getQuestions();
                for (QuestionVo question : questions) {
                    String questionid = question.getQuestionid();
                    List<Map> qsList = students.stream().filter(s -> s.get("questionids").toString().contains(questionid))
                            .collect(Collectors.toList());
                    Map<Integer, List<Map>> classCollect = qsList.stream().collect(Collectors.groupingBy(m -> (Integer) m.get("classid")
                            , LinkedHashMap::new, Collectors.toList()));
                    List<Map> classes = new ArrayList<>();
                    for (Map.Entry<Integer, List<Map>> entry : classCollect.entrySet()) {
                        Map cmap = classMap.get(entry.getKey());
                        List<String> studentNames = entry.getValue().stream().map(m -> m.get("username").toString()).collect(Collectors.toList());
                        cmap.put("students", studentNames);
                        classes.add(cmap);
                    }
                    //关闭引用检测，避免循环给classes赋值出现"$ref":"$[0]"现象
                    String str = JSON.toJSONString(classes, SerializerFeature.DisableCircularReferenceDetect);
                    question.setClasses(JSON.parseArray(str, Map.class));
                }
                type.setQuestions(questions);
            }
        }
        List<QuestionVo> qlist = new ArrayList<>();
        types.forEach(t -> {
            qlist.addAll(t.getQuestions());
        });
        List<String> questionids = qlist.stream().map(q -> q.getQuestionpid()).distinct().collect(Collectors.toList());
        List<Map> pointList = paperMapper.listQuestionPoints(questionids);
        List<String> questionpids = qlist.stream().filter(q -> q.getQlevel() == 3)
                .map(q -> q.getQuestionpid()).distinct().collect(Collectors.toList());
        List<QuestionVo> mquestions = new ArrayList<>();
        if (N_Utils.isListNotEmpty(questionpids)) {
            mquestions = paperMapper.listQuestionByQuestionIds(questionpids);
        }
        for (PaperQtypeVo type : types) {
            List<QuestionVo> questions = type.getQuestions();
            Map<String, List<QuestionVo>> fq = questions.stream().collect(Collectors.groupingBy(q -> q.getQuestionpid(),
                    LinkedHashMap::new, Collectors.toList()));
            List<QuestionVo> questionList = new ArrayList<>();
            for (Map.Entry<String, List<QuestionVo>> entry : fq.entrySet()) {
                List<QuestionVo> list = entry.getValue();
                QuestionVo tq = list.get(0);
                QuestionVo q;
                if (tq.getQlevel() == 3) {//复合题
                    String questionpid = tq.getQuestionpid();
                    q = mquestions.stream().filter(mq -> mq.getQuestionid().equals(questionpid)).findFirst().orElse(null);
                    double score = list.stream().mapToDouble(QuestionVo::getScore).sum();
                    q.setScore(score);
                    q.setPtqorder(tq.getPtqorder());
                    q.setSonqlist(JSON.parseArray(JSON.toJSONString(list), Map.class));
                } else {
                    q = tq;
                }
                String questionid = q.getQuestionid();
                List<Map> points = pointList.stream().filter(qp -> qp.get("questionid").toString().equals(questionid))
                        .collect(Collectors.toList());
                q.setPoints(JSON.parseArray(JSON.toJSONString(points), PointVo.class));
                questionList.add(q);
            }
            type.setQuestions(questionList);
        }
        paper.setTypes(types);
        return paper;
    }

    /**
     * 作业列表
     * @Param [paper]
     * @Author ywx
     * @Date 2020/6/11 16:30
     * @return java.util.List<com.xhkjedu.vo.paper.PaperListVo>
     **/
    public List<PaperListVo> findAll(PaperSearchVo paper) {
        if(paper.getPsstate()!=null && paper.getPsstate() == 21){
            //未布置作业
            return paperMapper.listWfbPapers(paper);
        }else{
            //全部作业
            List<PaperListVo>  list = paperMapper.listAll(paper);
            return getPaperListVo(list);
        }
    }

    /**
     * 设置批改方式
     * @Param [param]
     * @Author ywx
     * @Date 2020/6/12 7:57
     * @return void
     **/
    @Transactional(rollbackFor = Exception.class)
    public void setCheckType(PaperParam param) throws Exception {
        Integer checktype = param.getChecktype();//批改方式1教师批改2学生互改3指定学生批改
        Integer paperid = param.getPaperid();//试卷ID

        try {
            paperMapper.updateCheckType(paperid, checktype);//设置批改方式
            if (checktype == 1){//教师批阅
                if (N_Utils.isEmptyInteger(param.getTeacherid())) {//不同班级分别指定教师
                    List<PaperCheckParam> checkParams = JSON.parseArray(param.getClassids(), PaperCheckParam.class);
                    paperStudentMapper.updateCheckId2(paperid, checkParams);
                } else {//不同班级指定同一个教师
                    paperStudentMapper.updateCheckId(paperid,param.getTeacherid());//设置批改人
                }
            } else {
                List<PaperCheckParam> checkParams = JSON.parseArray(param.getClassids(), PaperCheckParam.class);
                List<PaperCheckParam> classStudents = paperStudentMapper.listStudentIdByPaperIdClassId(paperid, checkParams);
                Integer[] classids_ = new Integer[checkParams.size()];
                Map<Integer, Integer> map = new HashMap<>();
                for (int i = 0; i < checkParams.size(); i++) {
                    PaperCheckParam gs = checkParams.get(i);
                    List<Integer> studentids = classStudents.stream().filter(cs -> cs.getClassid().equals(gs.getClassid()))
                            .map(PaperCheckParam::getCheckid).collect(Collectors.toList());
                    gs.setStudentids(studentids);
                    if (checktype == 2) {
                        //学生互改
                        if (gs.getStudentids().size() == 1) {
                            gs.setCheckids(gs.getStudentids());
                        } else {
                            List<Integer> stuids = new ArrayList<>();
                            List<Integer> stuids_ = gs.getStudentids();
                            stuids.addAll(gs.getStudentids());
                            gs.setStudentids(stuids);

                            //互相批改作业,则把用户集合打散重新组成新的集合
                            Collections.shuffle(stuids_);
                            while (N_Utils.listNeworder(stuids, stuids_)) {
                                Collections.shuffle(stuids_);
                            }

                            gs.setCheckids(stuids_);
                        }
                        checkParams.set(i, gs);
                    } else if (checktype == 3) {
                        //如果选择的批改人只有一个人,则要自己批改自己的作业
                        if (gs.getCheckids().size() > 1) {
                            //设置批改人
                            Map<Integer, Integer> checkMap = this.setStudentIdCheckerId(gs);
                            map.putAll(checkMap);
                        }
                    }

                    classids_[i] = gs.getClassid();

                }
                List<TPaperStudent> list = setStudentCheckId(paperid, checkParams, checktype, map);//设置学生批改人对应关系
                paperStudentMapper.batchUpdateCheckId(list);//设置批改人
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("设置批改方式失败："+e.getMessage());
            throw new Exception("设置批改方式失败");
        }
    }

    /**
     * 设置学生批改人对应关系
     * @Param [paperid, checkParams, checktype, map]
     * @Author ywx
     * @Date 2020/6/12 9:05
     * @return java.util.List<com.xhkjedu.model.paperstudent.TPaperStudent>
     **/
    private List<TPaperStudent> setStudentCheckId(Integer paperid, List<PaperCheckParam> checkParams, Integer checktype, Map<Integer, Integer> map) {
        List<TPaperStudent> list = new ArrayList<>();
        for(int i=0;i<checkParams.size();i++){
            PaperCheckParam cp = checkParams.get(i);
            for(int j=0;j<cp.getStudentids().size();j++){
                TPaperStudent ps = new TPaperStudent();
                ps.setPaperid(paperid);
                ps.setClassid(cp.getClassid());
                Integer studentid = cp.getStudentids().get(j);
                ps.setStudentid(studentid);
                Integer checkid;
                if(checktype==1){
                    checkid = cp.getCheckids().get(0);
                } else if(checktype==2){
                    checkid = cp.getCheckids().get(j);
                }else{
                    //第一种只有一个批改人的
                    if(cp.getCheckids().size()==1){
                        checkid = cp.getCheckids().get(0);
                    }else{
                        checkid = map.get(studentid);
                    }
                }
                ps.setCheckid(checkid);
                list.add(ps);
            }
        }
        return list;
    }

    //设置作业批改人（选择指定学生）
    private Map<Integer,Integer> setStudentIdCheckerId(PaperCheckParam gs){
        Map<Integer,Integer> map = new HashMap<>();
        //选择学生批改
        List<Integer> allstudents = new ArrayList<>();//所有有作业的学生
        allstudents.addAll(gs.getStudentids());
        //去除选中的是批改人的作业
        for(int k=0;k<gs.getCheckids().size();k++){
            allstudents.remove(gs.getCheckids().get(k));//把批改人的作业去除
        }

        List<List<Integer>> result = N_Utils.averageAssignList(allstudents, gs.getCheckids().size());
        Collections.shuffle(gs.getCheckids());//重置批改作业人顺序

        for(int l=0;l<result.size();l++){
            List<Integer> groupstu = new ArrayList<>();
            groupstu.addAll(result.get(l));

            if(l==0){
                //把最有一个用户的作业插入这个集合中（避免数据自己批改自己的作业）
                groupstu.add(gs.getCheckids().get(result.size()-1));
            }else{
                //否则把上一个加入到作业集合中（避免数据自己批改自己的作业）
                int n = l-1;
                groupstu.add(gs.getCheckids().get(n));
            }
            for(int m=0;m<groupstu.size();m++){
                map.put(groupstu.get(m), gs.getCheckids().get(l));//设置批改人
            }
        }
        return map;
    }

    /**
     *获取批改学生列表
     * @Param [paperid, checkid, classid]
     * @Author ywx
     * @Date 2020/6/12 11:00
     * @return com.xhkjedu.vo.paper.CheckClassVo
     **/
    public CheckClassVo listStudentsByPaperIdCheckId(Integer paperid, Integer checkid, Integer classid) {
        CheckClassVo checkVo = paperMapper.listStudentsByPaperIdCheckId(paperid, checkid, classid);
        Integer ytjnum = checkVo.getYtjnum();
        checkVo.setWtjnum(checkVo.getClassnum()-ytjnum);
        if (!N_Utils.isEmptyInteger(ytjnum)){
            double scale = N_Utils.getIntegerDivideAndMulitiply(checkVo.getYpynum(),ytjnum);
            checkVo.setScale(scale);
        } else {
            checkVo.setScale(0);
        }
        if(checkVo.getYpynum() == null){
            checkVo.setYpynum(0);
        }
        return checkVo;
    }

    /**
     * 教师批阅列表
     * @Param [checkid]
     * @Author ywx
     * @Date 2020/6/18 14:55
     * @return java.util.List<com.xhkjedu.vo.paper.PaperListVo>
     **/
    public List<PaperListVo> correctList(Integer checkid) {
        List<PaperListVo> list = paperMapper.correctList(checkid);
        return getPaperListVo(list);
    }

    /**
     * 作业列表
     * @Param [list]
     * @Author ywx
     * @Date 2020/6/18 15:09
     * @return java.util.List<com.xhkjedu.vo.paper.PaperListVo>
     **/
    private List<PaperListVo> getPaperListVo(List<PaperListVo> list) {
        for (PaperListVo p : list) {
            if (p.getPaperstate() == 21){//未布置
                p.setClasses(null);
            } else {
                List<PaperClassVo> classes = p.getClasses();
                for (PaperClassVo c : classes) {
                    if (!N_Utils.isEmptyInteger(c.getClassnum())) {
                        c.setWtjnum(c.getClassnum() - c.getYtjnum());
                    }
                }
            }
        }
        return list;
    }

    /**
     * 作业附件列表
     * @Param [paperid]
     * @Author ywx
     * @Date 2020/6/23 21:53
     * @return java.util.List<com.xhkjedu.model.paper.TPaperFile>
     **/
    public List<TPaperFile> listPaperFile(Integer paperid, Integer fileclass) {
        return paperMapper.listPaperFile(paperid, fileclass);
    }

    //获取作业原文件保存地址列表
    public List<String> listSourcePath(Integer paperid) {
        return paperMapper.listSourcePath(paperid);
    }

    //获取今天布置作业数量
    public String getPaperNum(String subjectid, Integer createid, Integer createtime) {
        Integer num = paperMapper.getPaperNum(subjectid, createid, createtime);
        String paperNum = "("+ N_Utils.NumberToChn(num)+")";
        return paperNum;
    }

    //获取作业状态
    public Integer getPaperState(Integer paperid) {
        return paperMapper.getPaperState(paperid);
    }

    //获取批阅班级
    public List<Map> listPaperClass(Integer paperid, Integer checkid) {
        return paperMapper.listPaperClass(paperid, checkid);
    }
}
