package com.qmth.teachcloud.report.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.teachcloud.common.contant.SpringContextHolder;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.AssignEnum;
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.*;
import com.qmth.teachcloud.report.business.bean.dto.excel.TAExamCourseExportDto;
import com.qmth.teachcloud.report.business.bean.result.*;
import com.qmth.teachcloud.report.business.bean.result.inspectCourseExamTotal.InspectCourseTotalReportResult;
import com.qmth.teachcloud.report.business.entity.TBExamCourse;
import com.qmth.teachcloud.report.business.entity.TBPaper;
import com.qmth.teachcloud.report.business.enums.OrderEnum;
import com.qmth.teachcloud.report.business.enums.PublishStatusEnum;
import com.qmth.teachcloud.report.business.service.*;
import com.qmth.teachcloud.report.business.templete.execute.AsyncDataCalculateTempleteService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Api(tags = "课程Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.reportCourse}")
public class CourseController {
    private final static Logger log = LoggerFactory.getLogger(CourseController.class);

    @Resource
    TAExamCourseService taExamCourseService;

    @Resource
    CourseReportService courseReportService;

    @Resource
    AnalyzeForReportService analyzeForReportService;

    @Resource
    TBTaskService tbTaskService;

    @Resource
    AsyncDataCalculateTempleteService asyncDataCalculateTempleteService;

    @Resource
    TBPaperService tbPaperService;

