package com.yida.data.school.exam.controller;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.exam.*;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.Asserts;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.school.exam.mapper.CoreExaminationCourseMapper;
import com.yida.data.school.exam.mapper.CoreExaminationMapper;
import com.yida.data.school.exam.mapper.CoreExaminationStudentCourseMapper;
import com.yida.data.school.exam.mapper.CoreExaminationStudentMapper;
import com.yida.data.school.exam.service.CoreExaminationCourseService;
import com.yida.data.school.exam.service.CoreExaminationPublishService;
import com.yida.data.school.exam.service.CoreExaminationStudentCourseService;
import com.yida.data.school.exam.service.CoreExaminationStudentService;
import com.yida.data.school.exam.util.CoreRankExportTemplate;
import com.yida.data.school.vo.exam.ClassVO;
import com.yida.data.school.vo.exam.ImportScoreVO;
import com.yida.data.system.feign.RemoteDeptService;
import com.yida.data.user.feign.RemoteStudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Api(tags = "成绩-后台-排行榜")
@RequiredArgsConstructor
@RestController
@RequestMapping("/exam/rank")
public class CoreRankController{
    private final CoreExaminationStudentService coreExaminationStudentService;
    private final CoreExaminationPublishService coreExaminationPublishService;
    private final CoreExaminationStudentCourseService coreExaminationStudentCourseService;
    private final CoreExaminationCourseService coreExaminationCourseService;
    private final CoreExaminationMapper coreExaminationMapper;
    private final CoreExaminationStudentMapper coreExaminationStudentMapper;
    private final CoreExaminationCourseMapper coreExaminationCourseMapper;
    private final CoreExaminationStudentCourseMapper coreExaminationStudentCourseMapper;


    private final RemoteDeptService remoteDeptService;
    private final RemoteStudentService remoteStudentService;
    private final RedisService redisService;
    private final CoreRankExportTemplate coreRankExportTemplate;

    @ApiOperation("查询本次考试的排行榜数据列表")
    @GetMapping("/findRankPageList")
    public ResultBean<IPage<CoreExaminationStudent>> findRankPageList(@ApiParam("考试id") Long coreExaminationId,
                                                                      @ApiParam("学生姓名") String studentName,
                                                                      @ApiParam("班级id") Long classId,
                                                                      @ApiParam("当前页码") @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                                      @ApiParam("页面大小") @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        //查询分页数据
        return ResultBean.buildSuccess(coreExaminationStudentService.findRankPageList(pageNum,pageSize,coreExaminationId, studentName, classId));
    }

    @ApiOperation("查询该场考试得班级")
    @GetMapping("/listClassByExam")
    public ResultBean<List<ClassVO>> listClassByExam(@ApiParam("考试id") Long examId) {
        return ResultBean.buildSuccess(coreExaminationStudentMapper.findClassByExam(examId));
    }

