package cn.teammodel.controller.admin.service.impl;

import cn.teammodel.common.ErrorCode;
import cn.teammodel.common.PK;
import cn.teammodel.config.exception.ServiceException;
import cn.teammodel.controller.admin.service.TeacherService;
import cn.teammodel.model.dto.admin.teacher.*;
import cn.teammodel.model.entity.User;
import cn.teammodel.model.entity.common.GroupList;
import cn.teammodel.model.entity.school.*;
import cn.teammodel.model.entity.teacher.HonorInfo;
import cn.teammodel.model.entity.teacher.PtTeacherInfo;
import cn.teammodel.model.vo.admin.GpTeacherVo;
import cn.teammodel.model.vo.admin.SugVo;
import cn.teammodel.model.vo.admin.TeacherGradeVo;
import cn.teammodel.repository.*;
import cn.teammodel.security.utils.SecurityUtil;
import cn.teammodel.test.AsyncTeacherService;
import cn.teammodel.test.LessonRecordQueryService;
import cn.teammodel.utils.GroupUtil;
import cn.teammodel.utils.SchoolDateUtil;
import com.azure.cosmos.models.CosmosPatchOperations;
import com.azure.cosmos.models.PartitionKey;
import com.azure.spring.data.cosmos.core.query.CosmosPageRequest;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Slice;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.teammodel.utils.SchoolDateUtil.calculateWeekNum;

@Service
public class TeacherServiceImpl implements TeacherService {
    @Resource
    private SchoolTeacherRepository schoolTeacherRepository;
    @Resource
    private SchoolGroupListRepository schoolGroupListRepository;
    @Resource
    private SchoolRepository  schoolRepository;
    @Resource
    private LessonRecordRepository lessonRecordRepository;
    @Resource
    private PtTeacherRepository  ptTeacherRepository;
    @Resource
    private TeacherRepository teacherRepository;
    /**
     * 学校试卷
     */
    @Resource
    private PaperSchoolRepository  paperSchoolRepository;
    /**
     * 个人试卷
     */
    @Resource
    private PaperTeacherRepository  paperTeacherRepository;

    @Autowired
    private AsyncTeacherService asyncTeacherService;
    @Autowired
    private Environment env;
    private static final double K = 0.08; // 衰减系数常量

    // 添加日志对象
    private static final Logger logger = LoggerFactory.getLogger(TeacherServiceImpl.class);

    // 引入缓存，需根据实际情况配置大小和过期时间 每次服务重启时  缓存会清空
    // 初始化Guava Cache
    private Cache<String, Map<String, Object>> teacherCache;

    @PostConstruct
    public void init() {
        teacherCache = CacheBuilder.newBuilder()
                .expireAfterWrite(1, TimeUnit.HOURS) // 缓存1小时
                .maximumSize(1000)                  // 最大缓存数量
                .build();
    }

    @Cacheable(value = "schoolGroupCache", key = "#code")
    public List<GroupList> getCachedGroupLists(String code) {
        return schoolGroupListRepository.findAllByCode("GroupList-" + code);
    }

    @Cacheable(value = "TeacherCache", key = "#code")
    public List<SchoolTeacher> getTeacherInfos(String code) {
        return schoolTeacherRepository.findAllByCode("Teacher-" + code);
    }

    @Override
    public List<Map<String, Integer>> getTeacherList(TeacherDto teacherDto) {
        List<Map<String, Integer>> result = new ArrayList<>();
        Map<String, Integer> teacherCountMap = new HashMap<>();
        //Map<String, Integer> groupCountMap = new HashMap<>();
        String code = String.format(PK.PTTEACHER, teacherDto.getCode());
       //List<GroupList> groupLists = getCachedGroupLists(code);
        List<PtTeacherInfo> ptTeacherInfos = ptTeacherRepository.findAllTeacher(teacherDto.getCode(),code);
       teacherCountMap.put("教师总人数", ptTeacherInfos.size());
       List<School> school = schoolRepository.findBaseById(teacherDto.getCode());
       List<School.Subject> subjects = new ArrayList<>();
       List<School.Period> periods = new ArrayList<>();
       for (School sc : school) {
           if (sc.getPeriod() != null) {
               // 遍历每个 Period 对象
               for (School.Period period : sc.getPeriod()) {
                   periods.add(period);
                   // 检查 period 是否有 subjects 列表
                   if (period.getSubjects() != null) {
                       // 将 period 中的 subjects 添加到总的 subjects 列表中
                       subjects.addAll(period.getSubjects());
                   }
               }
           }

       }

        Map<String, Integer> updatedSubjectCountMap = getStringIntegerMap(subjects, ptTeacherInfos);

        // 创建一个映射，用于存储每个职位的教师数量
        Map<String, Integer> jobCountMap = new HashMap<>();

        // 遍历所有教师
        for (PtTeacherInfo teacher : ptTeacherInfos) {
            // 获取教师的职位
            String job = teacher.getJob();
            if (job != null) {
                // 更新每个职位的教师数量
                jobCountMap.put(job, jobCountMap.getOrDefault(job, 0) + 1);
            }
        }
        jobCountMap.entrySet().removeIf(entry -> entry.getKey().isEmpty());
        Map<String, Integer> periodCountMap = getPeriodCountMap(periods,ptTeacherInfos);
//        for (GroupList groupList : groupLists) {
//            groupCountMap.put(groupList.getName(), groupList.getMembers().size());
//        }
        periodCountMap.entrySet().removeIf(entry -> entry.getKey().isEmpty());
        updatedSubjectCountMap.entrySet().removeIf(entry -> entry.getKey().isEmpty());
        result.add(updatedSubjectCountMap);
        result.add(jobCountMap);
        result.add(periodCountMap);
        result.add(teacherCountMap);
        //result.add(groupCountMap);
        return result;
    }

