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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sundot.airport.attendance.service.IAttendancePostRecordService;
import com.sundot.airport.attendance.service.IAttendanceTeamUserRecordService;
import com.sundot.airport.check.domain.CheckLargeScreenCommonDto;
import com.sundot.airport.check.domain.CheckLargeScreenCorrectionAssistDto;
import com.sundot.airport.check.domain.CheckLargeScreenCorrectionDto;
import com.sundot.airport.check.domain.CheckLargeScreenCorrectionPortraitDto;
import com.sundot.airport.check.domain.CheckLargeScreenCorrectionPortraitSqlDto;
import com.sundot.airport.check.domain.CheckLargeScreenCorrectionQueryParamDto;
import com.sundot.airport.check.domain.CheckLargeScreenHomePageCheckCorrectionSqlDto;
import com.sundot.airport.check.domain.CheckLargeScreenHomePageCheckRecordSqlDto;
import com.sundot.airport.check.domain.CheckLargeScreenHomePageDto;
import com.sundot.airport.common.core.domain.CheckLargeScreenHomePageItemDto;
import com.sundot.airport.common.core.domain.CheckLargeScreenHomePageRankingDto;
import com.sundot.airport.check.domain.CheckLargeScreenInspectionExecuteDto;
import com.sundot.airport.check.domain.CheckLargeScreenInspectionExecuteItemDto;
import com.sundot.airport.check.domain.CheckLargeScreenInspectionExecuteUserDto;
import com.sundot.airport.check.domain.CheckLargeScreenPlanOverviewDto;
import com.sundot.airport.check.domain.CheckLargeScreenPlanQueryParamDto;
import com.sundot.airport.check.domain.CheckLargeScreenProblemDto;
import com.sundot.airport.check.domain.CheckLargeScreenProblemQueryParamDto;
import com.sundot.airport.check.domain.CheckLargeScreenProblemTrendDto;
import com.sundot.airport.check.domain.CheckTask;
import com.sundot.airport.check.mapper.CheckLargeScreenMapper;
import com.sundot.airport.check.service.ICheckLargeScreenService;
import com.sundot.airport.common.constant.CacheConstants;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckProblemCorrectionDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckProblemCorrectionItemDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckProblemDistributionItemDto;
import com.sundot.airport.common.core.domain.LargeScreenHomePageUserInfoSqlDto;
import com.sundot.airport.common.core.domain.SysAnalysisReportCompareItemDto;
import com.sundot.airport.common.core.domain.SysAnalysisReportDateRangeDto;
import com.sundot.airport.common.core.domain.SysAnalysisReportParamDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckProblemDiscoveryDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckProblemDiscoveryItemDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckProblemDistributionDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckTaskDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckTaskItemDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportCheckTaskTypeItemDto;
import com.sundot.airport.common.core.domain.SysCheckAnalysisReportDto;
import com.sundot.airport.common.core.domain.SysHomeReportDetailDto;
import com.sundot.airport.common.core.domain.SysLargeScreenDetailDto;
import com.sundot.airport.common.core.domain.SysUsageReportCheckTaskDto;
import com.sundot.airport.common.core.domain.SysUsageReportDto;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysDictData;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.core.redis.RedisCache;
import com.sundot.airport.common.dto.BaseCommonDto;
import com.sundot.airport.common.enums.CheckLargeScreenCorrectionTypeEnum;
import com.sundot.airport.common.enums.CheckLevelEnum;
import com.sundot.airport.common.enums.CheckTaskTypeEnum;
import com.sundot.airport.common.enums.CompareResultTypeEnum;
import com.sundot.airport.common.enums.CompareTypeEnum;
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.MedalTypeEnum;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.enums.SourceTypeEnum;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DeptUtils;
import com.sundot.airport.common.utils.LargeScreenDateUtils;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.common.utils.StringUtils;
import com.sundot.airport.system.domain.BaseCheckCategory;
import com.sundot.airport.system.domain.approval.ApprovalTask;
import com.sundot.airport.system.enums.ProcessStatusEnum;
import com.sundot.airport.system.service.IBaseCheckCategoryService;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysDictDataService;
import com.sundot.airport.system.service.ISysUserService;
import com.sundot.airport.system.service.approval.ICheckApprovalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 检查任务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-07
 */
