package com.xjrsoft.module.banding.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.enums.ArchivesStatusEnum;
import com.xjrsoft.common.enums.DeleteMark;
import com.xjrsoft.common.enums.EnabledMark;
import com.xjrsoft.common.enums.GenderDictionaryEnum;
import com.xjrsoft.common.enums.RoleEnum;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.config.CommonPropertiesConfig;
import com.xjrsoft.module.banding.dto.AutomaticBandingTaskDto;
import com.xjrsoft.module.banding.dto.BandingTaskClassStudentPageDto;
import com.xjrsoft.module.banding.dto.BandingTaskPageDto;
import com.xjrsoft.module.banding.dto.SureBandingTaskDto;
import com.xjrsoft.module.banding.entity.BandingRule;
import com.xjrsoft.module.banding.entity.BandingTask;
import com.xjrsoft.module.banding.entity.BandingTaskClass;
import com.xjrsoft.module.banding.entity.BandingTaskClassStudent;
import com.xjrsoft.module.banding.entity.BandingTaskMajorCondition;
import com.xjrsoft.module.banding.entity.BandingTaskRule;
import com.xjrsoft.module.banding.mapper.BandingRuleMapper;
import com.xjrsoft.module.banding.mapper.BandingTaskClassMapper;
import com.xjrsoft.module.banding.mapper.BandingTaskMapper;
import com.xjrsoft.module.banding.mapper.BandingTaskRuleMapper;
import com.xjrsoft.module.banding.service.IBandingTaskClassStudentService;
import com.xjrsoft.module.banding.service.IBandingTaskMajorConditionService;
import com.xjrsoft.module.banding.service.IBandingTaskService;
import com.xjrsoft.module.banding.vo.BandingTaskClassSureListVo;
import com.xjrsoft.module.banding.vo.BandingTaskPageVo;
import com.xjrsoft.module.banding.vo.IdManyCountVo;
import com.xjrsoft.module.base.entity.BaseClass;
import com.xjrsoft.module.base.entity.BaseGrade;
import com.xjrsoft.module.base.entity.BaseMajorSet;
import com.xjrsoft.module.base.mapper.BaseMajorSetMapper;
import com.xjrsoft.module.base.service.IBaseClassService;
import com.xjrsoft.module.base.service.IBaseGradeService;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.entity.UserRoleRelation;
import com.xjrsoft.module.organization.service.IUserRoleRelationService;
import com.xjrsoft.module.organization.service.IUserService;
import com.xjrsoft.module.outint.vo.IdCountVo;
import com.xjrsoft.module.student.entity.BaseClassMajorSet;
import com.xjrsoft.module.student.entity.BaseNewStudent;
import com.xjrsoft.module.student.entity.BaseStudent;
import com.xjrsoft.module.student.entity.BaseStudentFamily;
import com.xjrsoft.module.student.entity.BaseStudentSchoolRoll;
import com.xjrsoft.module.student.entity.EnrollmentPlan;
import com.xjrsoft.module.student.mapper.BaseClassMajorSetMapper;
import com.xjrsoft.module.student.service.IBaseNewStudentService;
import com.xjrsoft.module.student.service.IBaseStudentFamilyService;
import com.xjrsoft.module.student.service.IBaseStudentSchoolRollService;
import com.xjrsoft.module.student.service.IBaseStudentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

