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

import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.item.domain.ItemLargeScreenWorkDurationDto;
import com.sundot.airport.item.domain.SeizureEfficiencyDto;
import com.sundot.airport.item.domain.SeizureEfficiencyRankDto;
import com.sundot.airport.item.mapper.ItemLargeScreenMapper;
import com.sundot.airport.item.service.SeizureEfficiencyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 查获效率Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-25
 */
@Service
public class SeizureEfficiencyServiceImpl implements SeizureEfficiencyService {

    @Autowired
    private ItemLargeScreenMapper itemLargeScreenMapper;

    /**
     * 查询查获效率统计
     *
     * @param dto       查询参数
     * @param dimension 统计维度：1-人员、2-班级、3-科级、4-大队级
     * @return 查获效率统计结果
     */
    @Override
    public SeizureEfficiencyDto getSeizureEfficiency(BaseLargeScreenQueryParamDto dto, Integer dimension) {
        SeizureEfficiencyDto result = new SeizureEfficiencyDto();
        if (dto.getEndDate() != null) {
            //结束时间减一天
            dto.setEndDate(DateUtils.addDays(dto.getEndDate(), -1));
        }

        // 获取查获数量和在岗时长数据
        BigDecimal totalSeizureCount = itemLargeScreenMapper.getTotalSum(dto);
        BigDecimal totalWorkDuration = itemLargeScreenMapper.getWorkDuration(dto);

        result.setTotalSeizureCount(totalSeizureCount);
        result.setTotalWorkDuration(totalWorkDuration);

        // 计算总效率
        if (totalWorkDuration.compareTo(BigDecimal.ZERO) > 0) {
            result.setEfficiency(totalSeizureCount.divide(totalWorkDuration, 4, BigDecimal.ROUND_HALF_UP));
        } else {
            result.setEfficiency(BigDecimal.ZERO);
        }

        // 获取大队效率排行
        if (dimension == null || dimension == 4) {
            result.setBrigadeRankList(getBrigadeEfficiencyRank(dto));
        }

        // 获取科室效率排行
        if (dimension == null || dimension == 3) {
            result.setDepartmentRankList(getDepartmentEfficiencyRank(dto));
        }

        // 获取班组效率排行
        if (dimension == null || dimension == 2) {
            result.setTeamRankList(getTeamEfficiencyRank(dto));
        }

        // 获取个人效率排行
        if (dimension == null || dimension == 1) {
            result.setIndividualRankList(getIndividualEfficiencyRank(dto));
        }

        return result;
    }

    /**
     * 获取大队效率排行
     */
    private List<SeizureEfficiencyRankDto> getBrigadeEfficiencyRank(BaseLargeScreenQueryParamDto dto) {
        // 获取大队查获数量
        List<SeizureEfficiencyRankDto> brigadeSeizureList = itemLargeScreenMapper.rankByBrigade(dto)
                .stream()
                .map(item -> {
                    SeizureEfficiencyRankDto rankDto = new SeizureEfficiencyRankDto();
                    rankDto.setId(item.getId());
                    rankDto.setName(item.getName());
                    rankDto.setSeizureCount(item.getTotal());
                    return rankDto;
                })
                .collect(Collectors.toList());

        // 计算每个科室的效率
        for (SeizureEfficiencyRankDto item : brigadeSeizureList) {
            BaseLargeScreenQueryParamDto deptDto = new BaseLargeScreenQueryParamDto();
            deptDto.setStartDate(dto.getStartDate());
            deptDto.setEndDate(dto.getEndDate());
            deptDto.setInspectBrigadeId(item.getId());

            BigDecimal workDuration = itemLargeScreenMapper.getBrigadeWorkDuration(deptDto);
            item.setWorkDuration(workDuration);

            if (workDuration.compareTo(BigDecimal.ZERO) > 0) {
                item.setEfficiency(item.getSeizureCount().divide(workDuration, 4, BigDecimal.ROUND_HALF_UP));
            } else {
                item.setEfficiency(BigDecimal.ZERO);
            }
        }

        // 排序并设置排名
        brigadeSeizureList.sort((a, b) -> b.getEfficiency().compareTo(a.getEfficiency()));
        for (int i = 0; i < brigadeSeizureList.size(); i++) {
            brigadeSeizureList.get(i).setRank(i + 1);
        }

        return brigadeSeizureList;
    }

    /**
     * 获取科室效率排行
     */
    private List<SeizureEfficiencyRankDto> getDepartmentEfficiencyRank(BaseLargeScreenQueryParamDto dto) {
        // 获取科室查获数量
        List<SeizureEfficiencyRankDto> departmentSeizureList = itemLargeScreenMapper.rankByDepartment(dto)
                .stream()
                .map(item -> {
                    SeizureEfficiencyRankDto rankDto = new SeizureEfficiencyRankDto();
                    rankDto.setId(item.getId());
                    rankDto.setName(item.getName());
                    rankDto.setSeizureCount(item.getTotal());
                    return rankDto;
                })
                .collect(Collectors.toList());

        // 计算每个科室的效率
        for (SeizureEfficiencyRankDto item : departmentSeizureList) {
            BaseLargeScreenQueryParamDto deptDto = new BaseLargeScreenQueryParamDto();
            deptDto.setStartDate(dto.getStartDate());
            deptDto.setEndDate(dto.getEndDate());
            deptDto.setInspectDepartmentId(item.getId());

            BigDecimal workDuration = itemLargeScreenMapper.getDepartmentWorkDuration(deptDto);
            item.setWorkDuration(workDuration);

            if (workDuration.compareTo(BigDecimal.ZERO) > 0) {
                item.setEfficiency(item.getSeizureCount().divide(workDuration, 4, BigDecimal.ROUND_HALF_UP));
            } else {
                item.setEfficiency(BigDecimal.ZERO);
            }
        }

        // 排序并设置排名
        departmentSeizureList.sort((a, b) -> b.getEfficiency().compareTo(a.getEfficiency()));
        for (int i = 0; i < departmentSeizureList.size(); i++) {
            departmentSeizureList.get(i).setRank(i + 1);
        }

        return departmentSeizureList;
    }