@Service
public class CheckLargeScreenServiceImpl implements ICheckLargeScreenService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CheckLargeScreenMapper checkLargeScreenMapper;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IAttendancePostRecordService attendancePostRecordService;

    @Autowired
    private IAttendanceTeamUserRecordService attendanceTeamUserRecordService;

    @Autowired
    private IBaseCheckCategoryService baseCheckCategoryService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ICheckApprovalService checkApprovalService;

    /**
     * 巡检计划-计划安排总览
     *
     * @param dto 大屏查询参数
     * @return 计划安排总览
     */
    @Override
    public List<CheckLargeScreenPlanOverviewDto> planOverview(CheckLargeScreenPlanQueryParamDto dto, String source) {
        // 1、参数校验
        validateDateRange(dto.getStartDate(), dto.getEndDate());
        // 2、生成日期序列
        List<Date> dateRange = generateDateRange(dto.getStartDate(), dto.getEndDate());
        // 3、获取所有类别
        SysDictData dictData = new SysDictData();
        dictData.setDictType("check_task_category");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(dictData);
        Map<String, String> sysDictDataMap = sysDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<String> typeList = sysDictDataList.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
        // 4、构建统计映射
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            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())) {
                dto.setIsSelfCheck(null);
                dto.setCreateId(null);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
                dto.setCreateId(null);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(1);
                dto.setCreateId(SecurityUtils.getLoginUser().getUserId());
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(0);
                dto.setCreateId(SecurityUtils.getLoginUser().getUserId());
            } else {
                return Collections.emptyList();
            }
        }
        List<CheckLargeScreenPlanOverviewDto> list = checkLargeScreenMapper.planOverview(dto);
        Map<String, BigDecimal> statsMap = list.stream().collect(Collectors.toMap(item -> item.getType() + "***" + item.getDate(), CheckLargeScreenPlanOverviewDto::getTotal, (oldValue, newValue) -> newValue));
        // 5、组装最终结果
        List<CheckLargeScreenPlanOverviewDto> result = new ArrayList<>();
        dateRange.forEach(date -> {
            typeList.forEach(type -> {
                CheckLargeScreenPlanOverviewDto resultItem = new CheckLargeScreenPlanOverviewDto();
                resultItem.setDate(DateUtil.formatDate(date));
                resultItem.setType(type);
                resultItem.setTypeDesc(sysDictDataMap.getOrDefault(type, ""));
                resultItem.setTotal(ObjUtil.isNull(statsMap) ? BigDecimal.ZERO : statsMap.getOrDefault(type + "***" + DateUtil.formatDate(date), BigDecimal.ZERO));
                result.add(resultItem);
            });
        });
        return result;
    }

    /**
     * 巡检计划-日常任务检查指标累积分布
     *
     * @param dto 大屏查询参数
     * @return 日常任务检查指标累积分布
     */
    @Override
    public List<CheckLargeScreenCommonDto> planDistribution(CheckLargeScreenPlanQueryParamDto dto, String source) {
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            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())) {
                dto.setIsSelfCheck(null);
                dto.setCreateId(null);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
                dto.setCreateId(null);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(1);
                dto.setCreateId(SecurityUtils.getLoginUser().getUserId());
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(0);
                dto.setCreateId(SecurityUtils.getLoginUser().getUserId());
            } else {
                return Collections.emptyList();
            }
        }
        List<CheckLargeScreenCommonDto> resultTemp = checkLargeScreenMapper.planDistribution(dto);
        // 未查询到的需补充0数据填充到结果中
        Map<String, BigDecimal> resultTempMap = resultTemp.stream().collect(Collectors.toMap(CheckLargeScreenCommonDto::getCode, CheckLargeScreenCommonDto::getTotal, (oldValue, newValue) -> newValue));
        BaseCheckCategory baseCheckCategory = new BaseCheckCategory();
        baseCheckCategory.setLevel(1);
        List<BaseCheckCategory> baseCheckCategoryList = baseCheckCategoryService.selectBaseCheckCategoryList(baseCheckCategory);
        List<CheckLargeScreenCommonDto> result = new ArrayList<>();
        baseCheckCategoryList.forEach(checkCategory -> {
            CheckLargeScreenCommonDto resultItem = new CheckLargeScreenCommonDto();
            resultItem.setCode(checkCategory.getCode());
            resultItem.setName(checkCategory.getName());
            resultItem.setTotal(resultTempMap.getOrDefault(checkCategory.getCode(), BigDecimal.ZERO));
            result.add(resultItem);
        });
        return result;
    }

    /**
     * 巡检计划-任务明细统计表
     *
     * @param dto 大屏查询参数
     * @return 任务明细统计表
     */
    @Override
    public List<CheckTask> planStatistics(CheckLargeScreenPlanQueryParamDto dto, String source) {
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            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())) {
                dto.setIsSelfCheck(null);
                dto.setCreateId(null);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
                dto.setCreateId(null);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(1);
                dto.setCreateId(SecurityUtils.getLoginUser().getUserId());
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(0);
                dto.setCreateId(SecurityUtils.getLoginUser().getUserId());
            } else {
                return Collections.emptyList();
            }
        }
        List<CheckTask> result = checkLargeScreenMapper.planStatistics(dto);
        return result;
    }

    /**
     * 问题发现-总体问题分布
     *
     * @param dto 大屏查询参数
     * @return 总体问题分布
     */
    @Override
    public List<CheckLargeScreenProblemDto> problemDistribution(CheckLargeScreenProblemQueryParamDto dto, String source) {
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            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())) {
                dto.setIsSelfCheck(null);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedBrigadeId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedDepartmentId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedTeamId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
            } else {
                return Collections.emptyList();
            }
        }
        List<CheckLargeScreenProblemDto> result = checkLargeScreenMapper.problemDistribution(dto);
        // 问题对比和问题趋势
        result.forEach(item -> {
            if (item.getTotal().compareTo(BigDecimal.ZERO) == 0) {
                return;
            }
            CheckLargeScreenProblemQueryParamDto checkLargeScreenProblemQueryParamDto = new CheckLargeScreenProblemQueryParamDto();
            checkLargeScreenProblemQueryParamDto.setStartDate(dto.getStartDate());
            checkLargeScreenProblemQueryParamDto.setEndDate(dto.getEndDate());
            checkLargeScreenProblemQueryParamDto.setCategoryCodeOne(item.getCode());
            item.setCheckLargeScreenProblemDtoList(problemComparisonTwo(checkLargeScreenProblemQueryParamDto, source));
            item.setCheckLargeScreenProblemTrendDtoList(problemTrend(checkLargeScreenProblemQueryParamDto, source));
        });
        return result;
    }

    /**
     * 问题发现-问题分布对比
     *
     * @param dto 大屏查询参数
     * @return 问题分布对比
     */
    @Override
    public List<CheckLargeScreenProblemDto> problemComparison(CheckLargeScreenProblemQueryParamDto dto, String source) {
        List<CheckLargeScreenProblemDto> resultTemp;
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            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())) {
                dto.setIsSelfCheck(null);
                resultTemp = checkLargeScreenMapper.problemComparisonBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
                resultTemp = checkLargeScreenMapper.problemComparisonBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedBrigadeId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                resultTemp = checkLargeScreenMapper.problemComparisonBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedDepartmentId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                resultTemp = checkLargeScreenMapper.problemComparison(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedTeamId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                resultTemp = checkLargeScreenMapper.problemComparisonBanZu(dto);
            } else {
                return Collections.emptyList();
            }
        } else {
            resultTemp = checkLargeScreenMapper.problemComparisonBrigade(dto);
        }
        if (CollUtil.isEmpty(resultTemp)) {
            return Collections.emptyList();
        }
        // 未查询到的需补充0数据填充到结果中
        Map<String, BigDecimal> resultTempMap = resultTemp.stream().collect(Collectors.toMap(item -> item.getDeptId() + "***" + item.getCode(), CheckLargeScreenCommonDto::getTotal, (oldValue, newValue) -> newValue));
        List<Long> deptIdList = resultTemp.stream().map(CheckLargeScreenProblemDto::getDeptId).distinct().collect(Collectors.toList());
        Map<Long, String> deptMap = resultTemp.stream().collect(Collectors.toMap(CheckLargeScreenProblemDto::getDeptId, CheckLargeScreenProblemDto::getDeptName, (oldValue, newValue) -> newValue));
        BaseCheckCategory baseCheckCategory = new BaseCheckCategory();
        baseCheckCategory.setLevel(1);
        List<BaseCheckCategory> baseCheckCategoryList = baseCheckCategoryService.selectBaseCheckCategoryList(baseCheckCategory);
        List<CheckLargeScreenProblemDto> result = new ArrayList<>();
        baseCheckCategoryList.forEach(item -> {
            deptIdList.forEach(deptId -> {
                CheckLargeScreenProblemDto resultItem = new CheckLargeScreenProblemDto();
                resultItem.setDeptId(deptId);
                resultItem.setDeptName(deptMap.getOrDefault(deptId, ""));
                resultItem.setCode(item.getCode());
                resultItem.setName(item.getName());
                resultItem.setTotal(resultTempMap.getOrDefault(deptId + "***" + item.getCode(), BigDecimal.ZERO));
                result.add(resultItem);
            });
        });
        return result;
    }

    /**
     * 问题发现-通道面貌-问题对比
     *
     * @param dto 大屏查询参数
     * @return 通道面貌-问题对比
     */
    @Override
    public List<CheckLargeScreenProblemDto> problemComparisonTwo(CheckLargeScreenProblemQueryParamDto dto, String source) {
        List<CheckLargeScreenProblemDto> resultTemp;
        List<CheckLargeScreenProblemDto> deptList;
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            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())) {
                dto.setIsSelfCheck(null);
                resultTemp = checkLargeScreenMapper.problemComparisonTwoBrigade(dto);
                deptList = checkLargeScreenMapper.getProblemBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
                resultTemp = checkLargeScreenMapper.problemComparisonTwoBrigade(dto);
                deptList = checkLargeScreenMapper.getProblemBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedBrigadeId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                resultTemp = checkLargeScreenMapper.problemComparisonTwoBrigade(dto);
                deptList = checkLargeScreenMapper.getProblemBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedDepartmentId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                resultTemp = checkLargeScreenMapper.problemComparisonTwo(dto);
                deptList = checkLargeScreenMapper.getProblemDepartment(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedTeamId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                resultTemp = checkLargeScreenMapper.problemComparisonTwoBanZu(dto);
                deptList = checkLargeScreenMapper.getProblemTeam(dto);
            } else {
                return Collections.emptyList();
            }
        } else {
            resultTemp = checkLargeScreenMapper.problemComparisonTwoBrigade(dto);
            deptList = checkLargeScreenMapper.getProblemBrigade(dto);
        }
        if (CollUtil.isEmpty(resultTemp) || CollUtil.isEmpty(deptList)) {
            return Collections.emptyList();
        }
        // 未查询到的需补充0数据填充到结果中
        Map<String, BigDecimal> resultTempMap = resultTemp.stream().collect(Collectors.toMap(item -> item.getDeptId() + "***" + item.getCode(), CheckLargeScreenCommonDto::getTotal, (oldValue, newValue) -> newValue));
        List<Long> deptIdList = deptList.stream().map(CheckLargeScreenProblemDto::getDeptId).distinct().collect(Collectors.toList());
        Map<Long, String> deptMap = deptList.stream().collect(Collectors.toMap(CheckLargeScreenProblemDto::getDeptId, CheckLargeScreenProblemDto::getDeptName, (oldValue, newValue) -> newValue));
        BaseCheckCategory baseCheckCategory = new BaseCheckCategory();
        baseCheckCategory.setLevel(2);
        List<BaseCheckCategory> baseCheckCategoryList = baseCheckCategoryService.selectBaseCheckCategoryList(baseCheckCategory);
        List<CheckLargeScreenProblemDto> result = new ArrayList<>();
        baseCheckCategoryList.forEach(item -> {
            deptIdList.forEach(deptId -> {
                CheckLargeScreenProblemDto resultItem = new CheckLargeScreenProblemDto();
                resultItem.setDeptId(deptId);
                resultItem.setDeptName(deptMap.getOrDefault(deptId, ""));
                resultItem.setCode(item.getCode());
                resultItem.setName(item.getName());
                resultItem.setTotal(resultTempMap.getOrDefault(deptId + "***" + item.getCode(), BigDecimal.ZERO));
                result.add(resultItem);
            });
        });
        return result;
    }

    /**
     * 问题发现-通道面貌-问题趋势
     *
     * @param dto 大屏查询参数
     * @return 通道面貌-问题趋势
     */
    @Override
    public List<CheckLargeScreenProblemTrendDto> problemTrend(CheckLargeScreenProblemQueryParamDto dto, String source) {
        // 1、参数校验
        validateDateRange(dto.getStartDate(), dto.getEndDate());
        // 2、生成日期序列
        List<Date> dateRange = generateDateRange(dto.getStartDate(), dto.getEndDate());
        // 3、构建统计映射
        List<CheckLargeScreenProblemTrendDto> list;
        List<CheckLargeScreenProblemDto> deptList;
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            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())) {
                dto.setIsSelfCheck(null);
                list = checkLargeScreenMapper.problemTrendBrigade(dto);
                deptList = checkLargeScreenMapper.getProblemBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
                list = checkLargeScreenMapper.problemTrendBrigade(dto);
                deptList = checkLargeScreenMapper.getProblemBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedBrigadeId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                list = checkLargeScreenMapper.problemTrendBrigade(dto);
                deptList = checkLargeScreenMapper.getProblemBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedDepartmentId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                list = checkLargeScreenMapper.problemTrend(dto);
                deptList = checkLargeScreenMapper.getProblemDepartment(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedTeamId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                list = checkLargeScreenMapper.problemTrendBanZu(dto);
                deptList = checkLargeScreenMapper.getProblemTeam(dto);
            } else {
                return Collections.emptyList();
            }
        } else {
            list = checkLargeScreenMapper.problemTrendBrigade(dto);
            deptList = checkLargeScreenMapper.getProblemBrigade(dto);
        }
        if (CollUtil.isEmpty(list) || CollUtil.isEmpty(deptList)) {
            return Collections.emptyList();
        }
        Map<Long, String> deptMap = deptList.stream().collect(Collectors.toMap(CheckLargeScreenProblemDto::getDeptId, CheckLargeScreenProblemDto::getDeptName, (oldValue, newValue) -> newValue));
        List<Long> deptIdList = deptList.stream().map(CheckLargeScreenProblemDto::getDeptId).distinct().collect(Collectors.toList());
        Map<String, BigDecimal> statsMap = list.stream().collect(Collectors.toMap(item -> item.getId() + "***" + item.getDate(), CheckLargeScreenProblemTrendDto::getTotal, (oldValue, newValue) -> newValue));
        // 4、组装最终结果
        List<CheckLargeScreenProblemTrendDto> result = new ArrayList<>();
        dateRange.forEach(date -> {
            deptIdList.forEach(deptId -> {
                CheckLargeScreenProblemTrendDto resultItem = new CheckLargeScreenProblemTrendDto();
                resultItem.setDate(DateUtil.formatDate(date));
                resultItem.setId(deptId);
                resultItem.setName(deptMap.getOrDefault(deptId, ""));
                resultItem.setTotal(statsMap.getOrDefault(deptId + "***" + DateUtil.formatDate(date), BigDecimal.ZERO));
                result.add(resultItem);
            });
        });
        return result;
    }

    /**
     * 问题整改-整改状态总计
     *
     * @param dto 大屏查询参数
     * @return 整改状态总计
     */
    @Override
    public CheckLargeScreenCorrectionDto correction(CheckLargeScreenCorrectionQueryParamDto dto, String source) {
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
            if (CollUtil.isEmpty(roles)) {
                return null;
            }
            List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
            if (roleKeyList.contains(RoleTypeEnum.admin.getCode())) {
                dto.setIsSelfCheck(null);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedBrigadeId(SecurityUtils.getLoginUser().getDeptId());
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedDepartmentId(SecurityUtils.getLoginUser().getDeptId());
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedTeamId(SecurityUtils.getLoginUser().getDeptId());
            } else {
                return null;
            }
        }
        List<CheckLargeScreenCorrectionAssistDto> list = checkLargeScreenMapper.correction(dto);
        BigDecimal onTimeCompletedCount = BigDecimal.valueOf(list.stream().filter(item -> StringUtils.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getType())).count());
        BigDecimal overTimeCompletedCount = BigDecimal.valueOf(list.stream().filter(item -> StringUtils.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_COMPLETED.getCode(), item.getType())).count());
        BigDecimal onTimeUnfinishedCount = BigDecimal.valueOf(list.stream().filter(item -> StringUtils.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_UNFINISHED.getCode(), item.getType())).count());
        BigDecimal overTimeUnfinishedCount = BigDecimal.valueOf(list.stream().filter(item -> StringUtils.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_UNFINISHED.getCode(), item.getType())).count());
        BigDecimal otherCount = BigDecimal.valueOf(list.stream().filter(item -> StringUtils.equals(CheckLargeScreenCorrectionTypeEnum.OTHER.getCode(), item.getType())).count());

        CheckLargeScreenCorrectionDto result = new CheckLargeScreenCorrectionDto();
        if (ObjUtil.isNotNull(dto.getCheckedBrigadeId()) || ObjUtil.isNotNull(dto.getCheckedDepartmentId()) || ObjUtil.isNotNull(dto.getCheckedTeamId())) {
            Long deptId = ObjUtil.isNotNull(dto.getCheckedBrigadeId()) ? dto.getCheckedBrigadeId() : ObjUtil.isNotNull(dto.getCheckedDepartmentId()) ? dto.getCheckedDepartmentId() : dto.getCheckedTeamId();
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            if (ObjUtil.isNotNull(sysDept)) {
                result.setDeptId(sysDept.getDeptId());
                result.setDeptName(sysDept.getDeptName());
            }
        }
        result.setOnTimeCompletedCount(onTimeCompletedCount);
        result.setOverTimeCompletedCount(overTimeCompletedCount);
        result.setOnTimeUnfinishedCount(onTimeUnfinishedCount);
        result.setOverTimeUnfinishedCount(overTimeUnfinishedCount);
        result.setOtherCount(otherCount);
        return result;
    }

    /**
     * 问题整改-整改状态分布-科级对比
     *
     * @param dto 大屏查询参数
     * @return 整改状态总计
     */
    @Override
    public List<CheckLargeScreenCorrectionDto> correctionDistribution(CheckLargeScreenCorrectionQueryParamDto dto, String source) {
        List<CheckLargeScreenCorrectionDto> result;
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            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())) {
                dto.setIsSelfCheck(null);
                result = checkLargeScreenMapper.correctionDistributionBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(0);
                result = checkLargeScreenMapper.correctionDistributionBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedBrigadeId(SecurityUtils.getLoginUser().getDeptId());
                result = checkLargeScreenMapper.correctionDistributionBrigade(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedDepartmentId(SecurityUtils.getLoginUser().getDeptId());
                result = checkLargeScreenMapper.correctionDistribution(dto);
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                dto.setIsSelfCheck(null);
                dto.setCheckedTeamId(SecurityUtils.getLoginUser().getDeptId());
                result = checkLargeScreenMapper.correctionDistributionBanZu(dto);
            } else {
                return Collections.emptyList();
            }
        } else {
            result = checkLargeScreenMapper.correctionDistributionBrigade(dto);
        }
        return result;
    }

    /**
     * 巡检执行
     *
     * @param dto 大屏查询参数
     * @return 巡检执行
     */
    @Override
    public List<CheckLargeScreenInspectionExecuteDto> inspectionExecute(BaseLargeScreenQueryParamDto dto) {
        // 目标用户处理-按照角色分组
        List<Long> targetUserIdList = new ArrayList<>();
        targetUserIdList.addAll(attendancePostRecordService.queryKeIds());
        targetUserIdList.addAll(attendanceTeamUserRecordService.selectAttendanceTeamLeaderId());
        List<SysUser> sysUserList = sysUserService.selectUserListByRoleKey(Arrays.asList(RoleTypeEnum.test.getCode(), RoleTypeEnum.zhijianke.getCode()));
        List<Long> sysUserIdList = sysUserList.stream().map(SysUser::getUserId).distinct().collect(Collectors.toList());
        targetUserIdList.addAll(sysUserIdList);
        if (CollUtil.isEmpty(targetUserIdList)) {
            return Collections.emptyList();
        }
        List<CheckLargeScreenInspectionExecuteUserDto> stationTargetUserList = new ArrayList<>();
        List<CheckLargeScreenInspectionExecuteUserDto> brigadeTargetUserList = new ArrayList<>();
        List<CheckLargeScreenInspectionExecuteUserDto> departmentTargetUserList = new ArrayList<>();
        List<CheckLargeScreenInspectionExecuteUserDto> teamUserTargetList = new ArrayList<>();
        List<CheckLargeScreenInspectionExecuteUserDto> targetUserList = checkLargeScreenMapper.inspectionExecuteUser(targetUserIdList);
        Map<Long, CheckLargeScreenInspectionExecuteUserDto> targetUserMap = targetUserList.stream().collect(Collectors.toMap(CheckLargeScreenInspectionExecuteUserDto::getUserId, item -> item));
        Map<String, String> targetUserRoleMap = targetUserList.stream().collect(Collectors.groupingBy(item -> item.getUserId() + "-" + item.getNickName(), Collectors.mapping(CheckLargeScreenInspectionExecuteUserDto::getRoleKey, Collectors.joining(","))));
        targetUserRoleMap.forEach((key, value) -> {
            CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = new CheckLargeScreenInspectionExecuteUserDto();
            checkLargeScreenInspectionExecuteUserDto.setUserId(Long.valueOf(key.split("-")[0]));
            checkLargeScreenInspectionExecuteUserDto.setUserName(key.split("-")[1]);
            if (value.contains(RoleTypeEnum.test.getCode()) || value.contains(RoleTypeEnum.zhijianke.getCode())) {
                stationTargetUserList.add(checkLargeScreenInspectionExecuteUserDto);
            } else if (value.contains(RoleTypeEnum.jingli.getCode()) || value.contains(RoleTypeEnum.xingzheng.getCode())) {
                brigadeTargetUserList.add(checkLargeScreenInspectionExecuteUserDto);
            } else if (value.contains(RoleTypeEnum.kezhang.getCode())) {
                departmentTargetUserList.add(checkLargeScreenInspectionExecuteUserDto);
            } else if (value.contains(RoleTypeEnum.banzuzhang.getCode())) {
                teamUserTargetList.add(checkLargeScreenInspectionExecuteUserDto);
            } else {

            }
        });
        List<Long> stationTargetUserIdList = stationTargetUserList.stream().map(CheckLargeScreenInspectionExecuteUserDto::getUserId).collect(Collectors.toList());
        List<Long> brigadeTargetUserIdList = brigadeTargetUserList.stream().map(CheckLargeScreenInspectionExecuteUserDto::getUserId).collect(Collectors.toList());
        List<Long> departmentTargetUserIdList = departmentTargetUserList.stream().map(CheckLargeScreenInspectionExecuteUserDto::getUserId).collect(Collectors.toList());
        List<Long> teamTargetUserIdList = teamUserTargetList.stream().map(CheckLargeScreenInspectionExecuteUserDto::getUserId).collect(Collectors.toList());

        // 补充未执行用户数据
        List<CheckLargeScreenInspectionExecuteDto> result = checkLargeScreenMapper.inspectionExecute();
        if (CollUtil.isEmpty(result)) {
            return Collections.emptyList();
        }
        Map<String, CheckLargeScreenInspectionExecuteDto> checkLargeScreenInspectionExecuteDtoMap = result.stream().collect(Collectors.toMap(CheckLargeScreenInspectionExecuteDto::getTaskCode, item -> item));
        List<String> taskCodeList = result.stream().map(CheckLargeScreenInspectionExecuteDto::getTaskCode).collect(Collectors.toList());
        List<CheckLargeScreenInspectionExecuteItemDto> resultItemList = checkLargeScreenMapper.inspectionExecuteItem(taskCodeList);
        resultItemList = resultItemList.stream().filter(item -> targetUserIdList.contains(item.getUserId())).collect(Collectors.toList());
        Map<String, List<CheckLargeScreenInspectionExecuteItemDto>> checkLargeScreenInspectionExecuteItemDtoMap = resultItemList.stream().collect(Collectors.groupingBy(CheckLargeScreenInspectionExecuteItemDto::getTaskCode));
        checkLargeScreenInspectionExecuteItemDtoMap.forEach((key, value) -> {
            CheckLargeScreenInspectionExecuteDto checkLargeScreenInspectionExecuteDto = checkLargeScreenInspectionExecuteDtoMap.get(key);
            List<Long> userIdList = value.stream().map(CheckLargeScreenInspectionExecuteItemDto::getUserId).distinct().collect(Collectors.toList());
            if (StringUtils.equals(CheckLevelEnum.STATION_LEVEL.getCode(), checkLargeScreenInspectionExecuteDto.getCheckLevel())) {
                List<Long> unexecutedUserIdList = stationTargetUserIdList.stream().filter(item -> !userIdList.contains(item)).collect(Collectors.toList());
                unexecutedUserIdList.forEach(item -> {
                    CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = targetUserMap.get(item);
                    CheckLargeScreenInspectionExecuteItemDto checkLargeScreenInspectionExecuteItemDto = new CheckLargeScreenInspectionExecuteItemDto();
                    checkLargeScreenInspectionExecuteItemDto.setTaskId(checkLargeScreenInspectionExecuteDto.getTaskId());
                    checkLargeScreenInspectionExecuteItemDto.setTaskCode(checkLargeScreenInspectionExecuteDto.getTaskCode());
                    checkLargeScreenInspectionExecuteItemDto.setTaskName(checkLargeScreenInspectionExecuteDto.getTaskName());
                    checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(checkLargeScreenInspectionExecuteDto.getRuleTypeNum());
                    checkLargeScreenInspectionExecuteItemDto.setUserId(checkLargeScreenInspectionExecuteUserDto.getUserId());
                    checkLargeScreenInspectionExecuteItemDto.setUserName(checkLargeScreenInspectionExecuteUserDto.getNickName());
                    checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setCheckOrderCount(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setRectificationOrderCount(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setUnqualifiedProjectCount(BigDecimal.ZERO);
                    value.add(checkLargeScreenInspectionExecuteItemDto);
                });
            } else if (StringUtils.equals(CheckLevelEnum.BRIGADE_LEVEL.getCode(), checkLargeScreenInspectionExecuteDto.getCheckLevel())) {
                List<Long> unexecutedUserIdList = brigadeTargetUserIdList.stream().filter(item -> !userIdList.contains(item)).collect(Collectors.toList());
                unexecutedUserIdList.forEach(item -> {
                    CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = targetUserMap.get(item);
                    CheckLargeScreenInspectionExecuteItemDto checkLargeScreenInspectionExecuteItemDto = new CheckLargeScreenInspectionExecuteItemDto();
                    checkLargeScreenInspectionExecuteItemDto.setTaskId(checkLargeScreenInspectionExecuteDto.getTaskId());
                    checkLargeScreenInspectionExecuteItemDto.setTaskCode(checkLargeScreenInspectionExecuteDto.getTaskCode());
                    checkLargeScreenInspectionExecuteItemDto.setTaskName(checkLargeScreenInspectionExecuteDto.getTaskName());
                    checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(checkLargeScreenInspectionExecuteDto.getRuleTypeNum());
                    checkLargeScreenInspectionExecuteItemDto.setUserId(checkLargeScreenInspectionExecuteUserDto.getUserId());
                    checkLargeScreenInspectionExecuteItemDto.setUserName(checkLargeScreenInspectionExecuteUserDto.getNickName());
                    checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setCheckOrderCount(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setRectificationOrderCount(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setUnqualifiedProjectCount(BigDecimal.ZERO);
                    value.add(checkLargeScreenInspectionExecuteItemDto);
                });
            } else if (StringUtils.equals(CheckLevelEnum.DEPARTMENT_LEVEL.getCode(), checkLargeScreenInspectionExecuteDto.getCheckLevel())) {
                List<Long> unexecutedUserIdList = departmentTargetUserIdList.stream().filter(item -> !userIdList.contains(item)).collect(Collectors.toList());
                unexecutedUserIdList.forEach(item -> {
                    CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = targetUserMap.get(item);
                    CheckLargeScreenInspectionExecuteItemDto checkLargeScreenInspectionExecuteItemDto = new CheckLargeScreenInspectionExecuteItemDto();
                    checkLargeScreenInspectionExecuteItemDto.setTaskId(checkLargeScreenInspectionExecuteDto.getTaskId());
                    checkLargeScreenInspectionExecuteItemDto.setTaskCode(checkLargeScreenInspectionExecuteDto.getTaskCode());
                    checkLargeScreenInspectionExecuteItemDto.setTaskName(checkLargeScreenInspectionExecuteDto.getTaskName());
                    checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(checkLargeScreenInspectionExecuteDto.getRuleTypeNum());
                    checkLargeScreenInspectionExecuteItemDto.setUserId(checkLargeScreenInspectionExecuteUserDto.getUserId());
                    checkLargeScreenInspectionExecuteItemDto.setUserName(checkLargeScreenInspectionExecuteUserDto.getNickName());
                    checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setCheckOrderCount(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setRectificationOrderCount(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setUnqualifiedProjectCount(BigDecimal.ZERO);
                    value.add(checkLargeScreenInspectionExecuteItemDto);
                });
            } else if (StringUtils.equals(CheckLevelEnum.TEAM_LEVEL.getCode(), checkLargeScreenInspectionExecuteDto.getCheckLevel())) {
                List<Long> unexecutedUserIdList = teamTargetUserIdList.stream().filter(item -> !userIdList.contains(item)).collect(Collectors.toList());
                unexecutedUserIdList.forEach(item -> {
                    CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = targetUserMap.get(item);
                    CheckLargeScreenInspectionExecuteItemDto checkLargeScreenInspectionExecuteItemDto = new CheckLargeScreenInspectionExecuteItemDto();
                    checkLargeScreenInspectionExecuteItemDto.setTaskId(checkLargeScreenInspectionExecuteDto.getTaskId());
                    checkLargeScreenInspectionExecuteItemDto.setTaskCode(checkLargeScreenInspectionExecuteDto.getTaskCode());
                    checkLargeScreenInspectionExecuteItemDto.setTaskName(checkLargeScreenInspectionExecuteDto.getTaskName());
                    checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(checkLargeScreenInspectionExecuteDto.getRuleTypeNum());
                    checkLargeScreenInspectionExecuteItemDto.setUserId(checkLargeScreenInspectionExecuteUserDto.getUserId());
                    checkLargeScreenInspectionExecuteItemDto.setUserName(checkLargeScreenInspectionExecuteUserDto.getNickName());
                    checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setCheckOrderCount(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setRectificationOrderCount(BigDecimal.ZERO);
                    checkLargeScreenInspectionExecuteItemDto.setUnqualifiedProjectCount(BigDecimal.ZERO);
                    value.add(checkLargeScreenInspectionExecuteItemDto);
                });
            } else {

            }
        });

        // 数据处理-遍历任务单
        result.forEach(resultItem -> {
            List<CheckLargeScreenInspectionExecuteItemDto> checkLargeScreenInspectionExecuteItemDtoList = checkLargeScreenInspectionExecuteItemDtoMap.get(resultItem.getTaskCode());
            if (CollUtil.isNotEmpty(checkLargeScreenInspectionExecuteItemDtoList)) {
                // 补充数据
                checkLargeScreenInspectionExecuteItemDtoList.forEach(checkLargeScreenInspectionExecuteItemDto -> {
                    checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(checkLargeScreenInspectionExecuteItemDto.getCheckOrderCount().multiply(new BigDecimal("100")).divide(BigDecimal.valueOf(resultItem.getRuleTypeNum()), 2, RoundingMode.HALF_UP));
                    checkLargeScreenInspectionExecuteItemDto.setTaskId(resultItem.getTaskId());
                    checkLargeScreenInspectionExecuteItemDto.setTaskName(resultItem.getTaskName());
                    checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(resultItem.getRuleTypeNum());
                });
            } else {
                // 任务单无任何检查单-补充未执行用户数据
                checkLargeScreenInspectionExecuteItemDtoList = new ArrayList<>();
                if (StringUtils.equals(CheckLevelEnum.STATION_LEVEL.getCode(), resultItem.getCheckLevel())) {
                    for (Long item : stationTargetUserIdList) {
                        CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = targetUserMap.get(item);
                        CheckLargeScreenInspectionExecuteItemDto checkLargeScreenInspectionExecuteItemDto = new CheckLargeScreenInspectionExecuteItemDto();
                        checkLargeScreenInspectionExecuteItemDto.setTaskId(resultItem.getTaskId());
                        checkLargeScreenInspectionExecuteItemDto.setTaskCode(resultItem.getTaskCode());
                        checkLargeScreenInspectionExecuteItemDto.setTaskName(resultItem.getTaskName());
                        checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(resultItem.getRuleTypeNum());
                        checkLargeScreenInspectionExecuteItemDto.setUserId(checkLargeScreenInspectionExecuteUserDto.getUserId());
                        checkLargeScreenInspectionExecuteItemDto.setUserName(checkLargeScreenInspectionExecuteUserDto.getNickName());
                        checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setCheckOrderCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setRectificationOrderCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setUnqualifiedProjectCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDtoList.add(checkLargeScreenInspectionExecuteItemDto);
                    }
                } else if (StringUtils.equals(CheckLevelEnum.BRIGADE_LEVEL.getCode(), resultItem.getCheckLevel())) {
                    for (Long item : brigadeTargetUserIdList) {
                        CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = targetUserMap.get(item);
                        CheckLargeScreenInspectionExecuteItemDto checkLargeScreenInspectionExecuteItemDto = new CheckLargeScreenInspectionExecuteItemDto();
                        checkLargeScreenInspectionExecuteItemDto.setTaskId(resultItem.getTaskId());
                        checkLargeScreenInspectionExecuteItemDto.setTaskCode(resultItem.getTaskCode());
                        checkLargeScreenInspectionExecuteItemDto.setTaskName(resultItem.getTaskName());
                        checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(resultItem.getRuleTypeNum());
                        checkLargeScreenInspectionExecuteItemDto.setUserId(checkLargeScreenInspectionExecuteUserDto.getUserId());
                        checkLargeScreenInspectionExecuteItemDto.setUserName(checkLargeScreenInspectionExecuteUserDto.getNickName());
                        checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setCheckOrderCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setRectificationOrderCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setUnqualifiedProjectCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDtoList.add(checkLargeScreenInspectionExecuteItemDto);
                    }
                } else if (StringUtils.equals(CheckLevelEnum.DEPARTMENT_LEVEL.getCode(), resultItem.getCheckLevel())) {
                    for (Long item : departmentTargetUserIdList) {
                        CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = targetUserMap.get(item);
                        CheckLargeScreenInspectionExecuteItemDto checkLargeScreenInspectionExecuteItemDto = new CheckLargeScreenInspectionExecuteItemDto();
                        checkLargeScreenInspectionExecuteItemDto.setTaskId(resultItem.getTaskId());
                        checkLargeScreenInspectionExecuteItemDto.setTaskCode(resultItem.getTaskCode());
                        checkLargeScreenInspectionExecuteItemDto.setTaskName(resultItem.getTaskName());
                        checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(resultItem.getRuleTypeNum());
                        checkLargeScreenInspectionExecuteItemDto.setUserId(checkLargeScreenInspectionExecuteUserDto.getUserId());
                        checkLargeScreenInspectionExecuteItemDto.setUserName(checkLargeScreenInspectionExecuteUserDto.getNickName());
                        checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setCheckOrderCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setRectificationOrderCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setUnqualifiedProjectCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDtoList.add(checkLargeScreenInspectionExecuteItemDto);
                    }
                } else if (StringUtils.equals(CheckLevelEnum.TEAM_LEVEL.getCode(), resultItem.getCheckLevel())) {
                    for (Long item : teamTargetUserIdList) {
                        CheckLargeScreenInspectionExecuteUserDto checkLargeScreenInspectionExecuteUserDto = targetUserMap.get(item);
                        CheckLargeScreenInspectionExecuteItemDto checkLargeScreenInspectionExecuteItemDto = new CheckLargeScreenInspectionExecuteItemDto();
                        checkLargeScreenInspectionExecuteItemDto.setTaskId(resultItem.getTaskId());
                        checkLargeScreenInspectionExecuteItemDto.setTaskCode(resultItem.getTaskCode());
                        checkLargeScreenInspectionExecuteItemDto.setTaskName(resultItem.getTaskName());
                        checkLargeScreenInspectionExecuteItemDto.setRuleTypeNum(resultItem.getRuleTypeNum());
                        checkLargeScreenInspectionExecuteItemDto.setUserId(checkLargeScreenInspectionExecuteUserDto.getUserId());
                        checkLargeScreenInspectionExecuteItemDto.setUserName(checkLargeScreenInspectionExecuteUserDto.getNickName());
                        checkLargeScreenInspectionExecuteItemDto.setCompletionPercentage(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setCheckOrderCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setRectificationOrderCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDto.setUnqualifiedProjectCount(BigDecimal.ZERO);
                        checkLargeScreenInspectionExecuteItemDtoList.add(checkLargeScreenInspectionExecuteItemDto);
                    }
                } else {

                }
            }
            resultItem.setCheckLargeScreenInspectionExecuteItemDtoList(checkLargeScreenInspectionExecuteItemDtoList);
        });

        // 人数统计
        for (CheckLargeScreenInspectionExecuteDto checkLargeScreenInspectionExecuteDto : result) {
            Long ruleTypeNum = checkLargeScreenInspectionExecuteDto.getRuleTypeNum();
            long completedCount = checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList().stream().filter(item -> item.getCheckOrderCount().longValue() != 0 && item.getCheckOrderCount().longValue() >= ruleTypeNum).count();
            long inProgressCount = checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList().stream().filter(item -> item.getCheckOrderCount().longValue() != 0 && item.getCheckOrderCount().longValue() < ruleTypeNum).count();
            long notStartedCount = checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList().stream().filter(item -> item.getCheckOrderCount().longValue() == 0).count();
            checkLargeScreenInspectionExecuteDto.setCompletedCount(BigDecimal.valueOf(completedCount));
            checkLargeScreenInspectionExecuteDto.setInProgressCount(BigDecimal.valueOf(inProgressCount));
            checkLargeScreenInspectionExecuteDto.setNotStartedCount(BigDecimal.valueOf(notStartedCount));
        }

        //根据登录用户角色处理数据
        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())) {
            return result;
        } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
            return result;
        } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
            List<CheckLargeScreenInspectionExecuteDto> resultBrigade = result.stream()
                    .filter(checkLargeScreenInspectionExecuteDto -> StringUtils.equals(CheckLevelEnum.BRIGADE_LEVEL.getCode(), checkLargeScreenInspectionExecuteDto.getCheckLevel()))
                    .map(checkLargeScreenInspectionExecuteDto -> {
                                CheckLargeScreenInspectionExecuteDto temp = new CheckLargeScreenInspectionExecuteDto();
                                temp.setTaskId(checkLargeScreenInspectionExecuteDto.getTaskId());
                                temp.setTaskCode(checkLargeScreenInspectionExecuteDto.getTaskCode());
                                temp.setTaskName(checkLargeScreenInspectionExecuteDto.getTaskName());
                                temp.setCheckLevel(checkLargeScreenInspectionExecuteDto.getCheckLevel());
                                temp.setCheckLevelDesc(checkLargeScreenInspectionExecuteDto.getCheckLevelDesc());
                                temp.setRuleTypeNum(checkLargeScreenInspectionExecuteDto.getRuleTypeNum());
                                temp.setCheckStartTime(checkLargeScreenInspectionExecuteDto.getCheckStartTime());
                                temp.setCheckEndTime(checkLargeScreenInspectionExecuteDto.getCheckEndTime());
                                temp.setCompletedCount(checkLargeScreenInspectionExecuteDto.getCompletedCount());
                                temp.setInProgressCount(checkLargeScreenInspectionExecuteDto.getInProgressCount());
                                temp.setNotStartedCount(checkLargeScreenInspectionExecuteDto.getNotStartedCount());
                                if (CollUtil.isNotEmpty(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList())) {
                                    temp.setCheckLargeScreenInspectionExecuteItemDtoList(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList().stream()
                                            .filter(itemDto -> SecurityUtils.getLoginUser().getUserId().equals(itemDto.getUserId()))
                                            .collect(Collectors.toList()));
                                }
                                return temp;
                            }
                    )
                    .filter(checkLargeScreenInspectionExecuteDto -> CollUtil.isNotEmpty(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList()))
                    .collect(Collectors.toList());
            resultBrigade.addAll(result.stream()
                    .filter(checklargeScreenInspectionExecuteDto -> StringUtils.equals(CheckLevelEnum.DEPARTMENT_LEVEL.getCode(), checklargeScreenInspectionExecuteDto.getCheckLevel()))
                    .collect(Collectors.toList()));
            resultBrigade.addAll(result.stream()
                    .filter(checklargeScreenInspectionExecuteDto -> StringUtils.equals(CheckLevelEnum.TEAM_LEVEL.getCode(), checklargeScreenInspectionExecuteDto.getCheckLevel()))
                    .collect(Collectors.toList()));
            return resultBrigade;
        } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
            List<CheckLargeScreenInspectionExecuteDto> resultKeZhang = result.stream()
                    .filter(checkLargeScreenInspectionExecuteDto -> StringUtils.equals(CheckLevelEnum.DEPARTMENT_LEVEL.getCode(), checkLargeScreenInspectionExecuteDto.getCheckLevel()))
                    .map(checkLargeScreenInspectionExecuteDto -> {
                                CheckLargeScreenInspectionExecuteDto temp = new CheckLargeScreenInspectionExecuteDto();
                                temp.setTaskId(checkLargeScreenInspectionExecuteDto.getTaskId());
                                temp.setTaskCode(checkLargeScreenInspectionExecuteDto.getTaskCode());
                                temp.setTaskName(checkLargeScreenInspectionExecuteDto.getTaskName());
                                temp.setCheckLevel(checkLargeScreenInspectionExecuteDto.getCheckLevel());
                                temp.setCheckLevelDesc(checkLargeScreenInspectionExecuteDto.getCheckLevelDesc());
                                temp.setRuleTypeNum(checkLargeScreenInspectionExecuteDto.getRuleTypeNum());
                                temp.setCheckStartTime(checkLargeScreenInspectionExecuteDto.getCheckStartTime());
                                temp.setCheckEndTime(checkLargeScreenInspectionExecuteDto.getCheckEndTime());
                                temp.setCompletedCount(checkLargeScreenInspectionExecuteDto.getCompletedCount());
                                temp.setInProgressCount(checkLargeScreenInspectionExecuteDto.getInProgressCount());
                                temp.setNotStartedCount(checkLargeScreenInspectionExecuteDto.getNotStartedCount());
                                if (CollUtil.isNotEmpty(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList())) {
                                    temp.setCheckLargeScreenInspectionExecuteItemDtoList(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList().stream()
                                            .filter(itemDto -> SecurityUtils.getLoginUser().getUserId().equals(itemDto.getUserId()))
                                            .collect(Collectors.toList()));
                                }
                                return temp;
                            }
                    )
                    .filter(checkLargeScreenInspectionExecuteDto -> CollUtil.isNotEmpty(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList()))
                    .collect(Collectors.toList());
            resultKeZhang.addAll(result.stream()
                    .filter(checklargeScreenInspectionExecuteDto -> StringUtils.equals(CheckLevelEnum.TEAM_LEVEL.getCode(), checklargeScreenInspectionExecuteDto.getCheckLevel()))
                    .collect(Collectors.toList()));
            return resultKeZhang;
        } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
            List<CheckLargeScreenInspectionExecuteDto> resultBanZuZhang = result.stream()
                    .filter(checkLargeScreenInspectionExecuteDto -> StringUtils.equals(CheckLevelEnum.TEAM_LEVEL.getCode(), checkLargeScreenInspectionExecuteDto.getCheckLevel()))
                    .map(checkLargeScreenInspectionExecuteDto -> {
                                CheckLargeScreenInspectionExecuteDto temp = new CheckLargeScreenInspectionExecuteDto();
                                temp.setTaskId(checkLargeScreenInspectionExecuteDto.getTaskId());
                                temp.setTaskCode(checkLargeScreenInspectionExecuteDto.getTaskCode());
                                temp.setTaskName(checkLargeScreenInspectionExecuteDto.getTaskName());
                                temp.setCheckLevel(checkLargeScreenInspectionExecuteDto.getCheckLevel());
                                temp.setCheckLevelDesc(checkLargeScreenInspectionExecuteDto.getCheckLevelDesc());
                                temp.setRuleTypeNum(checkLargeScreenInspectionExecuteDto.getRuleTypeNum());
                                temp.setCheckStartTime(checkLargeScreenInspectionExecuteDto.getCheckStartTime());
                                temp.setCheckEndTime(checkLargeScreenInspectionExecuteDto.getCheckEndTime());
                                temp.setCompletedCount(checkLargeScreenInspectionExecuteDto.getCompletedCount());
                                temp.setInProgressCount(checkLargeScreenInspectionExecuteDto.getInProgressCount());
                                temp.setNotStartedCount(checkLargeScreenInspectionExecuteDto.getNotStartedCount());
                                if (CollUtil.isNotEmpty(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList())) {
                                    temp.setCheckLargeScreenInspectionExecuteItemDtoList(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList().stream()
                                            .filter(itemDto -> SecurityUtils.getLoginUser().getUserId().equals(itemDto.getUserId()))
                                            .collect(Collectors.toList()));
                                }
                                return temp;
                            }
                    )
                    .filter(checkLargeScreenInspectionExecuteDto -> CollUtil.isNotEmpty(checkLargeScreenInspectionExecuteDto.getCheckLargeScreenInspectionExecuteItemDtoList()))
                    .collect(Collectors.toList());
            return resultBanZuZhang;
        } else {
            return Collections.emptyList();
        }
    }

    /**
     * 巡检画像
     *
     * @param dto 大屏查询参数
     * @return 巡检画像
     */
    @Override
    public CheckLargeScreenCorrectionPortraitDto portrait(CheckLargeScreenCorrectionQueryParamDto dto) {
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeDays(91));
        }

        // 返回结果
        CheckLargeScreenCorrectionPortraitDto result = new CheckLargeScreenCorrectionPortraitDto();

        CheckLargeScreenCorrectionQueryParamDto tempQueryParam = new CheckLargeScreenCorrectionQueryParamDto();
        tempQueryParam.setIsSelfCheck(dto.getIsSelfCheck());
        tempQueryParam.setSpecifiedDate(dto.getSpecifiedDate());
        tempQueryParam.setStartDate(dto.getStartDate());
        tempQueryParam.setEndDate(dto.getEndDate());
        tempQueryParam.setProcessStatus("3");//ProcessStatusEnum.ARCHIVED.getCode()-归档
        List<CheckLargeScreenCorrectionPortraitSqlDto> all = checkLargeScreenMapper.portrait(tempQueryParam);
        if (CollUtil.isEmpty(all)) {
            return null;
        }
        //补充检查级别为站级的整改单中的被检查班组数据
        List<Long> userIdList = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedTeamId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userIdList)) {
            List<SysUser> sysUserList = sysUserService.selectByUserIdList(userIdList);
            Map<Long, Long> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getDeptId, (oldValue, newValue) -> newValue));
            List<Long> deptIdListTemp = sysUserList.stream().map(SysUser::getDeptId).distinct().collect(Collectors.toList());
            List<SysDept> deptListTemp = sysDeptService.selectDeptByIdList(deptIdListTemp);
            Map<Long, String> deptMap = deptListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
            all.forEach(item -> {
                if (ObjectUtil.isNull(item.getCheckedTeamId())) {
                    item.setCheckedTeamId(sysUserMap.getOrDefault(item.getUserId(), 0L));
                    item.setCheckedTeamName(deptMap.getOrDefault(item.getCheckedTeamId(), ""));
                }
            });
        }
        //补充被检查班科室数据
        List<Long> checkedTeamIdListTemp = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedDepartmentId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(checkedTeamIdListTemp)) {
            List<SysDept> checkedTeamListTemp = sysDeptService.selectDeptByIdList(checkedTeamIdListTemp);
            if (CollUtil.isNotEmpty(checkedTeamListTemp)) {
                Map<Long, Long> deptIdMap = checkedTeamListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getParentId, (oldValue, newValue) -> newValue));
                List<Long> checkedDepartmentIdListTemp = checkedTeamListTemp.stream().map(SysDept::getParentId).collect(Collectors.toList());
                List<SysDept> checkedDepartmentListTemp = sysDeptService.selectDeptByIdList(checkedDepartmentIdListTemp);
                if (CollUtil.isNotEmpty(checkedDepartmentListTemp)) {
                    Map<Long, String> deptMap = checkedDepartmentListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
                    all.forEach(item -> {
                        if (ObjectUtil.isNull(item.getCheckedDepartmentId())) {
                            item.setCheckedDepartmentId(deptIdMap.getOrDefault(item.getCheckedTeamId(), 0L));
                            item.setCheckedDepartmentName(deptMap.getOrDefault(item.getCheckedDepartmentId(), ""));
                        }
                    });
                }
            }
        }

        // 查询条件处理
        Long brigadeId = dto.getCheckedBrigadeId();
        Long departmentId = dto.getCheckedDepartmentId();
        Long teamId = dto.getCheckedTeamId();
        Long userId = dto.getCheckedUserId();
        if (ObjUtil.isNull(dto.getCheckedBrigadeId()) && ObjUtil.isNull(dto.getCheckedDepartmentId()) && ObjUtil.isNull(dto.getCheckedTeamId()) && ObjUtil.isNull(dto.getCheckedUserId())) {
            List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
            if (CollUtil.isEmpty(roles)) {
                return null;
            }
            List<String> roleKeyList = roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
            if (roleKeyList.contains(RoleTypeEnum.admin.getCode())) {
                dto.setIsSelfCheck(null);
            } else if (roleKeyList.contains(RoleTypeEnum.test.getCode()) || roleKeyList.contains(RoleTypeEnum.zhijianke.getCode())) {
                dto.setIsSelfCheck(null);
            } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                dto.setIsSelfCheck(null);
                brigadeId = SecurityUtils.getLoginUser().getDeptId();
                dto.setCheckedBrigadeId(brigadeId);
            } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                dto.setIsSelfCheck(null);
                departmentId = SecurityUtils.getLoginUser().getDeptId();
                dto.setCheckedDepartmentId(departmentId);
            } else if (roleKeyList.contains(RoleTypeEnum.banzuzhang.getCode())) {
                dto.setIsSelfCheck(null);
                teamId = SecurityUtils.getLoginUser().getDeptId();
                dto.setCheckedTeamId(teamId);
            } else if (roleKeyList.contains(RoleTypeEnum.SecurityCheck.getCode())) {
                dto.setIsSelfCheck(null);
                userId = SecurityUtils.getLoginUser().getUserId();
                dto.setCheckedUserId(userId);
            } else {
                return null;
            }
        } else {
            dto.setIsSelfCheck(null);
            if (ObjUtil.isNotNull(userId)) {
                dto.setCheckedUserId(userId);
            } else if (ObjUtil.isNotNull(teamId)) {
                dto.setCheckedTeamId(teamId);
            } else if (ObjUtil.isNotNull(departmentId)) {
                dto.setCheckedDepartmentId(departmentId);
            } else if (ObjUtil.isNotNull(brigadeId)) {
                dto.setCheckedBrigadeId(brigadeId);
            } else {
                return null;
            }
        }

        // 传入的用户角色为部门管理员时，则查询部门数据。其中班组长不做处理，由前端处理
        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.setCheckedUserId(userId);
                } else if (roleKeyList.contains(RoleTypeEnum.jingli.getCode()) || roleKeyList.contains(RoleTypeEnum.xingzheng.getCode())) {
                    userId = null;
                    dto.setCheckedUserId(userId);
                    brigadeId = sysUser.getDeptId();
                    dto.setCheckedBrigadeId(brigadeId);
                } else if (roleKeyList.contains(RoleTypeEnum.kezhang.getCode())) {
                    userId = null;
                    dto.setCheckedUserId(userId);
                    departmentId = sysUser.getDeptId();
                    dto.setCheckedDepartmentId(departmentId);
                } else {
                    // 保持原逻辑
                }
            }
        }

        List<CheckLargeScreenCorrectionPortraitSqlDto> target;
        // 个人
        if (ObjUtil.isNotNull(userId)) {
            Long finalUserId = userId;
            target = all.stream().filter(item -> ObjUtil.equals(item.getUserId(), finalUserId)).collect(Collectors.toList());
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (ObjUtil.isNotNull(sysUser.getDeptId())) {
                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<CheckLargeScreenCorrectionPortraitSqlDto> teamList = all.stream().filter(item -> ObjUtil.equals(item.getCheckedTeamId(), team.getDeptId())).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(teamList)) {
                            Map<Long, Long> userIdCountMap = teamList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getUserId, Collectors.counting()));
                            Map<Long, Long> tempMap = new HashMap<>();
                            List<SysUser> sysUserTempList = sysUserService.selectUserByDeptId(team.getDeptId());
                            sysUserTempList = sysUserTempList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(sysUserTempList)) {
                                List<Long> sysUserIdTempList = sysUserTempList.stream().map(SysUser::getUserId).distinct().collect(Collectors.toList());
                                sysUserIdTempList.forEach(item -> {
                                    tempMap.put(item, userIdCountMap.getOrDefault(item, 0L));
                                });
                                result.setTeamTotal(sysUserIdTempList.size());
                                // 1. 按值升序排序
                                List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.comparingByValue())
                                        .collect(Collectors.toList());
                                // 2. 计算排名（考虑并列情况）
                                Map<Long, Integer> rankMap = new HashMap<>();
                                int currentRank = 1;
                                Long prevValue = null;
                                int sameValueCount = 1; // 记录相同值的用户数
                                for (int i = 0; i < sortedEntries.size(); i++) {
                                    Map.Entry<Long, Long> entry = sortedEntries.get(i);
                                    Long 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);
                                result.setTeamRanking(integer);
                            }
                        }
                    }
                    // 本科排名处理
                    if (ObjUtil.isNotNull(department)) {
                        List<CheckLargeScreenCorrectionPortraitSqlDto> departmentList = all.stream().filter(item -> ObjUtil.equals(item.getCheckedDepartmentId(), department.getDeptId())).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(departmentList)) {
                            Map<Long, Long> userIdCountMap = departmentList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getUserId, Collectors.counting()));
                            Map<Long, Long> tempMap = new HashMap<>();
                            List<SysUser> sysUserTempList = sysUserService.selectUserByDeptId(department.getDeptId());
                            sysUserTempList = sysUserTempList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(sysUserTempList)) {
                                List<Long> sysUserIdTempList = sysUserTempList.stream().map(SysUser::getUserId).distinct().collect(Collectors.toList());
                                sysUserIdTempList.forEach(item -> {
                                    tempMap.put(item, userIdCountMap.getOrDefault(item, 0L));
                                });
                                result.setDepartmentTotal(sysUserIdTempList.size());
                                // 1. 按值升序排序
                                List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.comparingByValue())
                                        .collect(Collectors.toList());
                                // 2. 计算排名（考虑并列情况）
                                Map<Long, Integer> rankMap = new HashMap<>();
                                int currentRank = 1;
                                Long prevValue = null;
                                int sameValueCount = 1; // 记录相同值的用户数
                                for (int i = 0; i < sortedEntries.size(); i++) {
                                    Map.Entry<Long, Long> entry = sortedEntries.get(i);
                                    Long 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);
                                result.setDepartmentRanking(integer);
                            }
                        }
                    }
                    // 本大队排名处理
                    if (ObjUtil.isNotNull(brigade)) {
                        List<CheckLargeScreenCorrectionPortraitSqlDto> brigadeList = all.stream().filter(item -> ObjUtil.equals(item.getCheckedBrigadeId(), brigade.getDeptId())).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(brigadeList)) {
                            Map<Long, Long> userIdCountMap = brigadeList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getUserId, Collectors.counting()));
                            Map<Long, Long> tempMap = new HashMap<>();
                            List<SysUser> sysUserTempList = sysUserService.selectUserByDeptId(brigade.getDeptId());
                            sysUserTempList = sysUserTempList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(sysUserTempList)) {
                                List<Long> sysUserIdTempList = sysUserTempList.stream().map(SysUser::getUserId).distinct().collect(Collectors.toList());
                                sysUserIdTempList.forEach(item -> {
                                    tempMap.put(item, userIdCountMap.getOrDefault(item, 0L));
                                });
                                result.setBrigadeTotal(sysUserIdTempList.size());
                                // 1. 按值升序排序
                                List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.comparingByValue())
                                        .collect(Collectors.toList());
                                // 2. 计算排名（考虑并列情况）
                                Map<Long, Integer> rankMap = new HashMap<>();
                                int currentRank = 1;
                                Long prevValue = null;
                                int sameValueCount = 1; // 记录相同值的用户数
                                for (int i = 0; i < sortedEntries.size(); i++) {
                                    Map.Entry<Long, Long> entry = sortedEntries.get(i);
                                    Long 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);
                                result.setBrigadeRanking(integer);
                            }
                        }
                    }
                    // 本站排名处理
                    if (ObjUtil.isNotNull(station)) {
                        List<CheckLargeScreenCorrectionPortraitSqlDto> stationList = all;
                        if (CollUtil.isNotEmpty(stationList)) {
                            Map<Long, Long> userIdCountMap = stationList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getUserId, Collectors.counting()));
                            Map<Long, Long> tempMap = new HashMap<>();
                            List<SysUser> sysUserTempList = sysUserService.selectUserByDeptId(station.getDeptId());
                            sysUserTempList = sysUserTempList.stream().filter(item -> item.getRoles().stream().anyMatch(sysRole -> RoleTypeEnum.banzuzhang.getCode().equals(sysRole.getRoleKey()) || RoleTypeEnum.SecurityCheck.getCode().equals(sysRole.getRoleKey()))).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(sysUserTempList)) {
                                List<Long> sysUserIdTempList = sysUserTempList.stream().map(SysUser::getUserId).distinct().collect(Collectors.toList());
                                sysUserIdTempList.forEach(item -> {
                                    tempMap.put(item, userIdCountMap.getOrDefault(item, 0L));
                                });
                                result.setStationTotal(sysUserIdTempList.size());
                                // 1. 按值升序排序
                                List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.comparingByValue())
                                        .collect(Collectors.toList());
                                // 2. 计算排名（考虑并列情况）
                                Map<Long, Integer> rankMap = new HashMap<>();
                                int currentRank = 1;
                                Long prevValue = null;
                                int sameValueCount = 1; // 记录相同值的用户数
                                for (int i = 0; i < sortedEntries.size(); i++) {
                                    Map.Entry<Long, Long> entry = sortedEntries.get(i);
                                    Long 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);
                                result.setStationRanking(integer);
                            }
                        }
                    }
                }
            }
        } else if (ObjUtil.isNotNull(teamId)) {
            // 班组
            Long finalTeamId = teamId;
            target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedTeamId(), finalTeamId)).collect(Collectors.toList());
