package cn.com.qmth.stmms.ms.marking.assembler;

import cn.com.qmth.stmms.ms.commons.config.ImageConfig;
import cn.com.qmth.stmms.ms.commons.config.SystemConfig;
import cn.com.qmth.stmms.ms.commons.constant.SystemConstant;
import cn.com.qmth.stmms.ms.commons.utils.MD5Util;
import cn.com.qmth.stmms.ms.core.cache.ParamCache;
import cn.com.qmth.stmms.ms.core.domain.*;
import cn.com.qmth.stmms.ms.core.domain.enums.TrialEnum;
import cn.com.qmth.stmms.ms.core.domain.task.MarkTask;
import cn.com.qmth.stmms.ms.core.repository.*;
import cn.com.qmth.stmms.ms.core.vo.Subject;
import cn.com.qmth.stmms.ms.marking.api.MakrerApi;
import cn.com.qmth.stmms.ms.marking.dto.PaperDTO;
import com.sun.glass.ui.Window;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by zhengmin on 2016/10/10.
 */
@Component
public class PaperAssembler {

    @Autowired
    private MarkTaskRepo markTaskRepo;

    @Autowired
    private MarkTaskAssembler markTaskAssembler;

    @Autowired
    private SystemConfig systemConfig;

    @Autowired
    ImageConfig imageConfig;

    @Autowired
    StudentRepo studentRepo;

    @Autowired
    private MarkSubjectRepo markSubjectRepo;

    @Autowired
    private LevelRepo levelRepo;

    @Autowired
    private MarkLogRepo markLogRepo;