    @Override
    public Map<String, Object> compareData(TeacherDto teacherDto, HttpServletRequest request) {
        Map<String, Object> res = new HashMap<>();
        try {
            //从IES5获取相关教师基础信息
            String url = env.getProperty("ies.server-url-get-teacher-all");
            Map<String, Object> teacherInfos =GroupUtil.getGroupId(teacherDto, new GroupUtil(env), request, url);
            List<GpTeacherVo> existingTeachers = new ArrayList<>();
            if (teacherInfos != null) {
                //转换为GpTeacherVo对象数组
                List<GpTeacherVo> teachersList = convertToGpTeacherVoList(teacherInfos,  teacherDto.getCode());
                //过滤掉status为delete的数据
                teachersList = teachersList.stream()
                        .filter(t -> !t.getStatus().equals("delete"))
                        .collect(Collectors.toList());
                String code = String.format(PK.PTTEACHER, teacherDto.getCode());
                List<PtTeacherInfo> ptTeacherInfos = ptTeacherRepository.findAllTeacher(teacherDto.getCode(),code);
                //根据ID筛选出teachersList中不在ptTeacherInfos中的数据
                Set<String> ptIds = ptTeacherInfos.stream()
                        .map(PtTeacherInfo::getId)
                        .collect(Collectors.toSet());

                List<GpTeacherVo> result = teachersList.stream()
                        .filter(t -> !ptIds.contains(t.getId()))
                        .collect(Collectors.toList());
                res.put("Add", result);
                //根据source属性 筛选出ptTeacherInfos中source为ies 缺在teachersList没被找到的数据
                List<GpTeacherVo> finalTeachersList = teachersList;
                List<PtTeacherInfo> toDeactivate = ptTeacherInfos.stream()
                        .filter(pt -> pt.getSource().equals("ies"))
                        .filter(pt -> finalTeachersList.stream().noneMatch(t -> t.getId().equals(pt.getId())))
                        .collect(Collectors.toList());
                res.put("Delete", toDeactivate);

            }
            return res;
        }catch (Exception ex){
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "获取教师数据失败");
        }
    }

    @Override
    public List<GpTeacherVo> getTeacherFromIes(TeacherDto teacherDto, HttpServletRequest request) {
        List<GpTeacherVo> teachers = new ArrayList<>();
        try {
            //从IES5获取相关教师基础信息
            String url = env.getProperty("ies.server-url-get-teacher-all");
            Map<String, Object> teacherInfos = GroupUtil.getGroupId(teacherDto, new GroupUtil(env), request, url);
            if (teacherInfos != null) {
                //转换为GpTeacherVo对象数组
                teachers = convertToGpTeacherVoList(teacherInfos,  teacherDto.getCode());
            }
            return teachers;
        }catch(Exception ex){
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "获取教师数据失败");
        }
    }

    @Override
    public Map<String, Object> getTeacherDetail(TeacherDto teacherDto, HttpServletRequest request) {

        Map<String, Object> teachers = new HashMap<>();
        Map<String, Object> teacherInfos;
        String cacheKey = "teacher_data_" + teacherDto.getCode(); // 基于学校代码的缓存键
        try {
            try {
                // 尝试从缓存获取数据，若不存在则加载
                teacherInfos = teacherCache.get(cacheKey, () -> {
                    String url = env.getProperty("ies.server-url-get-teacher-all");
                    return GroupUtil.getGroupId(teacherDto, new GroupUtil(env), request, url);
                });
            } catch (ExecutionException e) {
                Throwable cause = e.getCause();
                if (cause instanceof ServiceException) {
                    throw (ServiceException) cause;
                } else {
                    throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "获取教师数据失败");
                }
            }
            List<GpTeacherVo> teachersList = convertToGpTeacherVoList(teacherInfos,  teacherDto.getCode());

            List<GpTeacherVo> copyList = new ArrayList<>(teachersList);
            // 同步保存，确保数据持久化
            asyncTeacherService.asyncSavePtTeacherInfos(Collections.unmodifiableList(copyList));
            String code = String.format(PK.PTTEACHER, teacherDto.getCode());
            List<PtTeacherInfo> ptTeacherInfos = ptTeacherRepository.findAllTeacher(teacherDto.getCode(),code);

            Map<String, Long> genderCount = ptTeacherInfos.stream()
                    .filter(gpTeacher -> gpTeacher.getGender() != null)
                    .collect(Collectors.groupingBy(PtTeacherInfo::getGender, Collectors.counting()));
            //移除key为U的键值对
            genderCount.remove("U");
            Map<String, Long> degreeCount = ptTeacherInfos.stream()
                    .filter(gpTeacher -> StringUtils.isNotEmpty(gpTeacher.getDegree()))
                    .collect(Collectors.groupingBy(PtTeacherInfo::getDegree, Collectors.counting()));
            teachers.put("gender", genderCount);
            teachers.put("degree", degreeCount);
            teachers.put("info", ptTeacherInfos);


        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");

        }
        return teachers;
    }


    private List<GpTeacherVo> convertToGpTeacherVoList(Map<String, Object> teachers,String code) {
        List<GpTeacherVo> teachersList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : teachers.entrySet()) {
            List<Map<String, Object>> mapList = (List<Map<String, Object>>) entry.getValue();
            for (Map<String, Object> map : mapList) {
                GpTeacherVo teacher = convertToGpTeacherVo(map,code);
                teachersList.add(teacher);
            }
        }
        return teachersList;
    }

    /*private List<GpTeacher> convertToGpTeacherList(Map<String, Object> tBase) {
        List<GpTeacher> gpTeachers = new ArrayList<>();
        for (Map.Entry<String, Object> entry : tBase.entrySet()) {
            if (entry.getKey().equals("teachers")) {
                List<Map<String, Object>> dataList = (List<Map<String, Object>>) entry.getValue();
                for (Map<String, Object> dataMap : dataList) {
                    GpTeacher gpTeacher = convertToGpTeacher(dataMap);
                    gpTeachers.add(gpTeacher);
                }
            }
        }
        return gpTeachers;
    }*/


    /*private void savePtTeacherInfosBatch(List<GpTeacherVo> teachersList) {
        // 预加载版本号
        Map<String, Integer> versionMap = loadExistingVersions(teachersList);

        List<PtTeacherInfo> ptTeacherInfos = teachersList.stream()
                .filter(t -> t.getId() != null)
                .map(t -> convertToPtTeacherInfo(t, versionMap))
                .collect(Collectors.toList());

        ptTeacherRepository.saveAll(ptTeacherInfos);
        ptTeacherInfos.forEach(pt -> PT_TEACHER_CACHE.put(pt.getCode(), pt));
    }*/

    /*private Map<String, Integer> loadExistingVersions(List<GpTeacherVo> teachersList) {
        // 收集所有id和code组合
        List<Pair<String, String>> idCodePairs = teachersList.stream()
                .filter(t -> t.getId() != null)
                .map(t -> Pair.of(t.getId(), "PtTeacher-" + t.getCode()))
                .collect(Collectors.toList());
        //将List<Pair<String, String>> 转化为 List<IdCodePair>
        List<IdCodePair> idAndCode = idCodePairs.stream()
                .map(pair -> new IdCodePair(pair.getLeft(), pair.getRight()))
                .collect(Collectors.toList());
        // 批量查询现有记录的版本号（需自定义Repository方法）
        List<PtTeacherInfo> existingList = ptTeacherRepository.findByIdCodePairs(idAndCode);

        // 转为Map<code, version>
        return existingList.stream()
                .collect(Collectors.toMap(
                        PtTeacherInfo::getCode,
                        PtTeacherInfo::getVersion
                ));
    }*/


    /*private PtTeacherInfo convertToPtTeacherInfo(GpTeacherVo teacher, Map<String, Integer> versionMap) {
        PtTeacherInfo ptTeacherInfo = new PtTeacherInfo();
        String code = "PtTeacher-" + teacher.getCode();
        ptTeacherInfo.setPk("PtTeacher");
        ptTeacherInfo.setTtl(-1);
        ptTeacherInfo.setCode(code);
        ptTeacherInfo.setId(teacher.getId());
        Integer currentVersion = versionMap.getOrDefault(code, 0);


        // 从缓存中获取现有对象
        PtTeacherInfo existingPtTeacherInfo = PT_TEACHER_CACHE.getIfPresent(ptTeacherInfo.getCode());
        if (existingPtTeacherInfo != null) {
            // 比较版本号，如果版本号相同则不需要更新
            if (Objects.equals(existingPtTeacherInfo.getVersion(), currentVersion)) {
                return existingPtTeacherInfo;
            }
        }
        //ptTeacherInfo.setVersion(currentVersion + 1);

        // 设置版本号
        ptTeacherInfo.setVersion(getNextVersion(ptTeacherInfo.getId(), ptTeacherInfo.getCode()));

        return ptTeacherInfo;
    }*/

   /* private Integer getNextVersion(String id,String code) {
        PtTeacherInfo existingPtTeacherInfo = ptTeacherRepository.findByIdAndCode(id,code);
        if (existingPtTeacherInfo != null) {
            return existingPtTeacherInfo.getVersion() + 1;
        }
        return 1;
    }

    private static @NotNull Map<String, Integer> getStringIntegerMap(TeacherDto teacherDto, List<GpTeacher> gpTeachers) {
        Map<String,Integer> practiceCount = new HashMap<>();
        for (GpTeacher gpTeacher : gpTeachers) {
            if(gpTeacher.practiceTime > 0) {
                // 将时间戳转换为 LocalDateTime
                LocalDateTime dateTime = LocalDateTime.ofInstant(
                        Instant.ofEpochMilli(gpTeacher.practiceTime),
                        ZoneId.systemDefault()
                );

                // 获取年份
                int year = dateTime.getYear();
                practiceCount.put(gpTeacher.basic.name, teacherDto.year - year);
            }
        }
        return practiceCount;
    }*/

    private GpTeacherVo convertToGpTeacherVo(Map<String, Object> map,String code) {
        GpTeacherVo teacher = new GpTeacherVo();
        // 假设 GpTeacherVo 有以下属性：name, age, subject
        teacher.setName((String) map.get("name"));
        teacher.setCode(code);
        teacher.setPhone((String) map.get("phone"));
        teacher.setId((String) map.get("id"));
        teacher.setEmail((String) map.get("email"));
        teacher.setPicture((String) map.get("picture"));
        teacher.setIname((String) map.get("iname"));
        teacher.setJob((String) map.get("job"));
        teacher.setStatus((String) map.get("status"));
        teacher.setRoles((List<String>) map.get("roles"));
        /*List<Map<String, Object>> groupList = (List<Map<String, Object>>) map.get("groups");
        if (groupList != null) {

            List<GpTeacherVo.IdNameCode> groups = new ArrayList<>();
            for (Map<String, Object> groupMap : groupList) {
                GpTeacherVo.IdNameCode group = new GpTeacherVo.IdNameCode();
                group.setId((String) groupMap.get("id"));
                group.setName((String) groupMap.get("name"));
                group.setCode((String) groupMap.get("code"));
                group.setPicture((String) groupMap.get("picture"));
                group.setNickname((String) groupMap.get("nickname"));
                groups.add(group);
            }
            teacher.setGroups(groups);
        }*/
        teacher.setNote((String) map.get("note"));
        teacher.setSubjectIds((List<String>) map.get("subjectIds"));
        teacher.setSubjectNames((List<String>) map.get("subjectNames"));
        // 根据实际属性进行转换
        return teacher;
    }

    private TeacherGradeVo convertToTeacherGradeVo(Map<String, Object> map) {
        TeacherGradeVo teacher = new TeacherGradeVo();
        teacher.setName((String) map.get("name"));
        teacher.setId((String) map.get("tmdId"));
        teacher.setPeriodId((String) map.get("periodId"));
        // 处理 grade 字段
        List<Map<String, Object>> gradeList = (List<Map<String, Object>>) map.get("grade");
        if (gradeList != null) {
            List<TeacherGradeVo.IdAndName> grades = new ArrayList<>();
            for (Map<String, Object> gradeMap : gradeList) {
                TeacherGradeVo.IdAndName grade = new TeacherGradeVo.IdAndName();
                grade.setGrade((Integer) gradeMap.get("grade"));
                grade.setGradeName((String) gradeMap.get("gradeName"));
                grades.add(grade);
            }
            teacher.setGrade(grades);
        }
        // 根据实际属性进行转换
        return teacher;
    }
    private GpTeacher convertToGpTeacher(Map<String, Object> map) {
        GpTeacher teacher = new GpTeacher();
        // 假设 GpTeacherVo 有以下属性：name, age, subject
        Object describeObj = map.get("describe");
        if (describeObj instanceof String) {
            teacher.setDescribe((String) describeObj);
        } else {
            teacher.setDescribe(null); // 或者设置一个默认值
        }
        Object IdObj = map.get("id");
        if (describeObj instanceof String) {
            teacher.setId((String) IdObj);
        } else {
            teacher.setId(null); // 或者设置一个默认值
        }
        Object depictObj = map.get("depict");
        if (depictObj instanceof String) {
            teacher.setDepict((String) depictObj);
        } else {
            teacher.setDepict(null); // 或者设置一个默认值
        }
        teacher.setPeriods((ArrayList<GpTeacher.GnericBase>) map.get("periods"));
        teacher.setSubjects((ArrayList<GpTeacher.GnericBase>) map.get("subjects"));
        teacher.setGrades((ArrayList<GpTeacher.GnericBase>) map.get("grades"));
        Object practiceTimeObj = map.get("practiceTime");
        if (practiceTimeObj instanceof Long) {
            teacher.setPracticeTime((Long) practiceTimeObj);
        } else {
            teacher.setPracticeTime(0L); // 或者设置一个默认值
        }
        Object titleObj = map.get("title");
        if (titleObj instanceof String) {
            teacher.setTitle((String) titleObj);
        } else {
            teacher.setTitle(null); // 或者设置一个默认值
        }
        Object mobileObj = map.get("mobile");
        if (mobileObj instanceof String) {
            teacher.setMobile((String) mobileObj);
        } else {
            teacher.setMobile(null); // 或者设置一个默认值
        }
        Object degreeObj = map.get("degree");
        if (degreeObj instanceof String) {
            teacher.setDegree((String) degreeObj);
        } else {
            teacher.setDegree(null); // 或者设置一个默认值
        }
        Map<String, Object> basicMap = (Map<String, Object>) map.get("basic");
        //teacher.setBasic(new GpTeacher.GPBasicInfo(basicMap.get("name").toString(),basicMap.get("fullName").toString(),basicMap.get("picture").toString(),basicMap.get("region").toString(),basicMap.get("province").toString(),basicMap.get("city").toString(),basicMap.get("dist").toString(),basicMap.get("gender").toString(),basicMap.get("age").toString(),basicMap.get("address").toString()));
        GpTeacher.GPBasicInfo basic = new GpTeacher.GPBasicInfo();
        Object nameObj = basicMap.get("name");
        if (nameObj instanceof String) {
            basic.setName((String) nameObj);
        } else {
            basic.setName(null); // 或者设置一个默认值
        }
        Object fullNameObj = basicMap.get("fullName");
        if (fullNameObj instanceof String) {
            basic.setFullName((String) fullNameObj);
        } else {
            basic.setFullName(null); // 或者设置一个默认值
        }
        Object distObj = basicMap.get("dist");
        if (distObj instanceof String) {
            basic.setDist((String) distObj);
        } else {
            basic.setDist(null); // 或者设置一个默认值
        }
        Object genderObj = basicMap.get("gender");
        if (genderObj instanceof String) {
            basic.setGender((String) genderObj);
        } else {
            basic.setGender(null); // 或者设置一个默认值
        }
        Object ageObj = basicMap.get("age");
        if (ageObj instanceof Integer) {
            basic.setAge((Integer) ageObj);
        } else {
            basic.setAge(0); // 或者设置一个默认值
        }
        teacher.basic = basic;


        // 根据实际属性进行转换
        return teacher;
    }

    @Override
    public Map<Long, Integer> getTeacherByRecord(TeacherDto teacherDto) {
        final int SLICE_SIZE = 10000;
        // 获取学期起止时间
        List<School.Semester> semesters = schoolRepository.findSemestersById(teacherDto.getCode(), teacherDto.getPeriodId());
        SchoolDateUtil.semesterModel semesterModel = SchoolDateUtil.getSemesterByNow(semesters, LocalDate.now());
        LocalDateTime startDatetime;
        LocalDateTime endDatetime;
        if(teacherDto.getStartTime() != null) {
            startDatetime = LocalDateTime.ofInstant(Instant.ofEpochMilli(teacherDto.getStartTime()), ZoneId.systemDefault());
            endDatetime = LocalDateTime.ofInstant(Instant.ofEpochMilli(teacherDto.getEndTime()), ZoneId.systemDefault());
        }else {
            startDatetime = semesterModel.getStartDatetime();
            endDatetime = semesterModel.getEndDatetime();
        }
        if (startDatetime == null || endDatetime == null) throw new ServiceException(ErrorCode.PARAMS_ERROR);
        long totalWeek = calculateWeekNum(startDatetime, endDatetime, null);

        // slice 分段读取
        CosmosPageRequest pageRequest = new CosmosPageRequest(0, SLICE_SIZE, null);
        Slice<LessonRecord> slice;
        Map<Long, Integer> countByWeek = SchoolDateUtil.createEmptyWeekMap(totalWeek);
        String lessonRecordKey = String.format(PK.PK_LESSON_RECORD, teacherDto.getCode());
        do {
            if(StringUtils.isNotEmpty(teacherDto.getGrade())) {
                slice = lessonRecordRepository.findAllByGrade(lessonRecordKey, teacherDto.getGrade(),teacherDto.getSubjectId(),teacherDto.getPeriodId(),pageRequest);
            } else if(StringUtils.isNotEmpty(teacherDto.getTmdId())) {
                slice = lessonRecordRepository.findAllByAcademicYearId(lessonRecordKey, teacherDto.getTmdId(),teacherDto.getSubjectId(),teacherDto.getPeriodId(),pageRequest);
            } else {
                slice = lessonRecordRepository.findAll(lessonRecordKey, teacherDto.getSubjectId(),teacherDto.getPeriodId(), pageRequest);
            }
            List<LessonRecord> content = slice.getContent();
            if (ObjectUtils.isEmpty(content)) {
                break;
            }

            // 分批次计算
            for (LessonRecord item : content) {
                long weekNum = calculateWeekNum(startDatetime, endDatetime, item.getStartTime());
                countByWeek.merge(weekNum, 1, Integer::sum); // 使用 merge 方法简化代码
            }

            if (slice.hasNext()) {
                pageRequest = (CosmosPageRequest) slice.nextPageable();
            }
        } while (slice.hasNext() && !Thread.currentThread().isInterrupted());
        countByWeek.entrySet().removeIf(entry -> entry.getKey() == -1);
        return countByWeek;
    }

    @Override
    public Map<String, Object> getTeacherLearningCategory(TeacherDto teacherDto) {

        Map<String, Object> LearningCategory = new HashMap<>(Collections.emptyMap());
        try {
            // 获取学期起止时间
            List<School.Semester> semesters = schoolRepository.findSemestersById(teacherDto.getCode(), teacherDto.getPeriodId());
            SchoolDateUtil.semesterModel semesterModel = SchoolDateUtil.getSemesterByNow(semesters, LocalDate.now());
            LocalDateTime startDatetime;
            LocalDateTime endDatetime;
            if(teacherDto.getStartTime() != null) {
                startDatetime = LocalDateTime.ofInstant(Instant.ofEpochMilli(teacherDto.getStartTime()), ZoneId.systemDefault());
                endDatetime = LocalDateTime.ofInstant(Instant.ofEpochMilli(teacherDto.getEndTime()), ZoneId.systemDefault());
            }else {
                startDatetime = semesterModel.getStartDatetime();
                endDatetime = semesterModel.getEndDatetime();
            }
            if (startDatetime == null || endDatetime == null) throw new ServiceException(ErrorCode.PARAMS_ERROR);

            // 将 LocalDateTime 转换为 Long 类型的时间戳
            long startTimestamp = startDatetime.toInstant(ZoneOffset.UTC).toEpochMilli();
            long endTimestamp = endDatetime.toInstant(ZoneOffset.UTC).toEpochMilli();
            List<LessonRecord> lessonRecords = new ArrayList<>();
            //List<LessonRecord> lessonRecords = lessonRecordRepository.getLessonsByConditions(String.format(PK.PK_LESSON_RECORD, teacherDto.getCode()), startTimestamp, endTimestamp, teacherDto.getSubjectId(),teacherDto.getTmdId(),teacherDto.getGrade(),teacherDto.getPeriodId());
            int[] counts = {0, 0, 0, 0, 0};
            String[] keys = {"cooperation", "internet", "task", "exam", "diffential"};

            for (LessonRecord record : lessonRecords) {
                if (record.getLearningCategory() != null) {
                    counts[0] += record.getLearningCategory().getCooperation();
                    counts[1] += record.getLearningCategory().getInteraction();
                    counts[2] += record.getLearningCategory().getTask();
                    counts[3] += record.getLearningCategory().getExam();
                    counts[4] += record.getLearningCategory().getDiffential();
                }
            }

            for (int i = 0; i < keys.length; i++) {
                LearningCategory.put(keys[i], counts[i]);
            }
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");

        }
        return LearningCategory;
    }

    @Override
    public Map<String, Object> getTeacherGradeCount(TeacherDto teacherDto, HttpServletRequest request) {

        Map<String, Object> gradeMap;
        String url = env.getProperty("ies.server-url-get-teacher-grade-count");
        try {
            gradeMap =  GroupUtil.getGroupId(teacherDto,new GroupUtil(env), request,url);
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");

        }
        return gradeMap;
    }

    @Override
    public List<Map<String,Map<String, Long>>> getDistributionOfTeachers(TeacherDto teacherDto, HttpServletRequest request) {

        List<Map<String,Map<String, Long>>> distributionList = new ArrayList<>();
        Map<String,Map<String, Long>>  gradesMap = new HashMap<>();
        Map<String,Map<String, Long>> degreesMap = new HashMap<>();
        Map<String,Map<String, Long>> subjectsMap= new HashMap<>();
        Map<String,Map<String, Long>> groupsMap = new HashMap<>();
        Map<String, Object> teachers;
        //获取全学校教师名单详情
        String url = env.getProperty("ies.server-url-get-teacher-all");
        try {
            teachers =  GroupUtil.getGroupId(teacherDto,new GroupUtil(env), request,url);
            List<GpTeacherVo> teachersList = new ArrayList<>();
            for (Map.Entry<String, Object> entry : teachers.entrySet()) {
                // 假设 entry.getValue() 返回的是 List<Map<String, Object>>
                List<Map<String, Object>> mapList = (List<Map<String, Object>>) entry.getValue();
                for (Map<String, Object> map : mapList) {
                    // 将 Map 转换为 GpTeacherVo 对象
                    GpTeacherVo teacher = convertToGpTeacherVo(map,teacherDto.getCode());
                    teachersList.add(teacher);
                }
            }
            List<String> phones = new ArrayList<>();
            // 进一步处理 teachersList
            for (GpTeacherVo teacher : teachersList) {
                phones.add(teacher.getPhone());
            }
            GpTeacherDto gpTeacherDto = new GpTeacherDto();
            gpTeacherDto.setMobiles(phones);
            Map<String, Object> tBase = getTeacherBase(gpTeacherDto, request);
            List<GpTeacher> gpTeachers = new ArrayList<>();
            for (Map.Entry<String, Object> entry : tBase.entrySet()) {
                if (entry.getKey().equals("teachers")) {
                    List<Map<String, Object>> dataList = (List<Map<String, Object>>) entry.getValue();
                    for (Map<String, Object> dataMap : dataList) {
                        GpTeacher gpTeacher = convertToGpTeacher(dataMap);
                        gpTeachers.add(gpTeacher);
                    }
                }
            }
            //把对应年级的信息进行映射
            List<TeacherGradeVo> gradeList = new ArrayList<>();
            Map<String,Object> gradeInfo =  getTeacherGradeCount(teacherDto, request);
            for (Map.Entry<String, Object> entry : gradeInfo.entrySet()) {
                if (entry.getKey().equals("teacher")) {
                    List<Map<String, Object>> dataList = (List<Map<String, Object>>) entry.getValue();
                    for (Map<String, Object> dataMap : dataList) {
                        TeacherGradeVo teacherGradeVo = convertToTeacherGradeVo(dataMap);
                        gradeList.add(teacherGradeVo);
                    }
                }
            }
            for (GpTeacherVo teacher : teachersList) {
                for(GpTeacher gpTeacher : gpTeachers) {
                    if(StringUtils.isNotEmpty(teacher.phone) && teacher.phone.equalsIgnoreCase(gpTeacher.mobile)) {
                        if(gpTeacher.basic.gender != null) {
                            teacher.setGender(gpTeacher.basic.gender);
                        }else {
                            teacher.setGender("");
                        }
                        if(gpTeacher.degree != null) {
                            teacher.setDegree(gpTeacher.degree);
                        }else {
                            teacher.setDegree("");
                        }
                        break;
                    }
                }
                for (TeacherGradeVo grade : gradeList) {
                    if(StringUtils.isNotEmpty(teacher.getId()) && teacher.getId().equals(grade.getId())) {
                        if(StringUtils.isNotEmpty(grade.getPeriodId())) {
                            teacher.setPeriodId(grade.getPeriodId());
                        }
                        List<TeacherGradeVo.IdAndName> grades = grade.getGrade();
                        for (TeacherGradeVo.IdAndName gg : grades) {
                            String id = String.valueOf(teacherDto.year - gg.getGrade());
                            if (teacher.grade == null) {
                                teacher.setGrade(new ArrayList<>());
                            }
                            teacher.grade.add(id);

                        }
                    }
                }
            }

            teachersList = teachersList.stream()
                    .filter(teacher -> teacherDto.periodId.equals(teacher.getPeriodId()))
                    .collect(Collectors.toList());
            Map<String, Long> gradeCount = new HashMap<>();
            Map<String, Long> degreeCount = new HashMap<>();
            Map<String, Long> subjectCount = new HashMap<>();
            Map<String, Long> GroupCount = new HashMap<>();
            if(StringUtils.isNotEmpty(teacherDto.getGrade()) && StringUtils.isNotEmpty(teacherDto.getSubjectId())) {
                for (GpTeacherVo teacher : teachersList) {
                    if(teacher.getGrade() != null &&teacher.getSubjectIds() != null &&teacher.getGrade().contains(teacherDto.getGrade()) && teacher.getSubjectIds().contains(teacherDto.getSubjectId())) {
                        {
                            Long count = gradeCount.getOrDefault(teacherDto.getGrade(), 0L);
                            gradeCount.put(teacherDto.getGrade(), count + 1);
                        }
                        if(StringUtils.isNotEmpty(teacher.getDegree())) {
                            {
                                Long count = degreeCount.getOrDefault(teacher.getDegree(), 0L);
                                degreeCount.put(teacher.getDegree(), count + 1);
                            }
                        }
                        {
                            int index = teacher.subjectIds.indexOf(teacherDto.getSubjectId());
                            String name = "";
                            if (index >= 0) {
                                name = teacher.subjectNames.get(index);
                            }
                            Long count = subjectCount.getOrDefault(name, 0L);
                            subjectCount.put(name, count + 1);
                        }
                        /*if(teacher.getGroups() != null) {
                            for (GpTeacherVo.IdNameCode group : teacher.getGroups()) {
                                Long count = GroupCount.getOrDefault(group.getName(), 0L);
                                GroupCount.put(group.getName(), count + 1);
                            }
                        }*/
                    }
                }
            }else if(StringUtils.isEmpty(teacherDto.getGrade()) && StringUtils.isNotEmpty(teacherDto.getSubjectId())) {
                for (GpTeacherVo teacher : teachersList) {
                    if(teacher.getSubjectIds() != null && teacher.getSubjectIds().contains(teacherDto.getSubjectId())) {
                        if(teacher.getGrade() != null) {
                            for (String grade : teacher.getGrade()) {
                                Long count = gradeCount.getOrDefault(grade, 0L);
                                gradeCount.put(grade, count + 1);
                            }
                        }
                        if(StringUtils.isNotEmpty(teacher.getDegree())) {
                            {
                                Long count = degreeCount.getOrDefault(teacher.getDegree(), 0L);
                                degreeCount.put(teacher.getDegree(), count + 1);
                            }
                        }
                        {
                            int index = teacher.subjectIds.indexOf(teacherDto.getSubjectId());
                            String name = "";
                            if (index >= 0) {
                                name = teacher.subjectNames.get(index);
                            }
                            Long count = subjectCount.getOrDefault(name, 0L);
                            subjectCount.put(name, count + 1);
                        }
                        /*if(teacher.getGroups() != null) {
                            for (GpTeacherVo.IdNameCode group : teacher.getGroups()) {
                                Long count = GroupCount.getOrDefault(group.getName(), 0L);
                                GroupCount.put(group.getName(), count + 1);
                            }
                        }*/
                    }
                }
                }else if(StringUtils.isNotEmpty(teacherDto.getGrade()) && StringUtils.isEmpty(teacherDto.getSubjectId())) {

                for (GpTeacherVo teacher : teachersList) {
                    if(teacher.getGrade() != null && teacher.getGrade().contains(teacherDto.getGrade())) {
                        {
                            Long count = gradeCount.getOrDefault(teacherDto.getGrade(), 0L);
                            gradeCount.put(teacherDto.getGrade(), count + 1);
                        }
                        if(StringUtils.isNotEmpty(teacher.getDegree())) {
                            {
                                Long count = degreeCount.getOrDefault(teacher.getDegree(), 0L);
                                degreeCount.put(teacher.getDegree(), count + 1);
                            }
                        }
                        if(teacher.getSubjectIds()!= null) {
                            for (String subjectId : teacher.getSubjectIds()) {
                                int index = teacher.subjectIds.indexOf(subjectId);
                                String name = "";
                                if (index >= 0) {
                                    name = teacher.subjectNames.get(index);
                                }
                                Long count = subjectCount.getOrDefault(name, 0L);
                                subjectCount.put(name, count + 1);
                            }
                        }
                      /*  if(teacher.getGroups() != null) {
                            for (GpTeacherVo.IdNameCode group : teacher.getGroups()) {
                                Long count = GroupCount.getOrDefault(group.getName(), 0L);
                                GroupCount.put(group.getName(), count + 1);
                            }
                        }*/
                    }
                }

            }else {
                for (GpTeacherVo teacher : teachersList) {
                    if(teacher.getGrade() != null) {
                        for (String grade : teacher.getGrade()) {
                            Long count = gradeCount.getOrDefault(grade, 0L);
                            gradeCount.put(grade, count + 1);
                        }
                    }
                        if(StringUtils.isNotEmpty(teacher.getDegree())) {
                            {
                                Long count = degreeCount.getOrDefault(teacher.getDegree(), 0L);
                                degreeCount.put(teacher.getDegree(), count + 1);
                            }
                        }
                        if(teacher.getSubjectIds()!= null) {
                            for (String subjectId : teacher.getSubjectIds()) {
                                int index = teacher.subjectIds.indexOf(subjectId);
                                String name = "";
                                if (index >= 0) {
                                    name = teacher.subjectNames.get(index);
                                }
                                Long count = subjectCount.getOrDefault(name, 0L);
                                subjectCount.put(name, count + 1);
                            }
                        }
                       /* if(teacher.getGroups() != null) {
                            for (GpTeacherVo.IdNameCode group : teacher.getGroups()) {
                                Long count = GroupCount.getOrDefault(group.getName(), 0L);
                                GroupCount.put(group.getName(), count + 1);
                            }
                        }*/

                }
            }
            gradeCount.keySet().removeIf(key -> key.startsWith("20"));
            gradesMap.put("grade", gradeCount);
            degreesMap.put("degree", degreeCount);
            subjectsMap.put("subject", subjectCount);
            groupsMap.put("group", GroupCount);
            distributionList.add(gradesMap);
            distributionList.add(degreesMap);
            distributionList.add(subjectsMap);
            distributionList.add(groupsMap);

           /* Map<String, Long> genderCount = gpTeachers.stream()
                    .collect(Collectors.groupingBy(gpTeacher -> gpTeacher.getBasic().getGender(), Collectors.counting()));
            Map<String, Long> degreeCount = gpTeachers.stream()
                    .filter(gpTeacher -> gpTeacher.getDegree() != null)
                    .collect(Collectors.groupingBy(GpTeacher::getDegree, Collectors.counting()));*/




        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");

        }
        return distributionList;
    }

    @Override
    public Map<String, Object> getTeachingAndResearch(TeacherDto teacherDto, HttpServletRequest request) {
        final int SLICE_SIZE = 1000;
        List<SugVo> sugVoList = getSugVos(teacherDto, request);
        //获取教师年级分配情况

        long startTimeOnline = System.currentTimeMillis(); // 记录开始时间
        Map<String, Object> Map = getTeacherGradeCount(teacherDto, request);
        User loginUser = SecurityUtil.getLoginUser();
        String loginId = loginUser.getId();
        List<TeacherGradeVo> gradeList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : Map.entrySet()) {
            if(entry.getKey().equals("teacher")) {
                List<Map<String, Object>> teacherList = (List<Map<String, Object>>) entry.getValue();
                for (Map<String, Object> statisticsMap : teacherList) {
                    TeacherGradeVo teacherGradeVo = convertToTeacherGradeVo(statisticsMap);
                    gradeList.add(teacherGradeVo);
                }
            }
        }
        List<LessonRecord> records;
        LessonRecordQueryService queryService = new LessonRecordQueryService(lessonRecordRepository);

        try {
            String lessonRecordKey = String.format(PK.PK_LESSON_RECORD, teacherDto.getCode());
            Long startTime = teacherDto.getStartTime();
            Long endTime = teacherDto.getEndTime();
            String subjectId = teacherDto.getSubjectId();
            String tmdId = teacherDto.getTmdId();
            String grade = teacherDto.getGrade();
            String periodId = teacherDto.getPeriodId();

            records = queryService.queryLessonsInParallel(
                    lessonRecordKey, startTime, endTime, subjectId, tmdId, grade, periodId
            );

            System.out.println("查询到的记录数量: " + records.size());
        } catch (InterruptedException | ExecutionException e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据查询异常");
        } finally {
            queryService.shutdown();
        }

        //试卷code
        String paperCode = "Paper-%s";

        //List<LessonRecord> lessonRecords = lessonRecordRepository.getLessonsByConditions(String.format(PK.PK_LESSON_RECORD, teacherDto.getCode()), teacherDto.getStartTime(), teacherDto.getEndTime(), teacherDto.getSubjectId(),teacherDto.getTmdId(),teacherDto.getGrade(),teacherDto.getPeriodId());
        if(teacherDto.getTmdId() != null) {
            //查询个人试卷  备注：若是后面影响速度，可以优化改代码
            int count = paperTeacherRepository.getPaperCount(String.format(paperCode, teacherDto.getTmdId()));
            List<SugVo> sugVos =  sugVoList.stream().filter(sugVo -> sugVo.getHabook().equals(teacherDto.getTmdId())).collect(Collectors.toList());
            LinkedHashMap<String,Object> mapTeach = new LinkedHashMap<>();
            int[] scores = new int[11];
            for (SugVo sugVo : sugVos) {
                scores[0] += sugVo.getT_data();
                scores[1] += sugVo.getT_green();
                scores[2] += sugVo.getT_duration();
                scores[3] += sugVo.getT_attendance();
                scores[4] += sugVo.getT_interaction();
                scores[5] += sugVo.getLesson_count();
                scores[6] += sugVo.getPublic_count();
                scores[7] += sugVo.getDouble_green_count();
                scores[8] += sugVo.getMaterial_count();
                scores[9] += sugVo.getTpcplan_count();
                if (sugVo.getObserve_lessons() != null) {
                    //采用set 去重课例ID
                    Set<String> observeLessons = new HashSet<>((List<String>) sugVo.getObserve_lessons());
                    // 如果后续需要使用 observeLessons，可以在此处添加逻辑
                    scores[10] += observeLessons.size();
                }

            }
            //T(数据)
            mapTeach.put("TData",scores[0]);
            //T（绿灯）
            mapTeach.put("TGreen",scores[1]);
            //总时长
            mapTeach.put("TDuration",scores[2]);
            //T(数据)学生人次
            mapTeach.put("TAttendance",scores[3]);
            //T(数据)互动次数
            mapTeach.put("TInteraction",scores[4]);

            mapTeach.put("LessonCount",scores[5]);
            mapTeach.put("PublicCount",scores[6]);
            mapTeach.put("DoubleGreenCount",scores[7]);
            mapTeach.put("MaterialCount",scores[8]);
            mapTeach.put("TpcplanCount",scores[9]);
            mapTeach.put("ObserveLessons",scores[10]);
            mapTeach.put("Lessons",records.size());
            //资源数量：试卷数量
            mapTeach.put("paperCount",count);
            // 检查 sugVos 是否为空
            if (!sugVos.isEmpty()) {
                //获取sugVos中starLevel不为空的值
                for( SugVo sugVo : sugVos){
                    if (sugVo.getStar_level() != null) {
                        mapTeach.put("starLevel", sugVo.getStar_level());
                        break; // 找到一个不为空的值就退出循环
                    }
                }
                //mapTeach.put("starLevel", sugVos.get(0).getStar_level());
            } else {
                // 处理空列表的情况，例如设置默认值
                mapTeach.put("starLevel", 0); // 或者其他默认值
            }
            return mapTeach;

        }else if(teacherDto.getGrade() != null) {
            //查询学校试卷 备注：若是后面影响速度，可以优化改代码
            int count = paperSchoolRepository.getPaperCount(String.format(paperCode, teacherDto.getCode()), loginId,teacherDto.getGrade(),"school",teacherDto.getPeriodId());
            List<String> teachers = new ArrayList<>();
            for (TeacherGradeVo gradeVo : gradeList) {
                for(TeacherGradeVo.IdAndName gradeId : gradeVo.getGrade()) {
                    if (gradeId.getGradeName().equals(teacherDto.getGradeName() )) {
                        teachers.add(gradeVo.getId());
                    }
                }
            }
            List<SugVo> filteredSugVoList = sugVoList.stream()
                    .filter(sugVo -> teachers.contains(sugVo.getHabook()))
                    .collect(Collectors.toList());
            LinkedHashMap<String,Object> mapTeach = new LinkedHashMap<>();
            int[] scores = new int[11];
            for (SugVo sugVo : filteredSugVoList) {
                scores[0] += sugVo.getT_data();
                scores[1] += sugVo.getT_green();
                scores[2] += sugVo.getT_duration();
                scores[3] += sugVo.getT_attendance();
                scores[4] += sugVo.getT_interaction();
                scores[5] += sugVo.getLesson_count();
                scores[6] += sugVo.getPublic_count();
                scores[7] += sugVo.getDouble_green_count();
                scores[8] += sugVo.getMaterial_count();
                scores[9] += sugVo.getTpcplan_count();
                if (sugVo.getObserve_lessons() != null) {
                    Set<String> observeLessons = new HashSet<>((List<String>) sugVo.getObserve_lessons());
                    // 如果后续需要使用 observeLessons，可以在此处添加逻辑
                    scores[10] += observeLessons.size();
                }
            }
            //T(数据)
            mapTeach.put("TData",scores[0]);
            //T（绿灯）
            mapTeach.put("TGreen",scores[1]);
            //总时长
            mapTeach.put("TDuration",scores[2]);
            //T(数据)学生人次
            mapTeach.put("TAttendance",scores[3]);
            //T(数据)互动次数
            mapTeach.put("TInteraction",scores[4]);
            mapTeach.put("LessonCount",scores[5]);
            mapTeach.put("PublicCount",scores[6]);
            mapTeach.put("DoubleGreenCount",scores[7]);
            mapTeach.put("MaterialCount",scores[8]);
            mapTeach.put("TpcplanCount",scores[9]);
            mapTeach.put("ObserveLessons",scores[10]);
            mapTeach.put("Lessons",records.size());
            //资源数量：试卷数量
            mapTeach.put("paperCount",count);

            return mapTeach;
        }else {
            //查询学校试卷   备注：若是后面影响速度，可以优化改代码
            int count = paperSchoolRepository.getPaperCount(String.format(paperCode, teacherDto.getCode()),loginId,null,"school",teacherDto.getPeriodId());
            LinkedHashMap<String, Object> mapTeach = new LinkedHashMap<>();
            int[] scores = new int[11];
            for (SugVo sugVo : sugVoList) {
                scores[0] += sugVo.getT_data();
                scores[1] += sugVo.getT_green();
                scores[2] += sugVo.getT_duration();
                scores[3] += sugVo.getT_attendance();
                scores[4] += sugVo.getT_interaction();
                scores[5] += sugVo.getLesson_count();
                scores[6] += sugVo.getPublic_count();
                scores[7] += sugVo.getDouble_green_count();
                scores[8] += sugVo.getMaterial_count();
                scores[9] += sugVo.getTpcplan_count();
                if (sugVo.getObserve_lessons() != null) {
                    Set<String> observeLessons = new HashSet<>((List<String>) sugVo.getObserve_lessons());
                    // 如果后续需要使用 observeLessons，可以在此处添加逻辑
                    scores[10] += observeLessons.size();
                }
            }
            //T(数据)
            mapTeach.put("TData", scores[0]);
            //T（绿灯）
            mapTeach.put("TGreen", scores[1]);
            //总时长
            mapTeach.put("TDuration", scores[2]);
            //T(数据)学生人次
            mapTeach.put("TAttendance", scores[3]);
            //T(数据)互动次数
            mapTeach.put("TInteraction", scores[4]);
            mapTeach.put("LessonCount",scores[5]);
            mapTeach.put("PublicCount",scores[6]);
            mapTeach.put("DoubleGreenCount",scores[7]);
            mapTeach.put("MaterialCount",scores[8]);
            mapTeach.put("TpcplanCount",scores[9]);
            mapTeach.put("ObserveLessons",scores[10]);
            mapTeach.put("Lessons",records.size());
            //资源数量：试卷数量
            mapTeach.put("paperCount",count);

            long endTime = System.currentTimeMillis(); // 记录结束时间
            long duration = endTime - startTimeOnline; // 计算耗时
            System.out.println("research 方法耗时: " + duration + " ms");
            return mapTeach;
        }
    }

    @Override
    public List<LinkedHashMap<String,LinkedHashMap<String,Object>>> getTeachingOfTeacher(TeacherDto teacherDto, HttpServletRequest request) {
        List<LinkedHashMap<String,LinkedHashMap<String,Object>>> list = new ArrayList<>();
        List<SugVo> sugVoList = getSugVos(teacherDto, request);
        //获取教师年级分配情况
        Map<String, Object> Map = getTeacherGradeCount(teacherDto, request);
        List<TeacherGradeVo> gradeList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : Map.entrySet()) {
            if(entry.getKey().equals("teacher")) {
                List<Map<String, Object>> teacherList = (List<Map<String, Object>>) entry.getValue();
                for (Map<String, Object> statisticsMap : teacherList) {
                   TeacherGradeVo teacherGradeVo = convertToTeacherGradeVo(statisticsMap);
                    gradeList.add(teacherGradeVo);
                }
            }
        }
        if(teacherDto.getTmdId() != null) {
            List<SugVo> sugVos =  sugVoList.stream().filter(sugVo -> sugVo.getHabook().equals(teacherDto.getTmdId())).collect(Collectors.toList());
            LinkedHashMap<String,Object> mapTeach = new LinkedHashMap<>();
            LinkedHashMap<String,LinkedHashMap<String,Object>> map = new LinkedHashMap<>();
            int[] scores = new int[7];
            for (SugVo sugVo : sugVos) {
                scores[0] += sugVo.getCooperation();
                scores[1] += sugVo.getInteraction();
                scores[2] += sugVo.getTask();
                scores[3] += sugVo.getExam();
                scores[4] += sugVo.getDiffential();
                scores[5] += sugVo.getSmartRating();
                scores[6] += sugVo.getCowork();
            }

            mapTeach.put("cooperation", scores[0]);
            mapTeach.put("interaction", scores[1]);
            mapTeach.put("task", scores[2]);
            mapTeach.put("exam", scores[3]);
            mapTeach.put("differential", scores[4]);
            mapTeach.put("smartRating", scores[5]);
            mapTeach.put("cowork", scores[6]);
            map.put(teacherDto.getTmdId(), mapTeach);
            list.add(map);
        }else {

            List<School> school = schoolRepository.findBaseById(teacherDto.getCode());
            List<String> grades = getGrades(teacherDto, school);
            LinkedHashMap<String,LinkedHashMap<String,Object>> map = new LinkedHashMap<>();
            for (String grade : grades) {
                List<String> teachers = new ArrayList<>();
                for (TeacherGradeVo gradeVo : gradeList) {
                    for(TeacherGradeVo.IdAndName gradeId : gradeVo.getGrade()) {
                        if (gradeId.getGradeName().equals(grade)) {
                            teachers.add(gradeVo.getId());
                        }
                    }
                }
                List<SugVo> filteredSugVoList = sugVoList.stream()
                        .filter(sugVo -> teachers.contains(sugVo.getHabook()))
                        .collect(Collectors.toList());
                LinkedHashMap<String,Object> mapTeach = new LinkedHashMap<>();
                int[] scores = new int[7]; // 索引 0: cooperation, 1: interaction, 2: task, 3: exam, 4: diffential, 5: smartRating, 6: cowork
                for (SugVo sugVo : filteredSugVoList) {
                    scores[0] += sugVo.getCooperation();
                    scores[1] += sugVo.getInteraction();
                    scores[2] += sugVo.getTask();
                    scores[3] += sugVo.getExam();
                    scores[4] += sugVo.getDiffential();
                    scores[5] += sugVo.getSmartRating();
                    scores[6] += sugVo.getCowork();
                }

                mapTeach.put("cooperation", scores[0]);
                mapTeach.put("interaction", scores[1]);
                mapTeach.put("task", scores[2]);
                mapTeach.put("exam", scores[3]);
                mapTeach.put("differential", scores[4]);
                mapTeach.put("smartRating", scores[5]);
                mapTeach.put("cowork", scores[6]);

                map.put(grade, mapTeach);
            }
            list.add(map);
        }

        return list;
    }

    @Override
    public Map<String, Object> getTeacherOfCapabilityAssessment(TeacherDto teacherDto, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 初始化四项数据
            double TData = 0, TGreen = 0, Lessons = 0, paperCount = 0,LessonCount = 0,DoubleGreenCount = 0,ObserveLessons = 0,PublicCount = 0;

            // 获取原始数据集合
            Map<String, Object> resMap = getTeachingAndResearch(teacherDto, request);

            GpTeacherDto gpTeacherDto = new GpTeacherDto();
            List<String> ownerIds = gpTeacherDto.getOwnerIds(); // 假设有一个 getOwnerIds 方法
            if (ownerIds == null) {
                ownerIds = new ArrayList<>();
            }
            ownerIds.add(teacherDto.getTmdId());
            gpTeacherDto.setOwnerIds(ownerIds);
            gpTeacherDto.setIds(ownerIds);
            gpTeacherDto.setSchoolId(teacherDto.getCode());


            // 遍历并提取八项数据
            for (Map.Entry<String, Object> entry : resMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof Integer) { // 类型安全校验
                    switch (key) {
                        case "TData": TData = (Integer) value; break;
                        case "TGreen": TGreen = (Integer) value; break;
                        case "Lessons": Lessons = (Integer) value; break;
                        case "paperCount": paperCount = (Integer) value; break;
                        case "LessonCount": LessonCount = (Integer) value; break;
                        case "DoubleGreenCount": DoubleGreenCount = (Integer) value; break;
                        case "ObserveLessons": ObserveLessons = (Integer) value; break;
                        case "PublicCount": PublicCount = (Integer) value; break;
                    }
                }
            }
            if (!StringUtils.isNotEmpty(teacherDto.getTmdId()) && !StringUtils.isNotEmpty(teacherDto.getGrade())) {
                Map<String, Object> detailMap = getTeacherDetail(teacherDto, request);
                List<GpTeacherVo> teachersList = new ArrayList<>();
                teachersList = (List<GpTeacherVo>) detailMap.get("info");
                TData = Math.round((TData / teachersList.size()) * 100.0) / 100.0;
                TGreen = Math.round((TGreen / teachersList.size()) * 100.0) / 100.0;
                Lessons = Math.round((Lessons / teachersList.size()) * 100.0) / 100.0;
                paperCount = Math.round((paperCount / teachersList.size()) * 100.0) / 100.0;
                LessonCount = Math.round((LessonCount / teachersList.size()) * 100.0) / 100.0;
                DoubleGreenCount = Math.round((DoubleGreenCount / teachersList.size()) * 100.0) / 100.0;
                ObserveLessons = Math.round((ObserveLessons / teachersList.size()) * 100.0) / 100.0;
                PublicCount = Math.round((PublicCount / teachersList.size()) * 100.0) / 100.0;
                List<String> ids = teachersList.stream()
                        .map(GpTeacherVo::getId)
                        .collect(Collectors.toList());
                gpTeacherDto.setOwnerIds(ids);
                gpTeacherDto.setIds(ids);
            }
            if (StringUtils.isNotEmpty(teacherDto.getGradeName())) {
                //调用年级相关接口数据
                Map<String, Object> gradeMap =  getTeacherGradeCount(teacherDto,request);
                Map<String, Object> gradeList = (Map<String, Object>) gradeMap.get("gradeCount");
                int count = (int) gradeList.get(teacherDto.getGradeName());
                List<Map<String, Object>> teachers = (List<Map<String, Object>>) gradeMap.get("teacher");
                List<String> tmdIds = new ArrayList<>();

                for (Map<String, Object> teacher : teachers) {
                    // 获取grade列表
                    Object gradeObj = teacher.get("grade");
                    if (!(gradeObj instanceof List)) {
                        continue;
                    }
                    List<Map<String, Object>> grades = (List<Map<String, Object>>) gradeObj;

                    // 检查是否存在匹配的年级
                    boolean isGradeMatch = grades.stream()
                            .anyMatch(grade ->
                                    teacherDto.getGradeName().equals(grade.get("gradeName"))
                            );

                    // 如果匹配且tmdId存在，则收集
                    if (isGradeMatch) {
                        Object tmdIdObj = teacher.get("tmdId");
                        if (tmdIdObj instanceof String) {
                            tmdIds.add((String) tmdIdObj);
                        }
                    }
                }
                if(count > 0) {
                    TData = Math.round((TData / count) * 100.0) / 100.0;
                    TGreen = Math.round((TGreen / count) * 100.0) / 100.0;
                    Lessons = Math.round((Lessons / count) * 100.0) / 100.0;
                    paperCount = Math.round((paperCount / count) * 100.0) / 100.0;
                    LessonCount = Math.round((LessonCount / count) * 100.0) / 100.0;
                    DoubleGreenCount = Math.round((DoubleGreenCount / count) * 100.0) / 100.0;
                    ObserveLessons = Math.round((ObserveLessons / count) * 100.0) / 100.0;
                    PublicCount = Math.round((PublicCount / count) * 100.0) / 100.0;
                }
                gpTeacherDto.setOwnerIds(tmdIds);
                gpTeacherDto.setIds(tmdIds);
                gpTeacherDto.setGradeIds(new ArrayList<>(Collections.singletonList( String.valueOf(Integer.parseInt(teacherDto.getGrade()) + 1))));
            }
            DoubleGreenCount = DoubleGreenCount * 10;


            /*if (!StringUtils.isNotEmpty(teacherDto.getGrade()) && StringUtils.isNotEmpty(teacherDto.getTmdId())) {
                //获取该tmdId下的年级信息
                Map<String, Object> gradeMap =  getTeacherGradeCount(teacherDto,request);
                List<Map<String, Object>> teachers = (List<Map<String, Object>>) gradeMap.get("teacher");
                List<Map<String, Object>> grades = teachers.stream()
                        .filter(teacher -> teacher.get("tmdId").equals(teacherDto.getTmdId()))
                        .findFirst()
                        .map(teacher -> (List<Map<String, Object>>) teacher.get("grade"))
                        .orElse(new ArrayList<>());
                //在根据当前tmdId获取的年级信息去筛选其他同属一个年级下的tmdId
                List<String> tmdIds = new ArrayList<>();
                for (Map<String, Object> grade : grades) {
                    String gradeCode = (String) grade.get("grade");
                    tmdIds = teachers.stream()
                            .filter(teacher -> {
                                Object gradeObj = teacher.get("grade");
                                if (!(gradeObj instanceof List)) {
                                    return false;
                                }
                                List<Map<String, Object>> gradeList = (List<Map<String, Object>>) gradeObj;
                                return gradeList.stream()
                                        .anyMatch(gradeItem ->
                                                gradeCode.equals(gradeItem.get("grade"))
                                        );
                            })
                            .map(teacher -> (String) teacher.get("tmdId"))
                            .collect(Collectors.toList());

                }
                gpTeacherDto.setOwnerIds(tmdIds);
                gpTeacherDto.setIds(tmdIds);
            }*/


            Map<String, Object> honor = getTeacherHonors(gpTeacherDto, request);
            List<HonorInfo> honors = new ArrayList<>();
            Object honorsObj = honor.get("honors");
            if (honorsObj instanceof List<?>) {
                List<?> rawHonors = (List<?>) honorsObj;

                for (Object item : rawHonors) {
                    if (item instanceof Map) {
                        Map<String, Object> map = (Map<String, Object>) item;
                        HonorInfo info = new HonorInfo();

                        // 手动设置属性，假设 HonorInfo 有对应的 setter 方法
                        info.setScore((Integer) map.get("score")); // 根据字段名称匹配
                        // 设置其他字段
                        // info.setHonorName((String) map.get("honorName"));
                        honors.add(info);
                    } else if (item instanceof HonorInfo) {
                        honors.add((HonorInfo) item);
                    }
                }
            }
            double honorScores = 0;
            for (HonorInfo honorInfo : honors) {
                double score = honorInfo.getScore().doubleValue();
                honorScores += score;
            }
            //研修分数获取
            double TrainingScore = 0;
            Map<String, Object> training = getTeacherTraining(gpTeacherDto, request);
            List<Map<String, Object>> trainings = (List<Map<String, Object>>) training.get("persons");
            if (trainings != null) {
                // 计算总分数
                for (Map<String, Object> trainingMap : trainings) {
                    Object scoreObj = trainingMap.get("studyHour");
                    Object isJoin = trainingMap.get("isJoin");
                    if(isJoin instanceof Boolean) {
                        if ((boolean) isJoin) {
                            double score = 60;
                            double hourScore = 0;
                            if (scoreObj instanceof Integer) {
                                int hour = (int) scoreObj;
                                if (hour > 0) {
                                    hourScore = 40 * (1 - Math.exp(-K * hour));
                                }
                            }
                            TrainingScore += (score + hourScore);
                        } else {
                            TrainingScore += 0;
                        }
                    }
                }
            }
            if (TrainingScore > 0) {
                TrainingScore = Math.round(TrainingScore / gpTeacherDto.getIds().size() * 100.0) / 100.0;
            }
            // 基础分计算
            honorScores = honorScores / gpTeacherDto.getIds().size();
            double honorScore =  honorScores > 0 ? Math.round(100.0 - (165.0 / (honorScores + 4.5))) : 60;

            // 计算各维度贡献值（使用指数衰减函数）
            double tDataScore = 25 * (1 - Math.exp(-K * TData));
            double tGreenScore = 50 * (1 - Math.exp(-K * TGreen));
            double lessonsScore = 15 * (1 - Math.exp(-K * Lessons));
            double paperScore = 10 * (1 - Math.exp(-K * paperCount));
            //计算教学贡献值
            // 基础分计算
            double baseScore = 40 * (1 - Math.exp(-K * DoubleGreenCount));

            // 附加分计算
            double lessonScore = 20 * (1 - Math.exp(-K * LessonCount));
            double materialScore = 30 * (1 - Math.exp(-K * ObserveLessons));
            double publicScore = 10 * (1 - Math.exp(-K * PublicCount));

            // 总分计算（不超过100）
            double totalTeachingScore = baseScore + lessonScore + materialScore + publicScore;
            totalTeachingScore = Math.round(totalTeachingScore * 100.0) / 100.0;
            totalTeachingScore = Math.min(totalTeachingScore, 100.0);

            // 计算总分（保留两位小数）
            double totalScore = tDataScore + tGreenScore + lessonsScore + paperScore;
            totalScore = Math.round(totalScore * 100.0) / 100.0; // 四舍五入

            // 特殊规则处理：TGreen>1时最低60分
            if (TGreen == 1 ) {
                totalScore = 60.0;
            }else if(TGreen > 1) {
                totalScore = 60 + totalScore * 0.4;
                totalScore = Math.round(totalScore * 100.0) / 100.0;
            }

            // 构建返回结果
            result.put("teachingScore", totalScore);
            result.put("researchScore", totalTeachingScore);
            result.put("honorScore", honorScore);
            result.put("trainingScore", TrainingScore);
            result.put("scientificScore", 60);


        } catch (Exception ex) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误: " + ex.getMessage());
        }
        return result;
    }

    @Override
    public void update(TeacherDto teacherDto) {
        try {
            String id = teacherDto.getTmdId();
            String code = String.format(PK.PTTEACHER, teacherDto.getCode());
            PtTeacherInfo ptTeacherInfo = ptTeacherRepository.findByIdAndCode(id, code);
            // 局部更新
            CosmosPatchOperations operations = CosmosPatchOperations.create();
            if (ptTeacherInfo != null) {
                operations.set("/identity", teacherDto.getIdentity());
            }
            ptTeacherRepository.save(id, new PartitionKey(code), PtTeacherInfo.class, operations);
        } catch (Exception ex) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据更新失败: " + ex.getMessage());
        }
    }

    @Override
    public Map<String, Object> findIdentityByTmdId(TeacherDto teacherDto) {
        try {
            String id = teacherDto.getTmdId();
            String code = String.format(PK.PTTEACHER, teacherDto.getCode());
            PtTeacherInfo ptTeacherInfo = ptTeacherRepository.findByIdAndCode(id, code);
            if (ptTeacherInfo != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("tmdId", id);
                result.put("identity", ptTeacherInfo.getIdentity());
                return result;
            }
        } catch (Exception ex) {
           throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据查询失败: " + ex.getMessage());
        }
        return Collections.emptyMap();
    }

    @Override
    public void delete(TeacherDto teacherDto) {
        try {
            String code = String.format(PK.PTTEACHER, teacherDto.getCode());
            List<PtTeacherInfo> ptTeacherInfo = ptTeacherRepository.findByCode(code);
            //删除查询出来的所有数据
            for (PtTeacherInfo ptTeacherInfo1 : ptTeacherInfo){
                ptTeacherRepository.delete(ptTeacherInfo1);
            }
        }catch (Exception ex) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据删除失败: " + ex.getMessage());
        }
    }

    @Override
    public List<GpTeacherVo> batchImportPtTeachers(List<GpTeacherVo> gpTeachers,HttpServletRequest request) {

        if (gpTeachers == null || gpTeachers.isEmpty()) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "导入数据为空");
        }
        // 获取当前登录用户信息
        User loginUser = SecurityUtil.getLoginUser();
        String operator = loginUser != null ? loginUser.getName() : "system";
        String schoolCode = SecurityUtil.getLoginUser().getSchoolId();
        logger.info("用户[{}]开始批量写入教师数据，数量：{}", operator, gpTeachers.size());

        // 检查导入数据中的教师电话号码是否重复

        Set<String> codeSet = new HashSet<>();
        for (GpTeacherVo teacher : gpTeachers) {
            String code = teacher.getPhone();
            if (StringUtils.isBlank(code)) {
                throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "教师电话号码不能为空");
            }
            if (!codeSet.add(code)) {
                throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "存在重复的电话号码: " + code);
            }
        }
        //获取手机号集合
        List<String> phoneNumbers = gpTeachers.stream()
                .map(GpTeacherVo::getPhone)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        //校验这些手机号码是否正常
        validatePhoneNumbers(phoneNumbers);
        //同理检查邮箱是否正确
        List<String> emails = gpTeachers.stream()
                .map(GpTeacherVo::getEmail)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        validateEmails(emails);

        //验证该手机号是否已在IES5中创建账号
        String url = env.getProperty("ies.server-url-get-core-user-data");
        List<Map<String, Object>> userData = GroupUtil.getUsers(phoneNumbers, new GroupUtil(env), request, url);

        //从userData中获取手机号 key 为 mobile
        // 提取所有已存在的 mobile 字段值
        Set<String> existingMobiles = userData.stream()
                .map(user -> (String) user.get("mobile"))
                .collect(Collectors.toSet());
        // 找出未返回的手机号
        List<String> missingPhones = phoneNumbers.stream()
                .filter(phone -> !existingMobiles.contains(phone))
                .collect(Collectors.toList());
        List<GpTeacherVo> missingPhonesGpTeachers = new ArrayList<>();
        if (!missingPhones.isEmpty()) {
            //创建一个集合，存储该手机号得对象
            missingPhonesGpTeachers = gpTeachers.stream()
                    .filter(t -> missingPhones.contains(t.getPhone()))
                    .collect(Collectors.toList());
            //剔除含有这些号码的gpTeachers对象
            gpTeachers.removeIf(t -> missingPhones.contains(t.getPhone()));
            //throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "手机号未在IES5中创建账号: " + String.join(", ", missingPhones));
        }

        if (gpTeachers.isEmpty()) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "手机号未在IES5中创建账号: " + String.join(", ", missingPhones));
            //return missingPhones;
        }
        // 提取 userData 中的 mobile 到 id 映射
        Map<String, String> mobileToIdMap = new HashMap<>();
        for (Map<String, Object> user : userData) {
            String mobile = (String) user.get("mobile");
            String id = (String) user.get("id");
            mobileToIdMap.put(mobile, id);
        }

        // 给 gpTeachers 对象赋值 id
        for (GpTeacherVo teacher : gpTeachers) {
            String phone = teacher.getPhone();
            String userId = mobileToIdMap.get(phone);
            if (userId != null) {
                teacher.setId(userId); // 将匹配到的 id 赋值给 gpTeachers 对象
            }
        }

        //从userData中获取手机号 key 为 mail 赋值给 gpTeachers 中每个对象中email，如果为空则赋值，不为空则跳过
        for (GpTeacherVo gpTeacher : gpTeachers) {
            final String phone = gpTeacher.getPhone();

            userData.stream()
                    .filter(user -> phone.equals(user.get("mobile")))
                    .findFirst()
                    .ifPresent(user -> {
                        if (StringUtils.isBlank(gpTeacher.getEmail())) {
                            gpTeacher.setEmail((String) user.get("mail"));
                        }
                        if (StringUtils.isBlank(gpTeacher.getName())) {
                            gpTeacher.setName((String) user.get("name"));
                        }
                        if (StringUtils.isBlank(gpTeacher.getPicture())) {
                            gpTeacher.setPicture((String) user.get("picture"));
                        }
                    });
        }


        List<Pair<String, String>> idCodePairs = gpTeachers.stream()
                .filter(t -> t.getId() != null)
                .map(t -> Pair.of(t.getId(), "PtTeacher-" + schoolCode))
                .collect(Collectors.toList());
        List<IdCodePair> idAndCode = idCodePairs.stream()
                .map(pair -> new IdCodePair(pair.getLeft(), pair.getRight()))
                .collect(Collectors.toList());
        List<PtTeacherInfo> existingList = ptTeacherRepository.findByIdCodePairs(idAndCode);

        Map<String, PtTeacherInfo> codeToTeacherMap = existingList.stream()
                .collect(Collectors.toMap(PtTeacherInfo::getId, Function.identity()));

        List<PtTeacherInfo> ptTeacherInfos = new ArrayList<>();
        for (GpTeacherVo teacher : gpTeachers) {
            // 数据校验
            if (StringUtils.isBlank(teacher.getName())) {
                throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "姓名不能为空");
            }

            String businessCode = "PtTeacher-" + schoolCode;
            PtTeacherInfo ptTeacherInfo = codeToTeacherMap.get(teacher.getId());

            if (ptTeacherInfo != null) {
                // 更新现有记录：保留ID，更新其他字段
                ptTeacherInfo.setName(teacher.getName());
                ptTeacherInfo.setPicture(teacher.getPicture());
                ptTeacherInfo.setSubjectIds(teacher.getSubjectIds());
                ptTeacherInfo.setSubjectNames(teacher.getSubjectNames());
                ptTeacherInfo.setDegree(teacher.getDegree());
                ptTeacherInfo.setGender(teacher.getGender());
                ptTeacherInfo.setGrade(teacher.getGrade());
                ptTeacherInfo.setGradeName(teacher.getGradeName());
                ptTeacherInfo.setPeriodId(teacher.getPeriodId());
                ptTeacherInfo.setAge(teacher.getAge());
                ptTeacherInfo.setTitle(teacher.getTitle());
                ptTeacherInfo.setTeachingAge(teacher.getTeachingAge());
                ptTeacherInfo.setJoinTime(teacher.getJoinTime());
                ptTeacherInfo.setSchool(schoolCode);
                ptTeacherInfo.setVersion(ptTeacherInfo.getVersion() + 1); // 版本号递增
            } else {
                // 新增记录：生成新ID
                ptTeacherInfo = new PtTeacherInfo();
                ptTeacherInfo.setId(teacher.getId());
                ptTeacherInfo.setCode(businessCode);
                ptTeacherInfo.setPk("PtTeacher");
                ptTeacherInfo.setTtl(-1);
                ptTeacherInfo.setName(teacher.getName());
                ptTeacherInfo.setPhone(teacher.getPhone());
                ptTeacherInfo.setEmail(teacher.getEmail());
                ptTeacherInfo.setPicture(teacher.getPicture());
                ptTeacherInfo.setJob(teacher.getJob());
                ptTeacherInfo.setSubjectIds(teacher.getSubjectIds());
                ptTeacherInfo.setSubjectNames(teacher.getSubjectNames());
                ptTeacherInfo.setRoles(teacher.getRoles());
                ptTeacherInfo.setDegree(teacher.getDegree());
                ptTeacherInfo.setGender(teacher.getGender());
                ptTeacherInfo.setGrade(teacher.getGrade());
                ptTeacherInfo.setGradeName(teacher.getGradeName());
                ptTeacherInfo.setPeriodId(teacher.getPeriodId());
                ptTeacherInfo.setAge(teacher.getAge());
                ptTeacherInfo.setTeachingAge(teacher.getTeachingAge());
                ptTeacherInfo.setStatus("join");
                ptTeacherInfo.setJoinTime(teacher.getJoinTime());
                ptTeacherInfo.setSchool(schoolCode);
                ptTeacherInfo.setTitle(teacher.getTitle());
                ptTeacherInfo.setSource("pt");
                ptTeacherInfo.setState(teacher.getState());
                ptTeacherInfo.setIdentity(Collections.singletonList("teacher"));
                ptTeacherInfo.setVersion(1);
            }
            ptTeacherInfos.add(ptTeacherInfo);
        }

        // 数据持久化日志
        logger.info("用户[{}]即将{}教师数据（新增：{}条，更新：{}条）",
                operator,
                existingList.isEmpty() ? "全部新增" : "批量更新",
                gpTeachers.size() - existingList.size(),
                existingList.size());
        ptTeacherRepository.saveAll(ptTeacherInfos);
        logger.info("用户[{}]成功完成教师数据写入，有效数据：{}条，缺失账号：{}条",
                operator,
                gpTeachers.size(),
                missingPhones.size());

        return missingPhonesGpTeachers;
    }

    @Override
    public List<Map<String, Object>> findTeachers(CoreUser dto,HttpServletRequest request) {
        List<Map<String, Object>> teachers;
        try {
            String url = env.getProperty("ies.server-url-get-core-user-data");
            teachers = GroupUtil.getUsers(dto.ids, new GroupUtil(env), request, url);
        }catch (Exception e){
            throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "查询数据异常");
        }
        return teachers;
    }

    @Override
    public List<PtTeacherInfo> saveOrUpdate(GpTeacherRequest gpTeachers, HttpServletRequest request) {

        List<PtTeacherInfo> missingTeachers = new ArrayList<>();
        try {
            // 获取当前登录用户信息
            User loginUser = SecurityUtil.getLoginUser();
            String operator = loginUser != null ? loginUser.getName() : "system";

            String schoolCode = SecurityUtil.getLoginUser().getSchoolId();

            List<Pair<String, String>> idCodePairs = gpTeachers.getGpTeacherDtos().stream()
                    .filter(t -> t.getId() != null)
                    .map(t -> Pair.of(t.getId(), "PtTeacher-" + schoolCode))
                    .collect(Collectors.toList());
            List<IdCodePair> idAndCode = idCodePairs.stream()
                    .map(pair -> new IdCodePair(pair.getLeft(), pair.getRight()))
                    .collect(Collectors.toList());
            List<PtTeacherInfo> existingList = ptTeacherRepository.findByIdCodePairs(idAndCode);

            Map<String, PtTeacherInfo> codeToTeacherMap = existingList.stream()
                    .collect(Collectors.toMap(PtTeacherInfo::getId, Function.identity()));
            // 根据传入的gpTeachers对象数据批量保存或更新PtTeacherInfo对象
            List<PtTeacherInfo> ptTeacherInfos = new ArrayList<>();

            //List<PtTeacherInfo> missingTeachers = new ArrayList<>();
            for (GpTeacherVo teacher : gpTeachers.getGpTeacherDtos()) {

                String businessCode = "PtTeacher-" + schoolCode;
                PtTeacherInfo ptTeacherInfo = codeToTeacherMap.get(teacher.getId());

                if (ptTeacherInfo != null) {
                    if (gpTeachers.getOpt().equalsIgnoreCase("save")) {
                        if (ptTeacherInfo.getState() == 2) {
                            ptTeacherInfo.setState(1);
                        }else {
                            missingTeachers.add(ptTeacherInfo);
                            continue;
                        }
                    }
                    // 更新现有记录：保留ID，更新其他字段
                    ptTeacherInfo.setName(teacher.getName());
                    ptTeacherInfo.setPicture(teacher.getPicture());
                    ptTeacherInfo.setSubjectIds(teacher.getSubjectIds());
                    ptTeacherInfo.setSubjectNames(teacher.getSubjectNames());
                    ptTeacherInfo.setDegree(teacher.getDegree());
                    ptTeacherInfo.setGender(teacher.getGender());
                    ptTeacherInfo.setGrade(teacher.getGrade());
                    ptTeacherInfo.setGradeName(teacher.getGradeName());
                    ptTeacherInfo.setPeriodId(teacher.getPeriodId());
                    ptTeacherInfo.setAge(teacher.getAge());
                    ptTeacherInfo.setTeachingAge(teacher.getTeachingAge());
                    ptTeacherInfo.setJoinTime(teacher.getJoinTime());
                    ptTeacherInfo.setTitle(teacher.getTitle());
                    ptTeacherInfo.setState(teacher.getState());
                    ptTeacherInfo.setSchool(schoolCode);
                    ptTeacherInfo.setVersion(ptTeacherInfo.getVersion() + 1); // 版本号递增
                } else {
                    // 新增记录：生成新ID
                    ptTeacherInfo = new PtTeacherInfo();
                    ptTeacherInfo.setId(teacher.getId());
                    ptTeacherInfo.setCode(businessCode);
                    ptTeacherInfo.setPk("PtTeacher");
                    ptTeacherInfo.setTtl(-1);
                    ptTeacherInfo.setName(teacher.getName());
                    ptTeacherInfo.setPhone(teacher.getPhone());
                    ptTeacherInfo.setEmail(teacher.getEmail());
                    ptTeacherInfo.setPicture(teacher.getPicture());
                    ptTeacherInfo.setJob(teacher.getJob());
                    ptTeacherInfo.setSubjectIds(teacher.getSubjectIds());
                    ptTeacherInfo.setSubjectNames(teacher.getSubjectNames());
                    ptTeacherInfo.setRoles(teacher.getRoles());
                    ptTeacherInfo.setDegree(teacher.getDegree());
                    ptTeacherInfo.setGender(teacher.getGender());
                    ptTeacherInfo.setGrade(teacher.getGrade());
                    ptTeacherInfo.setGradeName(teacher.getGradeName());
                    ptTeacherInfo.setPeriodId(teacher.getPeriodId());
                    ptTeacherInfo.setAge(teacher.getAge());
                    ptTeacherInfo.setTeachingAge(teacher.getTeachingAge());
                    ptTeacherInfo.setStatus("join");
                    ptTeacherInfo.setJoinTime(teacher.getJoinTime());
                    ptTeacherInfo.setSchool(schoolCode);
                    ptTeacherInfo.setState(teacher.getState());
                    ptTeacherInfo.setTitle(teacher.getTitle());
                    ptTeacherInfo.setSource(teacher.getSource());
                    ptTeacherInfo.setIdentity(Collections.singletonList("teacher"));
                    ptTeacherInfo.setVersion(1);
                }
                ptTeacherInfos.add(ptTeacherInfo);
            }

            // 数据持久化日志
            logger.info("用户[{}]即将{}教师数据（添加：{}条，更新：{}条）",
                    operator,
                    existingList.isEmpty() ? "新增" : "更新",
                    gpTeachers.getGpTeacherDtos().size() - existingList.size(),
                    existingList.size());
            ptTeacherRepository.saveAll(ptTeacherInfos);
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "保存数据异常");
        }
        return  missingTeachers;
    }

    @Override
    public void dataSync(GpTeacherRequest gpTeacherRequest, HttpServletRequest request) {
        String schoolCode = SecurityUtil.getLoginUser().getSchoolId();
        try {
           if (gpTeacherRequest.getOpt().equalsIgnoreCase("Add")) {
               List<SchoolTeacher> schoolTeachers =  new ArrayList<>();
               for (GpTeacherVo teacher : gpTeacherRequest.getGpTeacherDtos()) {
                   //处理新加入的学校教师
                   String code = String.format(PK.TEACHER, teacher.getCode());
                   SchoolTeacher schoolTeacher = new SchoolTeacher();
                   schoolTeacher.setName(teacher.getName());
                   schoolTeacher.setPicture(teacher.getPicture());
                   schoolTeacher.setJob(teacher.getJob());
                   schoolTeacher.setSubjectIds(teacher.getSubjectIds());
                   schoolTeacher.setPeriodId(teacher.getPeriodId());
                   schoolTeacher.setRoles(teacher.getRoles());
                   schoolTeacher.setStatus("join");
                   schoolTeacher.setCreateTime(System.currentTimeMillis());
                   schoolTeacher.setId(teacher.getId());
                   schoolTeacher.setCode(code);
                   schoolTeacher.setSize(0);
                   schoolTeacher.setPermissions(new ArrayList<>());
                   schoolTeachers.add(schoolTeacher);
               }
               schoolTeacherRepository.saveAll(schoolTeachers);
               //处理已存在教师得Base信息，先查询变更教师所有得Base信息
               List<String> teacherIds = gpTeacherRequest.getGpTeacherDtos().stream()
                       .map(GpTeacherVo::getId)
                       .collect(Collectors.toList());
               //获取学校简易信息
               List<School> schoolBases = schoolRepository.findBasePictureById(schoolCode);
               List<Teacher> BaseTeachers = teacherRepository.findAllByCodeAndIdIn(schoolCode,teacherIds);
               //检测teacherIds中的教师是否已存在BaseTeachers中
               List<String> missIds = teacherIds.stream()
                       .filter(id -> !BaseTeachers.stream().map(Teacher::getId).collect(Collectors.toList()).contains(id))
                       .collect(Collectors.toList());
               if (!missIds.isEmpty()) {
                   //根据missIds筛选出gpTeacherRequest.getGpTeacherDtos()的对象数组
                   List<GpTeacherVo> missTeachers = gpTeacherRequest.getGpTeacherDtos().stream()
                           .filter(teacher -> missIds.contains(teacher.getId()))
                           .collect(Collectors.toList());
                   List<Teacher> teachers = new ArrayList<>();
                   for (GpTeacherVo missTeacher : missTeachers) {
                       Teacher teacher = new Teacher();
                       teacher.setId(missTeacher.getId());
                       teacher.setName(missTeacher.getName());
                       teacher.setPicture(missTeacher.getPicture());
                       teacher.setDefaultSchool(schoolCode);
                       teacher.setCreateTime(System.currentTimeMillis());
                       teacher.setPk("Teacher");
                       teacher.setCode("Base");
                       teacher.setPicture(missTeacher.getPicture());
                       Teacher.School  school = new Teacher.School();
                       school.setSchoolId(schoolBases.get(0).getId());
                       school.setName(schoolBases.get(0).getName());
                       school.setPicture(schoolBases.get(0).getPicture());
                       school.setAreaId(schoolBases.get(0).getAreaId());
                       school.setStatus("join");
                       school.setTime(System.currentTimeMillis());
                       teacher.setSchools(Collections.singletonList(school));
                       Teacher.Area  area = new Teacher.Area();
                       area.setAreaId(schoolBases.get(0).getAreaId());
                       area.setName(schoolBases.get(0).getAreaId());
                       area.setStatus("join");
                       teacher.setArea(area);
                       teacher.setLoginInfos(new ArrayList<>());
                       teacher.setSize(0);
                       teachers.add(teacher);
                   }
                   teacherRepository.saveAll(teachers);
               }else {
                   BaseTeachers.forEach(teacher -> {
                       Teacher.School  school = new Teacher.School();
                       school.setSchoolId(schoolBases.get(0).getId());
                       school.setName(schoolBases.get(0).getName());
                       school.setPicture(schoolBases.get(0).getPicture());
                       school.setAreaId(schoolBases.get(0).getAreaId());
                       school.setStatus("join");
                       school.setTime(System.currentTimeMillis());
                       teacher.setSchools(Collections.singletonList(school));
                   });
                   teacherRepository.saveAll(BaseTeachers);
               }


           }else {
               //筛选出删除的教师ID
               List<String> teacherIds = gpTeacherRequest.getGpTeacherDtos().stream()
                       .map(GpTeacherVo::getId)
                       .collect(Collectors.toList());
               String code = String.format(PK.TEACHER, schoolCode);
               List<SchoolTeacher> schoolTeachers = schoolTeacherRepository.findAllByCodeAndIdIn(code,  teacherIds);
               //删除该对象数组
               schoolTeacherRepository.deleteAll(schoolTeachers);
               List<Teacher> teachers = teacherRepository.findAllByCodeAndIdIn(schoolCode, teacherIds);
               //移除teachers中含有schoolId为schoolCode的对象
               teachers = teachers.stream().filter(teacher -> !teacher.getSchools().stream()
                       .map(Teacher.School::getSchoolId).collect(Collectors.toList())
                       .contains(schoolCode)).collect(Collectors.toList());
               teacherRepository.saveAll(teachers);

           }
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "同步数据异常");
        }
    }

    // 手机号正则表达式（中国大陆）
    private static final String PHONE_REGEX = "^1\\d{10}$";
    /**
     * 校验手机号列表中的无效号码
     * @param phoneNumbers 手机号列表
     * @throws ServiceException 如果存在无效号码
     */
    public static void validatePhoneNumbers(List<String> phoneNumbers) {
        List<String> invalidPhones = phoneNumbers.stream()
                .filter(phone -> !isValidPhoneNumber(phone))
                .collect(Collectors.toList());

        if (!invalidPhones.isEmpty()) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "存在无效的手机号码: " + String.join(", ", invalidPhones));
        }
    }

    /**
     * 判断单个手机号是否合法
     * @param phone 手机号字符串
     * @return 是否有效
     */
    private static boolean isValidPhoneNumber(String phone) {
        return phone != null && phone.matches(PHONE_REGEX);
    }


    private static void validateEmails(List<String> emails) {
        List<String> invalidEmails = emails.stream()
                .filter(email -> !isValidEmail(email))
                .collect(Collectors.toList());

        if (!invalidEmails.isEmpty()) {
            throw new ServiceException(ErrorCode.PARAMS_ERROR.getCode(), "邮箱格式不正确: " + String.join(", ", invalidEmails));
        }
    }
    // 验证邮箱
    private static boolean isValidEmail(String email) {
        return StringUtils.isNotBlank(email) && email.matches("^[A-Za-z0-9+_.-]+@(.+)$");
    }

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    // 引入缓存，需根据实际情况配置大小和过期时间 每次服务重启时  缓存会清空
    private static final Cache<String, Map<String, Object>> REQUEST_CACHE = CacheBuilder.newBuilder()
            .maximumSize(500)
            .expireAfterWrite(8, TimeUnit.HOURS)
            .build();

    @NotNull
    private List<SugVo> getSugVos(TeacherDto teacherDto, HttpServletRequest request) {
        String url = env.getProperty("ies.server-url-get-channel-data");
        Map<String, Object> overView;
        List<SugVo> sugVoList = new ArrayList<>();
        try {
            // 处理时间参数
            Instant startInstant = Instant.ofEpochMilli(teacherDto.getStartTime());
            Instant endInstant = Instant.ofEpochMilli(teacherDto.getEndTime());
            ZoneId zoneId = ZoneId.of("Asia/Shanghai");
            String sTime = startInstant.atZone(zoneId).toLocalDate().format(DATE_FORMATTER);
            String eTime = endInstant.atZone(zoneId).toLocalDate().format(DATE_FORMATTER);
            teacherDto.duration.addAll(Arrays.asList(sTime, eTime));
            teacherDto.school_shortcode.add(teacherDto.getCode());

            // 生成缓存键，根据实际参数组合
            String cacheKey = generateCacheKey(teacherDto);
            overView = REQUEST_CACHE.get(cacheKey, () -> {
                // 缓存未命中时调用第三方接口
                return GroupUtil.getGroupId(teacherDto, new GroupUtil(env), request, url);
            });

            // 处理返回数据
            if (overView.containsKey("data")) {
                List<Map<String, Object>> dataList = (List<Map<String, Object>>) overView.get("data");
                // 使用并行流处理独立的dataMap（确保线程安全）
                dataList.parallelStream().forEach(dataMap -> {
                    List<Map<String, Object>> statisticsList = (List<Map<String, Object>>) dataMap.getOrDefault("statistics", Collections.emptyList());
                    List<Map<String, Object>> memberList = (List<Map<String, Object>>) dataMap.getOrDefault("member_list", Collections.emptyList());

                    // 构建habook到SugVo的映射
                    Map<String, SugVo> habookToSugVo = new ConcurrentHashMap<>();
                    List<SugVo> localSugVos = statisticsList.stream()
                            .map(this::convertToSugVo)
                            .collect(Collectors.toList());
                    localSugVos.forEach(sug -> habookToSugVo.put(sug.getHabook(), sug));

                    // 更新star_level
                    memberList.forEach(member -> {
                        String habook = (String) member.get("habook");
                        SugVo sug = habookToSugVo.get(habook);
                        if (sug != null) {
                            sug.setStar_level(Integer.parseInt(member.get("star_level").toString()));
                        }
                    });

                    // 将本地结果合并到主列表（需同步避免并发问题）
                    synchronized (sugVoList) {
                        sugVoList.addAll(localSugVos);
                    }
                });
            }
        } catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误");
        }
        return sugVoList;
    }

    // 生成缓存键
    private String generateCacheKey(TeacherDto dto) {
        return String.join(":",
                dto.getCode(),
                String.valueOf(dto.getStartTime()),
                String.valueOf(dto.getEndTime()));
    }

    private SugVo convertToSugVo(Map<String, Object> dataMap) {
        SugVo sugVo = new SugVo();
        sugVo.setDate(dataMap.get("date").toString());
        sugVo.setHabook(dataMap.get("habook").toString());
        sugVo.setT_data(Integer.parseInt(dataMap.get("t_data").toString()));
        sugVo.setT_green(Integer.parseInt(dataMap.get("t_green").toString()));
        sugVo.setT_duration(Integer.parseInt(dataMap.get("t_duration").toString()));
        sugVo.setT_attendance(Integer.parseInt(dataMap.get("t_attendance").toString()));
        sugVo.setT_interaction(Integer.parseInt(dataMap.get("t_interaction").toString()));
        sugVo.setCooperation(Integer.parseInt(dataMap.get("cooperation").toString()));
        sugVo.setInteraction(Integer.parseInt(dataMap.get("interaction").toString()));
        sugVo.setTask(Integer.parseInt(dataMap.get("task").toString()));
        sugVo.setExam(Integer.parseInt(dataMap.get("exam").toString()));
        sugVo.setDiffential(Integer.parseInt(dataMap.get("diffential").toString()));
        sugVo.setSmartRating(Integer.parseInt(dataMap.get("smartRating").toString()));
        sugVo.setCowork(Integer.parseInt(dataMap.get("cowork").toString()));
        sugVo.setLesson_count(Integer.parseInt(dataMap.get("lesson_count").toString()));
        sugVo.setPublic_count(Integer.parseInt(dataMap.get("public_count").toString()));
        sugVo.setDouble_green_count(Integer.parseInt(dataMap.get("double_green_count").toString()));
        sugVo.setMaterial_count(Integer.parseInt(dataMap.get("material_count").toString()));
        sugVo.setTpcplan_count(Integer.parseInt(dataMap.get("tpcplan_count").toString()));
        // 假设 dataMap.get("observe_lessons") 返回的是 JSON 字符串格式的数组
        Object observeLessonsObj = dataMap.get("observe_lessons");

        if (observeLessonsObj instanceof String) {
            // 如果是字符串，尝试解析为 List<String>
            try {
                String observeLessonsStr = (String) observeLessonsObj;
                List<String> observeLessonsList = new ObjectMapper().readValue(
                        observeLessonsStr, new TypeReference<List<String>>() {}
                );
                sugVo.setObserve_lessons(observeLessonsList);
            } catch (Exception e) {
                throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "数据转换错误: observe_lessons");
            }
        } else if (observeLessonsObj instanceof List) {
            // 如果已经是 List 类型，直接设置
            @SuppressWarnings("unchecked")
            List<String> observeLessonsList = (List<String>) observeLessonsObj;
            sugVo.setObserve_lessons(observeLessonsList);
        } else {
            // 如果类型不匹配，抛出异常或记录日志
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "observe_lessons 数据类型不匹配");
        }

        return sugVo;
    }

    private static @NotNull List<String> getGrades(TeacherDto teacherDto, List<School> school) {
        List<String> grades = new ArrayList<>();
        if(school != null && !school.isEmpty()) {
            for (School base : school) {
               for (School.Period period : base.getPeriod()) {
                   if(period.getId().equals(teacherDto.getPeriodId())) {
                       for(String grade : period.getGrades()) {
                           grades.add(grade.trim());
                       }
                   }
               }
            }
        }
        return grades;
    }

    public Map<String, Object> getTeacherBase(GpTeacherDto gpTeacherDto, HttpServletRequest request) {

        Map<String, Object> gradeMap;
        try {
            String url = "open_teacher/find";
            gpTeacherDto.setGrant_type("mobiles_infos");
            gradeMap =  GroupUtil.getTeacherInfo(gpTeacherDto,new GroupUtil(env), request, url);
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "国培数据转换错误");

        }
        return gradeMap;
    }

    //获取教师荣誉
    public Map<String, Object> getTeacherHonors(GpTeacherDto gpTeacherDto, HttpServletRequest request) {

        Map<String, Object> gradeMap;
        try {
            String url = "open_honor/find";
            gpTeacherDto.setGrant_type("list");
            gradeMap =  GroupUtil.getTeacherInfo(gpTeacherDto,new GroupUtil(env), request, url);
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "国培数据转换错误");

        }
        return gradeMap;
    }
    public Map<String, Object> getTeacherTraining(GpTeacherDto gpTeacherDto, HttpServletRequest request) {

        Map<String, Object> gradeMap;
        try {
            String url = "open_study/find";
            gpTeacherDto.setGrant_type("study_duration");
            gradeMap =  GroupUtil.getTeacherInfo(gpTeacherDto,new GroupUtil(env), request, url);
        }catch (Exception e) {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), "国培数据转换错误");

        }
        return gradeMap;
    }

    private static @NotNull Map<String, Integer> getStringIntegerMap(List<School.Subject> subjects, List<PtTeacherInfo> ptTeacherInfos) {
        Map<String, String> subjectNameMap = new HashMap<>();
        for (School.Subject subject : subjects) {
            subjectNameMap.put(subject.getId(), subject.getName());
        }
        Map<String, Integer> subjectCountMap = new HashMap<>();

        // 遍历所有教师
        for (PtTeacherInfo teacher : ptTeacherInfos) {
            // 获取教师的科目列表
            List<String> subjectIds = teacher.getSubjectIds();
            if (subjectIds != null) {
                for (String subjectId : subjectIds) {
                    // 更新每个科目的教师数量
                    subjectCountMap.put(subjectId, subjectCountMap.getOrDefault(subjectId, 0) + 1);
                }
            }
        }
        Map<String, Integer> updatedSubjectCountMap = new HashMap<>();
        for (Map.Entry<String, Integer> entry : subjectCountMap.entrySet()) {
            String subjectId = entry.getKey();
            Integer count = entry.getValue();
            String subjectName = subjectNameMap.get(subjectId);
            if (subjectName != null) {
                updatedSubjectCountMap.put(subjectName, count);
            }
        }
        return updatedSubjectCountMap;
    }

    private static @NotNull Map<String, Integer> getPeriodCountMap(List<School.Period> periods,List<PtTeacherInfo> ptTeacherInfos) {

        Map<String, Integer> periodCountMap = new HashMap<>();
        for (School.Period period : periods) {
            for ( School.Subject subject : period.getSubjects()) {
                for (PtTeacherInfo schoolTeacher : ptTeacherInfos) {
                    if (schoolTeacher.getSubjectIds().contains(subject.getId())) {
                        periodCountMap.put(period.getId(), periodCountMap.getOrDefault(period.getId(), 0) + 1);
                    }
                }
            }
        }
        Map<String, String> periodNameMap = new HashMap<>();
        List<String> periodNames = new ArrayList<>();
        for (School.Period period : periods) {
            periodNameMap.put(period.getId(), period.getName());
            periodNames.add(period.getName());
        }
        //Map<String, Integer> periodCountMap = getStringIntegerMap(groupLists);
        // 更新 periodCountMap 的 key 为 period 名称
        Map<String, Integer> updatedPeriodCountMap = new HashMap<>();
        for (Map.Entry<String, Integer> entry : periodCountMap.entrySet()) {
            String periodId = entry.getKey();
            Integer count = entry.getValue();
            String periodName = periodNameMap.get(periodId);
            if (periodName != null) {
                updatedPeriodCountMap.put(periodName, count);
            }
        }
        for (String periodName : periodNames) {
            if(!updatedPeriodCountMap.containsKey(periodName)) {
                updatedPeriodCountMap.put(periodName, 0);
            }
        }
        return updatedPeriodCountMap;
    }

    /*private static @NotNull Map<String, Integer> getStringIntegerMap(List<GroupList> groupLists) {
        Map<String, Integer> periodCountMap = new HashMap<>();
        // 遍历所有 GroupList 对象
        for (GroupList group : groupLists) {
            // 获取 periodId
            String periodId = group.getPeriodId();
            if (periodId != null) {
                    // 计算成员数量
                    int memberCount = (int) group.getMembers().stream().filter(member -> member.type == 1).count();
                    // 更新 periodCountMap
                    periodCountMap.put(periodId, periodCountMap.getOrDefault(periodId, 0) + memberCount);

            }
        }
        return periodCountMap;
    }*/
}