//            if (CollUtil.isEmpty(target)) {
//                return null;
//            }
            // 本科排名处理
            SysDept sysDeptTeam = sysDeptService.selectDeptById(teamId);
            Long ksId = sysDeptTeam.getParentId();
            List<CheckLargeScreenCorrectionPortraitSqlDto> departmentList = all.stream().filter(item -> ObjUtil.equals(item.getCheckedDepartmentId(), ksId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(departmentList)) {
                Map<Long, Long> teamIdCountMap = departmentList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId, Collectors.counting()));
                Map<Long, Long> tempMap = new HashMap<>();
                List<SysDept> deptList = sysDeptService.selectDeptInfoAll(new SysDept());
                deptList = deptList.stream().filter(item -> ObjUtil.equals(ksId, item.getParentId())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(deptList)) {
                    List<Long> teamIdTempList = deptList.stream().map(SysDept::getDeptId).distinct().collect(Collectors.toList());
                    teamIdTempList.forEach(item -> {
                        tempMap.put(item, teamIdCountMap.getOrDefault(item, 0L));
                    });
                    result.setDepartmentTotal(teamIdTempList.size());
                    // 1. 按值升序排序
                    List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                            .stream()
                            .sorted(Map.Entry.comparingByValue())
                            .collect(Collectors.toList());
                    // 2. 计算排名（考虑并列情况）
                    Map<Long, Integer> rankMap = new HashMap<>();
                    int currentRank = 1;
                    Long prevValue = null;
                    int sameValueCount = 1; // 记录相同值的用户数
                    for (int i = 0; i < sortedEntries.size(); i++) {
                        Map.Entry<Long, Long> entry = sortedEntries.get(i);
                        Long 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 = teamId;
                    Integer integer = rankMap.get(targetId);
                    result.setDepartmentRanking(integer);
                }
            }
            // 本大队排名处理
            SysDept sysDeptKs = sysDeptService.selectDeptById(ksId);
            Long ddId = sysDeptKs.getParentId();
            List<CheckLargeScreenCorrectionPortraitSqlDto> brigadeList = all.stream().filter(item -> ObjUtil.equals(item.getCheckedBrigadeId(), ddId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(brigadeList)) {
                Map<Long, Long> teamIdCountMap = brigadeList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId, Collectors.counting()));
                Map<Long, Long> tempMap = new HashMap<>();
                List<SysDept> deptList = sysDeptService.selectAllDept(ddId);
                deptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.TEAMS.getCode(), item.getDeptType())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(deptList)) {
                    List<Long> teamIdTempList = deptList.stream().map(SysDept::getDeptId).distinct().collect(Collectors.toList());
                    teamIdTempList.forEach(item -> {
                        tempMap.put(item, teamIdCountMap.getOrDefault(item, 0L));
                    });
                    result.setBrigadeTotal(teamIdTempList.size());
                    // 1. 按值升序排序
                    List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                            .stream()
                            .sorted(Map.Entry.comparingByValue())
                            .collect(Collectors.toList());
                    // 2. 计算排名（考虑并列情况）
                    Map<Long, Integer> rankMap = new HashMap<>();
                    int currentRank = 1;
                    Long prevValue = null;
                    int sameValueCount = 1; // 记录相同值的用户数
                    for (int i = 0; i < sortedEntries.size(); i++) {
                        Map.Entry<Long, Long> entry = sortedEntries.get(i);
                        Long 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 = teamId;
                    Integer integer = rankMap.get(targetId);
                    result.setBrigadeRanking(integer);
                }
            }
            // 本站排名处理
            List<CheckLargeScreenCorrectionPortraitSqlDto> stationList = all;
            if (CollUtil.isNotEmpty(stationList)) {
                Map<Long, Long> teamIdCountMap = stationList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId, Collectors.counting()));
                Map<Long, Long> tempMap = new HashMap<>();
                List<SysDept> deptList = sysDeptService.selectDeptInfoAll(new SysDept());
                deptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.TEAMS.getCode(), item.getDeptType())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(deptList)) {
                    List<Long> teamIdTempList = deptList.stream().map(SysDept::getDeptId).distinct().collect(Collectors.toList());
                    teamIdTempList.forEach(item -> {
                        tempMap.put(item, teamIdCountMap.getOrDefault(item, 0L));
                    });
                    result.setStationTotal(teamIdTempList.size());
                    // 1. 按值升序排序
                    List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                            .stream()
                            .sorted(Map.Entry.comparingByValue())
                            .collect(Collectors.toList());
                    // 2. 计算排名（考虑并列情况）
                    Map<Long, Integer> rankMap = new HashMap<>();
                    int currentRank = 1;
                    Long prevValue = null;
                    int sameValueCount = 1; // 记录相同值的用户数
                    for (int i = 0; i < sortedEntries.size(); i++) {
                        Map.Entry<Long, Long> entry = sortedEntries.get(i);
                        Long 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 = teamId;
                    Integer integer = rankMap.get(targetId);
                    result.setStationRanking(integer);
                }
            }
        } else if (ObjUtil.isNotNull(departmentId)) {
            // 科级
            Long finalDepartmentId = departmentId;
            target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedDepartmentId(), finalDepartmentId)).collect(Collectors.toList());
