package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.distributed.print.business.bean.dto.ExamTaskDetailCardDto;
import com.qmth.distributed.print.business.bean.dto.ExamTaskDto;
import com.qmth.distributed.print.business.bean.dto.ExamTaskImportDto;
import com.qmth.distributed.print.business.bean.dto.ExamTaskPrintDto;
import com.qmth.distributed.print.business.bean.params.ApproveFormParams;
import com.qmth.distributed.print.business.bean.params.ExamTaskApplyParam;
import com.qmth.distributed.print.business.bean.params.ExamTaskPrintParams;
import com.qmth.distributed.print.business.bean.params.ExamTaskReApplyParam;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.distributed.print.business.entity.*;
import com.qmth.distributed.print.business.enums.ExamStatusEnum;
import com.qmth.distributed.print.business.enums.MakeMethodEnum;
import com.qmth.distributed.print.business.enums.MessageEnum;
import com.qmth.distributed.print.business.enums.ReviewStatusEnum;
import com.qmth.distributed.print.business.service.*;
import com.qmth.distributed.print.business.templete.execute.AsyncTaskReviewSampleExportService;
import com.qmth.teachcloud.common.annotation.OperationLogDetail;
import com.qmth.teachcloud.common.bean.params.ArraysParams;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicAttachment;
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.FlowApprovePassEnum;
import com.qmth.teachcloud.common.enums.TaskTypeEnum;
import com.qmth.teachcloud.common.enums.UploadFileEnum;
import com.qmth.teachcloud.common.enums.log.LevelEnum;
import com.qmth.teachcloud.common.service.BasicAttachmentService;
import com.qmth.teachcloud.common.service.BasicStudentService;
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.*;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 命题任务 前端控制器
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Api(tags = "命题任务Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.exam}/task")
@Validated
public class ExamTaskController {

    @Resource
    private ExamTaskService examTaskService;

    @Resource
    private ExamTaskDetailService examTaskDetailService;

    @Resource
    private BasicAttachmentService basicAttachmentService;

    @Resource
    private AsyncTaskReviewSampleExportService asyncTaskReviewSampleExportService;

    @Resource
    private PrintCommonService printCommonService;

    @Resource
    private BasicMessageService basicMessageService;

    @Resource
    private ExamTaskPrintService examTaskPrintService;

    @Resource
    TaskService taskService;

    @Resource
    private BasicStudentService basicStudentService;

    @Resource
    ActivitiService activitiService;

    @Resource
    ExamTaskApplyTempService examTaskApplyTempService;

    @Resource
    TFFlowJoinService tfFlowJoinService;

    /**
     * 命题任务管理-查询
     *
     * @param enable      正常/禁用
     * @param status      状态
     * @param cardRuleId  题卡规则ID
     * @param courseCode  课程代码
     * @param paperNumber 试卷编号
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @param userName    命题老师名称
     * @param createName  创建人名称
     * @param pageNumber  分页参数
     * @param pageSize    分页参数
     * @return Result
     */
    @ApiOperation(value = "命题任务管理-分页查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result list(@RequestParam(required = false) String semesterId,
                       @RequestParam(required = false) String examId,
                       @RequestParam(required = false) Boolean enable,
                       @RequestParam(required = false) String status,
                       @RequestParam(required = false) String cardRuleId,
                       @RequestParam(required = false) String courseCode,
                       @RequestParam(required = false) String paperNumber,
                       @RequestParam(required = false) Long startTime,
                       @RequestParam(required = false) Long endTime,
                       @RequestParam(required = false) String userName,
                       @RequestParam(required = false) String createName,
                       @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                       @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {

        return ResultUtil.ok(examTaskService.list(SystemConstant.convertIdToLong(semesterId), SystemConstant.convertIdToLong(examId), enable, status, SystemConstant.convertIdToLong(cardRuleId), courseCode, paperNumber, startTime, endTime, userName, createName, pageNumber, pageSize));
    }

    /**
     * 试卷编号模糊查询
     */
    @ApiOperation(value = "试卷编号模糊查询")
    @RequestMapping(value = "/paper_number_query", method = RequestMethod.POST)
    public Result paperNumberQuery(@RequestParam(value = "param", required = false) String param,
                                   @RequestParam(value = "printPlanId", required = false) List<String> printPlanId) {

        if (Objects.isNull(printPlanId)) {
            printPlanId = new ArrayList<>();
        }
        List<Long> printPlanIdList = printPlanId.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList());
        return ResultUtil.ok(examTaskService.listPaperNumber(param, printPlanIdList));
    }

