package com.yida.data.school.exam.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.entity.constant.CachePrefixConstant;
import com.yida.data.common.core.entity.exam.*;
import com.yida.data.school.exam.mapper.*;
import com.yida.data.school.exam.service.CorePerformanceService;
import com.yida.data.school.vo.exam.StudentExamListVO;
import com.yida.data.school.vo.exam.StudentExamScoreVO;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CorePerformanceServiceImpl implements CorePerformanceService {

    private final CoreExaminationMapper coreExaminationMapper;
    private final CoreExaminationCourseMapper coreExaminationCourseMapper;
    private final CoreExaminationStudentMapper coreExaminationStudentMapper;
    private final CoreExaminationStudentCourseMapper coreExaminationStudentCourseMapper;
    private final CoreExaminationPublishRecordMapper coreExaminationPublishRecordMapper;
    private final CoreExaminationPublishMapper coreExaminationPublishMapper;
    private final EduExamAvgMapper eduExamAvgMapper;
    private final CoreExaminationPublishGradeConvertTypeMapper coreExaminationPublishGradeConvertTypeMapper;

    @Override
    public CoreStudentReturnData findStudentExamineGrade(Long studentId, Long examinationId) {
        //返回的成绩数据
        CoreStudentReturnData coreStudentReturnData = null;
        //查询的到的数据
        List<CoreStudentReturnData> returnDataList = coreExaminationMapper.findStudentExamineGrade(studentId, examinationId);
        if (returnDataList != null && returnDataList.size() > 0) {
            coreStudentReturnData = returnDataList.get(0);
        }
        //处理科目数据和总分
        if (coreStudentReturnData != null) {
            //科目数量
            Integer courseNumber = 0;
            //本次考试总分
            double studentTotalScore = 0.;

            List<CoreStudentReturnCourseData> courseDataList = coreStudentReturnData.getCourseDataList();
            //判断数据
            if (courseDataList != null && courseDataList.size() > 0) {
                //科目数量
                courseNumber = courseDataList.size();
                //本次考试总分
                for (CoreStudentReturnCourseData data : courseDataList) {
                    studentTotalScore = studentTotalScore + data.getStudentCourseScore();
                }
            }

            coreStudentReturnData.setCourseNumber(courseNumber);
            coreStudentReturnData.setStudentTotalScore(studentTotalScore);
        }

        return coreStudentReturnData;
    }

    @Override
    public List<StudentExamListVO> findStudentExamineList(Long studentId,
                                                          String examinationName) {
        LocalDate now = LocalDate.now();
        LocalDate start, end;
        if (now.getMonthValue() < 9) {
            start = LocalDate.of(now.getYear() - 1, 9, 1);
            end = LocalDate.of(now.getYear(), 8, 31);
        } else {
            start = LocalDate.of(now.getYear(), 9, 1);
            end = LocalDate.of(now.getYear() + 1, 8, 31);
        }
        return coreExaminationMapper.findStudentExamineList(start, end, studentId, examinationName);
    }

    @Override
    @Cacheable(value = CachePrefixConstant.EXAM_STUDENT_SCORE_RANK, key = "#examId+''+#studentId+''+#courseId")
    public StudentExamScoreVO getScore(Long examId, Long studentId, Long courseId) {
        CoreExaminationStudent student = coreExaminationStudentMapper.selectOne(Wrappers.lambdaQuery(new CoreExaminationStudent())
                .eq(CoreExaminationStudent::getCoreExaminationId, examId)
                .eq(CoreExaminationStudent::getCoreStudentId, studentId));
        CoreExaminationPublish examinationPublish = coreExaminationPublishMapper.selectOne(Wrappers.lambdaQuery(new CoreExaminationPublish())
                .eq(CoreExaminationPublish::getCoreExaminationId, examId));
        StudentExamScoreVO scoreVO = new StudentExamScoreVO();
        if (courseId == null) {
            scoreVO.setScore(student.getScore());
            scoreVO.setClassRank(student.getClassRank());
            scoreVO.setGradeRank(student.getGradeRank());
            scoreVO.setLevel(student.getGradeLevel());
        } else {
            CoreExaminationPublishRecord record = coreExaminationPublishRecordMapper.selectOne(Wrappers.lambdaQuery(new CoreExaminationPublishRecord())
                    .eq(CoreExaminationPublishRecord::getCoreExaminationId, examId)
                    .eq(CoreExaminationPublishRecord::getCoreExaminationStudentId, student.getId())
                    .eq(CoreExaminationPublishRecord::getCoreExaminationCourseId, courseId));
            scoreVO.setScore(record.getScore());
            scoreVO.setLevel(record.getGradeLevel());
            scoreVO.setClassRank(record.getClassRank());
            scoreVO.setGradeRank(record.getGradeRank());
        }
        LambdaQueryWrapper<EduExamAvg> condition1 = Wrappers.lambdaQuery(new EduExamAvg())
                .eq(EduExamAvg::getExamId, examId);
        LambdaQueryWrapper<EduExamAvg> condition2 = Wrappers.lambdaQuery(new EduExamAvg())
                .eq(EduExamAvg::getExamId, examId);
        if (courseId != null) {
            condition1.eq(EduExamAvg::getCourseId, courseId);
            condition2.eq(EduExamAvg::getCourseId, courseId);
        } else {
            condition1.isNull(EduExamAvg::getCourseId);
            condition2.isNull(EduExamAvg::getCourseId);
        }
        // 班级平均
        EduExamAvg classAvg = eduExamAvgMapper.selectOne(condition1.eq(EduExamAvg::getDeptType, 0).eq(EduExamAvg::getDeptId,
                student.getClassId()));
        // 年级平均
        EduExamAvg gradeAvg =
                eduExamAvgMapper.selectOne(condition2.eq(EduExamAvg::getDeptType, 1).eq(EduExamAvg::getDeptId,
                        student.getGradeId()));
        scoreVO.setClassAvg(classAvg.getScoreAvg());
        scoreVO.setGradeAvg(gradeAvg.getScoreAvg());
        // 计算等级
        Double score = 0D;
        if (courseId == null) {
            CoreExamination exam = coreExaminationMapper.selectById(examId);
            score = exam.getScore();
        } else {
            CoreExaminationCourse course =
                    coreExaminationCourseMapper.selectOne(Wrappers.lambdaQuery(new CoreExaminationCourse())
                            .eq(CoreExaminationCourse::getCoreExaminationId, examId)
                            .eq(CoreExaminationCourse::getCoreCourseId, courseId));
            score = course.getCoreCourseScore();
        }

        List<String> levelList1 =
                coreExaminationPublishGradeConvertTypeMapper.findGradeRank(score,
                        classAvg.getScoreAvg(), examId);
        if (CollUtil.isNotEmpty(levelList1)) {
            scoreVO.setClassAvgLevel(levelList1.get(0));
        }
        List<String> levelList2 =
                coreExaminationPublishGradeConvertTypeMapper.findGradeRank(score,
                        gradeAvg.getScoreAvg(), examId);
        if (CollUtil.isNotEmpty(levelList2)) {
            scoreVO.setGradeAvgLevel(levelList2.get(0));
        }
        scoreVO.setClassRankBlock(examinationPublish.getClassRankBlock());
        scoreVO.setGradeRankBlock(examinationPublish.getGradeRankBlock());
        return scoreVO;
    }
}



