package com.qmth.distributed.print.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.bean.params.BasicExamStudentParam;
import com.qmth.distributed.print.business.bean.result.BasicExamStudentResult;
import com.qmth.distributed.print.business.service.BasicExamStudentService;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.distributed.print.business.templete.execute.SyncBasicExamStudentImportService;
import com.qmth.teachcloud.common.annotation.OperationLogDetail;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
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.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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 考生字典表 前端控制器
 * </p>
 *
 * @author CaoZixuan
 * @since 2024-02-22
 */
@Api(tags = "考生管理controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_BASIC + "/exam_student")
public class BasicExamStudentController {

    @Resource
    private BasicExamStudentService basicExamStudentService;

    @Resource
    private PrintCommonService printCommonService;

    @Resource
    private SyncBasicExamStudentImportService syncBasicExamStudentImportService;

    @ApiOperation(value = "分页查询")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = BasicExamStudentResult.class)})
    public Result findBasicExamStudentPage(@ApiParam(value = "学期id") @RequestParam(required = false) String semesterId,
                                           @ApiParam(value = "考试id") @RequestParam(required = false) String examId,
                                           @ApiParam(value = "课程代码") @RequestParam(required = false) String courseCode,
                                           @ApiParam(value = "教师（工号/姓名）") @RequestParam(required = false) String teacher,
                                           @ApiParam(value = "学院") @RequestParam(required = false) String college,
                                           @ApiParam(value = "专业") @RequestParam(required = false) String major,
                                           @ApiParam(value = "教学班（模糊查询）") @RequestParam(required = false) String teachClazz,
                                           @ApiParam(value = "考生信息（姓名/学号）") @RequestParam(required = false) String examStudentInfo,
                                           @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) {
        if (semesterId == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择学期");
        }
        if (examId == null) {
            throw ExceptionResultEnum.ERROR.exception("请选择考试");
        }
        return ResultUtil.ok(basicExamStudentService.page(SystemConstant.convertIdToLong(semesterId),
                SystemConstant.convertIdToLong(examId), courseCode, teacher, college, major, teachClazz,
                examStudentInfo, pageNumber, pageSize));
    }

    @ApiOperation(value = "新增/编辑")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "更新成功", response = Result.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.SAVE)
    public Result saveBasicExamStudent(@Valid @RequestBody BasicExamStudentParam basicExamStudentParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(basicExamStudentService.save(basicExamStudentParam, sysUser));
    }

    @ApiOperation(value = "批量导入（同步）")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Result.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.IMPORT)
    public Result basicExamStudentImportSync(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file,
                                             @ApiParam(value = "考试id", required = true) @RequestParam String examId) throws Exception {
        Map<String, Object> map = printCommonService.saveTask(file, SystemConstant.convertIdToLong(examId), TaskTypeEnum.BASIC_EXAM_STUDENT_IMPORT);
        map.put("examId", SystemConstant.convertIdToLong(examId));
        return syncBasicExamStudentImportService.importTask(map);
    }

    @ApiOperation(value = "导出")
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Result.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.EXPORT)
    public void export(@ApiParam(value = "学期id") @RequestParam(required = false) String semesterId,
                       @ApiParam(value = "考试id") @RequestParam(required = false) String examId,
                       @ApiParam(value = "课程编号") @RequestParam(required = false) String courseCode,
                       @ApiParam(value = "教师（工号/姓名）") @RequestParam(required = false) String teacher,
                       @ApiParam(value = "学院") @RequestParam(required = false) String college,
                       @ApiParam(value = "专业") @RequestParam(required = false) String major,
                       @ApiParam(value = "教学班（模糊查询）") @RequestParam(required = false) String teachClazz,
                       @ApiParam(value = "考生信息（姓名/学号）") @RequestParam(required = false) String examStudentInfo, HttpServletResponse response) throws Exception {
        basicExamStudentService.exportLogic(response, SystemConstant.convertIdToLong(semesterId),
                SystemConstant.convertIdToLong(examId), courseCode, teacher, college, major, teachClazz,
                examStudentInfo);
    }

    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功", response = Result.class)})
    @OperationLogDetail(operationType = OperationTypeEnum.DELETE)
    public Result deleteBasicExamStudent(@ApiParam(value = "选择要删除的考生id集合", required = true) @RequestParam List<String> idList) {
        basicExamStudentService.deleteBatch(
                idList.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList()));
        return ResultUtil.ok();
    }
}