package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.params.ExamTaskReApplyParam;
import com.qmth.distributed.print.business.entity.ExamTask;
import com.qmth.distributed.print.business.entity.ExamTaskReviewLog;
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.SysUser;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.*;
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 com.qmth.teachcloud.mark.service.MarkPaperService;
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 javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.io.IOException;
import java.util.*;

/**
 * <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 ExamTaskAuditController {

    @Resource
    private ExamTaskService examTaskService;
    @Resource
    private AsyncTaskReviewSampleExportService asyncTaskReviewSampleExportService;
    @Resource
    private PrintCommonService printCommonService;
    @Resource
    private BasicMessageService basicMessageService;
    @Resource
    private TaskService taskService;
    @Resource
    private ActivitiService activitiService;
    @Resource
    private GradeInitializeService gradeInitializeService;
    @Resource
    private MarkPaperService markPaperService;


    @ApiOperation(value = "审核-印刷员驳回后命题老师修改")
    @RequestMapping(value = "/apply_resave", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE)
    public Result taskReApplySave(@RequestBody ExamTaskReApplyParam examTaskReApplyParam) {
        Map<String, Object> map = examTaskService.applyResave(examTaskReApplyParam);
        activitiService.sendFlowTaskApproveMsg(map);
        return ResultUtil.ok();
    }

    /**
     * 入库审核-查询-未审核
     *
     * @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) {
        if(examId == null){
            throw ExceptionResultEnum.EXAM_ID_IS_NULL.exception();
        }
        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) {
        if(examId == null){
            throw ExceptionResultEnum.EXAM_ID_IS_NULL.exception();
        }
        return ResultUtil.ok(examTaskService.listTaskReviewAudited(semesterId, examId, reviewStatus, courseCode, paperNumber, userId, SystemConstant.convertIdToLong(cardRuleId), startTime, endTime, startCreateTime, endCreateTime, createName, pageNumber, pageSize));
    }

    /**
     * 入库审核-查询-已审核数量
     *
     * @return
     */
    @ApiOperation(value = "入库审核-查询-已审核数量")
    @RequestMapping(value = "/review_list_audited_count", method = RequestMethod.POST)
    public Result taskReviewListAuditedCount() {
        int taskReviewAuditedCount = examTaskService.listTaskReviewAudited(null, null, null, null, null, null, null, null, null, null, null, null, SystemConstant.PAGE_NUMBER, SystemConstant.PAGE_SIZE).getRecords().size();
        long paperCount = markPaperService.countByPropositionTeacherId(true);
        long gradeCount = gradeInitializeService.countByPropositionTeacherId(GradeAnalyzePaperStatusEnum.SETTING_GRADE_PAPER_PARAM, true);
        return ResultUtil.ok(taskReviewAuditedCount + paperCount + gradeCount);
    }

    /**
     * 审核
     *
     * @param taskReviewLog 审核对象
     * @return Result ,
     */
    @ApiOperation(value = "审核")
    @RequestMapping(value = "/review_save", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE)
    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.getExamId(), 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)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE)
    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);
                        activitiService.sendFlowTaskApproveMsg(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)
    @OperationLogDetail(operationType = OperationTypeEnum.EXPORT)
    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("创建任务失败");
    }
}

