package com.qmth.distributed.print.api.mark;

import com.qmth.boot.core.exception.ParameterException;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.mark.MarkPaperStatus;
import com.qmth.teachcloud.common.util.DateDisposeUtils;
import com.qmth.teachcloud.mark.entity.MarkPaper;
import com.qmth.teachcloud.mark.entity.ScanBatch;
import com.qmth.teachcloud.mark.enums.BatchStatus;
import com.qmth.teachcloud.mark.service.MarkPaperService;

import javax.annotation.Resource;
import java.util.Date;

public class BaseController {

    @Resource
    private MarkPaperService markPaperService;

    /**
     * @param examId
     * @param paperNumber
     */
    public void validMarkPaperForMark(Long examId, String paperNumber) {
        MarkPaper markPaper = markPaperService.getByExamIdAndPaperNumber(examId, paperNumber);
        if (markPaper == null) {
            throw ExceptionResultEnum.DATA_ERROR.exception();
        }
        validMarkPaperStatus(markPaper);
        validMarkPaperMarkTime(markPaper);
    }

    public void validMarkPaperForScan(Long examId, String coursePaperId) {
        MarkPaper markPaper = markPaperService.getByExamIdAndCoursePaperId(examId, coursePaperId);
        if (markPaper == null) {
            throw ExceptionResultEnum.DATA_ERROR.exception();
        }
        validMarkPaperStatus(markPaper);
    }

    private void validMarkPaperStatus(MarkPaper markPaper) {
        if (MarkPaperStatus.FINISH.equals(markPaper.getStatus())) {
            throw ExceptionResultEnum.MARK_PAPER_FINISH.exception();
        }
    }

    private void validMarkPaperMarkTime(MarkPaper markPaper) {
        Long markStartTime = markPaper.getMarkStartTime();
        Long markEndTime = markPaper.getMarkEndTime();
        if (markPaper != null && markStartTime != null && markEndTime != null) {
            long time = System.currentTimeMillis();
            if (time < markStartTime || time > markEndTime) {
                String markStartTimeStr = DateDisposeUtils.parseDateToStr(DateDisposeUtils.YYYY_MM_DD_HH_MM_SS, new Date(markStartTime));
                String markEndTimeStr = DateDisposeUtils.parseDateToStr(DateDisposeUtils.YYYY_MM_DD_HH_MM_SS, new Date(markEndTime));
                throw ExceptionResultEnum.MARK_PAPER_OUT_MARK_TIME.exception(ExceptionResultEnum.MARK_PAPER_OUT_MARK_TIME.getMessage() + "[" + markStartTimeStr + "-" + markEndTimeStr + "]");
            }
        }
    }

    public void checkBatchStatus(ScanBatch b) {
        if (b == null) {
            throw new ParameterException("批次未找到");
        }
        if (BatchStatus.FINISH.equals(b.getStatus())) {
            throw new ParameterException("批次已经完成");
        }
    }
}
