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.ExamTaskDetailDto;
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.dto.RelatePaperDto;
import com.qmth.distributed.print.business.bean.params.DeleteParams;
import com.qmth.distributed.print.business.bean.params.PrintPlanParams;
import com.qmth.distributed.print.business.bean.params.RelatePaperParam;
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.enums.PrintPlanStatusEnum;
import com.qmth.distributed.print.business.service.ExamDetailService;
import com.qmth.distributed.print.business.service.ExamPrintPlanService;
import com.qmth.distributed.print.business.service.ExamTaskDetailService;
import com.qmth.distributed.print.business.service.ExamTaskService;
import com.qmth.distributed.print.business.templete.execute.AsyncDownloadPdfTempleteService;
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.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.beans.factory.annotation.Autowired;
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.*;
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}/print")
@Validated
public class ExamPrintPlanController {
    @Resource
    private ExamPrintPlanService examPrintPlanService;
    @Autowired
    private ExamTaskService examTaskService;

    @Autowired
    private ExamTaskDetailService examTaskDetailService;

    @Autowired
    private ExamDetailService examDetailService;

    @Resource
    TBTaskService tbTaskService;

    @Resource
    AsyncDownloadPdfTempleteService asyncDownloadPdfTempleteService;

    @ApiOperation(value = "印刷计划查询")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findPrintPlanPage(@ApiParam(value = "学期ID") @RequestParam(required = false) Long semesterId,
                                    @ApiParam(value = "考试id") @RequestParam(required = false) String examId,
                                    @ApiParam(value = "印刷计划id集合") @RequestParam(required = false) List<String> printPlanIdList,
                                    @ApiParam(value = "印刷计划状态") @RequestParam(required = false) PrintPlanStatusEnum status,
                                    @ApiParam(value = "计划创建时间段开始时间") @RequestParam(required = false) Long startTime,
                                    @ApiParam(value = "计划创建时间段结束时间") @RequestParam(required = false) Long endTime,
                                    @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                    @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {

        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        if (Objects.isNull(printPlanIdList)) {
            printPlanIdList = new ArrayList<>();
        }
        List<Long> idList = printPlanIdList.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList());
        return ResultUtil.ok(examPrintPlanService.printPlanPage(schoolId, semesterId, SystemConstant.convertIdToLong(examId), idList, status, startTime, endTime, pageNumber, pageSize));
    }

    @ApiOperation(value = "印刷计划模糊查询")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findPrintPlanQuery(@RequestParam(value = "source", required = false) String source,
                                     @RequestParam(value = "module", required = false) String module) {
        return ResultUtil.ok(examPrintPlanService.printPlanBriefQuery(source, module));
    }

