package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.distributed.print.business.entity.ExamTask;
import com.qmth.distributed.print.business.entity.ExamTaskDetail;
import com.qmth.distributed.print.business.enums.MakeMethodEnum;
import com.qmth.distributed.print.business.service.*;
import com.qmth.teachcloud.common.annotation.OperationLogDetail;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.MessageEnum;
import com.qmth.teachcloud.common.enums.log.OperationTypeEnum;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 卷库查询 前端控制器
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Api(tags = "卷库查询Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_EXAM + "/task")
@Validated
public class ExamTaskQueryController {

    @Resource
    private ExamTaskService examTaskService;
    @Resource
    private ExamTaskDetailService examTaskDetailService;
    @Resource
    private PrintCommonService printCommonService;
    @Resource
    private BasicMessageService basicMessageService;
    @Resource
    private ActivitiService activitiService;

    /**
     * 卷库查询
     *
     * @param courseCode  课程代码
     * @param paperNumber 试卷编号
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param pageNumber  分页参数
     * @param pageSize    分页参数
     * @return Result
     */
    @ApiOperation(value = "卷库查询")
    @RequestMapping(value = "/paper_list", method = RequestMethod.POST)
    public Result taskPaperList(@RequestParam(value = "semesterId", required = false) Long semesterId,
                                @RequestParam(value = "examId", required = false) Long examId,
                                @RequestParam(value = "courseCode", required = false) String courseCode,
                                @RequestParam(value = "paperNumber", required = false) String paperNumber,
                                @RequestParam(value = "startTime", required = false) Long startTime,
                                @RequestParam(value = "endTime", required = false) Long endTime,
                                @RequestParam(value = "makeMethod", required = false) MakeMethodEnum makeMethod,
                                @RequestParam(value = "cardRuleId", required = false) String cardRuleId,
                                @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        if(examId == null){
            throw ExceptionResultEnum.EXAM_ID_IS_NULL.exception();
        }
        return ResultUtil.ok(examTaskService.listTaskPaper(semesterId, examId, courseCode, paperNumber, startTime, endTime, makeMethod, SystemConstant.convertIdToLong(cardRuleId), pageNumber, pageSize));
    }

    /**
     * 下载
     *
     * @param examTaskId 命题任务ID
     */
    @ApiOperation(value = "下载")
    @RequestMapping(value = "/paper_download", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.EXPORT, detail = "下载操作，命题任务ID：{{examTaskId}}")
    public void taskPaperDownload(HttpServletResponse response, @RequestParam Long examTaskId) throws Exception {
        examTaskService.paperDownload(response, examTaskId);
    }

    /**
     * 卷库查询-启用/禁用
     *
     * @param examTaskDetail 命题任务详情对象
     * @return Result
     */
    @ApiOperation(value = "卷库查询-启用/禁用")
    @RequestMapping(value = "/paper_enable", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.ENABLE, detail = "启用/禁用操作，命题任务ID：{{examTaskDetail.examTaskId}}")
    public Result taskPaperEnable(@RequestBody ExamTaskDetail examTaskDetail) throws IOException {
        boolean isSuccess = examTaskDetailService.enable(examTaskDetail);
        // 启用，触发考场生成pdf
        if (examTaskDetail.getEnable()) {
            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
            ExamTask examTask = examTaskService.getById(examTaskDetail.getId());
            // 校验课程关联考场，是否已经提交打印
            Boolean isCreate = printCommonService.checkExamDetailStatus(examTask.getSchoolId(), null, examTask.getExamId(), examTask.getCourseCode(), examTask.getPaperNumber());
            // 校验是否可以提交打印状态
            if (isCreate) {
                printCommonService.checkExamDataAndCreatePdfTask(examTask.getSchoolId(), examTask.getExamId(), examTask.getCourseCode(), examTask.getPaperNumber(), sysUser);
            }
        }
        return ResultUtil.ok(isSuccess);
    }

    /**
     * 卷库查询-卷库修改
     *
     * @param examTaskDetail 命题任务详情对象
     * @return Result
     */
    @ApiOperation(value = "卷库查询-卷库修改")
    @RequestMapping(value = "/paper_update", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE, detail = "卷库修改操作，命题任务ID：{{examTaskDetail.examTaskId}}")
    public Result taskPaperUpdate(@RequestBody ExamTaskDetail examTaskDetail) {
        Map<String, Object> map = examTaskDetailService.paperUpdate(examTaskDetail);
        Boolean isSuccess = (Boolean) map.get(SystemConstant.SUCCESS);
        if (isSuccess) {
            ExamTask examTask = examTaskService.getById(examTaskDetail.getExamTaskId());
            if (Objects.nonNull(examTask.getReview()) && examTask.getReview()) {
                // 发送短信
                basicMessageService.sendNoticeTaskAuditCreateOrReview(examTask, MessageEnum.NOTICE_OF_AUDIT_REVIEW);
            } else {
               /* SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
                // 校验课程关联考场，是否已经提交打印
                Boolean isCreate = printCommonService.checkExamDetailStatus(examTask.getSchoolId(), null, examTask.getCourseCode(), examTask.getPaperNumber());
                // 校验是否可以提交打印状态
                if (isCreate) {
                    printCommonService.checkData(examTask.getSchoolId(), examTask.getExamId(), examTask.getCourseCode(), examTask.getPaperNumber(), sysUser);
                }*/
            }
            Boolean sendFlowStartMq = (Boolean) map.get(SystemConstant.SEND_FLOW_START_MQ);
            Boolean sendFlowMq = (Boolean) map.get(SystemConstant.SEND_FLOW_MQ);
            if (Objects.nonNull(sendFlowStartMq) && sendFlowStartMq) {
                activitiService.sendFlowStartMsg(examTask.getFlowId());
            } else if (Objects.nonNull(sendFlowMq) && sendFlowMq) {
                activitiService.sendFlowTaskApproveMsg(map);
            }
        }
        return ResultUtil.ok(isSuccess);
    }

    @ApiOperation(value = "卷库查询-批量下载试卷PDF、题卡")
    @RequestMapping(value = "/paper_card_download_pdf", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.EXPORT, detail = "批量下载试卷PDF、题卡操作，考试ID：{{examId}}、课程代码：{{courseCode}}、试卷编号：{{paperNumber}}")
    public Result paperCardDownloadPdf(@RequestParam(value = "semesterId", required = false) Long semesterId,
                                       @RequestParam(value = "examId", required = false) Long examId,
                                       @RequestParam(value = "courseCode", required = false) String courseCode,
                                       @RequestParam(value = "paperNumber", required = false) String paperNumber,
                                       @RequestParam(value = "cardRuleId", required = false) Long cardRuleId,
                                       @RequestParam(value = "makeMethod", required = false) MakeMethodEnum makeMethod,
                                       @RequestParam(value = "startTime", required = false) Long startTime,
                                       @RequestParam(value = "endTime", required = false) Long endTime) {
        if(examId == null){
            throw ExceptionResultEnum.EXAM_ID_IS_NULL.exception();
        }
        TBTask tbTask = examTaskService.taskDownloadPdf(semesterId, examId, courseCode, paperNumber, cardRuleId, makeMethod, startTime, endTime);
        return Objects.nonNull(tbTask) ? ResultUtil.ok(new EditResult(tbTask.getId())) : ResultUtil.error("创建任务失败");
    }

    /**
     * 卷库查询-作废
     *
     * @param id 命题任务ID
     * @return Result
     */
    @ApiOperation(value = "卷库查询-作废")
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE)
    public Result cancel(@RequestParam Long id,
                         @RequestParam String cancelRemark) {
        boolean isSuccess = examTaskDetailService.cancel(id, cancelRemark);
        return ResultUtil.ok(isSuccess);
    }

    @ApiOperation(value = "卷库查询-重启流程（打回）")
    @RequestMapping(value = "/restart", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE, detail = "打回操作，命题任务ID：{{examTaskDetail.examTaskId}}")
    public Result taskFlowRestart(@RequestBody ExamTaskDetail examTaskDetail) {
        Map<String, Object> map = examTaskDetailService.taskRestart(examTaskDetail);
        Boolean isSuccess = (Boolean) map.get(SystemConstant.SUCCESS);
        if (isSuccess) {
            ExamTask examTask = examTaskService.getById(examTaskDetail.getExamTaskId());
            if (Objects.nonNull(examTask.getReview()) && examTask.getReview()) {
                // 发送短信
                basicMessageService.sendNoticeTaskAuditCreateOrReview(examTask, MessageEnum.NOTICE_OF_AUDIT_REVIEW);
            } else {
               /* SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
                // 校验课程关联考场，是否已经提交打印
                Boolean isCreate = printCommonService.checkExamDetailStatus(examTask.getSchoolId(), null, examTask.getCourseCode(), examTask.getPaperNumber());
                // 校验是否可以提交打印状态
                if (isCreate) {
                    printCommonService.checkData(examTask.getSchoolId(), examTask.getExamId(), examTask.getCourseCode(), examTask.getPaperNumber(), sysUser);
                }*/
            }
            Boolean sendFlowStartMq = (Boolean) map.get(SystemConstant.SEND_FLOW_START_MQ);
            Boolean sendFlowMq = (Boolean) map.get(SystemConstant.SEND_FLOW_MQ);
            if (Objects.nonNull(sendFlowStartMq) && sendFlowStartMq) {
                activitiService.sendFlowStartMsg(examTask.getFlowId());
            } else if (Objects.nonNull(sendFlowMq) && sendFlowMq) {
                activitiService.sendFlowTaskApproveMsg(map);
            }
        }
        return ResultUtil.ok(isSuccess);
    }
}

