package com.sundot.airport.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.SysHomeReportDetailDto;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.enums.DeptType;
import com.sundot.airport.common.enums.DeptTypeEnum;
import com.sundot.airport.common.enums.HomePageQueryEnum;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.common.utils.LargeScreenDateUtils;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.system.domain.SysLargeScreenLearningGrowthDto;
import com.sundot.airport.system.domain.SysLargeScreenLearningGrowthOrganizationalSupportDto;
import com.sundot.airport.system.domain.SysLargeScreenLearningGrowthQueryParamDto;
import com.sundot.airport.system.domain.SysLargeScreenLearningGrowthSqlDto;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sundot.airport.system.mapper.SysLearningGrowthMapper;
import com.sundot.airport.system.domain.SysLearningGrowth;
import com.sundot.airport.system.service.ISysLearningGrowthService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学习成长Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-22
 */
@Service
public class SysLearningGrowthServiceImpl implements ISysLearningGrowthService {
    @Autowired
    private SysLearningGrowthMapper sysLearningGrowthMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询学习成长
     *
     * @param id 学习成长主键
     * @return 学习成长
     */
    @Override
    public SysLearningGrowth selectSysLearningGrowthById(Long id) {
        return sysLearningGrowthMapper.selectSysLearningGrowthById(id);
    }

    /**
     * 查询学习成长列表
     *
     * @param sysLearningGrowth 学习成长
     * @return 学习成长
     */
    @Override
    public List<SysLearningGrowth> selectSysLearningGrowthList(SysLearningGrowth sysLearningGrowth) {
        return sysLearningGrowthMapper.selectSysLearningGrowthList(sysLearningGrowth);
    }

    /**
     * 新增学习成长
     *
     * @param sysLearningGrowth 学习成长
     * @return 结果
     */
    @Override
    public int insertSysLearningGrowth(SysLearningGrowth sysLearningGrowth) {
        sysLearningGrowth.setCreateTime(DateUtils.getNowDate());
        return sysLearningGrowthMapper.insertSysLearningGrowth(sysLearningGrowth);
    }

    /**
     * 修改学习成长
     *
     * @param sysLearningGrowth 学习成长
     * @return 结果
     */
    @Override
    public int updateSysLearningGrowth(SysLearningGrowth sysLearningGrowth) {
        sysLearningGrowth.setUpdateTime(DateUtils.getNowDate());
        return sysLearningGrowthMapper.updateSysLearningGrowth(sysLearningGrowth);
    }

    /**
     * 批量删除学习成长
     *
     * @param ids 需要删除的学习成长主键
     * @return 结果
     */
    @Override
    public int deleteSysLearningGrowthByIds(Long[] ids) {
        return sysLearningGrowthMapper.deleteSysLearningGrowthByIds(ids);
    }

    /**
     * 删除学习成长信息
     *
     * @param id 学习成长主键
     * @return 结果
     */
    @Override
    public int deleteSysLearningGrowthById(Long id) {
        return sysLearningGrowthMapper.deleteSysLearningGrowthById(id);
    }

