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.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.AjaxResult;
import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.DataPermissionResult;
import com.sundot.airport.common.core.domain.SysHomePageDetailDto;
import com.sundot.airport.common.core.domain.SysHomePageDetailQueryParamDto;
import com.sundot.airport.common.core.domain.SysHomePageRankingDto;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.common.enums.DataPermissionType;
import com.sundot.airport.common.enums.DeptType;
import com.sundot.airport.common.enums.DeptTypeEnum;
import com.sundot.airport.common.enums.HomePageQueryEnum;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.enums.SourceTypeEnum;
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.mapper.SeizureReportMapper;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysLearningGrowthService;
import com.sundot.airport.system.service.ISysUserService;
import com.sundot.airport.web.core.utils.DataPermissionUtils;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 首页
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/homePage")
public class SysHomePageController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ICheckLargeScreenService checkLargeScreenService;

    @Autowired
    private ISysLearningGrowthService sysLearningGrowthService;

    @Autowired
    private SeizureReportMapper seizureReportMapper;

    @Autowired
    private IAttendancePostRecordService attendancePostRecordService;

    @Autowired
    private IAccuracyStatisticsService accuracyStatisticsService;

    /**
     * 首页-排名
     */
    @GetMapping("/homePageRanking")
    public AjaxResult homePageRanking(BaseLargeScreenQueryParamDto dto) {
        SysHomePageRankingDto result = new SysHomePageRankingDto();
        result.setCheckLargeScreenHomePageRankingDto(checkLargeScreenService.checkRanking(dto));
        result.setDailyTaskAccuracyRankingDto(accuracyStatisticsService.getAccuracyRanking(dto));
        return success(result);
    }

    /**
     * 首页-整体
     */
    @GetMapping("/homePageWhole")
    public AjaxResult homePageWhole(BaseLargeScreenQueryParamDto dto, @RequestHeader(value = "X-Request-Source", defaultValue = "mobile") String source) {
        List<SysHomePageDetailQueryParamDto> dtoList = new ArrayList<>();
        if (StrUtil.equals(SourceTypeEnum.mobile.getCode(), source)) {
            DataPermissionResult dataPermission = DataPermissionUtils.getDataPermission(getUserId(), getDeptId(), getLoginUser());
            if (DataPermissionType.SELF == dataPermission.getPermissionType()) {
                SysHomePageDetailQueryParamDto userDto = new SysHomePageDetailQueryParamDto();
                userDto.setId(getUserId());
                userDto.setName(getLoginUser().getUser().getNickName());
                userDto.setType(HomePageQueryEnum.USER.getCode());
                dtoList.add(userDto);
                List<SysDept> deptList = deptService.selectAllDept(getDeptId());
                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 (ObjectUtil.isNotNull(team)) {
                    SysHomePageDetailQueryParamDto teamDto = new SysHomePageDetailQueryParamDto();
                    teamDto.setId(team.getDeptId());
                    teamDto.setName(team.getDeptName());
                    teamDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(teamDto);
                }
                if (ObjectUtil.isNotNull(department)) {
                    SysHomePageDetailQueryParamDto departmentDto = new SysHomePageDetailQueryParamDto();
                    departmentDto.setId(department.getDeptId());
                    departmentDto.setName(department.getDeptName());
                    departmentDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(departmentDto);
                }
                if (ObjectUtil.isNotNull(brigade)) {
                    SysHomePageDetailQueryParamDto departmentDto = new SysHomePageDetailQueryParamDto();
                    departmentDto.setId(brigade.getDeptId());
                    departmentDto.setName(brigade.getDeptName());
                    departmentDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(departmentDto);
                }
                if (ObjectUtil.isNotNull(station)) {
                    SysHomePageDetailQueryParamDto stationDto = new SysHomePageDetailQueryParamDto();
                    stationDto.setId(station.getDeptId());
                    stationDto.setName(station.getDeptName());
                    stationDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(stationDto);
                }
            } else if (DataPermissionType.TEAM == dataPermission.getPermissionType() || DataPermissionType.DEPARTMENT == dataPermission.getPermissionType()) {
                List<SysDept> deptList = deptService.selectAllDept(getDeptId());
                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);

                // 支持dataSource参数：individual=个人数据，team=班组数据（默认）
                // 仅对班组长权限生效
                if (DataPermissionType.TEAM == dataPermission.getPermissionType() && "individual".equalsIgnoreCase(dto.getDataSource())) {
                    // 返回班组长个人数据（类似安检员视角）
                    SysHomePageDetailQueryParamDto userDto = new SysHomePageDetailQueryParamDto();
                    userDto.setId(getUserId());
                    userDto.setName(getLoginUser().getUser().getNickName());
                    userDto.setType(HomePageQueryEnum.USER.getCode());
                    dtoList.add(userDto);
                }

                // 添加班组、主管、大队、站点信息
                if (ObjectUtil.isNotNull(team)) {
                    SysHomePageDetailQueryParamDto teamDto = new SysHomePageDetailQueryParamDto();
                    teamDto.setId(team.getDeptId());
                    teamDto.setName(team.getDeptName());
                    teamDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(teamDto);
                }
                if (ObjectUtil.isNotNull(department)) {
                    SysHomePageDetailQueryParamDto departmentDto = new SysHomePageDetailQueryParamDto();
                    departmentDto.setId(department.getDeptId());
                    departmentDto.setName(department.getDeptName());
                    departmentDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(departmentDto);
                }
                if (ObjectUtil.isNotNull(brigade)) {
                    SysHomePageDetailQueryParamDto departmentDto = new SysHomePageDetailQueryParamDto();
                    departmentDto.setId(brigade.getDeptId());
                    departmentDto.setName(brigade.getDeptName());
                    departmentDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(departmentDto);
                }
                if (ObjectUtil.isNotNull(station)) {
                    SysHomePageDetailQueryParamDto stationDto = new SysHomePageDetailQueryParamDto();
                    stationDto.setId(station.getDeptId());
                    stationDto.setName(station.getDeptName());
                    stationDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(stationDto);
                }
            } else if (DataPermissionType.BRIGADE == dataPermission.getPermissionType()) {
                SysDept sysDept = deptService.selectDeptById(getDeptId());
                SysDept sysDeptStation = deptService.selectDeptById(sysDept.getParentId());
                SysHomePageDetailQueryParamDto stationDto = new SysHomePageDetailQueryParamDto();
                stationDto.setId(sysDeptStation.getDeptId());
                stationDto.setName(sysDeptStation.getDeptName());
                stationDto.setType(HomePageQueryEnum.DEPT.getCode());
                dtoList.add(stationDto);
                SysDept query = new SysDept();
                query.setParentId(sysDeptStation.getDeptId());
                List<SysDept> deptList = deptService.selectDeptInfoAll(query);
                deptList.forEach(item -> {
                    SysHomePageDetailQueryParamDto departmentDto = new SysHomePageDetailQueryParamDto();
                    departmentDto.setId(item.getDeptId());
                    departmentDto.setName(item.getDeptName());
                    departmentDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(departmentDto);
                });
            } else if (DataPermissionType.STATION == dataPermission.getPermissionType()) {
                SysDept sysDept = deptService.selectDeptById(getDeptId());
                SysHomePageDetailQueryParamDto stationDto = new SysHomePageDetailQueryParamDto();
                stationDto.setId(sysDept.getDeptId());
                stationDto.setName(sysDept.getDeptName());
                stationDto.setType(HomePageQueryEnum.DEPT.getCode());
                dtoList.add(stationDto);
                SysDept query = new SysDept();
                query.setParentId(sysDept.getDeptId());
                List<SysDept> deptList = deptService.selectDeptInfoAll(query);
                deptList.forEach(item -> {
                    SysHomePageDetailQueryParamDto departmentDto = new SysHomePageDetailQueryParamDto();
                    departmentDto.setId(item.getDeptId());
                    departmentDto.setName(item.getDeptName());
                    departmentDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(departmentDto);
                });
            } else {
                List<SysDept> deptListAll = deptService.selectDeptInfoAll(new SysDept());
                List<SysDept> SysDeptStation = deptListAll.stream().filter(item -> ObjectUtil.equal(DeptTypeEnum.STATION.getCode(), item.getDeptType())).collect(Collectors.toList());
                SysDeptStation.forEach(item -> {
                    SysDept sysDept = deptService.selectDeptById(item.getDeptId());
                    SysHomePageDetailQueryParamDto stationDto = new SysHomePageDetailQueryParamDto();
                    stationDto.setId(sysDept.getDeptId());
                    stationDto.setName(sysDept.getDeptName());
                    stationDto.setType(HomePageQueryEnum.DEPT.getCode());
                    dtoList.add(stationDto);
                    SysDept query = new SysDept();
                    query.setParentId(sysDept.getDeptId());
                    List<SysDept> deptList = deptService.selectDeptInfoAll(query);
                    deptList.forEach(department -> {
                        SysHomePageDetailQueryParamDto departmentDto = new SysHomePageDetailQueryParamDto();
                        departmentDto.setId(department.getDeptId());
                        departmentDto.setName(department.getDeptName());
                        departmentDto.setType(HomePageQueryEnum.DEPT.getCode());
                        dtoList.add(departmentDto);
                    });
                });
            }
        } else {
            List<SysDept> sysDeptList = deptService.selectAllDept(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("未查询到站级部门信息");
            }
            SysHomePageDetailQueryParamDto stationDto = new SysHomePageDetailQueryParamDto();
            stationDto.setId(sysDept.getDeptId());
            stationDto.setName(sysDept.getDeptName());
            stationDto.setType(HomePageQueryEnum.DEPT.getCode());
            dtoList.add(stationDto);
            SysDept query = new SysDept();
            query.setParentId(sysDept.getDeptId());
            List<SysDept> deptList = deptService.selectDeptInfoAll(query);
            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());
        });
        List<SysHomePageDetailDto> result = getSysHomePageDetailDtoList(dtoList);
        return success(result);
    }

    /**
     * 首页-明细（能力对比）
     * 支持班组长角色使用dataSource参数：
     * - 如果列表中包含班组数据，且dataSource=individual，则将班组数据替换为班组长个人数据
     */
    @PostMapping("/homePageDetail")
    public AjaxResult homePageDetail(@RequestBody List<SysHomePageDetailQueryParamDto> dtoList) {
        List<SysHomePageDetailDto> result = getSysHomePageDetailDtoList(dtoList);
        return success(result);
    }

    /**
     * 获取首页-明细
     */
    private List<SysHomePageDetailDto> getSysHomePageDetailDtoList(List<SysHomePageDetailQueryParamDto> dtoList) {
        List<SysHomePageDetailDto> result = new ArrayList<>();
        // 批量调用前统一初始化部门缓存，避免每次 getAnswersAccuracy 都重复查询数据库
        accuracyStatisticsService.initDeptCache();
        try {
            for (SysHomePageDetailQueryParamDto item : dtoList) {
                SysHomePageDetailDto resultItem = new SysHomePageDetailDto();
                resultItem.setId(item.getId());
                resultItem.setName(item.getName());
                resultItem.setType(item.getType());
                resultItem.setLearningGrowthScore(getLearningGrowthScore(item));
                resultItem.setLearningGrowthScoreGraph(resultItem.getLearningGrowthScore().divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP));
                resultItem.setCheckPassRate(getCheckPassRate(item));
                resultItem.setCheckPassRateGraph(resultItem.getCheckPassRate());
                resultItem.setSeizureCount(getSeizureCount(item));
                resultItem.setSeizureCountGraph(getSeizureCountGraph(item));
                resultItem.setWorkingHours(getWorkingHours(item));
                resultItem.setWorkingHoursGraph(getWorkingHoursGraph(item));
                // 抽问抽答正确率
                resultItem.setAnswersAccuracy(getAnswersAccuracy(item));
                resultItem.setAnswersAccuracyGraph(resultItem.getAnswersAccuracy());
                result.add(resultItem);
            }
        } finally {
            accuracyStatisticsService.clearDeptCache();
        }
        return result;
    }

    /**
     * 获取抽问抽答正确率
     */
    private BigDecimal getAnswersAccuracy(SysHomePageDetailQueryParamDto item) {
        Long userId = null;
        Long deptId = null;
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            userId = item.getId();
        } else {
            deptId = item.getId();
        }
        return accuracyStatisticsService.getAccuracyRate(userId, deptId, item.getStartDate(), item.getEndDate());
    }

    /**
     * 获取巡检合格率
     */
    private BigDecimal getCheckPassRate(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.checkPassRate(dto);
    }

    /**
     * 获取培训答题平均分
     */
    private BigDecimal getLearningGrowthScore(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.learningGrowthAverage(dto);
    }

    /**
     * 部门值计算器函数式接口
     */
    @FunctionalInterface
    private interface DeptValueCalculator {
        BigDecimal calculate(String deptType, SysHomePageDetailQueryParamDto item);
    }

    /**
     * 获取查获数量
     */
    private BigDecimal getSeizureCount(SysHomePageDetailQueryParamDto item) {
        if (item.getEndDate() != null) {
            item.setEndDate(DateUtils.addSeconds(DateUtils.truncate(item.getEndDate(), Calendar.DAY_OF_MONTH), 86399));
        }
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            return seizureReportMapper.selectSelfSeizureCount(item.getId(), item.getStartDate(), item.getEndDate());
        } else {
            return calculateDeptBasedValue(item, this::calculateAverageSeizureCountForDeptType);
        }
    }

    /**
     * 获取查获数量图形
     */
    private BigDecimal getSeizureCountGraph(SysHomePageDetailQueryParamDto item) {
        if (item.getEndDate() != null) {
            item.setEndDate(DateUtils.addSeconds(DateUtils.truncate(item.getEndDate(), Calendar.DAY_OF_MONTH), 86399));
        }
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            BigDecimal totalSeizure = seizureReportMapper.selectSelfSeizureCount(item.getId(), item.getStartDate(), item.getEndDate());
            Long stationId = getStationIdByUserId(item.getId());
            BigDecimal maxSeizureCount = seizureReportMapper.selectMaxSeizureCountInStation(stationId, item.getStartDate(), item.getEndDate());
            return (maxSeizureCount != null && maxSeizureCount.compareTo(BigDecimal.ZERO) > 0) ?
                    totalSeizure.divide(maxSeizureCount, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
        } else {
            return calculateDeptBasedValue(item, this::calculateSeizureCountGraphForDeptType);
        }
    }

    /**
     * 获取部门相关数值的通用方法
     */
    private BigDecimal calculateDeptBasedValue(SysHomePageDetailQueryParamDto item,
                                               DeptValueCalculator calculator) {
        SysDept sysDept = deptService.selectDeptById(item.getId());
        if (sysDept == null) {
            return BigDecimal.ZERO;
        }
        return calculator.calculate(sysDept.getDeptType(), item);
    }

    /**
     * 平均查获数量计算
     */
    private BigDecimal calculateAverageSeizureCountForDeptType(String deptType, SysHomePageDetailQueryParamDto item) {
        switch (deptType) {
            case "TEAMS":
                BigDecimal totalTeamSeizure = seizureReportMapper.selectTeamAverage(item.getId(), item.getStartDate(), item.getEndDate());
                Integer teamUserCount = seizureReportMapper.selectUserCountByTeamId(item.getId());
                return (teamUserCount != null && teamUserCount > 0) ?
                        totalTeamSeizure.divide(new BigDecimal(teamUserCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            case "MANAGER":
                BigDecimal totalDepartmentSeizure = seizureReportMapper.selectDepartmentAverage(item.getId(), item.getStartDate(), item.getEndDate());
                Integer deptUserCount = seizureReportMapper.selectUserCountByDepartmentId(item.getId());
                return (deptUserCount != null && deptUserCount > 0) ?
                        totalDepartmentSeizure.divide(new BigDecimal(deptUserCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            case "BRIGADE":
                BigDecimal totalBrigadeSeizure = seizureReportMapper.selectBrigadeAverage(item.getId(), item.getStartDate(), item.getEndDate());
                Integer brigadeUserCount = seizureReportMapper.selectUserCountByBrigadeId(item.getId());
                return (brigadeUserCount != null && brigadeUserCount > 0) ?
                        totalBrigadeSeizure.divide(new BigDecimal(brigadeUserCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            case "STATION":
                BigDecimal totalStationSeizure = seizureReportMapper.selectStationAverage(item.getId(), item.getStartDate(), item.getEndDate());
                Integer stationUserCount = seizureReportMapper.selectUserCountByStationId(item.getId());
                return (stationUserCount != null && stationUserCount > 0) ?
                        totalStationSeizure.divide(new BigDecimal(stationUserCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            default:
                return BigDecimal.ZERO;
        }
    }

    /**
     * 查获数量图表计算
     */
    private BigDecimal calculateSeizureCountGraphForDeptType(String deptType, SysHomePageDetailQueryParamDto item) {
        switch (deptType) {
            case "TEAMS":
                Long sectionDeptId = seizureReportMapper.selectSectionDeptIdByTeamId(item.getId());
                Long brigadeDeptId = seizureReportMapper.selectBrigadeDeptIdByDepartmentId(sectionDeptId);
                Long stationId = seizureReportMapper.selectStationDeptIdByDeptId(brigadeDeptId);
                BigDecimal totalTeamSeizure = seizureReportMapper.selectTeamAverage(item.getId(), item.getStartDate(), item.getEndDate());
                //查询班级人数
                Integer teamUserCount = seizureReportMapper.selectUserCountByTeamId(item.getId());
                BigDecimal maxSeizureCount = seizureReportMapper.selectMaxSeizureCountInStation(stationId, item.getStartDate(), item.getEndDate());
                return (maxSeizureCount != null && maxSeizureCount.compareTo(BigDecimal.ZERO) > 0 && teamUserCount != null && teamUserCount > 0) ?
                        totalTeamSeizure.divide(new BigDecimal(teamUserCount), 2, RoundingMode.HALF_UP).divide(maxSeizureCount, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            case "MANAGER":
                Long brigadeId = seizureReportMapper.selectBrigadeDeptIdByDepartmentId(item.getId());
                Long deptStationId = seizureReportMapper.selectStationDeptIdByDeptId(brigadeId);
                BigDecimal totalDepartmentSeizure = seizureReportMapper.selectDepartmentAverage(item.getId(), item.getStartDate(), item.getEndDate());
                BigDecimal maxSeizureCountForDept = seizureReportMapper.selectMaxSeizureCountInStation(deptStationId, item.getStartDate(), item.getEndDate());
                //查询科室人数
                Integer deptUserCount = seizureReportMapper.selectUserCountByDepartmentId(item.getId());
                return (maxSeizureCountForDept != null && maxSeizureCountForDept.compareTo(BigDecimal.ZERO) > 0 && deptUserCount != null && deptUserCount > 0) ?
                        totalDepartmentSeizure.divide(new BigDecimal(deptUserCount), 2, RoundingMode.HALF_UP).divide(maxSeizureCountForDept, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            case "BRIGADE":
                Long stationDeptId = seizureReportMapper.selectStationDeptIdByDeptId(item.getId());
                BigDecimal totalBrigadeSeizure = seizureReportMapper.selectBrigadeAverage(item.getId(), item.getStartDate(), item.getEndDate());
                BigDecimal maxSeizureCountFor = seizureReportMapper.selectMaxSeizureCountInStation(stationDeptId, item.getStartDate(), item.getEndDate());
                //查询大队人数
                Integer deptBrigadeUserCount = seizureReportMapper.selectUserCountByBrigadeId(item.getId());
                return (maxSeizureCountFor != null && maxSeizureCountFor.compareTo(BigDecimal.ZERO) > 0 && deptBrigadeUserCount != null && deptBrigadeUserCount > 0) ?
                        totalBrigadeSeizure.divide(new BigDecimal(deptBrigadeUserCount), 2, RoundingMode.HALF_UP).divide(maxSeizureCountFor, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            case "STATION":
                BigDecimal totalStationSeizure = seizureReportMapper.selectStationAverage(item.getId(), item.getStartDate(), item.getEndDate());
                BigDecimal maxSeizureCountForStation = seizureReportMapper.selectMaxSeizureCountInStation(item.getId(), item.getStartDate(), item.getEndDate());
                //查询站人数
                Integer stationUserCount = seizureReportMapper.selectUserCountByStationId(item.getId());
                return (maxSeizureCountForStation != null && maxSeizureCountForStation.compareTo(BigDecimal.ZERO) > 0 && stationUserCount != null && stationUserCount > 0) ?
                        totalStationSeizure.divide(new BigDecimal(stationUserCount), 2, RoundingMode.HALF_UP).divide(maxSeizureCountForStation, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            default:
                return BigDecimal.ZERO;
        }
    }

    /**
     * 根据用户ID获取对应站点ID
     */
    private Long getStationIdByUserId(Long userId) {
        SysUser sysUser = sysUserService.selectUserById(userId);
        List<SysDept> deptList = deptService.selectAllDept(sysUser.getDeptId());
        Collections.reverse(deptList);
        SysDept station = deptList.stream().filter(x -> StrUtil.equals(DeptType.STATION.getCode(), x.getDeptType())).findFirst().orElse(null);
        return station != null ? station.getDeptId() : 0;
    }

    private BigDecimal getWorkingHours(SysHomePageDetailQueryParamDto item) {
        if (item.getEndDate() != null) {
            item.setEndDate(DateUtils.addSeconds(DateUtils.truncate(item.getEndDate(), Calendar.DAY_OF_MONTH), 86399));
        }
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            BigDecimal bigDecimal = attendancePostRecordService.selectPersonalTotalWorkDurationInTimeRange(item.getId(), item.getStartDate(), item.getEndDate());
            return bigDecimal != null ? bigDecimal.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
        } else {
            return calculateDeptBasedValue(item, this::calculateAverageWorkDurationForDeptType);
        }
    }

    private BigDecimal getWorkingHoursGraph(SysHomePageDetailQueryParamDto item) {
        if (item.getEndDate() != null) {
            item.setEndDate(DateUtils.addSeconds(DateUtils.truncate(item.getEndDate(), Calendar.DAY_OF_MONTH), 86399));
        }
        if (StrUtil.equals(HomePageQueryEnum.USER.getCode(), item.getType())) {
            BigDecimal totalWorkDuration = attendancePostRecordService.selectPersonalTotalWorkDurationInTimeRange(item.getId(), item.getStartDate(), item.getEndDate());
            Long stationId = getStationIdByUserId(item.getId());
            BigDecimal maxUserWorkDuration = attendancePostRecordService.selectTopUserWorkDurationInTimeRange(stationId, item.getStartDate(), item.getEndDate());
            return (maxUserWorkDuration != null && maxUserWorkDuration.compareTo(BigDecimal.ZERO) > 0) ?
                    totalWorkDuration.divide(maxUserWorkDuration, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
        } else {
            return calculateDeptBasedValue(item, this::calculateWorkDurationForDeptType);
        }
    }

    /**
     * 平均工作时长计算
     */
    private BigDecimal calculateAverageWorkDurationForDeptType(String deptType, SysHomePageDetailQueryParamDto item) {
        List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()), item.getId());
        if (CollUtil.isEmpty(sysUserList)) {
            return BigDecimal.ZERO;
        }
        List<Long> list = sysUserList.stream().map(SysUser::getUserId).distinct().collect(Collectors.toList());
        int size = list.size();
        BigDecimal totalWorkDuration = attendancePostRecordService.selectTotalWorkDurationInTimeRange(list, item.getStartDate(), item.getEndDate());
        return totalWorkDuration.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP).divide(new BigDecimal(size), 2, RoundingMode.HALF_UP);
    }

    /**
     * 工作时长图表计算
     */
    private BigDecimal calculateWorkDurationForDeptType(String deptType, SysHomePageDetailQueryParamDto item) {
        List<SysDept> deptList = deptService.selectAllDept(item.getId());
        if (CollUtil.isEmpty(deptList)) {
            return BigDecimal.ZERO;
        }
        Collections.reverse(deptList);
        SysDept station = deptList.stream().filter(x -> StrUtil.equals(DeptType.STATION.getCode(), x.getDeptType())).findFirst().orElse(null);
        BigDecimal maxUserWorkDuration = attendancePostRecordService.selectTopUserWorkDurationInTimeRange(station.getDeptId(), item.getStartDate(), item.getEndDate());
        if (maxUserWorkDuration == null || maxUserWorkDuration.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        List<SysUser> sysUserList = sysUserService.selectUserListByRoleKeyAndDeptId(Arrays.asList(RoleTypeEnum.banzuzhang.getCode(), RoleTypeEnum.SecurityCheck.getCode()), item.getId());
        if (CollUtil.isEmpty(sysUserList)) {
            return BigDecimal.ZERO;
        }
        List<Long> list = sysUserList.stream().map(SysUser::getUserId).distinct().collect(Collectors.toList());
        int size = list.size();
        BigDecimal totalWorkDuration = attendancePostRecordService.selectTotalWorkDurationInTimeRange(list, item.getStartDate(), item.getEndDate());
        return totalWorkDuration.divide(new BigDecimal(size), 2, RoundingMode.HALF_UP).divide(maxUserWorkDuration, 4, RoundingMode.HALF_UP);
    }

}