    /**
     * 命题老师模糊查询
     */
    @ApiOperation(value = "命题老师模糊查询")
    @RequestMapping(value = "/user_query", method = RequestMethod.POST)
    public Result userQuery(@RequestParam(value = "param", required = false) String param) {
        return ResultUtil.ok(examTaskService.listUser(param));
    }

    /**
     * 命题任务管理-更改/指派命题老师
     */
    @ApiOperation(value = "命题任务管理-更改/指派命题老师")
    @RequestMapping(value = "/assign_user", method = RequestMethod.POST)
    public Result assignUser(@RequestBody ExamTask examTask) {
        return ResultUtil.ok(examTaskService.assignUser(examTask));
    }

    /**
     * 命题任务管理-启用/禁用
     */
    @ApiOperation(value = "命题任务管理-启用/禁用")
    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    public Result enable(@RequestBody ExamTask examTask) {
        return ResultUtil.ok(examTaskService.enable(examTask));
    }

    /**
     * 命题任务管理-新建命题任务
     */
    @ApiOperation(value = "命题任务管理-新建命题任务")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Result save(@RequestBody ExamTask examTask) {
        examTaskService.saveExamTaskNew(examTask);
        return ResultUtil.ok(true);
    }

    /**
     * 命题任务管理-文件导入
     */
    @ApiOperation(value = "命题任务管理-批量新建命题任务-文件导入")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public Result importFile(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file) {
        BasicAttachment basicAttachment = null;
        try {
            basicAttachment = printCommonService.saveAttachment(file, ServletUtil.getRequestMd5(), UploadFileEnum.FILE);
            if (Objects.isNull(basicAttachment)) {
                throw ExceptionResultEnum.ATTACHMENT_ERROR.exception();
            } else {
                ExamTaskImportDto examTaskImportDto = examTaskService.importFile(file);
                return ResultUtil.ok(examTaskImportDto);
            }
        } catch (Exception e) {
            if (Objects.nonNull(basicAttachment)) {
                basicAttachmentService.deleteAttachment(basicAttachment);
            }
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return null;
    }

    /**
     * 命题任务管理-批量保存命题任务
     */
    @ApiOperation(value = "命题任务管理-批量新建命题任务-保存")
    @RequestMapping(value = "/save_batch", method = RequestMethod.POST)
    public Result saveBatch(@RequestBody ExamTask task) {
        examTaskService.saveBatch(task);
        return ResultUtil.ok(true);
    }

//    /**
//     * 审核历史
//     */
//    @ApiOperation(value = "审核历史")
//    @RequestMapping(value = "/review_list", method = RequestMethod.POST)
//    public Result reviewList(@ApiParam(value = "流程id", required = true) @RequestParam String flowId) {
//        return ResultUtil.ok(examTaskReviewLogService.list(SystemConstant.convertIdToLong(flowId)));
//    }

    /**
     * 入库申请-查询
     *
     * @param auditStatus
     * @param cardRuleId
     * @param courseCode
     * @param paperNumber
     * @param startTime
     * @param endTime
     * @param userName    命题老师名称
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "入库申请-分页查询")
    @RequestMapping(value = "/apply_list", method = RequestMethod.POST)
    public Result taskApplyList(@RequestParam(value = "semesterId", required = false) Long semesterId,
                                @RequestParam(value = "examId", required = false) Long examId,
                                @RequestParam(value = "auditStatus", required = false) String auditStatus,
                                @RequestParam(value = "cardRuleId", required = false) String cardRuleId,
                                @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 = "userName", required = false) String userName,
                                @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(examTaskService.listTaskApply(semesterId, examId, auditStatus, SystemConstant.convertIdToLong(cardRuleId), courseCode, paperNumber, startTime, endTime, userName, pageNumber, pageSize));
    }

    /**
     * 根据命题任务ID查询单个数据
     *
     * @param examTaskId 命题任务ID
     * @return Result
     */
    @ApiOperation(value = "根据命题任务ID查询任务详情数据")
    @RequestMapping(value = "/exam_task_get_one", method = RequestMethod.POST)
    public Result applyGetOne(@RequestParam(value = "examTaskId") Long examTaskId) {
        ExamTaskDto examTaskDto = examTaskService.getByExamTaskId(examTaskId);
        return ResultUtil.ok(examTaskDto);
    }

    /**
     * 根据命题任务ID查询单个数据
     *
     * @param examTaskId 命题任务ID
     * @return Result
     */
    @ApiOperation(value = "根据命题任务ID查询任务详情数据")
    @RequestMapping(value = "/apply_get_one", method = RequestMethod.POST)
    public Result applyGetOne(@RequestParam(value = "examTaskId") Long examTaskId,
                              @RequestParam(value = "source", required = false) String source) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        ExamTaskDetailCardDto detail = examTaskService.applyGetOne(examTaskId, source);
        if (Objects.nonNull(detail) && Objects.nonNull(detail.getFlowId())) {
            Task task = taskService.createTaskQuery().processInstanceId(detail.getFlowId())
                    .taskCandidateOrAssigned(String.valueOf(sysUser.getId())).singleResult();
            if (Objects.nonNull(task)) {
                detail.setFlowTaskId(task.getId());
            } else {
                List<TFFlowJoin> tfFlowJoinList = tfFlowJoinService.findByObjectId(Long.parseLong(detail.getExamTaskId()));
                String flowId = null;
                TFFlowJoin tfFlowJoin = null;
                if (Objects.nonNull(tfFlowJoinList) && tfFlowJoinList.size() > 1) {
                    tfFlowJoin = tfFlowJoinList.get(tfFlowJoinList.size() - 1);
                } else if (Objects.nonNull(tfFlowJoinList) && tfFlowJoinList.size() == 1) {
                    tfFlowJoin = tfFlowJoinList.get(0);
                }
                flowId = Objects.nonNull(tfFlowJoin) ? String.valueOf(tfFlowJoin.getFlowId()) : flowId;
                task = taskService.createTaskQuery().processInstanceId(detail.getFlowId())
                        .taskCandidateOrAssigned(String.valueOf(sysUser.getId())).singleResult();
                if (Objects.nonNull(task)) {
//                    detail.setSubFlowReject(true);
                    detail.setFlowTaskId(task.getId());
                    detail.setFlowId(flowId);
                }
            }
        }
        return ResultUtil.ok(detail);
    }

