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

import cn.com.qmth.stmms.ms.core.cache.ParamCache;
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.ParamSetting;
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.MarkSubjectRepo;
import cn.com.qmth.stmms.ms.core.repository.MarkTaskRepo;
import cn.com.qmth.stmms.ms.core.repository.PaperRepo;
import cn.com.qmth.stmms.ms.core.repository.ParamSettingRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 全局参数
 */
@RestController
@RequestMapping("/api/param")
public class ParamApi {

    @Autowired
    private ParamSettingRepo paramSettingRepo;

    @Autowired
    private PaperRepo paperRepo;

    @Autowired
    private MarkSubjectRepo markSubjectRepo;

    @Autowired
    private MarkTaskRepo markTaskRepo;

    /**
     * 查询
     *
     * @param workId
     * @return
     */
    @RequestMapping(value = "/getParam", method = RequestMethod.GET)
    public ParamSetting getOne(@RequestParam Long workId) {
        return paramSettingRepo.findByWorkId(workId);
    }

    /**
     * 更新采集参数
     *
     * @param workId
     * @param packageScan
     * @param imageEncrypt
     * @param nameRule
     * @param paperStage
     * @return
     */
    @RequestMapping(value = "/collect", method = RequestMethod.POST)
    public ResponseEntity updateCollectParam(@RequestParam Long workId,
                                             @RequestParam Integer packageScan,
                                             @RequestParam Integer imageEncrypt,
                                             @RequestParam Integer nameRule,
                                             @RequestParam Integer paperStage) {


        //保存采集参数
        ParamSetting paramSetting = paramSettingRepo.findByWorkId(workId);
        if (paramSetting == null) {
            paramSetting = ParamSetting.init();
        }

        List<MarkTask> markTasks = markTaskRepo.findByWorkId(workId);
        if (!markTasks.isEmpty() && markTasks.size() > 0
                && !Objects.equals(packageScan, paramSetting.getPackageScan())) {
            throw new RuntimeException("该评卷工作当前不是采集阶段，不能修改是否整包扫描参数");
        }

        //有采集数据，不能修改采集参数
        List<Paper> papers = paperRepo.findByWorkId(workId);
        if (papers != null && papers.size() > 0) {
            if (!Objects.equals(imageEncrypt, paramSetting.getImageEncrypt())
                    || !Objects.equals(nameRule, paramSetting.getNameRule())
                    || !Objects.equals(paperStage, paramSetting.getPaperStage())) {
                throw new RuntimeException("该评卷工作已有采集数据，不能修改图片是否加密、图片命名规则、试卷档位参数");
            }
        }

//        if(paramSetting.getPaperStage() == 1 && !Objects.equals(paperStage, paramSetting.getPaperStage())){
//            throw new RuntimeException("试卷档位已经设置，不能修改");
//        }

        paramSetting.setPackageScan(packageScan);
        paramSetting.setImageEncrypt(imageEncrypt);
        paramSetting.setNameRule(nameRule);
        paramSetting.setPaperStage(paperStage);
        paramSettingRepo.saveAndFlush(paramSetting);
        ParamCache.resetParam(paramSetting);

        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 更新分档规则参数
     *
     * @param workId
     * @param deviation
     * @param autoCallback
     * @param majority
     * @param cumulativeError
     * @param levelShowAllPaper
     * @return
     */
    @RequestMapping(value = "/level", method = RequestMethod.POST)
    public ResponseEntity updateLevelParam(@RequestParam Long workId,
                                           @RequestParam Integer deviation,
                                           @RequestParam Integer autoCallback,
                                           @RequestParam Integer majority,
                                           @RequestParam Integer cumulativeError,
                                           @RequestParam Integer levelShowAllPaper) {
        List<MarkSubject> markSubjects = markSubjectRepo.findByWorkIdAndTestNotIn(workId, Arrays.asList(TrialEnum.DEFAULT.ordinal(), TrialEnum.START_FORMAL.ordinal()));
        List<MarkTask> markTasks = markTaskRepo.findByWorkId(workId);
        boolean flag = false;
        if ((markSubjects == null || markSubjects.size() == 0) && (markTasks != null && markTasks.size() > 0)) {
            flag = true;
        }

        //保存分档参数
        ParamSetting paramSetting = paramSettingRepo.findByWorkId(workId);
        if (flag && (!Objects.equals(deviation, paramSetting.getDeviation())
                || !Objects.equals(autoCallback, paramSetting.getAutoCallback())
                || !Objects.equals(majority, paramSetting.getMajority())
                || !Objects.equals(cumulativeError, paramSetting.getCumulativeError()))) {
            throw new RuntimeException("该评卷工作已有评卷数据，不能修改仲裁档位差、系统自动打回、是否过半定档参数");
        }
        if (paramSetting == null) {
            paramSetting = ParamSetting.init();
        }
        paramSetting.setDeviation(deviation);
        paramSetting.setAutoCallback(autoCallback);
        paramSetting.setMajority(majority);
        paramSetting.setCumulativeError(cumulativeError);
        paramSetting.setLevelShowAllPaper(levelShowAllPaper);
        paramSettingRepo.saveAndFlush(paramSetting);
        ParamCache.resetParam(paramSetting);

        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 打分改档参数
     *
     * @return
     */
    @RequestMapping(value = "/score", method = RequestMethod.POST)
    public ResponseEntity updateScoreParam(@RequestBody Map map) {
        Long workId = Long.valueOf(map.get("workId").toString());
        Integer roundUp = (Integer) map.get("roundUp");
        Integer changeStage = (Integer) map.get("changeStage");
        Integer scoreShowAllPaper = (Integer) map.get("scoreShowAllPaper");
        List<MarkSubject> markSubjects = markSubjectRepo.findByWorkIdAndTestNotIn(workId, Arrays.asList(TrialEnum.DEFAULT.ordinal(), TrialEnum.START_FORMAL.ordinal()));
        List<MarkTask> markTasks = markTaskRepo.findByWorkId(workId);
        boolean flag = false;
        if ((markSubjects == null || markSubjects.size() == 0) && (markTasks != null && markTasks.size() > 0)) {
            flag = true;
        }

        //保存打分参数
        ParamSetting paramSetting = paramSettingRepo.findByWorkId(workId);
        if (flag && (!Objects.equals(roundUp, paramSetting.getRoundUp()))) {
            throw new RuntimeException("该评卷工作已有评卷数据，不能修改分数处理方式参数");
        }
        if (paramSetting == null) {
            paramSetting = ParamSetting.init();
        }
        paramSetting.setRoundUp(roundUp);
        paramSetting.setChangeStage(changeStage);
        paramSetting.setScoreShowAllPaper(scoreShowAllPaper);
        paramSettingRepo.saveAndFlush(paramSetting);
        ParamCache.resetParam(paramSetting);

        return new ResponseEntity(HttpStatus.OK);
    }

}
