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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sundot.airport.attendance.domain.AttendanceCheckRecord;
import com.sundot.airport.attendance.domain.AttendancePostRecord;
import com.sundot.airport.attendance.domain.AttendanceTeamUserRecord;
import com.sundot.airport.attendance.enums.CheckInTypeEnum;
import com.sundot.airport.attendance.service.IAttendanceCheckRecordService;
import com.sundot.airport.attendance.service.IAttendancePostRecordService;
import com.sundot.airport.attendance.service.IAttendanceTeamUserRecordService;
import com.sundot.airport.check.service.ICheckLargeScreenService;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.core.domain.model.LoginUser;
import com.sundot.airport.common.dto.AttendanceStatsResult;
import com.sundot.airport.common.dto.BrigadeLeaderStats;
import com.sundot.airport.common.dto.ChannelOpenStats;
import com.sundot.airport.common.dto.SectionLeaderStats;
import com.sundot.airport.common.dto.SecurityCheckStats;
import com.sundot.airport.common.dto.StationLeaderStats;
import com.sundot.airport.common.dto.TeamLeaderStats;
import com.sundot.airport.common.enums.DeptType;
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.SecurityUtils;
import com.sundot.airport.common.utils.StringUtils;
import com.sundot.airport.item.domain.ItemLargeScreenTotalSomeDto;
import com.sundot.airport.item.domain.SimpleDutySchedule;
import com.sundot.airport.item.mapper.SimpleDutyScheduleMapper;
import com.sundot.airport.item.service.ItemLargeScreenService;
import com.sundot.airport.system.domain.vo.PositionInfoVO;
import com.sundot.airport.system.service.IBasePositionService;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 考勤统计控制器
 * 实现不同角色的考勤统计数据查询
 *
 * @author wangxx
 */
@RestController
@RequestMapping("/attendance/stats")
public class AttendanceIndexStatsController extends BaseController {

    @Autowired
    private IAttendancePostRecordService attendancePostRecordService;

    @Autowired
    private IAttendanceTeamUserRecordService attendanceTeamUserRecordService;


    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ItemLargeScreenService itemLargeScreenService;

    @Autowired
    private IAttendanceCheckRecordService attendanceCheckRecordService;

    @Autowired
    private IBasePositionService basePositionService;

    @Autowired
    private ICheckLargeScreenService checkLargeScreenService;

    @Autowired
    private SimpleDutyScheduleMapper simpleDutyScheduleMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 获取考勤统计数据
     * 根据当前登录用户的角色返回不同的考勤统计数据
     */
    @GetMapping("/getAttendanceStats")
    public AjaxResult getAttendanceStats(@RequestHeader(value = "X-Request-Source", defaultValue = "mobile") String source) {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();
        Long userId = currentUser.getUserId();
        Long deptId = currentUser.getDeptId();

        // 获取用户角色列表
        List<String> roleKeys = currentUser.getRoles().stream()
                .map(role -> role.getRoleKey())
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

        AttendanceStatsResult result = new AttendanceStatsResult();

        // 根据角色返回不同的统计数据
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            if (roleKeys.contains(RoleTypeEnum.SecurityCheck.getCode())) {
                // 安检员角色：查出勤班组、出勤通道、出勤时间
                result.setSecurityCheckStats(getSecurityCheckStats(userId, deptId));
            } else if (roleKeys.contains(RoleTypeEnum.banzuzhang.getCode())) {
                // 班组长角色：查出勤班组、出勤通道、出勤时间
                result.setTeamLeaderStats(getTeamLeaderStats(userId, deptId));
            } else if (roleKeys.contains(RoleTypeEnum.kezhang.getCode())) {
                // 科长角色：查在岗班组、在岗人员、出勤时间、今日查获上报
                result.setSectionLeaderStats(getSectionLeaderStats(userId, deptId));
            } else if (roleKeys.contains(RoleTypeEnum.jingli.getCode()) || roleKeys.contains(RoleTypeEnum.xingzheng.getCode())) {
                // 经理和大队行政角色：查在岗班组、在岗人员、通道开放、今日查获上报
                result.setBrigadeLeaderStats(getBrigadeLeaderStats(userId, deptId));
            } else if (roleKeys.contains(RoleTypeEnum.test.getCode()) || roleKeys.contains(RoleTypeEnum.zhijianke.getCode()) || roleKeys.contains(RoleTypeEnum.admin.getCode())) {
                // 站长和质检科角色：查在岗班组、在岗人员、通道开放、今日查获上报
                result.setStationLeaderStats(getStationLeaderStats(userId, deptId));
            } else {
                throw new ServiceException("当前用户角色无法获取考勤统计数据");
            }
        } else {
            List<SysDept> sysDeptList = sysDeptService.selectAllDept(SecurityUtils.getLoginUser().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("未查询到站级部门信息");
            }
            // 站长和质检科角色：查在岗班组、在岗人员、通道开放、今日查获上报
            result.setStationLeaderStats(getStationLeaderStats(userId, stationDept.getDeptId()));
        }

