package com.qmth.distributed.print.api.mark;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.distributed.print.business.entity.ExamTaskDetail;
import com.qmth.distributed.print.business.service.ExamTaskDetailService;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.distributed.print.business.templete.execute.SyncObjectiveStructImportService;
import com.qmth.distributed.print.business.templete.execute.SyncSubjectiveStructImportService;
import com.qmth.teachcloud.common.annotation.OperationLogDetail;
import com.qmth.teachcloud.common.bean.dto.mark.MarkSettingDto;
import com.qmth.teachcloud.common.bean.vo.PaperInfoVo;
import com.qmth.teachcloud.common.contant.SystemConstant;
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.ExamTaskUtil;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.mark.dto.mark.manage.MarkManageDto;
import com.qmth.teachcloud.mark.dto.mark.score.CheckScoreListDto;
import com.qmth.teachcloud.mark.entity.MarkPaper;
import com.qmth.teachcloud.mark.service.MarkPaperService;
import com.qmth.teachcloud.mark.service.MarkTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * <p>
 * 小题信息表 前端控制器
 * </p>
 *
 * @author xf
 * @since 2023-09-22
 */
@Api(tags = "评卷-试卷结构")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_MARK + "/setting")
public class MarkSettingController {

    @Resource
    private MarkPaperService markPaperService;
    @Resource
    private MarkTaskService markTaskService;
    @Resource
    private ExamTaskDetailService examTaskDetailService;
    @Resource
    private PrintCommonService printCommonService;
    @Resource
    private SyncObjectiveStructImportService syncObjectiveStructImportService;
    @Resource
    private SyncSubjectiveStructImportService syncSubjectiveStructImportService;

    /**
     * 评卷设置数据列表
     */
    @ApiOperation(value = "评卷设置数据列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result list(@ApiParam(value = "学期ID") @RequestParam(required = false) Long semesterId,
                       @ApiParam(value = "考试ID") @RequestParam(required = false) Long examId,
                       @ApiParam(value = "课程代码") @RequestParam(required = false) String courseCode,
                       @ApiParam(value = "试卷编号") @RequestParam(required = false) String paperNumber,
                       @ApiParam(value = "提交状态") @RequestParam(required = false) Boolean groupStatus,
                       @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<MarkSettingDto> markSettingDtoIPage = markPaperService.listPaperSetting(examId, courseCode, paperNumber,
                groupStatus, pageNumber, pageSize);
        for (MarkSettingDto record : markSettingDtoIPage.getRecords()) {
            ExamTaskDetail examTaskDetail = examTaskDetailService.findByExamIdAndCourseCodeAndPaperNumber(record.getExamId(), record.getCourseCode(), record.getPaperNumber());
            if (examTaskDetail != null) {
                List<PaperInfoVo> paperInfoVos = ExamTaskUtil.parsePaperAttachmentPath(examTaskDetail.getPaperAttachmentIds(), record.getPaperType());
                if (CollectionUtils.isNotEmpty(paperInfoVos)) {
                    record.setCardId(Long.valueOf(paperInfoVos.get(0).getCardId()));
                }
            }
        }
        return ResultUtil.ok(markSettingDtoIPage);
    }

    /**
     * 评卷设置数据获取
     */
    @ApiOperation(value = "评卷设置数据获取")
    @RequestMapping(value = "/paper/get", method = RequestMethod.POST)
    public Result paperGet(@ApiParam(value = "考试ID", required = true) @RequestParam Long examId, @ApiParam(value = "试卷编号", required = true) @RequestParam String paperNumber) {
        return ResultUtil.ok(markPaperService.getByExamIdAndPaperNumber(examId, paperNumber));
    }

    /**
     * 评判设置数据保存
     */
    @ApiOperation(value = "评卷设置数据保存")
    @RequestMapping(value = "/paper/save", method = RequestMethod.POST)
    @OperationLogDetail(operationType = OperationTypeEnum.SAVE)
    public Result paperSave(@RequestBody MarkPaper markPaper) {
        markPaperService.savePaperSetting(markPaper);
        return ResultUtil.ok(true);
    }