    public PaperDTO toDTO(Paper paper) {
        String imgSrc = null;
        String thumbSrc = null;
        String fileName = paper.getExamNumber();
        Student student = studentRepo.findByWorkIdAndExamNumberAndTest(paper.getWorkId(), paper.getExamNumber(), String.valueOf(TrialEnum.DEFAULT.getId()));
        //0：随机码 1：考号
        if(ParamCache.paramMap.get(paper.getWorkId()).getNameRule() == 1){
//            fileName = DigestUtils.md5Hex(paper.getSubject().name() + fileName);
            fileName = MD5Util.getImageRuleMd5(paper.getWorkId(),paper.getSubject().ordinal(), student.getAreaCode(), student.getExamNumber(), student.getId());
        }
        if (ParamCache.paramMap.get(paper.getWorkId()).getImageEncrypt() == 1) {
            imgSrc = systemConfig.getImageUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.IMAGE);
            thumbSrc = systemConfig.getThumbUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.THUMB);
            /*if(paper.isManual()) {
                imgSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.IMAGE);
            }*/
        } else {
            imgSrc = systemConfig.getImageUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
            thumbSrc = systemConfig.getThumbUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
            /*if(paper.isManual()) {
                imgSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
                thumbSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
            }*/
        }
        //查询阶段
        MarkSubject markSubject = markSubjectRepo.findOne(paper.getWorkId() + "-" + paper.getSubject());
        PaperDTO paperDTO = null;
        if (paper != null) {
            paperDTO = new PaperDTO();
            paperDTO.setId(paper.getId());
            paperDTO.setSubjectName(paper.getSubject().getName());
            paperDTO.setExamNumber(paper.getExamNumber());
            paperDTO.setSn(paper.getSecretNumber());
            paperDTO.setLevel(paper.getLevel());
            paperDTO.setManual(paper.isManual());
            paperDTO.setScore(Objects.isNull(paper.getScore())? null: paper.getScore().intValue());
            paperDTO.setArbitrated(paper.isArbitrated());
            paperDTO.setRejected(paper.isRejected());
            paperDTO.setSample(paper.isSample());
            paperDTO.setMarkByLeader(paper.isMarkByLeader());
            paperDTO.setTagged(paper.isTagged());
            paperDTO.setMarkedLogic(paper.isMarkedLogic());
            paperDTO.setRedoLevel(paper.getRedoLevel());
            paperDTO.setUpdatedOn(paper.getUpdatedOn());
//            String imgSrc = systemConfig.getImageUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), paper.getExamNumber());
//            String thumbSrc = systemConfig.getThumbUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), paper.getExamNumber());
            paperDTO.setImgSrc(imgSrc);
            paperDTO.setThumbSrc(thumbSrc);
            paperDTO.setAreaCode(paper.getAreaCode());
            paperDTO.setMissing(paper.getIsMissing());
            if (paper.getInspectScore() != null) {
                paperDTO.setInspectScore(paper.getInspectScore().intValue());
            }
            if (paper.getInspectLevel() != null) {
                paperDTO.setInspectLevel(paper.getInspectLevel());
            }
            paperDTO.setStage(markSubject.getStage());
            paperDTO.setTest(markSubject.getTest());
            paperDTO.setPaperTest(paper.getTest());
            paperDTO.setShift(paper.isShift());
            paperDTO.setShiftScore(paper.isShiftScore());
            paperDTO.setIsRejectedByLeader(paper.isRejectedByLeader() == null ? false : paper.isRejectedByLeader());
            //打回总次数
            int rejectedCount = markLogRepo.countByWorkIdAndPaperIdAndOperType(paper.getWorkId(), paper.getId(), MarkLogOperType.SYSTEM_CALLBACK_LEVEl.getId(), MarkLogOperType.CALLBACK_LEVEl.getId());
            paperDTO.setRejectedCount(rejectedCount);
            //计算levelValue和（试评阶段不用）
            if(markSubject.getTest() == 0 && Objects.nonNull(paper.getLevel())) {
                List<Level> levels = levelRepo.findByWorkId(paper.getWorkId());
                if(!levels.isEmpty() && levels.size() > 0){
                    Map<String, Integer> map = levels.stream().collect(Collectors.toMap(Level::getCode, Level::getLevelValue));
                    List<MarkTask> markTaskList = markTaskRepo.findByPaperIdAndStage(paper.getId(), MarkStage.LEVEL);
                    int sum = markTaskList.stream().mapToInt(m-> map.get(m.getResult()) == null ? 0 : map.get(m.getResult())).sum();
                    paperDTO.setSortSum(sum);
                }
            }
        }
        return paperDTO;
    }

    public PaperDTO toDTOForPaperManager(Paper paper, Boolean isManual) {
        String imgSrc = null;
        String thumbSrc = null;
        String fileName = paper.getExamNumber();
        Student student = studentRepo.findByWorkIdAndExamNumberAndTest(paper.getWorkId(), paper.getExamNumber(), String.valueOf(TrialEnum.DEFAULT.getId()));
        //0：随机码 1：考号
        if(ParamCache.paramMap.get(paper.getWorkId()).getNameRule() == 1){
            fileName = MD5Util.getImageRuleMd5(paper.getWorkId(),paper.getSubject().ordinal(), student.getAreaCode(), student.getExamNumber(), student.getId());
        }
        if (ParamCache.paramMap.get(paper.getWorkId()).getImageEncrypt() == 1) {
            imgSrc = systemConfig.getImageUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.IMAGE);
            thumbSrc = systemConfig.getThumbUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.THUMB);
            if(paper.isManual() && Objects.nonNull(isManual) && isManual) {
                imgSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.IMAGE);
                thumbSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.THUMB);
            }
        } else {
            imgSrc = systemConfig.getImageUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
            thumbSrc = systemConfig.getThumbUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
            if(paper.isManual() && Objects.nonNull(isManual) && isManual) {
                imgSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
                thumbSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
            }
        }
        //查询阶段
        MarkSubject markSubject = markSubjectRepo.findOne(paper.getWorkId() + "-" + paper.getSubject());
        PaperDTO paperDTO = null;
        if (paper != null) {
            paperDTO = new PaperDTO();
            paperDTO.setId(paper.getId());
            paperDTO.setSubjectName(paper.getSubject().getName());
            paperDTO.setExamNumber(paper.getExamNumber());
            paperDTO.setSn(paper.getSecretNumber());
            paperDTO.setLevel(paper.getLevel());
            paperDTO.setManual(paper.isManual());
            paperDTO.setScore(Objects.isNull(paper.getScore())? null: paper.getScore().intValue());
            paperDTO.setArbitrated(paper.isArbitrated());
            paperDTO.setRejected(paper.isRejected());
            paperDTO.setSample(paper.isSample());
            paperDTO.setMarkByLeader(paper.isMarkByLeader());
            paperDTO.setTagged(paper.isTagged());
            paperDTO.setMarkedLogic(paper.isMarkedLogic());
            paperDTO.setRedoLevel(paper.getRedoLevel());
            paperDTO.setUpdatedOn(paper.getUpdatedOn());
            paperDTO.setImgSrc(imgSrc);
            paperDTO.setThumbSrc(thumbSrc);
            paperDTO.setAreaCode(paper.getAreaCode());
            paperDTO.setMissing(paper.getIsMissing());
            if (paper.getInspectScore() != null) {
                paperDTO.setInspectScore(paper.getInspectScore().intValue());
            }
            if (paper.getInspectLevel() != null) {
                paperDTO.setInspectLevel(paper.getInspectLevel());
            }
            paperDTO.setStage(markSubject.getStage());
            paperDTO.setTest(markSubject.getTest());
            paperDTO.setPaperTest(paper.getTest());
            paperDTO.setShift(paper.isShift());
            paperDTO.setShiftScore(paper.isShiftScore());
        }
        return paperDTO;
    }

    public PaperDTO toDTOForSheet(Paper paper) {
        String imgSrc = null;
        String thumbSrc = null;
        String sheetSrc = null;
        String fileName = paper.getExamNumber();
        Student student = studentRepo.findByWorkIdAndExamNumberAndTest(paper.getWorkId(), paper.getExamNumber(), String.valueOf(TrialEnum.DEFAULT.getId()));
        //0：随机码 1：考号
        if(ParamCache.paramMap.get(paper.getWorkId()).getNameRule() == 1){
//            fileName = DigestUtils.md5Hex(paper.getSubject().name() + fileName);
            fileName = MD5Util.getImageRuleMd5(paper.getWorkId(), paper.getSubject().ordinal(), student.getAreaCode(), student.getExamNumber(), student.getId());
        }
        if (ParamCache.paramMap.get(paper.getWorkId()).getImageEncrypt() == 1) {
            imgSrc = systemConfig.getImageUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.IMAGE);
            thumbSrc = systemConfig.getThumbUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.THUMB);
            sheetSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().ordinal(), student.getId(), SystemConstant.SHEET);
        } else {
            imgSrc = systemConfig.getImageUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
            thumbSrc = systemConfig.getThumbUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
            sheetSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), fileName);
        }
        //查询阶段
        MarkSubject markSubject = markSubjectRepo.findOne(paper.getWorkId() + "-" + paper.getSubject());
        PaperDTO paperDTO = null;
        if (paper != null) {
            paperDTO = new PaperDTO();
            paperDTO.setId(paper.getId());
            paperDTO.setExamNumber(paper.getExamNumber());
            paperDTO.setSn(paper.getSecretNumber());
            paperDTO.setLevel(paper.getLevel());
            paperDTO.setManual(paper.isManual());
            paperDTO.setScore(Objects.isNull(paper.getScore())? null: paper.getScore().intValue());
            paperDTO.setArbitrated(paper.isArbitrated());
            paperDTO.setRejected(paper.isRejected());
            paperDTO.setSample(paper.isSample());
            paperDTO.setMarkByLeader(paper.isMarkByLeader());
            paperDTO.setTagged(paper.isTagged());
            paperDTO.setMarkedLogic(paper.isMarkedLogic());
            paperDTO.setRedoLevel(paper.getRedoLevel());
            paperDTO.setUpdatedOn(paper.getUpdatedOn());
//            String imgSrc = systemConfig.getImageUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), paper.getExamNumber());
//            String thumbSrc = systemConfig.getThumbUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), paper.getExamNumber());
//            String sheetSrc = systemConfig.getSheetUrl(paper.getWorkId(), paper.getSubject().toString(), paper.getAreaCode(), paper.getExamNumber());
            paperDTO.setImgSrc(imgSrc);
            paperDTO.setThumbSrc(thumbSrc);
            paperDTO.setSheetSrc(sheetSrc);
            paperDTO.setAreaCode(paper.getAreaCode());
            if (paper.getInspectScore() != null) {
                paperDTO.setInspectScore(paper.getInspectScore().intValue());
            }
            if (paper.getInspectLevel() != null) {
                paperDTO.setInspectLevel(paper.getInspectLevel());
            }
            paperDTO.setMissing(paper.getIsMissing());
            paperDTO.setStage(markSubject.getStage());
            paperDTO.setTest(paper.getTest());
            paperDTO.setPaperTest(paper.getTest());
        }
        return paperDTO;
    }
}
