package com.xhkjedu.sexam.service.paper;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.sexam.mapper.exam.ESubjectMapper;
import com.xhkjedu.sexam.mapper.paper.*;
import com.xhkjedu.sexam.mapper.paperstudent.EPaperStudentMapper;
import com.xhkjedu.sexam.mapper.paperstudent.EPaperStudentQuestionMapper;
import com.xhkjedu.sexam.mapper.system.UserBasketMapper;
import com.xhkjedu.sexam.model.paper.*;
import com.xhkjedu.sexam.model.paperstudent.EPaperStudentQuestion;
import com.xhkjedu.sexam.utils.ConvertUtil;
import com.xhkjedu.sexam.utils.ExamUtil;
import com.xhkjedu.sexam.vo.paper.*;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 题库题型
 * @Author WN
 * Date 2022/7/19 9:07
 **/
@Service
@Slf4j
public class EPaperQtypeService {
    @Resource
    private EPaperQtypeMapper ePaperQtypeMapper;
    @Resource
    private EPaperQtypeQuestionMapper ePaperQtypeQuestionMapper;
    @Resource
    private EPaperMapper ePaperMapper;
    @Resource
    private EPaperAnalyzeMapper ePaperAnalyzeMapper;
    @Resource
    private ESubjectMapper eSubjectMapper;
    @Resource
    private EPaperFileMapper ePaperFileMapper;
    @Resource
    private UserBasketMapper userBasketMapper;
    @Resource
    private EPaperStudentQuestionMapper ePaperStudentQuestionMapper;
    @Resource
    private EPaperStudentMapper ePaperStudentMapper;
    @Autowired
    private ConvertUtil convertUtil;


    /**
     * @Description 保存题库试卷
     * @Param [paper]
     * @Return void
     * @Author wn
     * @Date 2022/7/19 9:10
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo saveQtPaper(EPaper paper) {
        //获取考试科目信息
        EExamSubjectPaperVo espVo = ePaperMapper.getPaperParamsByEpid(paper.getEpid());
        if(espVo.getExamstate() > 0){
            return new ResultVo(1,"不能进行操作");
        }

        List<EPaperQtype> qtypelist = paper.getQtypelist();
        /*if (paper.getPtype() == 2) {
            List<EPaperQtypeQuestion> questions = new ArrayList<>();
            qtypelist.forEach(t -> {
                questions.addAll(t.getQuestions());
            });
            long count = questions.stream().map(q -> q.getQn()).distinct().count();
            if (count < questions.size()) return new ResultVo(1, "题号不能重复");
        }*/

        //说明已经有改考试对应的试卷，删除试卷中试题，试卷分析
        ePaperQtypeMapper.deleteByEpid(espVo.getEpid());
        ePaperAnalyzeMapper.deleteByEpid(espVo.getEpid());
        ePaperFileMapper.deleteByEpid(espVo.getEpid());

        List<EPaperQtypeQuestion> queslist = new ArrayList<>();//存放试题
        paper.setEpid(espVo.getEpid());
        setEPaperBaseDetail(paper,qtypelist);
        //保存试卷信息
        ePaperMapper.updatePaperInfo(paper);
        //保存题型试题信息
        savePaperQtype(paper,qtypelist,queslist);

        //保存试卷分析
        if(paper.getPtype() == 1){
            savePaperAnalyzeForQuestion(paper);
        }else{
            List<EPaperFile> pfiles = paper.getPfiles();//附件
            if(paper.getHasfile() == 1){
                setPaperFiles(paper,pfiles);
                ePaperFileMapper.insertList(pfiles);
            }
            savePaperAnalyzeForFj(paper,qtypelist,queslist);
        }

