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

import static org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND;
import static org.apache.poi.ss.usermodel.IndexedColors.PALE_BLUE;

import cc.mrbird.febs.common.redis.service.RedisService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.CoreExamination;
import com.yida.data.common.core.entity.exam.CoreExaminationCourse;
import com.yida.data.common.core.entity.exam.CoreExaminationStudent;
import com.yida.data.common.core.entity.exam.CoreExaminationStudentCourse;
import com.yida.data.common.core.entity.user.EduStudent;
import com.yida.data.common.core.entity.user.EduUserDept;
import com.yida.data.common.core.utils.ExcelUtil;
import com.yida.data.common.service.CommonService;
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.CoreExaminationStudentCourseService;
import com.yida.data.school.vo.exam.ImportScoreVO;
import com.yida.data.system.feign.RemoteDeptService;
import com.yida.data.user.feign.RemoteStudentService;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


/**
 * @ClassName CoreRankExportTemplate
 * @Description TODO
 * @Author wenshijia
 * @Date 2020/6/30 18:19
 * @Version 1.0
 */
@Component
@Slf4j
public class CoreRankExportTemplate {

    @Resource
    private RedisService redisService;
    @Resource
    private RemoteStudentService remoteStudentService;
    @Resource
    private CommonService commonService;

    public static Object cellType(CellType cellType, Cell cell) {
        switch (cellType) {
            case BOOLEAN:
                break;
            case NUMERIC:
                return Integer.valueOf((int) cell.getNumericCellValue());
            case STRING:
                return cell.getStringCellValue();
            case BLANK:
                break;
            case ERROR:
                break;
            case FORMULA:
                break;
            default:
        }
        return "";
    }

    public static Integer objectToInteger(Object o) {
        if (o == null) {
            return null;
        }
        if ("java.lang.String".equals(o.getClass().getName())) {
            return Integer.valueOf((String) o);
        } else if ("java.lang.Integer".equals(o.getClass().getName())) {
            return (int) o;
        }
        return null;
    }

