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.PaperLibraryService;
import com.qmth.paper.library.business.service.PictureManageService;
import com.qmth.paper.library.business.templete.execute.AsyncDownloadPictureService;
import com.qmth.paper.library.common.bean.params.DownloadPictureParams;
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.ExceptionResultEnum;
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.*;
import org.apache.commons.collections4.CollectionUtils;
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 org.springframework.web.multipart.MultipartFile;

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;

/**
 * @Description 图片管理控制类
 */
@Api(tags = "图片管理Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + ApiPrefixConstant.PREFIX_PAPER + "/picture")
@Validated
public class PictureManageController {

    @Resource
    private PictureManageService pictureManageService;

    @Resource
    private PaperLibraryService paperLibraryService;

    @Resource
    private TBTaskService tbTaskService;

    @Resource
    private AsyncDownloadPictureService asyncDownloadPictureService;

    @ApiOperation(value = "分页查询")
    @PostMapping("/page")
    @ApiResponses({ @ApiResponse(code = 200, message = "查询成功", response = Result.class) })
    public Result page(@ApiParam(value = "姓名或学号") @RequestParam(value = "param", required = false) String param,
            @ApiParam(value = "学号（开始）") @RequestParam(value = "startStudentCode", required = false) String startStudentCode,
            @ApiParam(value = "学号（结束）") @RequestParam(value = "endStudentCode", required = false) String endStudentCode,
            @ApiParam(value = "学期ID") @RequestParam(value = "semesterId", required = false) Long semesterId,
            @ApiParam(value = "考试ID") @RequestParam(value = "examId", required = false) Long examId,
            @ApiParam(value = "课程代码") @RequestParam(value = "courseCode", required = false) String courseCode,
            @ApiParam(value = "任课老师") @RequestParam(value = "teacher", required = false) String teacher,
            @ApiParam(value = "学院") @RequestParam(value = "collegeName", required = false) String collegeName,
            @ApiParam(value = "专业") @RequestParam(value = "majorName", required = false) String majorName,
            @ApiParam(value = "班级") @RequestParam(value = "className", required = false) String className,
            @ApiParam(value = "教学班") @RequestParam(value = "teachClass", required = false) String teachClass,
            @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(
                pictureManageService.pageData(semesterId, examId, courseCode, collegeName, majorName, className, teacher, teachClass, param, startStudentCode,
                        endStudentCode, pictureSymbol, pictureCount, pageNumber, pageSize));
    }

    @ApiOperation(value = "查询考生图片集合")
    @PostMapping("/list_student_picture")
    @ApiResponses({ @ApiResponse(code = 200, message = "查询成功", response = Result.class) })
    public Result listStudentPicture(@ApiParam(value = "考生ID", required = true) @RequestParam Long studentId) {
        return ResultUtil.ok(paperLibraryService.listStudentPicture(null, studentId));
    }

    @ApiOperation(value = "保存图片")
    @PostMapping("/save")
    @ApiResponses({ @ApiResponse(code = 200, message = "保存图片成功", response = Result.class) })
    public Result save(@ApiParam(value = "需要修改的图片", required = true) @RequestParam MultipartFile file,
            @ApiParam(value = "文件的MD5", required = true) @RequestParam String fileMd5,
            @ApiParam(value = "修改文件的路径", required = true) @RequestParam String fileUrl,
            @ApiParam(value = "图片表ID", required = true) @RequestParam Long paperLibraryId) {
        return ResultUtil.ok(pictureManageService.savePicture(file, fileMd5, fileUrl, paperLibraryId));
    }

    @ApiOperation(value = "下载图片异步")
    @PostMapping("/download")
    @ApiResponses({ @ApiResponse(code = 200, message = "下载成功", response = EditResult.class) })
    public Result download(DownloadPictureParams params) {
        if(CollectionUtils.isEmpty(params.getStudentIds())){
            throw ExceptionResultEnum.ERROR.exception("请选择要下载数据");
        }
        String pictureParams = JSON.toJSONString(params);
        Map<String, Object> map = tbTaskService.saveTask(TaskTypeEnum.PICTURE_DOWNLOAD, pictureParams, (SysUser) ServletUtil.getRequestUser());
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        map.put("schoolId", schoolId);
        //异步任务
        asyncDownloadPictureService.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("创建任务失败");
    }

}
