package com.qmth.jkserver.core.kw.validate;

import com.qmth.jkserver.constant.SpringContextHolder;
import com.qmth.jkserver.constant.SystemConstant;
import com.qmth.jkserver.core.exception.JkServerException;
import com.qmth.jkserver.core.kw.IKwTempDataProcessor;
import com.qmth.jkserver.dto.KWObjectDto;
import com.qmth.jkserver.enums.ExamType;
import com.qmth.jkserver.model.*;
import com.qmth.jkserver.service.AttachmentService;
import com.qmth.jkserver.service.JkExamPlanService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 通用机考 考务数据校验
 *
 * @author tianjun
 */
public class NormalKwTempDataProcessor implements IKwTempDataProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(NormalKwTempDataProcessor.class);

    @Override
    public KWObjectDto execute(String examCode, ExamType examType, Long kcFileId, Long kwZipFileId, Long paperFileId,
                               Long additionalFileId, Long sceneScoreFileId) throws Exception {
        // 1\校验考试识别码是否正确
        JkExamPlanService examPlanService = SpringContextHolder.getBean(JkExamPlanService.class);
        AttachmentService attachmentService = SpringContextHolder.getBean(AttachmentService.class);
        Map<String, Set<String>> batchs = new HashMap<String, Set<String>>();
        List<ExamStageTemp> examStageTemps = examPlanService.findKwStageTemps(examCode, kwZipFileId);
        List<ExamStage> stages = new LinkedList<ExamStage>();
        for (ExamStageTemp examStageTemp : examStageTemps) {
            if (batchs.get(StringUtils.trimToEmpty(examStageTemp.getBatchId())) == null) {
                batchs.put(StringUtils.trimToEmpty(examStageTemp.getBatchId()), new HashSet<String>());
            }
            batchs.get(StringUtils.trimToEmpty(examStageTemp.getBatchId())).add(examStageTemp.getStageId());
            ExamStage examStage = new ExamStage(examStageTemp);
            stages.add(examStage);
        }
        List<ExamRoomTemp> examRoomTemps = examPlanService.findKwRoomsTemp(examCode, kcFileId);
        Map<String, Set<String>> roomMap = new HashMap<String, Set<String>>();
        List<ExamRoom> rooms = new LinkedList<ExamRoom>();
        for (ExamRoomTemp examRoomTemp : examRoomTemps) {
            if (roomMap.get(examRoomTemp.getPlaceCode()) == null) {
                roomMap.put(examRoomTemp.getPlaceCode(), new HashSet<String>());
            }
            roomMap.get(examRoomTemp.getPlaceCode()).add(examRoomTemp.getRoomCode());
            ExamRoom room = new ExamRoom(examRoomTemp);
            rooms.add(room);
        }
        List<ExamPaperTemp> examPaperTemps = examPlanService.findKwCoursePaperTemp(examCode, paperFileId);
        Map<String, Set<String>> paperMap = new HashMap<String, Set<String>>();
        for (ExamPaperTemp examPaperTemp : examPaperTemps) {
            if (paperMap.get(examPaperTemp.getCourseCode()) == null) {
                paperMap.put(examPaperTemp.getCourseCode(), new HashSet<String>());
            }
            paperMap.get(examPaperTemp.getCourseCode()).add(examPaperTemp.getPaperId());
        }
        //每一次从数据库中查询10000条数据进行校验
        int skip = 0;
        int limit = 10000;
        boolean isend = false;
        int i = 0;
        while (!isend) {
            List<ExamStudentTemp> examStudentTemps = examPlanService.findKwStudentTemp(examCode, kwZipFileId,
                    skip, limit);
            if (examStudentTemps.size() < limit) {
                LOGGER.info("-----------------END Query KwStudentTemp-----------------------");
                isend = true;
            }
            for (ExamStudentTemp examStudentTemp : examStudentTemps) {
//                String batchId = getProperty(examStudentTemp, "batch_id");
//                String stageId = getProperty(examStudentTemp, "stage_id");
//                String placeCode = getProperty(examStudentTemp, "place_code");
//                String roomCode = getProperty(examStudentTemp, "room_code");
//                String courseCode = getProperty(examStudentTemp, "course_code");
                String batchId = examStudentTemp.getBatchId();
                String stageId = examStudentTemp.getStageId();
                String placeCode = examStudentTemp.getPlaceCode();
                String roomCode = examStudentTemp.getRoomCode();
                String courseCode = examStudentTemp.getCourseCode();
                if (batchs.get(batchId) == null) {
                    throw new JkServerException("student.csv表中的批次ID:" + batchId + "在batch.csv表中不存在");
                }
                if (!batchs.get(batchId).contains(stageId)) {
                    throw new JkServerException("student.csv表中的场次ID:" + stageId + "在batch.csv表中不存在");
                }
                if (roomMap.get(placeCode) == null) {
                    throw new JkServerException("student.csv表中的考点代码:" + placeCode + "在kc.csv表中不存在");
                }
                if (!roomMap.get(placeCode).contains(roomCode)) {
                    throw new JkServerException("student.csv表中的考场代码:" + roomCode + "在kc.csv表中不存在");
                }
                if (paperMap.get(courseCode) == null) {
                    throw new JkServerException(
                            "student.csv表中的科目代码:" + courseCode + "在paper.csv表中没有找到对应的试卷");
                }
                i++;
            }
            LOGGER.info("-----------------Query KwStudentTemp sum count" + i + "-----------------------");
            skip = skip + limit;
        }
        // 考场文件
        Attachment kcattachment = attachmentService.copyKwWorkFile2Storage(kcFileId, examCode, examType);
        // 考生zip包文件复制
        Attachment kwZipAttachment = attachmentService.copyKwWorkFile2Storage(kwZipFileId, examCode, examType);
        // paper试卷文件复制
        Attachment paperAttachment = attachmentService.copyKwWorkFile2Storage(paperFileId, examCode, examType);
        //标准答案以及评分规则文件复制
        Attachment sceneScoreAttachment = null;
        if (Objects.nonNull(sceneScoreFileId)) {
            sceneScoreAttachment = attachmentService.copyKwWorkFile2Storage(sceneScoreFileId, examCode, examType);
        }
        KwFile kwFile = new KwFile();
        kwFile.setId(SystemConstant.getDbUuid());
        kwFile.setExamCode(examCode);
        if (Objects.nonNull(paperAttachment)) {
            kwFile.setPaperFileId(paperAttachment.getId());
        }
        kwFile.setPaperFileTempId(paperFileId);
        if (Objects.nonNull(kcattachment)) {
            kwFile.setRoomFileId(kcattachment.getId());
        }
        kwFile.setRoomFileTempId(kcFileId);
        if (Objects.nonNull(kwZipAttachment)) {
            kwFile.setStudentFileId(kwZipAttachment.getId());
        }
        kwFile.setStudentFileTempId(kwZipFileId);
        kwFile.setCreateTime(System.currentTimeMillis());
        if (Objects.nonNull(sceneScoreAttachment)) {
            kwFile.setSceneScoreFileId(sceneScoreAttachment.getId());
        }
        kwFile.setSceneScoreFileTempId(sceneScoreFileId);
        KWObjectDto kwData = new KWObjectDto();
        kwData.setKwFile(kwFile);
        kwData.setExamCode(examCode);
        kwData.setRooms(rooms);
        kwData.setStages(stages);
        kwData.setExamType(ExamType.NORMAL);
        return kwData;
    }

//    private String getProperty(DBObject dbObject, String key) {
//        if (dbObject.get(key) == null) {
//            return null;
//        } else {
//            return dbObject.get(key).toString();
//        }
//    }
}
