package com.srs.comprehensive.service.impl;

import com.srs.comprehensive.domain.CphStuExtraInfo;
import com.srs.comprehensive.domain.GraduateStudentNews;
import com.srs.comprehensive.domain.SaveStudent;
import com.srs.comprehensive.domain.ViewStuInfo;
import com.srs.comprehensive.domain.Vo.CphCollegeLook;
import com.srs.comprehensive.mapper.GraduateTextMapper;
import com.srs.comprehensive.service.GraduateTextService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
/**
 * 毕业生信息管理serviceImpI
 * 邵政文
 * @date 2025-07-01
 **/
public class GraduateTextImpI implements GraduateTextService {

    @Autowired
    private GraduateTextMapper graduateTextMapper;

    /**
     * 根据学号查询毕业生信息
     * @param studentCode
     * @return
     * @author GraduateStudentNews
     * 邵政文
     * @date 2025-07-02
     **/
    @Override
    public GraduateStudentNews getStudentByName(String studentCode) {
        return graduateTextMapper.selectByStudentCode(studentCode);
    }

    /**
     * 查询毕业生列表信息
     * @param student 学生信息实体
     * 邵政文
     * @date 2025-07-02
     */
    @Override
    public List<GraduateStudentNews> getGraduateList(GraduateStudentNews student) {
        return graduateTextMapper.selectGraduateList(student);
    }

    /**
     * 查询班级信息
     * @return
     * @author classId
     * 邵政文
     * @date 2025-07-02
     **/
    @Override
    public String selectGraduateClassData(Integer classId) {
        return graduateTextMapper.selectGraduateClassData(classId);
    }

    /**
     * 根据id查询毕业生信息
     * @return
     * @author id
     * 邵政文
     * @date 2025-07-02
     **/
    @Override
    public SaveStudent selectGraduateExclById(Long id) {
        return graduateTextMapper.selectByStudentById(id);
    }

    /**
     * 添加毕业生信息
     * @param graduateStudents 毕业生信息列表
     * 邵政文
     * 2025-07-02
     *//*
    @Override
    public int addGraduateList(List<GraduateStudentNews> graduateStudents) {
        int count = 0;
        for (GraduateStudentNews student : graduateStudents) {
            String studentCode = student.getStudentCode();
            // 根据学号查询是否已存在该学生信息
            GraduateStudentNews existingStudent = graduateTextMapper.selectByStudentCode(studentCode);

            if (existingStudent != null) {
                // 存在，使用现有 id 作为 graduate_id
                Long graduateId = existingStudent.getId();
                student.setGraduateId(graduateId.intValue()); // 设置 graduate_id

                // 查询该学生已有的学年信息
                List<Integer> existingYears = graduateTextMapper.selectStuYearByStudentCode(studentCode);
                // 如果学年信息存在于集合中，则更新子表
                if (existingYears != null && existingYears.contains(student.getStuYear())) {
                    int updateResult = graduateTextMapper.updateGraduateStudentByGraduateId(student);
                    count += updateResult;
                } else {
                    // 否则插入子表
                    int insertResult = graduateTextMapper.insertGraduateStudent(student);
                    count += insertResult;
                }
            } else {
                // 不存在，先插入主表 graduate_studentinfo
                // 查询该学生基本信息
                ViewStuInfo res = graduateTextMapper.selectStudentByStudentCode(student.getStudentCode());
                //查询该学生民族信息
                CphStuExtraInfo ress = graduateTextMapper.selectStudentMZByStudentCode(student.getStudentCode());
                //查询该学生学年分数信息
                CphCollegeLook cphCollegeLook = graduateTextMapper.selectStudentFnByStuNOAndStuYear(student);

                student.setStudentCollege(res.getDeptName());
                student.setStudentGrade(res.getGradeName());
                student.setStudentClass(res.getClassName());
                student.setSex(res.getGender());
                student.setBirthData(res.getBirthday());
                if(ress != null) {
                    student.setNation(ress.getMz());
                }
                double totalPoints = 0;//总分
                if (cphCollegeLook != null) {
                    totalPoints += cphCollegeLook.getIamScore() != null ? Double.parseDouble(cphCollegeLook.getIamScore()) : 0;
                    totalPoints += cphCollegeLook.getStuScore() != null ? Double.parseDouble(cphCollegeLook.getStuScore()) : 0;
                    totalPoints += cphCollegeLook.getSportScore() != null ? Double.parseDouble(cphCollegeLook.getSportScore()) : 0;
                    student.setLdeologicalPolitical(cphCollegeLook.getIamScore());
                    student.setScientificQuality(cphCollegeLook.getStuScore());
                    student.setPhysicalQuality(cphCollegeLook.getSportScore());
                }
                double rounded = Math.round(totalPoints * 100.0) / 100.0;
                student.setTotalPoints(rounded);
                // 注意：由于 useGeneratedKeys=true，插入后会自动回填 id 到 student.id
                graduateTextMapper.inserts(student);

                // 获取新生成的 id 并设置为 graduate_id
                Integer newGraduateId = student.getId().intValue();
                student.setGraduateId(newGraduateId);

                // 插入子表 graduate_student
                int insertResult = graduateTextMapper.insertGraduateStudent(student);
                count += insertResult;
            }
        }
        return count;
    }*/