    @ApiOperation(value = "按类型查询模板")
    @RequestMapping(value = "/get_template", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result findPrintPlanPage() {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        SysUser user = (SysUser) ServletUtil.getRequestUser();
        Long userId = user.getId();
        return ResultUtil.ok(examPrintPlanService.printPlanTemplateDatasource(schoolId, userId));
    }

    @ApiOperation(value = "印刷计划-新增/修改")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "更新成功", response = Result.class)})
    public Result savePrintPlan(@Valid @RequestBody PrintPlanParams printPlanParams, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        printPlanParams.setSchoolId(schoolId);
        return ResultUtil.ok(examPrintPlanService.savePrintPlan(printPlanParams));
    }

    @ApiOperation(value = "印刷计划-删除")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功", response = Result.class)})
    public Result removePrintPlan(@Valid @RequestBody DeleteParams deleteParams, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultUtil.ok(examPrintPlanService.removePrintPlan(deleteParams));
    }

    /**
     * 关联试卷管理-查询
     *
     * @param relateType
     * @param printPlanIdList 印刷计划id集合
     * @param courseCode
     * @param paperNumber
     * @param userName        命题老师
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "关联试卷管理-查询")
    @RequestMapping(value = "/relate_list", method = RequestMethod.POST)
    public Result relateList(@RequestParam(value = "relateType", required = false) String relateType,
                             @RequestParam(value = "printPlanIdList", required = false) List<String> printPlanIdList,
                             @RequestParam(value = "courseCode", required = false) String courseCode,
                             @RequestParam(value = "paperNumber", required = false) String paperNumber,
                             @RequestParam(value = "userName", required = false) String userName,
                             @RequestParam(value = "cardRuleId", required = false) Long cardRuleId,
                             @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                             @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) {
        if (Objects.isNull(printPlanIdList)) {
            printPlanIdList = new ArrayList<>();
        }
        List<Long> idList = printPlanIdList.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList());
        IPage<ExamTaskDetailDto> examTasks = examTaskDetailService.list(relateType, idList, courseCode, paperNumber, userName, cardRuleId, pageNumber, pageSize);
        return ResultUtil.ok(examTasks);
    }

    /**
     * 关联/更换试卷
     *
     * @param paperParam
     * @return
     */
    @ApiOperation(value = "关联/更换试卷")
    @RequestMapping(value = "/relate_update", method = RequestMethod.POST)
    public Result relateUpdate(@RequestBody RelatePaperParam paperParam) throws IOException {
        boolean isSuccess = examTaskDetailService.updatePaper(paperParam);
        return ResultUtil.ok(isSuccess);
    }

    /**
     * 查询所有试卷编号/关联卷型
     *
     * @param examTaskId
     * @return
     */
    @ApiOperation(value = "查询所有试卷编号/关联卷型")
    @RequestMapping(value = "/relate_get_paper_numbers", method = RequestMethod.POST)
    public Result relateGetPaperNumbers(@RequestParam(value = "examTaskId", required = true) Long examTaskId,
                                        @RequestParam(value = "printPlanId", required = true) Long printPlanId,
                                        @RequestParam(value = "courseCode", required = true) String courseCode) {
        List<RelatePaperDto> list = examTaskService.listPaperTypes(examTaskId, printPlanId, courseCode);
        return ResultUtil.ok(list);
    }

    /**
     * 印刷任务管理-查询
     *
     * @param printPlanId
     * @param status
     * @param courseCode
     * @param paperNumber
     * @param examPlace
     * @param examStartTime
     * @param examEndTime
     * @param printHouseId  印刷室id
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "印刷任务管理-查询")
    @RequestMapping(value = "/task_list", method = RequestMethod.POST)
    public Result taskList(@RequestParam(value = "printPlanId", required = false) Long printPlanId,
                           @RequestParam(value = "status", required = false) String status,
                           @RequestParam(value = "courseCode", required = false) String courseCode,
                           @RequestParam(value = "paperNumber", required = false) String paperNumber,
                           @RequestParam(value = "examPlace", required = false) String examPlace,
                           @RequestParam(value = "examRoom", required = false) String examRoom,
                           @RequestParam(value = "examStartTime", required = false) Long examStartTime,
                           @RequestParam(value = "examEndTime", required = false) Long examEndTime,
                           @RequestParam(value = "printStartTime", required = false) Long printStartTime,
                           @RequestParam(value = "printEndTime", required = false) Long printEndTime,
                           @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) {
        IPage<PrintTaskDto> examTasks = examDetailService.listPrintTask(printPlanId, status, courseCode, paperNumber, examPlace, examRoom, examStartTime, examEndTime, printStartTime, printEndTime, SystemConstant.convertIdToLong(printHouseId), pageNumber, pageSize);
        return ResultUtil.ok(examTasks);
    }

    /**
     * 提交印刷
     *
     * @param examDetail
     * @return
     */
    @ApiOperation(value = "印刷任务管理-提交印刷")
    @RequestMapping(value = "/task_submit", method = RequestMethod.POST)
    public Result taskSubmit(@RequestBody ExamDetail examDetail) throws IOException {
        boolean isSuccess = examDetailService.submitTask(examDetail);
        return ResultUtil.ok(isSuccess);
    }

    /**
     * 撤回
     *
     * @param examDetail
     * @return
     */
    @ApiOperation(value = "印刷任务管理-撤回提交")
    @RequestMapping(value = "/task_cancel", method = RequestMethod.POST)
    public Result taskCancel(@RequestBody ExamDetail examDetail) {
        boolean isSuccess = examDetailService.taskCancel(examDetail);
        return ResultUtil.ok(isSuccess);
    }


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

    /**
     * 印刷任务管理-汇总数据查询
     *
     * @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(@RequestParam(value = "printPlanId", required = false) Long printPlanId,
                                @RequestParam(value = "status", required = false) String status,
                                @RequestParam(value = "courseCode", required = false) String courseCode,
                                @RequestParam(value = "paperNumber", required = false) String paperNumber,
                                @RequestParam(value = "examPlace", required = false) String examPlace,
                                @RequestParam(value = "examRoom", required = false) String examRoom,
                                @RequestParam(value = "examStartTime", required = false) Long examStartTime,
                                @RequestParam(value = "examEndTime", required = false) Long examEndTime,
                                @RequestParam(value = "printStartTime", required = false) Long printStartTime,
                                @RequestParam(value = "printEndTime", required = false) Long printEndTime,
                                @RequestParam(value = "printHouseId", required = false) String printHouseId) {
        PrintTaskTotalDto printTaskTotalDto = examDetailService.taskTotalData(printPlanId, status, courseCode, paperNumber, examPlace, examRoom, examStartTime, examEndTime, printStartTime, printEndTime, SystemConstant.convertIdToLong(printHouseId));
        return ResultUtil.ok(printTaskTotalDto);
    }

    /**
     * 印刷任务管理-查看印品
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "印刷任务管理-查看印品")
    @RequestMapping(value = "/template_view", method = RequestMethod.POST)
    public Result tempalteViewPDF(@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 = "印刷任务管理-查看PDF")
    @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)})
    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("创建任务失败");
    }

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