    /**
     * @return void 导出模板
     * @Author WSJ
     * @Date 18:26 2020/6/30
     * @Param [coreExaminationCourseRepository, request, response, examinationId]
     **/
    public void exportTemplate(CoreExaminationCourseService coreExaminationCourseService,
        HttpServletRequest request, HttpServletResponse response, Integer examinationId, Integer gradeId,
        RemoteDeptService remoteDeptService) {

        String[] strings = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z"};

        List<CoreExaminationCourse> list = coreExaminationCourseService.list(Wrappers.lambdaQuery(new CoreExaminationCourse())
            .eq(CoreExaminationCourse::getCoreExaminationId, examinationId));
        List<String> stringList = new ArrayList<>(25);
        stringList.add("姓名");
        stringList.add("学号");
        stringList.add("考号");
        stringList.add("班级");
        for (CoreExaminationCourse coreExaminationCourse : list) {
            stringList.add(coreExaminationCourse.getCoreCourseName());
        }

        List<Object> rowList = new ArrayList<>(stringList.size());
        rowList.add("张英");
        rowList.add("123455678");
        rowList.add("120");
        rowList.add("1班");
        for (CoreExaminationCourse coreExaminationCourse : list) {
            rowList.add(90);
        }

        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfWorkbook.createSheet();
        hssfWorkbook.setSheetName(0, "成绩导入模板");
        //设置列宽度大小
        sheet.setDefaultColumnWidth((short) 20);
        //第二步， 生成表格第一行的样式和字体
        HSSFCellStyle style = hssfWorkbook.createCellStyle();
        //设置水平对齐的样式为居中对齐;

        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置这些样式
        style.setFillForegroundColor(PALE_BLUE.index);
        style.setFillPattern(SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成一个字体
        HSSFFont font = hssfWorkbook.createFont();
        font.setColor(IndexedColors.BLACK.index);
        //设置字体所在的行高度
        font.setFontHeightInPoints((short) 20);
        font.setBold(true);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 指定当单元格内容显示不下时自动换行
        style.setWrapText(true);
        // 产生表格标题行

        EduUserDept infoById = commonService.getUserDept(gradeId.longValue());
        HSSFRow xssfRow = sheet.createRow(0);
        xssfRow.setHeightInPoints(60);
        HSSFCell xssfCell = xssfRow.createCell(0);
        xssfCell.setCellStyle(style);
        xssfCell.setCellValue("当前考试年级为" + infoById.getDeptName());
        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$" + strings[rowList.size() - 1] + "$1"));

        HSSFRow row = sheet.createRow(1);
        for (int i = 0; i < stringList.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellStyle(style);
            XSSFRichTextString text = new XSSFRichTextString(stringList.get(i));
            cell.setCellValue(text.toString());
        }

        HSSFRow row1 = sheet.createRow(2);
        for (int i = 0; i < rowList.size(); i++) {
            HSSFCell cell = row1.createCell((short) i);
            Object o = rowList.get(i);
            cell.setCellValue(String.valueOf(o));
        }
        // 设置response头信息
        try {
            //从请求头中获取User-Agent判断当前使用的是否是火狐浏览器
            String agent = request.getHeader("User-Agent");
            //根据不同浏览器进行不同的编码
            String excelName = "成绩导入模板" + DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now()) + ".xls";
            String realFilename = "";
            if (agent.contains("MSIE")) {
                // IE浏览器
                realFilename = URLEncoder.encode(excelName, "utf-8");
            } else if (agent.contains("Firefox")) {
                // 火狐浏览器，此处使用java8
                realFilename = Base64.getEncoder().encodeToString(excelName.getBytes("utf-8"));
            } else {
                // 其它浏览器
                realFilename = URLEncoder.encode(excelName, "utf-8");
            }
            ServletOutputStream outputStream = response.getOutputStream();
            response.reset();
            // 改成输出excel文件
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment; filename=" + realFilename);

            hssfWorkbook.write(outputStream);

            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Async
    @Transactional
    public void importExcelDetail(CurrentUser userInfo, String path,
        Long schoolId,
        Long coreExaminationId,
        Long gradeId, CoreExaminationStudentMapper
        coreExaminationStudentMapper,
        CoreExaminationMapper coreExaminationMapper,
        CoreExaminationStudentCourseService coreExaminationStudentCourseService,
        CoreExaminationStudentCourseMapper coreExaminationStudentCourseMapper, CoreExaminationCourseMapper
        coreExaminationCourseMapper) {
        // 错误信息
        List<String> error = new ArrayList<>();
        // 上传信息
        ImportScoreVO vo = new ImportScoreVO();
        vo.setPercent(0);
        vo.setFinish(0);
        vo.setStartTime(LocalDateTime.now());
        vo.setErrorMsg(error);
        Integer total = 0;
        Integer finish = 0;
        Integer percent = 0;
        // 标识正在上传
        redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
        try {
            File saveFile = new File(path);
            CoreExamination coreExamination = coreExaminationMapper.selectById(coreExaminationId);
            List<CoreExaminationStudent> coreExaminationStudentList = new ArrayList<>();
            Map<Long, Integer> repeatStudent = new HashMap<>();
            //  获取到workbook对象
            Workbook workbook = WorkbookFactory.create(saveFile);
            // 获取到sheet对象
            Sheet sheet = workbook.getSheetAt(0);
            int firstRowNum = sheet.getFirstRowNum();
            // 获取到最后一行的行数
            int lastRowNum = sheet.getLastRowNum();
            // 进度总数
            total = (lastRowNum - 2) * 2;
            // 遍历所有的行封装数据
            for (int i = 2; i <= lastRowNum; i++) {
                finish++;
                // 进度改变进行保存
                if (finish * 100 / total != percent) {
                    percent = finish * 100 / total;
                    vo.setPercent(percent);
                    redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                }
                // 考生信息对象
                CoreExaminationStudent coreExaminationStudent = new CoreExaminationStudent();
                Row row = sheet.getRow(i);
                // 当前行的最后一列
                int firstCellNum = row.getFirstCellNum();
                int lastCellNum = row.getLastCellNum();
                // 将当前行数据封装到考生信息对象
                coreExaminationStudent.setStudentName(ExcelUtil.getCellValue(row.getCell(0)));
                coreExaminationStudent.setStudentNumber(ExcelUtil.getCellValue(row.getCell(1)));
                coreExaminationStudent.setExaminationNumber(ExcelUtil.getCellValue(row.getCell(2)));
                coreExaminationStudent.setClassName(ExcelUtil.getCellValue(row.getCell(3)));
                if (StrUtil.isBlank(coreExaminationStudent.getStudentName())) {
                    break;
                }
                if (StrUtil.isBlank(coreExaminationStudent.getClassName())) {
                    error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "班级为空");
                    redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                    continue;
                }
                List<CoreExaminationStudentCourse> list = new ArrayList<>(lastCellNum - 3);
                // 校验学生信息是否存在

                // 根据年级，班级去查询班级id
                EduStudent eduStudent = remoteStudentService.getStudentByStuNumAndSchool(
                    coreExaminationStudent.getStudentNumber(), schoolId).getData();
                if (Objects.isNull(eduStudent)) {
                    // 学号不存在班级不为空才根据班级查询
                    if (StrUtil.isBlank(coreExaminationStudent.getStudentNumber()) && StrUtil.isNotBlank(
                        coreExaminationStudent.getClassName())) {
                        List<EduStudent> students =
                            remoteStudentService.listStudentByGradeAndClass(coreExaminationStudent.getStudentName(),
                                coreExaminationStudent.getClassName(), coreExamination.getGradeId()).getData();
                        if (CollUtil.isNotEmpty(students)) {
                            if (students.size() > 1) {
                                error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "考生信息存在重复");
                                redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                                continue;
                            } else {
                                eduStudent = students.get(0);
                            }
                        } else {
                            error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "考生信息不存在");
                            redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                            continue;
                        }
                    } else {
                        error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "考生信息不存在");
                        redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                        continue;
                    }
                } else {
                    // 年级不匹配
                    if (!eduStudent.getGradeId().equals(coreExamination.getGradeId())) {
                        error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "考生不属于考试年级");
                        redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                        continue;
                    }
                    // 班级或姓名不匹配
                    if (!eduStudent.getClassName().equals(coreExaminationStudent.getClassName())) {
                        error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "考生班级错误");
                        redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                        continue;
                    }
                    // 班级或姓名不匹配
                    if (!eduStudent.getStuName().equals(coreExaminationStudent.getStudentName())) {
                        error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "考生姓名错误");
                        redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                        continue;
                    }
                }
                coreExaminationStudent.setCoreStudentId(eduStudent.getId());
                if (repeatStudent.containsKey(coreExaminationStudent.getCoreStudentId())) {
                    error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "考生与第" + repeatStudent.get(
                        coreExaminationStudent.getCoreStudentId()) + "行重复");
                    redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                    continue;
                }
                if (coreExaminationStudentMapper.selectCount(Wrappers.lambdaQuery(new CoreExaminationStudent())
                    .eq(CoreExaminationStudent::getCoreStudentId, eduStudent.getId())
                    .eq(CoreExaminationStudent::getCoreExaminationId, coreExaminationId)) > 0) {
                    error.add("第" + (i + 1) + "行：" + coreExaminationStudent.getStudentName() + "考生成绩已录入");
                    redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                    continue;
                }
                repeatStudent.put(coreExaminationStudent.getCoreStudentId(), (i + 1));
                coreExaminationStudent.setClassId(eduStudent.getClassId());
                coreExaminationStudent.setClassName(eduStudent.getClassName());
                coreExaminationStudent.setGradeName(eduStudent.getGradeName());
                coreExaminationStudent.setGradeId(eduStudent.getGradeId());
                coreExaminationStudent.setSchoolId(eduStudent.getSchoolId());
                coreExaminationStudent.setSchoolName(eduStudent.getSchoolName());
                List<CoreExaminationCourse> coreExaminationCourseList = new ArrayList<>();
                StringBuilder stringBuilder = new StringBuilder();
                boolean flag = false;
                for (int j = 4; j < sheet.getRow(1).getLastCellNum(); j++) {
                    if (StrUtil.isNotBlank(ExcelUtil.getCellValue(sheet.getRow(1).getCell(j)))) {
                        CoreExaminationStudentCourse examinationStudentCourse = new CoreExaminationStudentCourse();
                        examinationStudentCourse.setCoreExaminationCourseName(ExcelUtil.getCellValue(sheet.getRow(1).getCell(j)));
                        examinationStudentCourse.setScore(StrUtil.isNotBlank(ExcelUtil.getCellValue(row.getCell(j))) ?
                            Double.valueOf(ExcelUtil.getCellValue(row.getCell(j))) : null);
                        // 成绩不存在不保存
                        if (examinationStudentCourse.getScore() == null) {
                            continue;
                        }
                        examinationStudentCourse.setClassId(eduStudent.getClassId());
                        examinationStudentCourse.setCoreExaminationId(coreExaminationId);
                        examinationStudentCourse.setGradeId(gradeId);
                        CoreExaminationCourse coreExaminationCourse = coreExaminationCourseMapper.selectOne(
                            Wrappers.lambdaQuery(new CoreExaminationCourse())
                                .eq(CoreExaminationCourse::getCoreCourseName,
                                    examinationStudentCourse.getCoreExaminationCourseName())
                                .eq(CoreExaminationCourse::getCoreExaminationId, coreExaminationId));
                        if (coreExaminationCourse == null) {
                            continue;
                        }
                        examinationStudentCourse.setCoreExaminationCourseId(coreExaminationCourse.getCoreCourseId());
                        if (Objects.nonNull(examinationStudentCourse.getScore())
                            && examinationStudentCourse.getScore() > coreExaminationCourse.getCoreCourseScore()) {
                            coreExaminationCourseList.add(coreExaminationCourse);
                        }
                        list.add(examinationStudentCourse);
                        flag = true;
                    }
                }

                if (!CollectionUtils.isEmpty(coreExaminationCourseList)) {
                    stringBuilder.append("以下科目输入分数大于考试分数：");
                    for (CoreExaminationCourse coreExaminationCourse : coreExaminationCourseList) {
                        stringBuilder.append("科目：");
                        stringBuilder.append(coreExaminationCourse.getCoreCourseName());
                        stringBuilder.append(", 考试分数为:");
                        stringBuilder.append(coreExaminationCourse.getCoreCourseScore());
                        stringBuilder.append("。");
                    }
                    error.add("第" + (i + 1) + "行：" + stringBuilder.toString());
                    redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                    continue;
                }

                // 以实际数据库保存的学生信息保存
                coreExaminationStudent.setStudentIdNumber(eduStudent.getIdNumber());
                coreExaminationStudent.setStudentNumber(eduStudent.getStuNumber());
                coreExaminationStudent.setStudentName(eduStudent.getStuName());
                coreExaminationStudent.setCoreExaminationId(coreExaminationId);
                // 设置当前行数
                coreExaminationStudent.setStudentAppId(String.valueOf(i + 1));

                coreExaminationStudent.setStudentCourseList(list);
                // 有分数不为空才保存
                if (flag) {
                    coreExaminationStudentList.add(coreExaminationStudent);
                }
            }
            for (CoreExaminationStudent coreExaminationStudent : coreExaminationStudentList) {
                finish++;
                // 进度改变进行保存
                if (finish * 100 / total != percent) {
                    percent = finish * 100 / total;
                    vo.setPercent(percent);
                    redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
                }
                LocalDateTime localDateTime = LocalDateTime.now();
                //登录用户id
                Long userId = 1L;
                if (Optional.ofNullable(userInfo).map(o -> o.getUserId()).isPresent()) {
                    userId = userInfo.getUserId();
                }
                coreExaminationStudent.setCreateId(userId);
                coreExaminationStudent.setCreateDate(localDateTime);

                EduStudent eduStudent = remoteStudentService.getStudentByStuNumAndSchool(
                    coreExaminationStudent.getStudentNumber(), schoolId).getData();

                // 设置考场名称
                coreExaminationStudent.setExaminationRoom(coreExamination.getName());

                // 计算总分数
                for (CoreExaminationStudentCourse coreExaminationStudentCourse : coreExaminationStudent.getStudentCourseList()) {
                    coreExaminationStudent.setScore(Optional.ofNullable(coreExaminationStudentCourse.getScore()).orElse(0D) +
                        Optional.ofNullable(coreExaminationStudent).map(obj -> obj.getScore()).orElse(0D));
                }

                if (Objects.equals(Optional.ofNullable(coreExaminationStudent).map(obj -> obj.getScore()).orElse(0D), 0)) {
                    coreExaminationStudent.setScore(null);
                    coreExaminationStudent.setMiss("1");
                }
                coreExaminationStudentMapper.insert(coreExaminationStudent);

                // 判断是否有总成绩，没有则不更新排名操作
                if (coreExaminationStudent.getScore() != null) {
                    // 根据考场和年级id查询对应的所有成绩并返回排序
                    List<CoreExaminationStudent> examinationIdAndGradeId =
                        coreExaminationStudentMapper.findByCoreExaminationIdAndGradeId(
                            coreExaminationStudent.getCoreExaminationId(), coreExaminationStudent.getGradeId());
                    // 更新所有考生年级排名
                    if (!CollectionUtils.isEmpty(examinationIdAndGradeId)) {
                        for (CoreExaminationStudent examinationStudent : examinationIdAndGradeId) {
                            coreExaminationStudentMapper.updateGradleRankOrClassRank(examinationStudent);
                        }
                    }

                    // 根据考场,年级id,班级id查询对应的所有成绩并返回排序
                    List<CoreExaminationStudent> examinationIdAndGradeIdClassId = coreExaminationStudentMapper.
                        findByCoreExaminationIdAndGradeIdClassId(coreExaminationStudent.getCoreExaminationId(),
                            coreExaminationStudent.getGradeId(),
                            coreExaminationStudent.getClassId());
                    // 更新所有考生班级排名
                    if (!CollectionUtils.isEmpty(examinationIdAndGradeIdClassId)) {
                        for (CoreExaminationStudent examinationStudent : examinationIdAndGradeIdClassId) {
                            coreExaminationStudentMapper.updateGradleRankOrClassRank(examinationStudent);
                        }
                    }
                }

                if (!CollectionUtils.isEmpty(coreExaminationStudent.getStudentCourseList())) {
                    for (CoreExaminationStudentCourse coreExaminationStudentCourse : coreExaminationStudent.getStudentCourseList()) {
                        // 设置考生id
                        coreExaminationStudentCourse.setCoreExaminationStudentId(coreExaminationStudent.getId());
                        // 设置考场id
                        coreExaminationStudentCourse.setCoreExaminationId(coreExaminationStudent.getCoreExaminationId());
                        coreExaminationStudentCourse.setCreateId(userId);
                        // 设置学校id和name
                        coreExaminationStudentCourse.setSchoolId(eduStudent.getSchoolId());
                        coreExaminationStudentCourse.setSchoolName(eduStudent.getSchoolName());
                        // 设置年级id和name
                        coreExaminationStudentCourse.setGradeId(coreExaminationStudent.getGradeId());
                        coreExaminationStudentCourse.setGradeName(eduStudent.getGradeName());
                        // 设置班级id和name
                        coreExaminationStudentCourse.setClassId(coreExaminationStudent.getClassId());
                        coreExaminationStudentCourse.setClassName(coreExaminationStudent.getClassName());
                        // 设置考场name
                        coreExaminationStudentCourse.setExaminationRoom(coreExamination.getName());
                        // 设置考号
                        coreExaminationStudentCourse.setExaminationNumber(coreExaminationStudent.getExaminationNumber());
                        // 设置座位号
                        coreExaminationStudentCourse.setSeatNumber(coreExaminationStudent.getSeatNumber());

                        if (Objects.isNull(coreExaminationStudentCourse.getScore())) {
                            coreExaminationStudentCourse.setMiss("1");
                        }
                    }
                    coreExaminationStudentCourseService.saveBatch(coreExaminationStudent.getStudentCourseList());

                    for (CoreExaminationStudentCourse coreExaminationStudentCourse : coreExaminationStudent.getStudentCourseList()) {
                        // 判断科目是否有输入成绩，有成绩在更新各科的最新排名
                        if (Objects.nonNull(coreExaminationStudentCourse.getScore())) {
                            // 根据考场,年级id,科目id查询对应的所有成绩并返回排序
                            List<CoreExaminationStudentCourse> coreExaminationStudentCourses =
                                coreExaminationStudentCourseMapper.findByCoreExaminationIdAndGradeIdCourseId(
                                    coreExaminationStudentCourse.getCoreExaminationId(),
                                    coreExaminationStudentCourse.getGradeId(),
                                    coreExaminationStudentCourse.getCoreExaminationCourseId());
                            //更新年级排名
                            if (!CollectionUtils.isEmpty(coreExaminationStudentCourses)) {
                                for (CoreExaminationStudentCourse coreExaminationStudentCours : coreExaminationStudentCourses) {
                                    coreExaminationStudentCourseMapper.updateGradleRankOrClassRank(coreExaminationStudentCours);

                                }
                            }
                            // 根据考场,年级id,年级id，科目id查询对应的所有成绩并返回排序
                            List<CoreExaminationStudentCourse> coreExaminationStudentCourses1 =
                                coreExaminationStudentCourseMapper.findByCoreExaminationIdAndGradeIdClassIdCourseId(
                                    coreExaminationStudentCourse.getCoreExaminationId(),
                                    coreExaminationStudentCourse.getGradeId(),
                                    coreExaminationStudentCourse.getClassId(),
                                    coreExaminationStudentCourse.getCoreExaminationCourseId());
                            //更新班级排名
                            if (!CollectionUtils.isEmpty(coreExaminationStudentCourses1)) {
                                for (CoreExaminationStudentCourse examinationStudentCourse : coreExaminationStudentCourses1) {
                                    coreExaminationStudentCourseMapper.updateGradleRankOrClassRank(examinationStudentCourse);

                                }
                            }
                        }
                    }

                }

            }

        } catch (Exception e) {
            log.error("msg:[{}],stack:[{}]", e.getMessage(), e.getStackTrace());
            e.printStackTrace();
        } finally {
            vo.setFinish(1);
            redisService.hset(CachePrefixConstant.EXAM_UPLOAD_STUDENT_DATA, coreExaminationId.toString(), vo);
        }
    }
}