    @ApiOperation(value = "开课课程考试总览列表接口")
    @RequestMapping(value = "/survey_teacher/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = TAExamCourseResult.class)})
    public Result surveyTeacherList(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                    @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                                    @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId,
                                    @ApiParam(value = "分页页码", required = true) @RequestParam int pageNumber,
                                    @ApiParam(value = "分页数", required = true) @RequestParam int pageSize,
                                    @ApiParam(value = "排序列", required = false) @RequestParam(required = false) String column,
                                    @ApiParam(value = "排序规则", required = false) @RequestParam(required = false) OrderEnum order) {
        return ResultUtil.ok(taExamCourseService.surveyTeacherList(new Page<>(pageNumber, pageSize), SystemConstant.convertIdToLong(examId), SystemConstant.convertIdToLong(semesterId), Objects.isNull(schoolId) ? SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId())) : SystemConstant.convertIdToLong(schoolId), column, order));
    }

    @ApiOperation(value = "开课课程考试总览列表导出接口")
    @RequestMapping(value = "/survey_teacher/export", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = TAExamCourseResult.class)})
    public void export(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                       @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                       @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId,
                       @ApiParam(value = "排序列", required = false) @RequestParam(required = false) String column,
                       @ApiParam(value = "排序规则", required = false) @RequestParam(required = false) OrderEnum order) throws Exception {
        IPage<TAExamCourseResult> taExamCourseResultIPage = taExamCourseService.surveyTeacherList(new Page<>(SystemConstant.PAGE_NUMBER, SystemConstant.PAGE_SIZE), SystemConstant.convertIdToLong(examId), SystemConstant.convertIdToLong(semesterId), Objects.isNull(schoolId) ? SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId())) : SystemConstant.convertIdToLong(schoolId), column, order);
        Gson gson = new Gson();
        List<TAExamCourseExportDto> taExamCourseExportDtoList = gson.fromJson(JacksonUtil.parseJson(taExamCourseResultIPage.getRecords()), new TypeToken<List<TAExamCourseExportDto>>() {
        }.getType());
        ExcelUtil.excelExport("开课课程考试总览", TAExamCourseExportDto.class, taExamCourseExportDtoList, ServletUtil.getResponse());
    }

    @ApiOperation(value = "导出课程分析接口")
    @RequestMapping(value = "/survey_teacher/course_export", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = Result.class)})
    public void courseExport(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                             @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                             @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId,
                             @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode) throws Exception {
        taExamCourseService.courseExport(SystemConstant.convertIdToLong(examId), SystemConstant.convertIdToLong(semesterId), Objects.nonNull(schoolId) ? SystemConstant.convertIdToLong(schoolId) : null, courseCode);
    }

    @ApiOperation(value = "开课课程考试总览-教师各课堂成绩排名接口")
    @RequestMapping(value = "/survey_teacher/teacher_view", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = TAExamCourseCollegeTeacherResult.class)})
    public Result surveyTeacherTeacherView(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                           @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                                           @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId,
                                           @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
                                           @ApiParam(value = "分页页码", required = true) @RequestParam int pageNumber,
                                           @ApiParam(value = "分页数", required = true) @RequestParam int pageSize,
                                           @ApiParam(value = "排序列", required = false) @RequestParam(required = false) String column,
                                           @ApiParam(value = "排序规则", required = false) @RequestParam(required = false) OrderEnum order) {
        return ResultUtil.ok(taExamCourseService.surveyTeacherTeacherView(new Page<>(pageNumber, pageSize), Objects.isNull(schoolId) ? SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId())) : SystemConstant.convertIdToLong(schoolId), SystemConstant.convertIdToLong(semesterId), SystemConstant.convertIdToLong(examId), courseCode, column, order));
    }

    @ApiOperation(value = "开课课程考试总览-试题难度得分情况分析接口")
    @RequestMapping(value = "/survey_teacher/question_view", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = DimensionAnalyzeResult.class)})
    public Result surveyTeacherQuestionView(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                            @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                                            @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId,
                                            @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
                                            @ApiParam(value = "考查学院id", required = false) @RequestParam(required = false) String collegeId,
                                            @ApiParam(value = "任课老师id", required = false) @RequestParam(required = false) String teacherId) {
        return ResultUtil.ok(taExamCourseService.surveyTeacherQuestionView(Objects.isNull(schoolId) ? SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId())) : SystemConstant.convertIdToLong(schoolId), SystemConstant.convertIdToLong(semesterId), SystemConstant.convertIdToLong(examId), courseCode, Objects.nonNull(collegeId) ? SystemConstant.convertIdToLong(collegeId) : null, Objects.nonNull(teacherId) ? SystemConstant.convertIdToLong(teacherId) : null));
    }

    @ApiOperation(value = "开课课程考试总览-各难度水平题目上的作答分析接口")
    @RequestMapping(value = "/survey_teacher/question_answer_view", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = TAExamCourseResult.class)})
    public Result surveyTeacherQuestionAnswerView(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                                  @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                                                  @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId,
                                                  @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
                                                  @ApiParam(value = "考查学院id", required = false) @RequestParam(required = false) String collegeId,
                                                  @ApiParam(value = "任课老师id", required = false) @RequestParam(required = false) String teacherId) {
        return ResultUtil.ok(taExamCourseService.surveyTeacherQuestionAnswerView(Objects.isNull(schoolId) ? SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId())) : SystemConstant.convertIdToLong(schoolId), SystemConstant.convertIdToLong(semesterId), SystemConstant.convertIdToLong(examId), courseCode, Objects.nonNull(collegeId) ? SystemConstant.convertIdToLong(collegeId) : null, Objects.nonNull(teacherId) ? SystemConstant.convertIdToLong(teacherId) : null));
    }

    @ApiOperation(value = "开课课程考试总览图表接口")
    @RequestMapping(value = "/survey_teacher/view", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = SurveyTeacherViewResult.class)})
    public Result surveyTeacherView(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                    @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                                    @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId,
                                    @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        if (Objects.isNull(sysUser)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        return ResultUtil.ok(taExamCourseService.surveyTeacherView(Objects.isNull(schoolId) ? SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId())) : SystemConstant.convertIdToLong(schoolId), SystemConstant.convertIdToLong(semesterId), SystemConstant.convertIdToLong(examId), courseCode, sysUser.getOrgId()));
    }

    @ApiOperation(value = "考查课程考试总览-公共课概况接口")
    @RequestMapping(value = "/survey_inspect/view", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = InspectCourseTotalReportResult.class)})
    public Result surveyInspectView(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                    @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                                    @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId) {
        Object obj = ServletUtil.getRequestHeaderSchoolId();
        Long tmp = SystemConstant.convertIdToLong(String.valueOf(obj));
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        if (Objects.isNull(sysUser)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        Long collegeId = sysUser.getOrgId();
        if (Objects.isNull(collegeId)) {
            throw ExceptionResultEnum.ERROR.exception("学院id不存在");
        }
        return ResultUtil.ok(courseReportService.findInfoInspectCourseExamTotal(Objects.isNull(schoolId) ? tmp : SystemConstant.convertIdToLong(schoolId), SystemConstant.convertIdToLong(semesterId), SystemConstant.convertIdToLong(examId), collegeId));
    }

    @ApiOperation(value = "考查课程考试分析接口")
    @RequestMapping(value = "/survey_inspect_analyse/view", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = CollegeAndCourseResult.class)})
    public Result surveyInspectAnalyseView(@ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                           @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                                           @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
                                           @ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        if (Objects.isNull(sysUser)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        return ResultUtil.ok(taExamCourseService.surveyInspectAnalyseView(Objects.isNull(schoolId) ? SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId())) : SystemConstant.convertIdToLong(schoolId), SystemConstant.convertIdToLong(semesterId), SystemConstant.convertIdToLong(examId), courseCode, sysUser.getOrgId()));
    }

    @ApiOperation(value = "赋分管理列表接口")
    @RequestMapping(value = "/survey_aspoints/list", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "考试科目信息", response = TAExamCourseResult.class)})
    public Result surveyAspointsList(@ApiParam(value = "学校id", required = false) @RequestParam(required = false) String schoolId,
                                     @ApiParam(value = "学期id", required = true) @RequestParam String semesterId,
                                     @ApiParam(value = "考试id", required = true) @RequestParam String examId,
                                     @ApiParam(value = "科目编码", required = false) @RequestParam(required = false) String courseCode,
                                     @ApiParam(value = "发布状态", required = false) @RequestParam(required = false) PublishStatusEnum publishStatus,
                                     @ApiParam(value = "分页页码", required = true) @RequestParam int pageNumber,
                                     @ApiParam(value = "分页数", required = true) @RequestParam int pageSize,
                                     @ApiParam(value = "排序列", required = false) @RequestParam(required = false) String column,
                                     @ApiParam(value = "排序规则", required = false) @RequestParam(required = false) OrderEnum order) {
        return ResultUtil.ok(taExamCourseService.surveyAspointsList(new Page<>(pageNumber, pageSize), Objects.isNull(schoolId) ? SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId())) : SystemConstant.convertIdToLong(schoolId), SystemConstant.convertIdToLong(examId), courseCode, publishStatus, SystemConstant.convertIdToLong(semesterId), column, order));
    }

    @ApiOperation(value = "赋分试算接口")
    @RequestMapping(value = "/survey_aspoints/calculation", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "赋分试算接口", response = TrialCalculationResult.class)})
    public Result surveyAspointsCalculation(
            @ApiParam(value = "考试id", required = true) @RequestParam String examId,
            @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
            @ApiParam(value = "赋分系数", required = true) @RequestParam String coefficient) {
        return ResultUtil.ok(taExamCourseService.trialCalculate(SystemConstant.convertIdToLong(examId), courseCode, coefficient));
    }

    @ApiOperation(value = "赋分管理-发布&撤回接口")
    @RequestMapping(value = "/survey_aspoints/publish", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "赋分管理-发布&撤回接口", response = Result.class)})
    public Result surveyAspointsCalculation(
            @ApiParam(value = "考试id", required = true) @RequestParam String examId,
            @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
            @ApiParam(value = "发布状态", required = true) @RequestParam PublishStatusEnum publishStatus) {

        analyzeForReportService.publishReport(SystemConstant.convertIdToLong(examId), courseCode, publishStatus);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "赋分管理-保存")
    @RequestMapping(value = "/survey_aspoints/save", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "赋分管理-保存", response = Result.class)})
    public Result surveyAspointsSave(
            @ApiParam(value = "考试id", required = true) @RequestParam String examId,
            @ApiParam(value = "科目编码", required = true) @RequestParam String courseCode,
            @ApiParam(value = "赋分系数", required = true) @RequestParam String coefficient) {
        List<TBPaper> tbPaperList = tbPaperService.list(new QueryWrapper<TBPaper>().lambda()
                .eq(TBPaper::getExamId, examId)
                .eq(TBPaper::getCourseCode, courseCode));
        if (tbPaperList.size() != 1) {
            log.error("未找到考试id为 ：" + examId + " 课程编号为 ： " + courseCode + "的试卷结构");
            throw ExceptionResultEnum.ERROR.exception("未找到试卷结构");
        }

        // 赋分系数不为#且试卷结构不为特殊赋分的科目才执行赋分操作
        if (!coefficient.equals(SystemConstant.DEFAULT_SIGN) && !AssignEnum.SPECIAL_ASSIGN_SCORE.equals(tbPaperList.get(0).getScoreType())) {
            Map<String, Object> map = tbTaskService.saveTask(TaskTypeEnum.DATA_CALCULATE);
            map.put("examId", examId);
            map.put("courseCode", courseCode);
            map.put("coefficient", coefficient);
            TBExamCourseService tbExamCourseService = SpringContextHolder.getBean(TBExamCourseService.class);
            TBExamCourse tbExamCourse = tbExamCourseService.getOne(new QueryWrapper<TBExamCourse>().lambda()
                    .eq(TBExamCourse::getExamId, examId)
                    .eq(TBExamCourse::getCourseCode, courseCode));

            analyzeForReportService.realityForCalculate(SystemConstant.convertIdToLong(examId), courseCode);
            map.put("tbExamCourse", tbExamCourse);
            asyncDataCalculateTempleteService.calculateTask(map);
        }
        return ResultUtil.ok();
    }

}