    /**
     * 入库申请-暂存/提交
     *
     * @param examTaskDetail 命题任务详情对象
     * @return Result
     */
    @ApiOperation(value = "入库申请-暂存/提交")
    @RequestMapping(value = "/apply_save", method = RequestMethod.POST)
    public Result taskApplySave(@RequestBody ExamTaskDetail examTaskDetail) throws IOException {
        boolean isSuccess = examTaskService.saveExamTaskDetail(examTaskDetail);
        ExamTask examTask = examTaskService.getById(examTaskDetail.getExamTaskId());
        if (examTaskDetail.getOperateType().equals(ExamStatusEnum.SUBMIT.name()) && !examTask.getReview()) {
            // 校验是否可以提交打印状态
            printCommonService.checkData(examTask.getSchoolId(), examTask.getCourseCode(), examTask.getPaperNumber(), (SysUser) ServletUtil.getRequestUser());
        }

        return ResultUtil.ok(isSuccess);
    }

    @ApiOperation(value = "审核-印刷员驳回后命题老师修改")
    @RequestMapping(value = "/apply_resave", method = RequestMethod.POST)
    public Result taskReApplySave(@RequestBody ExamTaskReApplyParam examTaskReApplyParam) {
        examTaskService.applyResave(examTaskReApplyParam);
        return ResultUtil.ok();
    }