    /**
     * 导入学习成长数据
     *
     * @param list            用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String importData(List<SysLearningGrowth> list, Boolean isUpdateSupport, String operName) {
        if (CollUtil.isEmpty(list)) {
            throw new ServiceException("导入学习成长数据不能为空！");
        }

        // 查询所有用户
        List<SysUser> sysUserList = sysUserService.selectUserAll();
        Map<String, String> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserName, SysUser::getNickName, (oldValue, newValue) -> newValue));

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysLearningGrowth sysLearningGrowth : list) {
            try {
                // 数据校验
                if (ObjUtil.isNull(sysLearningGrowth.getUserCode()) || ObjUtil.isNull(sysUserMap.getOrDefault(sysLearningGrowth.getUserCode(), null)) || !StrUtil.equals(sysUserMap.getOrDefault(sysLearningGrowth.getUserCode(), ""), sysLearningGrowth.getUserName())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、用户编号【" + sysLearningGrowth.getUserCode() + "】、用户名称【" + sysLearningGrowth.getUserName() + "】、考试编号【" + sysLearningGrowth.getExamCode() + "】用户编号或用户名称不存在或不匹配");
                    continue;
                }
                List<SysLearningGrowth> temp = sysLearningGrowthMapper.selectSysLearningGrowthList(sysLearningGrowth);
                if (CollUtil.isEmpty(temp)) {
                    sysLearningGrowth.setCreateBy(operName);
                    sysLearningGrowth.setCreateTime(DateUtils.getNowDate());
                    sysLearningGrowthMapper.insertSysLearningGrowth(sysLearningGrowth);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、用户编号【" + sysLearningGrowth.getUserCode() + "】、用户名称【" + sysLearningGrowth.getUserName() + "】、考试编号【" + sysLearningGrowth.getExamCode() + "】导入成功");
                } else if (isUpdateSupport) {
                    SysLearningGrowth old = temp.get(0);
                    sysLearningGrowth.setId(old.getId());
                    sysLearningGrowth.setUpdateBy(operName);
                    sysLearningGrowth.setUpdateTime(DateUtils.getNowDate());
                    sysLearningGrowthMapper.updateSysLearningGrowth(sysLearningGrowth);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、用户编号【" + sysLearningGrowth.getUserCode() + "】、用户名称【" + sysLearningGrowth.getUserName() + "】、考试编号【" + sysLearningGrowth.getExamCode() + "】更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、用户编号【" + sysLearningGrowth.getUserCode() + "】、用户名称【" + sysLearningGrowth.getUserName() + "】、考试编号【" + sysLearningGrowth.getExamCode() + "】已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、用户编号【" + sysLearningGrowth.getUserCode() + "】、用户名称【" + sysLearningGrowth.getUserName() + "】、考试编号【" + sysLearningGrowth.getExamCode() + "】导入失败:";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 能力画像-学习成长
     *
     * @param dto 上行参数
     * @return 能力画像-学习成长
     */
    @Override
    public List<SysLargeScreenLearningGrowthDto> portrait(SysLargeScreenLearningGrowthQueryParamDto dto) {
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeDays(91));
        }

        // 返回结果
        List<SysLargeScreenLearningGrowthDto> result = new ArrayList<>();

        SysLargeScreenLearningGrowthQueryParamDto tempQueryParam = new SysLargeScreenLearningGrowthQueryParamDto();
        tempQueryParam.setSpecifiedDate(dto.getSpecifiedDate());
        tempQueryParam.setStartDate(dto.getStartDate());
        tempQueryParam.setEndDate(dto.getEndDate());
        List<SysLargeScreenLearningGrowthSqlDto> all = sysLearningGrowthMapper.selectSysLearningGrowthListByCondition(tempQueryParam);
        if (CollUtil.isEmpty(all)) {
            return Collections.emptyList();
        }

        // 查询条件处理
        Long brigadeId = dto.getBrigadeId();
        Long departmentId = dto.getDepartmentId();
        Long teamId = dto.getTeamId();
        Long userId = dto.getUserId();
        if (ObjUtil.isNull(brigadeId) && ObjUtil.isNull(departmentId) && ObjUtil.isNull(teamId) && ObjUtil.isNull(userId)) {
            List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
            if (CollUtil.isEmpty(roles)) {
                return Collections.emptyList();
            }
            List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
            if (roleKeyList.contains(RoleTypeEnum.admin.getCode())) {

            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {

            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                brigadeId = SecurityUtils.getLoginUser().getDeptId();
                dto.setBrigadeId(brigadeId);
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                departmentId = SecurityUtils.getLoginUser().getDeptId();
                dto.setDepartmentId(departmentId);
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                teamId = SecurityUtils.getLoginUser().getDeptId();
                dto.setTeamId(teamId);
            } else if (roleKeyList.contains(RoleTypeEnum.SecurityCheck.getCode())) {
                userId = SecurityUtils.getLoginUser().getUserId();
                dto.setUserId(userId);
            } else {
                return Collections.emptyList();
            }
        } else {
            if (ObjUtil.isNotNull(userId)) {
                dto.setUserId(userId);
            } else if (ObjUtil.isNotNull(teamId)) {
                dto.setTeamId(teamId);
            } else if (ObjUtil.isNotNull(departmentId)) {
                dto.setDepartmentId(departmentId);
            } else if (ObjUtil.isNotNull(brigadeId)) {
                dto.setBrigadeId(brigadeId);
            } else {
                return Collections.emptyList();
            }
        }

        // 传入的用户角色为部门管理员时，则查询部门数据。其中班组长不做处理，由前端处理
        if (ObjUtil.isNotNull(userId)) {
            SysUser sysUser = sysUserService.selectUserById(userId);
            List<SysRole> roles = sysUser.getRoles();
            if (CollUtil.isNotEmpty(roles)) {
                List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
                if (roleKeyList.contains(RoleTypeEnum.admin.getCode()) || roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                    userId = null;
                    dto.setUserId(userId);
                } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                    userId = null;
                    dto.setUserId(userId);
                    brigadeId = sysUser.getDeptId();
                    dto.setBrigadeId(brigadeId);
                } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                    userId = null;
                    dto.setUserId(userId);
                    departmentId = sysUser.getDeptId();
                    dto.setDepartmentId(departmentId);
                } else {
                    // 保持原逻辑
                }
            }
        }

        // 个人
        if (ObjUtil.isNotNull(userId)) {
            Long finalUserId = userId;
            List<SysLargeScreenLearningGrowthSqlDto> target = all.stream()
                    .filter(item -> ObjUtil.equals(item.getUserId(), finalUserId))
                    .collect(Collectors.toList());
            if (CollUtil.isEmpty(target)) {
                return Collections.emptyList();
            }
            SysLargeScreenLearningGrowthDto resultItem = new SysLargeScreenLearningGrowthDto();
            resultItem.setId(userId);
            resultItem.setName(target.get(0).getUserName());
            resultItem.setHighestScore(target
                    .stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::max)
                    .orElse(BigDecimal.ZERO));
            resultItem.setLowestScore(target
                    .stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::min)
                    .orElse(BigDecimal.ZERO));
            resultItem.setAverageScore(target.stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::add)
                    .map(sum -> sum.divide(BigDecimal.valueOf(target.size()), 2, RoundingMode.HALF_UP))
                    .orElse(BigDecimal.ZERO));
            SysUser sysUser = sysUserService.selectUserById(userId);
            List<SysDept> deptList = sysDeptService.selectAllDept(sysUser.getDeptId());
            if (CollUtil.isNotEmpty(deptList)) {
                SysDept team = deptList.stream().filter(item -> StrUtil.equals(DeptType.TEAMS.getCode(), item.getDeptType())).findFirst().orElse(null);
                SysDept department = deptList.stream().filter(item -> StrUtil.equals(DeptType.MANAGER.getCode(), item.getDeptType())).findFirst().orElse(null);
                SysDept brigade = deptList.stream().filter(item -> StrUtil.equals(DeptType.BRIGADE.getCode(), item.getDeptType())).findFirst().orElse(null);
                SysDept station = deptList.stream().filter(item -> StrUtil.equals(DeptType.STATION.getCode(), item.getDeptType())).findFirst().orElse(null);
                // 本班排名处理
                if (ObjUtil.isNotNull(team)) {
                    List<SysLargeScreenLearningGrowthSqlDto> teamList = all.stream().filter(item -> ObjUtil.equals(item.getBzDeptId(), team.getDeptId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(teamList)) {
                        Map<Long, BigDecimal> avgMap = teamList.stream()
                                .filter(item -> item.getExamScore() != null)
                                .collect(Collectors.groupingBy(
                                        SysLargeScreenLearningGrowthSqlDto::getUserId,
                                        Collectors.collectingAndThen(
                                                Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                                avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                        )
                                ));
                        long count = avgMap.keySet().stream().count();
                        resultItem.setTeamTotal((int) count);
                        // 1. 按值升序排序
                        List<Map.Entry<Long, BigDecimal>> sortedEntries = avgMap.entrySet()
                                .stream()
                                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                                .collect(Collectors.toList());
                        // 2. 计算排名（考虑并列情况）
                        Map<Long, Integer> rankMap = new HashMap<>();
                        int currentRank = 1;
                        BigDecimal prevValue = null;
                        int sameValueCount = 1; // 记录相同值的用户数
                        for (int i = 0; i < sortedEntries.size(); i++) {
                            Map.Entry<Long, BigDecimal> entry = sortedEntries.get(i);
                            BigDecimal currentValue = entry.getValue();
                            if (prevValue != null && !currentValue.equals(prevValue)) {
                                // 如果当前值与前一个值不同，更新排名
                                currentRank += sameValueCount;
                                sameValueCount = 1;
                            } else if (prevValue != null) {
                                // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                                sameValueCount++;
                            }
                            // 存储用户ID和排名
                            rankMap.put(entry.getKey(), currentRank);
                            prevValue = currentValue;
                        }
                        // 3. 查询指定排名
                        Long targetId = userId;
                        Integer integer = rankMap.get(targetId);
                        resultItem.setTeamRanking(integer);
                    }
                }
                // 本科排名处理
                if (ObjUtil.isNotNull(department)) {
                    List<SysLargeScreenLearningGrowthSqlDto> departmentList = all.stream().filter(item -> ObjUtil.equals(item.getKsDeptId(), department.getDeptId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(departmentList)) {
                        Map<Long, BigDecimal> avgMap = departmentList.stream()
                                .filter(item -> item.getExamScore() != null)
                                .collect(Collectors.groupingBy(
                                        SysLargeScreenLearningGrowthSqlDto::getUserId,
                                        Collectors.collectingAndThen(
                                                Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                                avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                        )
                                ));
                        long count = avgMap.keySet().stream().count();
                        resultItem.setDepartmentTotal((int) count);
                        // 1. 按值升序排序
                        List<Map.Entry<Long, BigDecimal>> sortedEntries = avgMap.entrySet()
                                .stream()
                                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                                .collect(Collectors.toList());
                        // 2. 计算排名（考虑并列情况）
                        Map<Long, Integer> rankMap = new HashMap<>();
                        int currentRank = 1;
                        BigDecimal prevValue = null;
                        int sameValueCount = 1; // 记录相同值的用户数
                        for (int i = 0; i < sortedEntries.size(); i++) {
                            Map.Entry<Long, BigDecimal> entry = sortedEntries.get(i);
                            BigDecimal currentValue = entry.getValue();
                            if (prevValue != null && !currentValue.equals(prevValue)) {
                                // 如果当前值与前一个值不同，更新排名
                                currentRank += sameValueCount;
                                sameValueCount = 1;
                            } else if (prevValue != null) {
                                // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                                sameValueCount++;
                            }
                            // 存储用户ID和排名
                            rankMap.put(entry.getKey(), currentRank);
                            prevValue = currentValue;
                        }
                        // 3. 查询指定排名
                        Long targetId = userId;
                        Integer integer = rankMap.get(targetId);
                        resultItem.setDepartmentRanking(integer);
                    }
                }
                // 本大队排名处理
                if (ObjUtil.isNotNull(brigade)) {
                    List<SysLargeScreenLearningGrowthSqlDto> brigadeList = all.stream().filter(item -> ObjUtil.equals(item.getDdDeptId(), brigade.getDeptId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(brigadeList)) {
                        Map<Long, BigDecimal> avgMap = brigadeList.stream()
                                .filter(item -> item.getExamScore() != null)
                                .collect(Collectors.groupingBy(
                                        SysLargeScreenLearningGrowthSqlDto::getUserId,
                                        Collectors.collectingAndThen(
                                                Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                                avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                        )
                                ));
                        long count = avgMap.keySet().stream().count();
                        resultItem.setBrigadeTotal((int) count);
                        // 1. 按值升序排序
                        List<Map.Entry<Long, BigDecimal>> sortedEntries = avgMap.entrySet()
                                .stream()
                                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                                .collect(Collectors.toList());
                        // 2. 计算排名（考虑并列情况）
                        Map<Long, Integer> rankMap = new HashMap<>();
                        int currentRank = 1;
                        BigDecimal prevValue = null;
                        int sameValueCount = 1; // 记录相同值的用户数
                        for (int i = 0; i < sortedEntries.size(); i++) {
                            Map.Entry<Long, BigDecimal> entry = sortedEntries.get(i);
                            BigDecimal currentValue = entry.getValue();
                            if (prevValue != null && !currentValue.equals(prevValue)) {
                                // 如果当前值与前一个值不同，更新排名
                                currentRank += sameValueCount;
                                sameValueCount = 1;
                            } else if (prevValue != null) {
                                // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                                sameValueCount++;
                            }
                            // 存储用户ID和排名
                            rankMap.put(entry.getKey(), currentRank);
                            prevValue = currentValue;
                        }
                        // 3. 查询指定排名
                        Long targetId = userId;
                        Integer integer = rankMap.get(targetId);
                        resultItem.setBrigadeRanking(integer);
                    }
                }
                // 本站排名处理
                if (ObjUtil.isNotNull(station)) {
                    List<SysLargeScreenLearningGrowthSqlDto> stationList = all.stream().filter(item -> ObjUtil.equals(item.getZjDeptId(), station.getDeptId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(stationList)) {
                        Map<Long, BigDecimal> avgMap = stationList.stream()
                                .filter(item -> item.getExamScore() != null)
                                .collect(Collectors.groupingBy(
                                        SysLargeScreenLearningGrowthSqlDto::getUserId,
                                        Collectors.collectingAndThen(
                                                Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                                avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                        )
                                ));
                        long count = avgMap.keySet().stream().count();
                        resultItem.setStationTotal((int) count);
                        // 1. 按值升序排序
                        List<Map.Entry<Long, BigDecimal>> sortedEntries = avgMap.entrySet()
                                .stream()
                                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                                .collect(Collectors.toList());
                        // 2. 计算排名（考虑并列情况）
                        Map<Long, Integer> rankMap = new HashMap<>();
                        int currentRank = 1;
                        BigDecimal prevValue = null;
                        int sameValueCount = 1; // 记录相同值的用户数
                        for (int i = 0; i < sortedEntries.size(); i++) {
                            Map.Entry<Long, BigDecimal> entry = sortedEntries.get(i);
                            BigDecimal currentValue = entry.getValue();
                            if (prevValue != null && !currentValue.equals(prevValue)) {
                                // 如果当前值与前一个值不同，更新排名
                                currentRank += sameValueCount;
                                sameValueCount = 1;
                            } else if (prevValue != null) {
                                // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                                sameValueCount++;
                            }
                            // 存储用户ID和排名
                            rankMap.put(entry.getKey(), currentRank);
                            prevValue = currentValue;
                        }
                        // 3. 查询指定排名
                        Long targetId = userId;
                        Integer integer = rankMap.get(targetId);
                        resultItem.setStationRanking(integer);
                    }
                }
            }
            result.add(resultItem);
        } else if (ObjUtil.isNotNull(teamId)) {
            // 班组
            Long finalTeamId = teamId;
            List<SysLargeScreenLearningGrowthSqlDto> target = all.stream()
                    .filter(item -> ObjUtil.equals(item.getBzDeptId(), finalTeamId))
                    .collect(Collectors.toList());
            if (CollUtil.isEmpty(target)) {
                return Collections.emptyList();
            }
            SysLargeScreenLearningGrowthDto resultItem = new SysLargeScreenLearningGrowthDto();
            resultItem.setId(teamId);
            resultItem.setName(target.get(0).getBzDeptName());
            resultItem.setHighestScore(target
                    .stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::max)
                    .orElse(BigDecimal.ZERO));
            resultItem.setLowestScore(target
                    .stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::min)
                    .orElse(BigDecimal.ZERO));
            resultItem.setAverageScore(target.stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::add)
                    .map(sum -> sum.divide(BigDecimal.valueOf(target.size()), 2, RoundingMode.HALF_UP))
                    .orElse(BigDecimal.ZERO));

            // 本科排名处理
            SysDept sysDeptTeam = sysDeptService.selectDeptById(teamId);
            Long ksId = sysDeptTeam.getParentId();
            List<SysLargeScreenLearningGrowthSqlDto> departmentList = all.stream().filter(item -> ObjUtil.equals(item.getKsDeptId(), ksId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(departmentList)) {
                Map<Long, BigDecimal> avgMap = departmentList.stream()
                        .filter(item -> item.getExamScore() != null)
                        .collect(Collectors.groupingBy(
                                SysLargeScreenLearningGrowthSqlDto::getBzDeptId,
                                Collectors.collectingAndThen(
                                        Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                        avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                )
                        ));
                long count = avgMap.keySet().stream().count();
                resultItem.setDepartmentTotal((int) count);
                // 1. 按值升序排序
                List<Map.Entry<Long, BigDecimal>> sortedEntriesTeam = avgMap.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                        .collect(Collectors.toList());
                // 2. 计算排名（考虑并列情况）
                Map<Long, Integer> rankMapTeam = new HashMap<>();
                int currentRank = 1;
                BigDecimal prevValueTeam = null;
                int sameValueCount = 1; // 记录相同值的用户数
                for (int i = 0; i < sortedEntriesTeam.size(); i++) {
                    Map.Entry<Long, BigDecimal> entry = sortedEntriesTeam.get(i);
                    BigDecimal currentValue = entry.getValue();
                    if (prevValueTeam != null && !currentValue.equals(prevValueTeam)) {
                        // 如果当前值与前一个值不同，更新排名
                        currentRank += sameValueCount;
                        sameValueCount = 1;
                    } else if (prevValueTeam != null) {
                        // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                        sameValueCount++;
                    }
                    // 存储用户ID和排名
                    rankMapTeam.put(entry.getKey(), currentRank);
                    prevValueTeam = currentValue;
                }
                // 3. 查询指定排名
                Long targetId = teamId;
                Integer integer = rankMapTeam.get(targetId);
                resultItem.setDepartmentRanking(integer);
            }
            // 本大队排名处理
            SysDept sysDeptKs = sysDeptService.selectDeptById(ksId);
            Long ddId = sysDeptKs.getParentId();
            List<SysLargeScreenLearningGrowthSqlDto> brigadeList = all.stream().filter(item -> ObjUtil.equals(item.getDdDeptId(), ddId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(brigadeList)) {
                Map<Long, BigDecimal> avgMap = brigadeList.stream()
                        .filter(item -> item.getExamScore() != null)
                        .collect(Collectors.groupingBy(
                                SysLargeScreenLearningGrowthSqlDto::getBzDeptId,
                                Collectors.collectingAndThen(
                                        Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                        avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                )
                        ));
                long count = avgMap.keySet().stream().count();
                resultItem.setBrigadeTotal((int) count);
                // 1. 按值升序排序
                List<Map.Entry<Long, BigDecimal>> sortedEntriesTeam = avgMap.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                        .collect(Collectors.toList());
                // 2. 计算排名（考虑并列情况）
                Map<Long, Integer> rankMapTeam = new HashMap<>();
                int currentRank = 1;
                BigDecimal prevValueTeam = null;
                int sameValueCount = 1; // 记录相同值的用户数
                for (int i = 0; i < sortedEntriesTeam.size(); i++) {
                    Map.Entry<Long, BigDecimal> entry = sortedEntriesTeam.get(i);
                    BigDecimal currentValue = entry.getValue();
                    if (prevValueTeam != null && !currentValue.equals(prevValueTeam)) {
                        // 如果当前值与前一个值不同，更新排名
                        currentRank += sameValueCount;
                        sameValueCount = 1;
                    } else if (prevValueTeam != null) {
                        // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                        sameValueCount++;
                    }
                    // 存储用户ID和排名
                    rankMapTeam.put(entry.getKey(), currentRank);
                    prevValueTeam = currentValue;
                }
                // 3. 查询指定排名
                Long targetId = teamId;
                Integer integer = rankMapTeam.get(targetId);
                resultItem.setBrigadeRanking(integer);
            }
            // 本站排名处理
            SysDept sysDeptDepartment = sysDeptService.selectDeptById(ksId);
            Long stationId = sysDeptDepartment.getParentId();
            List<SysLargeScreenLearningGrowthSqlDto> stationList = all.stream().filter(item -> ObjUtil.equals(item.getZjDeptId(), stationId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(stationList)) {
                Map<Long, BigDecimal> avgMap = stationList.stream()
                        .filter(item -> item.getExamScore() != null)
                        .collect(Collectors.groupingBy(
                                SysLargeScreenLearningGrowthSqlDto::getBzDeptId,
                                Collectors.collectingAndThen(
                                        Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                        avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                )
                        ));
                long count = avgMap.keySet().stream().count();
                resultItem.setStationTotal((int) count);
                // 1. 按值升序排序
                List<Map.Entry<Long, BigDecimal>> sortedEntriesTeam = avgMap.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                        .collect(Collectors.toList());
                // 2. 计算排名（考虑并列情况）
                Map<Long, Integer> rankMapTeam = new HashMap<>();
                int currentRank = 1;
                BigDecimal prevValueTeam = null;
                int sameValueCount = 1; // 记录相同值的用户数
                for (int i = 0; i < sortedEntriesTeam.size(); i++) {
                    Map.Entry<Long, BigDecimal> entry = sortedEntriesTeam.get(i);
                    BigDecimal currentValue = entry.getValue();
                    if (prevValueTeam != null && !currentValue.equals(prevValueTeam)) {
                        // 如果当前值与前一个值不同，更新排名
                        currentRank += sameValueCount;
                        sameValueCount = 1;
                    } else if (prevValueTeam != null) {
                        // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                        sameValueCount++;
                    }
                    // 存储用户ID和排名
                    rankMapTeam.put(entry.getKey(), currentRank);
                    prevValueTeam = currentValue;
                }
                // 3. 查询指定排名
                Long targetId = teamId;
                Integer integer = rankMapTeam.get(targetId);
                resultItem.setStationRanking(integer);
            }
            result.add(resultItem);
        } else if (ObjUtil.isNotNull(departmentId)) {
            // 科级
            Long finalDepartmentId = departmentId;
            List<SysLargeScreenLearningGrowthSqlDto> target = all.stream()
                    .filter(item -> ObjUtil.equals(item.getKsDeptId(), finalDepartmentId))
                    .collect(Collectors.toList());
            if (CollUtil.isEmpty(target)) {
                return Collections.emptyList();
            }
            SysLargeScreenLearningGrowthDto resultItem = new SysLargeScreenLearningGrowthDto();
            resultItem.setId(departmentId);
            resultItem.setName(target.get(0).getKsDeptName());
            resultItem.setHighestScore(target
                    .stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::max)
                    .orElse(BigDecimal.ZERO));
            resultItem.setLowestScore(target
                    .stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::min)
                    .orElse(BigDecimal.ZERO));
            resultItem.setAverageScore(target.stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::add)
                    .map(sum -> sum.divide(BigDecimal.valueOf(target.size()), 2, RoundingMode.HALF_UP))
                    .orElse(BigDecimal.ZERO));
            // 本大队排名处理
            SysDept sysDeptKs = sysDeptService.selectDeptById(departmentId);
            Long ddId = sysDeptKs.getParentId();
            List<SysLargeScreenLearningGrowthSqlDto> brigadeList = all.stream().filter(item -> ObjUtil.equals(item.getDdDeptId(), ddId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(brigadeList)) {
                Map<Long, BigDecimal> avgMap = brigadeList.stream()
                        .filter(item -> item.getExamScore() != null)
                        .collect(Collectors.groupingBy(
                                SysLargeScreenLearningGrowthSqlDto::getKsDeptId,
                                Collectors.collectingAndThen(
                                        Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                        avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                )
                        ));
                long count = avgMap.keySet().stream().count();
                resultItem.setBrigadeTotal((int) count);
                // 1. 按值升序排序
                List<Map.Entry<Long, BigDecimal>> sortedEntriesTeam = avgMap.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                        .collect(Collectors.toList());
                // 2. 计算排名（考虑并列情况）
                Map<Long, Integer> rankMapTeam = new HashMap<>();
                int currentRank = 1;
                BigDecimal prevValueTeam = null;
                int sameValueCount = 1; // 记录相同值的用户数
                for (int i = 0; i < sortedEntriesTeam.size(); i++) {
                    Map.Entry<Long, BigDecimal> entry = sortedEntriesTeam.get(i);
                    BigDecimal currentValue = entry.getValue();
                    if (prevValueTeam != null && !currentValue.equals(prevValueTeam)) {
                        // 如果当前值与前一个值不同，更新排名
                        currentRank += sameValueCount;
                        sameValueCount = 1;
                    } else if (prevValueTeam != null) {
                        // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                        sameValueCount++;
                    }
                    // 存储用户ID和排名
                    rankMapTeam.put(entry.getKey(), currentRank);
                    prevValueTeam = currentValue;
                }
                // 3. 查询指定排名
                Long targetId = departmentId;
                Integer integer = rankMapTeam.get(targetId);
                resultItem.setBrigadeRanking(integer);
            }
            result.add(resultItem);
            // 本站排名处理
            SysDept sysDeptBrigade = sysDeptService.selectDeptById(ddId);
            Long stationId = sysDeptBrigade.getParentId();
            List<SysLargeScreenLearningGrowthSqlDto> stationList = all.stream().filter(item -> ObjUtil.equals(item.getZjDeptId(), stationId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(stationList)) {
                Map<Long, BigDecimal> avgMap = stationList.stream()
                        .filter(item -> item.getExamScore() != null)
                        .collect(Collectors.groupingBy(
                                SysLargeScreenLearningGrowthSqlDto::getKsDeptId,
                                Collectors.collectingAndThen(
                                        Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                        avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                )
                        ));
                long count = avgMap.keySet().stream().count();
                resultItem.setStationTotal((int) count);
                // 1. 按值升序排序
                List<Map.Entry<Long, BigDecimal>> sortedEntriesTeam = avgMap.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                        .collect(Collectors.toList());
                // 2. 计算排名（考虑并列情况）
                Map<Long, Integer> rankMapTeam = new HashMap<>();
                int currentRank = 1;
                BigDecimal prevValueTeam = null;
                int sameValueCount = 1; // 记录相同值的用户数
                for (int i = 0; i < sortedEntriesTeam.size(); i++) {
                    Map.Entry<Long, BigDecimal> entry = sortedEntriesTeam.get(i);
                    BigDecimal currentValue = entry.getValue();
                    if (prevValueTeam != null && !currentValue.equals(prevValueTeam)) {
                        // 如果当前值与前一个值不同，更新排名
                        currentRank += sameValueCount;
                        sameValueCount = 1;
                    } else if (prevValueTeam != null) {
                        // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                        sameValueCount++;
                    }
                    // 存储用户ID和排名
                    rankMapTeam.put(entry.getKey(), currentRank);
                    prevValueTeam = currentValue;
                }
                // 3. 查询指定排名
                Long targetId = departmentId;
                Integer integer = rankMapTeam.get(targetId);
                resultItem.setStationRanking(integer);
            }
            result.add(resultItem);
        } else if (ObjUtil.isNotNull(brigadeId)) {
            // 大队级
            Long finalBrigadeId = brigadeId;
            List<SysLargeScreenLearningGrowthSqlDto> target = all.stream()
                    .filter(item -> ObjUtil.equals(item.getDdDeptId(), finalBrigadeId))
                    .collect(Collectors.toList());
            if (CollUtil.isEmpty(target)) {
                return Collections.emptyList();
            }
            SysLargeScreenLearningGrowthDto resultItem = new SysLargeScreenLearningGrowthDto();
            resultItem.setId(brigadeId);
            resultItem.setName(target.get(0).getDdDeptName());
            resultItem.setHighestScore(target
                    .stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::max)
                    .orElse(BigDecimal.ZERO));
            resultItem.setLowestScore(target
                    .stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::min)
                    .orElse(BigDecimal.ZERO));
            resultItem.setAverageScore(target.stream()
                    .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                    .filter(ObjUtil::isNotNull)
                    .reduce(BigDecimal::add)
                    .map(sum -> sum.divide(BigDecimal.valueOf(target.size()), 2, RoundingMode.HALF_UP))
                    .orElse(BigDecimal.ZERO));
            // 本站排名处理
            SysDept sysDeptBrigade = sysDeptService.selectDeptById(brigadeId);
            Long stationId = sysDeptBrigade.getParentId();
            List<SysLargeScreenLearningGrowthSqlDto> stationList = all.stream().filter(item -> ObjUtil.equals(item.getZjDeptId(), stationId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(stationList)) {
                Map<Long, BigDecimal> avgMap = stationList.stream()
                        .filter(item -> item.getExamScore() != null)
                        .collect(Collectors.groupingBy(
                                SysLargeScreenLearningGrowthSqlDto::getDdDeptId,
                                Collectors.collectingAndThen(
                                        Collectors.averagingDouble(record -> record.getExamScore().doubleValue()),
                                        avg -> BigDecimal.valueOf(avg).setScale(2, RoundingMode.HALF_UP)
                                )
                        ));
                long count = avgMap.keySet().stream().count();
                resultItem.setStationTotal((int) count);
                // 1. 按值升序排序
                List<Map.Entry<Long, BigDecimal>> sortedEntriesTeam = avgMap.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                        .collect(Collectors.toList());
                // 2. 计算排名（考虑并列情况）
                Map<Long, Integer> rankMapTeam = new HashMap<>();
                int currentRank = 1;
                BigDecimal prevValueTeam = null;
                int sameValueCount = 1; // 记录相同值的用户数
                for (int i = 0; i < sortedEntriesTeam.size(); i++) {
                    Map.Entry<Long, BigDecimal> entry = sortedEntriesTeam.get(i);
                    BigDecimal currentValue = entry.getValue();
                    if (prevValueTeam != null && !currentValue.equals(prevValueTeam)) {
                        // 如果当前值与前一个值不同，更新排名
                        currentRank += sameValueCount;
                        sameValueCount = 1;
                    } else if (prevValueTeam != null) {
                        // 如果当前值与前一个值相同，排名不变，但增加相同值的计数
                        sameValueCount++;
                    }
                    // 存储用户ID和排名
                    rankMapTeam.put(entry.getKey(), currentRank);
                    prevValueTeam = currentValue;
                }
                // 3. 查询指定排名
                Long targetId = brigadeId;
                Integer integer = rankMapTeam.get(targetId);
                resultItem.setStationRanking(integer);
            }
            result.add(resultItem);
        } else {
            // 站级
            Map<Long, String> allMap = all.stream().collect(Collectors.toMap(SysLargeScreenLearningGrowthSqlDto::getDdDeptId, SysLargeScreenLearningGrowthSqlDto::getDdDeptName, (oldValue, newValue) -> newValue));
            Map<Long, List<SysLargeScreenLearningGrowthSqlDto>> groupingByMap = all.stream().collect(Collectors.groupingBy(SysLargeScreenLearningGrowthSqlDto::getDdDeptId));
            groupingByMap.forEach((ddDeptId, sysLargeScreenLearningGrowthSqlDtolist) -> {
                SysLargeScreenLearningGrowthDto resultItem = new SysLargeScreenLearningGrowthDto();
                resultItem.setId(ddDeptId);
                resultItem.setName(allMap.get(ddDeptId));
                resultItem.setHighestScore(sysLargeScreenLearningGrowthSqlDtolist
                        .stream()
                        .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                        .filter(ObjUtil::isNotNull)
                        .reduce(BigDecimal::max)
                        .orElse(BigDecimal.ZERO));
                resultItem.setLowestScore(sysLargeScreenLearningGrowthSqlDtolist
                        .stream()
                        .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                        .filter(ObjUtil::isNotNull)
                        .reduce(BigDecimal::min)
                        .orElse(BigDecimal.ZERO));
                resultItem.setAverageScore(sysLargeScreenLearningGrowthSqlDtolist.stream()
                        .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                        .filter(ObjUtil::isNotNull)
                        .reduce(BigDecimal::add)
                        .map(sum -> sum.divide(BigDecimal.valueOf(all.size()), 2, RoundingMode.HALF_UP))
                        .orElse(BigDecimal.ZERO));
                result.add(resultItem);
            });
        }
        return result;
    }

    /**
     * 能力画像-总体概览-学习成长平均分
     *
     * @param dto 大屏查询参数
     * @return 能力画像-总体概览-学习成长平均分
     */
    @Override
    public BigDecimal population(BaseLargeScreenQueryParamDto dto) {
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeDays(91));
        }

        // 查询出全量数据
        SysLargeScreenLearningGrowthQueryParamDto tempQueryParam = new SysLargeScreenLearningGrowthQueryParamDto();
        tempQueryParam.setSpecifiedDate(dto.getSpecifiedDate());
        tempQueryParam.setStartDate(dto.getStartDate());
        tempQueryParam.setEndDate(dto.getEndDate());
        List<SysLargeScreenLearningGrowthSqlDto> all = sysLearningGrowthMapper.selectSysLearningGrowthListByCondition(tempQueryParam);
        if (CollUtil.isEmpty(all)) {
            return BigDecimal.ZERO;
        }
        // 对全量数据进行过滤+处理返回数据
        if (ObjUtil.isNotNull(dto.getUserId())) {
            // 个人
            List<SysLargeScreenLearningGrowthSqlDto> target = all.stream().filter(item -> ObjUtil.equals(item.getUserId(), dto.getUserId())).collect(Collectors.toList());
            BigDecimal sum = target.stream().map(SysLargeScreenLearningGrowthSqlDto::getExamScore).reduce(BigDecimal.ZERO, BigDecimal::add);
            int count = target.size();
            return count == 0 ? BigDecimal.ZERO : sum.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP);
        } else {
            // 组织
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (StrUtil.equals(DeptTypeEnum.STATION.getCode(), sysDept.getDeptType())) {
                List<SysLargeScreenLearningGrowthSqlDto> target = all;
                BigDecimal sum = target.stream().map(SysLargeScreenLearningGrowthSqlDto::getExamScore).reduce(BigDecimal.ZERO, BigDecimal::add);
                int count = target.size();
                return count == 0 ? BigDecimal.ZERO : sum.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP);
            } else if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
                List<SysLargeScreenLearningGrowthSqlDto> target = all.stream().filter(item -> ObjUtil.equals(item.getDdDeptId(), dto.getDeptId())).collect(Collectors.toList());
                BigDecimal sum = target.stream().map(SysLargeScreenLearningGrowthSqlDto::getExamScore).reduce(BigDecimal.ZERO, BigDecimal::add);
                int count = target.size();
                return count == 0 ? BigDecimal.ZERO : sum.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP);
            } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
                List<SysLargeScreenLearningGrowthSqlDto> target = all.stream().filter(item -> ObjUtil.equals(item.getKsDeptId(), dto.getDeptId())).collect(Collectors.toList());
                BigDecimal sum = target.stream().map(SysLargeScreenLearningGrowthSqlDto::getExamScore).reduce(BigDecimal.ZERO, BigDecimal::add);
                int count = target.size();
                return count == 0 ? BigDecimal.ZERO : sum.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP);
            } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
                List<SysLargeScreenLearningGrowthSqlDto> target = all.stream().filter(item -> ObjUtil.equals(item.getBzDeptId(), dto.getDeptId())).collect(Collectors.toList());
                BigDecimal sum = target.stream().map(SysLargeScreenLearningGrowthSqlDto::getExamScore).reduce(BigDecimal.ZERO, BigDecimal::add);
                int count = target.size();
                return count == 0 ? BigDecimal.ZERO : sum.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP);
            } else {
                return BigDecimal.ZERO;
            }
        }
    }

    /**
     * 工作画像-组织支撑-培训测试平均分趋势图
     *
     * @param dto 大屏查询参数
     * @return 工作画像-组织支撑-培训测试平均分趋势图
     */
    @Override
    public List<SysLargeScreenLearningGrowthOrganizationalSupportDto> organizationalSupport(SysLargeScreenLearningGrowthQueryParamDto dto) {
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeDays(91));
        }

        // 部门类型为非大队时查询全部数据
        Long deptId = dto.getDeptId();
        if (ObjUtil.isNotNull(deptId)) {
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
                dto.setBrigadeId(deptId);
            } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
                dto.setDepartmentId(deptId);
            } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
                dto.setTeamId(deptId);
            } else {

            }
        }

        List<SysLargeScreenLearningGrowthOrganizationalSupportDto> result = sysLearningGrowthMapper.organizationalSupport(dto);
        return result;
    }

    /**
     * 首页-学习成长-平均分
     *
     * @param dto 上行参数
     * @return 首页-学习成长-平均分
     */
    @Override
    public BigDecimal learningGrowthAverage(BaseLargeScreenQueryParamDto dto) {
        if (ObjUtil.isNull(dto.getUserId()) && ObjUtil.isNull(dto.getDeptId())) {
            throw new ServiceException("用户ID和部门ID不能同时为空");
        }
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeYears(1));
        }
        SysLargeScreenLearningGrowthQueryParamDto tempQueryParam = new SysLargeScreenLearningGrowthQueryParamDto();
        tempQueryParam.setSpecifiedDate(dto.getSpecifiedDate());
        tempQueryParam.setStartDate(dto.getStartDate());
        tempQueryParam.setEndDate(dto.getEndDate());
        if (ObjUtil.isNotNull(dto.getUserId())) {
            tempQueryParam.setUserId(dto.getUserId());
        } else {
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (ObjUtil.isNull(sysDept)) {
                throw new ServiceException("部门不存在");
            }
            if (StrUtil.equals(DeptTypeEnum.STATION.getCode(), sysDept.getDeptType())) {
                tempQueryParam.setStationId(sysDept.getDeptId());
            } else if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
                tempQueryParam.setBrigadeId(sysDept.getDeptId());
            } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
                tempQueryParam.setDepartmentId(sysDept.getDeptId());
            } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
                tempQueryParam.setTeamId(sysDept.getDeptId());
            } else {
                return BigDecimal.ZERO;
            }
        }
        List<SysLargeScreenLearningGrowthSqlDto> target = sysLearningGrowthMapper.selectSysLearningGrowthListByCondition(tempQueryParam);
        if (CollUtil.isEmpty(target)) {
            return BigDecimal.ZERO;
        }
        BigDecimal sum = target.stream().map(SysLargeScreenLearningGrowthSqlDto::getExamScore).reduce(BigDecimal.ZERO, BigDecimal::add);
        return sum.divide(BigDecimal.valueOf(target.size()), 2, RoundingMode.HALF_UP);
    }

    /**
     * 首页报表-培训答题分数数据
     *
     * @param dto 上行参数
     * @return 首页报表-培训答题分数数据
     */
    @Override
    public SysHomeReportDetailDto learningGrowthData(BaseLargeScreenQueryParamDto dto) {
        if (ObjUtil.isNull(dto.getUserId()) && ObjUtil.isNull(dto.getDeptId())) {
            throw new ServiceException("用户ID和部门ID不能同时为空");
        }
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeYears(1));
        }
        SysHomeReportDetailDto result = new SysHomeReportDetailDto();
        SysLargeScreenLearningGrowthQueryParamDto tempQueryParam = new SysLargeScreenLearningGrowthQueryParamDto();
        tempQueryParam.setSpecifiedDate(dto.getSpecifiedDate());
        tempQueryParam.setStartDate(dto.getStartDate());
        tempQueryParam.setEndDate(dto.getEndDate());
        if (ObjUtil.isNotNull(dto.getUserId())) {
            SysUser sysUser = sysUserService.selectUserById(dto.getUserId());
            if (ObjUtil.isNull(sysUser)) {
                throw new ServiceException("【" + dto.getUserId() + "】用户不存在");
            }
            result.setId(sysUser.getUserId());
            result.setName(sysUser.getNickName());
            result.setType(HomePageQueryEnum.USER.getCode());
            tempQueryParam.setUserId(dto.getUserId());
        } else {
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (ObjUtil.isNull(sysDept)) {
                throw new ServiceException("【" + dto.getDeptId() + "】部门不存在");
            }
            result.setId(sysDept.getDeptId());
            result.setName(sysDept.getDeptName());
            result.setType(HomePageQueryEnum.DEPT.getCode());
            if (StrUtil.equals(DeptTypeEnum.STATION.getCode(), sysDept.getDeptType())) {
                tempQueryParam.setStationId(sysDept.getDeptId());
            } else if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
                tempQueryParam.setBrigadeId(sysDept.getDeptId());
            } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
                tempQueryParam.setDepartmentId(sysDept.getDeptId());
            } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
                tempQueryParam.setTeamId(sysDept.getDeptId());
            } else {
                throw new ServiceException("【" + dto.getDeptId() + "】部门类型异常");
            }
        }
        List<SysLargeScreenLearningGrowthSqlDto> targetList = sysLearningGrowthMapper.selectSysLearningGrowthListByCondition(tempQueryParam);
        List<BigDecimal> targetValueList = targetList.stream()
                .map(SysLargeScreenLearningGrowthSqlDto::getExamScore)
                .filter(Objects::nonNull)
                .sorted()
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(targetValueList)) {
            result.setMaxNumber(BigDecimal.ZERO);
            result.setMinNumber(BigDecimal.ZERO);
            result.setAverageNumber(BigDecimal.ZERO);
            result.setMedianNumber(BigDecimal.ZERO);
            return result;
        }
        // 最大值
        result.setMaxNumber(targetValueList.get(targetValueList.size() - 1));
        // 最小值
        result.setMinNumber(targetValueList.get(0));
        // 总和
        BigDecimal sum = targetValueList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        // 总数
        int totalCount = targetValueList.size();
        // 平均值
        result.setAverageNumber(sum.divide(new BigDecimal(totalCount), 2, RoundingMode.HALF_UP));
        // 中位数
        int size = targetValueList.size();
        int middle = size / 2;
        if (size % 2 == 1) {
            result.setMedianNumber(targetValueList.get(middle));
        } else {
            result.setMedianNumber(targetValueList.get(middle - 1).add(targetValueList.get(middle)).divide(new BigDecimal(2), 2, RoundingMode.HALF_UP));
        }
        return result;
    }
}
