package com.xhkjedu.sexam.service.paperstudent;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.sexam.mapper.exam.EBaseMapper;
import com.xhkjedu.sexam.mapper.exam.EClassMapper;
import com.xhkjedu.sexam.mapper.exam.EClassStudentMapper;
import com.xhkjedu.sexam.mapper.paper.EPaperMapper;
import com.xhkjedu.sexam.mapper.paperstudent.EScanbatchMapper;
import com.xhkjedu.sexam.mapper.paperstudent.EScanerrorMapper;
import com.xhkjedu.sexam.model.paperstudent.EScanbatch;
import com.xhkjedu.sexam.model.paperstudent.EScanerror;
import com.xhkjedu.sexam.utils.ExamUtil;
import com.xhkjedu.sexam.vo.paperscan.ScanSubjectVo;
import com.xhkjedu.sexam.vo.paperstudent.PaperStudentWebVo;
import com.xhkjedu.utils.N_Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: wn
 * @CreateTime: 2022-08-11  09:31
 */
@Service
public class EScanbatchService {
    @Resource
    private EScanbatchMapper eScanbatchMapper;
    @Resource
    private EPaperMapper ePaperMapper;
    @Resource
    private EBaseMapper eBaseMapper;
    @Resource
    private EClassMapper eClassMapper;
    @Resource
    private EScanerrorMapper eScanerrorMapper;
    @Resource
    private EClassStudentMapper eClassStudentMapper;

    /**
     * @description: 保持扫描试卷批次信息
     * @param: [eScanbatch]
     * @return: java.util.Map
     * @author: wn
     * @date: 2022/8/11/011 9:42
     **/
    public Map saveScanBatch(EScanbatch eScanbatch) {
        String batchname = eScanbatch.getDevice() + "-" + eScanbatch.getEpid() + "-";
        //获取数据库中该批次名的扫描批次数量
        Integer bnum = eScanbatchMapper.getBatchNameLikeNum(batchname);
        if (bnum == null || bnum == 0) {
            bnum = 1;
        } else {
            bnum++;
        }
        batchname = batchname + bnum;
        //对应考试id
        Integer examid = ePaperMapper.getExamIdByEpId(eScanbatch.getEpid());
        eScanbatch.setBatchname(batchname);
        eScanbatch.setExamid(examid);
        eScanbatch.setScannum(0);
        eScanbatch.setErrornum(0);
        eScanbatch.setQknum(0);
        eScanbatch.setWgnum(0);
        eScanbatch.setCreatetime(N_Utils.getSecondTimestamp());
        eScanbatchMapper.insertUseGeneratedKeys(eScanbatch);
        Integer batchid = eScanbatch.getId();
        Map rtnmap = new HashMap<>();
        rtnmap.put("batchid",batchid);
        rtnmap.put("batchname",batchname);
        return rtnmap;
    }

    //扫描答题卡列表
    public Map listScan2(Integer examid) {
        Map map = eBaseMapper.findById(examid);
        List<Map> subjects = eScanbatchMapper.listScanSubject(examid);//扫描答题卡列表
        map.put("subjects", subjects);
        return map;
    }

    //扫描答题卡列表
    public Map listScan(Integer examid){
        //获取考试信息
        Map map = eBaseMapper.findById(examid);
        List<ScanSubjectVo> subjectList = eScanbatchMapper.listScanExamSubject(examid);

        //扫描答题卡为处理数量
        List<ScanSubjectVo> wclList = eScanbatchMapper.listScanExamSubjectWcl(examid);

        for(ScanSubjectVo subjectVo : subjectList){
            ScanSubjectVo wclScan = wclList.stream().filter(s -> s.getEpid().equals(subjectVo.getEpid())).findFirst().orElse(null);
            if(wclScan!=null){
                subjectVo.setWclnum(wclScan.getWclnum());
            }
        }
        map.put("subjects", subjectList);
        return map;
    }