    /**
     * 评卷管理数据列表
     */
    @ApiOperation(value = "评卷管理数据列表")
    @RequestMapping(value = "/summary", method = RequestMethod.POST)
    public Result summary(@ApiParam(value = "学期ID") @RequestParam(required = false) Long semesterId,
                          @ApiParam(value = "考试ID") @RequestParam(required = false) Long examId,
                          @ApiParam(value = "课程代码") @RequestParam(required = false) String courseCode,
                          @ApiParam(value = "试卷编号") @RequestParam(required = false) String paperNumber,
                          @ApiParam(value = "完成进度") @RequestParam(required = false) Boolean progressStatus,
                          @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<MarkManageDto> markManageDtoIPage = markTaskService.listPaperManage(examId, courseCode, paperNumber,
                progressStatus, pageNumber, pageSize);
        return ResultUtil.ok(markManageDtoIPage);
    }

    /**
     * 导出评卷员工作量
     */
    @ApiOperation(value = "导出评卷员工作量")
    @RequestMapping(value = "/export_marker", method = RequestMethod.POST)
    public void exportMarker(@ApiParam(value = "学期ID") @RequestParam(required = false) Long semesterId,
                             @ApiParam(value = "考试ID") @RequestParam(required = false) Long examId,
                             @ApiParam(value = "课程代码") @RequestParam(required = false) String courseCode,
                             @ApiParam(value = "试卷编号") @RequestParam(required = false) String paperNumber,
                             HttpServletResponse response) {
        if (semesterId == null) {
            throw ExceptionResultEnum.SEMESTER_ID_IS_NULL.exception();
        }
        if (examId == null) {
            throw ExceptionResultEnum.EXAM_ID_IS_NULL.exception();
        }
        markTaskService.exportMarker(examId, courseCode, paperNumber, response);
    }

    /**
     * 成绩检查数据列表
     */
    @ApiOperation(value = "成绩检查数据列表")
    @RequestMapping(value = "/scoreList", method = RequestMethod.POST)
    public Result scoreList(@ApiParam(value = "学期ID") @RequestParam(required = false) Long semesterId,
                            @ApiParam(value = "考试ID") @RequestParam(required = false) Long examId,
                            @ApiParam(value = "课程代码") @RequestParam(required = false) String courseCode,
                            @ApiParam(value = "试卷编号") @RequestParam(required = false) String paperNumber,
                            @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<CheckScoreListDto> scoreListDtoIPage = markPaperService.listStudentScoreList(examId, courseCode,
                paperNumber, pageNumber, pageSize);
        return ResultUtil.ok(scoreListDtoIPage);
    }

    @ApiOperation(value = "客观题导入")
    @RequestMapping(value = "/objective_struct/import", method = RequestMethod.POST)
    public Result objectiveStructImport(@ApiParam(value = "考试ID", required = true) @RequestParam String examId,
                                        @ApiParam(value = "标答excel文件", required = true) @RequestParam MultipartFile file) throws Exception {
        Map<String, Object> map = printCommonService.saveTask(file, SystemConstant.convertIdToLong(examId), TaskTypeEnum.OBJECTIVE_STRUCT_IMPORT);
        map.put("examId", SystemConstant.convertIdToLong(examId));
        return syncObjectiveStructImportService.importTask(map);
    }

    @ApiOperation(value = "主观题导入")
    @RequestMapping(value = "/subjective_struct/import", method = RequestMethod.POST)
    public Result subjectiveStructImport(@ApiParam(value = "考试ID", required = true) @RequestParam String examId,
                                         @ApiParam(value = "标答excel文件", required = true) @RequestParam MultipartFile file) throws Exception {
        Map<String, Object> map = printCommonService.saveTask(file, SystemConstant.convertIdToLong(examId), TaskTypeEnum.SUBJECTIVE_STRUCT_IMPORT);
        map.put("examId", SystemConstant.convertIdToLong(examId));
        return syncSubjectiveStructImportService.importTask(map);
    }
}