        //更加试卷状态是否需要生成分析和更改科目状态
        if(espVo.getExammode() == 1 && paper.getPstate()!=null && paper.getPstate() == 1){
            //如果提交试卷，更改科目状态
            eSubjectMapper.updateExamSubjectState(1,espVo.getEsid());
        }
        //保存后清除试题栏中试题
        userBasketMapper.deleteByUseridAndSubjectid(paper.getCreateid(),espVo.getSubjectid());
        return new ResultVo(0,"保存成功",espVo.getEpid());
    }

    //设置试卷基本信息
    private void setEPaperBaseDetail(EPaper paper,List<EPaperQtype> qtypelist){
        if(paper.getPtype() == 2 && paper.getPfiles()!=null && paper.getPfiles().size()>0){
            paper.setHasfile(1);
        }else {
            paper.setHasfile(0);
        }
        int timestamp = N_Utils.getSecondTimestamp();
        double pscore = qtypelist.stream().collect(Collectors.summingDouble(EPaperQtype:: getEptscore));
        int pnum = qtypelist.stream().collect(Collectors.summingInt(EPaperQtype:: getEptnum));
        paper.setPnum(pnum);
        paper.setPscore(pscore);
        paper.setCreatetime(timestamp);
        paper.setHandletime(timestamp);
        paper.setHandleid(paper.getCreateid());
        if(paper.getPtype() == 1){
            paper.setAnswered(1);//题库已设置正确答案
        }else{
            paper.setAnswered(0);
        }
    }

    //保存试卷题型试题信息
    private void savePaperQtype(EPaper epaper,List<EPaperQtype> qtypelist,List<EPaperQtypeQuestion> qtqs){
        for(EPaperQtype qtype : qtypelist){
            qtype.setEpid(epaper.getEpid());
            qtype.setCreateid(epaper.getHandleid());
            qtype.setCreatetime(epaper.getHandletime());
            qtype.setEptname(qtype.getEptname().trim());
        }
        ePaperQtypeMapper.insertList(qtypelist);//保存题型
        for(EPaperQtype qtype : qtypelist){
            List<EPaperQtypeQuestion> questions = qtype.getQuestions();
            Integer ctype = qtype.getCtype();
            Integer ptype = epaper.getPtype();

            for (int i = 0; i < questions.size(); i++) {
                EPaperQtypeQuestion q=questions.get(i);
                q.setEpid(epaper.getEpid());
                q.setEptid(qtype.getId());
                if(q.getOptionnum()==null){
                    q.setOptionnum(0);
                }
                Integer qorder = q.getQorder();
                if (ptype == 1 && ctype != 11) {
                    q.setQn(qorder.toString());
                } else if (ptype == 1 && ctype == 11) {
                    q.setQn(qorder + "." + (i + 1));
                }
                if(q.getCtype() == 14){
                    q.setGnum(900);//语文作文格数
                }else if(q.getCtype() == 15){
                    q.setGnum(10);//英语作文行数
                }

                qtqs.add(q);
            }
        }
        ePaperQtypeQuestionMapper.insertList(qtqs);
    }

    //设置附件
    private void setPaperFiles(EPaper paper,List<EPaperFile> pfiles) {
        if(paper.getHasfile() == 1){
            int order= 1;
            for(EPaperFile pf :pfiles){
                pf.setCreateid(paper.getCreateid());
                pf.setCreatetime(paper.getHandletime());
                pf.setEpid(paper.getEpid());
                pf.setFileorder(order);
                order ++;
            }
        }
    }

    //保存试卷分析--题库
    private void savePaperAnalyzeForQuestion(EPaper ePaper){
        //保存之前先清除之前的试卷分析
        ePaperAnalyzeMapper.deleteByEpid(ePaper.getEpid());
        //总体分析（主观题、客观题）
        List<EPaperQtypeVo> qtypelist = ePaperQtypeMapper.listPaperQtypeQuestions(ePaper.getEpid());//试卷题型试题信息
        List<EPaperQtypeQuestionVo> queslist = new ArrayList<>();//试卷中所有试题(子题)
        List<EPaperQPointVo> quespoints = new ArrayList<>();//试卷中所有单题和子题以及对应知识点

        //处理题型1单选题2多选题3主观题4判断对错5判断√×6判断TF7完形填空8阅读理解10任务型阅读11综合题12听力
        List<EPaperQsVo> typelist = new ArrayList<>();//题型分析
        //处理出试卷中所有试题、知识点
        for(EPaperQtypeVo qt : qtypelist){
            for(EPaperQtypeQuestionVo q : qt.getQuestions()){
                //处理试题关联知识点
                List<EPaperQPointVo> pointslist = q.getPoints();
                if(pointslist != null && pointslist.size()>0){
                    for(EPaperQPointVo point : pointslist){
                        EPaperQPointVo p = new EPaperQPointVo();
                        p.setPointid(point.getPointid());
                        p.setPointname(point.getPointname());
                        p.setQuestionid(q.getQuestionid());
                        p.setQorder(q.getQorder());
                        p.setScore(q.getScore());
                        quespoints.add(p);
                    }
                }
                if(q.getQlevel()==1){
                    q.setQuestionpid("000");
                }
                queslist.add(q);
            }

            double storerate = N_Utils.getDoubleDivideAndMulitiply(qt.getEptscore(), ePaper.getPscore());
            EPaperQsVo tvo = new EPaperQsVo();
            tvo.setQtname(qt.getEptname());
            tvo.setNum(qt.getEptnum());
            tvo.setScore(qt.getEptscore());
            tvo.setSrate(storerate);
            typelist.add(tvo);
        }

        //获取出所有单题和母题,进行判断区分
        Map<String,List<EPaperQtypeQuestionVo>> quesMap = queslist.stream().collect(Collectors.groupingBy(EPaperQtypeQuestionVo:: getQuestionpid, Collectors.toList()));
        List<EPaperQtypeQuestionVo> mquestions = new ArrayList<>();//仅存放单题和母题
        for(Map.Entry<String, List<EPaperQtypeQuestionVo>> entry : quesMap.entrySet()){
            if(entry.getKey().equals("000")){
                for(EPaperQtypeQuestionVo dq : entry.getValue()){
                    if(N_Utils.isObjectiveQuestion(dq.getCtype())){
                        //判断试题是否是客观题,暂时用mctype进行标识
                        dq.setMctype(111);
                    }else{
                        dq.setMctype(112);
                    }
                    mquestions.add(dq);
                }
            }else{
                EPaperQtypeQuestionVo mq = new EPaperQtypeQuestionVo();
                List<EPaperQtypeQuestionVo> sonques = entry.getValue();
                int k = 0;//如果k大于1说明有小题是主观题，则母题为主观题
                double score = 0;
                for(EPaperQtypeQuestionVo sq : sonques){
                    if(!N_Utils.isObjectiveQuestion(sq.getCtype())){
                        k++;
                    }
                    score = N_Utils.getDoubleSum(score,sq.getScore());
                }

                EPaperQtypeQuestionVo qobj = sonques.get(0);
                mq.setQuestionid(qobj.getQuestionpid());
                mq.setComplexity(qobj.getMcomplexity());
                mq.setScore(score);
                if(k == 0){
                    mq.setMctype(111);
                }else{
                    mq.setMctype(112);
                }
                mquestions.add(mq);
            }
        }

        //试题总体分布进行分析
        //客观题集合
        List<EPaperQtypeQuestionVo> ktlst = mquestions.stream().filter(q->q.getMctype() == 111).collect(Collectors.toList());
        int ktnum = ktlst.size();
        double ktscore = ktlst.stream().collect(Collectors.summingDouble(EPaperQtypeQuestionVo:: getScore));
        double ktnrate = N_Utils.getIntegerDivideAndMulitiply(ktnum, ePaper.getPnum());
        double ktsrate = N_Utils.getDoubleDivideAndMulitiply(ktscore, ePaper.getPscore());
        List<EPaperQsVo> ranglist = new ArrayList<>();
        ranglist.add(new EPaperQsVo("客观题",ktscore,ktnum,ktsrate,ktnrate));
        EPaperQsVo zgq = new EPaperQsVo();
        zgq.setQtname("主观题");
        zgq.setNum(ePaper.getPnum() - ktnum);
        zgq.setNrate(N_Utils.getDoubleReduce(100.0,ktnrate));
        zgq.setScore(N_Utils.getDoubleReduce(ePaper.getPscore(),ktscore));
        zgq.setSrate(N_Utils.getDoubleReduce(100.0,ktsrate));
        ranglist.add(zgq);
        Map ztmap = new HashMap<>();
        ztmap.put("pnum", ePaper.getPnum());
        ztmap.put("pscore",ePaper.getPscore());
        ztmap.put("ranglist",ranglist);

        //难易度
        Map<Integer,List<EPaperQtypeQuestionVo>> complxmap =  mquestions.stream().collect(Collectors.groupingBy(EPaperQtypeQuestionVo:: getComplexity, Collectors.toList()));
        List<Map> clist = new ArrayList<>();
        for(Map.Entry<Integer, List<EPaperQtypeQuestionVo>> entry : complxmap.entrySet()){
            Map cmap = new HashMap();
            cmap.put("level",entry.getKey());
            List<EPaperQtypeQuestionVo> aq = entry.getValue();
            double cscore = aq.stream().collect(Collectors.summingDouble(EPaperQtypeQuestionVo:: getScore));
            double scorerate = N_Utils.getDoubleDivideAndMulitiply(cscore, ePaper.getPscore());
            cmap.put("score",cscore);
            cmap.put("srate",scorerate);
            clist.add(cmap);
        }

        //知识点
        Map<String,List<EPaperQPointVo>> pointmap =  quespoints.stream().collect(Collectors.groupingBy(EPaperQPointVo:: getPointid, Collectors.toList()));
        List<Map> pointlist = new ArrayList<>();
        for(Map.Entry<String, List<EPaperQPointVo>> entry : pointmap.entrySet()){
            Map pm = new HashMap();
            List<EPaperQPointVo> pvo = entry.getValue();
            double cscore = pvo.stream().collect(Collectors.summingDouble(EPaperQPointVo:: getScore));
            double scorerate = N_Utils.getDoubleDivideAndMulitiply(cscore, ePaper.getPscore());
            List<Integer> thlist = pvo.stream().map(EPaperQPointVo :: getQorder).collect(Collectors.toList());
            thlist = thlist.stream().distinct().collect(Collectors.toList());
            pm.put("pointname",pvo.get(0).getPointname());
            pm.put("score",cscore);
            pm.put("srate",scorerate);
            pm.put("order",JSON.toJSONString(thlist));
            pointlist.add(pm);
        }

        EPaperAnalyze epa = new EPaperAnalyze();
        epa.setEpid(ePaper.getEpid());
        epa.setAlljson(JSON.toJSONString(ztmap));//总体分析
        epa.setQnumjson(JSON.toJSONString(typelist));//试题栏题型分析
        epa.setComplexityjson(JSON.toJSONString(clist));//难易度分析
        epa.setPointjson(JSON.toJSONString(pointlist));//知识点分析
        ePaperAnalyzeMapper.insertUseGeneratedKeys(epa);

    }

    //保存试卷分析--附件
    private void savePaperAnalyzeForFj(EPaper ePaper,List<EPaperQtype> fjtypelist,List<EPaperQtypeQuestion> queslist){
        //保存之前先清除之前的试卷分析
        ePaperAnalyzeMapper.deleteByEpid(ePaper.getEpid());
        //总体分析（主观题、客观题）
        //处理题型1单选题2多选题3主观题4判断对错5判断√×6判断TF7完形填空8阅读理解10任务型阅读11综合题12听力
        int znum = 0;
        double zscore = 0;
        int knum = 0;
        double kscore = 0;
        for(EPaperQtypeQuestion q : queslist){
            if(N_Utils.isObjectiveQuestion(q.getCtype())){
                knum ++;
                kscore = kscore + q.getScore();
            }else{
                znum ++;
                zscore = zscore + q.getScore();
            }
        }

        double znumrate = N_Utils.getIntegerDivideAndMulitiply(znum, ePaper.getPnum());
        double knumrate = N_Utils.getDoubleReduce(100.0,znumrate);;

        double zscorerate = N_Utils.getDoubleDivideAndMulitiply(zscore, ePaper.getPscore());
        double kscorerate = N_Utils.getDoubleReduce(100.0,zscorerate);

        List<EPaperQsVo> ranglist = new ArrayList<>();
        ranglist.add(new EPaperQsVo("主观题",zscore,znum,zscorerate,znumrate));
        ranglist.add(new EPaperQsVo("客观题",kscore,knum,kscorerate,knumrate));

        Map ztmap = new HashMap<>();
        ztmap.put("pnum", ePaper.getPnum());
        ztmap.put("pscore",ePaper.getPscore());
        ztmap.put("ranglist",ranglist);

        //题型分布(按照名称进行分组)
        fjtypelist.stream().sorted(Comparator.comparing(EPaperQtype::getEptorder)).collect(Collectors.toList());
        Map<String,List<EPaperQtype>> qtypemap =  fjtypelist.stream().collect(Collectors.groupingBy(EPaperQtype:: getEptname, Collectors.toList()));
        List<EPaperQsVo> qtlist = new ArrayList<>();
        for(Map.Entry<String, List<EPaperQtype>> entry : qtypemap.entrySet()){
            List<EPaperQtype> aq = entry.getValue();
            int num = aq.stream().mapToInt(EPaperQtype::getEptnum).sum();
            double tscore = aq.stream().collect(Collectors.summingDouble(EPaperQtype:: getEptscore));
            double storerate = N_Utils.getDoubleDivideAndMulitiply(tscore, ePaper.getPscore());
            EPaperQsVo qvo = new EPaperQsVo();
            qvo.setQtname(entry.getKey());
            qvo.setNum(num);
            qvo.setScore(tscore);
            qvo.setSrate(storerate);
            qtlist.add(qvo);
        }

        EPaperAnalyze epa = new EPaperAnalyze();
        epa.setEpid(ePaper.getEpid());
        epa.setAlljson(JSON.toJSONString(ztmap));
        epa.setQnumjson(JSON.toJSONString(qtlist));
        ePaperAnalyzeMapper.insertUseGeneratedKeys(epa);
    }

    /**
     * @Description  试卷详情
     * @Param [epid]
     * @Return java.util.Map
     * @Author wn
     * @Date 2022/7/19 9:10
     **/
    public Map getPaperQtDetail(Integer esid) {
        Map map = ePaperMapper.getExamPaperDetailByEsid(esid);//试卷信息
        List<EPaperQtypeVo> fjtypelist = new ArrayList<>();
        List<Map> files = new ArrayList<>();
        if(map.get("epid") != null){
            Integer epid = Integer.parseInt(map.get("epid").toString()) ;
            Integer ptype = Integer.parseInt(map.get("ptype").toString()) ;//试卷类型1题库2附件
            if(ptype == 1){
                fjtypelist = ePaperQtypeMapper.listPaperQtypeQuestions(epid);//试卷题型试题信息（题库）
                setEPaperQtypeForQues(fjtypelist);

            }else{
                fjtypelist = ePaperQtypeMapper.listPaperQtypeQuesitonsForFj(epid);//试卷题型试题信息（附件）
                files = ePaperFileMapper.listPaperFiles(epid);

            }
        }
        map.put("qtypes",fjtypelist);
        map.put("pfiles",files);
        return map;
    }

    private void setEPaperQtypeForQues(List<EPaperQtypeVo> fjtypelist){
        for(EPaperQtypeVo qt : fjtypelist){
            List<EPaperQtypeQuestionVo> qlist = qt.getQuestions();
            List<EPaperQtypeQuestionVo> rtnqlist = new ArrayList<>();//保存处理后的试题
            String qpid = "";//母题id
            List<EPaperQtypeQuestionVo> sonqlist = new ArrayList<>();
            for(EPaperQtypeQuestionVo q : qlist){
                //试题类型1单题2母题3子题
                if(q.getQlevel() == 3){
                   if(!q.getQuestionpid().equals(qpid)){
                       sonqlist = qlist.stream().filter(o -> o.getQuestionpid().equals(q.getQuestionpid())).collect(Collectors.toList());
                       EPaperQtypeQuestionVo mq = new EPaperQtypeQuestionVo();
                       mq.setQuestionid(q.getQuestionpid());
                       mq.setCtype(q.getMctype());
                       mq.setQtypeid(q.getMqtypeid());
                       mq.setQtypename(q.getMqtypename());
                       mq.setQstem(q.getMqstem());
                       mq.setComplexity(q.getMcomplexity());
                       mq.setQanalyze(q.getMqanalyze());
                       mq.setQanswer(q.getMqanswer());
                       mq.setQorder(q.getQorder());
                       mq.setQlevel(q.getMqlevel());
                       List<EPaperQPointVo> allpoint = new ArrayList<>();
                       for(EPaperQtypeQuestionVo sq : sonqlist){
                           List<EPaperQPointVo> sqpoints = sq.getPoints();
                           for(EPaperQPointVo p : sqpoints){
                               if(!isExistEPaperPoints(allpoint,p)){
                                   allpoint.add(p);
                               }
                           }
                       }
                       Double mscore = sonqlist.stream().collect(Collectors.summingDouble(EPaperQtypeQuestionVo:: getScore));
                       mq.setScore(mscore);
                       mq.setSonques(sonqlist);
                       mq.setPoints(allpoint);
                       rtnqlist.add(mq);
                   }
                    qpid = q.getQuestionpid();
                }else{
                    EPaperQtypeQuestionVo mq = new EPaperQtypeQuestionVo();
                    BeanUtils.copyProperties(q,mq);
                    mq.setCtype(mq.getCtype());
                    rtnqlist.add(mq);
                }
            }
            qt.setQuestions(rtnqlist);
        }

    }

    private boolean isExistEPaperPoints(List<EPaperQPointVo> allpoint,EPaperQPointVo p){
        for(EPaperQPointVo pvo : allpoint){
            if(p.getPointid().equals(pvo.getPointid())){
                return true;
            }
        }
        return false;
    }

    /**
     * @Description 设置试卷正确答案
     * @Param [ePaper]
     * @Return void
     * @Author wn
     * @Date 2022/7/25 15:12
     **/
    @Transactional(rollbackFor = Exception.class)
    public void saveQuesitonAnswer(EPaper ePaper){
        List<EPaperQtypeQuestion> questions = ePaper.getQuestions();
        if(questions != null && questions.size() > 0){
            ePaperQtypeMapper.updateBatchQuestionAnswer(questions);
            ePaper.setAnswered(1);
            ePaperMapper.updateEPaperAnswered(ePaper);
            //设置完答案进行匹配
            setChangeQuestionAnswer(questions,ePaper.getEpid());
        }
    }

    //对于已经开始考试的试卷修改正确答案重新判断试题
    private void setChangeQuestionAnswer(List<EPaperQtypeQuestion> questions,Integer epid){
        //获取考试对应的状态,如果考试状态未进行中或者已结束，则需要更改学生已提交试卷中对应试题的答案
        Map map = ePaperMapper.getExamPaperAndSubject(epid);
        Integer examstate = Integer.parseInt(map.get("examstate").toString());
        if(examstate > 0){
            //获取试卷中原试题答案
            List<EPaperQtypeQuestion> yqlist = ePaperQtypeMapper.listQuestionsByEpid(epid);
            List<EPaperQtypeQuestion> changeQs = new ArrayList<>();//改变答案的试题
            for(EPaperQtypeQuestion tq : questions){
                EPaperQtypeQuestion yq = yqlist.stream().filter(y -> y.getEptqid().equals(tq.getEptqid())).findFirst().orElse(null);
                if(!tq.getAnswer().equalsIgnoreCase(yq.getAnswer())){
                    //说明新设置的答案和原设置的答案不一致，则为变动的
                    tq.setCtype(yq.getCtype());
                    tq.setScore(yq.getScore());
                    changeQs.add(tq);
                }
            }
            if(changeQs.size()>0){
                //说明有试题答案变更，则更改学生试卷试题表中原批改内容
                List<Integer> eptqids = changeQs.stream().map(EPaperQtypeQuestion::getEptqid).collect(Collectors.toList());
                //学生试卷试题情况
                List<EPaperStudentQuestion> psqlist = ePaperStudentQuestionMapper.listPaperStudentQuestionByeptqid(epid,eptqids);
                if(N_Utils.isListNotEmpty(psqlist)){
                    List<EPaperStudentQuestion> uplist = new ArrayList<>();//要更新的
                    for(EPaperQtypeQuestion q : changeQs){
                        List<String> qanswers = JSON.parseArray(q.getAnswer(),String.class);
                        //处理指定试题
                        List<EPaperStudentQuestion> cqlist = psqlist.stream().filter(s -> s.getEptqid().equals(q.getEptqid())).collect(Collectors.toList());
                        for(EPaperStudentQuestion cq : cqlist){
                            Double stuscore = 0D;
                            List<String> stuanswers = JSON.parseArray(cq.getStuanswer(),String.class);
                            if(N_Utils.isListNotEmpty(stuanswers)){
                                if(q.getCtype() == 1 || q.getCtype() == 4 || q.getCtype() == 5 || q.getCtype() == 6){
                                    if(q.getAnswer().equalsIgnoreCase(cq.getStuanswer())){
                                        stuscore = q.getScore();
                                    }
                                }else if(q.getCtype() == 2){
                                    if(stuanswers.get(0).length() <= qanswers.get(0).length()){
                                        String[] qanswerList = qanswers.get(0).split("");
                                        String[] stuanswerList = stuanswers.get(0).split("");
                                        int rightNum = 0;//选对个数
                                        for(String sa : stuanswerList){
                                            int right = 0;
                                            for(String qa : qanswerList){
                                                if(qa.equals(sa)){
                                                    right = 1;
                                                    rightNum ++;
                                                }
                                            }
                                            if(right == 0){//说明选错
                                                rightNum = 0;
                                                break;
                                            }
                                        }
                                        if(rightNum>0){
                                            if(qanswerList.length == rightNum){
                                                //全选对
                                                stuscore = q.getScore();
                                            }else if (qanswerList.length > rightNum){
                                                //少选得半分
                                                stuscore = ExamUtil.div(q.getScore(), 2, 1);
                                            }
                                        }
                                    }
                                }else if(q.getCtype() == 7 || q.getCtype() == 8 || q.getCtype() == 10){
                                    //完形填空、阅读理解、任务型阅读
                                    Double qscore = ExamUtil.div(q.getScore(),qanswers.size());
                                    Double stuScoreDouble = 0d;
                                    for(int i=0;i<qanswers.size();i++){
                                        if(qanswers.get(i).equalsIgnoreCase(stuanswers.get(i))){
                                            stuScoreDouble = ExamUtil.add(stuScoreDouble,qscore);
                                        }
                                    }
                                    stuscore = ExamUtil.round(stuScoreDouble,1);
                                }
                                cq.setStuscore(stuscore);
                                uplist.add(cq);
                            }
                        }
                    }

                    if(N_Utils.isListNotEmpty(uplist)){
                        //批量更新学生试题分值
                        ePaperStudentQuestionMapper.updateBatchStuQuestionScore(uplist);
                        //更新学生试卷分值
                        ePaperStudentMapper.updateBathStudentPaperScoreByEpid(epid);
                    }
                }
            }
        }
    }

    /**
     * @Description 获取制作答题卡需要的试卷信息
     * @Param [epid]
     * @Return java.util.Map
     * @Author wn
     * @Date 2022/7/22 10:19
     **/
    public Map getPaperAndQuesitons(Integer epid){
        Map eps = ePaperMapper.getExamPaperAndSubject(epid);//考试考试科目名称
        List<Map> qtypes = new ArrayList<>();//题型试题
        if(eps!=null && eps.get("ptype")!=null){
            int ptype = Integer.parseInt(eps.get("ptype").toString());//试卷类型1题库2附件
            qtypes = ePaperQtypeMapper.listPaperqtypeQuestionsForScan(epid);
            if(ptype == 1){
                //处理试卷中试题选项数量
                for(Map qtm : qtypes){
                    List<Map> qlist = (List<Map>) qtm.get("questions");
                    for(Map qm : qlist){
                        String qoption = qm.get("qoption").toString();
                        Integer ctype = Integer.parseInt(qm.get("ctype").toString());
                        if(ctype == 1 || ctype ==2 || ctype==4 || ctype ==5 || ctype==6 ){
                            List<String> strlst = JSON.parseArray(qoption,String.class);
                            qm.put("qoption","");
                            qm.put("optionnum",strlst.size());
                        }else if(ctype == 7 || ctype == 8 || ctype ==10){
                            //完形填空、阅读理解、任务型阅读
                            List<QuestionOptionVo> qopt = JSON.parseArray(qoption,QuestionOptionVo.class);
                            qm.put("optionnum",qopt.get(0).getSqoptions().size());
                            qm.put("quenum",qopt.size());
                            qm.put("qoption","");

                        }
                    }
                }
            }

            //设置答题卡需要默认值
            if(eps.get("scantronnote") == null){
                String scantronnote = "1.答题前，考生先将自己的姓名、班级、考场填写清楚，并认真核对条形码上的姓名和准考证号。\n" +
                        "2.选择题部分请按题号用2B铅笔填涂方框，修改时用橡皮擦干净，不留痕迹。\n" +
                        "3.非选择题部分请按题号用0.5毫米黑色墨水签字笔书写，否则作答无效。要求字体工整、笔迹清晰。作图时，必须使用2B铅笔，并描浓\n" +
                        "4.在草稿纸、试题卷上答题无效。";
                eps.put("scantronnote",scantronnote);
            }
        }

        Map rtnmap = new HashMap();
        rtnmap.put("paper",eps);
        rtnmap.put("qtypes",qtypes);
        return rtnmap;
    }

    /**
     * @Description 保存答题卡
     * @Param [paper]
     * @Return void
     * @Author wn
     * @Date 2022/7/25 17:38
     **/
    @Transactional(rollbackFor = Exception.class)
    public void savePaperScan(EPaper paper){
        List<EPaperQtypeQuestion> questions = paper.getQuestions();
        ePaperMapper.updatePaperScantron(paper);
        ePaperQtypeMapper.updateBatchQuestionForScan(questions);
        if(paper.getPstate() == 1){
            eSubjectMapper.updateEsubjectStateByEpid(1,paper.getEpid());
            //提交之后把答题卡base图片转成pdf
            chandleScantronFile(paper.getEpid());
        }
    }

    //答题卡中图片处理
    public void chandleScantronFile(Integer epid){
        //获取试卷中答题卡文件，
        Map map = ePaperMapper.getPaperScantronfile(epid);
        if(map.get("scantronfile")!=null){
            List<String> scantronfiles = JSON.parseArray(map.get("scantronfile").toString(),String.class);
            if(N_Utils.isNotEmpty(scantronfiles)){
                Integer examid = Integer.parseInt(map.get("examid").toString());
                Integer schoolid = Integer.parseInt(map.get("schoolid").toString());
                String cloudcode =  map.get("cloudcode").toString();
                String path = cloudcode + File.separator + schoolid + File.separator + "exam";
                Integer scantroncol = Integer.parseInt(map.get("scantroncol").toString());
                convertUtil.baseToPdf(epid,examid,scantronfiles,path,scantroncol);
            }
        }
    }
}
