package com.qmth.distributed.print.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.dto.PrintTaskDto;
import com.qmth.distributed.print.business.bean.dto.PrintTaskTotalDto;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.distributed.print.business.entity.ExamDetail;
import com.qmth.distributed.print.business.enums.ExamDetailStatusEnum;
import com.qmth.distributed.print.business.service.ExamDetailService;
import com.qmth.distributed.print.business.service.ExamPrintPlanService;
import com.qmth.distributed.print.business.templete.execute.AsyncDownloadPdfTempleteService;
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.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.TaskTypeEnum;
import com.qmth.teachcloud.common.enums.log.OperationTypeEnum;
import com.qmth.teachcloud.common.service.TBTaskService;
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.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.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 印刷任务管理 前端控制器
 * </p>
 */
@Api(tags = "印刷任务管理Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_EXAM + "/print")
@Validated
public class ExamPrintTaskController {
    @Resource
    private ExamPrintPlanService examPrintPlanService;
    @Resource
    private ExamDetailService examDetailService;
    @Resource
    private TBTaskService tbTaskService;
    @Resource
    private AsyncDownloadPdfTempleteService asyncDownloadPdfTempleteService;

    /**
     * 印刷任务管理-查询
     */
    @ApiOperation(value = "印刷任务管理-查询")
    @RequestMapping(value = "/task_list", method = RequestMethod.POST)
    public Result taskList(@ApiParam(value = "学期ID") @RequestParam(required = false) String semesterId,
                           @ApiParam(value = "考试ID") @RequestParam(required = false) String examId,
                           @ApiParam(value = "印刷计划ID") @RequestParam(value = "printPlanId", required = false) Long printPlanId,
                           @ApiParam(value = "印刷计划状态") @RequestParam(value = "status", required = false) String status,
                           @ApiParam(value = "课程代码") @RequestParam(value = "courseCode", required = false) String courseCode,
                           @ApiParam(value = "试卷编号") @RequestParam(value = "paperNumber", required = false) String paperNumber,
                           @ApiParam(value = "考点") @RequestParam(value = "examPlace", required = false) String examPlace,
                           @ApiParam(value = "考场") @RequestParam(value = "examRoom", required = false) String examRoom,
                           @ApiParam(value = "考试时间（开始）") @RequestParam(value = "examStartTime", required = false) Long examStartTime,
                           @ApiParam(value = "考试时间（结束）") @RequestParam(value = "examEndTime", required = false) Long examEndTime,
                           @ApiParam(value = "打印时间（开始）") @RequestParam(value = "printStartTime", required = false) Long printStartTime,
                           @ApiParam(value = "打印时间（结束）") @RequestParam(value = "printEndTime", required = false) Long printEndTime,
                           @ApiParam(value = "印刷室ID") @RequestParam(value = "printHouseId", required = false) String printHouseId,
                           @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                           @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        if (semesterId == null) {
            throw ExceptionResultEnum.SEMESTER_ID_IS_NULL.exception();
        }
        if (examId == null) {
            throw ExceptionResultEnum.EXAM_ID_IS_NULL.exception();
        }
        IPage<PrintTaskDto> examTasks = examDetailService.listPrintTask(SystemConstant.convertIdToLong(semesterId), SystemConstant.convertIdToLong(examId), printPlanId, status, courseCode, paperNumber, examPlace, examRoom, examStartTime, examEndTime, printStartTime, printEndTime, SystemConstant.convertIdToLong(printHouseId), pageNumber, pageSize);
        return ResultUtil.ok(examTasks);
    }

    /**
     * 印刷任务管理-汇总数据查询
     *
     * @param printPlanId
     * @param status
     * @param courseCode
     * @param paperNumber
     * @param examPlace
     * @param examRoom
     * @param examStartTime
     * @param examEndTime
     * @return
     */
    @ApiOperation(value = "印刷任务管理-汇总数据查询")
    @RequestMapping(value = "/task_total_data", method = RequestMethod.POST)
    public Result taskTotalData(@ApiParam(value = "学期ID") @RequestParam(required = false) Long semesterId,
                                @ApiParam(value = "考试ID") @RequestParam(required = false) Long examId,
                                @ApiParam(value = "印刷计划ID") @RequestParam(value = "printPlanId", required = false) Long printPlanId,
                                @ApiParam(value = "印刷计划状态") @RequestParam(value = "status", required = false) String status,
                                @ApiParam(value = "课程代码") @RequestParam(value = "courseCode", required = false) String courseCode,
                                @ApiParam(value = "试卷编号") @RequestParam(value = "paperNumber", required = false) String paperNumber,
                                @ApiParam(value = "考点") @RequestParam(value = "examPlace", required = false) String examPlace,
                                @ApiParam(value = "考场") @RequestParam(value = "examRoom", required = false) String examRoom,
                                @ApiParam(value = "考试时间（开始）") @RequestParam(value = "examStartTime", required = false) Long examStartTime,
                                @ApiParam(value = "考试时间（结束）") @RequestParam(value = "examEndTime", required = false) Long examEndTime,
                                @ApiParam(value = "打印时间（开始）") @RequestParam(value = "printStartTime", required = false) Long printStartTime,
                                @ApiParam(value = "打印时间（结束）") @RequestParam(value = "printEndTime", required = false) Long printEndTime,
                                @ApiParam(value = "印刷室ID") @RequestParam(value = "printHouseId", required = false) String printHouseId) {
        PrintTaskTotalDto printTaskTotalDto = examDetailService.taskTotalData(semesterId, examId, printPlanId, status, courseCode, paperNumber, examPlace, examRoom, examStartTime, examEndTime, printStartTime, printEndTime, SystemConstant.convertIdToLong(printHouseId));
        return ResultUtil.ok(printTaskTotalDto);
    }

    /**
     * 提交印刷
     *
     * @param examDetail
     * @return
     */
    @ApiOperation(value = "印刷任务管理-提交印刷")
    @RequestMapping(value = "/task_submit", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE, detail = "提交印刷操作，考场ID：{{examDetail.id}}、状态：{{examDetail.status}}")
    public Result taskSubmit(@RequestBody ExamDetail examDetail) throws IOException {
        boolean isSuccess = examDetailService.taskSubmit(examDetail);
        return ResultUtil.ok(isSuccess);
    }

    /**
     * 撤回
     *
     * @param examDetail
     * @return
     */
    @ApiOperation(value = "印刷任务管理-撤回提交")
    @RequestMapping(value = "/task_cancel", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE, detail = "撤回提交操作，考场ID：{{examDetail.id}}、状态：{{examDetail.status}}")
    public Result taskCancel(@RequestBody ExamDetail examDetail) {
        boolean isSuccess = examDetailService.taskCancel(examDetail.getId());
        return ResultUtil.ok(isSuccess);
    }

    /**
     * 批量完成/撤回/提交
     *
     * @param data id集合
     * @return
     */
    @ApiOperation(value = "印刷任务管理-批量完成/撤回/提交")
    @RequestMapping(value = "/task_batch_cancel", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE, detail = "批量完成/撤回/提交操作，参数：{{data}}")
    public Result taskCancel(@RequestBody Map data) {
        boolean isSuccess = examDetailService.taskBatchCancel(data);
        return ResultUtil.ok(isSuccess);
    }


//    /**
//     * 重新提交
//     *
//     * @param examDetail
//     * @return
//     */
//    @ApiOperation(value = "印刷任务管理-重新提交")
//    @RequestMapping(value = "/task_resubmit", method = RequestMethod.POST)
//    @OperationLogDetail(customizedOperationType = CustomizedOperationTypeEnum.UPDATE)
//    public Result taskResubmit(@RequestBody ExamDetail examDetail) throws IOException {
//        boolean isSuccess = examDetailService.resubmitTask(examDetail);
//        return ResultUtil.ok(isSuccess);
//    }

    /**
     * 印刷任务管理-查看印品
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "印刷任务管理-查看印品")
    @RequestMapping(value = "/template_view", method = RequestMethod.POST)
    public Result templateViewPDF(@RequestBody Map<String, Long> map) {
        List<Map<String, String>> list = examPrintPlanService.tempalteView(map.get("printPlanId"));
        return ResultUtil.ok(list);
    }

    /**
     * 印刷任务管理-预览PDF
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "印刷任务管理-预览")
    @RequestMapping(value = "/task_view_pdf", method = RequestMethod.POST)
    public Result taskViewPDF(@RequestBody Map<String, Long> map) {
        List<JSONObject> list = examDetailService.taskViewPDF(map.get("examDetailId"));
        return ResultUtil.ok(list);
    }

    @ApiOperation(value = "印刷任务管理-批量下载PDF")
    @RequestMapping(value = "/task_download_pdf", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = EditResult.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.EXPORT)
    public Result taskDownloadPdf(@ApiParam(value = "id数组", required = true) @Valid @RequestBody ArraysParams arraysParams, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        List<ExamDetail> examDetailList = examDetailService.listByIds(Arrays.asList(arraysParams.getIds()));
        for (ExamDetail ExamDetail : examDetailList) {
            if (ExamDetail.getStatus() == ExamDetailStatusEnum.NEW) {
                throw ExceptionResultEnum.ERROR.exception("状态为新建不能下载");
            }
        }
        Map<String, Object> map = tbTaskService.saveTask(TaskTypeEnum.PRINT_PDF_DOWNLOAD, arraysParams, (SysUser) ServletUtil.getRequestUser());
        asyncDownloadPdfTempleteService.exportTask(map);
        TBTask tbTask = Objects.nonNull(map.get(SystemConstant.TASK)) ? (TBTask) map.get(SystemConstant.TASK) : null;
        return Objects.nonNull(tbTask) ? ResultUtil.ok(new EditResult(tbTask.getId())) : ResultUtil.error("创建任务失败");
    }

    /**
     * 印刷任务做废、恢复
     */
    @ApiOperation(value = "印刷任务管理-作废/恢复")
    @RequestMapping(value = "/task_normal", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.UPDATE)
    public Result taskNormal(@RequestBody ExamDetail examDetail) {
        boolean isSuccess = examDetailService.taskNormal(examDetail);
        return ResultUtil.ok(isSuccess);
    }
}

