package com.sundot.airport.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sundot.airport.attendance.service.IAttendancePostRecordService;
import com.sundot.airport.check.service.ICheckLargeScreenService;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.*;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.dto.AttendanceWorkDurationDto;
import com.sundot.airport.common.enums.DeptType;
import com.sundot.airport.common.enums.HomePageQueryEnum;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.exam.service.IAccuracyStatisticsService;
import com.sundot.airport.item.service.SeizureReportService;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysLearningGrowthService;
import com.sundot.airport.system.service.ISysUserService;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 首页报表控制器
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/homeReport")
public class SysHomeReportController extends BaseController {

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ICheckLargeScreenService checkLargeScreenService;

    @Autowired
    private ISysLearningGrowthService sysLearningGrowthService;

    @Autowired
    private IAccuracyStatisticsService accuracyStatisticsService;

    @Autowired
    private SeizureReportService seizureReportService;

    @Autowired
    private IAttendancePostRecordService attendancePostRecordService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 首页报表-下载
     */
    @SneakyThrows
    @GetMapping("/download")
    public void downloadHomeReport(HttpServletResponse response, BaseLargeScreenQueryParamDto dto) {
        // 获取首页报表-整体
        SysHomeReportDto result = getHomeReportDto(dto);
        // 设置响应头
        String fileName = URLEncoder.encode("首页报表", "UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        // 1. 创建表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();

        // 设置表头字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 11);  // 字体大小
        headWriteFont.setBold(true);                      // 加粗
        headWriteFont.setFontName("宋体");                // 字体类型
        headWriteFont.setColor(IndexedColors.BLACK.getIndex()); // 字体颜色
        headWriteCellStyle.setWriteFont(headWriteFont);

        // 设置表头单元格样式
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 背景色
        headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); // 填充模式
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);    // 水平居中
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);      // 垂直居中
        headWriteCellStyle.setWrapped(true);  // 自动换行

        // 设置表头边框 - 细实线
        headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        headWriteCellStyle.setBorderRight(BorderStyle.THIN);
        headWriteCellStyle.setBorderTop(BorderStyle.THIN);
        headWriteCellStyle.setBorderBottom(BorderStyle.THIN);

        // 设置边框颜色
        headWriteCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        headWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        headWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        headWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

        // 2. 创建内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        // 设置内容字体
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short) 11);  // 内容字体大小
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setColor(IndexedColors.BLACK.getIndex());
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        // 设置内容单元格样式
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setWrapped(true);

        // 设置内容边框 - 细实线
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

        // 设置边框颜色
        contentWriteCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        contentWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        contentWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        contentWriteCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        // 创建ExcelWriter
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(horizontalCellStyleStrategy)
                .build();

        try {
            // 第一个sheet：巡检合格率
            WriteSheet checkSheet = EasyExcel.writerSheet(0, "巡检合格率")
                    .head(SysHomeReportDetailCheckExcelDto.class)
                    .build();
            List<SysHomeReportDetailCheckExcelDto> checkExcelData = getCheckExcelDtoData(result.getCheckList());
            excelWriter.write(checkExcelData, checkSheet);

            // 第二个sheet：培训答题分数
            WriteSheet learningSheet = EasyExcel.writerSheet(1, "培训答题分数")
                    .head(SysHomeReportDetailLearningExcelDto.class)
                    .build();
            List<SysHomeReportDetailLearningExcelDto> learningExcelData = getLearningExcelDtoData(result.getLearningList());
            excelWriter.write(learningExcelData, learningSheet);

            // 第三个sheet：抽问抽答正确率
            WriteSheet answerSheet = EasyExcel.writerSheet(2, "抽问抽答正确率")
                    .head(SysHomeReportDetailAnswerExcelDto.class)
                    .build();
            List<SysHomeReportDetailAnswerExcelDto> answerExcelData = getAnswerExcelDtoData(result.getAnswerList());
            excelWriter.write(answerExcelData, answerSheet);

            // 第四个sheet：查获数量
            WriteSheet seizureSheet = EasyExcel.writerSheet(3, "查获数量")
                    .head(SysHomeReportDetailSeizureExcelDto.class)
                    .build();
            List<SysHomeReportDetailSeizureExcelDto> seizureExcelData = getSeizureExcelDtoData(result.getSeizureList());
            excelWriter.write(seizureExcelData, seizureSheet);

            // 第五个sheet：工作时长
            WriteSheet workingSheet = EasyExcel.writerSheet(4, "工作时长")
                    .head(SysHomeReportDetailWorkingExcelDto.class)
                    .build();
            List<SysHomeReportDetailWorkingExcelDto> workingExcelData = getWorkingExcelDtoData(result.getWorkingList());
            excelWriter.write(workingExcelData, workingSheet);
        } catch (Exception e) {
            throw new RuntimeException("导出报表失败", e);
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    /**
     * 获取首页报表下载数据-工作时长
     *
     * @param workingList
     * @return
     */
    private List<SysHomeReportDetailWorkingExcelDto> getWorkingExcelDtoData(List<SysHomeReportDetailDto> workingList) {
        List<SysHomeReportDetailWorkingExcelDto> result = new ArrayList<>();
        workingList.forEach(item -> {
            SysHomeReportDetailWorkingExcelDto excelDto = new SysHomeReportDetailWorkingExcelDto();
            excelDto.setName(item.getName());
            excelDto.setTotalNumber(item.getTotalNumber());
            excelDto.setAverageNumber(item.getAverageNumber());
            excelDto.setMedianNumber(item.getMedianNumber());
            excelDto.setMaxNumber(item.getMaxNumber());
            excelDto.setMinNumber(item.getMinNumber());
            result.add(excelDto);
        });
        return result;
    }

    /**
     * 获取首页报表下载数据-巡检合格率
     */
    private List<SysHomeReportDetailCheckExcelDto> getCheckExcelDtoData(List<SysHomeReportDetailDto> checkList) {
        List<SysHomeReportDetailCheckExcelDto> result = new ArrayList<>();
        checkList.forEach(item -> {
            SysHomeReportDetailCheckExcelDto excelDto = new SysHomeReportDetailCheckExcelDto();
            excelDto.setName(item.getName());
            excelDto.setAverageNumber(item.getAverageNumber().multiply(BigDecimal.valueOf(100)));
            excelDto.setMedianNumber(item.getMedianNumber().multiply(BigDecimal.valueOf(100)));
            excelDto.setMaxNumber(item.getMaxNumber().multiply(BigDecimal.valueOf(100)));
            excelDto.setMinNumber(item.getMinNumber().multiply(BigDecimal.valueOf(100)));
            result.add(excelDto);
        });
        return result;
    }

    /**
     * 获取首页报表下载数据-培训答题分数
     */
    private List<SysHomeReportDetailLearningExcelDto> getLearningExcelDtoData(List<SysHomeReportDetailDto> learningList) {
        List<SysHomeReportDetailLearningExcelDto> result = new ArrayList<>();
        learningList.forEach(item -> {
            SysHomeReportDetailLearningExcelDto excelDto = new SysHomeReportDetailLearningExcelDto();
            excelDto.setName(item.getName());
            excelDto.setAverageNumber(item.getAverageNumber());
            excelDto.setMedianNumber(item.getMedianNumber());
            excelDto.setMaxNumber(item.getMaxNumber());
            excelDto.setMinNumber(item.getMinNumber());
            result.add(excelDto);
        });
        return result;
    }

    /**
     * 获取首页报表下载数据-抽问抽答正确率
     */
    private List<SysHomeReportDetailAnswerExcelDto> getAnswerExcelDtoData(List<SysHomeReportDetailDto> answerList) {
        List<SysHomeReportDetailAnswerExcelDto> result = new ArrayList<>();
        if (answerList != null) {
            answerList.forEach(item -> {
                SysHomeReportDetailAnswerExcelDto excelDto = new SysHomeReportDetailAnswerExcelDto();
                excelDto.setName(item.getName());
                excelDto.setAverageNumber(item.getAverageNumber());
                excelDto.setMedianNumber(item.getMedianNumber());
                excelDto.setMaxNumber(item.getMaxNumber());
                excelDto.setMinNumber(item.getMinNumber());
                result.add(excelDto);
            });
        }
        return result;
    }

    /**
     * 获取首页报表下载数据-查获数量
     */
    private List<SysHomeReportDetailSeizureExcelDto> getSeizureExcelDtoData(List<SysHomeReportDetailDto> learningList) {
        List<SysHomeReportDetailSeizureExcelDto> result = new ArrayList<>();
        learningList.forEach(item -> {
            SysHomeReportDetailSeizureExcelDto excelDto = new SysHomeReportDetailSeizureExcelDto();
            excelDto.setName(item.getName());
            excelDto.setTotalNumber(item.getTotalNumber());
            excelDto.setAverageNumber(item.getAverageNumber());
            excelDto.setMedianNumber(item.getMedianNumber());
            excelDto.setMaxNumber(item.getMaxNumber());
            excelDto.setMinNumber(item.getMinNumber());
            result.add(excelDto);
        });
        return result;
    }

    /**
     * 首页报表-整体
     */
    @GetMapping("/homeReportWhole")
    public AjaxResult homePageWhole(BaseLargeScreenQueryParamDto dto) {
        SysHomeReportDto result = getHomeReportDto(dto);
        return success(result);
    }

    /**
     * 获取首页报表-整体
     */
    private SysHomeReportDto getHomeReportDto(BaseLargeScreenQueryParamDto dto) {
        List<SysHomePageDetailQueryParamDto> dtoList = new ArrayList<>();
        List<SysDept> sysDeptList = deptService.selectAllDept(getDeptId());
        Collections.reverse(sysDeptList);
        SysDept stationDept = sysDeptList.stream().filter(x -> StrUtil.equals(DeptType.STATION.getCode(), x.getDeptType())).findFirst().orElse(null);
        if (ObjectUtil.isNull(stationDept)) {
            throw new ServiceException("未查询到站级部门信息");
        }
        SysHomePageDetailQueryParamDto stationDto = new SysHomePageDetailQueryParamDto();
        stationDto.setId(stationDept.getDeptId());
        stationDto.setName(stationDept.getDeptName());
        stationDto.setType(HomePageQueryEnum.DEPT.getCode());
        dtoList.add(stationDto);
        SysDept queryDept = new SysDept();
        queryDept.setParentId(stationDept.getDeptId());
        List<SysDept> deptList = deptService.selectDeptInfoAll(queryDept);
        deptList.forEach(item -> {
            SysHomePageDetailQueryParamDto departmentDto = new SysHomePageDetailQueryParamDto();
            departmentDto.setId(item.getDeptId());
            departmentDto.setName(item.getDeptName());
            departmentDto.setType(HomePageQueryEnum.DEPT.getCode());
            dtoList.add(departmentDto);
        });

        dtoList.forEach(item -> {
            item.setSpecifiedDate(dto.getSpecifiedDate());
            item.setStartDate(dto.getStartDate());
            item.setEndDate(dto.getEndDate());
        });
        SysHomeReportDto result = getSysHomeReportDto(dtoList);
        return result;
    }

    /**
     * 首页报表-明细
     */
    @PostMapping("/homeReportDetail")
    public AjaxResult homePageDetail(@RequestBody List<SysHomePageDetailQueryParamDto> dtoList) {
        SysHomeReportDto result = getSysHomeReportDto(dtoList);
        return success(result);
    }

    /**
     * 获取首页报表-明细
     */
    private SysHomeReportDto getSysHomeReportDto(List<SysHomePageDetailQueryParamDto> dtoList) {
        SysHomeReportDto result = new SysHomeReportDto();
        // 培训答题分数
        result.setLearningList(getLearningList(dtoList));
        // 巡检合格率
        result.setCheckList(getCheckList(dtoList));
        // 查获数量
        result.setSeizureList(getSeizureList(dtoList));
        // 在岗时长
        result.setWorkingList(getWorkingList(dtoList));
        // 抽问抽答正确率
        result.setAnswerList(getAnswerList(dtoList));
        return result;
    }


    /**
     * 获取首页报表-明细-查获数量
     */
    private List<SysHomeReportDetailDto> getSeizureList(List<SysHomePageDetailQueryParamDto> dtoList) {
        List<SysHomeReportDetailDto> result = new ArrayList<>();
        for (SysHomePageDetailQueryParamDto item : dtoList) {
            result.add(getSeizure(item));
        }
        return result;
    }

    /**
     * 获取首页报表-明细-培训答题分数
     */
    private List<SysHomeReportDetailDto> getLearningList(List<SysHomePageDetailQueryParamDto> dtoList) {
        List<SysHomeReportDetailDto> result = new ArrayList<>();
        for (SysHomePageDetailQueryParamDto item : dtoList) {
            result.add(getLearning(item));
        }
        return result;
    }

    /**
     * 获取首页报表-明细-巡检合格率
     */
    private List<SysHomeReportDetailDto> getCheckList(List<SysHomePageDetailQueryParamDto> dtoList) {
        List<SysHomeReportDetailDto> result = new ArrayList<>();
        for (SysHomePageDetailQueryParamDto item : dtoList) {
            result.add(getCheck(item));
        }
        return result;
    }

    /**
     * 获取巡检合格率数据
     */
    private SysHomeReportDetailDto getCheck(SysHomePageDetailQueryParamDto item) {
        BaseLargeScreenQueryParamDto dto = new BaseLargeScreenQueryParamDto();
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            dto.setUserId(item.getId());
        } else {
            dto.setDeptId(item.getId());
        }
        dto.setSpecifiedDate(item.getSpecifiedDate());
        dto.setStartDate(item.getStartDate());
        dto.setEndDate(item.getEndDate());
        return checkLargeScreenService.checkData(dto);
    }

    /**
     * 获取培训答题分数数据
     */
    private SysHomeReportDetailDto getLearning(SysHomePageDetailQueryParamDto item) {
        BaseLargeScreenQueryParamDto dto = new BaseLargeScreenQueryParamDto();
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            dto.setUserId(item.getId());
        } else {
            dto.setDeptId(item.getId());
        }
        dto.setSpecifiedDate(item.getSpecifiedDate());
        dto.setStartDate(item.getStartDate());
        dto.setEndDate(item.getEndDate());
        return sysLearningGrowthService.learningGrowthData(dto);
    }

    /**
     * 获取查获数量数据
     */
    private SysHomeReportDetailDto getSeizure(SysHomePageDetailQueryParamDto item) {
        BaseLargeScreenQueryParamDto dto = new BaseLargeScreenQueryParamDto();
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            dto.setUserId(item.getId());
        } else {
            dto.setDeptId(item.getId());
        }
        dto.setSpecifiedDate(item.getSpecifiedDate());
        dto.setStartDate(item.getStartDate());
        dto.setEndDate(item.getEndDate());
        return seizureReportService.seizureData(dto);
    }

    /**
     * 获取首页报表-明细-抽问抽答正确率
     */
    private List<SysHomeReportDetailDto> getAnswerList(List<SysHomePageDetailQueryParamDto> dtoList) {
        List<SysHomeReportDetailDto> result = new ArrayList<>();
        // 批量调用前统一初始化部门缓存，避免每次 answerData 都重复查询数据库
        accuracyStatisticsService.initDeptCache();
        try {
            for (SysHomePageDetailQueryParamDto item : dtoList) {
                result.add(getAnswer(item));
            }
        } finally {
            accuracyStatisticsService.clearDeptCache();
        }
        return result;
    }

    /**
     * 获取抽问抽答正确率数据
     */
    private SysHomeReportDetailDto getAnswer(SysHomePageDetailQueryParamDto item) {
        BaseLargeScreenQueryParamDto dto = new BaseLargeScreenQueryParamDto();
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            dto.setUserId(item.getId());
        } else {
            dto.setDeptId(item.getId());
        }
        dto.setSpecifiedDate(item.getSpecifiedDate());
        dto.setStartDate(item.getStartDate());
        dto.setEndDate(item.getEndDate());
        return accuracyStatisticsService.answerData(dto);
    }

    private List<SysHomeReportDetailDto> getWorkingList(List<SysHomePageDetailQueryParamDto> dtoList) {
        List<SysHomeReportDetailDto> result = new ArrayList<>();
        for (SysHomePageDetailQueryParamDto item : dtoList) {
            result.add(getWorking(item));
        }
        return result;
    }

    private SysHomeReportDetailDto getWorking(SysHomePageDetailQueryParamDto item) {
        // 构建查询参数
        BaseLargeScreenQueryParamDto dto = new BaseLargeScreenQueryParamDto();
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            dto.setUserId(item.getId());
        } else {
            dto.setDeptId(item.getId());
        }
        dto.setSpecifiedDate(item.getSpecifiedDate());
        dto.setStartDate(item.getStartDate());
        dto.setEndDate(item.getEndDate());
        return getWorkingHoursData(dto);
    }

    /**
     * 获取在岗时长数据
     */
    public SysHomeReportDetailDto getWorkingHoursData(BaseLargeScreenQueryParamDto dto) {
        if (ObjectUtils.isNull(dto.getUserId()) && ObjectUtils.isNull(dto.getDeptId())) {
            throw new ServiceException("用户ID和部门ID不能同时为空");
        }
        // 默认筛选条件
        if (ObjectUtils.isNull(dto.getStartDate()) && ObjectUtils.isNull(dto.getEndDate()) && ObjectUtils.isNull(dto.getSpecifiedDate())) {
            dto.setEndDate(DateUtils.addSeconds(DateUtils.truncate(DateUtils.getNowDate(), Calendar.DAY_OF_MONTH), 86399));
            dto.setStartDate(DateUtils.addDays(DateUtils.truncate(DateUtils.getNowDate(), Calendar.DAY_OF_MONTH), -6));
        }

        SysHomeReportDetailDto result = new SysHomeReportDetailDto();

        // 全量数据 - 根据用户ID或部门ID获取对应的在岗记录
        List<AttendanceWorkDurationDto> itemListAll = getAttendanceWorkDurationList(dto);

        List<AttendanceWorkDurationDto> targetList;
        if (ObjectUtils.isNotNull(dto.getUserId())) {
            SysUser sysUser = sysUserService.selectUserById(dto.getUserId());
            if (ObjectUtils.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 -> ObjectUtil.equals(item.getId(), dto.getUserId())).collect(Collectors.toList());
        } else {
            SysDept sysDept = deptService.selectDeptById(dto.getDeptId());
            if (ObjectUtils.isNull(sysDept)) {
                throw new ServiceException("部门不存在");
            }
            result.setId(sysDept.getDeptId());
            result.setName(sysDept.getDeptName());
            result.setType(HomePageQueryEnum.DEPT.getCode());
            // 根据部门ID查询该部门下的用户列表（这里可以根据实际角色进行调整）
            List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(
                    Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()),
                    dto.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(AttendanceWorkDurationDto::getWorkDuration)
                .filter(Objects::nonNull)
                .sorted()
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(targetValueList)) {
            return result;
        }

        // 最大值
        result.setMaxNumber(targetValueList.get(targetValueList.size() - 1));
        // 最小值
        result.setMinNumber(targetValueList.get(0));
        // 总和
        BigDecimal sum = targetValueList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        result.setTotalNumber(sum);
        // 总数
        long totalCount = targetList.stream().map(AttendanceWorkDurationDto::getId).distinct().count();
        // 平均值
        result.setAverageNumber(sum.divide(new BigDecimal(totalCount), 2, RoundingMode.HALF_UP));
        // 中位数
        int size = targetValueList.size();
        int middle = size / 2;
        if (size % 2 == 1) {
            result.setMedianNumber(targetValueList.get(middle));
        } else {
            result.setMedianNumber(targetValueList.get(middle - 1).add(targetValueList.get(middle)).divide(new BigDecimal(2), 2, RoundingMode.HALF_UP));
        }
        return result;
    }

    /**
     * 获取在岗工作时长列表
     */
    private List<AttendanceWorkDurationDto> getAttendanceWorkDurationList(BaseLargeScreenQueryParamDto dto) {
        List<AttendanceWorkDurationDto> result = new ArrayList<>();

        if (ObjectUtils.isNotNull(dto.getUserId())) {
            // 查询指定用户的总工作时长
            BigDecimal workDuration = attendancePostRecordService.selectPersonalTotalWorkDurationInTimeRange(
                    dto.getUserId(),
                    dto.getStartDate(),
                    dto.getEndDate()
            );
            if (workDuration != null) {
                // 将分钟转换为小时
                workDuration = workDuration.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
                AttendanceWorkDurationDto item = new AttendanceWorkDurationDto();
                item.setId(dto.getUserId());
                item.setWorkDuration(workDuration);
                result.add(item);
            }
        } else if (ObjectUtils.isNotNull(dto.getDeptId())) {
            // 根据部门查询该部门下所有用户的工作时长
            SysDept sysDept = deptService.selectDeptById(dto.getDeptId());
            if (sysDept != null) {
                // 根据部门查询该部门下的所有用户
                List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(
                        Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()),
                        dto.getDeptId()
                );

                // 提取用户ID列表
                List<Long> userIds = sysUserList.stream()
                        .map(SysUser::getUserId).distinct()
                        .collect(Collectors.toList());

                // 批量查询所有用户的工作时长
                List<AttendanceWorkDurationDto> workDurationList = attendancePostRecordService.selectBatchPersonalTotalWorkDurationInTimeRange(
                        userIds,
                        dto.getStartDate(),
                        dto.getEndDate()
                );

                // 将查询结果转换为Map便于查找
                Map<Long, BigDecimal> workDurationMap = workDurationList.stream()
                        .collect(Collectors.toMap(
                                AttendanceWorkDurationDto::getId,
                                AttendanceWorkDurationDto::getWorkDuration,
                                (existing, replacement) -> existing
                        ));

                // 组装结果
                for (SysUser user : sysUserList) {
                    BigDecimal workDuration = workDurationMap.get(user.getUserId());
                    if (workDuration == null) {
                        workDuration = BigDecimal.ZERO;
                    }
                    if (workDuration.compareTo(BigDecimal.ZERO) > 0) {
                        // 将分钟转换为小时
                        workDuration = workDuration.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
                    }
                    AttendanceWorkDurationDto item = new AttendanceWorkDurationDto();
                    item.setId(user.getUserId());
                    item.setWorkDuration(workDuration);
                    result.add(item);
                }
            }
        }

        return result;
    }


}