    /**
     * 入库申请-撤销申请
     *
     * @param examTask 命题任务对象
     * @return Result
     */
    @ApiOperation(value = "入库申请-撤销申请")
    @RequestMapping(value = "/apply_status", method = RequestMethod.POST)
    public Result taskApplyStatus(@RequestBody ExamTask examTask) {
        return ResultUtil.ok(examTaskService.status(examTask));
    }

    /**
     * 入库审核-查询-未审核
     *
     * @param courseCode
     * @param paperNumber
     * @param userId
     * @param cardRuleId
     * @param startTime
     * @param endTime
     * @param startCreateTime 申请时间-起始
     * @param endCreateTime   申请时间-终止
     * @param createName      创建人
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "入库审核-查询-未审核")
    @RequestMapping(value = "/review_list_unaudited", method = RequestMethod.POST)
    public Result taskReviewListUnaudited(@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 = "userId", required = false) Long userId,
                                          @RequestParam(value = "cardRuleId", required = false) String cardRuleId,
                                          @RequestParam(value = "startTime", required = false) Long startTime,
                                          @RequestParam(value = "endTime", required = false) Long endTime,
                                          @RequestParam(value = "startCreateTime", required = false) Long startCreateTime,
                                          @RequestParam(value = "endCreateTime", required = false) Long endCreateTime,
                                          @RequestParam(value = "createName", required = false) String createName,
                                          @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                          @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(examTaskService.listTaskReviewUnaudited(semesterId, examId, courseCode, paperNumber, userId, SystemConstant.convertIdToLong(cardRuleId), startTime, endTime, startCreateTime, endCreateTime, createName, pageNumber, pageSize));
    }

    /**
     * 入库审核-查询-未审核
     *
     * @param courseCode      课程代码
     * @param paperNumber     试卷编号
     * @param userId          命题老师ID
     * @param cardRuleId      题卡规则ID
     * @param startTime       开始时间
     * @param endTime         结束时间
     * @param startCreateTime 申请时间-起始
     * @param endCreateTime   申请时间-终止
     * @param createName      创建人
     * @param pageNumber      分页参数
     * @param pageSize        分页参数
     * @return Result
     */
    @ApiOperation(value = "入库审核-查询-已审核")
    @RequestMapping(value = "/review_list_audited", method = RequestMethod.POST)
    public Result taskReviewListAudited(@RequestParam(value = "semesterId", required = false) Long semesterId,
                                        @RequestParam(value = "examId", required = false) Long examId,
                                        @RequestParam(value = "reviewStatus", required = false) String reviewStatus,
                                        @RequestParam(value = "courseCode", required = false) String courseCode,
                                        @RequestParam(value = "paperNumber", required = false) String paperNumber,
                                        @RequestParam(value = "userId", required = false) Long userId,
                                        @RequestParam(value = "cardRuleId", required = false) String cardRuleId,
                                        @RequestParam(value = "startTime", required = false) Long startTime,
                                        @RequestParam(value = "endTime", required = false) Long endTime,
                                        @RequestParam(value = "startCreateTime", required = false) Long startCreateTime,
                                        @RequestParam(value = "endCreateTime", required = false) Long endCreateTime,
                                        @RequestParam(value = "createName", required = false) String createName,
                                        @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                        @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        return ResultUtil.ok(examTaskService.listTaskReviewAudited(semesterId, examId, reviewStatus, courseCode, paperNumber, userId, SystemConstant.convertIdToLong(cardRuleId), startTime, endTime, startCreateTime, endCreateTime, createName, pageNumber, pageSize));
    }