//            if (CollUtil.isEmpty(target)) {
//                return null;
//            }
            // 本大队排名处理
            SysDept sysDeptKs = sysDeptService.selectDeptById(departmentId);
            Long ddId = sysDeptKs.getParentId();
            List<CheckLargeScreenCorrectionPortraitSqlDto> brigadeList = all.stream().filter(item -> ObjUtil.equals(item.getCheckedBrigadeId(), ddId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(brigadeList)) {
                Map<Long, Long> departmentIdCountMap = brigadeList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedDepartmentId, Collectors.counting()));
                Map<Long, Long> tempMap = new HashMap<>();
                List<SysDept> deptList = sysDeptService.selectAllDept(ddId);
                deptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.MANAGER.getCode(), item.getDeptType())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(deptList)) {
                    List<Long> departmentIdTempList = deptList.stream().map(SysDept::getDeptId).distinct().collect(Collectors.toList());
                    departmentIdTempList.forEach(item -> {
                        tempMap.put(item, departmentIdCountMap.getOrDefault(item, 0L));
                    });
                    result.setBrigadeTotal(departmentIdTempList.size());
                    // 1. 按值升序排序
                    List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                            .stream()
                            .sorted(Map.Entry.comparingByValue())
                            .collect(Collectors.toList());
                    // 2. 计算排名（考虑并列情况）
                    Map<Long, Integer> rankMap = new HashMap<>();
                    int currentRank = 1;
                    Long prevValue = null;
                    int sameValueCount = 1; // 记录相同值的用户数
                    for (int i = 0; i < sortedEntries.size(); i++) {
                        Map.Entry<Long, Long> entry = sortedEntries.get(i);
                        Long 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 = departmentId;
                    Integer integer = rankMap.get(targetId);
                    result.setBrigadeRanking(integer);
                }
            }
            // 本站排名处理
            List<CheckLargeScreenCorrectionPortraitSqlDto> stationList = all;
            Map<Long, Long> departmentIdCountMap = stationList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedDepartmentId, Collectors.counting()));
            Map<Long, Long> tempMap = new HashMap<>();
            List<SysDept> deptList = sysDeptService.selectDeptInfoAll(new SysDept());
            deptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.MANAGER.getCode(), item.getDeptType())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(deptList)) {
                List<Long> departmentIdTempList = deptList.stream().map(SysDept::getDeptId).distinct().collect(Collectors.toList());
                departmentIdTempList.forEach(item -> {
                    tempMap.put(item, departmentIdCountMap.getOrDefault(item, 0L));
                });
                result.setStationTotal(departmentIdTempList.size());
                // 1. 按值升序排序
                List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByValue())
                        .collect(Collectors.toList());
                // 2. 计算排名（考虑并列情况）
                Map<Long, Integer> rankMap = new HashMap<>();
                int currentRank = 1;
                Long prevValue = null;
                int sameValueCount = 1; // 记录相同值的用户数
                for (int i = 0; i < sortedEntries.size(); i++) {
                    Map.Entry<Long, Long> entry = sortedEntries.get(i);
                    Long 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 = departmentId;
                Integer integer = rankMap.get(targetId);
                result.setStationRanking(integer);
            }
        } else if (ObjUtil.isNotNull(brigadeId)) {
            // 大队级
            Long finalbrigadeId = brigadeId;
            target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedBrigadeId(), finalbrigadeId)).collect(Collectors.toList());
