package com.storlead.sales.service.impl.target;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.common.util.StringUtil;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.pojo.entity.customer.BusinessEntity;
import com.storlead.sales.pojo.entity.customer.CustomerEntity;
import com.storlead.sales.pojo.entity.customer.CustomerFollowUpEntity;
import com.storlead.sales.pojo.entity.customer.OrderFormEntity;
import com.storlead.sales.pojo.dto.target.TargetRankingDTO;
import com.storlead.sales.pojo.entity.target.TargetPlanEntity;
import com.storlead.sales.pojo.entity.target.TargetQuotaEntity;
import com.storlead.sales.service.customer.BusinessService;
import com.storlead.sales.service.customer.CustomerFollowUpService;
import com.storlead.sales.service.customer.CustomerService;
import com.storlead.sales.service.customer.OrderFormService;
import com.storlead.sales.mapper.target.TargetQuotaMapper;
import com.storlead.sales.service.target.TargetPlanService;
import com.storlead.sales.service.target.TargetQuotaService;
import com.storlead.sales.service.target.TargetRinkService;
import com.storlead.system.enums.OrganizationalTypeEnum;
import com.storlead.system.service.IUserRoleService;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.SubCompanyEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.ISubCompanyService;
import com.storlead.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 目标进度 服务实现类
 * </p>
 *
 * @author LPK
 * @since 2024-12-24
 */

@Service
public class TargetRinkServiceImpl extends MyBaseServiceImpl<TargetQuotaMapper, TargetQuotaEntity> implements TargetRinkService {

    private static final Logger logger = LoggerFactory.getLogger(TargetQuotaServiceImpl.class);

    private static final String[] TIME_KEYS = {"time", "company", "dept", "user", "Target", "Total", "Progress"};

    private static final int QUARTER_CYCLE = 4;

    private static final int MONTH_CYCLE = 12;

    @Resource
    private IUserService userService;
    @Resource
    private ISubCompanyService subCompanyService;
    @Resource
    private IDepartService departService;
    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private OrderFormService orderFormService;

    @Resource
    private CustomerService customerService;

    @Resource
    private BusinessService businessService;

    @Resource
    private CustomerFollowUpService customerFollowUpService;

    @Resource
    private TargetPlanService targetPlanService;

    @Resource
    private TargetQuotaService targetQuotaService;



    @Override
    public Map<String, Object> getTotalAmount(TargetRankingDTO targetRankingDTO) {
        return processTargetDatas(targetRankingDTO, "OrdertotalAmount");
    }

    @Override
    public Map<String, Object> getTotalOrders(TargetRankingDTO targetRankingDTO) {
        return processTargetDatas(targetRankingDTO, "OrderCount");
    }

    @Override
    public Map<String, Object> getNewCustomers(TargetRankingDTO targetRankingDTO) {
        return processTargetDatas(targetRankingDTO, "CustomerCount");
    }

    @Override
    public Map<String, Object> getNewBusinesses(TargetRankingDTO targetRankingDTO) {
        return processTargetDatas(targetRankingDTO, "BusinessCount");
    }

    @Override
    public Map<String, Object> getNewClues(TargetRankingDTO targetRankingDTO) {
        return processTargetDatas(targetRankingDTO, "NewClueCount");
    }

    @Override
    public Map<String, Object> getFollowUpCounts(TargetRankingDTO targetRankingDTO) {
        return processTargetDatas(targetRankingDTO, "FollowUpCount");
    }


    @Override
    public Map<String, Object> getTotalProgress(TargetRankingDTO targetRankingDTO) {
        // 新增：获取 quarter 参数
        Integer quarter = targetRankingDTO.getQuarter();

        // 存储每个组织ID的总达成率数据
        Map<String, Map<String, Object>> organizationProgressMap = new HashMap<>();

        // 定义需要处理的指标及其对应的type值
        Map<String, Integer> progressMetrics = new HashMap<String, Integer>() {{
            put("OrdertotalAmount", 41);
            put("OrderCount", 40);
            put("CustomerCount", 10);
            put("BusinessCount", 30);
            put("NewClueCount", 11);
            put("FollowUpCount", 12);
        }};

        // 遍历每个指标并获取其进度数据
        for (Map.Entry<String, Integer> metric : progressMetrics.entrySet()) {
            targetRankingDTO.setType(metric.getValue());
            Map<String, Object> metricData = processTargetDatas(targetRankingDTO, metric.getKey());

            if (metricData != null && metricData.containsKey("data")) {
                List<List<Map<String, Object>>> dataList = (List<List<Map<String, Object>>>) metricData.get("data");

                if (!dataList.isEmpty()) {
                    for (List<Map<String, Object>> orgData : dataList) {
                        if (!orgData.isEmpty()) {
                            String organizationalId = getOrganizationalId(orgData.get(0));

                            // 获取或创建组织的进度数据
                            Map<String, Object> orgProgress = organizationProgressMap.computeIfAbsent(
                                    organizationalId, k -> new HashMap<String, Object>() {{
                                        put("timeProgressMap", new HashMap<String, List<Double>>());
                                        put("company", orgData.get(0).get("company"));
                                        put("dept", orgData.get(0).get("dept"));
                                        put("user", orgData.get(0).get("user"));
                                    }});

                            // 存储每个时间点的进度数据
                            Map<String, List<Double>> timeProgressMap = (Map<String, List<Double>>) orgProgress.get("timeProgressMap");
                            for (Map<String, Object> timeData : orgData) {
                                String time = (String) timeData.get("time");
                                // 修改这里的类型转换逻辑
                                Object progressObj = timeData.get("Progress");
                                double progress;
                                if (progressObj instanceof String) {
                                    String progressStr = (String) progressObj;
                                    if (progressStr.endsWith("%")) {
                                        progressStr = progressStr.substring(0, progressStr.length() - 1);
                                    }
                                    progress = Double.parseDouble(progressStr);
                                } else if (progressObj instanceof Number) {
                                    progress = ((Number) progressObj).doubleValue();
                                } else {
                                    progress = 0.0;
                                }
                                timeProgressMap.computeIfAbsent(time, k -> new ArrayList<>()).add(progress);
                            }
                        }
                    }
                }
            }
        }

        // 转换数据格式
        Map<String, Object> result = new HashMap<>();
        List<List<Map<String, Object>>> finalDataList = new ArrayList<>();

        for (Map.Entry<String, Map<String, Object>> entry : organizationProgressMap.entrySet()) {
            List<Map<String, Object>> orgDataList = new ArrayList<>();
            Map<String, Object> orgProgress = entry.getValue();
            Map<String, List<Double>> timeProgressMap = (Map<String, List<Double>>) orgProgress.get("timeProgressMap");

            // 为每个时间点创建数据
            for (Map.Entry<String, List<Double>> timeEntry : timeProgressMap.entrySet()) {
                Map<String, Object> timeData = new HashMap<>();
                List<Double> progressList = timeEntry.getValue();

                // 计算平均进度
                double avgProgress = progressList.stream()
                        .mapToDouble(Double::doubleValue)
                        .average()
                        .orElse(0.0);

                //根据quarter参数转换时间格式
                String originalTime = timeEntry.getKey();
                String formattedTime;

                if (quarter != null) {
                    // 季度格式：2025-1 → 2025年1季度
                    String[] parts = originalTime.split("-");
                    formattedTime = parts[0] + "年" + parts[1] + "季度";
                } else {
                    // 月份格式：2025-1 → 2025年1月
                    formattedTime = originalTime.replace("-", "年") + "月";
                }

                timeData.put("time", formattedTime);
                timeData.put("company", orgProgress.get("company"));
                timeData.put("dept", orgProgress.get("dept"));
                timeData.put("user", orgProgress.get("user"));
                timeData.put("Progress", String.format("%.2f", avgProgress));

                orgDataList.add(timeData);
            }

            // 修改排序逻辑适配新格式
            orgDataList.sort((a, b) -> {
                String timeA = (String) a.get("time");
                String timeB = (String) b.get("time");

                // 统一提取年份和数字部分
                Pattern pattern = Pattern.compile("(\\d+)年(\\d+)");
                Matcher matcherA = pattern.matcher(timeA);
                Matcher matcherB = pattern.matcher(timeB);

                if (matcherA.find() && matcherB.find()) {
                    int yearA = Integer.parseInt(matcherA.group(1));
                    int numA = Integer.parseInt(matcherA.group(2));
                    int yearB = Integer.parseInt(matcherB.group(1));
                    int numB = Integer.parseInt(matcherB.group(2));

                    int yearCompare = Integer.compare(yearA, yearB);
                    if (yearCompare != 0) return yearCompare;

                    return Integer.compare(numA, numB);
                }
                return 0;
            });

            finalDataList.add(orgDataList);
        }

        result.put("data", finalDataList);
        return result;
    }