    /**
     * 添加毕业生信息
     * @param graduateStudents 毕业生信息列表
     * 邵政文
     * 2025-07-02
     */
    @Override
    public int addGraduateList(List<GraduateStudentNews> graduateStudents) {
        int count = 0;
        for (GraduateStudentNews student : graduateStudents) {
            String studentCode = student.getStudentCode();
            // 根据学号查询是否已存在该学生信息
            GraduateStudentNews existingStudent = graduateTextMapper.selectByStudentCode(studentCode);

            if (existingStudent != null) {
                // 存在，使用现有 id 作为 graduate_id
                Long graduateId = existingStudent.getId();
                student.setGraduateId(graduateId.intValue()); // 设置 graduate_id

                // 查询该学生已有的学年信息
                List<Integer> existingYears = graduateTextMapper.selectStuYearByStudentCode(studentCode);

                // 如果学年信息存在于集合中，则更新子表
                if (existingYears != null && existingYears.contains(student.getStuYear())) {

                    //查询该学生学年分数信息
                    CphCollegeLook cphCollegeLook = graduateTextMapper.selectStudentFnByStuNOAndStuYear(student);
                    // 更新各项成绩字段
                    updateStudentScore(student, cphCollegeLook);

                    int updateResult = graduateTextMapper.updateGraduateStudentByGraduateId(student);
                    count += updateResult;
                } else {
                    // 否则插入子表

                    //查询该学生学年分数信息
                    CphCollegeLook cphCollegeLook = graduateTextMapper.selectStudentFnByStuNOAndStuYear(student);
                    // 更新各项成绩字段
                    updateStudentScore(student, cphCollegeLook);

                    int insertResult = graduateTextMapper.insertGraduateStudent(student);
                    count += insertResult;
                }
            } else {
                // 不存在，先插入主表 graduate_studentinfo
                // 查询该学生基本信息
                ViewStuInfo res = graduateTextMapper.selectStudentByStudentCode(student.getStudentCode());
                //查询该学生民族信息
                CphStuExtraInfo ress = graduateTextMapper.selectStudentMZByStudentCode(student.getStudentCode());
                //查询该学生学年分数信息
                CphCollegeLook cphCollegeLook = graduateTextMapper.selectStudentFnByStuNOAndStuYear(student);

                student.setStudentCollege(res.getDeptName());
                student.setStudentGrade(res.getGradeName());
                student.setStudentClass(res.getClassName());
                student.setSex(res.getGender());
                student.setBirthData(res.getBirthday());
                if(ress != null) {
                    student.setNation(ress.getMz());
                }

                updateStudentScore(student,cphCollegeLook);

                // 注意：由于 useGeneratedKeys=true，插入后会自动回填 id 到 student.id
                graduateTextMapper.inserts(student);

                // 获取新生成的 id 并设置为 graduate_id
                Integer newGraduateId = student.getId().intValue();
                student.setGraduateId(newGraduateId);

                // 插入子表 graduate_student
                int insertResult = graduateTextMapper.insertGraduateStudent(student);
                count += insertResult;
            }
        }

        return count;
    }

    /**
     * 获取毕业生成绩列表
     * @param student 毕业生信息
     * 邵政文
     * 2025-07-01
     */
    private void updateStudentScore(GraduateStudentNews student, CphCollegeLook cphCollegeLook){
        Double totalPoints = null;//当综测成绩为空时，总分设为null而不是0，更符合实际情况
        if (cphCollegeLook != null) {
            //直接使用查询到学生学年分数信息中的综测成绩作为总分
            if (cphCollegeLook.getCphScore() != null && !cphCollegeLook.getCphScore().isEmpty()) {//综测成绩不为空
                try {
                    totalPoints = Double.parseDouble(cphCollegeLook.getCphScore());//转换为double
                    // 保留两位小数
                    totalPoints = Math.round(totalPoints * 100.0) / 100.0;
                } catch (NumberFormatException e) {
                    // 如果转换失败，保持totalPoints为null
                    totalPoints = null;
                }
            }
            student.setLdeologicalPolitical(cphCollegeLook.getIamScore());
            student.setScientificQuality(cphCollegeLook.getStuScore());
            student.setPhysicalQuality(cphCollegeLook.getSportScore());
        }
        //设置总分，如果综测成绩为空则设为null
        student.setTotalPoints(totalPoints);
    }


    /**
     * 根据ids批量查询毕业生信息
     * @return 毕业生信息列表
     * @author ids
     * 邵政文
     * @date 2025-07-02
     **/
    @Override
    public List<SaveStudent> graduateByIdsList(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return new ArrayList<>();
        }
        return graduateTextMapper.graduateByIdsList(ids);
    }
}