        return AjaxResult.success(result);
    }

    /**
     * 安检员考勤统计数据
     * 出勤班组：查询哪个班组长在勤务板块将该安检员维护到自己班组，则显示班组长所在组织架构的班组名称
     * 出勤通道：进入该界面的时候班组长将该安检员带上哪个通道（仅显示最后一个层级，例如A02通道）
     * 出勤时间：安检员打卡时间，若未打卡需要提示未打卡
     */
    private SecurityCheckStats getSecurityCheckStats(Long userId, Long deptId) {
        SecurityCheckStats stats = new SecurityCheckStats();

        // 获取当前日期
        Date today = DateUtil.beginOfDay(new Date());

        // 获取该安检员今日的班组维护记录
        AttendanceTeamUserRecord teamUserRecord = attendanceTeamUserRecordService.selectAttendanceTeamUserRecordByUserId(userId, null, "1");

        if (teamUserRecord != null) {
            stats.setAttendanceTeamName(teamUserRecord.getAttendanceTeamName());
        } else {
            stats.setAttendanceTeamName("未分配班组");
        }

        // 获取安检员的打卡记录（上岗时间）
        List<AttendancePostRecord> checkInRecords = attendancePostRecordService.selectTodayRecordsByUserId(null, userId, null, "1");
        if (CollUtil.isNotEmpty(checkInRecords)) {
            // 获取最后一条上岗记录
            AttendancePostRecord lastRecord = checkInRecords.get(checkInRecords.size() - 1);
            // 获取通道信息（从通道名称中提取最后一个层级）
            if (StrUtil.isNotBlank(lastRecord.getChannelName())) {
                String channelName = extractChannelName(lastRecord.getChannelName());
                stats.setAttendanceChannel(channelName);
            } else {
                stats.setAttendanceChannel("未分配通道");
            }
        } else {
            stats.setAttendanceChannel("未分配通道");
        }

        // 获取安检员的打卡记录
        AttendanceCheckRecord attendanceCheckRecord = new AttendanceCheckRecord();
        attendanceCheckRecord.setUserId(userId);
        List<AttendanceCheckRecord> attendanceCheckRecords = attendanceCheckRecordService.selectAttendanceCheckRecordList(attendanceCheckRecord);
        if (CollUtil.isNotEmpty(attendanceCheckRecords)) {
            AttendanceCheckRecord lastRecord = attendanceCheckRecords.get(attendanceCheckRecords.size() - 1);
            if (StrUtil.equals(CheckInTypeEnum.CLOCK_IN.getValue(), lastRecord.getCheckInType())) {
                stats.setAttendanceTime(lastRecord.getCheckInTime());
                stats.setAttendanceTimeTips("已打卡");
            } else {
                stats.setAttendanceTime(null);
                stats.setAttendanceTimeTips("未打卡");
            }
        } else {
            stats.setAttendanceTime(null);
            stats.setAttendanceTimeTips("未打卡");
        }
        return stats;
    }

    /**
     * 班组长考勤统计数据
     * 出勤班组：查询该班组长在勤务板块将该安检员维护到自己班组，则显示自己所在组织架构的班组名称
     * 出勤通道：进入该界面的时候班组长将该安检员带上哪个通道（仅显示最后一个层级，例如A02通道）
     * 出勤时间：班组长打卡时间，若未打卡需要提示未打卡
     */
    private TeamLeaderStats getTeamLeaderStats(Long userId, Long deptId) {
        TeamLeaderStats stats = new TeamLeaderStats();
        Date today = DateUtil.beginOfDay(new Date());

        // 获取班组长所在班组信息
        AttendanceTeamUserRecord teamUserRecord = attendanceTeamUserRecordService.selectAttendanceTeamUserRecordByUserId(userId, null, "1");

        if (teamUserRecord != null) {
            stats.setAttendanceTeamName(teamUserRecord.getAttendanceTeamName());
        } else {
            stats.setAttendanceTeamName("未分配班组");
        }
        // 获取通道信息（从通道名称中提取最后一个层级）
        List<AttendancePostRecord> checkInRecords = attendancePostRecordService.selectTodayRecordsByUserId(null, userId, null, "1");
        if (CollUtil.isNotEmpty(checkInRecords)) {
            // 获取最后一条上岗记录
            AttendancePostRecord lastRecord = checkInRecords.get(checkInRecords.size() - 1);
            if (StrUtil.isNotBlank(lastRecord.getChannelName())) {
                String channelName = extractChannelName(lastRecord.getChannelName());
                stats.setAttendanceChannel(channelName);
            } else {
                stats.setAttendanceChannel("未分配通道");
            }
        } else {
            stats.setAttendanceChannel("未分配通道");
        }

        // 获取班组长的打卡记录
        AttendanceCheckRecord attendanceCheckRecord = new AttendanceCheckRecord();
        attendanceCheckRecord.setUserId(userId);
        List<AttendanceCheckRecord> attendanceCheckRecords = attendanceCheckRecordService.selectAttendanceCheckRecordList(attendanceCheckRecord);
        if (CollUtil.isNotEmpty(attendanceCheckRecords)) {
            AttendanceCheckRecord lastRecord = attendanceCheckRecords.get(attendanceCheckRecords.size() - 1);
            if (StrUtil.equals(CheckInTypeEnum.CLOCK_IN.getValue(), lastRecord.getCheckInType())) {
                stats.setAttendanceTime(lastRecord.getCheckInTime());
                stats.setAttendanceTimeTips("已打卡");
            } else {
                stats.setAttendanceTime(null);
                stats.setAttendanceTimeTips("未打卡");
            }
        } else {
            stats.setAttendanceTime(null);
            stats.setAttendanceTimeTips("未打卡");
        }

        return stats;
    }

    /**
     * 科长考勤统计数据
     * 在岗班组：进入界面时有多少班组长打了上岗卡/多少班组长维护人员区域
     * 在岗人员：进入该界面的时候多少人被带上通道/多少人的信息被班组长进行了维护
     * 出勤时间：科长打卡时间，若未打卡需要提示未打卡
     * 今日查获上报：今日安检员和班组长进行上报的数量，不需要完成审核
     */
    private SectionLeaderStats getSectionLeaderStats(Long userId, Long deptId) {
        SectionLeaderStats stats = new SectionLeaderStats();

        // 获取当天开始和结束时间
        Date[] dayRange = getDayStartAndEnd();
        Date startOfDay = dayRange[0];
        Date endOfDay = dayRange[1];

        AttendanceCheckRecord attendanceCheckRecord = new AttendanceCheckRecord();
        attendanceCheckRecord.setUserId(userId);
        List<AttendanceCheckRecord> attendanceCheckRecords = attendanceCheckRecordService.selectAttendanceCheckRecordList(attendanceCheckRecord);
        if (CollUtil.isNotEmpty(attendanceCheckRecords)) {
            AttendanceCheckRecord lastRecord = attendanceCheckRecords.get(attendanceCheckRecords.size() - 1);
            if (StrUtil.equals(CheckInTypeEnum.CLOCK_IN.getValue(), lastRecord.getCheckInType())) {
                stats.setAttendanceTime(lastRecord.getCheckInTime());
                stats.setAttendanceTimeTips("已打卡");
            } else {
                stats.setAttendanceTime(null);
                stats.setAttendanceTimeTips("未打卡");
            }
        } else {
            stats.setAttendanceTime(null);
            stats.setAttendanceTimeTips("未打卡");
        }
        // 获取在岗班组数量（打了上岗卡的班组长数量/维护了人员区域的班组长数量）
        String onDutyTeamCount = getOnDutyTeamCount(deptId, startOfDay, endOfDay);
        stats.setOnDutyTeamCount(onDutyTeamCount);

        // 获取在岗人员数量（被带上通道的人员数量或被班组长维护的人员数量）
        String onDutyPersonnelCount = getOnDutyPersonnelCount(deptId, startOfDay, endOfDay);
        stats.setOnDutyPersonnelCount(onDutyPersonnelCount);

        // 获取今日查获上报数量（安检员和班组长上报的数量，不需要完成审核）
        BigDecimal todaySeizureReportCount = getTodaySeizureReportCount(deptId, startOfDay, endOfDay, "3");
        stats.setTodaySeizureReportCount(todaySeizureReportCount);

        // 获取今日巡检问题数
        Integer todayCheckCorrectionCount = getTodayCheckCorrectionCount();
        stats.setTodayCheckCorrectionCount(todayCheckCorrectionCount);

        return stats;
    }

    /**
     * 站长/质检科考勤统计数据
     * 在岗班组：进入界面时有多少班组长打了上岗卡/多少班组长维护人员区域
     * 在岗人员：进入该界面的时候多少人被带上通道/多少人的信息被班组长进行了维护
     * 通道开放：开放通道/总通道
     * 今日查获上报：今日安检员和班组长进行上报的数量，不需要完成审核
     */
    private StationLeaderStats getStationLeaderStats(Long userId, Long deptId) {
        StationLeaderStats stats = new StationLeaderStats();

        // 获取当天开始和结束时间
        Date[] dayRange = getDayStartAndEnd();
        Date startOfDay = dayRange[0];
        Date endOfDay = dayRange[1];

        // 获取在岗班组数量（打了上岗卡的班组长数量/维护了人员区域的班组长数量）
        String onDutyTeamCount = getOnDutyTeamCount(deptId, startOfDay, endOfDay);
        stats.setOnDutyTeamCount(onDutyTeamCount);

        // 获取在岗人员数量（被带上通道的人员数量/被班组长维护的人员数量）
        String onDutyPersonnelCount = getOnDutyPersonnelCount(deptId, startOfDay, endOfDay);
        stats.setOnDutyPersonnelCount(onDutyPersonnelCount);

        // 获取通道开放情况：开放通道/总通道
        ChannelOpenStats channelStats = getChannelOpenStats(startOfDay, endOfDay);
        stats.setChannelOpenStats(channelStats);

        // 获取今日查获上报数量（安检员和班组长上报的数量，不需要完成审核）
        BigDecimal todaySeizureReportCount = getTodaySeizureReportCount(deptId, startOfDay, endOfDay, "1");
        stats.setTodaySeizureReportCount(todaySeizureReportCount);

        // 获取今日巡检问题数
        Integer todayCheckCorrectionCount = getTodayCheckCorrectionCount();
        stats.setTodayCheckCorrectionCount(todayCheckCorrectionCount);

        SimpleDutySchedule simpleDutySchedule = simpleDutyScheduleMapper.selectSimpleDutyScheduleByDate(new Date());
        if (Objects.nonNull(simpleDutySchedule)) {
            stats.setDutyDeptName(simpleDutySchedule.getDepartmentName());
        }

        return stats;
    }

    /**
     * 获取当天开始和结束时间
     */
    private Date[] getDayStartAndEnd() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startOfDay = calendar.getTime();

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endOfDay = calendar.getTime();

        return new Date[]{startOfDay, endOfDay};
    }

    /**
     * 上岗卡的班组长数量/维护了人员区域的班组长数量
     */
    private String getOnDutyTeamCount(Long deptId, Date startOfDay, Date endOfDay) {
        // 查询该部门下的班组长上岗记录（在指定时间范围内的记录）
        // 先获取该部门下的所有班组长
        List<SysUser> teamLeaderUsers = sysUserService.selectUserListByRoleKeyAndDeptId(Collections.singletonList(RoleTypeEnum.banzuzhang.getCode()), deptId);

        if (CollUtil.isEmpty(teamLeaderUsers)) {
            return "0/0";
        }

        int onDutyCount = 0;
        // 统计在指定时间段内有上岗记录的班组长数量
        for (SysUser teamLeader : teamLeaderUsers) {
            List<AttendancePostRecord> attendancePostRecords = attendancePostRecordService.selectTeamOnList(new Date(), teamLeader.getDeptId());
            if (CollUtil.isNotEmpty(attendancePostRecords)) {
                onDutyCount++;
            }
        }

        List<Long> teamList = teamLeaderUsers.stream().map(SysUser::getDeptId).distinct().collect(Collectors.toList());
        // 统计该部门下维护了人员的班组数量
        AttendanceTeamUserRecord queryRecord = new AttendanceTeamUserRecord();
        queryRecord.setCheckInType("1");
        List<AttendanceTeamUserRecord> teamUserRecords = attendanceTeamUserRecordService.selectAttendanceTeamUserRecordList(queryRecord, false);
        List<Long> distinctTeamIds = teamUserRecords.stream().filter(team -> teamList.contains(team.getAttendanceTeamId())).map(AttendanceTeamUserRecord::getAttendanceTeamId).distinct().collect(Collectors.toList());


        //打了上岗卡的班组长数量/维护了人员区域的班组长数量
        return onDutyCount + "/" + distinctTeamIds.size();
    }

    /**
     * 获取在岗人员数量(在岗人/被维护的人)
     */
    private String getOnDutyPersonnelCount(Long deptId, Date startOfDay, Date endOfDay) {
        // 查询该部门下的人员上岗记录（在指定时间范围内的记录）
        // 获取该部门下的所有安检员和班组长
        List<SysUser> personnelUsers = sysUserService.selectUserListByRoleKeyAndDeptId(
                Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()),
                deptId
        );

        if (CollUtil.isEmpty(personnelUsers)) {
            return "0/0";
        }

        List<Long> personnelList = personnelUsers.stream().filter(item -> Objects.nonNull(item.getUserId())).map(item -> item.getUserId()).collect(Collectors.toList());


        int onDutyCount = 0;
        // 统计在指定时间段内有上岗记录的人员数量
        for (Long personnel : personnelList) {
            List<AttendancePostRecord> records = attendancePostRecordService.selectTodayRecordsByUserId(null, personnel, null, "1");
            if (CollUtil.isNotEmpty(records)) {
                onDutyCount++;
            }
        }

        // 统计该部门下被维护到班组的人员数量
        AttendanceTeamUserRecord queryRecord = new AttendanceTeamUserRecord();
        queryRecord.setCheckInType("1");
        List<AttendanceTeamUserRecord> teamUserRecords = attendanceTeamUserRecordService.selectAttendanceTeamUserRecordList(queryRecord, false);
        List<Long> teamUserIds = teamUserRecords.stream().filter(team -> personnelList.contains(team.getUserId())).map(team -> team.getUserId()).collect(Collectors.toList());

        // 返回两个统计中较大的值（被带上通道的人员数量或被班组长维护的人员数量）
        return onDutyCount + "/" + teamUserIds.size();
    }

    /**
     * 获取今日查获上报数量
     */
    private BigDecimal getTodaySeizureReportCount(Long deptId, Date startOfDay, Date endOfDay, String type) {
        // 查询今日的查获上报记录数量（安检员和班组长上报的数量，不需要完成审核）
        BaseLargeScreenQueryParamDto record = new BaseLargeScreenQueryParamDto();
        switch (type) {
            case "1":
                record.setInspectStationId(deptId);
                break;
            case "2":
                record.setInspectBrigadeId(deptId);
                break;
            case "3":
                record.setInspectDepartmentId(deptId);
                break;
            default:
                break;
        }
        record.setStartDate(startOfDay);
        record.setEndDate(endOfDay);
        // 不限制process_status，即包含所有状态的记录（不需要完成审核）
        ItemLargeScreenTotalSomeDto result = itemLargeScreenService.getPcTotalSome(record);
        return ObjectUtil.isNotEmpty(result) ? result.getTotal() : BigDecimal.ZERO;
    }

    /**
     * 获取通道开放统计
     */
    private ChannelOpenStats getChannelOpenStats(Date startOfDay, Date endOfDay) {
        ChannelOpenStats stats = new ChannelOpenStats();

        // 查询所有通道
        List<PositionInfoVO> positionInfoVOS = basePositionService.selectChannelsUnderArea(new ArrayList<>());
        // 获取所有通道的开放状态
        AttendancePostRecord queryPostRecord = new AttendancePostRecord();
        queryPostRecord.setCheckOutTimeType(1);
        List<AttendancePostRecord> postRecords = attendancePostRecordService.selectAttendancePostRecordList(queryPostRecord);
        List<String> collect = postRecords.stream().filter(item -> StringUtils.isNotEmpty(item.getChannelName())).map(item -> extractChannelName(item.getChannelName())).distinct().collect(Collectors.toList());

        stats.setOpenChannels(collect.size());
        stats.setTotalChannels(positionInfoVOS.size());
        return stats;
    }

    /**
     * 从通道名称中提取最后一个层级（例如从"安检A区/A02通道"中提取"A02通道"）
     */
    private String extractChannelName(String fullChannelName) {
        if (StrUtil.isBlank(fullChannelName)) {
            return "";
        }

        // 按斜杠分割，取最后一部分
        String[] parts = fullChannelName.split("/");
        if (parts.length > 0) {
            return parts[parts.length - 1].trim();
        }

        return fullChannelName.trim();
    }

    /**
     * 获取今日巡检问题数
     */
    private Integer getTodayCheckCorrectionCount() {
        BaseLargeScreenQueryParamDto queryParam = new BaseLargeScreenQueryParamDto();
        return checkLargeScreenService.checkCorrectionCount(queryParam);
    }

    /**
     * 经理和大队行政考勤统计数据
     * 在岗班组：进入界面时有多少班组长打了上岗卡/多少班组长维护人员区域
     * 在岗人员：进入该界面的时候多少人被带上通道/多少人的信息被班组长进行了维护
     * 通道开放：开放通道/总通道
     * 今日查获上报：今日安检员和班组长进行上报的数量，不需要完成审核
     */
    private BrigadeLeaderStats getBrigadeLeaderStats(Long userId, Long deptId) {
        BrigadeLeaderStats stats = new BrigadeLeaderStats();

        // 获取当天开始和结束时间
        Date[] dayRange = getDayStartAndEnd();
        Date startOfDay = dayRange[0];
        Date endOfDay = dayRange[1];

        // 获取在岗班组数量（打了上岗卡的班组长数量/维护了人员区域的班组长数量）
        String onDutyTeamCount = getOnDutyTeamCount(deptId, startOfDay, endOfDay);
        stats.setOnDutyTeamCount(onDutyTeamCount);

        // 获取在岗人员数量（被带上通道的人员数量/被班组长维护的人员数量）
        String onDutyPersonnelCount = getOnDutyPersonnelCount(deptId, startOfDay, endOfDay);
        stats.setOnDutyPersonnelCount(onDutyPersonnelCount);

        // 获取通道开放情况：开放通道/总通道
        ChannelOpenStats channelStats = getChannelOpenStats(startOfDay, endOfDay);
        stats.setChannelOpenStats(channelStats);

        // 获取今日查获上报数量（安检员和班组长上报的数量，不需要完成审核）
        BigDecimal todaySeizureReportCount = getTodaySeizureReportCount(deptId, startOfDay, endOfDay, "2");
        stats.setTodaySeizureReportCount(todaySeizureReportCount);

        // 获取今日巡检问题数
        Integer todayCheckCorrectionCount = getTodayCheckCorrectionCount();
        stats.setTodayCheckCorrectionCount(todayCheckCorrectionCount);

        SimpleDutySchedule simpleDutySchedule = simpleDutyScheduleMapper.selectSimpleDutyScheduleByDate(new Date());
        if (Objects.nonNull(simpleDutySchedule)) {
            stats.setDutyDeptName(simpleDutySchedule.getDepartmentName());
        }

        return stats;
    }
}