    /**
     * 审核
     *
     * @param taskReviewLog 审核对象
     * @return Result
     */
    @ApiOperation(value = "审核")
    @RequestMapping(value = "/review_save", method = RequestMethod.POST)
    public Result taskReviewSave(@RequestBody ExamTaskReviewLog taskReviewLog) throws IOException {
        List<Long> examTaskIdList = new ArrayList<>();
        examTaskIdList.add(taskReviewLog.getExamTaskId());
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        boolean isSuccess = examTaskService.taskReviewSave(taskReviewLog);
        if (isSuccess && taskReviewLog.getReviewStatus().name().equals(ReviewStatusEnum.PASS.name())) {
            ExamTask examTask = examTaskService.getById(taskReviewLog.getExamTaskId());
            // 校验是否可以提交打印状态
            printCommonService.checkData(examTask.getSchoolId(), examTask.getCourseCode(), examTask.getPaperNumber(), sysUser);
            // 发送审核通过短信通知
            basicMessageService.noticeOfExamTaskAudit(examTaskIdList, MessageEnum.NOTICE_OF_AUDIT_PASS, sysUser);
        } else if (isSuccess && taskReviewLog.getReviewStatus().name().equals(ReviewStatusEnum.NOT_PASS.name())) {
            // 发送审核不通过短信通知
            basicMessageService.noticeOfExamTaskAudit(examTaskIdList, MessageEnum.NOTICE_OF_AUDIT_NOT_PASS, sysUser);
        }
        return ResultUtil.ok(isSuccess);
    }

    /**
     * 入库审核-批量审核
     *
     * @param taskReviewLog 审核对象
     * @return Result
     */
    @ApiOperation(value = "入库审核-批量审核")
    @RequestMapping(value = "/review_save_batch", method = RequestMethod.POST)
    public Result taskReviewSaveBatch(@RequestBody ExamTaskReviewLog taskReviewLog) throws IOException {
        List<Long> examTaskIdList = Arrays.asList(taskReviewLog.getExamTaskIds());
        if (!CollectionUtils.isEmpty(examTaskIdList)) {
            for (Long examTaskId : examTaskIdList) {
                ExamTask examTask = examTaskService.getById(examTaskId);
                List<Task> taskList = taskService.createTaskQuery().processInstanceId(String.valueOf(examTask.getFlowId())).list();
                if (Objects.nonNull(taskList) && taskList.size() > 0) {
                    for (Task task : taskList) {
                        Map<String, Object> map = new HashMap<>();
                        map.computeIfAbsent(SystemConstant.FLOW_TASK_ID, v -> task.getId());
                        map.computeIfAbsent(SystemConstant.APPROVE_OPERATION, v -> FlowApprovePassEnum.PASS);
                        activitiService.taskApprove(map);
                    }
                }
            }
        }
        /*SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        boolean isSuccess = examTaskService.taskReviewSaveBatch(taskReviewLog);
        if (isSuccess && taskReviewLog.getReviewStatus().name().equals(ReviewStatusEnum.PASS.name())) {
            // 发送审核通过短信通知
            basicMessageService.noticeOfExamTaskAudit(examTaskIdList, MessageEnum.NOTICE_OF_AUDIT_PASS, sysUser);
        } else if (isSuccess && taskReviewLog.getReviewStatus().name().equals(ReviewStatusEnum.NOT_PASS.name())) {
            // 发送审核不通过短信通知
            basicMessageService.noticeOfExamTaskAudit(examTaskIdList, MessageEnum.NOTICE_OF_AUDIT_NOT_PASS, sysUser);
        }*/
        return ResultUtil.ok();
    }