/**
* @title: 新生分班任务
* @Author dzx
* @Date: 2024-07-01
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class BandingTaskServiceImpl extends MPJBaseServiceImpl<BandingTaskMapper, BandingTask> implements IBandingTaskService {
    private final BandingTaskMapper bandingTaskMapper;
    private final BandingRuleMapper ruleMapper;
    private final BandingTaskRuleMapper taskRuleMapper;
    private final BandingTaskClassMapper taskClassMapper;
    private final IBaseNewStudentService newStudentService;
    private final IBandingTaskClassStudentService classStudentService;
    private final IBandingTaskMajorConditionService conditionService;

    private final IBaseClassService classService;
    private final BaseClassMajorSetMapper classMajorSetMapper;
    private final CommonPropertiesConfig propertiesConfig;
    private final IUserService userService;
    private final IUserRoleRelationService roleRelationService;
    private final IBaseStudentSchoolRollService schoolRollService;
    private final IBaseStudentService studentService;
    private final IBaseStudentFamilyService familyService;
    private final IBaseGradeService gradeService;
    private final BaseMajorSetMapper majorSetMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(BandingTask bandingTask) {
        bandingTask.setCreateDate(new Date());
        bandingTaskMapper.insert(bandingTask);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(BandingTask bandingTask) {
        bandingTask.setModifyDate(new Date());
        bandingTaskMapper.updateById(bandingTask);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        bandingTaskMapper.deleteBatchIds(ids);
        taskRuleMapper.delete(Wrappers.lambdaQuery(BandingTaskRule.class).in(BandingTaskRule::getBandingTaskId, ids));
        taskClassMapper.delete(Wrappers.lambdaQuery(BandingTaskClass.class).in(BandingTaskClass::getBandingTaskId, ids));

        return true;
    }

    /**
     * 自动分班
     * 1、根据分班任务的信息，查询出来需要分班的学生
     * 2、查询该任务下的班级信息
     * 3、查询该任务使用的规则
     * 4、执行自动分班
     * 5、完成后，将分好班的信息存到banding_task_class_student表中
     */
    @Override
    public Boolean automaticBanding(AutomaticBandingTaskDto dto) {
        BandingTask bandingTask = this.getById(dto.getBandingTaskId());
        if(bandingTask == null){
            throw new MyException("未能查询到该任务，无法自动分班");
        }
        //1、查询需要分班的学生信息
        List<BandingTaskClassStudent> classStudents = classStudentService.selectJoinList(BandingTaskClassStudent.class,
                new MPJLambdaWrapper<BandingTaskClassStudent>()
                        .select(BandingTaskClassStudent::getId)
                        .select(BandingTaskClassStudent.class, x -> VoToColumnUtil.fieldsToColumns(BandingTaskClassStudent.class).contains(x.getProperty()))
                        .leftJoin(BandingTaskClass.class, BandingTaskClass::getId, BandingTaskClassStudent::getBandingTaskClassId)
                        .eq(BandingTaskClass::getStatus, 1)
        );
        List<Long> studentIds = classStudents.stream().map(BandingTaskClassStudent::getNewStudentId).collect(Collectors.toList());

        List<String> orderColumn = new ArrayList();
        orderColumn.add("score");
        List<BaseNewStudent> baseNewStudents = newStudentService.selectJoinList(BaseNewStudent.class,
                new MPJLambdaWrapper<BaseNewStudent>()
                        .select(BaseNewStudent::getId)
                        .select(BaseNewStudent.class, x -> VoToColumnUtil.fieldsToColumns(BaseNewStudent.class).contains(x.getProperty()))
                        .leftJoin(EnrollmentPlan.class, EnrollmentPlan::getId, BaseNewStudent::getEnrollmentPlanId)
                        .eq(EnrollmentPlan::getGradeId, bandingTask.getGradeId())
                        .eq(EnrollmentPlan::getEnrollType, bandingTask.getEnrollType())
                        .eq(BaseNewStudent::getStatus, 0)
                        .notIn(!studentIds.isEmpty(), BaseNewStudent::getId, studentIds)
                        .orderByDescStr(orderColumn)
        );
        //2、查询所有班级信息
        List<BandingTaskClass> classList = taskClassMapper.getListOrderByAsc(bandingTask.getId());
        if(!classList.isEmpty()){
            //清除数据
            List<Long> classIds = classList.stream().map(BandingTaskClass::getId).collect(Collectors.toList());
            classStudentService.remove(
                    new QueryWrapper<BandingTaskClassStudent>().lambda()
                            .in(BandingTaskClassStudent::getBandingTaskClassId, classIds)
            );
        }

        //3、查询所用到的规则
        List<BandingRule> ruleList = ruleMapper.selectJoinList(BandingRule.class,
                new MPJLambdaWrapper<BandingRule>()
                        .select(BandingRule::getId)
                        .select(BandingRule.class, x -> VoToColumnUtil.fieldsToColumns(BandingRule.class).contains(x.getProperty()))
                        .innerJoin(BandingTaskRule.class, BandingTaskRule::getBandingRuleId, BandingRule::getId)
                        .eq(BandingTaskRule::getBandingTaskId, bandingTask.getId())
        );
        List<String> ruleCodes = ruleList.stream().map(BandingRule::getCode).collect(Collectors.toList());

        //查询每个专业符合限制条件的人数
        List<IdManyCountVo> majorStudentCountList = newStudentService.getMajorStudentCount(bandingTask.getId());
        Map<Long, IdManyCountVo> majorStudentCountMap = majorStudentCountList.stream().collect(Collectors.toMap(IdManyCountVo::getId, x -> x));
        //查询每个专业下面有多少个班级
        List<IdCountVo> majorClassCountList = taskClassMapper.getMajorClassCount(bandingTask.getId());
        Map<Long, Integer> majorClassCount = majorClassCountList.stream().collect(Collectors.toMap(IdCountVo::getId, IdCountVo::getCount));
        //计算每个专业平均的男女人数
        Map<Long, Integer> majorMaleCountMap = new HashMap<>();
        Map<Long, Integer> majorFemaleCountMap = new HashMap<>();
        if(ruleCodes.contains("BR0001")){
            for (Long majorSetId : majorClassCount.keySet()) {
                int classCount = majorClassCount.get(majorSetId);
                Integer maleCount = majorStudentCountMap.get(majorSetId).getMaleCount();
                Integer femaleCount = majorStudentCountMap.get(majorSetId).getFemaleCount();
                if(classCount == 1 || classCount == 0){
                    majorMaleCountMap.put(majorSetId, maleCount);
                    majorFemaleCountMap.put(majorSetId, femaleCount);
                    continue;
                }
                majorMaleCountMap.put(majorSetId, maleCount / classCount);
                majorFemaleCountMap.put(majorSetId, femaleCount / classCount);
            }
        }

        //包含下面个条件，则需要计算每个班级应该分配的人数
        Map<Long, Integer> classLimitMap = new HashMap<>();
        if(ruleCodes.contains("BR0004")){
            //查询每个专业下面的班级人数
            Map<Long, Integer> majorClassStudentCount = taskClassMapper.getMajorClassStudentCount(bandingTask.getId())
                    .stream().collect(Collectors.toMap(IdCountVo::getId, IdCountVo::getCount));

            Map<Long, Integer> majorStudentCount = majorStudentCountList.stream().collect(Collectors.toMap(IdManyCountVo::getId, IdManyCountVo::getCount));

            Map<Long, Integer> majorLimitMap = new HashMap<>();
            for (Long majorSetId : majorClassStudentCount.keySet()) {
                int majorClassNumber = 0;
                if(majorClassStudentCount.get(majorSetId) != null){
                    majorClassNumber = majorClassStudentCount.get(majorSetId);
                }
                if(majorClassCount.get(majorSetId) == 1 || majorClassCount.get(majorSetId) == 0){
                    continue;
                }
                int majorStudentNumber = 0;
                if(majorStudentCount.get(majorSetId) != null){
                    majorStudentNumber = majorStudentCount.get(majorSetId);
                }
                Integer classCount = majorClassCount.get(majorSetId);
                if(majorStudentNumber < majorClassNumber){//报名人数小于班级人数
                    Integer classLimtCount = majorStudentNumber / classCount;
                    majorLimitMap.put(majorSetId, classLimtCount);
                }else{
                    Integer classLimtCount = majorClassNumber / classCount;
                    majorLimitMap.put(majorSetId, classLimtCount);
                }
            }

            for (BandingTaskClass bandingTaskClass : classList) {
                classLimitMap.put(bandingTaskClass.getId(), majorLimitMap.get(bandingTaskClass.getMajorSetId()));
            }
        }

        //查询每个专业的限制条件
        List<BandingTaskMajorCondition> list = conditionService.list(
                new QueryWrapper<BandingTaskMajorCondition>().lambda()
                        .eq(BandingTaskMajorCondition::getBandingTaskId, dto.getBandingTaskId())
        );
        Map<Long, BandingTaskMajorCondition> classConditionMap = new HashMap<>();
        for (BandingTaskMajorCondition conditionDto : list) {
            classConditionMap.put(conditionDto.getMajorSetId(), conditionDto);
        }

        Map<Long, List<BaseNewStudent>> classStudentMap = new HashMap<>();
        if(ruleCodes.contains("BR0002")){
            classStudentMap.putAll(divideStudentByScore(classConditionMap, baseNewStudents, classList));
        }

        //存班级和学生的关系
        Map<Long, Long> studentClassMap = new HashMap<>();
        Map<Long, List<String>> classNameMap = new HashMap<>();
        //4、开始分班
        for (BandingTaskClass taskClass : classList) {
            Integer number = taskClass.getNumber();//班级总人数
            if(classLimitMap.get(taskClass.getId()) != null){
                if(number > classLimitMap.get(taskClass.getId())){
                    number = classLimitMap.get(taskClass.getId());
                }
            }
            Integer maleCount = 0, femaleCount = 0;
            if(ruleCodes.contains("BR0001")){
                IdManyCountVo countVo = majorStudentCountMap.get(taskClass.getMajorSetId());
                maleCount = number / 2;
                femaleCount = number / 2;
                //如果班级人数是奇数，随机分配一个名额
                if(number % 2 != 0){
                    Random random = new Random();
                    int randomIndex = random.nextInt(GenderDictionaryEnum.getCodes().length);

                    String randomGender = GenderDictionaryEnum.getCodes()[randomIndex];
                    if(GenderDictionaryEnum.MALE.getCode().equals(randomGender)){
                        maleCount ++;
                    }else if(GenderDictionaryEnum.FEMALE.getCode().equals(randomGender)){
                        femaleCount ++ ;
                    }
                }
                if(majorMaleCountMap.get(taskClass.getMajorSetId()) < maleCount){
                    maleCount = countVo.getMaleCount();
                    femaleCount = number - maleCount;
                }else if(majorFemaleCountMap.get(taskClass.getMajorSetId()) < femaleCount){
                    femaleCount = countVo.getFemaleCount();
                    maleCount = number - femaleCount;
                }
            }
            List<String> nameList = new ArrayList<>();
            List<BaseNewStudent> maleList = new ArrayList();//男生
            List<BaseNewStudent> femaleList = new ArrayList();//女生

            List<BaseNewStudent> studentList = new ArrayList<>();
            studentList.addAll(baseNewStudents);
            if(ruleCodes.contains("BR0002") && classStudentMap.get(taskClass.getMajorSetId()) != null && !classStudentMap.get(taskClass.getMajorSetId()).isEmpty()){
                studentList.clear();
                studentList.addAll(classStudentMap.get(taskClass.getMajorSetId()));
            }

            for (BaseNewStudent newStudent : studentList) {
                //人数已满，进行下一个班级的的循环
                if(nameList.size() == number){
                    break;
                }
                //该学生已被分配
                if(studentClassMap.containsKey(newStudent.getId())){
                    continue;
                }
                if(ruleCodes.contains("BR0003") && nameList.contains(newStudent.getName())){
                    continue;
                }
                //专业不匹配，直接跳过
                if(!Objects.equals(taskClass.getMajorSetId(), newStudent.getFirstAmbitionId()) && !Objects.equals(taskClass.getMajorSetId(), newStudent.getSecondAmbitionId())){
                    continue;
                }
                //判断该班性别是否已满，如果设置了排序，即使性别满了班级人数没满继续分班
                if(ruleCodes.contains("BR0001")){
                    if(GenderDictionaryEnum.MALE.getCode().equals(newStudent.getGender()) && maleList.size() == maleCount){
                        continue;
                    }else if(GenderDictionaryEnum.FEMALE.getCode().equals(newStudent.getGender()) && femaleList.size() == femaleCount){
                        continue;
                    }
                }

                if(taskClass.getSortCode() == null && !Objects.equals(taskClass.getMajorSetId(), newStudent.getFirstAmbitionId())){//如果未给班级设置优先级，只匹配一志愿的学生
                    continue;
                }

                List<Boolean> conditionList = new ArrayList<>();
                BandingTaskMajorCondition condition = classConditionMap.get(taskClass.getMajorSetId());
                if(condition != null){
                    if(condition.getHeight() !=null && newStudent.getHeight() != null && newStudent.getHeight().compareTo(condition.getHeight()) >= 0 ){
                        conditionList.add(true);
                    }else if(condition.getHeight() !=null && newStudent.getHeight() != null && newStudent.getHeight().compareTo(condition.getHeight()) < 0){
                        conditionList.add(false);
                    }else if(condition.getHeight() !=null && newStudent.getHeight() == null){
                        conditionList.add(false);
                    }

                    if(condition.getScore() !=null && newStudent.getScore() != null && newStudent.getScore().compareTo(condition.getScore()) >= 0 ){
                        conditionList.add(true);
                    }else if(condition.getScore() !=null && newStudent.getScore() != null && newStudent.getScore().compareTo(condition.getScore()) < 0){
                        conditionList.add(false);
                    }else if(condition.getScore() !=null && newStudent.getScore() == null){
                        conditionList.add(false);
                    }
                }

                //如果包含false，则表明不符合条件，这个学生跳过
                if(conditionList.contains(false)){
                    continue;
                }
                studentClassMap.put(newStudent.getId(), taskClass.getId());
                if(GenderDictionaryEnum.MALE.getCode().equals(newStudent.getGender())){
                    maleList.add(newStudent);
                }else if(GenderDictionaryEnum.FEMALE.getCode().equals(newStudent.getGender())){
                    femaleList.add(newStudent);
                }
                nameList.add(newStudent.getName());
            }
            classNameMap.put(taskClass.getId(), nameList);
        }
        // 4.1、二次循环班级，对没有设置排序的班级进行分班，
        for (BandingTaskClass taskClass : classList) {
            Integer number = taskClass.getNumber();//班级总人数
            if(classLimitMap.get(taskClass.getId()) != null){
                if(number > classLimitMap.get(taskClass.getId())){
                    number = classLimitMap.get(taskClass.getId());
                }
            }
            List<String> nameList = classNameMap.get(taskClass.getId());
            if(nameList.size() == number){
                continue;
            }
            for (BaseNewStudent newStudent : baseNewStudents) {
                //人数已满，进行下一个班级的的循环
                if(nameList.size() == number){
                    break;
                }
                //该学生已被分配
                if(studentClassMap.containsKey(newStudent.getId())){
                    continue;
                }
                if(ruleCodes.contains("BR0003") && nameList.contains(newStudent.getName())){
                    continue;
                }
                //专业不匹配，直接跳过
                if(!Objects.equals(taskClass.getMajorSetId(), newStudent.getFirstAmbitionId()) && !Objects.equals(taskClass.getMajorSetId(), newStudent.getSecondAmbitionId())){
                    continue;
                }
                //判断该班性别是否已满
                List<Boolean> conditionList = new ArrayList<>();
                BandingTaskMajorCondition condition = classConditionMap.get(taskClass.getMajorSetId());
                if(condition != null){
                    if(condition.getHeight() !=null && newStudent.getHeight() != null && newStudent.getHeight().compareTo(condition.getHeight()) >= 0 ){
                        conditionList.add(true);
                    }else if(condition.getHeight() !=null && newStudent.getHeight() != null && newStudent.getHeight().compareTo(condition.getHeight()) < 0){
                        conditionList.add(false);
                    }else if(condition.getHeight() !=null && newStudent.getHeight() == null){
                        conditionList.add(false);
                    }

                    if(condition.getScore() !=null && newStudent.getScore() != null && newStudent.getScore().compareTo(condition.getScore()) >= 0 ){
                        conditionList.add(true);
                    }else if(condition.getScore() !=null && newStudent.getScore() != null && newStudent.getScore().compareTo(condition.getScore()) < 0){
                        conditionList.add(false);
                    }else if(condition.getScore() !=null && newStudent.getScore() == null){
                        conditionList.add(false);
                    }
                }

                //如果包含false，则表明不符合条件，这个学生跳过
                if(conditionList.contains(false)){
                    continue;
                }
                studentClassMap.put(newStudent.getId(), taskClass.getId());
                nameList.add(newStudent.getName());
            }
        }


        List<BandingTaskClassStudent> dataList = new ArrayList<>();
        Date createDate = new Date();
        for (Long studentId : studentClassMap.keySet()) {
            dataList.add(
                    new BandingTaskClassStudent(){{
                        setBandingTaskClassId(studentClassMap.get(studentId));
                        setNewStudentId(studentId);
                        setStatus(0);
                        setCreateDate(createDate);
                    }}
            );
        }
        if(!dataList.isEmpty()){
            classStudentService.saveBatch(dataList);
        }

        return true;
    }

    /**
     * 按照成绩均衡划分学生
     * @return 班级id和学生
     */
    Map<Long, List<BaseNewStudent>> divideStudentByScore(Map<Long, BandingTaskMajorCondition> classConditionMap, List<BaseNewStudent> baseNewStudents,
                                                         List<BandingTaskClass> classList){
        Map<Long, List<BaseNewStudent>> classStudentMap = new HashMap<>();
        for (Long majorSetId : classConditionMap.keySet()) {
            //查询该专业下面有几个班级，把这部分学生按照成绩均匀分组
            List<List<BaseNewStudent>> result = new ArrayList<>();
            for (int i = 0; i < classList.size(); i++) {
                result.add(new ArrayList<>());
            }
            if(result.size() == 1){
                continue;
            }

            // 1、先把每个专业匹配的学生分组存一起，并按照分数高低排序
            List<BaseNewStudent> stuList = new ArrayList<>();

            for (BaseNewStudent newStudent : baseNewStudents) {
                if(!Objects.equals(majorSetId, newStudent.getFirstAmbitionId()) && !Objects.equals(majorSetId, newStudent.getSecondAmbitionId())){
                    continue;
                }

                List<Boolean> conditionList = new ArrayList<>();
                BandingTaskMajorCondition condition = classConditionMap.get(majorSetId);
                if(condition.getHeight() !=null && newStudent.getHeight() != null && newStudent.getHeight().compareTo(condition.getHeight()) >= 0 ){
                    conditionList.add(true);
                }else if(condition.getHeight() !=null && newStudent.getHeight() != null && newStudent.getHeight().compareTo(condition.getHeight()) < 0){
                    conditionList.add(false);
                }else if(condition.getHeight() !=null && newStudent.getHeight() == null){
                    conditionList.add(false);
                }

                if(condition.getScore() !=null && newStudent.getScore() != null && newStudent.getScore().compareTo(condition.getScore()) >= 0 ){
                    conditionList.add(true);
                }else if(condition.getScore() !=null && newStudent.getScore() != null && newStudent.getScore().compareTo(condition.getScore()) < 0){
                    conditionList.add(false);
                }else if(condition.getScore() !=null && newStudent.getScore() == null){
                    conditionList.add(false);
                }
                //如果包含false，则表明不符合条件，这个学生跳过
                if(conditionList.contains(false)){
                    continue;
                }
                stuList.add(newStudent);
            }
            if(!stuList.isEmpty()){
                for (BaseNewStudent student : stuList) {
                    if(student.getScore() == null){
                        student.setScore(BigDecimal.ZERO);
                    }
                }
                Collections.sort(stuList, (s1, s2) -> (int) (s2.getScore().doubleValue() - s1.getScore().doubleValue())); //按照成绩降序排序
            }

            for (int i = 0; i < stuList.size(); i++) {
                BaseNewStudent currentStudent = stuList.get(i);
                int classIndex = i % result.size(); //分配班级
                result.get(classIndex).add(currentStudent);
            }


            for (int i = 0; i < result.size(); i ++){
                classStudentMap.put(classList.get(i).getId(), result.get(i));
            }
        }

        return classStudentMap;
    }

    @Override
    public Boolean sure(SureBandingTaskDto dto) {
        List<BandingTaskClassStudent> classStudents = classStudentService.selectJoinList(BandingTaskClassStudent.class,
                new MPJLambdaWrapper<BandingTaskClassStudent>()
                        .select(BandingTaskClassStudent::getId)
                        .select(BandingTaskClassStudent.class, x -> VoToColumnUtil.fieldsToColumns(BandingTaskClassStudent.class).contains(x.getProperty()))
                        .leftJoin(BandingTaskClass.class, BandingTaskClass::getId, BandingTaskClassStudent::getBandingTaskClassId)
                        .eq(BandingTaskClass::getBandingTaskId, dto.getId())
                        .eq(BandingTaskClassStudent::getStatus, 0)
        );
        List<Long> studentIds = classStudents.stream().map(BandingTaskClassStudent::getNewStudentId).collect(Collectors.toList());
        if(studentIds.isEmpty()){
            throw new MyException("未能查询到学生，无法确认");
        }
        List<BaseNewStudent> list = newStudentService.list(
                new QueryWrapper<BaseNewStudent>().lambda()
                        .in(BaseNewStudent::getId, studentIds)
        );
        List<BaseNewStudent> updateList = new ArrayList<>();
        for (BaseNewStudent student : list) {
            student.setStatus(1);
            updateList.add(student);
        }

        if(!updateList.isEmpty()){
            newStudentService.updateBatchById(updateList);
        }

        //形成学生数据
        createStudentData(dto.getId(), classStudents, updateList);

        BandingTask bandingTask = this.getById(dto.getId());
        bandingTask.setStatus(1);
        bandingTask.setModifyDate(new Date());
        Boolean isSuccess = this.update(bandingTask);
        return isSuccess;
    }

    @Override
    public Page<BandingTaskPageVo> getPage(Page<BandingTaskPageVo> page, BandingTaskPageDto dto) {
        return this.baseMapper.getPage(page, dto);
    }

    void createStudentData(Long badingTaskId,List<BandingTaskClassStudent> classStudents, List<BaseNewStudent> updateList){
        Date createDate = new Date();
        BandingTask bandingTask = this.getById(badingTaskId);
        List<BandingTaskClassSureListVo> classSure = taskClassMapper.getClassSure(new BandingTaskClassStudentPageDto() {{
            setBandingTaskId(badingTaskId);
        }});

        Map<Long, Integer> classTotal = classSure.stream().collect(Collectors.toMap(BandingTaskClassSureListVo::getId, BandingTaskClassSureListVo::getNumber));
        Map<Long, Integer> classBoy = classSure.stream().collect(Collectors.toMap(BandingTaskClassSureListVo::getId, BandingTaskClassSureListVo::getMaleCount));
        Map<Long, Integer> classGirl = classSure.stream().collect(Collectors.toMap(BandingTaskClassSureListVo::getId, BandingTaskClassSureListVo::getFemaleCount));

        //生成班级数据
        Map<Long, Long> classMap = new HashMap<>();
        Map<Long, Long> taskClassMajorMap = new HashMap<>();
        //查询出需要新增的班级信息
        List<Long> classIds = classStudents.stream().map(BandingTaskClassStudent::getBandingTaskClassId).collect(Collectors.toList());
        List<BandingTaskClass> classList = taskClassMapper.selectList(new QueryWrapper<BandingTaskClass>().lambda().in(BandingTaskClass::getId, classIds));

        long maxCode = classService.count(
                new QueryWrapper<BaseClass>().lambda()
                        .eq(BaseClass::getGradeId, bandingTask.getGradeId())
        );
        BaseGrade baseGrade = gradeService.getById(bandingTask.getGradeId());
        String gradeCode = baseGrade.getTitle().replace("年", "");

        Map<Long, Long> majorDeptMap = majorSetMapper.selectList(new QueryWrapper<BaseMajorSet>()).stream().collect(Collectors.toMap(BaseMajorSet::getId, BaseMajorSet::getDepartmentId));
        for (BandingTaskClass taskClass : classList) {
            BaseClass baseClass = new BaseClass() {{
                setName(taskClass.getName());
                setClassroomId(taskClass.getClassroomId());
                setTeacherId(taskClass.getTeacherId());
                setIsGraduate(1);
                setIsOrderClass(taskClass.getIsOrderClass()==null?0:taskClass.getIsOrderClass().intValue());
                setGradeId(bandingTask.getGradeId());
                setDeleteMark(DeleteMark.NODELETE.getCode());
                setEnrollType(bandingTask.getEnrollType());
                setOrgId(majorDeptMap.get(taskClass.getMajorSetId()));
                setCode(gradeCode + String.format("%03d", maxCode));
            }};

            classService.save(baseClass);

            BaseClassMajorSet majorSet = new BaseClassMajorSet() {{
                setCreateDate(createDate);
                setMajorSetId(taskClass.getMajorSetId());
                setClassId(baseClass.getId());
                setPlanTotalStudent(taskClass.getNumber());
                setTotalStudent(classTotal.get(taskClass.getId()));
                setBoyNum(classBoy.get(taskClass.getId()));
                setGirlNum(classGirl.get(taskClass.getId()));
            }};
            classMajorSetMapper.insert(majorSet);

            classMap.put(taskClass.getId(), baseClass.getId());
            taskClassMajorMap.put(taskClass.getId(), taskClass.getMajorSetId());
        }

        /**
         * 新增学生数据
         * 1、新增用户xjr_user
         * 2、新增用户与角色的关系xjr_user_role_relation
         * 3、新增学生基本信息base_student
         * 4、新增学籍信息表base_student_school_roll
         * 5、新增家庭信息表base_student_family
         */
        LocalDateTime now = LocalDateTime.now();
        Map<Long, Long> studentClassRelation = classStudents.stream().collect(Collectors.toMap(BandingTaskClassStudent::getNewStudentId, BandingTaskClassStudent::getBandingTaskClassId));
        for (BaseNewStudent student : updateList) {
            LocalDate birthDate = getBirthDate(student.getCredentialNumber());
            User xjrUser = new User() {{
                setCreateDate(now);
                setPassword(BCrypt.hashpw(propertiesConfig.getDefaultPassword(), BCrypt.gensalt()));
                setName(student.getName());
                setUserName(student.getCredentialNumber());
                setCredentialNumber(student.getCredentialNumber());
                setCredentialType("ZZLS10007");
                setMobile(student.getMobile());
                setEnabledMark(EnabledMark.DISABLED.getCode());
                setGender(student.getGender());
                setIsChangePassword(1);
                setBirthDate(birthDate.atStartOfDay());
            }};
            userService.save(xjrUser);

            UserRoleRelation userRoleRelation = new UserRoleRelation() {{
                setRoleId(RoleEnum.STUDENT.getCode());
                setUserId(xjrUser.getId());
            }};
            roleRelationService.save(userRoleRelation);

            BaseStudent baseStudent = new BaseStudent() {{
                setUserId(xjrUser.getId());
                setCreateDate(now);
                setStudentId(student.getCredentialNumber());
                setHeight(student.getHeight().doubleValue());
                setWeight(student.getWeight().doubleValue());
            }};
            studentService.save(baseStudent);

            BaseStudentSchoolRoll schoolRoll = new BaseStudentSchoolRoll() {{
                setUserId(xjrUser.getId());
                if(student.getScore() != null){
                    setGraduatedScore(student.getScore().doubleValue());
                }
                setGraduatedUniversity(student.getGraduateSchool());
                setClassId(classMap.get(studentClassRelation.get(student.getId())));
                setMajorSetId(taskClassMajorMap.get(studentClassRelation.get(student.getId())));
                setStduyStatus(student.getStduyStatus());
                setEnrollType(bandingTask.getEnrollType());
                setStudentSource(student.getSource());
                setGradeId(bandingTask.getGradeId());
                setArchivesStatus(ArchivesStatusEnum.FB2901.getCode());
                setCreateDate(now);
            }};
            schoolRollService.save(schoolRoll);

            BaseStudentFamily studentFamily = new BaseStudentFamily() {{
                setCreateDate(now);
                setUserId(xjrUser.getId());
                setTelephone(student.getFamilyMobile());
                setAddress(student.getFamilyAddress());
            }};
            familyService.save(studentFamily);
        }
    }

    LocalDate getBirthDate(String idCardNumber){
        // 获取出生日期前6位，即yyyyMM
        String birthdayString = idCardNumber.substring(6, 14);

        // 将字符串解析为LocalDate对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        try {
            LocalDate parse = LocalDate.parse(birthdayString, formatter);
            return parse;
        }catch (Exception e){
            throw new MyException("身份证号填写错误，无法提取出生日期");
        }
    }
}