//            if (CollUtil.isEmpty(target)) {
//                return null;
//            }
            // 本站排名处理
            List<CheckLargeScreenCorrectionPortraitSqlDto> stationList = all;
            Map<Long, Long> brigadeIdCountMap = stationList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedBrigadeId, Collectors.counting()));
            Map<Long, Long> tempMap = new HashMap<>();
            List<SysDept> deptList = sysDeptService.selectDeptInfoAll(new SysDept());
            deptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.BRIGADE.getCode(), item.getDeptType())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(deptList)) {
                List<Long> brigadeIdList = deptList.stream().map(SysDept::getDeptId).distinct().collect(Collectors.toList());
                brigadeIdList.forEach(item -> {
                    tempMap.put(item, brigadeIdCountMap.getOrDefault(item, 0L));
                });
                result.setStationTotal(brigadeIdList.size());
                // 1. 按值升序排序
                List<Map.Entry<Long, Long>> sortedEntries = tempMap.entrySet()
                        .stream()
                        .sorted(Map.Entry.comparingByValue())
                        .collect(Collectors.toList());
                // 2. 计算排名（考虑并列情况）
                Map<Long, Integer> rankMap = new HashMap<>();
                int currentRank = 1;
                Long prevValue = null;
                int sameValueCount = 1; // 记录相同值的用户数
                for (int i = 0; i < sortedEntries.size(); i++) {
                    Map.Entry<Long, Long> entry = sortedEntries.get(i);
                    Long 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 = brigadeId;
                Integer integer = rankMap.get(targetId);
                result.setStationRanking(integer);
            }
        } else {
            // 站级
            target = all;
            // 无排名
        }
        // 总问题数
        result.setSumCount(target.size());
        // 数量统计处理
        Map<Long, String> correctionTypeMap = target.stream().collect(Collectors.toMap(CheckLargeScreenCorrectionPortraitSqlDto::getId, CheckLargeScreenCorrectionPortraitSqlDto::getCorrectionType, (oldValue, newValue) -> newValue));
        result.setOnTimeCompletedCount((int) correctionTypeMap.values().stream().filter(item -> StrUtil.equals("ON_TIME_COMPLETED", item)).count());
        result.setOverTimeCompletedCount((int) correctionTypeMap.values().stream().filter(item -> StrUtil.equals("OVER_TIME_COMPLETED", item)).count());
        result.setOnTimeUnfinishedCount((int) correctionTypeMap.values().stream().filter(item -> StrUtil.equals("ON_TIME_UNFINISHED", item)).count());
        result.setOverTimeUnfinishedCount((int) correctionTypeMap.values().stream().filter(item -> StrUtil.equals("OVER_TIME_UNFINISHED", item)).count());
        result.setOtherCount((int) correctionTypeMap.values().stream().filter(item -> StrUtil.equals("OTHER", item)).count());
        // 部门及分类处理
        Map<String, Long> categoryCodeCountMap = target.stream().collect(Collectors.groupingBy(item -> item.getCheckedBrigadeId() + "***" + item.getCategoryCodeOne(), Collectors.counting()));
        BaseCheckCategory baseCheckCategory = new BaseCheckCategory();
        baseCheckCategory.setLevel(1);
        List<BaseCheckCategory> baseCheckCategoryList = baseCheckCategoryService.selectBaseCheckCategoryList(baseCheckCategory);
        List<CheckLargeScreenProblemDto> resultItemTempList = new ArrayList<>();
        List<String> checkedBrigadeList = target.stream().map(item -> item.getCheckedBrigadeId() + "###" + item.getCheckedBrigadeName()).distinct().collect(Collectors.toList());
        checkedBrigadeList.forEach(item -> {
            String[] split = item.split("###");
            Long deptId = Long.valueOf(split[0]);
            String deptName = split[1];
            baseCheckCategoryList.forEach(checkCategory -> {
                CheckLargeScreenProblemDto resultItem = new CheckLargeScreenProblemDto();
                resultItem.setDeptId(deptId);
                resultItem.setDeptName(deptName);
                resultItem.setCode(checkCategory.getCode());
                resultItem.setName(checkCategory.getName());
                resultItem.setTotal(BigDecimal.valueOf(categoryCodeCountMap.getOrDefault(deptId + "***" + checkCategory.getCode(), 0L)));
                resultItemTempList.add(resultItem);
            });
        });
        List<CheckLargeScreenProblemDto> resultItemAllTempList = new ArrayList<>();
        baseCheckCategoryList.forEach(checkCategory -> {
            CheckLargeScreenProblemDto resultItem = new CheckLargeScreenProblemDto();
            resultItem.setDeptId(null);
            resultItem.setDeptName("总数");
            resultItem.setCode(checkCategory.getCode());
            resultItem.setName(checkCategory.getName());
            resultItem.setTotal(resultItemTempList.stream().filter(item -> item.getCode().equals(checkCategory.getCode())).map(CheckLargeScreenCommonDto::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add));
            resultItemAllTempList.add(resultItem);
        });
        List<CheckLargeScreenProblemDto> resultItemList = new ArrayList<>();
        resultItemList.addAll(resultItemTempList);
        resultItemList.addAll(resultItemAllTempList);
        result.setCheckLargeScreenCommonDtoList(resultItemList);
        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));
        }

        // 查询出全量数据
        CheckLargeScreenCorrectionQueryParamDto tempQueryParam = new CheckLargeScreenCorrectionQueryParamDto();
        tempQueryParam.setSpecifiedDate(dto.getSpecifiedDate());
        tempQueryParam.setStartDate(dto.getStartDate());
        tempQueryParam.setEndDate(dto.getEndDate());
        tempQueryParam.setProcessStatus("3");//ProcessStatusEnum.ARCHIVED.getCode()-归档
        List<CheckLargeScreenCorrectionPortraitSqlDto> all = checkLargeScreenMapper.portrait(tempQueryParam);
        if (CollUtil.isEmpty(all)) {
            return BigDecimal.ZERO;
        }
        //补充检查级别为站级的整改单中的被检查班组数据
        List<Long> userIdList = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedTeamId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userIdList)) {
            List<SysUser> sysUserList = sysUserService.selectByUserIdList(userIdList);
            Map<Long, Long> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getDeptId, (oldValue, newValue) -> newValue));
            List<Long> deptIdList = sysUserList.stream().map(SysUser::getDeptId).distinct().collect(Collectors.toList());
            List<SysDept> deptList = sysDeptService.selectDeptByIdList(deptIdList);
            Map<Long, String> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
            all.forEach(item -> {
                if (ObjectUtil.isNull(item.getCheckedTeamId())) {
                    item.setCheckedTeamId(sysUserMap.getOrDefault(item.getUserId(), 0L));
                    item.setCheckedTeamName(deptMap.getOrDefault(item.getCheckedTeamId(), ""));
                }
            });
        }
        //补充被检查班科室数据
        List<Long> checkedTeamIdListTemp = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedDepartmentId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(checkedTeamIdListTemp)) {
            List<SysDept> checkedTeamListTemp = sysDeptService.selectDeptByIdList(checkedTeamIdListTemp);
            if (CollUtil.isNotEmpty(checkedTeamListTemp)) {
                Map<Long, Long> deptIdMap = checkedTeamListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getParentId, (oldValue, newValue) -> newValue));
                List<Long> checkedDepartmentIdListTemp = checkedTeamListTemp.stream().map(SysDept::getParentId).collect(Collectors.toList());
                List<SysDept> checkedDepartmentListTemp = sysDeptService.selectDeptByIdList(checkedDepartmentIdListTemp);
                if (CollUtil.isNotEmpty(checkedDepartmentListTemp)) {
                    Map<Long, String> deptMap = checkedDepartmentListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
                    all.forEach(item -> {
                        if (ObjectUtil.isNull(item.getCheckedDepartmentId())) {
                            item.setCheckedDepartmentId(deptIdMap.getOrDefault(item.getCheckedTeamId(), 0L));
                            item.setCheckedDepartmentName(deptMap.getOrDefault(item.getCheckedDepartmentId(), ""));
                        }
                    });
                }
            }
        }

        // 对全量数据进行过滤+处理返回数据
        List<CheckLargeScreenCorrectionPortraitSqlDto> target;
        if (ObjectUtil.isNotNull(dto.getUserId())) {
            // 个人
            target = all.stream().filter(item -> ObjUtil.equals(item.getUserId(), dto.getUserId())).collect(Collectors.toList());
        } else {
            // 组织
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (StrUtil.equals(DeptTypeEnum.STATION.getCode(), sysDept.getDeptType())) {
                target = all;
            } else if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
                target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedBrigadeId(), dto.getDeptId())).collect(Collectors.toList());
            } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
                target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedDepartmentId(), dto.getDeptId())).collect(Collectors.toList());
            } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
                target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedTeamId(), dto.getDeptId())).collect(Collectors.toList());
            } else {
                return BigDecimal.ZERO;
            }
        }
        int sum = target.size();
        return sum == 0 ? BigDecimal.ZERO : BigDecimal.valueOf(sum);
    }

    /**
     * 能力画像-明细
     *
     * @param dto 大屏查询参数
     * @return 能力画像-明细
     */
    @Override
    public List<SysLargeScreenDetailDto> detail(BaseLargeScreenQueryParamDto dto) {
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeDays(91));
        }

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

        // 查询出全量数据
        CheckLargeScreenCorrectionQueryParamDto tempQueryParam = new CheckLargeScreenCorrectionQueryParamDto();
        tempQueryParam.setSpecifiedDate(dto.getSpecifiedDate());
        tempQueryParam.setStartDate(dto.getStartDate());
        tempQueryParam.setEndDate(dto.getEndDate());
        tempQueryParam.setProcessStatus("3");//ProcessStatusEnum.ARCHIVED.getCode()-归档
        List<CheckLargeScreenCorrectionPortraitSqlDto> all = checkLargeScreenMapper.portrait(tempQueryParam);
        if (CollUtil.isEmpty(all)) {
            return Collections.emptyList();
        }
        //补充检查级别为站级的整改单中的被检查班组数据
        List<Long> userIdList = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedTeamId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userIdList)) {
            List<SysUser> sysUserList = sysUserService.selectByUserIdList(userIdList);
            Map<Long, Long> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getDeptId, (oldValue, newValue) -> newValue));
            List<Long> deptIdList = sysUserList.stream().map(SysUser::getDeptId).distinct().collect(Collectors.toList());
            List<SysDept> deptList = sysDeptService.selectDeptByIdList(deptIdList);
            Map<Long, String> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
            all.forEach(item -> {
                if (ObjectUtil.isNull(item.getCheckedTeamId())) {
                    item.setCheckedTeamId(sysUserMap.getOrDefault(item.getUserId(), 0L));
                    item.setCheckedTeamName(deptMap.getOrDefault(item.getCheckedTeamId(), ""));
                }
            });
        }
        //补充被检查班科室数据
        List<Long> checkedTeamIdListTemp = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedDepartmentId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(checkedTeamIdListTemp)) {
            List<SysDept> checkedTeamListTemp = sysDeptService.selectDeptByIdList(checkedTeamIdListTemp);
            if (CollUtil.isNotEmpty(checkedTeamListTemp)) {
                Map<Long, Long> deptIdMap = checkedTeamListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getParentId, (oldValue, newValue) -> newValue));
                List<Long> checkedDepartmentIdListTemp = checkedTeamListTemp.stream().map(SysDept::getParentId).collect(Collectors.toList());
                List<SysDept> checkedDepartmentListTemp = sysDeptService.selectDeptByIdList(checkedDepartmentIdListTemp);
                if (CollUtil.isNotEmpty(checkedDepartmentListTemp)) {
                    Map<Long, String> deptMap = checkedDepartmentListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
                    all.forEach(item -> {
                        if (ObjectUtil.isNull(item.getCheckedDepartmentId())) {
                            item.setCheckedDepartmentId(deptIdMap.getOrDefault(item.getCheckedTeamId(), 0L));
                            item.setCheckedDepartmentName(deptMap.getOrDefault(item.getCheckedDepartmentId(), ""));
                        }
                    });
                }
            }
        }

        // 对全量数据进行过滤+处理返回数据
        SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
        if (StrUtil.equals(DeptTypeEnum.STATION.getCode(), sysDept.getDeptType())) {
            List<CheckLargeScreenCorrectionPortraitSqlDto> target = all;
            Map<Long, String> map = target.stream().collect(Collectors.toMap(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedBrigadeId, CheckLargeScreenCorrectionPortraitSqlDto::getCheckedBrigadeName, (oldValue, newValue) -> newValue));
            Map<Long, List<CheckLargeScreenCorrectionPortraitSqlDto>> groupingBy = target.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedBrigadeId));
            groupingBy.forEach((key, value) -> {
                SysLargeScreenDetailDto temp = new SysLargeScreenDetailDto();
                temp.setId(key);
                temp.setName(map.getOrDefault(key, ""));
                int sum = value.size();
                long count = value.stream().map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().count();
                temp.setCheckCount(BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP));
                result.add(temp);
            });
        } else if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
            List<CheckLargeScreenCorrectionPortraitSqlDto> target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedBrigadeId(), dto.getDeptId())).collect(Collectors.toList());
            Map<Long, String> map = target.stream().collect(Collectors.toMap(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedDepartmentId, CheckLargeScreenCorrectionPortraitSqlDto::getCheckedDepartmentName, (oldValue, newValue) -> newValue));
            Map<Long, List<CheckLargeScreenCorrectionPortraitSqlDto>> groupingBy = target.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedDepartmentId));
            groupingBy.forEach((key, value) -> {
                SysLargeScreenDetailDto temp = new SysLargeScreenDetailDto();
                temp.setId(key);
                temp.setName(map.getOrDefault(key, ""));
                int sum = value.size();
                long count = value.stream().map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().count();
                temp.setCheckCount(BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP));
                result.add(temp);
            });
        } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
            List<CheckLargeScreenCorrectionPortraitSqlDto> target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedDepartmentId(), dto.getDeptId())).collect(Collectors.toList());
            Map<Long, String> map = target.stream().collect(Collectors.toMap(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId, CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamName, (oldValue, newValue) -> newValue));
            Map<Long, List<CheckLargeScreenCorrectionPortraitSqlDto>> groupingBy = target.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId));
            groupingBy.forEach((key, value) -> {
                SysLargeScreenDetailDto temp = new SysLargeScreenDetailDto();
                temp.setId(key);
                temp.setName(map.getOrDefault(key, ""));
                int sum = value.size();
                long count = value.stream().map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().count();
                temp.setCheckCount(BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP));
                result.add(temp);
            });
        } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
            List<CheckLargeScreenCorrectionPortraitSqlDto> target = all.stream().filter(item -> ObjUtil.equals(item.getCheckedTeamId(), dto.getDeptId())).collect(Collectors.toList());
            Map<Long, String> map = target.stream().collect(Collectors.toMap(CheckLargeScreenCorrectionPortraitSqlDto::getUserId, CheckLargeScreenCorrectionPortraitSqlDto::getUserName, (oldValue, newValue) -> newValue));
            Map<Long, List<CheckLargeScreenCorrectionPortraitSqlDto>> groupingBy = target.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getUserId));
            groupingBy.forEach((key, value) -> {
                SysLargeScreenDetailDto temp = new SysLargeScreenDetailDto();
                temp.setId(key);
                temp.setName(map.getOrDefault(key, ""));
                int sum = value.size();
                long count = value.stream().map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().count();
                temp.setCheckCount(BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP));
                result.add(temp);
            });
        } else {
            return Collections.emptyList();
        }
        return result;
    }

    /**
     * 工作画像-管理推动-检查单
     *
     * @param dto 大屏查询参数
     * @return 工作画像-管理推动-检查单
     */
    @Override
    public List<CheckLargeScreenPlanOverviewDto> managementPromotionRecord(CheckLargeScreenCorrectionQueryParamDto dto) {
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeDays(91));
        }

        // 1、参数校验
        validateDateRange(dto.getStartDate(), dto.getEndDate());
        // 2、生成日期序列
        List<Date> dateRange = generateDateRange(dto.getStartDate(), dto.getEndDate());
        // 3、获取所有类别
        SysDictData dictData = new SysDictData();
        dictData.setDictType("check_task_category");
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(dictData);
        Map<String, String> sysDictDataMap = sysDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<String> typeList = sysDictDataList.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
        // 4、构建统计映射
        Long deptId = dto.getDeptId();
        if (ObjUtil.isNotNull(deptId)) {
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
                dto.setCheckedBrigadeId(deptId);
            } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
                dto.setCheckedDepartmentId(deptId);
            } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
                dto.setCheckedTeamId(deptId);
            } else {

            }
        }
        List<CheckLargeScreenPlanOverviewDto> list = checkLargeScreenMapper.managementPromotionRecord(dto);
        Map<String, BigDecimal> statsMap = list.stream().collect(Collectors.toMap(item -> item.getType() + "***" + item.getDate(), CheckLargeScreenPlanOverviewDto::getTotal, (oldValue, newValue) -> newValue));
        // 5、组装最终结果
        List<CheckLargeScreenPlanOverviewDto> result = new ArrayList<>();
        dateRange.forEach(date -> {
            typeList.forEach(type -> {
                CheckLargeScreenPlanOverviewDto resultItem = new CheckLargeScreenPlanOverviewDto();
                resultItem.setDate(DateUtil.formatDate(date));
                resultItem.setType(type);
                resultItem.setTypeDesc(sysDictDataMap.getOrDefault(type, ""));
                resultItem.setTotal(ObjUtil.isNull(statsMap) ? BigDecimal.ZERO : statsMap.getOrDefault(type + "***" + DateUtil.formatDate(date), BigDecimal.ZERO));
                result.add(resultItem);
            });
        });
        return result;
    }

    /**
     * 工作画像-管理推动-整改单
     *
     * @param dto 大屏查询参数
     * @return 工作画像-管理推动-整改单
     */
    @Override
    public CheckLargeScreenCorrectionDto managementPromotionCorrection(CheckLargeScreenCorrectionQueryParamDto 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.setCheckedBrigadeId(deptId);
            } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
                dto.setCheckedDepartmentId(deptId);
            } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
                dto.setCheckedTeamId(deptId);
            } else {

            }
        }
        CheckLargeScreenCorrectionDto result = checkLargeScreenMapper.managementPromotionCorrection(dto);
        return result;
    }

    /**
     * 工作画像-工作产出-巡检问题统计图
     *
     * @param dto 大屏查询参数
     * @return 工作画像-工作产出-巡检问题统计图
     */
    @Override
    public List<CheckLargeScreenCommonDto> workOutputCheck(CheckLargeScreenCorrectionQueryParamDto dto) {
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeDays(91));
        }

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

        CheckLargeScreenCorrectionQueryParamDto tempQueryParam = new CheckLargeScreenCorrectionQueryParamDto();
        tempQueryParam.setIsSelfCheck(dto.getIsSelfCheck());
        tempQueryParam.setSpecifiedDate(dto.getSpecifiedDate());
        tempQueryParam.setStartDate(dto.getStartDate());
        tempQueryParam.setEndDate(dto.getEndDate());
        tempQueryParam.setProcessStatus("3");//ProcessStatusEnum.ARCHIVED.getCode()-归档
        List<CheckLargeScreenCorrectionPortraitSqlDto> all = checkLargeScreenMapper.portrait(tempQueryParam);

        //补充检查级别为站级的整改单中的被检查班组数据
        List<Long> userIdList = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedTeamId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userIdList)) {
            List<SysUser> sysUserList = sysUserService.selectByUserIdList(userIdList);
            Map<Long, Long> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getDeptId, (oldValue, newValue) -> newValue));
            List<Long> deptIdListTemp = sysUserList.stream().map(SysUser::getDeptId).distinct().collect(Collectors.toList());
            List<SysDept> deptListTemp = sysDeptService.selectDeptByIdList(deptIdListTemp);
            Map<Long, String> deptMap = deptListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
            all.forEach(item -> {
                if (ObjectUtil.isNull(item.getCheckedTeamId())) {
                    item.setCheckedTeamId(sysUserMap.getOrDefault(item.getUserId(), 0L));
                    item.setCheckedTeamName(deptMap.getOrDefault(item.getCheckedTeamId(), ""));
                }
            });
        }
        //补充被检查班科室数据
        List<Long> checkedTeamIdListTemp = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedDepartmentId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(checkedTeamIdListTemp)) {
            List<SysDept> checkedTeamListTemp = sysDeptService.selectDeptByIdList(checkedTeamIdListTemp);
            if (CollUtil.isNotEmpty(checkedTeamListTemp)) {
                Map<Long, Long> deptIdMap = checkedTeamListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getParentId, (oldValue, newValue) -> newValue));
                List<Long> checkedDepartmentIdListTemp = checkedTeamListTemp.stream().map(SysDept::getParentId).collect(Collectors.toList());
                List<SysDept> checkedDepartmentListTemp = sysDeptService.selectDeptByIdList(checkedDepartmentIdListTemp);
                if (CollUtil.isNotEmpty(checkedDepartmentListTemp)) {
                    Map<Long, String> deptMap = checkedDepartmentListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
                    all.forEach(item -> {
                        if (ObjectUtil.isNull(item.getCheckedDepartmentId())) {
                            item.setCheckedDepartmentId(deptIdMap.getOrDefault(item.getCheckedTeamId(), 0L));
                            item.setCheckedDepartmentName(deptMap.getOrDefault(item.getCheckedDepartmentId(), ""));
                        }
                    });
                }
            }
        }

        // 筛选部门
        Long deptId = dto.getDeptId();
        if (ObjUtil.isNotNull(deptId)) {
            SysDept sysDept = sysDeptService.selectDeptById(deptId);
            if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
                all = all.stream().filter(item -> item.getCheckedBrigadeId().equals(deptId)).collect(Collectors.toList());
            } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
                all = all.stream().filter(item -> item.getCheckedDepartmentId().equals(deptId)).collect(Collectors.toList());
            } else if (StrUtil.equals(DeptTypeEnum.TEAMS.getCode(), sysDept.getDeptType())) {
                all = all.stream().filter(item -> item.getCheckedTeamId().equals(deptId)).collect(Collectors.toList());
            }
        }

        // 数据处理
        Map<String, Long> categoryCodeCountMap = all.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCategoryCodeOne, Collectors.counting()));
        BaseCheckCategory baseCheckCategory = new BaseCheckCategory();
        baseCheckCategory.setLevel(1);
        List<BaseCheckCategory> baseCheckCategoryList = baseCheckCategoryService.selectBaseCheckCategoryList(baseCheckCategory);
        baseCheckCategoryList.forEach(checkCategory -> {
            CheckLargeScreenCommonDto resultItem = new CheckLargeScreenCommonDto();
            resultItem.setCode(checkCategory.getCode());
            resultItem.setName(checkCategory.getName());
            resultItem.setTotal(ObjUtil.isNull(categoryCodeCountMap) ? BigDecimal.ZERO : BigDecimal.valueOf(categoryCodeCountMap.getOrDefault(checkCategory.getCode(), 0L)));
            result.add(resultItem);
        });
        return result;
    }

    /**
     * 参数校验
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     */
    private void validateDateRange(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            throw new ServiceException("日期参数不能为空");
        }
        if (startDate.after(endDate)) {
            throw new ServiceException("开始日期不能晚于结束日期");
        }
    }

    /**
     * 生成日期序列
     *
     * @param start 开始日期
     * @param end   结束日期
     * @return 日期序列
     */
    private List<Date> generateDateRange(Date start, Date end) {
        List<Date> dates = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(start);

        while (!cal.getTime().after(end)) {
            dates.add(getDateWithoutTime(cal.getTime()));
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return dates;
    }

    /**
     * 获取日期的零时零分零秒
     *
     * @param date 日期
     * @return 零时零分零秒
     */
    private Date getDateWithoutTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 首页
     *
     * @param dto 首页查询参数
     * @return 首页
     */
    @Override
    public CheckLargeScreenHomePageDto homePage(BaseLargeScreenQueryParamDto dto, String source) {
        if (StrUtil.equals(SourceTypeEnum.web.getCode(), source)) {
            List<SysDept> sysDeptList = sysDeptService.selectAllDept(SecurityUtils.getLoginUser().getDeptId());
            Collections.reverse(sysDeptList);
            SysDept sysDept = sysDeptList.stream().filter(x -> StrUtil.equals(DeptType.STATION.getCode(), x.getDeptType())).findFirst().orElse(null);
            if (ObjectUtil.isNull(sysDept)) {
                throw new ServiceException("未查询到站级部门信息");
            }
            dto.setUserId(null);
            dto.setDeptId(sysDept.getDeptId());
        }

        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));
        }

        // 返回结果
        CheckLargeScreenHomePageDto result = new CheckLargeScreenHomePageDto();

        // 全量数据
        List<CheckLargeScreenHomePageItemDto> itemListAll = getCheckLargeScreenHomePageItemDtoList(dto);
        if (CollUtil.isEmpty(itemListAll)) {
            return result;
        }

        // 合格率+排序列表
        if (ObjUtil.isNotNull(dto.getUserId())) {
            SysUser sysUser = sysUserService.selectUserById(dto.getUserId());
            if (ObjUtil.isNull(sysUser.getDeptId())) {
                return result;
            }
            List<SysDept> deptList = sysDeptService.selectAllDept(sysUser.getDeptId());
            if (CollUtil.isEmpty(deptList)) {
                return result;
            }
            Collections.reverse(deptList);
            SysDept team = deptList.stream().filter(x -> StrUtil.equals(DeptType.TEAMS.getCode(), x.getDeptType())).findFirst().orElse(null);
            SysDept department = deptList.stream().filter(x -> StrUtil.equals(DeptType.MANAGER.getCode(), x.getDeptType())).findFirst().orElse(null);
            SysDept brigade = deptList.stream().filter(x -> StrUtil.equals(DeptType.BRIGADE.getCode(), x.getDeptType())).findFirst().orElse(null);
            SysDept station = deptList.stream().filter(x -> StrUtil.equals(DeptType.STATION.getCode(), x.getDeptType())).findFirst().orElse(null);

            result.setPersonalPassRate(itemListAll.stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).findFirst().map(CheckLargeScreenHomePageItemDto::getPassRate).orElse(BigDecimal.ONE));
            if (team != null) {
                result.setTeamPassRate(calculate(itemListAll, team.getDeptId()));
                result.setTeamRankingList(sort(itemListAll, team.getDeptId()));
                result.setTeamTotal(result.getTeamRankingList().size());
                result.setTeamRanking(result.getTeamRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            }
            if (department != null) {
                result.setDepartmentPassRate(calculate(itemListAll, department.getDeptId()));
                result.setDepartmentRankingList(sort(itemListAll, department.getDeptId()));
                result.setDepartmentTotal(result.getDepartmentRankingList().size());
                result.setDepartmentRanking(result.getDepartmentRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            }
            if (brigade != null) {
                result.setBrigadePassRate(calculate(itemListAll, brigade.getDeptId()));
                result.setBrigadeRankingList(sort(itemListAll, brigade.getDeptId()));
                result.setBrigadeTotal(result.getBrigadeRankingList().size());
                result.setBrigadeRanking(result.getBrigadeRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            }
            if (station != null) {
                result.setStationPassRate(calculate(itemListAll, station.getDeptId()));
                result.setStationRankingList(sort(itemListAll, station.getDeptId()));
                result.setStationTotal(result.getStationRankingList().size());
                result.setStationRanking(result.getStationRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            }
        } else {
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (ObjUtil.isNull(sysDept)) {
                return result;
            }
            if (ObjUtil.equals(DeptType.TEAMS.getCode(), sysDept.getDeptType())) {
                SysDept teamDept = sysDept;
                result.setTeamPassRate(calculate(itemListAll, teamDept.getDeptId()));
                SysDept departmentDept = sysDeptService.selectDeptById(teamDept.getParentId());
                result.setDepartmentPassRate(calculate(itemListAll, departmentDept.getDeptId()));
                SysDept brigadeDept = sysDeptService.selectDeptById(departmentDept.getParentId());
                result.setBrigadePassRate(calculate(itemListAll, brigadeDept.getDeptId()));
                SysDept stationDept = sysDeptService.selectDeptById(brigadeDept.getParentId());
                result.setStationPassRate(calculate(itemListAll, stationDept.getDeptId()));

                List<SysDept> deptList = sysDeptService.selectChildrenDeptById(stationDept.getDeptId());
                List<SysDept> departmentDeptList = deptList.stream().filter(item -> ObjUtil.equals(departmentDept.getDeptId(), item.getParentId())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> departmentRankingList = departmentDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setDepartmentRankingList(processListBest(departmentRankingList));
                result.setDepartmentTotal(result.getDepartmentRankingList().size());
                result.setDepartmentRanking(result.getDepartmentRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), teamDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));

                List<SysDept> deptBrigadeList = sysDeptService.selectChildrenDeptById(brigadeDept.getDeptId());
                List<SysDept> brigadeDeptList = deptBrigadeList.stream().filter(item -> StrUtil.equals(DeptType.TEAMS.getCode(), item.getDeptType())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> brigadeRankingList = brigadeDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setBrigadeRankingList(processListBest(brigadeRankingList));
                result.setBrigadeTotal(result.getBrigadeRankingList().size());
                result.setBrigadeRanking(result.getBrigadeRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), teamDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));

                List<SysDept> stationDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.TEAMS.getCode(), item.getDeptType())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> stationRankingList = stationDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setStationRankingList(processListBest(stationRankingList));
                result.setStationTotal(result.getStationRankingList().size());
                result.setStationRanking(result.getStationRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), teamDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            } else if (ObjUtil.equals(DeptType.MANAGER.getCode(), sysDept.getDeptType())) {
                SysDept departmentDept = sysDept;
                result.setDepartmentPassRate(calculate(itemListAll, departmentDept.getDeptId()));
                SysDept brigadeDept = sysDeptService.selectDeptById(departmentDept.getParentId());
                result.setBrigadePassRate(calculate(itemListAll, brigadeDept.getDeptId()));
                SysDept stationDept = sysDeptService.selectDeptById(brigadeDept.getParentId());
                result.setStationPassRate(calculate(itemListAll, stationDept.getDeptId()));

                List<SysDept> deptBrigadeList = sysDeptService.selectChildrenDeptById(brigadeDept.getDeptId());
                List<SysDept> brigadeDeptList = deptBrigadeList.stream().filter(item -> ObjUtil.equals(brigadeDept.getDeptId(), item.getParentId())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> brigadeRankingList = brigadeDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setBrigadeRankingList(processListBest(brigadeRankingList));
                result.setBrigadeTotal(result.getBrigadeRankingList().size());
                result.setBrigadeRanking(result.getBrigadeRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), departmentDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));

                List<SysDept> deptList = sysDeptService.selectChildrenDeptById(stationDept.getDeptId());
                List<SysDept> stationDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.MANAGER.getCode(), item.getDeptType())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> stationRankingList = stationDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setStationRankingList(processListBest(stationRankingList));
                result.setStationTotal(result.getStationRankingList().size());
                result.setStationRanking(result.getStationRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), departmentDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));

                List<SysDept> teamDeptList = deptList.stream().filter(item -> ObjUtil.equals(departmentDept.getDeptId(), item.getParentId())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> teamRankingList = teamDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setTeamRankingList(processListBest(teamRankingList));
            } else if (ObjUtil.equals(DeptType.BRIGADE.getCode(), sysDept.getDeptType())) {
                SysDept brigadeDept = sysDept;
                result.setBrigadePassRate(calculate(itemListAll, brigadeDept.getDeptId()));
                SysDept stationDept = sysDeptService.selectDeptById(brigadeDept.getParentId());
                result.setStationPassRate(calculate(itemListAll, stationDept.getDeptId()));

                List<SysDept> deptList = sysDeptService.selectChildrenDeptById(stationDept.getDeptId());
                List<SysDept> stationDeptList = deptList.stream().filter(item -> ObjUtil.equals(stationDept.getDeptId(), item.getParentId())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> stationRankingList = stationDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setStationRankingList(processListBest(stationRankingList));
                result.setStationTotal(result.getStationRankingList().size());
                result.setStationRanking(result.getStationRankingList().stream().filter(item -> ObjUtil.equals(item.getId(), brigadeDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));

                List<SysDept> departmentDeptList = deptList.stream().filter(item -> ObjUtil.equals(brigadeDept.getDeptId(), item.getParentId())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> departmentRankingList = departmentDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setDepartmentRankingList(processListBest(departmentRankingList));
            } else if (ObjUtil.equals(DeptType.STATION.getCode(), sysDept.getDeptType())) {
                SysDept stationDept = sysDept;
                result.setStationPassRate(calculate(itemListAll, stationDept.getDeptId()));

                List<SysDept> deptList = sysDeptService.selectChildrenDeptById(stationDept.getDeptId());
                List<SysDept> brigadeDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.BRIGADE.getCode(), item.getDeptType())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> brigadeRankingList = brigadeDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                result.setBrigadeRankingList(processListBest(brigadeRankingList));

                List<SysDept> departmentDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.MANAGER.getCode(), item.getDeptType())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> departmentRankingList = departmentDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> departmentRankingSortList = processListBest(departmentRankingList);
                List<CheckLargeScreenHomePageItemDto> departmentRankingSortLimitList = departmentRankingSortList.stream().limit(3).peek(item -> {
                    SysDept sysDeptTeam = sysDeptService.selectDeptById(item.getId());
                    SysDept sysDeptDepartment = sysDeptService.selectDeptById(sysDeptTeam.getParentId());
                    if (ObjUtil.isNotNull(sysDeptDepartment)) {
                        item.setName(sysDeptDepartment.getDeptName() + sysDeptTeam.getDeptName());
                    }
                }).collect(Collectors.toList());
                result.setDepartmentRankingList(departmentRankingSortLimitList);
                Collections.reverse(departmentRankingSortList);
                List<CheckLargeScreenHomePageItemDto> reverseDepartmentRankingList = departmentRankingSortList.stream().limit(3).peek(item -> {
                    SysDept sysDeptTeam = sysDeptService.selectDeptById(item.getId());
                    SysDept sysDeptDepartment = sysDeptService.selectDeptById(sysDeptTeam.getParentId());
                    if (ObjUtil.isNotNull(sysDeptDepartment)) {
                        item.setName(sysDeptDepartment.getDeptName() + sysDeptTeam.getDeptName());
                    }
                }).collect(Collectors.toList());
                result.setReverseDepartmentRankingList(reverseDepartmentRankingList);

                List<SysDept> teamDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.TEAMS.getCode(), item.getDeptType())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> teamRankingList = teamDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> teamRankingSortList = processListBest(teamRankingList);
                List<CheckLargeScreenHomePageItemDto> teamRankingSortLimitList = teamRankingSortList.stream().limit(3).peek(item -> {
                    SysDept sysDeptTeam = sysDeptService.selectDeptById(item.getId());
                    SysDept sysDeptDepartment = sysDeptService.selectDeptById(sysDeptTeam.getParentId());
                    if (ObjUtil.isNotNull(sysDeptDepartment)) {
                        item.setName(sysDeptDepartment.getDeptName() + sysDeptTeam.getDeptName());
                    }
                }).collect(Collectors.toList());
                result.setTeamRankingList(teamRankingSortLimitList);
                Collections.reverse(teamRankingSortList);
                List<CheckLargeScreenHomePageItemDto> reverseTeamRankingList = teamRankingSortList.stream().limit(3).peek(item -> {
                    SysDept sysDeptTeam = sysDeptService.selectDeptById(item.getId());
                    SysDept sysDeptDepartment = sysDeptService.selectDeptById(sysDeptTeam.getParentId());
                    if (ObjUtil.isNotNull(sysDeptDepartment)) {
                        item.setName(sysDeptDepartment.getDeptName() + sysDeptTeam.getDeptName());
                    }
                }).collect(Collectors.toList());
                result.setReverseTeamRankingList(reverseTeamRankingList);
            } else {
            }
        }

        // 已办数量+办理中数量
        List<CheckLargeScreenHomePageCheckCorrectionSqlDto> checkCorrectionListAll = checkLargeScreenMapper.homePageCheckCorrection(dto);
        if (CollUtil.isEmpty(checkCorrectionListAll)) {
            return result;
        }
        if (ObjUtil.isNotNull(dto.getUserId())) {
            List<CheckLargeScreenHomePageCheckCorrectionSqlDto> checkCorrectionSqlDtoList = checkCorrectionListAll.stream().filter(item -> ObjUtil.equals(item.getUserId(), dto.getUserId())).collect(Collectors.toList());
            long total = checkCorrectionSqlDtoList.stream().map(CheckLargeScreenHomePageCheckCorrectionSqlDto::getId).distinct().count();
            long doneNumber = checkCorrectionSqlDtoList.stream().filter(item -> ObjUtil.equals(item.getProcessStatus(), ProcessStatusEnum.ARCHIVED.getCode())).map(CheckLargeScreenHomePageCheckCorrectionSqlDto::getId).distinct().count();
            long doingNumber = total - doneNumber;
            result.setDoneNumber((int) doneNumber);
            result.setDoingNumber((int) doingNumber);
        } else {
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (ObjUtil.isNull(sysDept)) {
                return result;
            }
            List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()), sysDept.getDeptId());
            List<Long> userIdList = sysUserList.stream().map(item -> item.getUserId()).collect(Collectors.toList());
            List<CheckLargeScreenHomePageCheckCorrectionSqlDto> checkCorrectionSqlDtoList = checkCorrectionListAll.stream().filter(item -> userIdList.contains(item.getUserId())).collect(Collectors.toList());
            long total = checkCorrectionSqlDtoList.stream().map(CheckLargeScreenHomePageCheckCorrectionSqlDto::getId).distinct().count();
            long doneNumber = checkCorrectionSqlDtoList.stream().filter(item -> ObjUtil.equals(item.getProcessStatus(), ProcessStatusEnum.ARCHIVED.getCode())).map(CheckLargeScreenHomePageCheckCorrectionSqlDto::getId).distinct().count();
            long doingNumber = total - doneNumber;
            result.setDoneNumber((int) doneNumber);
            result.setDoingNumber((int) doingNumber);
        }

        // 待办数量
        try {
            List<ApprovalTask> approvalTaskList = checkApprovalService.getPendingTasks(SecurityUtils.getUserId());
            List<String> businessTypeList = Arrays.asList("PERSONAL_CHECK", "GROUP_CHECK", "SECTION_CHECK");
            long count = approvalTaskList.stream().filter(item -> businessTypeList.contains(item.getInstance().getBusinessType())).count();
            result.setToDoNumber((int) count);
        } catch (Exception e) {
            result.setToDoNumber(0);
        }

        return result;
    }

    /**
     * 计算部门通过率
     *
     * @param itemListAll 全量数据
     * @param deptId      部门ID
     * @return 部门通过率
     */
    private BigDecimal calculate(List<CheckLargeScreenHomePageItemDto> itemListAll, Long deptId) {
        if (CollUtil.isEmpty(itemListAll)) {
            return BigDecimal.ONE;
        }
        List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()), deptId);
        List<Long> userIdList = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        List<CheckLargeScreenHomePageItemDto> itemDtoList = itemListAll.stream().filter(item -> userIdList.contains(item.getId())).collect(Collectors.toList());
        BigDecimal reduce = itemDtoList.stream().map(CheckLargeScreenHomePageItemDto::getPassRate).reduce(BigDecimal.ZERO, BigDecimal::add);
        return CollUtil.isEmpty(itemDtoList) ? BigDecimal.ONE : reduce.divide(new BigDecimal(itemDtoList.size()), 4, RoundingMode.HALF_UP);
    }

    /**
     * 过滤并排序
     *
     * @param itemListAll 全量数据
     * @param deptId      部门ID
     * @return 过滤并排序后列表
     */
    private List<CheckLargeScreenHomePageItemDto> sort(List<CheckLargeScreenHomePageItemDto> itemListAll, Long deptId) {
        if (CollUtil.isEmpty(itemListAll)) {
            return Collections.emptyList();
        }
        List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()), deptId);
        List<Long> userIdList = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        List<CheckLargeScreenHomePageItemDto> itemDtoList = itemListAll.stream().filter(item -> userIdList.contains(item.getId())).collect(Collectors.toList());
        return processListBest(itemDtoList);
    }

    /**
     * 排序
     *
     * @param list 待排序列表
     * @return 排序后列表
     */
    public List<CheckLargeScreenHomePageItemDto> processListBest(List<CheckLargeScreenHomePageItemDto> list) {
        AtomicInteger index = new AtomicInteger(1);
        return list.stream().sorted(Comparator.comparing(CheckLargeScreenHomePageItemDto::getPassRate).reversed()).peek(item -> item.setRank(index.getAndIncrement())).collect(Collectors.toList());
    }

    /**
     * 首页-巡检-巡检合格率
     *
     * @param dto 首页查询参数
     * @return 首页-巡检-巡检合格率
     */
    @Override
    public BigDecimal checkPassRate(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));
        }

        // 全量数据
        List<CheckLargeScreenHomePageItemDto> itemListAll = getCheckLargeScreenHomePageItemDtoList(dto);
        if (CollUtil.isEmpty(itemListAll)) {
            return BigDecimal.ONE;
        }

        if (ObjUtil.isNotNull(dto.getUserId())) {
            return itemListAll.stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).findFirst().map(CheckLargeScreenHomePageItemDto::getPassRate).orElse(BigDecimal.ONE);
        } else {
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (ObjUtil.isNull(sysDept)) {
                throw new ServiceException("部门不存在");
            }
            return calculate(itemListAll, sysDept.getDeptId());
        }
    }

    /**
     * 巡检合格率全量数据
     *
     * @param dto 查询参数
     * @return 巡检合格率全量数据
     */
    @Override
    public List<CheckLargeScreenHomePageItemDto> getCheckLargeScreenHomePageItemDtoList(BaseLargeScreenQueryParamDto dto) {
        List<CheckLargeScreenHomePageItemDto> result = new ArrayList<>();
        String key = CacheConstants.USER_CHECK_PASS_RATE_KEY + dto.getStartDate() + ":" + dto.getEndDate() + ":" + dto.getSpecifiedDate();
        List<CheckLargeScreenHomePageItemDto> cacheList = redisCache.getCacheList(key);
        if (CollUtil.isNotEmpty(cacheList)) {
            result.addAll(cacheList);
        } else {
            List<LargeScreenHomePageUserInfoSqlDto> userInfoListAll = sysUserService.homePageUserInfo();
            if (CollUtil.isEmpty(userInfoListAll)) {
                return Collections.emptyList();
            }
            List<CheckLargeScreenHomePageCheckRecordSqlDto> checkRecordListAll = checkLargeScreenMapper.homePageCheckRecord(dto);
            if (CollUtil.isEmpty(checkRecordListAll)) {
                return Collections.emptyList();
            }
            userInfoListAll.forEach(userInfoSqlDto -> {
                CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                itemDto.setId(userInfoSqlDto.getUserId());
                itemDto.setName(userInfoSqlDto.getNickName());
                List<CheckLargeScreenHomePageCheckRecordSqlDto> brigadeList = checkRecordListAll.stream().filter(checkRecordSqlDto -> StrUtil.equals(checkRecordSqlDto.getCheckedLevel(), CheckLevelEnum.BRIGADE_LEVEL.getCode()) && ObjUtil.equals(userInfoSqlDto.getBrigadeId(), checkRecordSqlDto.getCheckedBrigadeId())).collect(Collectors.toList());
                long brigadeTotal = brigadeList.stream().map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                long brigadeUnqualifiedNum = brigadeList.stream().filter(item -> ObjUtil.equals(userInfoSqlDto.getUserId(), item.getUserId())).map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                long brigadeQualifiedNum = brigadeTotal - brigadeUnqualifiedNum;
                List<CheckLargeScreenHomePageCheckRecordSqlDto> departmentList = checkRecordListAll.stream().filter(checkRecordSqlDto -> StrUtil.equals(checkRecordSqlDto.getCheckedLevel(), CheckLevelEnum.DEPARTMENT_LEVEL.getCode()) && ObjUtil.equals(userInfoSqlDto.getDepartmentId(), checkRecordSqlDto.getCheckedDepartmentId())).collect(Collectors.toList());
                long departmentTotal = departmentList.stream().map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                long departmentUnqualifiedNum = departmentList.stream().filter(item -> ObjUtil.equals(userInfoSqlDto.getUserId(), item.getUserId())).map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                long departmentQualifiedNum = departmentTotal - departmentUnqualifiedNum;
                List<CheckLargeScreenHomePageCheckRecordSqlDto> teamList = checkRecordListAll.stream().filter(checkRecordSqlDto -> StrUtil.equals(checkRecordSqlDto.getCheckedLevel(), CheckLevelEnum.TEAM_LEVEL.getCode()) && ObjUtil.equals(userInfoSqlDto.getTeamId(), checkRecordSqlDto.getCheckedTeamId())).collect(Collectors.toList());
                long teamTotal = teamList.stream().map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                long teamUnqualifiedNum = teamList.stream().filter(item -> ObjUtil.equals(userInfoSqlDto.getUserId(), item.getUserId())).map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                long teamQualifiedNum = teamTotal - teamUnqualifiedNum;
                List<CheckLargeScreenHomePageCheckRecordSqlDto> personalList = checkRecordListAll.stream().filter(checkRecordSqlDto -> StrUtil.equals(checkRecordSqlDto.getCheckedLevel(), CheckLevelEnum.PERSONNEL_LEVEL.getCode()) && ObjUtil.equals(userInfoSqlDto.getUserId(), checkRecordSqlDto.getCheckedPersonnelId())).collect(Collectors.toList());
                long personalTotal = personalList.stream().map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                long personalUnqualifiedNum = personalList.stream().filter(item -> ObjUtil.equals(userInfoSqlDto.getUserId(), item.getUserId())).map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                long personalQualifiedNum = personalTotal - personalUnqualifiedNum;
                long total = personalTotal + teamTotal + departmentTotal + brigadeTotal;
                long qualifiedNum = brigadeQualifiedNum + departmentQualifiedNum + teamQualifiedNum + personalQualifiedNum;
                itemDto.setPassRate(total == 0 ? BigDecimal.ONE : new BigDecimal(qualifiedNum).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP));
                result.add(itemDto);
            });
            redisCache.setCacheList(key, result);
            redisCache.expire(key, 10, TimeUnit.MINUTES);
        }
        return result;
    }

    /**
     * 巡检合格率全量数据-为空时默认合格率
     *
     * @param dto 查询参数
     * @return 巡检合格率全量数据
     */
    @Override
    public List<CheckLargeScreenHomePageItemDto> getCheckLargeScreenHomePageItemDtoListAndNull(BaseLargeScreenQueryParamDto dto) {
        List<CheckLargeScreenHomePageItemDto> result = new ArrayList<>();
        String key = CacheConstants.USER_CHECK_PASS_RATE_KEY + dto.getStartDate() + ":" + dto.getEndDate() + ":" + dto.getSpecifiedDate();
        List<CheckLargeScreenHomePageItemDto> cacheList = redisCache.getCacheList(key);
        if (CollUtil.isNotEmpty(cacheList)) {
            result.addAll(cacheList);
        } else {
            List<LargeScreenHomePageUserInfoSqlDto> userInfoListAll = sysUserService.homePageUserInfo();
            if (CollUtil.isEmpty(userInfoListAll)) {
                return Collections.emptyList();
            }
            List<CheckLargeScreenHomePageCheckRecordSqlDto> checkRecordListAll = checkLargeScreenMapper.homePageCheckRecord(dto);
            if (CollUtil.isEmpty(checkRecordListAll)) {
                userInfoListAll.forEach(userInfoSqlDto -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(userInfoSqlDto.getUserId());
                    itemDto.setName(userInfoSqlDto.getNickName());
                    itemDto.setPassRate(BigDecimal.ONE);
                    result.add(itemDto);
                });
            } else {
                userInfoListAll.forEach(userInfoSqlDto -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(userInfoSqlDto.getUserId());
                    itemDto.setName(userInfoSqlDto.getNickName());
                    List<CheckLargeScreenHomePageCheckRecordSqlDto> departmentList = checkRecordListAll.stream().filter(checkRecordSqlDto -> StrUtil.equals(checkRecordSqlDto.getCheckedLevel(), CheckLevelEnum.DEPARTMENT_LEVEL.getCode()) && ObjUtil.equals(userInfoSqlDto.getDepartmentId(), checkRecordSqlDto.getCheckedDepartmentId())).collect(Collectors.toList());
                    long departmentTotal = departmentList.stream().map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                    long departmentUnqualifiedNum = departmentList.stream().filter(item -> ObjUtil.equals(userInfoSqlDto.getUserId(), item.getUserId())).map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                    long departmentQualifiedNum = departmentTotal - departmentUnqualifiedNum;
                    List<CheckLargeScreenHomePageCheckRecordSqlDto> teamList = checkRecordListAll.stream().filter(checkRecordSqlDto -> StrUtil.equals(checkRecordSqlDto.getCheckedLevel(), CheckLevelEnum.TEAM_LEVEL.getCode()) && ObjUtil.equals(userInfoSqlDto.getTeamId(), checkRecordSqlDto.getCheckedTeamId())).collect(Collectors.toList());
                    long teamTotal = teamList.stream().map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                    long teamUnqualifiedNum = teamList.stream().filter(item -> ObjUtil.equals(userInfoSqlDto.getUserId(), item.getUserId())).map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                    long teamQualifiedNum = teamTotal - teamUnqualifiedNum;
                    List<CheckLargeScreenHomePageCheckRecordSqlDto> personalList = checkRecordListAll.stream().filter(checkRecordSqlDto -> StrUtil.equals(checkRecordSqlDto.getCheckedLevel(), CheckLevelEnum.PERSONNEL_LEVEL.getCode()) && ObjUtil.equals(userInfoSqlDto.getUserId(), checkRecordSqlDto.getCheckedPersonnelId())).collect(Collectors.toList());
                    long personalTotal = personalList.stream().map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                    long personalUnqualifiedNum = personalList.stream().filter(item -> ObjUtil.equals(userInfoSqlDto.getUserId(), item.getUserId())).map(CheckLargeScreenHomePageCheckRecordSqlDto::getId).distinct().count();
                    long personalQualifiedNum = personalTotal - personalUnqualifiedNum;
                    long total = personalTotal + teamTotal + departmentTotal;
                    long qualifiedNum = departmentQualifiedNum + teamQualifiedNum + personalQualifiedNum;
                    itemDto.setPassRate(total == 0 ? BigDecimal.ONE : new BigDecimal(qualifiedNum).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP));
                    result.add(itemDto);
                });
            }
            redisCache.setCacheList(key, result);
            redisCache.expire(key, 10, TimeUnit.MINUTES);
        }
        return result;
    }

    /**
     * 首页-巡检-巡检合格率排名
     *
     * @param dto 首页查询参数
     * @return 首页-巡检-巡检合格率排名
     */
    @Override
    public CheckLargeScreenHomePageRankingDto checkRanking(BaseLargeScreenQueryParamDto dto) {
        if (ObjUtil.isNull(dto.getUserId()) && ObjUtil.isNull(dto.getDeptId())) {
            throw new ServiceException("用户ID和部门ID不能同时为空");
        }

        CheckLargeScreenHomePageRankingDto result = new CheckLargeScreenHomePageRankingDto();
        result.setTotal(0);
        result.setRank(0);

        // 默认筛选条件
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(LargeScreenDateUtils.getCurrentDate());
            dto.setStartDate(LargeScreenDateUtils.getDateBeforeYears(1));
        }

        // 全量数据
        List<CheckLargeScreenHomePageItemDto> itemListAll = getCheckLargeScreenHomePageItemDtoList(dto);
        if (CollUtil.isEmpty(itemListAll)) {
            return result;
        }

        if (ObjUtil.isNotNull(dto.getUserId())) {
            SysUser sysUser = sysUserService.selectUserById(dto.getUserId());
            if (ObjUtil.isNull(sysUser.getDeptId())) {
                return result;
            }
            result.setId(sysUser.getUserId());
            result.setName(sysUser.getNickName());
            List<SysDept> deptList = sysDeptService.selectAllDept(sysUser.getDeptId());
            if (CollUtil.isEmpty(deptList)) {
                return result;
            }
            Collections.reverse(deptList);
            SysDept station = deptList.stream().filter(x -> StrUtil.equals(DeptType.STATION.getCode(), x.getDeptType())).findFirst().orElse(null);
            result.setPassRate(itemListAll.stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).findFirst().map(CheckLargeScreenHomePageItemDto::getPassRate).orElse(BigDecimal.ONE));
            if (station != null) {
                List<CheckLargeScreenHomePageItemDto> sort = sort(itemListAll, station.getDeptId());
                result.setRankingList(sort);
                result.setTotal(sort.size());
                result.setRank(sort.stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            }
        } else {
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (ObjUtil.isNull(sysDept)) {
                return result;
            }
            result.setId(sysDept.getDeptId());
            result.setName(sysDept.getDeptName());
            if (ObjUtil.equals(DeptType.TEAMS.getCode(), sysDept.getDeptType())) {
                SysDept teamDept = sysDept;
                result.setPassRate(calculate(itemListAll, teamDept.getDeptId()));
                SysDept departmentDept = sysDeptService.selectDeptById(teamDept.getParentId());
                SysDept brigadeDept = sysDeptService.selectDeptById(departmentDept.getParentId());
                SysDept stationDept = sysDeptService.selectDeptById(brigadeDept.getParentId());

                List<SysDept> deptList = sysDeptService.selectChildrenDeptById(stationDept.getDeptId());
                List<SysDept> stationDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.TEAMS.getCode(), item.getDeptType())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> stationRankingList = stationDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> itemDtoList = processListBest(stationRankingList);
                result.setRankingList(itemDtoList);
                result.setTotal(itemDtoList.size());
                result.setRank(itemDtoList.stream().filter(item -> ObjUtil.equals(item.getId(), teamDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            } else if (ObjUtil.equals(DeptType.MANAGER.getCode(), sysDept.getDeptType())) {
                SysDept departmentDept = sysDept;
                result.setPassRate(calculate(itemListAll, departmentDept.getDeptId()));
                SysDept brigadeDept = sysDeptService.selectDeptById(departmentDept.getParentId());
                SysDept stationDept = sysDeptService.selectDeptById(brigadeDept.getParentId());

                List<SysDept> deptList = sysDeptService.selectChildrenDeptById(stationDept.getDeptId());
                List<SysDept> stationDeptList = deptList.stream().filter(item -> StrUtil.equals(DeptType.MANAGER.getCode(), item.getDeptType())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> stationRankingList = stationDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> itemDtoList = processListBest(stationRankingList);
                result.setRankingList(itemDtoList);
                result.setTotal(itemDtoList.size());
                result.setRank(itemDtoList.stream().filter(item -> ObjUtil.equals(item.getId(), departmentDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            } else if (ObjUtil.equals(DeptType.BRIGADE.getCode(), sysDept.getDeptType())) {
                SysDept brigadeDept = sysDept;
                result.setPassRate(calculate(itemListAll, brigadeDept.getDeptId()));
                SysDept stationDept = sysDeptService.selectDeptById(brigadeDept.getParentId());

                List<SysDept> deptList = sysDeptService.selectChildrenDeptById(stationDept.getDeptId());
                List<SysDept> stationDeptList = deptList.stream().filter(item -> ObjUtil.equals(stationDept.getDeptId(), item.getParentId())).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> stationRankingList = stationDeptList.stream().map(item -> {
                    CheckLargeScreenHomePageItemDto itemDto = new CheckLargeScreenHomePageItemDto();
                    itemDto.setId(item.getDeptId());
                    itemDto.setName(item.getDeptName());
                    itemDto.setPassRate(calculate(itemListAll, item.getDeptId()));
                    return itemDto;
                }).collect(Collectors.toList());
                List<CheckLargeScreenHomePageItemDto> itemDtoList = processListBest(stationRankingList);
                result.setRankingList(itemDtoList);
                result.setTotal(itemDtoList.size());
                result.setRank(itemDtoList.stream().filter(item -> ObjUtil.equals(item.getId(), brigadeDept.getDeptId())).findFirst().map(CheckLargeScreenHomePageItemDto::getRank).orElse(0));
            }
        }

        // 奖牌类型处理
        if (result.getTotal() != 0 && result.getRank() != 0) {
            // 后三名:最后一名哭脸红,倒数第二名哭脸橙,倒数第三名哭脸黄
            int positionFromEnd = result.getTotal() - result.getRank() + 1;
            if (result.getRank() == 1) {
                result.setMedalType(MedalTypeEnum.GOLD.getCode());
                result.setMedalTypeDesc(MedalTypeEnum.GOLD.getDesc());
            } else if (result.getRank() == 2) {
                result.setMedalType(MedalTypeEnum.SILVER.getCode());
                result.setMedalTypeDesc(MedalTypeEnum.SILVER.getDesc());
            } else if (result.getRank() == 3) {
                result.setMedalType(MedalTypeEnum.BRONZE.getCode());
                result.setMedalTypeDesc(MedalTypeEnum.BRONZE.getDesc());
            } else if (positionFromEnd == 1) {
                result.setMedalType(MedalTypeEnum.CRY_RED.getCode());
                result.setMedalTypeDesc(MedalTypeEnum.CRY_RED.getDesc());
            } else if (positionFromEnd == 2) {
                result.setMedalType(MedalTypeEnum.CRY_ORANGE.getCode());
                result.setMedalTypeDesc(MedalTypeEnum.CRY_ORANGE.getDesc());
            } else if (positionFromEnd == 3) {
                result.setMedalType(MedalTypeEnum.CRY_YELLOW.getCode());
                result.setMedalTypeDesc(MedalTypeEnum.CRY_YELLOW.getDesc());
            }
        }
        return result;
    }

    /**
     * 首页-巡检-今日巡检问题数
     *
     * @param dto 首页查询参数
     * @return 首页-巡检-今日巡检问题数
     */
    @Override
    public Integer checkCorrectionCount(BaseLargeScreenQueryParamDto dto) {
        // 默认筛选条件
        if (ObjUtil.isNull(dto.getUserId())) {
            dto.setUserId(SecurityUtils.getUserId());
        }
        if (ObjUtil.isNull(dto.getStartDate()) && ObjUtil.isNull(dto.getEndDate()) && ObjUtil.isNull(dto.getSpecifiedDate())) {
            dto.setSpecifiedDate(LargeScreenDateUtils.getCurrentDate());
        }
        return checkLargeScreenMapper.checkCorrectionCount(dto);
    }

    /**
     * 首页报表-巡检合格率数据
     *
     * @param dto 首页查询参数
     * @return 首页报表-巡检合格率数据
     */
    @Override
    public SysHomeReportDetailDto checkData(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();
        // 全量数据
        List<CheckLargeScreenHomePageItemDto> itemListAll = getCheckLargeScreenHomePageItemDtoList(dto);

        List<CheckLargeScreenHomePageItemDto> targetList;
        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());
            targetList = itemListAll.stream().filter(item -> ObjUtil.equals(item.getId(), dto.getUserId())).collect(Collectors.toList());
        } else {
            SysDept sysDept = sysDeptService.selectDeptById(dto.getDeptId());
            if (ObjUtil.isNull(sysDept)) {
                throw new ServiceException("部门不存在");
            }
            result.setId(sysDept.getDeptId());
            result.setName(sysDept.getDeptName());
            result.setType(HomePageQueryEnum.DEPT.getCode());
            List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()), sysDept.getDeptId());
            List<Long> userIdList = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
            targetList = itemListAll.stream().filter(item -> userIdList.contains(item.getId())).collect(Collectors.toList());
        }
        List<BigDecimal> targetValueList = targetList.stream()
                .map(CheckLargeScreenHomePageItemDto::getPassRate)
                .filter(Objects::nonNull)
                .sorted()
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(targetValueList)) {
            result.setMaxNumber(BigDecimal.ONE);
            result.setMinNumber(BigDecimal.ONE);
            result.setAverageNumber(BigDecimal.ONE);
            result.setMedianNumber(BigDecimal.ONE);
            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), 4, 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;
    }

    /**
     * 质控分析报告-质控活动
     *
     * @param paramDto 质控分析报告-质控活动查询参数
     * @return 质控分析报告-质控活动
     */
    @Override
    public SysCheckAnalysisReportDto checkAnalysisReport(SysAnalysisReportParamDto paramDto) {
        if (ObjUtil.isNull(paramDto.getUserId()) && ObjUtil.isNull(paramDto.getDeptId())) {
            paramDto.setDeptId(DeptUtils.getTopSiteId(sysDeptService.selectDeptById(SecurityUtils.getDeptId())));
        }
        SysCheckAnalysisReportDto result = new SysCheckAnalysisReportDto();
        result.setCheckTaskDto(getCheckTaskDto(paramDto));
        result.setCheckProblemDiscoveryDto(getCheckProblemDiscoveryDto(paramDto));
        result.setCheckProblemDistributionDto(getCheckProblemDistributionDto(paramDto));
        result.setCheckProblemCorrectionDto(getCheckProblemCorrectionDto(paramDto));
        return result;
    }

    /**
     * 获取任务计划安排统计
     *
     * @param paramDto 质控分析报告-任务计划安排统计查询参数
     * @return 任务计划安排统计
     */
    private SysCheckAnalysisReportCheckTaskDto getCheckTaskDto(SysAnalysisReportParamDto paramDto) {
        if (ObjectUtil.isNotNull(paramDto.getUserId())) {
            return null;
        }
        SysDept sysDept = sysDeptService.selectDeptById(paramDto.getDeptId());
        if (ObjUtil.isNull(sysDept)) {
            throw new ServiceException("【" + paramDto.getDeptId() + "】部门不存在");
        }
        if (!StrUtil.equals(DeptTypeEnum.STATION.getCode(), sysDept.getDeptType()) && !StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType()) && !StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
            return null;
        }
        List<SysUser> sysUserList;
        if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
            sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.jingli.getCode(), RoleTypeEnum.xingzheng.getCode()), sysDept.getDeptId());
        } else if (StrUtil.equals(DeptTypeEnum.MANAGER.getCode(), sysDept.getDeptType())) {
            sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.kezhang.getCode()), sysDept.getDeptId());
        } else {
            sysUserList = Collections.emptyList();
        }
        SysCheckAnalysisReportCheckTaskDto checkTaskDto = new SysCheckAnalysisReportCheckTaskDto();
        List<SysCheckAnalysisReportCheckTaskItemDto> checkTaskItemDtoList = new ArrayList<>();
        paramDto.getDateRangeList().forEach(dateRange -> {
            List<CheckTask> checkTaskList = Collections.emptyList();
            CheckLargeScreenPlanQueryParamDto dto = new CheckLargeScreenPlanQueryParamDto();
            dto.setStartDate(dateRange.getStartDate());
            dto.setEndDate(dateRange.getEndDate());
            if (StrUtil.equals(DeptTypeEnum.STATION.getCode(), sysDept.getDeptType())) {
                dto.setIsSelfCheck(null);
                dto.setCreateId(null);
                dto.setUserIdList(null);
                checkTaskList = checkLargeScreenMapper.planStatistics(dto);
            } else if (StrUtil.equals(DeptTypeEnum.BRIGADE.getCode(), sysDept.getDeptType())) {
                if (!CollUtil.isEmpty(sysUserList)) {
                    List<Long> userIdList = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
                    dto.setIsSelfCheck(1);
                    dto.setCreateId(null);
                    dto.setUserIdList(userIdList);
                    checkTaskList = checkLargeScreenMapper.planStatistics(dto);
                }
            } else {
                if (!CollUtil.isEmpty(sysUserList)) {
                    List<Long> userIdList = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
                    dto.setIsSelfCheck(0);
                    dto.setCreateId(null);
                    dto.setUserIdList(userIdList);
                    checkTaskList = checkLargeScreenMapper.planStatistics(dto);
                }
            }
            Map<String, Long> map = checkTaskList.stream().collect(Collectors.groupingBy(CheckTask::getCheckCategory, Collectors.counting()));

            SysCheckAnalysisReportCheckTaskItemDto itemDtoSpecialTask = new SysCheckAnalysisReportCheckTaskItemDto();
            itemDtoSpecialTask.setStartDate(dateRange.getStartDate());
            itemDtoSpecialTask.setEndDate(dateRange.getEndDate());
            itemDtoSpecialTask.setDesc(dateRange.getDesc());
            itemDtoSpecialTask.setTag(dateRange.getTag());
            itemDtoSpecialTask.setTagDesc(dateRange.getTagDesc());
            itemDtoSpecialTask.setType(CheckTaskTypeEnum.SPECIAL_TASK.getCode());
            itemDtoSpecialTask.setTypeDesc(CheckTaskTypeEnum.SPECIAL_TASK.getDesc());
            itemDtoSpecialTask.setCount(map.get(CheckTaskTypeEnum.SPECIAL_TASK.getCode()) == null ? BigDecimal.ZERO : BigDecimal.valueOf(map.get(CheckTaskTypeEnum.SPECIAL_TASK.getCode())));
            checkTaskItemDtoList.add(itemDtoSpecialTask);
            SysCheckAnalysisReportCheckTaskItemDto itemDtoDailyTask = new SysCheckAnalysisReportCheckTaskItemDto();
            itemDtoDailyTask.setStartDate(dateRange.getStartDate());
            itemDtoDailyTask.setEndDate(dateRange.getEndDate());
            itemDtoDailyTask.setDesc(dateRange.getDesc());
            itemDtoDailyTask.setTag(dateRange.getTag());
            itemDtoDailyTask.setTagDesc(dateRange.getTagDesc());
            itemDtoDailyTask.setType(CheckTaskTypeEnum.DAILY_TASK.getCode());
            itemDtoDailyTask.setTypeDesc(CheckTaskTypeEnum.DAILY_TASK.getDesc());
            itemDtoDailyTask.setCount(map.get(CheckTaskTypeEnum.DAILY_TASK.getCode()) == null ? BigDecimal.ZERO : BigDecimal.valueOf(map.get(CheckTaskTypeEnum.DAILY_TASK.getCode())));
            checkTaskItemDtoList.add(itemDtoDailyTask);
        });
        checkTaskDto.setCheckTaskItemDtoList(checkTaskItemDtoList);

        List<SysCheckAnalysisReportCheckTaskTypeItemDto> checkTaskTypeItemDtoList = new ArrayList<>();
        List<SysCheckAnalysisReportCheckTaskItemDto> specialTaskList = checkTaskItemDtoList.stream().filter(item -> CheckTaskTypeEnum.SPECIAL_TASK.getCode().equals(item.getType())).collect(Collectors.toList());
        List<SysCheckAnalysisReportCheckTaskItemDto> dailyTaskList = checkTaskItemDtoList.stream().filter(item -> CheckTaskTypeEnum.DAILY_TASK.getCode().equals(item.getType())).collect(Collectors.toList());
        BigDecimal specialTaskCurrentCount = specialTaskList.stream().filter(item -> CompareTypeEnum.CURRENT.getCode().equals(item.getTag())).findFirst().map(SysCheckAnalysisReportCheckTaskItemDto::getCount).orElse(BigDecimal.ZERO);
        BigDecimal specialTaskYearOnYearCount = specialTaskList.stream().filter(item -> CompareTypeEnum.YEAR_ON_YEAR.getCode().equals(item.getTag())).findFirst().map(SysCheckAnalysisReportCheckTaskItemDto::getCount).orElse(BigDecimal.ZERO);
        SysCheckAnalysisReportCheckTaskItemDto specialTaskRingRatioCheckTaskItemDto = specialTaskList.stream().filter(item -> CompareTypeEnum.RING_RATIO.getCode().equals(item.getTag())).findFirst().orElse(null);
        BigDecimal specialTaskRingRatioCount = specialTaskRingRatioCheckTaskItemDto != null ? specialTaskRingRatioCheckTaskItemDto.getCount() : BigDecimal.ZERO;
        BigDecimal dailyTaskCurrentCount = dailyTaskList.stream().filter(item -> CompareTypeEnum.CURRENT.getCode().equals(item.getTag())).findFirst().map(SysCheckAnalysisReportCheckTaskItemDto::getCount).orElse(BigDecimal.ZERO);
        BigDecimal dailyTaskYearOnYearCount = dailyTaskList.stream().filter(item -> CompareTypeEnum.YEAR_ON_YEAR.getCode().equals(item.getTag())).findFirst().map(SysCheckAnalysisReportCheckTaskItemDto::getCount).orElse(BigDecimal.ZERO);
        SysCheckAnalysisReportCheckTaskItemDto dailyTaskRingRatioCheckTaskItemDto = dailyTaskList.stream().filter(item -> CompareTypeEnum.RING_RATIO.getCode().equals(item.getTag())).findFirst().orElse(null);
        BigDecimal dailyTaskRingRatioCount = dailyTaskRingRatioCheckTaskItemDto != null ? dailyTaskRingRatioCheckTaskItemDto.getCount() : BigDecimal.ZERO;

        SysCheckAnalysisReportCheckTaskTypeItemDto checkTaskTypeItemDtoSpecialTask = new SysCheckAnalysisReportCheckTaskTypeItemDto();
        checkTaskTypeItemDtoSpecialTask.setType(CheckTaskTypeEnum.SPECIAL_TASK.getCode());
        checkTaskTypeItemDtoSpecialTask.setTypeDesc(CheckTaskTypeEnum.SPECIAL_TASK.getDesc());
        checkTaskTypeItemDtoSpecialTask.setCount(specialTaskCurrentCount);
        List<SysAnalysisReportCompareItemDto> specialTaskItemDtoList = new ArrayList<>();
        checkTaskTypeItemDtoSpecialTask.setCompareItemDtoList(specialTaskItemDtoList);
        SysCheckAnalysisReportCheckTaskTypeItemDto checkTaskTypeItemDtoDailyTask = new SysCheckAnalysisReportCheckTaskTypeItemDto();
        checkTaskTypeItemDtoDailyTask.setType(CheckTaskTypeEnum.DAILY_TASK.getCode());
        checkTaskTypeItemDtoDailyTask.setTypeDesc(CheckTaskTypeEnum.DAILY_TASK.getDesc());
        checkTaskTypeItemDtoDailyTask.setCount(dailyTaskCurrentCount);
        List<SysAnalysisReportCompareItemDto> dailyTaskItemDtoList = new ArrayList<>();
        checkTaskTypeItemDtoDailyTask.setCompareItemDtoList(dailyTaskItemDtoList);

        SysAnalysisReportCompareItemDto specialTaskYearOnYearItemDto = new SysAnalysisReportCompareItemDto();
        specialTaskYearOnYearItemDto.setCompareType(CompareTypeEnum.YEAR_ON_YEAR.getCode());
        specialTaskYearOnYearItemDto.setCompareTypeDesc(CompareTypeEnum.YEAR_ON_YEAR.getDesc());
        BigDecimal subtractSpecialTaskYearOnYear = specialTaskCurrentCount.subtract(specialTaskYearOnYearCount);
        if (subtractSpecialTaskYearOnYear.compareTo(BigDecimal.ZERO) > 0) {
            specialTaskYearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
            specialTaskYearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
            specialTaskYearOnYearItemDto.setProportion(specialTaskYearOnYearCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractSpecialTaskYearOnYear.divide(specialTaskYearOnYearCount, 4, RoundingMode.HALF_UP));
            specialTaskYearOnYearItemDto.setProportionDesc(specialTaskYearOnYearItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : specialTaskYearOnYearItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
        } else if (subtractSpecialTaskYearOnYear.compareTo(BigDecimal.ZERO) < 0) {
            specialTaskYearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.DECLINE.getCode());
            specialTaskYearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.DECLINE.getDesc());
            specialTaskYearOnYearItemDto.setProportion(specialTaskYearOnYearCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractSpecialTaskYearOnYear.abs().divide(specialTaskYearOnYearCount, 4, RoundingMode.HALF_UP));
            specialTaskYearOnYearItemDto.setProportionDesc(specialTaskYearOnYearItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : specialTaskYearOnYearItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
        } else {
            specialTaskYearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
            specialTaskYearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
            specialTaskYearOnYearItemDto.setProportion(BigDecimal.ZERO);
            specialTaskYearOnYearItemDto.setProportionDesc("0%");
        }
        specialTaskItemDtoList.add(specialTaskYearOnYearItemDto);
        if (specialTaskRingRatioCheckTaskItemDto != null) {
            SysAnalysisReportCompareItemDto specialTaskRingRatioItemDto = new SysAnalysisReportCompareItemDto();
            specialTaskRingRatioItemDto.setCompareType(CompareTypeEnum.RING_RATIO.getCode());
            specialTaskRingRatioItemDto.setCompareTypeDesc(CompareTypeEnum.RING_RATIO.getDesc());
            BigDecimal subtractSpecialTaskRingRatio = specialTaskCurrentCount.subtract(specialTaskRingRatioCount);
            if (subtractSpecialTaskRingRatio.compareTo(BigDecimal.ZERO) > 0) {
                specialTaskRingRatioItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
                specialTaskRingRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
                specialTaskRingRatioItemDto.setProportion(specialTaskRingRatioCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractSpecialTaskRingRatio.divide(specialTaskRingRatioCount, 4, RoundingMode.HALF_UP));
                specialTaskRingRatioItemDto.setProportionDesc(specialTaskRingRatioItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : specialTaskRingRatioItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
            } else if (subtractSpecialTaskRingRatio.compareTo(BigDecimal.ZERO) < 0) {
                specialTaskRingRatioItemDto.setCompareResultType(CompareResultTypeEnum.DECLINE.getCode());
                specialTaskRingRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.DECLINE.getDesc());
                specialTaskRingRatioItemDto.setProportion(specialTaskRingRatioCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractSpecialTaskRingRatio.abs().divide(specialTaskRingRatioCount, 4, RoundingMode.HALF_UP));
                specialTaskRingRatioItemDto.setProportionDesc(specialTaskRingRatioItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : specialTaskRingRatioItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
            } else {
                specialTaskRingRatioItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
                specialTaskRingRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
                specialTaskRingRatioItemDto.setProportion(BigDecimal.ZERO);
                specialTaskRingRatioItemDto.setProportionDesc("0%");
            }
            specialTaskItemDtoList.add(specialTaskRingRatioItemDto);
        }

        SysAnalysisReportCompareItemDto dailyTaskYearOnYearItemDto = new SysAnalysisReportCompareItemDto();
        dailyTaskYearOnYearItemDto.setCompareType(CompareTypeEnum.YEAR_ON_YEAR.getCode());
        dailyTaskYearOnYearItemDto.setCompareTypeDesc(CompareTypeEnum.YEAR_ON_YEAR.getDesc());
        BigDecimal subtractDailyTaskYearOnYear = dailyTaskCurrentCount.subtract(dailyTaskYearOnYearCount);
        if (subtractDailyTaskYearOnYear.compareTo(BigDecimal.ZERO) > 0) {
            dailyTaskYearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
            dailyTaskYearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
            dailyTaskYearOnYearItemDto.setProportion(dailyTaskYearOnYearCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractDailyTaskYearOnYear.divide(dailyTaskYearOnYearCount, 4, RoundingMode.HALF_UP));
            dailyTaskYearOnYearItemDto.setProportionDesc(dailyTaskYearOnYearItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : dailyTaskYearOnYearItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
        } else if (subtractDailyTaskYearOnYear.compareTo(BigDecimal.ZERO) < 0) {
            dailyTaskYearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.DECLINE.getCode());
            dailyTaskYearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.DECLINE.getDesc());
            dailyTaskYearOnYearItemDto.setProportion(dailyTaskYearOnYearCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractDailyTaskYearOnYear.abs().divide(dailyTaskYearOnYearCount, 4, RoundingMode.HALF_UP));
            dailyTaskYearOnYearItemDto.setProportionDesc(dailyTaskYearOnYearItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : dailyTaskYearOnYearItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
        } else {
            dailyTaskYearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
            dailyTaskYearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
            dailyTaskYearOnYearItemDto.setProportion(BigDecimal.ZERO);
            dailyTaskYearOnYearItemDto.setProportionDesc("0%");
        }
        dailyTaskItemDtoList.add(dailyTaskYearOnYearItemDto);
        if (dailyTaskRingRatioCheckTaskItemDto != null) {
            SysAnalysisReportCompareItemDto dailyTaskRingRatioItemDto = new SysAnalysisReportCompareItemDto();
            dailyTaskRingRatioItemDto.setCompareType(CompareTypeEnum.RING_RATIO.getCode());
            dailyTaskRingRatioItemDto.setCompareTypeDesc(CompareTypeEnum.RING_RATIO.getDesc());
            BigDecimal subtractDailyTaskRingRatio = dailyTaskCurrentCount.subtract(dailyTaskRingRatioCount);
            if (subtractDailyTaskRingRatio.compareTo(BigDecimal.ZERO) > 0) {
                dailyTaskRingRatioItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
                dailyTaskRingRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
                dailyTaskRingRatioItemDto.setProportion(dailyTaskRingRatioCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractDailyTaskRingRatio.divide(dailyTaskRingRatioCount, 4, RoundingMode.HALF_UP));
                dailyTaskRingRatioItemDto.setProportionDesc(dailyTaskRingRatioItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : dailyTaskRingRatioItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
            } else if (subtractDailyTaskRingRatio.compareTo(BigDecimal.ZERO) < 0) {
                dailyTaskRingRatioItemDto.setCompareResultType(CompareResultTypeEnum.DECLINE.getCode());
                dailyTaskRingRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.DECLINE.getDesc());
                dailyTaskRingRatioItemDto.setProportion(dailyTaskRingRatioCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractDailyTaskRingRatio.abs().divide(dailyTaskRingRatioCount, 4, RoundingMode.HALF_UP));
                dailyTaskRingRatioItemDto.setProportionDesc(dailyTaskRingRatioItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : dailyTaskRingRatioItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
            } else {
                dailyTaskRingRatioItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
                dailyTaskRingRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
                dailyTaskRingRatioItemDto.setProportion(BigDecimal.ZERO);
                dailyTaskRingRatioItemDto.setProportionDesc("0%");
            }
            dailyTaskItemDtoList.add(dailyTaskRingRatioItemDto);
        }
        checkTaskTypeItemDtoList.add(checkTaskTypeItemDtoSpecialTask);
        checkTaskTypeItemDtoList.add(checkTaskTypeItemDtoDailyTask);
        checkTaskDto.setCheckTaskTypeItemDtoList(checkTaskTypeItemDtoList);

        List<String> descResultList = new ArrayList<>();
        checkTaskTypeItemDtoList.forEach(checkTaskTypeItemDto -> {
            String descOne = checkTaskTypeItemDto.getTypeDesc() + ":发布" + checkTaskTypeItemDto.getCount() + "次,";
            List<String> descList = new ArrayList<>();
            checkTaskTypeItemDto.getCompareItemDtoList().forEach(item -> {
                descList.add(item.getCompareTypeDesc() + item.getCompareResultTypeDesc() + item.getProportionDesc());
            });
            String descTwo = String.join(",", descList);
            descResultList.add(descOne + descTwo);
        });
        String desc = String.join(";\n", descResultList);
        checkTaskDto.setDesc(desc);

        return checkTaskDto;
    }

    /**
     * 获取问题发现统计
     *
     * @param paramDto 质控分析报告-问题发现统计查询参数
     * @return 问题发现统计
     */
    private SysCheckAnalysisReportCheckProblemDiscoveryDto getCheckProblemDiscoveryDto(SysAnalysisReportParamDto paramDto) {
        List<Long> userIdList = new ArrayList<>();
        if (ObjUtil.isNotNull(paramDto.getUserId())) {
            userIdList.add(paramDto.getUserId());
        } else {
            List<SysUser> sysUserList = sysUserService.selectUserByDeptId(paramDto.getDeptId());
            if (ObjUtil.isEmpty(sysUserList)) {
                return null;
            }
            userIdList.addAll(sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList()));
        }
        SysCheckAnalysisReportCheckProblemDiscoveryDto checkProblemDiscoveryDto = new SysCheckAnalysisReportCheckProblemDiscoveryDto();
        List<SysCheckAnalysisReportCheckProblemDiscoveryItemDto> checkProblemDiscoveryItemDtoList = new ArrayList<>();
        paramDto.getDateRangeList().forEach(dateRange -> {
            CheckLargeScreenPlanQueryParamDto dto = new CheckLargeScreenPlanQueryParamDto();
            dto.setStartDate(dateRange.getStartDate());
            dto.setEndDate(dateRange.getEndDate());
            dto.setUserIdList(userIdList);
            BigDecimal count = checkLargeScreenMapper.problemDistributionTotal(dto);
            SysCheckAnalysisReportCheckProblemDiscoveryItemDto checkProblemDiscoveryItemDto = new SysCheckAnalysisReportCheckProblemDiscoveryItemDto();
            checkProblemDiscoveryItemDto.setStartDate(dateRange.getStartDate());
            checkProblemDiscoveryItemDto.setEndDate(dateRange.getEndDate());
            checkProblemDiscoveryItemDto.setDesc(dateRange.getDesc());
            checkProblemDiscoveryItemDto.setTag(dateRange.getTag());
            checkProblemDiscoveryItemDto.setTagDesc(dateRange.getTagDesc());
            checkProblemDiscoveryItemDto.setCount(count);
            checkProblemDiscoveryItemDtoList.add(checkProblemDiscoveryItemDto);
        });
        checkProblemDiscoveryDto.setCheckProblemDiscoveryItemDtoList(checkProblemDiscoveryItemDtoList);

        BigDecimal currentCount = checkProblemDiscoveryItemDtoList.stream().filter(item -> CompareTypeEnum.CURRENT.getCode().equals(item.getTag())).findFirst().map(SysCheckAnalysisReportCheckProblemDiscoveryItemDto::getCount).orElse(BigDecimal.ZERO);
        checkProblemDiscoveryDto.setCount(currentCount);
        BigDecimal yearOnYearCount = checkProblemDiscoveryItemDtoList.stream().filter(item -> CompareTypeEnum.YEAR_ON_YEAR.getCode().equals(item.getTag())).findFirst().map(SysCheckAnalysisReportCheckProblemDiscoveryItemDto::getCount).orElse(BigDecimal.ZERO);
        SysCheckAnalysisReportCheckProblemDiscoveryItemDto checkProblemDiscoveryRingRatioItemDto = checkProblemDiscoveryItemDtoList.stream().filter(item -> CompareTypeEnum.RING_RATIO.getCode().equals(item.getTag())).findFirst().orElse(null);
        BigDecimal ringRatioCount = checkProblemDiscoveryRingRatioItemDto != null ? checkProblemDiscoveryRingRatioItemDto.getCount() : BigDecimal.ZERO;

        List<SysAnalysisReportCompareItemDto> compareItemDtoList = new ArrayList<>();
        checkProblemDiscoveryDto.setCompareItemDtoList(compareItemDtoList);
        SysAnalysisReportCompareItemDto yearOnYearItemDto = new SysAnalysisReportCompareItemDto();
        yearOnYearItemDto.setCompareType(CompareTypeEnum.YEAR_ON_YEAR.getCode());
        yearOnYearItemDto.setCompareTypeDesc(CompareTypeEnum.YEAR_ON_YEAR.getDesc());
        BigDecimal subtractYearOnYear = currentCount.subtract(yearOnYearCount);
        if (subtractYearOnYear.compareTo(BigDecimal.ZERO) > 0) {
            yearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
            yearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
            yearOnYearItemDto.setProportion(yearOnYearCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractYearOnYear.divide(yearOnYearCount, 4, RoundingMode.HALF_UP));
            yearOnYearItemDto.setProportionDesc(yearOnYearItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : yearOnYearItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
        } else if (subtractYearOnYear.compareTo(BigDecimal.ZERO) < 0) {
            yearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.DECLINE.getCode());
            yearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.DECLINE.getDesc());
            yearOnYearItemDto.setProportion(yearOnYearCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractYearOnYear.abs().divide(yearOnYearCount, 4, RoundingMode.HALF_UP));
            yearOnYearItemDto.setProportionDesc(yearOnYearItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : yearOnYearItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
        } else {
            yearOnYearItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
            yearOnYearItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
            yearOnYearItemDto.setProportion(BigDecimal.ZERO);
            yearOnYearItemDto.setProportionDesc("0%");
        }
        compareItemDtoList.add(yearOnYearItemDto);
        if (checkProblemDiscoveryRingRatioItemDto != null) {
            SysAnalysisReportCompareItemDto ringRatioItemDto = new SysAnalysisReportCompareItemDto();
            ringRatioItemDto.setCompareType(CompareTypeEnum.RING_RATIO.getCode());
            ringRatioItemDto.setCompareTypeDesc(CompareTypeEnum.RING_RATIO.getDesc());
            BigDecimal subtractSpecialTaskRingRatio = currentCount.subtract(ringRatioCount);
            if (subtractSpecialTaskRingRatio.compareTo(BigDecimal.ZERO) > 0) {
                ringRatioItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
                ringRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
                ringRatioItemDto.setProportion(ringRatioCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractSpecialTaskRingRatio.divide(ringRatioCount, 4, RoundingMode.HALF_UP));
                ringRatioItemDto.setProportionDesc(ringRatioItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : ringRatioItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
            } else if (subtractSpecialTaskRingRatio.compareTo(BigDecimal.ZERO) < 0) {
                ringRatioItemDto.setCompareResultType(CompareResultTypeEnum.DECLINE.getCode());
                ringRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.DECLINE.getDesc());
                ringRatioItemDto.setProportion(ringRatioCount.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : subtractSpecialTaskRingRatio.abs().divide(ringRatioCount, 4, RoundingMode.HALF_UP));
                ringRatioItemDto.setProportionDesc(ringRatioItemDto.getProportion().compareTo(BigDecimal.ZERO) == 0 ? "--%" : ringRatioItemDto.getProportion().multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP) + "%");
            } else {
                ringRatioItemDto.setCompareResultType(CompareResultTypeEnum.RISE.getCode());
                ringRatioItemDto.setCompareResultTypeDesc(CompareResultTypeEnum.RISE.getDesc());
                ringRatioItemDto.setProportion(BigDecimal.ZERO);
                ringRatioItemDto.setProportionDesc("0%");
            }
            compareItemDtoList.add(ringRatioItemDto);
        }

        String descOne = "共发现问题" + checkProblemDiscoveryDto.getCount() + "个,";
        List<String> descList = new ArrayList<>();
        checkProblemDiscoveryDto.getCompareItemDtoList().forEach(item -> descList.add(item.getCompareTypeDesc() + item.getCompareResultTypeDesc() + item.getProportionDesc()));
        String descTwo = String.join(",", descList);
        checkProblemDiscoveryDto.setDesc(descOne + descTwo);
        return checkProblemDiscoveryDto;
    }

    /**
     * 获取问题分布统计
     *
     * @param paramDto 质控分析报告-问题分布统计查询参数
     * @return 问题分布统计
     */
    private SysCheckAnalysisReportCheckProblemDistributionDto getCheckProblemDistributionDto(SysAnalysisReportParamDto paramDto) {
        List<Long> userIdList = new ArrayList<>();
        if (ObjUtil.isNotNull(paramDto.getUserId())) {
            userIdList.add(paramDto.getUserId());
        } else {
            List<SysUser> sysUserList = sysUserService.selectUserByDeptId(paramDto.getDeptId());
            if (ObjUtil.isEmpty(sysUserList)) {
                return null;
            }
            userIdList.addAll(sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList()));
        }
        SysCheckAnalysisReportCheckProblemDistributionDto checkProblemDistributionDto = new SysCheckAnalysisReportCheckProblemDistributionDto();
        SysAnalysisReportDateRangeDto currentDateRangeDto = paramDto.getDateRangeList().stream().filter(dateRange -> StrUtil.equals(CompareTypeEnum.CURRENT.getCode(), dateRange.getTag())).findFirst().orElse(null);
        BaseLargeScreenQueryParamDto queryParamDto = new BaseLargeScreenQueryParamDto();
        queryParamDto.setStartDate(currentDateRangeDto.getStartDate());
        queryParamDto.setEndDate(currentDateRangeDto.getEndDate());
        queryParamDto.setUserIdList(userIdList);
        List<SysCheckAnalysisReportCheckProblemDistributionItemDto> checkProblemDistributionItemDtoList = checkLargeScreenMapper.problemDistributionStatistics(queryParamDto);
        checkProblemDistributionDto.setCheckProblemDistributionItemDtoList(checkProblemDistributionItemDtoList);
        if (CollUtil.isEmpty(checkProblemDistributionItemDtoList)) {
            return null;
        }

        StringBuilder desc = new StringBuilder();
        String formatOne = "当前安检质控中,%s类型问题的数量最多(%s件),是问题集中的主要类型";
        desc.append(String.format(formatOne, checkProblemDistributionItemDtoList.get(0).getName(), checkProblemDistributionItemDtoList.get(0).getTotal()));
        if (checkProblemDistributionItemDtoList.size() > 1) {
            List<String> list = new ArrayList<>();
            checkProblemDistributionItemDtoList = checkProblemDistributionItemDtoList.stream().skip(1).collect(Collectors.toList());
            checkProblemDistributionItemDtoList = checkProblemDistributionItemDtoList.stream().limit(2).collect(Collectors.toList());
            checkProblemDistributionItemDtoList.forEach(sysCheckAnalysisReportCheckProblemDistributionItemDto -> list.add(sysCheckAnalysisReportCheckProblemDistributionItemDto.getName() + "(" + sysCheckAnalysisReportCheckProblemDistributionItemDto.getTotal() + "件)"));
            String join = String.join("、", list);
            String formatTwo = ";其次是%s";
            desc.append(String.format(formatTwo, join));
        }
        checkProblemDistributionDto.setDesc(desc.length() == 0 ? null : desc.toString());

        return checkProblemDistributionDto;
    }

    /**
     * 获取问题整改统计
     *
     * @param paramDto 质控分析报告-问题整改统计查询参数
     * @return 问题整改统计
     */
    private SysCheckAnalysisReportCheckProblemCorrectionDto getCheckProblemCorrectionDto(SysAnalysisReportParamDto paramDto) {
        SysCheckAnalysisReportCheckProblemCorrectionDto checkProblemCorrectionDto = new SysCheckAnalysisReportCheckProblemCorrectionDto();
        List<SysCheckAnalysisReportCheckProblemCorrectionItemDto> checkProblemCorrectionItemDtoList = new ArrayList<>();
        checkProblemCorrectionDto.setCheckProblemCorrectionItemDtoList(checkProblemCorrectionItemDtoList);
        SysAnalysisReportDateRangeDto currentDateRangeDto = paramDto.getDateRangeList().stream().filter(dateRange -> StrUtil.equals(CompareTypeEnum.CURRENT.getCode(), dateRange.getTag())).findFirst().orElse(null);

        CheckLargeScreenCorrectionQueryParamDto tempQueryParam = new CheckLargeScreenCorrectionQueryParamDto();
        tempQueryParam.setStartDate(currentDateRangeDto.getStartDate());
        tempQueryParam.setEndDate(currentDateRangeDto.getEndDate());
        List<CheckLargeScreenCorrectionPortraitSqlDto> all = checkLargeScreenMapper.portrait(tempQueryParam);
        if (CollUtil.isEmpty(all)) {
            return null;
        }
        //补充检查级别为站级的整改单中的被检查班组数据
        List<Long> userIdList = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedTeamId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getUserId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userIdList)) {
            List<SysUser> sysUserList = sysUserService.selectByUserIdList(userIdList);
            Map<Long, Long> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getDeptId, (oldValue, newValue) -> newValue));
            List<Long> deptIdList = sysUserList.stream().map(SysUser::getDeptId).distinct().collect(Collectors.toList());
            List<SysDept> deptList = sysDeptService.selectDeptByIdList(deptIdList);
            Map<Long, String> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
            all.forEach(item -> {
                if (ObjectUtil.isNull(item.getCheckedTeamId())) {
                    item.setCheckedTeamId(sysUserMap.getOrDefault(item.getUserId(), 0L));
                    item.setCheckedTeamName(deptMap.getOrDefault(item.getCheckedTeamId(), ""));
                }
            });
        }
        //补充被检查班科室数据
        List<Long> checkedTeamIdListTemp = all.stream().filter(item -> ObjectUtil.isNull(item.getCheckedDepartmentId())).map(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedTeamId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(checkedTeamIdListTemp)) {
            List<SysDept> checkedTeamListTemp = sysDeptService.selectDeptByIdList(checkedTeamIdListTemp);
            if (CollUtil.isNotEmpty(checkedTeamListTemp)) {
                Map<Long, Long> deptIdMap = checkedTeamListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getParentId, (oldValue, newValue) -> newValue));
                List<Long> checkedDepartmentIdListTemp = checkedTeamListTemp.stream().map(SysDept::getParentId).collect(Collectors.toList());
                List<SysDept> checkedDepartmentListTemp = sysDeptService.selectDeptByIdList(checkedDepartmentIdListTemp);
                if (CollUtil.isNotEmpty(checkedDepartmentListTemp)) {
                    Map<Long, String> deptMap = checkedDepartmentListTemp.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (oldValue, newValue) -> newValue));
                    all.forEach(item -> {
                        if (ObjectUtil.isNull(item.getCheckedDepartmentId())) {
                            item.setCheckedDepartmentId(deptIdMap.getOrDefault(item.getCheckedTeamId(), 0L));
                            item.setCheckedDepartmentName(deptMap.getOrDefault(item.getCheckedDepartmentId(), ""));
                        }
                    });
                }
            }
        }

        if (ObjUtil.isNotNull(paramDto.getUserId())) {
            List<CheckLargeScreenCorrectionPortraitSqlDto> targetList = all.stream().filter(item -> ObjUtil.equals(paramDto.getUserId(), item.getUserId())).collect(Collectors.toList());
            if (CollUtil.isEmpty(targetList)) {
                return null;
            }
            SysCheckAnalysisReportCheckProblemCorrectionItemDto individual = new SysCheckAnalysisReportCheckProblemCorrectionItemDto();
            SysUser sysUser = sysUserService.selectUserById(paramDto.getUserId());
            individual.setDeptId(sysUser.getUserId());
            individual.setDeptName(sysUser.getNickName());
            individual.setOnTimeCompletedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
            individual.setOverTimeCompletedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
            individual.setOnTimeUnfinishedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
            individual.setOverTimeUnfinishedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
            individual.setOtherCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OTHER.getCode(), item.getCorrectionType())).count()));
            String desc = "按期整改" + individual.getOnTimeCompletedCount().add(individual.getOnTimeUnfinishedCount()) + "个,超期整改" + individual.getOverTimeCompletedCount().add(individual.getOverTimeUnfinishedCount()) + "个";
            checkProblemCorrectionDto.setDesc(desc);
            checkProblemCorrectionItemDtoList.add(individual);
        } else {
            SysDept sysDept = sysDeptService.selectDeptById(paramDto.getDeptId());
            List<SysUser> sysUserList = sysUserService.selectUserByDeptId(sysDept.getDeptId());
            if (CollUtil.isEmpty(sysUserList)) {
                return null;
            }
            List<Long> targetUserIdList = sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
            List<CheckLargeScreenCorrectionPortraitSqlDto> targetList = all.stream().filter(item -> targetUserIdList.contains(item.getUserId())).collect(Collectors.toList());
            if (CollUtil.isEmpty(targetList)) {
                return null;
            }
            if (StrUtil.equals(sysDept.getDeptType(), DeptTypeEnum.STATION.getCode())) {
                Map<String, Long> descMap = targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).collect(Collectors.groupingBy(item -> item.getCheckedBrigadeId() + "###" + item.getCheckedBrigadeName(), Collectors.counting()));
                String key = descMap.entrySet().stream()
                        .max(Map.Entry.comparingByValue())
                        .map(Map.Entry::getKey)
                        .orElse(null);
                if (ObjUtil.isNotNull(key)) {
                    String desc = key.split("###")[1] + "的按时整改率更高、整改更及时,是当时整改工作落实较好的大队";
                    checkProblemCorrectionDto.setDesc(desc);
                }

                Map<Long, List<CheckLargeScreenCorrectionPortraitSqlDto>> deptMap = targetList.stream().collect(Collectors.groupingBy(CheckLargeScreenCorrectionPortraitSqlDto::getCheckedBrigadeId));
                SysDept deptQuery = new SysDept();
                deptQuery.setParentId(sysDept.getDeptId());
                deptQuery.setDeptType(DeptTypeEnum.BRIGADE.getCode());
                List<SysDept> sysDeptList = sysDeptService.selectDeptInfoAll(deptQuery);
                sysDeptList.forEach(dept -> {
                    SysCheckAnalysisReportCheckProblemCorrectionItemDto itemDto = new SysCheckAnalysisReportCheckProblemCorrectionItemDto();
                    itemDto.setDeptId(dept.getDeptId());
                    itemDto.setDeptName(dept.getDeptName());
                    List<CheckLargeScreenCorrectionPortraitSqlDto> list = deptMap.get(dept.getDeptId());
                    if (CollUtil.isNotEmpty(list)) {
                        itemDto.setOnTimeCompletedCount(BigDecimal.valueOf(list.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
                        itemDto.setOverTimeCompletedCount(BigDecimal.valueOf(list.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
                        itemDto.setOnTimeUnfinishedCount(BigDecimal.valueOf(list.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
                        itemDto.setOverTimeUnfinishedCount(BigDecimal.valueOf(list.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
                        itemDto.setOtherCount(BigDecimal.valueOf(list.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OTHER.getCode(), item.getCorrectionType())).count()));
                    } else {
                        itemDto.setOnTimeCompletedCount(BigDecimal.ZERO);
                        itemDto.setOverTimeCompletedCount(BigDecimal.ZERO);
                        itemDto.setOnTimeUnfinishedCount(BigDecimal.ZERO);
                        itemDto.setOverTimeUnfinishedCount(BigDecimal.ZERO);
                        itemDto.setOtherCount(BigDecimal.ZERO);
                    }
                    checkProblemCorrectionItemDtoList.add(itemDto);
                });

                SysCheckAnalysisReportCheckProblemCorrectionItemDto totalItem = new SysCheckAnalysisReportCheckProblemCorrectionItemDto();
                totalItem.setDeptId(null);
                totalItem.setDeptName("总数");
                totalItem.setOnTimeCompletedCount(checkProblemCorrectionItemDtoList.stream().map(SysCheckAnalysisReportCheckProblemCorrectionItemDto::getOnTimeCompletedCount).reduce(BigDecimal.ZERO, BigDecimal::add));
                totalItem.setOverTimeCompletedCount(checkProblemCorrectionItemDtoList.stream().map(SysCheckAnalysisReportCheckProblemCorrectionItemDto::getOverTimeCompletedCount).reduce(BigDecimal.ZERO, BigDecimal::add));
                totalItem.setOnTimeUnfinishedCount(checkProblemCorrectionItemDtoList.stream().map(SysCheckAnalysisReportCheckProblemCorrectionItemDto::getOnTimeUnfinishedCount).reduce(BigDecimal.ZERO, BigDecimal::add));
                totalItem.setOverTimeUnfinishedCount(checkProblemCorrectionItemDtoList.stream().map(SysCheckAnalysisReportCheckProblemCorrectionItemDto::getOverTimeUnfinishedCount).reduce(BigDecimal.ZERO, BigDecimal::add));
                totalItem.setOtherCount(checkProblemCorrectionItemDtoList.stream().map(SysCheckAnalysisReportCheckProblemCorrectionItemDto::getOtherCount).reduce(BigDecimal.ZERO, BigDecimal::add));
                checkProblemCorrectionItemDtoList.add(0, totalItem);
            } else if (StrUtil.equals(sysDept.getDeptType(), DeptTypeEnum.BRIGADE.getCode())) {
                Map<String, Long> descMap = targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).collect(Collectors.groupingBy(item -> item.getCheckedDepartmentId() + "###" + item.getCheckedDepartmentName(), Collectors.counting()));
                String key = descMap.entrySet().stream()
                        .max(Map.Entry.comparingByValue())
                        .map(Map.Entry::getKey)
                        .orElse(null);
                if (ObjUtil.isNotNull(key)) {
                    String desc = key.split("###")[1] + "的按时整改率更高、整改更及时,是当时整改工作落实较好的主管";
                    checkProblemCorrectionDto.setDesc(desc);
                }

                SysCheckAnalysisReportCheckProblemCorrectionItemDto totalItem = new SysCheckAnalysisReportCheckProblemCorrectionItemDto();
                totalItem.setDeptId(sysDept.getDeptId());
                totalItem.setDeptName(sysDept.getDeptName());
                totalItem.setOnTimeCompletedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOverTimeCompletedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOnTimeUnfinishedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOverTimeUnfinishedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOtherCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OTHER.getCode(), item.getCorrectionType())).count()));
                checkProblemCorrectionItemDtoList.add(totalItem);
            } else if (StrUtil.equals(sysDept.getDeptType(), DeptTypeEnum.MANAGER.getCode())) {
                Map<String, Long> descMap = targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).collect(Collectors.groupingBy(item -> item.getCheckedTeamId() + "###" + item.getCheckedTeamName(), Collectors.counting()));
                String key = descMap.entrySet().stream()
                        .max(Map.Entry.comparingByValue())
                        .map(Map.Entry::getKey)
                        .orElse(null);
                if (ObjUtil.isNotNull(key)) {
                    String desc = key.split("###")[1] + "的按时整改率更高、整改更及时,是当时整改工作落实较好的班组";
                    checkProblemCorrectionDto.setDesc(desc);
                }

                SysCheckAnalysisReportCheckProblemCorrectionItemDto totalItem = new SysCheckAnalysisReportCheckProblemCorrectionItemDto();
                totalItem.setDeptId(sysDept.getDeptId());
                totalItem.setDeptName(sysDept.getDeptName());
                totalItem.setOnTimeCompletedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOverTimeCompletedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOnTimeUnfinishedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOverTimeUnfinishedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOtherCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OTHER.getCode(), item.getCorrectionType())).count()));
                checkProblemCorrectionItemDtoList.add(totalItem);
            } else if (StrUtil.equals(sysDept.getDeptType(), DeptTypeEnum.TEAMS.getCode())) {
                Map<String, Long> descMap = targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).collect(Collectors.groupingBy(item -> item.getUserId() + "###" + item.getUserName(), Collectors.counting()));
                String key = descMap.entrySet().stream()
                        .max(Map.Entry.comparingByValue())
                        .map(Map.Entry::getKey)
                        .orElse(null);
                if (ObjUtil.isNotNull(key)) {
                    String desc = key.split("###")[1] + "的按时整改率更高、整改更及时,是当时整改工作落实较好的成员";
                    checkProblemCorrectionDto.setDesc(desc);
                }

                SysCheckAnalysisReportCheckProblemCorrectionItemDto totalItem = new SysCheckAnalysisReportCheckProblemCorrectionItemDto();
                totalItem.setDeptId(sysDept.getDeptId());
                totalItem.setDeptName(sysDept.getDeptName());
                totalItem.setOnTimeCompletedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOverTimeCompletedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_COMPLETED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOnTimeUnfinishedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.ON_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOverTimeUnfinishedCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OVER_TIME_UNFINISHED.getCode(), item.getCorrectionType())).count()));
                totalItem.setOtherCount(BigDecimal.valueOf(targetList.stream().filter(item -> StrUtil.equals(CheckLargeScreenCorrectionTypeEnum.OTHER.getCode(), item.getCorrectionType())).count()));
                checkProblemCorrectionItemDtoList.add(totalItem);
            } else {
                throw new ServiceException("部门类型错误");
            }
        }

        return checkProblemCorrectionDto;
    }

    /**
     * 质控分析报告-质控活动-问题分布统计
     *
     * @param paramDto 查询参数
     * @return 质控分析报告-质控活动-问题分布统计
     */
    @Override
    public SysCheckAnalysisReportCheckProblemDistributionDto getCheckProblemDistribution(BaseLargeScreenQueryParamDto paramDto) {
        SysCheckAnalysisReportCheckProblemDistributionDto checkProblemDistributionDto = new SysCheckAnalysisReportCheckProblemDistributionDto();
        List<SysCheckAnalysisReportCheckProblemDistributionItemDto> checkProblemDistributionItemDtoList = checkLargeScreenMapper.problemDistributionStatistics(paramDto);
        checkProblemDistributionDto.setCheckProblemDistributionItemDtoList(checkProblemDistributionItemDtoList);
        if (CollUtil.isEmpty(checkProblemDistributionItemDtoList)) {
            return null;
        }

        StringBuilder desc = new StringBuilder();
        String formatOne = "%s类型问题占比最大";
        desc.append(String.format(formatOne, checkProblemDistributionItemDtoList.get(0).getName()));
        checkProblemDistributionDto.setDesc(desc.length() == 0 ? null : desc.toString());

        return checkProblemDistributionDto;
    }

    /**
     * 使用报表-运行情况-巡检模块
     *
     * @param paramDto 查询参数
     * @return 使用报表-运行情况-巡检模块
     */
    @Override
    public SysUsageReportDto.CheckModule getCheckModule(BaseLargeScreenQueryParamDto paramDto) {
        SysUsageReportDto.CheckModule checkModule = new SysUsageReportDto.CheckModule();
        List<SysUsageReportCheckTaskDto> checkTaskDtoList = checkLargeScreenMapper.getUsageReportCheckTaskDto(paramDto);
        if (CollUtil.isEmpty(checkTaskDtoList)) {
            return null;
        }
        List<String> taskCodeList = checkTaskDtoList.stream().map(SysUsageReportCheckTaskDto::getTaskCode).collect(Collectors.toList());
        List<BaseCommonDto> checkTaskTypeList = new ArrayList<>();
        Map<String, List<SysUsageReportCheckTaskDto>> levelCodeMap = checkTaskDtoList.stream().collect(Collectors.groupingBy(dto -> dto.getLevelCode() + "###" + dto.getLevelName()));
        levelCodeMap.forEach((key, value) -> {
            String[] split = key.split("###");
            String levelCode = split[0];
            String levelName = split[1];
            BaseCommonDto baseCommonDto = new BaseCommonDto();
            baseCommonDto.setCode(levelCode);
            baseCommonDto.setName(levelName);
            baseCommonDto.setTotal(new BigDecimal((int) value.stream().map(SysUsageReportCheckTaskDto::getTaskCode).distinct().count()));
            baseCommonDto.setRemark(value.stream().map(SysUsageReportCheckTaskDto::getCategoryName).distinct().collect(Collectors.joining("、")));
            checkTaskTypeList.add(baseCommonDto);
        });
        checkTaskTypeList.sort(Comparator.comparing(BaseCommonDto::getTotal).reversed());
        checkModule.setCheckTaskTypeList(checkTaskTypeList);
        checkModule.setTotalCheckForm(checkLargeScreenMapper.getUsageReportCheckRecordCount(taskCodeList));
        List<BaseCommonDto> usageReportCheckCorrectionDto = checkLargeScreenMapper.getUsageReportCheckCorrectionDto(taskCodeList);
        checkModule.setCheckCategoryTypeList(usageReportCheckCorrectionDto);
        checkModule.setTotalProblemItem(usageReportCheckCorrectionDto.stream().map(BaseCommonDto::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add).intValue());
        return checkModule;
    }

}
