package cn.com.qmth.stmms.ms.admin.service;

import cn.com.qmth.stmms.ms.core.domain.MarkStage;
import cn.com.qmth.stmms.ms.core.domain.MarkSubject;
import cn.com.qmth.stmms.ms.core.domain.Paper;
import cn.com.qmth.stmms.ms.core.domain.Work;
import cn.com.qmth.stmms.ms.core.domain.enums.TrialEnum;
import cn.com.qmth.stmms.ms.core.repository.*;
import cn.com.qmth.stmms.ms.core.vo.Subject;
import cn.com.qmth.stmms.ms.marking.service.MarkingService;
import cn.com.qmth.stmms.ms.marking.service.StageControlService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 试评任务
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2019/11/4
 */
@Service
public class TrialService {

    @Autowired
    WorkRepo workRepo;

    @Autowired
    MarkSubjectRepo markSubjectRepo;

    @Autowired
    StudentRepo studentRepo;

    @Autowired
    MarkTaskRepo markTaskRepo;

    @Autowired
    PaperRepo paperRepo;

    @Autowired
    StageControlService stageControlService;

    @Autowired
    ExamQuestionRepo examQuestionRepo;

//    @Autowired
//    MarkLogRepo markLogRepo;

    @Autowired
    MarkerGroupRepo markerGroupRepo;

    @Autowired
    MarkingService markingService;

    /**
     * 检查任务状态
     *
     * @param workId
     * @param subject
     * @throws Exception
     */
    @Transactional
    public void checkMissionStatus(Long workId, Subject subject) throws Exception {
        Work work = workRepo.findOne(workId);
        if (Objects.isNull(work)) {
            throw new Exception("没有此工作区，请检查workId是否正确");
        }
        List<MarkSubject> markSubjectList = work.getSubjects().stream().filter(o -> o.getId().toUpperCase().contains(subject.toString().toUpperCase()))
                .collect(Collectors.toList());
        MarkSubject markSubject = markSubjectList.get(0);
        if (markSubject.getTest() == TrialEnum.INIT.getId() || markSubject.getTest() == TrialEnum.START_TRIAL.getId()) {
            finishTrial(workId, subject);
        }
        //修改科目test
        markSubject.setTest(TrialEnum.START_FORMAL.getId());
//        markSubject.setFormal(true);
        markSubjectRepo.save(markSubject);
    }

    /**
     * 开始试评任务
     *
     * @param workId
     * @param subject
     * @throws Exception
     */
    @Transactional
    public void startTrial(Long workId, Subject subject) throws Exception {
        Work work = workRepo.findOne(workId);
        if (Objects.isNull(work)) {
            throw new Exception("没有此工作区，请检查workId是否正确");
        }
        List<MarkSubject> markSubjectList = work.getSubjects().stream().filter(o -> o.getId().toUpperCase().contains(subject.toString().toUpperCase()))
                .collect(Collectors.toList());
        MarkSubject markSubject = markSubjectList.get(0);
        //分配任务
        Map map = new HashMap();
        map.put("taskCount", 0);
        stageControlService.goNext(markSubject, map);
        //修改科目test
        markSubject.setTest(TrialEnum.START_TRIAL.getId());
        markSubjectRepo.save(markSubject);
        //先删除上次试评试卷(取标准卷用)
//        paperRepo.deleteByWorkIdAndSubjectAndTest(workId, subject, TrialEnum.START_TRIAL.getId());
        //修改试卷test
        paperRepo.updateByWorkIdAndSubjectAndTest(workId, subject, TrialEnum.INIT.getId(), TrialEnum.START_TRIAL.getId());
    }

    /**
     * 删除试评任务，保留标准卷
     *
     * @param workId
     * @param subject
     * @throws Exception
     */
    @Transactional
    public void finishTrial(Long workId, Subject subject) throws Exception {
        Work work = workRepo.findOne(workId);
        if (Objects.isNull(work)) {
            throw new Exception("没有此工作区，请检查workId是否正确");
        }
        //1.更新科目为初始状态并设置test为false
        work.getSubjects().stream().filter(o -> o.getId().toUpperCase().contains(subject.toString().toUpperCase()))
                .collect(Collectors.toList())
                .forEach(o -> {
                    o.setTest(TrialEnum.DEFAULT.getId());
                    o.setStage(MarkStage.INIT);
                    o.setSampleCount(0);
                    o.setFormal(false);
                    markSubjectRepo.save(o);
                });
        //2.删除该科目下所有任务数据
        markTaskRepo.deleteByWorkIdAndSubjectAndTest(workId, subject, TrialEnum.START_TRIAL.getId());
        //3.删除学生数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(String.valueOf(TrialEnum.INIT.getId()), subject);
        studentRepo.deleteByWorkIdAndTest(workId, jsonObject.toJSONString());

        //4.删除卷子信息
        examQuestionRepo.deleteByWorkIdAndSubjectAndTest(workId, subject, TrialEnum.INIT.getId());
        //5.更新该科目下的试卷信息(正式卷子，并删除试评卷子)
        List<Paper> paperList = paperRepo.findByWorkIdAndSubjectAndTest(workId, subject, TrialEnum.START_TRIAL.getId());
//        List<Long> paperIds = new ArrayList<>();
        if (Objects.nonNull(paperList) && paperList.size() > 0) {
            List<Paper> paperAllList = paperRepo.findByWorkIdAndSubject(workId, subject);
            Map<String, Paper> paperAllMap = paperAllList.stream().filter(o -> (o.getTest() == 0 || o.getTest() == 3))
                    .collect(Collectors.toList())
                    .stream()
                    .collect(Collectors.toMap(Paper::getExamNumber, Function.identity(), (dto1, dto2) -> dto1));
            List<Paper> finalPaperList = new ArrayList<>();
            Map<String, String> levelMap = new HashMap<>();
            paperList.forEach(p -> {
                if (Objects.nonNull(paperAllMap.get(p.getExamNumber())) && p.isMarkByLeader() && p.isSample() && Objects.nonNull(p.getLevel())) {
                    if (Objects.equals(p.getAreaCode(), paperAllMap.get(p.getExamNumber()).getAreaCode())) {
                        finalPaperList.add(paperAllMap.get(p.getExamNumber()));
                        levelMap.put(p.getExamNumber(), p.getLevel());
                    }
                }
//                paperIds.add(p.getId());
            });

            if (finalPaperList.size() > 0) {
                finalPaperList.forEach(o -> {
                    markingService.levelMarkPaper(o, levelMap.get(o.getExamNumber()), true);
                    o.setTest(TrialEnum.DEFAULT.getId());
                    o.setActive(false);
                });
                paperRepo.save(finalPaperList);
            }
            //6.删除log日志
//            markLogRepo.deleteByPaperIdIn(paperIds);
        } else {
            paperList = paperRepo.findByWorkIdAndSubjectAndTest(workId, subject, TrialEnum.INIT.getId());
        }
        //5.删除试评卷子
        paperRepo.delete(paperList);
        //7.删除分组
        markerGroupRepo.deleteBySubjectAndWorkId(subject, workId);
    }
}