    @ApiOperation(value = "导出审核样本")
    @RequestMapping(value = "/review_export", method = RequestMethod.POST)
    public Result taskReviewExport(@Valid @RequestBody ArraysParams arraysParams, BindingResult bindingResult) throws
            Exception {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        Long[] ids = arraysParams.getIds();
        Map<String, Object> map = printCommonService.saveTask(TaskTypeEnum.SAMPLE_EXPORT);
        map.put("ids", ids);
        asyncTaskReviewSampleExportService.exportTask(map);
        TBTask tbTask = Objects.nonNull(map.get(SystemConstant.TASK)) ? (TBTask) map.get(SystemConstant.TASK) : null;
        return Objects.nonNull(tbTask) ? ResultUtil.ok(tbTask.getId()) : ResultUtil.error("创建任务失败");
    }

    /**
     * 卷库查询
     *
     * @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) {
        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)
    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)
    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.getCourseCode(), examTask.getPaperNumber());
            // 校验是否可以提交打印状态
            if (isCreate) {
                printCommonService.checkData(examTask.getSchoolId(), examTask.getCourseCode(), examTask.getPaperNumber(), sysUser);
            }
        }
        return ResultUtil.ok(isSuccess);
    }

    /**
     * 卷库查询-卷库修改
     *
     * @param examTaskDetail 命题任务详情对象
     * @return Result
     */
    @ApiOperation(value = "卷库查询-卷库修改")
    @RequestMapping(value = "/paper_update", method = RequestMethod.POST)
    public Result taskPaperUpdate(@RequestBody ExamTaskDetail examTaskDetail) throws IOException {
        boolean isSuccess = examTaskDetailService.paperUpdate(examTaskDetail);
        if (isSuccess) {
            ExamTask examTask = examTaskService.getById(examTaskDetail.getExamTaskId());
            if (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.getCourseCode(), examTask.getPaperNumber(), sysUser);
                }
            }
        }
        return ResultUtil.ok(isSuccess);
    }

    @ApiOperation(value = "卷库查询-批量下载试卷PDF、题卡")
    @RequestMapping(value = "/paper_card_download_pdf", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
    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) {
        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 courseCode 课程代码
     * @return Result
     */
    @ApiOperation(value = "命题任务管理-命题申请-班级列表")
    @RequestMapping(value = "/list_task_apply_class", method = RequestMethod.POST)
    public Result listTaskApplyClass(@RequestParam(value = "courseCode") String courseCode) {
        return ResultUtil.ok(examTaskPrintService.listExamTaskClass(courseCode));
    }

    /**
     * 命题任务管理-命题申请-暂存
     *
     * @param examTaskApplyTemp
     * @return
     */
    @ApiOperation(value = "命题任务管理-命题申请-暂存")
    @RequestMapping(value = "/stage_task_apply", method = RequestMethod.POST)
    public Result stageTaskApply(@RequestBody ExamTaskApplyTemp examTaskApplyTemp) {
        ExamTaskApplyTemp task = examTaskApplyTempService.stageTaskApply(examTaskApplyTemp);
        return ResultUtil.ok(task);
    }

    /**
     * 入库申请-新建任务-保存
     *
     * @param examTaskApplyTemp
     * @return
     */
    @ApiOperation(value = "入库申请-新建任务-保存")
    @RequestMapping(value = "/submit_task_apply", method = RequestMethod.POST)
//    @OperationLogDetail(detail = "入库申请-新建任务（一步到位）",level = LevelEnum.PRIMARY)
    public Result submitTaskApply(@RequestBody ExamTaskApplyTemp examTaskApplyTemp) throws IOException {
        ExamTask examTask = examTaskService.submitTaskApply(examTaskApplyTemp);
        if (!examTask.getReview()) {
            // 校验是否可以提交打印状态
            printCommonService.checkData(examTask.getSchoolId(), examTask.getCourseCode(), examTask.getPaperNumber(), (SysUser) ServletUtil.getRequestUser());
        }
        return ResultUtil.ok();
    }

    /**
     * 入库申请-新建命题任务
     *
     * @param examTaskApplyParam
     * @return
     */
    @ApiOperation(value = "入库申请-新建命题任务-暂存/提交")
    @RequestMapping(value = "/save_task_apply", method = RequestMethod.POST)
    public Result saveTaskApply(@RequestBody ExamTaskApplyParam examTaskApplyParam) throws IOException {
        ExamTask examTask = examTaskService.saveExamTaskAndExamTaskDetail(examTaskApplyParam);
        if (examTaskApplyParam.getExamTaskDetail().getOperateType().equals(ExamStatusEnum.SUBMIT.name()) && !examTask.getReview()) {
            // 校验是否可以提交打印状态
            printCommonService.checkData(examTask.getSchoolId(), examTask.getCourseCode(), examTask.getPaperNumber(), (SysUser) ServletUtil.getRequestUser());
        }

        return ResultUtil.ok(examTask);
    }

    /**
     * 入库申请-新建命题任务-取消/删除
     *
     * @param examTaskId
     * @return
     */
    @ApiOperation(value = "入库申请-新建命题任务-取消/删除")
    @RequestMapping(value = "/remove_task_apply", method = RequestMethod.POST)
    public Result removeTaskApply(@RequestParam(value = "examTaskId") Long examTaskId) {
        examTaskService.removeByExamTaskId(examTaskId);
        return ResultUtil.ok(true, "");
    }

    /**
     * 入库申请-新建命题任务-切换题卡
     *
     * @param examTaskId
     * @return
     */
    @ApiOperation(value = "切换题卡")
    @RequestMapping(value = "/switch_card", method = RequestMethod.POST)
    public Result switchCard(@RequestParam(value = "examTaskId") Long examTaskId) {
        examTaskService.switchCard(examTaskId);
        return ResultUtil.ok(true, "");
    }

    /**
     * 查看印刷任务发布
     *
     * @param printPlanId
     * @param courseCode
     * @param paperNumber
     * @return
     */
    @ApiOperation(value = "卷库查询-发布印刷任务-查看列表")
    @RequestMapping(value = "/list_task_print", method = RequestMethod.POST)
    public Result listTaskPrintStudent(@RequestParam(value = "printPlanId") Long printPlanId,
                                       @RequestParam(value = "courseCode") String courseCode,
                                       @RequestParam(value = "paperNumber") String paperNumber) {
        ExamTaskPrintDto examTaskPrintDto = examTaskPrintService.listTaskPrint(printPlanId, courseCode, paperNumber);
        return ResultUtil.ok(examTaskPrintDto);
    }

    /**
     * 扩展字段列表
     *
     * @return
     */
    @ApiOperation(value = "卷库查询-发布印刷任务-扩展字段列表")
    @RequestMapping(value = "/list_task_print_extend_fields", method = RequestMethod.POST)
    public Result listTaskPrintExtendFields() {
        return ResultUtil.ok(examTaskPrintService.listTaskPrintExtendFields());
    }

    /**
     * 班级列表
     *
     * @param printPlanId
     * @return
     */
    @ApiOperation(value = "卷库查询-发布印刷任务-班级列表")
    @RequestMapping(value = "/list_task_print_class", method = RequestMethod.POST)
    public Result listTaskPrintClass(@RequestParam(value = "printPlanId") String printPlanId,
                                     @RequestParam(value = "courseCode") String courseCode,
                                     @RequestParam(value = "paperNumber") String paperNumber,
                                     @RequestParam(value = "examTaskPrintId", required = false) Long examTaskPrintId) {
        return ResultUtil.ok(examTaskPrintService.listClass(printPlanId, courseCode, paperNumber, examTaskPrintId));
    }

    /**
     * 印刷室列表
     *
     * @return
     */
    @ApiOperation(value = "卷库查询-发布印刷任务-印刷室列表")
    @RequestMapping(value = "/list_task_print_house", method = RequestMethod.POST)
    public Result listTaskPrintHouse() {
        return ResultUtil.ok(examTaskPrintService.listHouse());
    }

    /**
     * 发布印刷任务
     *
     * @param examTaskPrint
     * @return
     */
    @ApiOperation(value = "卷库查询-发布印刷任务")
    @RequestMapping(value = "/save_task_print", method = RequestMethod.POST)
    public Result createTaskPrint(@RequestBody ExamTaskPrint examTaskPrint) {
        examTaskPrintService.createTaskPrint(examTaskPrint);
        return ResultUtil.ok(true, "");
    }

    /**
     * 提交印刷任务
     *
     * @param examTaskPrintParams
     * @return
     */
    @ApiOperation(value = "卷库查询-批量提交印刷任务")
    @RequestMapping(value = "/submit_task_print", method = RequestMethod.POST)
    public Result submitTaskPrint(@RequestBody ExamTaskPrintParams examTaskPrintParams) throws IOException {
        examTaskPrintService.submitTaskPrint(examTaskPrintParams);
        return ResultUtil.ok(true, "");
    }

    /**
     * 查看考生
     *
     * @param classId
     * @return
     */
    @ApiOperation(value = "卷库查询-发布印刷任务-查看考生")
    @RequestMapping(value = "/list_task_print_student", method = RequestMethod.POST)
    public Result listTaskPrintStudent(@RequestParam(value = "classId") String classId,
                                       @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                       @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        Set<Long> classIds = Arrays.stream(classId.split(",")).map(SystemConstant::convertIdToLong).collect(Collectors.toSet());
        return ResultUtil.ok(basicStudentService.basicStudentPage(null, null, null, null, classIds, pageNumber, pageSize));
    }

    /**
     * 卷库查询-发布印刷任务-删除
     *
     * @param examTaskPrintId
     * @return
     */
    @ApiOperation(value = "卷库查询-发布印刷任务-删除")
    @RequestMapping(value = "/remove_task_print", method = RequestMethod.POST)
    public Result listTaskPrintStudent(@RequestParam(value = "examTaskPrintId") Long examTaskPrintId) {
        examTaskPrintService.remove(examTaskPrintId);
        return ResultUtil.ok(true, "");
    }

    @ApiOperation(value = "题卡标题查询")
    @RequestMapping(value = "/find_card_title", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findCardTitle(@ApiParam(value = "题卡规则id", required = true) @RequestParam String cardRuleId) {
        return ResultUtil.ok((Object) examTaskService.findCardTitle(SystemConstant.convertIdToLong(cardRuleId)));
    }

    @ApiOperation(value = "命题任务-审批-获取试卷审批表数据")
    @RequestMapping(value = "/find_approve_form_json", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findApproveFormJson(@ApiParam(value = "命题任务id", required = true) @RequestParam String examTaskId) {
        return ResultUtil.ok((Object) examTaskService.findExamTaskApprovalForm(SystemConstant.convertIdToLong(examTaskId)));
    }

    @ApiOperation(value = "命题任务-审批-获取试卷审批表pdf")
    @RequestMapping(value = "/find_approve_form_pdf", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public void findApproveFormPdf(@Valid @RequestBody ApproveFormParams approveFormParams, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw ExceptionResultEnum.ERROR.exception(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        HttpServletResponse response = ServletUtil.getResponse();
        examTaskService.findExamTaskApprovalPdf(response, approveFormParams.getExamTaskId(), approveFormParams.getHtmlContent());
    }

    @ApiOperation(value = "命题任务-考试对象查询")
    @RequestMapping(value = "/find_exam_object", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findExamObject(@ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber) {
        return ResultUtil.ok((Object) examTaskService.findExamObjectDtoByPaperNumber(paperNumber));
    }

}