    /**
     * @description: 扫码答卷详情
     * @param: [epid]
     * @return: java.util.Map
     * @author: wn
     * @date:
     **/
    public Map scanPaperDetail(Integer epid) {
        Map paper = ePaperMapper.getExamPaperSubjectForScan(epid);
        Integer ysrnum = Integer.parseInt(paper.get("ysrnum").toString());
        Integer scantronnum = Integer.parseInt(paper.get("scantronnum").toString());
        int ysznum = ysrnum * scantronnum;//应扫码张数
        paper.put("ysznum", ysznum);
        paper.remove("scantronnum");

        if (N_Utils.isNotEmpty(paper.get("alljson"))) {
            String alljson = paper.get("alljson").toString();
            Map pamap = JSON.parseObject(alljson, Map.class);
            List<Map> ranglist = (List<Map>) pamap.get("ranglist");
            for (Map m : ranglist) {
                String ptname = m.get("qtname").toString();
                Integer num = Integer.parseInt(m.get("num").toString());
                if ("客观题".equals(ptname)) {
                    paper.put("kgt", num);
                } else {
                    paper.put("zgt", num);
                }
            }
        } else {
            paper.put("kgt", 0);
            paper.put("zgt", 0);
        }
        paper.remove("alljson");
        List<Map> batchlist = eScanbatchMapper.listScanBatchPapers(epid);

        Map rtnmap = new HashMap();
        rtnmap.put("paper", paper);
        if(N_Utils.isListNotEmpty(batchlist)){
            Map batchobj = batchlist.get(0);
            if(N_Utils.isEmpty(batchobj.get("batchid"))){
                rtnmap.put("scans", new ArrayList<>());
            }else{
                rtnmap.put("scans", batchlist);
            }
        }else{
            rtnmap.put("scans", batchlist);
        }

        return rtnmap;
    }

    //扫描答题卡详情
    public Map getScanDetail(Integer epid, Integer examid) {
        Map map = eScanbatchMapper.getScanDetail(epid);
        List<Map> classes = eClassMapper.listByExamId(examid);
        int jhnum = classes.stream().mapToInt(m -> (int) m.get("classnum")).sum();
        Integer ysnum = N_Utils.str2Int(map.get("ysnum").toString());//已扫人数
        Integer wsnum = ExamUtil.subtractInt(jhnum, ysnum);
        map.put("jhnum", jhnum);//计划人数
        map.put("wsnum", wsnum);//未扫人数
        map.put("smrate", N_Utils.getIntegerDivideAndMulitiply(ysnum, jhnum));//扫描进度
        map.put("classes", classes);//班级列表
        return map;
    }

    //扫描答题卡详情-学生列表
    public List<Map> listScanStu(Integer epid, Integer sstate, String username, Integer classid) {
        return eScanbatchMapper.listScanStu(epid, sstate, username, classid);
    }

    //获取扫描答卷识别异常详情
    public Map getScanErrorDetail(Integer epid) {
        Map map = eScanbatchMapper.listByEpId(epid);
        List<Map> errortypelist = eScanerrorMapper.listBatchErrorNum(epid);
        map.put("errors",errortypelist);

        return map;
    }

    /**
     * @Description 获取扫描详情中指定类型错误信息集合
     * @Param [epid, errortype]
     * @Return java.util.Map
     * @Author wn
     * @Date 2022/8/26 14:42
     **/
    public Map getScanErrorDetailByErrorType(Integer epid,Integer errortype){
        List<EScanerror> list = eScanerrorMapper.listErrorsByErrortype(epid,errortype);
        if(errortype == 3 || errortype == 4){
            //获取参加考试的学生名单
            List<Map> stulist = eClassStudentMapper.listStudentsByEpid(epid);
            for(EScanerror e : list){

                if(N_Utils.isNotEmpty(e.getErrorjson())){
                    String errorsjon = e.getErrorjson();
                    PaperStudentWebVo errvo = JSON.parseObject(errorsjon,PaperStudentWebVo.class);
                    String examno = errvo.getExamno();
                    Map stumap = stulist.stream().filter(s -> examno.equals(s.get("examno").toString())).findFirst().orElse(null);
                    if(stumap!=null){
                        String studentname = stumap.get("studentname").toString();
                        errvo.setStudentname(studentname);
                        e.setErrorjson(JSON.toJSONString(errvo));
                    }

                }
            }
        }
        Map map = new HashMap();
        List<EScanerror> dcllist = list.stream().filter(s -> s.getErrorstate().equals(0)).collect(Collectors.toList());
        map.put("errortype",errortype);
        map.put("dcllist", dcllist);
        List<EScanerror> ycllist = new ArrayList<>();
        if(errortype == 1){
            ycllist = list.stream().filter(s -> s.getErrorstate().equals(10)).collect(Collectors.toList());
        }else{
            ycllist = list.stream().filter(s -> s.getErrorstate().equals(1)).collect(Collectors.toList());
        }
        map.put("ycllist", ycllist);
        return map;
    }

    //更新状态
    public void updateErrorState(Integer serrorid, Integer errorstate) {
        eScanerrorMapper.updateErrorState(serrorid, errorstate);
    }

    //根据批次名称获取扫描出错数量
    public Integer getErrNumByBatchName(String batchname) {
        return eScanerrorMapper.getErrNumByBatchName(batchname);
    }
}