    /**
     * 获取班组效率排行
     */
    private List<SeizureEfficiencyRankDto> getTeamEfficiencyRank(BaseLargeScreenQueryParamDto dto) {
        // 获取班组查获数量
        List<SeizureEfficiencyRankDto> teamSeizureList = itemLargeScreenMapper.rankByTeam(dto)
                .stream()
                .map(item -> {
                    SeizureEfficiencyRankDto rankDto = new SeizureEfficiencyRankDto();
                    rankDto.setId(item.getId());
                    rankDto.setName(item.getName());
                    rankDto.setSeizureCount(item.getTotal());
                    return rankDto;
                })
                .collect(Collectors.toList());

        // 如果没有数据，直接返回
        if (teamSeizureList.isEmpty()) {
            return teamSeizureList;
        }

        // 批量获取所有班组的工作时长
        List<Long> teamIds = teamSeizureList.stream()
                .map(SeizureEfficiencyRankDto::getId)
                .collect(Collectors.toList());

        List<ItemLargeScreenWorkDurationDto> workDurationList = itemLargeScreenMapper.getBatchTeamWorkDuration(
                DateUtils.parseDateToStr("yyyy-MM-dd", dto.getStartDate()),
                DateUtils.parseDateToStr("yyyy-MM-dd", dto.getEndDate()),
                teamIds);

        // 转换为Map方便查找
        Map<Long, BigDecimal> workDurationMap = workDurationList.stream()
                .collect(Collectors.toMap(ItemLargeScreenWorkDurationDto::getId, ItemLargeScreenWorkDurationDto::getWorkDuration));

        // 计算每个班组的效率
        for (SeizureEfficiencyRankDto item : teamSeizureList) {
            BigDecimal workDuration = workDurationMap.getOrDefault(item.getId(), BigDecimal.ZERO);
            item.setWorkDuration(workDuration);

            if (workDuration.compareTo(BigDecimal.ZERO) > 0) {
                item.setEfficiency(item.getSeizureCount().divide(workDuration, 4, BigDecimal.ROUND_HALF_UP));
            } else {
                item.setEfficiency(BigDecimal.ZERO);
            }
        }

        // 排序并设置排名
        teamSeizureList.sort((a, b) -> b.getEfficiency().compareTo(a.getEfficiency()));
        for (int i = 0; i < teamSeizureList.size(); i++) {
            teamSeizureList.get(i).setRank(i + 1);
        }

        return teamSeizureList;
    }

    /**
     * 获取个人效率排行
     */
    private List<SeizureEfficiencyRankDto> getIndividualEfficiencyRank(BaseLargeScreenQueryParamDto dto) {
        // 获取个人查获数量
        List<SeizureEfficiencyRankDto> individualSeizureList = itemLargeScreenMapper.rankByIndividual(dto)
                .stream()
                .map(item -> {
                    SeizureEfficiencyRankDto rankDto = new SeizureEfficiencyRankDto();
                    rankDto.setId(item.getId());
                    rankDto.setName(item.getName());
                    rankDto.setSeizureCount(item.getTotal());
                    return rankDto;
                })
                .collect(Collectors.toList());

        // 如果没有数据，直接返回
        if (individualSeizureList.isEmpty()) {
            return individualSeizureList;
        }

        // 批量获取所有人员的工作时长
        List<Long> userIds = individualSeizureList.stream()
                .map(SeizureEfficiencyRankDto::getId)
                .collect(Collectors.toList());

        List<ItemLargeScreenWorkDurationDto> workDurationList = itemLargeScreenMapper.getBatchIndividualWorkDuration(
                DateUtils.parseDateToStr("yyyy-MM-dd", dto.getStartDate()),
                DateUtils.parseDateToStr("yyyy-MM-dd", dto.getEndDate()),
                userIds);

        // 转换为Map方便查找
        Map<Long, BigDecimal> workDurationMap = workDurationList.stream()
                .collect(Collectors.toMap(ItemLargeScreenWorkDurationDto::getId, ItemLargeScreenWorkDurationDto::getWorkDuration));

        // 计算每个人的效率
        for (SeizureEfficiencyRankDto item : individualSeizureList) {
            BigDecimal workDuration = workDurationMap.getOrDefault(item.getId(), BigDecimal.ZERO);
            item.setWorkDuration(workDuration);

            if (workDuration.compareTo(BigDecimal.ZERO) > 0) {
                item.setEfficiency(item.getSeizureCount().divide(workDuration, 4, BigDecimal.ROUND_HALF_UP));
            } else {
                item.setEfficiency(BigDecimal.ZERO);
            }
        }

        // 排序并设置排名
        individualSeizureList.sort((a, b) -> b.getEfficiency().compareTo(a.getEfficiency()));
        for (int i = 0; i < individualSeizureList.size(); i++) {
            individualSeizureList.get(i).setRank(i + 1);
        }

        return individualSeizureList;
    }
}