    @Override
    public Map<String, Object> getUserTotalProgress(TargetRankingDTO targetRankingDTO) {
        Map<String, Object> result = new HashMap<>();

        // 1. 设置基础参数
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        targetRankingDTO.setOrganizationalType(4);
        targetRankingDTO.setYear(LocalDateTime.now().getYear());
        targetRankingDTO.setTotalOrValue(1);
        targetRankingDTO.setOrganizationIds(Collections.singletonList(loginUser.getId()));

        // 2. 验证用户ID
        String organizationIdsStr = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        if (organizationIdsStr == null || organizationIdsStr.isEmpty()) {
            result.put("progress", "0.00");
            return result;
        }

        // 3. 定义指标类型映射
        Map<String, Integer> progressMetrics = new HashMap<String, Integer>() {{
            put("OrdertotalAmount", 41);
            put("OrderCount", 40);
            put("CustomerCount", 10);
            put("BusinessCount", 30);
            put("NewClueCount", 11);
            put("FollowUpCount", 12);
        }};

        // 4. 获取当前月份
        int currentMonth = LocalDateTime.now().getMonthValue();
        String currentTime = targetRankingDTO.getYear() + "-" + currentMonth;

        // 5. 存储有效的达成率
        List<Double> validProgressRates = new ArrayList<>();

        // 6. 遍历每个指标获取达成率
        for (Map.Entry<String, Integer> metric : progressMetrics.entrySet()) {
            try {
                // 设置指标类型
                targetRankingDTO.setType(metric.getValue());

                // 获取目标方案ID
                List<Long> idList = targetPlanService.getTargetPlanId(targetRankingDTO);
                if (idList == null || idList.isEmpty()) {
                    continue;
                }

                // 获取指标数据
                Map<String, Object> metricData = processTargetDatas(targetRankingDTO, metric.getKey());
                if (metricData == null || !metricData.containsKey("data")) {
                    continue;
                }

                // 提取当月数据
                List<List<Map<String, Object>>> dataList = (List<List<Map<String, Object>>>) metricData.get("data");
                if (!dataList.isEmpty() && !dataList.get(0).isEmpty()) {
                    Optional<Map<String, Object>> currentMonthData = dataList.get(0).stream()
                            .filter(data -> currentTime.equals(data.get("time")))
                            .findFirst();

                    if (currentMonthData.isPresent()) {
                        Map<String, Object> data = currentMonthData.get();
                        Object progressObj = data.get("Progress");

                        // 处理进度值
                        if (progressObj != null) {
                            double progress;
                            if (progressObj instanceof Double) {
                                progress = (Double) progressObj;
                            } else if (progressObj instanceof String) {
                                String progressStr = ((String) progressObj).replace("%", "");
                                progress = Double.parseDouble(progressStr);
                            } else {
                                continue;
                            }

                            if (progress > 0) {
                                validProgressRates.add(progress);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("获取{}指标进度失败: {}", metric.getKey(), e.getMessage());
            }
        }

        // 7. 计算平均达成率
        double finalProgress = 0.0;
        if (!validProgressRates.isEmpty()) {
            finalProgress = validProgressRates.stream()
                    .mapToDouble(Double::doubleValue)
                    .average()
                    .orElse(0.0);
        }

        // 8. 返回结果
        result.put("progress", String.format("%.2f", finalProgress));
        return result;
    }

    @Override
    public Map<String, Object> getCurrentMonthProgress(TargetRankingDTO targetRankingDTO) {
        Map<String, Object> result = new HashMap<>();
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        targetRankingDTO.setType(41);
        targetRankingDTO.setOrganizationalType(4);
        targetRankingDTO.setYear(LocalDateTime.now().getYear());
        targetRankingDTO.setTotalOrValue(1);
        targetRankingDTO.setOrganizationIds(Collections.singletonList(loginUser.getId()));

        // 验证用户ID
        String organizationIdsStr = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        if (organizationIdsStr == null || organizationIdsStr.isEmpty()) {
            result.put("target", "0");
            result.put("total", "0");
            result.put("progress", "0.00");
            return result;
        }

        // 获取目标方案ID列表
        List<Long> idList;
        try {
            idList = targetPlanService.getTargetPlanId(targetRankingDTO);
        } catch (Exception e) {
            logger.error("获取目标方案失败: {}", e.getMessage());
            result.put("target", "0");
            result.put("total", "0");
            result.put("progress", "0.00");
            return result;
        }

        // 如果无目标方案，返回空结果
        if (idList == null || idList.isEmpty()) {
            logger.error("未找到目标方案");
            result.put("target", "0");
            result.put("total", "0");
            result.put("progress", "0.00");
            return result;
        }

        // 获取当前月份
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        String currentTime = currentYear + "-" + currentMonth;

        // 根据指标类型调用对应的方法
        String methodName = "";
        switch (targetRankingDTO.getType()) {
            case 41:
                methodName = "OrdertotalAmount";
                break;
            case 40:
                methodName = "OrderCount";
                break;
            case 10:
                methodName = "CustomerCount";
                break;
            case 30:
                methodName = "BusinessCount";
                break;
            case 11:
                methodName = "NewClueCount";
                break;
            case 12:
                methodName = "FollowUpCount";
                break;
            default:
                result.put("target", "0");
                result.put("total", "0");
                result.put("progress", "0.00");
                return result;
        }

        // 获取指标数据
        Map<String, Object> metricData = processTargetDatas(targetRankingDTO, methodName);

        if (metricData != null && metricData.containsKey("data")) {
            List<List<Map<String, Object>>> dataList = (List<List<Map<String, Object>>>) metricData.get("data");

            if (!dataList.isEmpty() && !dataList.get(0).isEmpty()) {
                // 在第一个组织的数据中查找当月数据
                Optional<Map<String, Object>> currentMonthData = dataList.get(0).stream()
                        .filter(data -> currentTime.equals(data.get("time")))
                        .findFirst();

                if (currentMonthData.isPresent()) {
                    Map<String, Object> data = currentMonthData.get();
                    // 修改这里的类型转换逻辑
                    Object progressObj = data.get("Progress");
                    String progress;
                    if (progressObj instanceof Double) {
                        progress = String.format("%.2f", (Double) progressObj);
                    } else if (progressObj instanceof String) {
                        progress = ((String) progressObj).replace("%", "");
                    } else {
                        progress = "0.00";
                    }

                    result.put("target", data.get("Target"));
                    result.put("total", data.get("Total"));
                    result.put("progress", progress);
                    return result;
                }
            }
        }

        // 如果没有找到当月数据，返回默认值
        result.put("target", "0");
        result.put("total", "0");
        result.put("progress", "0.00");
        return result;
    }

    //获取组织ID
    private String getOrganizationalId(Map<String, Object> data) {
        // 根据组织类型返回相应的ID
        if (data.get("user") != null) {
            return Objects.toString(data.get("user"));
        } else if (data.get("dept") != null) {
            return Objects.toString(data.get("dept"));
        } else {
            return Objects.toString(data.get("company"));
        }
    }


    private Map<String, Object> processTargetDatas(TargetRankingDTO targetRankingDTO, String methodName) {

        // 获取目标方案
        LambdaQueryWrapper<TargetPlanEntity> targetWrapper = new LambdaQueryWrapper<>();
        targetWrapper.eq(TargetPlanEntity::getType, targetRankingDTO.getType());
        targetWrapper.eq(TargetPlanEntity::getYear, targetRankingDTO.getYear());
        targetWrapper.eq(TargetPlanEntity::getIsDelete, 0);
        List<Long> idList;
        try {
            idList = targetPlanService.getTargetPlanId(targetRankingDTO);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            logger.error("获取目标方案失败: {}", e.getMessage());
            List<Map<String, Object>> list = new ArrayList<>();
            // 初始化AllTarget和AllTotal
            BigDecimal allTarget = BigDecimal.ZERO;
            BigDecimal allTotal = BigDecimal.ZERO;
            double allProgress = 0.0;
            result.put("AllTarget", allTarget);
            result.put("AllTotal", allTotal);
            result.put("AllProgress", allProgress);
            result.put("data", list);
            return result;
        }

        Map<String, Object> result = new HashMap<>();

        // 如果无目标方案，则直接返回
        if (idList == null || idList.isEmpty()) {
            logger.error("未找到目标方案");
            List<Map<String, Object>> list = new ArrayList<>();
            // 初始化AllTarget和AllTotal
            BigDecimal allTarget = BigDecimal.ZERO;
            BigDecimal allTotal = BigDecimal.ZERO;
            double allProgress = 0.0;
            result.put("AllTarget", allTarget);
            result.put("AllTotal", allTotal);
            result.put("AllProgress", allProgress);
            result.put("data", list);
            return result;
        }

        try {
            int organizationalType = targetRankingDTO.getOrganizationalType();
            switch (organizationalType) {
                case 2:
                    invokeMethod(2, idList, targetWrapper, targetRankingDTO, result, methodName);
                    break;
                case 3:
                    invokeMethod(3, idList, targetWrapper, targetRankingDTO, result, methodName);
                    break;
                case 4:
                    invokeMethod(4, idList, targetWrapper, targetRankingDTO, result, methodName);
                    break;
                default:
                    result.put("message", "未知的组织类型");
                    return result;
            }
        } catch (Exception e) {
            logger.error("获取目标数据失败: {}", e.getMessage());
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return result;
        }

        return result;
    }


    private void invokeMethod(int organizationalType, List<Long> idList, LambdaQueryWrapper<TargetPlanEntity> targetWrapper, TargetRankingDTO targetRankingDTO, Map<String, Object> result, String methodName) throws Exception {
        switch (methodName) {
            case "OrdertotalAmount":
                OrdertotalAmount(organizationalType, idList, targetRankingDTO, result);
                break;
            case "OrderCount":
                OrderCount(organizationalType, idList, targetRankingDTO, result);
                break;
            case "CustomerCount":
                CustomerCount(organizationalType, idList, targetRankingDTO, result);
                break;
            case "BusinessCount":
                BusinessCount(organizationalType, idList, targetRankingDTO, result);
                break;
            case "FollowUpCount":
                FollowUpCount(organizationalType, idList, targetRankingDTO, result);
                break;
            case "NewClueCount":
                ClueCount(organizationalType, idList, targetRankingDTO, result);
                break;
            default:
                throw new IllegalArgumentException("未知的方法名");
        }
    }

    // 统计订单总金额
    private void OrdertotalAmount(int organizationalType, List<Long> idList, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete, 0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 获取targetRankingDTO中的季度
        Integer quarter = targetRankingDTO.getQuarter();

        // 获取所有用户的ID
        List<Long> userIds =targetQuotaService.getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete, 0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联orderFormEntity的ownBy字段，筛选出当前组织的订单
        LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
        orderFormWrapper.in(OrderFormEntity::getOwnerBy, userIds);
        orderFormWrapper.eq(OrderFormEntity::getIsDelete, 0);
        orderFormWrapper.apply("YEAR(signing_date) = {0}", year);

        List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);

        Map<Long, Map<Integer, Object>> transactionTotalMap = new HashMap<>();

        // 创建组织ID到用户ID的映射关系
        Map<Long, List<Long>> orgToUserMap = new HashMap<>();

        // 根据组织类型建立映射关系
        for (TargetQuotaEntity quota : targetQuotaList) {
            Long orgId = quota.getOrganizationalId();
            List<Long> orgUsers = userIds.stream()
                    .filter(userId -> {
                        UserEntity user = userService.IdListToUserMap(Collections.singletonList(userId)).get(userId);
                        if (user == null) return false;

                        switch (organizationalType) {
                            case 2: return user.getSubCompanyId().equals(orgId);
                            case 3: return user.getDeptId().equals(orgId);
                            case 4: return userId.equals(orgId);
                            default: return false;
                        }
                    })
                    .collect(Collectors.toList());
            orgToUserMap.put(orgId, orgUsers);
        }

        // 计算每个组织的订单金额总和
        for (OrderFormEntity orderForm : orderFormList) {
            Long ownerId = orderForm.getOwnerBy();
            // 找到该用户所属的组织
            for (Map.Entry<Long, List<Long>> entry : orgToUserMap.entrySet()) {
                if (entry.getValue().contains(ownerId)) {
                    // 更新该组织的统计数据
                    updateCount(
                            transactionTotalMap,
                            entry.getKey(),
                            orderForm.getSigningDate(),
                            quarter,
                            orderForm.getTotalOrderAmt()
                    );
                }
            }
        }

        // 存放所有组织的数据集合
        List<List<Map<String, Object>>> organizationDataList = new ArrayList<>();

        // 初始化AllTarget和AllTotal
        BigDecimal allTarget = BigDecimal.ZERO;
        BigDecimal allTotal = BigDecimal.ZERO;

        // 遍历targetQuotaList，获取每个组织的目标值和成交金额
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            // 创建存储单个组织所有时间段数据的列表
            List<Map<String, Object>> orgTimeDataList = new ArrayList<>();
            Long organizationalId = targetQuota.getOrganizationalId();

            if (targetQuota.getTotal() != null) {
                allTarget = allTarget.add(targetQuota.getTotal());
            }
            // 获取组织名称
            Map<String, String> orgNames = getOrganizationNames(organizationalType, organizationalId, userIds);
            String companyName = orgNames.get("companyName");
            String deptName = orgNames.get("deptName");
            String userName = orgNames.get("userName");

            // 如果目标值为空，则直接添加0值数据
            if (targetQuota.getTotal() == null) {
                addZeroData(orgTimeDataList,
                        targetRankingDTO.getYear().toString(),
                        quarter != null,
                        companyName,
                        deptName,
                        userName);

                organizationDataList.add(orgTimeDataList);
                continue;
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);
            if (quarter != null) {
                // 按季度计算
                for (int q = 1; q <= 4; q++) {
                    Map<String, Object> quarterData = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByQuarter(targetQuota, cycle, q);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalQ = q;
                    BigDecimal transactionTotal = Optional.ofNullable(transactionTotalMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalQ))
                                    .map(value -> value instanceof BigDecimal ?
                                            (BigDecimal) value :
                                            BigDecimal.valueOf(((Number) value).doubleValue()))
                                    .orElse(BigDecimal.ZERO))
                            .orElse(BigDecimal.ZERO);

                    double progress = BigDecimalProgress(transactionTotal, targetValue);

                    quarterData.put("times", targetRankingDTO.getYear() + "年" + q + "季度");
                    quarterData.put("time", targetRankingDTO.getYear() + "-" + q);
                    quarterData.put("company", companyName);
                    quarterData.put("dept", deptName);
                    quarterData.put("user", userName);
                    quarterData.put("Target", targetValue);
                    quarterData.put("Total", transactionTotal);
                    quarterData.put("Progress", progress);

                    orgTimeDataList.add(quarterData);
                    allTotal = allTotal.add(transactionTotal);
                }
            } else {
                // 按月份计算目标值和达成金额
                for (int m = 1; m <= 12; m++) {
                    Map<String, Object> monthMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByMonth(targetQuota, cycle, m);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalM = m;
                    BigDecimal transactionTotal = Optional.ofNullable(transactionTotalMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalM))
                                    .map(value -> value instanceof BigDecimal ?
                                            (BigDecimal) value :
                                            BigDecimal.valueOf(((Number) value).doubleValue()))
                                    .orElse(BigDecimal.ZERO))
                            .orElse(BigDecimal.ZERO);

                    double progress = 0.0;
                    if (transactionTotal.compareTo(BigDecimal.ZERO) > 0) {
                        progress = BigDecimalProgress(transactionTotal, targetValue);
                    }
                    monthMp.put("times", targetRankingDTO.getYear() + "年" + m + "月");
                    monthMp.put("time", targetRankingDTO.getYear() + "-" + m);
                    monthMp.put("company", companyName);
                    monthMp.put("dept", deptName);
                    monthMp.put("user", userName);
                    monthMp.put("Target", targetValue);
                    monthMp.put("Total", transactionTotal);
                    monthMp.put("Progress", progress);

                    allTotal = allTotal.add(transactionTotal);
                    orgTimeDataList.add(monthMp);
                }
            }
            // 将该组织的数据集合添加到组织数据列表中
            organizationDataList.add(orgTimeDataList);
        }
        // 直接将combinedResultList赋值给result
        result.put("data", organizationDataList);
        // 计算AllProgress
        double allProgress = 0.0;
        if (allTotal.compareTo(BigDecimal.ZERO) > 0) {
            allProgress = BigDecimalProgress(allTotal, allTarget);
            allProgress = Double.parseDouble(String.format("%.2f", allProgress));
        }

        // 将AllTarget, AllTotal, AllProgress放入结果中
        result.put("AllTarget", allTarget);
        result.put("AllTotal", allTotal);
        result.put("AllProgress", allProgress);
    }

    // 统计订单总数量
    private void OrderCount(int organizationalType, List<Long> idList, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete, 0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 获取targetRankingDTO中的季度
        Integer quarter = targetRankingDTO.getQuarter();

        // 获取所有用户的ID
        List<Long> userIds = targetQuotaService.getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete, 0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联orderFormEntity的ownBy字段，筛选出当前组织的订单
        LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
        orderFormWrapper.in(OrderFormEntity::getOwnerBy, userIds);
        orderFormWrapper.eq(OrderFormEntity::getIsDelete, 0);
        orderFormWrapper.apply("YEAR(signing_date) = {0}", year);

        List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);

        Map<Long, Map<Integer, Object>> transactionCountMap = new HashMap<>();

        // 创建组织ID到用户ID的映射关系
        Map<Long, List<Long>> orgToUserMap = new HashMap<>();

        // 根据组织类型建立映射关系
        for (TargetQuotaEntity quota : targetQuotaList) {
            Long orgId = quota.getOrganizationalId();
            List<Long> orgUsers = userIds.stream()
                    .filter(userId -> {
                        UserEntity user = userService.IdListToUserMap(Collections.singletonList(userId)).get(userId);
                        if (user == null) return false;

                        switch (organizationalType) {
                            case 2: return user.getSubCompanyId().equals(orgId);
                            case 3: return user.getDeptId().equals(orgId);
                            case 4: return userId.equals(orgId);
                            default: return false;
                        }
                    })
                    .collect(Collectors.toList());
            orgToUserMap.put(orgId, orgUsers);
        }

        // 计算每个组织的订单数量总和
        for (OrderFormEntity orderForm : orderFormList) {
            Long ownerId = orderForm.getOwnerBy();
            // 找到该用户所属的组织
            for (Map.Entry<Long, List<Long>> entry : orgToUserMap.entrySet()) {
                if (entry.getValue().contains(ownerId)) {
                    // 更新该组织的统计数据
                    updateCount(
                            transactionCountMap,
                            entry.getKey(),
                            orderForm.getSigningDate(),
                            quarter,
                            1L
                    );
                }
            }
        }

        // 存放每个组织的详细数据列表
        List<List<Map<String, Object>>> organizationDataList = new ArrayList<>();

        // 初始化AllTarget和AllTotal
        BigDecimal allTarget = BigDecimal.ZERO;
        long allTotal = 0;

        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            List<Map<String, Object>> orgTimeDataList = new ArrayList<>();
            Long organizationalId = targetQuota.getOrganizationalId();

            if (targetQuota.getTotal() != null) {
                allTarget = allTarget.add(targetQuota.getTotal());
            }
            // 获取组织名称
            Map<String, String> orgNames = getOrganizationNames(organizationalType, organizationalId, userIds);
            String companyName = orgNames.get("companyName");
            String deptName = orgNames.get("deptName");
            String userName = orgNames.get("userName");

            // 如果目标值为空，则直接添加0值数据
            if (targetQuota.getTotal() == null) {
                addZeroData(orgTimeDataList,
                        targetRankingDTO.getYear().toString(),
                        quarter != null,
                        companyName,
                        deptName,
                        userName);

                organizationDataList.add(orgTimeDataList);
                continue;
            }


            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);

            if (quarter != null) {
                // 按季度计算
                for (int q = 1; q <= 4; q++) {
                    Map<String, Object> quarterMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByQuarter(targetQuota, cycle, q);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalQ = q;
                    Long transactionCount = Optional.ofNullable(transactionCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalQ))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    quarterMp.put("times", targetRankingDTO.getYear() + "年" + q + "季度");
                    quarterMp.put("time", targetRankingDTO.getYear()+ "-" + q);
                    quarterMp.put("company", companyName);
                    quarterMp.put("dept", deptName);
                    quarterMp.put("user", userName);
                    quarterMp.put("Target", targetValue);
                    quarterMp.put("Total", transactionCount);
                    quarterMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(quarterMp);
                }
            } else {
                // 按月份计算
                for (int m = 1; m <= 12; m++) {
                    Map<String, Object> monthMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByMonth(targetQuota, cycle, m);
                    }

                    int finalM = m;
                    Long transactionCount = Optional.ofNullable(transactionCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalM))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    monthMp.put("times", targetRankingDTO.getYear() + "年" + m + "月");
                    monthMp.put("time", targetRankingDTO.getYear() + "-" + m);
                    monthMp.put("company", companyName);
                    monthMp.put("dept", deptName);
                    monthMp.put("user", userName);
                    monthMp.put("Target", targetValue);
                    monthMp.put("Total", transactionCount);
                    monthMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(monthMp);
                }
            }
            organizationDataList.add(orgTimeDataList);
            // 直接将combinedResultList赋值给result
            result.put("data", organizationDataList);
        }
        // 计算AllProgress，使用BigDecimal确保精度
        double allProgress = 0.0;
        if (allTotal != 0) {
            allProgress = BigDecimalProgress(new BigDecimal(allTotal), allTarget);
        }

        // 将AllTarget, AllTotal, AllProgress放入结果中
        result.put("AllTarget", allTarget);
        result.put("AllTotal", allTotal);
        result.put("AllProgress", allProgress);
    }

    // 统计客户总数量
    private void CustomerCount(int organizationalType, List<Long> idList, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete, 0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 获取targetRankingDTO中的季度
        Integer quarter = targetRankingDTO.getQuarter();

        // 获取所有用户的ID
        List<Long> userIds = targetQuotaService.getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete, 0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联customerEntity的ownBy字段，筛选出当前组织的客户
        LambdaQueryWrapper<CustomerEntity> customerFormWrapper = new LambdaQueryWrapper<>();
        customerFormWrapper.in(CustomerEntity::getOwnerBy, userIds);
        customerFormWrapper.eq(CustomerEntity::getIsDelete, 0);
        customerFormWrapper.eq(CustomerEntity::getCustomerForm, 10);
        customerFormWrapper.eq(CustomerEntity::getHasGarbageCustomer, 0);
        customerFormWrapper.apply("YEAR(create_time) = {0}", year);

        List<CustomerEntity> customerFormList = customerService.list(customerFormWrapper);

        Map<Long, Map<Integer, Object>> customerCountMap = new HashMap<>();

        // 创建组织ID到用户ID的映射关系
        Map<Long, List<Long>> orgToUserMap = new HashMap<>();

        // 根据组织类型建立映射关系
        for (TargetQuotaEntity quota : targetQuotaList) {
            Long orgId = quota.getOrganizationalId();
            List<Long> orgUsers = userIds.stream()
                    .filter(userId -> {
                        UserEntity user = userService.IdListToUserMap(Collections.singletonList(userId)).get(userId);
                        if (user == null) return false;

                        switch (organizationalType) {
                            case 2: return user.getSubCompanyId().equals(orgId);
                            case 3: return user.getDeptId().equals(orgId);
                            case 4: return userId.equals(orgId);
                            default: return false;
                        }
                    })
                    .collect(Collectors.toList());
            orgToUserMap.put(orgId, orgUsers);
        }

        // 计算每个组织的客户数量总和
        for (CustomerEntity customer : customerFormList) {
            Long ownerId = customer.getOwnerBy();
            // 找到该用户所属的组织
            for (Map.Entry<Long, List<Long>> entry : orgToUserMap.entrySet()) {
                if (entry.getValue().contains(ownerId)) {
                    // 更新该组织的统计数据
                    updateCount(
                            customerCountMap,
                            entry.getKey(),
                            Date.from(customer.getOwnerTime().atZone(ZoneId.systemDefault()).toInstant()),
                            quarter,
                            1L
                    );
                }
            }
        }

        // 存放每个组织的详细数据列表
        List<List<Map<String, Object>>> organizationDataList = new ArrayList<>();

        // 初始化AllTarget和AllTotal
        BigDecimal allTarget = BigDecimal.ZERO;
        long allTotal = 0;

        // 遍历customerList，获取每个组织的目标值和客户数量达成值
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            List<Map<String, Object>> orgTimeDataList = new ArrayList<>();
            Long organizationalId = targetQuota.getOrganizationalId();
            if (targetQuota.getTotal() != null) {
                allTarget = allTarget.add(targetQuota.getTotal());
            }
            // 获取组织名称
            Map<String, String> orgNames = getOrganizationNames(organizationalType, organizationalId, userIds);
            String companyName = orgNames.get("companyName");
            String deptName = orgNames.get("deptName");
            String userName = orgNames.get("userName");

            // 如果目标值为空，则直接添加0值数据
            if (targetQuota.getTotal() == null) {
                addZeroData(orgTimeDataList,
                        targetRankingDTO.getYear().toString(),
                        quarter != null,
                        companyName,
                        deptName,
                        userName);

                organizationDataList.add(orgTimeDataList);
                continue;
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);

            if (quarter != null) {
                // 按季度计算
                for (int q = 1; q <= 4; q++) {
                    Map<String, Object> quarterMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByQuarter(targetQuota, cycle, q);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalQ = q;
                    Long transactionCount = Optional.ofNullable(customerCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalQ))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    quarterMp.put("times", targetRankingDTO.getYear() + "年" + q + "季度");
                    quarterMp.put("time", targetRankingDTO.getYear() + "-" + q);
                    quarterMp.put("company", companyName);
                    quarterMp.put("dept", deptName);
                    quarterMp.put("user", userName);
                    quarterMp.put("Target", targetValue);
                    quarterMp.put("Total", transactionCount);
                    quarterMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(quarterMp);
                }
            } else {
                // 按月份计算
                for (int m = 1; m <= 12; m++) {
                    Map<String, Object> monthMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByMonth(targetQuota, cycle, m);
                    }

                    int finalM = m;
                    Long transactionCount = Optional.ofNullable(customerCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalM))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    monthMp.put("times", targetRankingDTO.getYear() + "年" + m + "月");
                    monthMp.put("time", targetRankingDTO.getYear() + "-" + m);
                    monthMp.put("company", companyName);
                    monthMp.put("dept", deptName);
                    monthMp.put("user", userName);
                    monthMp.put("Target", targetValue);
                    monthMp.put("Total", transactionCount);
                    monthMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(monthMp);
                }
            }
            organizationDataList.add(orgTimeDataList);
            // 直接将combinedResultList赋值给result
            result.put("data", organizationDataList);
        }
        // 计算AllProgress，使用BigDecimal确保精度
        double allProgress = 0.0;
        if (allTotal != 0) {
            allProgress = BigDecimalProgress(new BigDecimal(allTotal), allTarget);
        }
        // 将AllTarget, AllTotal, AllProgress放入结果中
        result.put("AllTarget", allTarget);
        result.put("AllTotal", allTotal);
        result.put("AllProgress", allProgress);
    }

    // 统计线索总数量
    private void ClueCount(int organizationalType, List<Long> idList, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete, 0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 获取targetRankingDTO中的季度
        Integer quarter = targetRankingDTO.getQuarter();

        // 获取所有用户的ID
        List<Long> userIds = targetQuotaService.getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete, 0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联customerEntity的ownBy字段，筛选出当前组织的线索
        LambdaQueryWrapper<CustomerEntity> customerFormWrapper = new LambdaQueryWrapper<>();
        customerFormWrapper.in(CustomerEntity::getOwnerBy, userIds);
        customerFormWrapper.eq(CustomerEntity::getIsDelete, 0);
        customerFormWrapper.eq(CustomerEntity::getCustomerForm, 11);
        customerFormWrapper.apply("YEAR(create_time) = {0}", year);

        List<CustomerEntity> customerFormList = customerService.list(customerFormWrapper);

        Map<Long, Map<Integer, Object>> clueCountMap = new HashMap<>();

        // 创建组织ID到用户ID的映射关系
        Map<Long, List<Long>> orgToUserMap = new HashMap<>();

        // 根据组织类型建立映射关系
        for (TargetQuotaEntity quota : targetQuotaList) {
            Long orgId = quota.getOrganizationalId();
            List<Long> orgUsers = userIds.stream()
                    .filter(userId -> {
                        UserEntity user = userService.IdListToUserMap(Collections.singletonList(userId)).get(userId);
                        if (user == null) return false;

                        switch (organizationalType) {
                            case 2: // 公司级别
                                return user.getSubCompanyId().equals(orgId);
                            case 3: // 部门级别
                                return user.getDeptId().equals(orgId);
                            case 4: // 用户级别
                                return userId.equals(orgId);
                            default:
                                return false;
                        }
                    })
                    .collect(Collectors.toList());
            orgToUserMap.put(orgId, orgUsers);
        }

        // 计算每个组织的线索数量总和
        for (CustomerEntity customer : customerFormList) {
            Long ownerId = customer.getOwnerBy();
            // 找到该用户所属的组织
            for (Map.Entry<Long, List<Long>> entry : orgToUserMap.entrySet()) {
                if (entry.getValue().contains(ownerId)) {
                    // 更新该组织的统计数据
                    updateCount(
                            clueCountMap,
                            entry.getKey(),
                            customer.getCreateTime(),
                            quarter,
                            1L
                    );
                }
            }
        }

        // 存放每个组织的详细数据列表
        List<List<Map<String, Object>>> organizationDataList = new ArrayList<>();

        // 初始化AllTarget和AllTotal
        BigDecimal allTarget = BigDecimal.ZERO;
        long allTotal = 0;

        // 遍历customerList，获取每个组织的目标值和线索数量达成值
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            List<Map<String, Object>> orgTimeDataList = new ArrayList<>();
            Long organizationalId = targetQuota.getOrganizationalId();
            if (targetQuota.getTotal() != null) {
                allTarget = allTarget.add(targetQuota.getTotal());
            }
            // 获取组织名称
            Map<String, String> orgNames = getOrganizationNames(organizationalType, organizationalId, userIds);
            String companyName = orgNames.get("companyName");
            String deptName = orgNames.get("deptName");
            String userName = orgNames.get("userName");

            // 如果目标值为空，则直接添加0值数据
            if (targetQuota.getTotal() == null) {
                addZeroData(orgTimeDataList,
                        targetRankingDTO.getYear().toString(),
                        quarter != null,
                        companyName,
                        deptName,
                        userName);

                organizationDataList.add(orgTimeDataList);
                continue;
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);

            if (quarter != null) {
                // 按季度计算
                for (int q = 1; q <= 4; q++) {
                    Map<String, Object> quarterMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByQuarter(targetQuota, cycle, q);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalQ = q;
                    Long transactionCount = Optional.ofNullable(clueCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalQ))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    quarterMp.put("times", targetRankingDTO.getYear() + "年" + q + "季度");
                    quarterMp.put("time", targetRankingDTO.getYear() + "-" + q);
                    quarterMp.put("company", companyName);
                    quarterMp.put("dept", deptName);
                    quarterMp.put("user", userName);
                    quarterMp.put("Target", targetValue);
                    quarterMp.put("Total", transactionCount);
                    quarterMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(quarterMp);
                }
            } else {
                // 按月份计算
                for (int m = 1; m <= 12; m++) {
                    Map<String, Object> monthMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByMonth(targetQuota, cycle, m);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalM = m;
                    Long transactionCount = Optional.ofNullable(clueCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalM))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    monthMp.put("times", targetRankingDTO.getYear() + "年" + m + "月");
                    monthMp.put("time", targetRankingDTO.getYear() + "-" + m );
                    monthMp.put("company", companyName);
                    monthMp.put("dept", deptName);
                    monthMp.put("user", userName);
                    monthMp.put("Target", targetValue);
                    monthMp.put("Total", transactionCount);
                    monthMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(monthMp);
                }
            }
            organizationDataList.add(orgTimeDataList);
            // 直接将combinedResultList赋值给result
            result.put("data", organizationDataList);
        }
        // 计算AllProgress，使用BigDecimal确保精度
        double allProgress = 0.0;
        if (allTotal != 0) {
            allProgress = BigDecimalProgress(new BigDecimal(allTotal), allTarget);
        }

        // 将AllTarget, AllTotal, AllProgress放入结果中
        result.put("AllTarget", allTarget);
        result.put("AllTotal", allTotal);
        result.put("AllProgress", allProgress);
    }

    // 统计商机总数量
    private void BusinessCount(int organizationalType, List<Long> idList, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete, 0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 获取targetRankingDTO中的季度
        Integer quarter = targetRankingDTO.getQuarter();

        // 获取所有用户的ID
        List<Long> userIds = targetQuotaService.getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete, 0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联customerEntity的ownBy字段，筛选出当前组织的商机
        LambdaQueryWrapper<BusinessEntity> businessWrapper = new LambdaQueryWrapper<>();
        businessWrapper.in(BusinessEntity::getOwnerBy, userIds);
        businessWrapper.eq(BusinessEntity::getIsDelete, 0);
        businessWrapper.eq(BusinessEntity::getHasLoss, 0);
        businessWrapper.apply("YEAR(geted_date) = {0}", year);

        List<BusinessEntity> businessList = businessService.list(businessWrapper);

        Map<Long, Map<Integer, Object>> businessCountMap = new HashMap<>();

        // 创建组织ID到用户ID的映射关系
        Map<Long, List<Long>> orgToUserMap = new HashMap<>();

        // 根据组织类型建立映射关系
        for (TargetQuotaEntity quota : targetQuotaList) {
            Long orgId = quota.getOrganizationalId();
            List<Long> orgUsers = userIds.stream()
                    .filter(userId -> {
                        UserEntity user = userService.IdListToUserMap(Collections.singletonList(userId)).get(userId);
                        if (user == null) return false;

                        switch (organizationalType) {
                            case 2: return user.getSubCompanyId().equals(orgId);
                            case 3: return user.getDeptId().equals(orgId);
                            case 4: return userId.equals(orgId);
                            default: return false;
                        }
                    })
                    .collect(Collectors.toList());
            orgToUserMap.put(orgId, orgUsers);
        }

        // 计算每个组织的商机数量总和
        for (BusinessEntity business : businessList) {
            Long ownerId = business.getOwnerBy();
            // 找到该用户所属的组织
            for (Map.Entry<Long, List<Long>> entry : orgToUserMap.entrySet()) {
                if (entry.getValue().contains(ownerId)) {
                    // 更新该组织的统计数据
                    updateCount(
                            businessCountMap,
                            entry.getKey(),
                            business.getGetedDate(),
                            quarter,
                            1L
                    );
                }
            }
        }


        // 存放每个组织的详细数据列表
        List<List<Map<String, Object>>> organizationDataList = new ArrayList<>();

        // 初始化AllTarget和AllTotal
        BigDecimal allTarget = BigDecimal.ZERO;
        long allTotal = 0;

        // 遍历customerList，获取每个组织的目标值和商机数量达成值
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            List<Map<String, Object>> orgTimeDataList = new ArrayList<>();
            Long organizationalId = targetQuota.getOrganizationalId();
            if (targetQuota.getTotal() != null) {
                allTarget = allTarget.add(targetQuota.getTotal());
            }
            // 获取组织名称
            Map<String, String> orgNames = getOrganizationNames(organizationalType, organizationalId, userIds);
            String companyName = orgNames.get("companyName");
            String deptName = orgNames.get("deptName");
            String userName = orgNames.get("userName");

            if (targetQuota.getTotal() == null) {
                addZeroData(orgTimeDataList,
                        targetRankingDTO.getYear().toString(),
                        quarter != null,
                        companyName,
                        deptName,
                        userName);

                organizationDataList.add(orgTimeDataList);
                continue;
            }


            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);

            if (quarter != null) {
                // 按季度计算
                for (int q = 1; q <= 4; q++) {
                    Map<String, Object> quarterMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByQuarter(targetQuota, cycle, q);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalQ = q;
                    Long transactionCount = Optional.ofNullable(businessCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalQ))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    quarterMp.put("times", targetRankingDTO.getYear() + "年" + q + "季度");
                    quarterMp.put("time", targetRankingDTO.getYear() + "-" + q);
                    quarterMp.put("company", companyName);
                    quarterMp.put("dept", deptName);
                    quarterMp.put("user", userName);
                    quarterMp.put("Target", targetValue);
                    quarterMp.put("Total", transactionCount);
                    quarterMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(quarterMp);
                }
            } else {
                // 按月份计算
                for (int m = 1; m <= 12; m++) {
                    Map<String, Object> monthMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByMonth(targetQuota, cycle, m);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalM = m;
                    Long transactionCount = Optional.ofNullable(businessCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalM))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    monthMp.put("times", targetRankingDTO.getYear() + "年" + m + "月");
                    monthMp.put("time", targetRankingDTO.getYear() + "-" + m);
                    monthMp.put("company", companyName);
                    monthMp.put("dept", deptName);
                    monthMp.put("user", userName);
                    monthMp.put("Target", targetValue);
                    monthMp.put("Total", transactionCount);
                    monthMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(monthMp);
                }
            }
            organizationDataList.add(orgTimeDataList);
            // 直接将combinedResultList赋值给result
            result.put("data", organizationDataList);
        }
        // 计算AllProgress，使用BigDecimal确保精度
        double allProgress = 0.0;
        if (allTotal != 0) {
            allProgress = BigDecimalProgress(new BigDecimal(allTotal), allTarget);
        }

        // 将AllTarget, AllTotal, AllProgress放入结果中
        result.put("AllTarget", allTarget);
        result.put("AllTotal", allTotal);
        result.put("AllProgress", allProgress);
    }

    // 统计客户跟进次数总数量
    private void FollowUpCount(int organizationalType, List<Long> idList, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete, 0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 获取targetRankingDTO中的季度
        Integer quarter = targetRankingDTO.getQuarter();

        // 获取所有用户的ID
        List<Long> userIds = targetQuotaService.getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete, 0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联CustomerFollowUpEntity的ownBy字段，筛选出当前组织的客户跟进次数
        LambdaQueryWrapper<CustomerFollowUpEntity> followUpWrapper = new LambdaQueryWrapper<>();
        followUpWrapper.in(CustomerFollowUpEntity::getFollowUpMemberId, userIds);
        followUpWrapper.eq(CustomerFollowUpEntity::getIsDelete, 0);
        followUpWrapper.apply("YEAR(follow_up_time) = {0}", year);

        List<CustomerFollowUpEntity> followUpList = customerFollowUpService.list(followUpWrapper);

        Map<Long, Map<Integer, Object>> followUpCountMap = new HashMap<>();

        // 创建组织ID到用户ID的映射关系
        Map<Long, List<Long>> orgToUserMap = new HashMap<>();

        // 根据组织类型建立映射关系
        for (TargetQuotaEntity quota : targetQuotaList) {
            Long orgId = quota.getOrganizationalId();
            List<Long> orgUsers = userIds.stream()
                    .filter(userId -> {
                        UserEntity user = userService.IdListToUserMap(Collections.singletonList(userId)).get(userId);
                        if (user == null) return false;

                        switch (organizationalType) {
                            case 2: return user.getSubCompanyId().equals(orgId);
                            case 3: return user.getDeptId().equals(orgId);
                            case 4: return userId.equals(orgId);
                            default: return false;
                        }
                    })
                    .collect(Collectors.toList());
            orgToUserMap.put(orgId, orgUsers);
        }

        // 计算每个组织的跟进次数总和
        for (CustomerFollowUpEntity followUp : followUpList) {
            Long ownerId = followUp.getFollowUpMemberId();
            // 找到该用户所属的组织
            for (Map.Entry<Long, List<Long>> entry : orgToUserMap.entrySet()) {
                if (entry.getValue().contains(ownerId)) {
                    // 更新该组织的统计数据
                    updateCount(
                            followUpCountMap,
                            entry.getKey(),
                            Date.from(followUp.getFollowUpTime().atZone(ZoneId.systemDefault()).toInstant()),
                            quarter,
                            1L
                    );
                }
            }
        }

        // 存放每个组织的详细数据列表
        List<List<Map<String, Object>>> organizationDataList = new ArrayList<>();

        // 初始化AllTarget和AllTotal
        BigDecimal allTarget = BigDecimal.ZERO;
        long allTotal = 0;

        // 遍历customerList，获取每个组织的目标值和跟进次数达成值
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            List<Map<String, Object>> orgTimeDataList = new ArrayList<>();
            Long organizationalId = targetQuota.getOrganizationalId();
            if (targetQuota.getTotal() != null) {
                allTarget = allTarget.add(targetQuota.getTotal());
            }
            // 获取组织名称
            Map<String, String> orgNames = getOrganizationNames(organizationalType, organizationalId, userIds);
            String companyName = orgNames.get("companyName");
            String deptName = orgNames.get("deptName");
            String userName = orgNames.get("userName");

            // 如果目标值为空，则直接添加0值数据
            if (targetQuota.getTotal() == null) {
                addZeroData(orgTimeDataList,
                        targetRankingDTO.getYear().toString(),
                        quarter != null,
                        companyName,
                        deptName,
                        userName);

                organizationDataList.add(orgTimeDataList);
                continue;
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);

            if (quarter != null) {
                // 按季度计算
                for (int q = 1; q <= 4; q++) {
                    Map<String, Object> quarterMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByQuarter(targetQuota, cycle, q);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalQ = q;
                    Long transactionCount = Optional.ofNullable(followUpCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalQ))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    quarterMp.put("times", targetRankingDTO.getYear() + "年" + q + "季度");
                    quarterMp.put("time", targetRankingDTO.getYear() + "-" + q );
                    quarterMp.put("company", companyName);
                    quarterMp.put("dept", deptName);
                    quarterMp.put("user", userName);
                    quarterMp.put("Target", targetValue);
                    quarterMp.put("Total", transactionCount);
                    quarterMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(quarterMp);
                }
            } else {
                // 按月份计算
                for (int m = 1; m <= 12; m++) {
                    Map<String, Object> monthMp = new HashMap<>();
                    BigDecimal targetValue = BigDecimal.ZERO;
                    if (targetQuota.getTotal() != null) {
                        targetValue = calculateTargetValueByMonth(targetQuota, cycle, m);
                    }

                    // 确保从正确的组织ID获取数据
                    int finalM = m;
                    Long transactionCount = Optional.ofNullable(followUpCountMap.get(organizationalId))
                            .map(periodMap -> Optional.ofNullable(periodMap.get(finalM))
                                    .map(value -> value instanceof Long ? (Long) value : ((Number) value).longValue())
                                    .orElse(0L))
                            .orElse(0L);

                    Double progress = 0.0;
                    if (transactionCount != 0) {
                        progress = BigDecimalProgress(new BigDecimal(transactionCount), targetValue);
                    }

                    monthMp.put("times", targetRankingDTO.getYear() + "年" + m + "月");
                    monthMp.put("time", targetRankingDTO.getYear() + "-" + m);
                    monthMp.put("company", companyName);
                    monthMp.put("dept", deptName);
                    monthMp.put("user", userName);
                    monthMp.put("Target", targetValue);
                    monthMp.put("Total", transactionCount);
                    monthMp.put("Progress", progress);

                    allTotal += transactionCount;
                    orgTimeDataList.add(monthMp);
                }
            }
            organizationDataList.add(orgTimeDataList);
            // 直接将combinedResultList赋值给result
            result.put("data", organizationDataList);
        }
        // 计算AllProgress，使用BigDecimal确保精度
        double allProgress = 0.0;
        if (allTotal != 0) {
            allProgress = BigDecimalProgress(new BigDecimal(allTotal), allTarget);
        }

        // 将AllTarget, AllTotal, AllProgress放入结果中
        result.put("AllTarget", allTarget);
        result.put("AllTotal", allTotal);
        result.put("AllProgress", allProgress);

    }

    // 针对无目标值进行处理
    private void addZeroData(List<Map<String, Object>> orgTimeDataList,
                             String year,
                             boolean isQuarter,
                             String companyName,
                             String deptName,
                             String userName) {
        int cycle = isQuarter ? QUARTER_CYCLE : MONTH_CYCLE;
        String timeFormat = isQuarter ? "%s-Q%d" : "%s-%02d"; // 统一时间格式处理

        for (int i = 1; i <= cycle; i++) {
            orgTimeDataList.add(createZeroDataMap(
                    String.format(timeFormat, year, i),
                    companyName,
                    deptName,
                    userName
            ));
        }
    }

    // 统一创建0值数据
    private Map<String, Object> createZeroDataMap(String time,
                                                  String company,
                                                  String dept,
                                                  String user) {
        return new HashMap<String, Object>() {{
            put("time", time);
            put("company", company);
            put("dept", dept);
            put("user", user);
            put("Target", BigDecimal.ZERO);
            put("Total", BigDecimal.ZERO);
            put("Progress", 0.0);
        }};
    }

    /**
     * 更新计数的辅助方法
     */
    private void updateCount(
            Map<Long, Map<Integer, Object>> countMap,
            Long organizationalId,
            Date dateTime,
            Integer quarter,
            Object value) {

        if (organizationalId != null) {
            Map<Integer, Object> periodMap = countMap.computeIfAbsent(organizationalId, k -> new HashMap<>());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateTime);
            int month = calendar.get(Calendar.MONTH) + 1;

            int period = quarter != null ? (month - 1) / 3 + 1 : month;

            if (value instanceof BigDecimal || value instanceof Double) {
                // 金额类型，需要累加
                BigDecimal currentValue = value instanceof BigDecimal ?
                        (BigDecimal) value :
                        BigDecimal.valueOf((Double) value);

                BigDecimal existingValue = Optional.ofNullable(periodMap.get(period))
                        .map(v -> v instanceof BigDecimal ? (BigDecimal) v : BigDecimal.valueOf((Double) v))
                        .orElse(BigDecimal.ZERO);

                periodMap.put(period, existingValue.add(currentValue));
            } else {
                // 数量类型，直接累加1
                Long existingCount = Optional.ofNullable(periodMap.get(period))
                        .map(v -> v instanceof Long ? (Long) v : Long.valueOf(String.valueOf(v)))
                        .orElse(0L);

                periodMap.put(period, existingCount + 1);
            }
        }
    }

    //
    private BigDecimal calculateTargetValueByQuarter(TargetQuotaEntity targetQuota, int cycle, int quarter) {
        if (cycle == 1) {
            // 根据quarter值获取对应的季度目标
            switch (quarter) {
                case 1: return targetQuota.getMonthOrQuarter1();
                case 2: return targetQuota.getMonthOrQuarter2();
                case 3: return targetQuota.getMonthOrQuarter3();
                case 4: return targetQuota.getMonthOrQuarter4();
                default: return targetQuota.getTotal(); // 默认值
            }
        } else if (cycle == 2) {
            // 根据quarter值计算对应的月度目标总和
            switch (quarter) {
                case 1: return targetQuota.getMonthOrQuarter1().add(targetQuota.getMonthOrQuarter2()).add(targetQuota.getMonthOrQuarter3());
                case 2: return targetQuota.getMonthOrQuarter4().add(targetQuota.getMonthOrQuarter5()).add(targetQuota.getMonthOrQuarter6());
                case 3: return targetQuota.getMonthOrQuarter7().add(targetQuota.getMonthOrQuarter8()).add(targetQuota.getMonthOrQuarter9());
                case 4: return targetQuota.getMonthOrQuarter10().add(targetQuota.getMonthOrQuarter11()).add(targetQuota.getMonthOrQuarter12());
                default: return targetQuota.getTotal(); // 默认值
            }
        }
        return targetQuota.getTotal(); // 默认值
    }

    private BigDecimal calculateTargetValueByMonth(TargetQuotaEntity targetQuota, int cycle, int month) {
        if (cycle == 2) {
            // 直接取对应的月份目标
            switch (month) {
                case 1: return targetQuota.getMonthOrQuarter1();
                case 2: return targetQuota.getMonthOrQuarter2();
                case 3: return targetQuota.getMonthOrQuarter3();
                case 4: return targetQuota.getMonthOrQuarter4();
                case 5: return targetQuota.getMonthOrQuarter5();
                case 6: return targetQuota.getMonthOrQuarter6();
                case 7: return targetQuota.getMonthOrQuarter7();
                case 8: return targetQuota.getMonthOrQuarter8();
                case 9: return targetQuota.getMonthOrQuarter9();
                case 10: return targetQuota.getMonthOrQuarter10();
                case 11: return targetQuota.getMonthOrQuarter11();
                case 12: return targetQuota.getMonthOrQuarter12();
                default: return targetQuota.getTotal(); // 默认值
            }
        } else if (cycle == 1) {
            // 根据month值计算对应的季度目标
            if (month >= 1 && month <= 3) {
                return targetQuota.getMonthOrQuarter1().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
            } else if (month >= 4 && month <= 6) {
                return targetQuota.getMonthOrQuarter2().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
            } else if (month >= 7 && month <= 9) {
                return targetQuota.getMonthOrQuarter3().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
            } else if (month >= 10 && month <= 12) {
                return targetQuota.getMonthOrQuarter4().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
            }
        }
        return targetQuota.getTotal(); // 默认值
    }

    private double BigDecimalProgress(BigDecimal transactionTotal, BigDecimal targetValue) {
        if (targetValue.compareTo(BigDecimal.ZERO) == 0 || transactionTotal.compareTo(BigDecimal.ZERO) == 0) {
            return 0.0;
        }
        // 先进行除法运算
        BigDecimal result = transactionTotal.divide(targetValue, 4, RoundingMode.HALF_UP);
        // 乘以100后再四舍五入到2位小数
        return result.multiply(new BigDecimal("100"))
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue();
    }

    // 新增一个私有方法来获取组织名称信息
    private Map<String, String> getOrganizationNames(int organizationalType, Long organizationalId, List<Long> userIds) {
        Map<String, String> names = new HashMap<>();
        names.put("companyName", null);
        names.put("deptName", null);
        names.put("userName", null);

        try {
            switch (organizationalType) {
                case 2: // 公司级别
                    SubCompanyEntity subCompany = subCompanyService.getSubCompanyMap(
                            Collections.singletonList(organizationalId)
                    ).get(organizationalId);
                    if (subCompany != null) {
                        names.put("companyName", subCompany.getName());
                    }
                    break;

                case 3: // 部门级别
                    DeptEntity dept = departService.getDeptMap(
                            Collections.singletonList(organizationalId)
                    ).get(organizationalId);
                    if (dept != null) {
                        names.put("deptName", dept.getName());
                        // 获取公司信息
                        SubCompanyEntity deptCompany = subCompanyService.getSubCompanyMap(
                                Collections.singletonList(dept.getSubCompanyId())
                        ).get(dept.getSubCompanyId());
                        if (deptCompany != null) {
                            names.put("companyName", deptCompany.getName());
                        }
                    }
                    break;

                case 4: // 用户级别
                    UserEntity user = userService.IdListToUserMap(userIds).get(organizationalId);
                    if (user != null) {
                        names.put("userName", user.getRealName());
                        // 获取部门信息
                        DeptEntity userDept = departService.getDeptMap(
                                Collections.singletonList(user.getDeptId())
                        ).get(user.getDeptId());
                        if (userDept != null) {
                            names.put("deptName", userDept.getName());
                        }
                        // 获取公司信息
                        SubCompanyEntity userCompany = subCompanyService.getSubCompanyMap(
                                Collections.singletonList(user.getSubCompanyId())
                        ).get(user.getSubCompanyId());
                        if (userCompany != null) {
                            names.put("companyName", userCompany.getName());
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            logger.error("获取组织名称信息失败: {}", e.getMessage());
        }

        return names;
    }


}
