package com.qmth.paper.library.api;

import com.alibaba.fastjson.JSON;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.paper.library.business.bean.result.EditResult;
import com.qmth.paper.library.business.service.DocManageService;
import com.qmth.paper.library.business.service.PaperLibraryService;
import com.qmth.paper.library.business.templete.execute.AsyncDownloadPaperService;
import com.qmth.paper.library.common.bean.params.DownLoadPaperParams;
import com.qmth.paper.library.common.contant.ApiPrefixConstant;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.SysUser;
import com.qmth.paper.library.common.entity.TBTask;
import com.qmth.paper.library.common.enums.TaskTypeEnum;
import com.qmth.paper.library.common.service.TBTaskService;
import com.qmth.paper.library.common.util.Result;
import com.qmth.paper.library.common.util.ResultUtil;
import com.qmth.paper.library.common.util.ServletUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 文档管理表 前端控制器
 * </p>
 */
@Api(tags = "文档管理controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + ApiPrefixConstant.PREFIX_PAPER + "/document")
@Validated
public class DocManageController {
    @Resource
    private DocManageService docManageService;
    @Resource
    private PaperLibraryService paperLibraryService;
    @Resource
    private TBTaskService tbTaskService;
    @Resource
    private AsyncDownloadPaperService asyncDownloadPaperService;

    @ApiOperation(value = "分页查询")
    @PostMapping("/page")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result page(@ApiParam(value = "学期ID", required = true) @RequestParam Long semesterId,
                       @ApiParam(value = "考试ID", required = true) @RequestParam Long examId,
                       @ApiParam(value = "课程代码") @RequestParam(required = false) String courseCode,
                       @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) {
        return ResultUtil.ok(docManageService.pageData(semesterId, examId, courseCode, pageNumber, pageSize));
    }

    @ApiOperation(value = "汇总统计")
    @PostMapping("/stat")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result stat(@ApiParam(value = "学期ID", required = true) @RequestParam Long semesterId,
                       @ApiParam(value = "考试ID", required = true) @RequestParam Long examId,
                       @ApiParam(value = "课程代码") @RequestParam(required = false) String courseCode) {
        return ResultUtil.ok(docManageService.statData(semesterId, examId, courseCode));
    }

    @ApiOperation(value = "查看详情")
    @PostMapping("/detail")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result pageDetail(@ApiParam(value = "扫描任务ID") @RequestParam(required = false) Long paperScanTaskId,
                             @ApiParam(value = "学院") @RequestParam(required = false) String collegeName,
                             @ApiParam(value = "专业") @RequestParam(required = false) String majorName,
                             @ApiParam(value = "班级") @RequestParam(required = false) String className,
                             @ApiParam(value = "考场") @RequestParam(required = false) String examRoom,
                             @ApiParam(value = "任课老师") @RequestParam(required = false) String teacher,
                             @ApiParam(value = "教学班") @RequestParam(required = false) String teachClass,
                             @ApiParam(value = "是否绑定") @RequestParam(required = false) Boolean isBind,
                             @ApiParam(value = "模糊查询（姓名/学号）") @RequestParam(required = false) String param,
                             @ApiParam(value = "成绩（小）") @RequestParam(required = false) Double minScore,
                             @ApiParam(value = "成绩（大）") @RequestParam(required = false) Double maxScore,
                             @ApiParam(value = "绑定数量（小）") @RequestParam(required = false) Integer minBindCount,
                             @ApiParam(value = "绑定数量（大）") @RequestParam(required = false) Integer maxBindCount,
                             @ApiParam(value = "大于、等于、小于、不等于") @RequestParam(value = "pictureSymbol", required = false) String pictureSymbol,
                             @ApiParam(value = "图片张数") @RequestParam(value = "pictureCount", required = false) Integer pictureCount,
                             @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) {
        return ResultUtil.ok(docManageService.pageDetail(paperScanTaskId, collegeName, majorName, className, examRoom, teacher, teachClass, isBind, param, minScore, maxScore, minBindCount, maxBindCount, pictureSymbol, pictureCount, pageNumber, pageSize));
    }

    @ApiOperation(value = "批量下载")
    @PostMapping("/download")
    @ApiResponses({@ApiResponse(code = 200, message = "下载成功", response = EditResult.class)})
    public Result paperDownload(DownLoadPaperParams downLoadPaperParams) {
        String remark = JSON.toJSONString(downLoadPaperParams);
        Map<String, Object> map = tbTaskService.saveTask(TaskTypeEnum.PAPER_DOWNLOAD, remark, (SysUser) ServletUtil.getRequestUser());
        asyncDownloadPaperService.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 = "查询考生图片集合")
    @PostMapping("/list_student_picture")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result listStudentPicture(@ApiParam(value = "扫描任务ID", required = true) @RequestParam Long paperScanTaskId,
                                     @ApiParam(value = "考生ID", required = true) @RequestParam Long studentId) {
        return ResultUtil.ok(paperLibraryService.listStudentPicture(paperScanTaskId, studentId));
    }

    @ApiOperation(value = "查询可绑定考生")
    @PostMapping("/page_student")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result pageStudent(@ApiParam(value = "考试ID", required = true) @RequestParam Long examId,
                              @ApiParam(value = "课程代码") @RequestParam(required = false) String courseCode,
                              @ApiParam(value = "学号模糊查询") @RequestParam(required = false) String studentCode,
                              @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) {
        return ResultUtil.ok(paperLibraryService.pageStudent(examId, courseCode, studentCode, pageNumber, pageSize));
    }

    @ApiOperation(value = "重新绑定")
    @PostMapping("/rebind")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result rebind(@ApiParam(value = "图片ID", required = true) @RequestParam Long paperLibraryId,
                         @ApiParam(value = "考生ID", required = true) @RequestParam() Long studentId) {
        return ResultUtil.ok(paperLibraryService.rebind(paperLibraryId, studentId));
    }

    @ApiOperation(value = "其它文件详情")
    @PostMapping("/other_detail")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result pageDetail(@ApiParam(value = "扫描任务ID", required = true) @RequestParam Long paperScanTaskId,
                             @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) {
        return ResultUtil.ok(docManageService.pageOtherDetail(paperScanTaskId, pageNumber, pageSize));
    }

    @ApiOperation(value = "pdf图片生成")
    @PostMapping("/pdf/generate")
    @ApiResponses({@ApiResponse(code = 200, message = "下载成功", response = EditResult.class)})
    public Result pdfGenerate(DownLoadPaperParams params) {
        Map<String, Object> map = paperLibraryService.pdfGenerate(params);
        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 = "删除图片")
    @PostMapping("/picture/delete")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result deletePicture(@ApiParam(value = "图片ID", required = true) @RequestParam List<Long> paperLibraryIds) {
        return ResultUtil.ok(paperLibraryService.deletePicture(paperLibraryIds));
    }

    @ApiOperation(value = "旋转保存图片")
    @PostMapping("/picture/save")
    @ApiResponses({@ApiResponse(code = 200, message = "保存图片成功", response = Result.class)})
    public Result pictureUpload(@ApiParam(value = "图片ID", required = true) @RequestParam Long paperLibraryId,
                                @ApiParam(value = "是否正面", required = true) @RequestParam boolean isFront,
                                @ApiParam(value = "旋转角度") @RequestParam(defaultValue = "0") Integer rotate) {
        return ResultUtil.ok(paperLibraryService.rotatePictureUpload(paperLibraryId, isFront, rotate));
    }
}