    @ApiOperation("发布考试成绩")
    @PostMapping("/publishExamination")
    public ResultBean publishExamination(@RequestBody CoreExaminationPublish coreExaminationPublish) {

        //获得登录用户的信息
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        String score_parent = "score_parent";
        Long coreExaminationId = coreExaminationPublish.getCoreExaminationId();
        CoreExamination coreExamination = coreExaminationMapper.selectById(coreExaminationId);
        Asserts.isFalse(coreExamination.getEndDate().isAfter(LocalDate.now()), "考试还未结束，暂不能发布");
        //发布考试成绩
        coreExaminationPublishService.publishExamination(coreExaminationPublish, currentUser);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("保存考生信息和成绩")
    @PostMapping("/saveExamResults")
    public ResultBean saveExamResults(@RequestBody CoreExaminationStudent coreExaminationStudent) {
        // 根据主键id匹配学生
        Long schoolId = coreExaminationStudent.getSchoolId();
        EduStudent student =
                remoteStudentService.getStudentByStuNumAndSchool(coreExaminationStudent.getStudentNumber(),
                        schoolId).getData();
        Asserts.isNotNull(student, "学生不存在");
        Asserts.isTrue(coreExaminationStudentService.count(Wrappers.lambdaQuery(new CoreExaminationStudent())
                .eq(CoreExaminationStudent::getCoreExaminationId, coreExaminationStudent.getCoreExaminationId())
                .eq(CoreExaminationStudent::getCoreStudentId, student.getId())) == 0, "该学生已录入成绩！");
        CoreExaminationStudent coreExaminationStudent2 = coreExaminationStudentMapper.selectOne(Wrappers.lambdaQuery(new CoreExaminationStudent())
                .eq(CoreExaminationStudent::getExaminationNumber, coreExaminationStudent.getExaminationNumber())
                .eq(CoreExaminationStudent::getCoreExaminationId, coreExaminationStudent.getCoreExaminationId()));
        if (ObjectUtil.isNotEmpty(coreExaminationStudent2)) {
            return ResultBean.buildError("学生考号已经存在，请重新输入");
        }
        coreExaminationStudent.setCoreStudentId(student.getId());
        coreExaminationStudent.setClassId(student.getClassId());
        coreExaminationStudent.setClassName(student.getClassName());
        coreExaminationStudent.setGradeId(student.getGradeId());
        coreExaminationStudent.setGradeName(student.getGradeName());
        coreExaminationStudentService.saveExamResults(coreExaminationStudent, FebsUtil.getCurrentUser());
        return ResultBean.buildSuccess();
    }


    @ApiOperation("根据考场和考生信息查询考生的考试信息（考生信息和成绩）")
    @GetMapping("/findCoreExaminationStudentDetail")
    public ResultBean findCoreExaminationStudentDetail(@ApiParam("考试id") Long coreExaminationId,
                                                       @ApiParam("考生信息id") Long coreExaminationStudentId,
                                                       @ApiParam("班级id") Long classId,
                                                       @ApiParam("姓名") String name) {
        CoreExaminationStudent coreExaminationStudentDetail;

        coreExaminationStudentDetail =
                coreExaminationStudentService.findCoreExaminationStudentDetail(coreExaminationId,
                        coreExaminationStudentId, classId, name);

        return ResultBean.buildSuccess(coreExaminationStudentDetail);
    }

    @PostMapping("/editExamResultsDetail")
    public ResultBean editExamResultsDetail(@RequestBody CoreExaminationStudent
                                                    coreExaminationStudent) {
        // 获得登录用户的信息
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        List<CoreExaminationCourse> coreExaminationCourseList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(coreExaminationStudent.getStudentCourseList())) {
            for (CoreExaminationStudentCourse coreExaminationStudentCourse : coreExaminationStudent.getStudentCourseList()) {
                if (Objects.nonNull(coreExaminationStudentCourse.getScore())) {
                    CoreExaminationCourse coreExaminationCourse = coreExaminationCourseService.getOne(Wrappers.lambdaQuery(new CoreExaminationCourse())
                            .eq(CoreExaminationCourse::getCoreCourseName, coreExaminationStudentCourse.getCoreExaminationCourseName())
                            .eq(CoreExaminationCourse::getCoreExaminationId,
                                    coreExaminationStudent.getCoreExaminationId()));
                    if (coreExaminationStudentCourse.getScore() > coreExaminationCourse.getCoreCourseScore()) {
                        coreExaminationCourseList.add(coreExaminationCourse);
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(coreExaminationCourseList)) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("以下科目输入分数大于考试分数：");
            for (CoreExaminationCourse coreExaminationCourse : coreExaminationCourseList) {

                stringBuilder.append("科目：");
                stringBuilder.append(coreExaminationCourse.getCoreCourseName());
                stringBuilder.append(", 考试分数为:");
                stringBuilder.append(coreExaminationCourse.getCoreCourseScore());
                stringBuilder.append("。");
            }
            return ResultBean.buildError(stringBuilder.toString());
        }
        coreExaminationStudentService.editExamResultsDetail(coreExaminationStudent, currentUser);
        return ResultBean.buildSuccess("成绩补录成功");
    }

    @ApiOperation("生成excel导入模板")
    @PostMapping("/exportTemplate")
    public void exportTemplate(@RequestParam Integer examinationId, @RequestParam Integer
            gradeId, HttpServletResponse response, HttpServletRequest request) {
        coreRankExportTemplate.exportTemplate(coreExaminationCourseService, request, response, examinationId, gradeId,
                remoteDeptService);
        System.out.println("导出模板下载成功");
    }

    @ApiOperation("导入学生成绩")
    @PostMapping("importExcelDetail")
    public ResultBean importExcelDetail(@RequestPart(value = "file") MultipartFile file, Long coreExaminationId, Long gradeId, Long schoolId) {
        CurrentUser userInfo = FebsUtil.getCurrentUser();
        Object o = redisService.hget(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA,
                coreExaminationId.toString());
        if (o != null && ((ImportScoreVO) o).getFinish() == 0) {
            throw new FebsException("该考试正在上传学生，请稍后");
        }
        coreRankExportTemplate.importExcelDetail(userInfo,
                FileUtil.uploadMultipartFile(file),
                schoolId,
                coreExaminationId, gradeId, coreExaminationStudentMapper, coreExaminationMapper,
                coreExaminationStudentCourseService,
                coreExaminationStudentCourseMapper, coreExaminationCourseMapper);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询上传信息")
    @GetMapping("/getImportPercent")
    public ResultBean<Object> getUploadError(Long examId) {
        return ResultBean.buildSuccess(redisService.hget(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, examId.toString()));
    }

    @ApiOperation("取消发布")
    @GetMapping("/delTeacherBatch")
    public ResultBean delTeacherBatch(@ApiParam("考试id") Long examinationId) {
        // 获得登录用户的信息
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        Integer num = coreExaminationStudentService.delTeacherBatch(examinationId, currentUser);
        if (num == 0) {
            return ResultBean.buildError("成绩取消发布失败");
        }
        return ResultBean.buildSuccess();
    }

    @ApiOperation("批量删除考生信息")
    @PostMapping("/delRankBatchIds")
    public ResultBean delTeacherBatchIds(@RequestBody List<Long> rankIds) {

        //批量删除成绩信息
        coreExaminationStudentService.delRankBatchIds(rankIds);
        return ResultBean.buildSuccess();
    }
}
