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


import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.core.exception.ParameterException;
import com.qmth.distributed.print.business.service.BasicExamService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicExam;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import com.qmth.teachcloud.mark.bean.answerbatch.AnswerDomain;
import com.qmth.teachcloud.mark.bean.answerbatch.BatchCreateDomain;
import com.qmth.teachcloud.mark.entity.ScanBatch;
import com.qmth.teachcloud.mark.service.ScanBatchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 批次 前端控制器
 * </p>
 *
 * @author xf
 * @since 2023-09-22
 */
@Api(tags = "扫描-批次")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_SCAN + "/answer/batch")
public class ScanAnswerBatchController extends BaseController {

    @Autowired
    private ScanBatchService scanBatchService;

    @Autowired
    private BasicExamService basicExamService;

    @ApiOperation(value = "答题卡扫描批次创建")
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public Result batchCreate(@Validated @RequestBody BatchCreateDomain domain) {
        validMarkPaperForScan(domain.getExamId(), domain.getCoursePaperId());
        BasicExam exam = basicExamService.getById(domain.getExamId());
        if (exam == null) {
            throw new ParameterException("未找到考试信息");
        }
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(scanBatchService.batchCreate(domain, sysUser));
    }

    @ApiOperation(value = "答题卡扫描批次完成")
    @RequestMapping(value = "finish", method = RequestMethod.POST)
    public Result batchFinish(@RequestParam Long id) {
        ScanBatch scanBatch = scanBatchService.getById(id);
        checkBatchStatus(scanBatch);
        validMarkPaperForScan(scanBatch.getExamId(), scanBatch.getCoursePaperId());
        return ResultUtil.ok(scanBatchService.batchFinish(scanBatch));
    }

    @ApiOperation(value = "答题卡扫描结果保存")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Result batchSave(@Validated @RequestBody AnswerDomain domain) {
        ScanBatch scanBatch = scanBatchService.getById(domain.getBatchId());
        checkBatchStatus(scanBatch);
        validMarkPaperForScan(scanBatch.getExamId(), scanBatch.getCoursePaperId());
        SysUser user = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(scanBatchService.batchSave(domain,scanBatch, user));
    }
}
