package com.aircraft.modules.order.service.impl;

import com.aircraft.modules.aircraft.domain.AircraftDevice;
import com.aircraft.modules.aircraft.service.AircraftDeviceService;
import com.aircraft.modules.order.controller.OrderAnalysisController;
import com.aircraft.modules.order.domain.OrderDetail;
import com.aircraft.modules.order.domain.dto.*;
import com.aircraft.modules.order.mapper.OrderDetailMapper;
import com.aircraft.modules.order.service.IOrderDetailService;
import com.aircraft.modules.order.service.OrderDetailAnalysisService;
import com.aircraft.modules.route.domain.CpRoute;
import com.aircraft.modules.route.mapper.CpRouteMapper;
import com.aircraft.modules.system.domain.EmScenic;
import com.aircraft.modules.system.mapper.EmScenicMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class OrderDetailAnalysisServiceImpl implements OrderDetailAnalysisService {
    private static final Logger LOG = LoggerFactory.getLogger(OrderAnalysisController.class);

    // 日期格式化器（用于按日/月/季度/年分组）
    private static final DateTimeFormatter DAY_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM");
    private static final DateTimeFormatter QUARTER_FORMATTER = DateTimeFormatter.ofPattern("yyyy-Qq"); // 如2025-Q1
    private static final DateTimeFormatter YEAR_FORMATTER = DateTimeFormatter.ofPattern("yyyy");

    // 订单状态
    private static final Integer STATUS_NOT_STARTED = 0;//未进行
    private static final Integer STATUS_PROCESSING = 1;//进行中
    private static final Integer STATUS_COMPLETED = 2;//已完成
    private static final Integer STATUS_FAILED = 3;//执行失败

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CpRouteMapper cpRouteMapper;
    @Autowired
    private EmScenicMapper emScenicMapper;
    @Autowired
    private AircraftDeviceService aircraftDeviceService;
    @Autowired
    private IOrderDetailService orderDetailService;

    @Override
    public OrderDetailAnalysisResult<T> analyzeAllOrderDetails(List<OrderDetail> allDetails) {
        return buildOrderDetailAnalysisResult(allDetails);
    }

    @Override
    public OrderDetailAnalysisResult<List<DailyStat>> analyzeByDayRange(LocalDate start, LocalDate end) {
        // 1. 查询时间范围内的所有订单
        List<OrderDetail> orders = queryOrderDetailByDateRange(start, end);
        if (CollectionUtils.isEmpty(orders)) {
            return buildEmptyResult();
        }

        // 2. 时间范围内总订单量
        Map<String, Long> dailyTotalCountMap = orders.stream()
                .filter(order -> order.getCreateTime() != null) // 过滤掉创建时间为空的订单
                .collect(Collectors.groupingBy(
                        order -> {
                            // 将订单创建时间转换为yyyy-MM-dd格式的日期字符串
                            LocalDate localDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                            return localDate.format(DAY_FORMATTER);
                        },
                        Collectors.counting()
                ));

        System.out.println(dailyTotalCountMap);

        // 3. 填充每日统计数据（确保日期连续性，即使某天无订单也显示0）
        List<DailyStat> dailyStats = new ArrayList<>();
        LocalDate current = start;
        // 4.计算每日完成量和失败量
        Map<String, Long> dailyCompletedMap = calculateDailyStatusCount(orders, STATUS_COMPLETED);
        Map<String, Long> dailyFailedMap = calculateDailyStatusCount(orders, STATUS_FAILED);
        while (!current.isAfter(end)) {
            String dateStr = current.format(DAY_FORMATTER);
            DailyStat stat = new DailyStat();
            stat.setDate(dateStr);
            stat.setDailyTotalCount(dailyTotalCountMap.getOrDefault(dateStr, 0L));//每日任务总数量
            stat.setDailyCompletedCount(dailyCompletedMap.getOrDefault(dateStr, 0L)); //每日完成量
            stat.setDailyFailedCount(dailyFailedMap.getOrDefault(dateStr, 0L));//每日失败量
            dailyStats.add(stat);
            current = current.plusDays(1); // 移至下一天
        }
        // 4. 构建并返回完整结果
        return buildAnalysisResult(orders, dailyStats);
    }

    @Override
    public OrderDetailAnalysisResult<List<MonthlyStat>> analyzeByMonthRange(LocalDate start, LocalDate end) {
        // 1. 查询时间范围内的所有订单
        List<OrderDetail> orders = queryOrderDetailByDateRange(start, end);
        if (CollectionUtils.isEmpty(orders)) {
            return buildEmptyResult();
        }

        // 2. 按月分组统计每月订单量
        Map<String, Long> monthlyCountMap = orders.stream()
                .collect(Collectors.groupingBy(
                        order -> {
                            LocalDate localDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                            return localDate.format(MONTH_FORMATTER);
                        },
                        Collectors.counting()
                ));

        // 3. 填充每月统计数据（确保月份连续性）
        List<MonthlyStat> monthlyStats = new ArrayList<>();
        LocalDate current = start.withDayOfMonth(1); // 从当月第一天开始
        LocalDate endMonth = end.withDayOfMonth(1);  // 结束月份第一天
        Map<String, Long> monthlyCompletedMap = calculateMonthlyStatusCount(orders, STATUS_COMPLETED);
        Map<String, Long> monthlyFailedMap = calculateMonthlyStatusCount(orders, STATUS_FAILED);
        while (!current.isAfter(endMonth)) {
            String monthStr = current.format(MONTH_FORMATTER);
            MonthlyStat stat = new MonthlyStat();
            stat.setMonth(monthStr);
            stat.setMonthlyTotalCount(monthlyCountMap.getOrDefault(monthStr, 0L));
            stat.setMonthlyCompletedCount(monthlyCompletedMap.getOrDefault(monthStr, 0L));
            stat.setMonthlyFailedCount(monthlyFailedMap.getOrDefault(monthStr, 0L));
            monthlyStats.add(stat);
            current = current.plusMonths(1); // 移至下一月
        }

        // 4. 构建并返回完整结果
        return buildAnalysisResult(orders, monthlyStats);
    }

    @Override
    public OrderDetailAnalysisResult<List<QuarterlyStat>> analyzeByQuarterRange(LocalDate start, LocalDate end) {
        // 1. 查询时间范围内的所有订单
        List<OrderDetail> orders = queryOrderDetailByDateRange(start, end);
        if (CollectionUtils.isEmpty(orders)) {
            return buildEmptyResult();
        }

        // 2. 按季度分组统计每季度订单量
        Map<String, Long> quarterCountMap = orders.stream()
                .collect(Collectors.groupingBy(
                        order -> {
                            // 将 java.util.Date 转换为 java.time.YearMonth
                            YearMonth yearMonth = YearMonth.from(order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
                            int quarter = (yearMonth.getMonthValue() - 1) / 3 + 1;
                            return yearMonth.format(YEAR_FORMATTER) + "-Q" + quarter;
                        },
                        Collectors.counting()
                ));

        // 3. 填充每季度统计数据（确保季度连续性）
        List<QuarterlyStat> quarterlyStats = new ArrayList<>();
        LocalDate currentQuarterStart = start;
        // 调整至当前季度第一天（如2025-05-10 → 2025-04-01）
        currentQuarterStart = currentQuarterStart.minusMonths((currentQuarterStart.getMonthValue() - 1) % 3);
        currentQuarterStart = currentQuarterStart.withDayOfMonth(1);
        Map<String, Long> quarterlyCompletedMap = calculateQuarterlyStatusCount(orders, STATUS_COMPLETED);
        Map<String, Long> quarterlyFailedMap = calculateQuarterlyStatusCount(orders, STATUS_FAILED);
        while (!currentQuarterStart.isAfter(end)) {
            // 计算当前季度标识（如2025-Q2）
            int quarter = (currentQuarterStart.getMonthValue() - 1) / 3 + 1;
            String quarterStr = currentQuarterStart.format(YEAR_FORMATTER) + "-Q" + quarter;

            QuarterlyStat stat = new QuarterlyStat();
            stat.setQuarter(quarterStr);
            stat.setQuarterlyTotalCount(quarterCountMap.getOrDefault(quarterStr, 0L));
            stat.setQuarterlyCompletedCount(quarterlyCompletedMap.getOrDefault(quarterStr, 0L));
            stat.setQuarterlyFailedCount(quarterlyFailedMap.getOrDefault(quarterStr, 0L));
            quarterlyStats.add(stat);

            // 移至下一季度第一天
            currentQuarterStart = currentQuarterStart.plusMonths(3);
        }

        // 4. 构建并返回完整结果
        return buildAnalysisResult(orders, quarterlyStats);
    }

    @Override
    public OrderDetailAnalysisResult<List<YearlyStat>> analyzeByYearRange(LocalDate start, LocalDate end) {
        // 1. 查询时间范围内的所有订单
        List<OrderDetail> orders = queryOrderDetailByDateRange(start, end);
        if (CollectionUtils.isEmpty(orders)) {
            return buildEmptyResult();
        }

        // 2. 按年分组统计每年订单量
        Map<String, Long> yearCountMap = orders.stream()
                .collect(Collectors.groupingBy(
                        order -> {
                            LocalDate localDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                            return localDate.format(YEAR_FORMATTER);
                        },
                        Collectors.counting()
                ));
        // 3. 填充每年统计数据（确保年份连续性）
        List<YearlyStat> yearlyStats = new ArrayList<>();
        int startYear = start.getYear();
        int endYear = end.getYear();
        Map<String, Long> yearlyCompletedMap = calculateYearlyStatusCount(orders, STATUS_COMPLETED);
        Map<String, Long> yearlyFailedMap = calculateYearlyStatusCount(orders, STATUS_FAILED);
        for (int year = startYear; year <= endYear; year++) {
            String yearStr = String.valueOf(year);
            YearlyStat stat = new YearlyStat();
            stat.setYear(yearStr);
            stat.setYearlyTotalCount(yearCountMap.getOrDefault(yearStr, 0L));
            stat.setYearlyCompletedCount(yearlyCompletedMap.getOrDefault(yearStr, 0L));
            stat.setYearlyFailedCount(yearlyFailedMap.getOrDefault(yearStr, 0L));
            yearlyStats.add(stat);
        }

        // 4. 构建并返回完整结果
        return buildAnalysisResult(orders, yearlyStats);
    }

// ====================== 通用工具方法 ======================

    /**
     * 根据日期范围查询订单
     */
    private List<OrderDetail> queryOrderDetailByDateRange(LocalDate start, LocalDate end) {
        // MyBatis Plus 条件构造器：查询 create_time 在 [start, end] 范围内的订单
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(OrderDetail::getCreateTime, start.atStartOfDay()) // 开始时间：当天00:00:00
                .le(OrderDetail::getCreateTime, end.atTime(23, 59, 59)); // 结束时间：当天23:59:59
        return orderDetailMapper.selectList(queryWrapper);
    }

    /**
     * 构建完整的订单分析结果
     */
    private <T> OrderDetailAnalysisResult<T> buildAnalysisResult(List<OrderDetail> orderDetails, T timeSeriesData) {
        OrderDetailAnalysisResult<T> result = buildOrderDetailAnalysisResult(orderDetails);
        // 时间序列数据（日/月/季/年统计）
        result.setTimeSeriesData(timeSeriesData);
        return result;
    }

    /**
     * 处理任务分析结果
     */
    private <T> OrderDetailAnalysisResult<T> buildOrderDetailAnalysisResult(List<OrderDetail> orderDetails) {
        OrderDetailAnalysisResult<T> result = new OrderDetailAnalysisResult<>();

        // 1. 基础统计指标
        long totalTaskCount = orderDetails.size();
        result.setTotalTaskCount(totalTaskCount);

        // 2. 按状态统计任务数量
        long notStartedCount = countTasksByStatus(orderDetails, STATUS_NOT_STARTED);
        long processingCount = countTasksByStatus(orderDetails, STATUS_PROCESSING);
        long completedCount = countTasksByStatus(orderDetails, STATUS_COMPLETED);
        long failedCount = countTasksByStatus(orderDetails, STATUS_FAILED);

        // 3. 设置状态统计结果
        result.setNotStartedTaskCount(notStartedCount);
        result.setProcessingTaskCount(processingCount);
        result.setCompletedTaskCount(completedCount);
        result.setFailedTaskCount(failedCount);

        // 4. 计算状态比率（保留两位小数）
        BigDecimal total = BigDecimal.valueOf(totalTaskCount);
        result.setNotStartedRate(calculateRate(notStartedCount, total));
        result.setProcessingRate(calculateRate(processingCount, total));
        result.setCompletionRate(calculateRate(completedCount, total));
        result.setFailedRate(calculateRate(failedCount, total));

        // 新增： 计算平均任务周期（单位：分钟）
        double averageTaskCycle = calculateAverageTaskCycle(orderDetails);
        result.setAverageTaskCycle(averageTaskCycle);

        // 新增： 计算今日无人机使用率
        BigDecimal droneUsageRate = calculateTodayDroneUsageRate();
//        时间范围内的无人机使用率
//        BigDecimal droneUsageRate = calculateTodayDroneUsageRate(orderDetails);
        result.setDroneUsageRate(droneUsageRate);

        // 5. 景区路线订单分布
        result.setRouteDistribution(calculateRouteDistribution(orderDetails));

        // 6. 分页信息和订单列表（默认取第一页，每页10条）
        PageInfo pageInfo = buildTaskPageInfo(orderDetails, 1, 10);
        result.setPageInfo(pageInfo);
        result.setOrderDetailList(getPagedTasks(orderDetails, pageInfo));

        // 7. 时间序列数据（在调用此方法的上层设置）
        result.setTimeSeriesData(null);

        return result;
    }

    //计算当日无人机使用率
    private BigDecimal calculateTodayDroneUsageRate() {
        //1. 获取今日订单中出现的无人机数量（去重）
        LocalDate today = LocalDate.now();
        LocalDateTime todayStart = today.atStartOfDay();
        LocalDateTime todayEnd = today.plusDays(1).atStartOfDay();

        QueryWrapper<OrderDetail> orderQueryWrapper = new QueryWrapper<>();
        // 筛选今日创建的订单
        orderQueryWrapper.ge("create_time", todayStart)
                .lt("create_time", todayEnd);

        List<OrderDetail> todayOrders = orderDetailService.list(orderQueryWrapper);

        Set<Long> usedDroneIds = new HashSet<>();
        for (OrderDetail order : todayOrders) {
            Long droneId = order.getDeviceId();
            if (droneId != null) {
                usedDroneIds.add(droneId);
            }
        }
        int usedDroneCount = usedDroneIds.size();


        // 2. 获取无人机总量
        QueryWrapper<AircraftDevice> queryWrapper = new QueryWrapper<>();
        int totalDroneCount = aircraftDeviceService.count(queryWrapper);

        // 3. 计算使用率（保留两位小数）
        if (totalDroneCount == 0) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf((double) usedDroneCount / totalDroneCount)
                .setScale(2, RoundingMode.HALF_UP);
    }

    //计算平均任务周期
    private double calculateAverageTaskCycle(List<OrderDetail> orderDetails) {
        //获取任务数
        List<OrderDetail> completedTasks = orderDetails.stream()
                .filter(task -> task.getOrderItemStatus() == STATUS_COMPLETED)
                .collect(Collectors.toList());
        int completedTaskCount = completedTasks.size();
        if (completedTasks.isEmpty()) {
            return 0.0;
        }
        //获取时间范围内任务的执行总时间：更新时间-创建时间
        long totalSeconds = completedTasks.stream()
                .mapToLong(task ->
                        Duration.between(task.getCreateTime().toInstant(), task.getUpdateTime().toInstant()).getSeconds()
                )
                .sum();

        //平均执行任务时间=总执行任务时间÷总任务数
        return (double) totalSeconds / (60.0 * completedTaskCount);
    }

    //计算时间范围内无人机使用率
    private BigDecimal calculateDroneUsageRate(List<OrderDetail> orderDetails) {
        // 1. 获取时间范围内订单中出现的无人机数量（去重）
        Set<Long> usedDroneIds = orderDetails.stream()
                .filter(task -> task.getDeviceId() != null) // 过滤使用了无人机的任务
                .map(OrderDetail::getDeviceId)
                .collect(Collectors.toSet());
        int usedDroneCount = usedDroneIds.size();

        // 2. 获取无人机总量
        QueryWrapper<AircraftDevice> queryWrapper = new QueryWrapper<>();
        int totalDroneCount = aircraftDeviceService.count(queryWrapper);

        // 3. 计算使用率（保留两位小数）
        if (totalDroneCount == 0) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf((double) usedDroneCount / totalDroneCount)
                .setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 按状态统计时间范围内的任务数量
     */
    private long countTasksByStatus(List<OrderDetail> tasks, Integer status) {
        return tasks.stream()
                .filter(task -> status.equals(task.getOrderItemStatus()))
                .count();
    }

    /**
     * 按日期和状态统计每日订单数量
     */
    private Map<String, Long> calculateDailyStatusCount(List<OrderDetail> orderDetails, Integer status) {
        return orderDetails.stream()
                .filter(order -> order.getOrderItemStatus().equals(status))
                .collect(Collectors.groupingBy(
                        order -> order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(DAY_FORMATTER),
                        Collectors.counting()
                ));
    }

    /**
     * 按月份和状态统计每月订单数量
     */
    private Map<String, Long> calculateMonthlyStatusCount(List<OrderDetail> orderDetails, Integer status) {
        return orderDetails.stream()
                .filter(order -> order.getOrderItemStatus().equals(status))
                .collect(Collectors.groupingBy(
                        order -> order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(MONTH_FORMATTER),
                        Collectors.counting()
                ));
    }

    /**
     * 按季节和状态统计每计季节订单数量
     */
    private Map<String, Long> calculateQuarterlyStatusCount(List<OrderDetail> orderDetails, Integer status) {
        return orderDetails.stream()
                .filter(order -> order.getOrderItemStatus().equals(status))
                .collect(Collectors.groupingBy(
                        order -> order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(QUARTER_FORMATTER),
                        Collectors.counting()
                ));
    }

    /**
     * 按年份和状态统计每计年订单数量
     */
    private Map<String, Long> calculateYearlyStatusCount(List<OrderDetail> orderDetails, Integer status) {
        return orderDetails.stream()
                .filter(order -> order.getOrderItemStatus().equals(status))
                .collect(Collectors.groupingBy(
                        order -> order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(YEAR_FORMATTER),
                        Collectors.counting()
                ));
    }

    /**
     * 计算比率（保留两位小数）
     */
    private BigDecimal calculateRate(long count, BigDecimal total) {
        if (total.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(count)
                .divide(total, 4, BigDecimal.ROUND_HALF_UP) // 中间计算保留4位小数
                .multiply(BigDecimal.valueOf(100))        // 转换为百分比
                .setScale(2, BigDecimal.ROUND_HALF_UP);   // 最终结果保留两位小数
    }

    /**
     * 构建任务分页信息
     */
    private PageInfo buildTaskPageInfo(List<OrderDetail> tasks, int pageNum, int pageSize) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal((long) tasks.size());
        return pageInfo;
    }

    /**
     * 获取分页后的任务列表
     */
    private List<OrderDetail> getPagedTasks(List<OrderDetail> tasks, PageInfo pageInfo) {
        int start = (pageInfo.getPageNum() - 1) * pageInfo.getPageSize();
        int end = Math.min(start + pageInfo.getPageSize(), tasks.size());
        return tasks.subList(start, end);
    }

    /**
     * 将列表按指定大小分割为多个子列表
     *
     * @param list      原始列表
     * @param batchSize 每个子列表的最大大小
     * @return 子列表集合
     */
    private <T> List<List<T>> partitionList(List<T> list, int batchSize) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }

        return IntStream.range(0, (list.size() + batchSize - 1) / batchSize)
                .mapToObj(i -> list.subList(i * batchSize, Math.min((i + 1) * batchSize, list.size())))
                .collect(Collectors.toList());
    }

    /**
     * 计算景区内各路线的任务分布
     */
    public List<RouteStat> calculateRouteDistribution(List<OrderDetail> orderDetails) {
        // 1. 校验输入
        if (CollectionUtils.isEmpty(orderDetails)) {
            return Collections.emptyList();
        }

        // 2. 统计各路线的任务数量（基于子单的routeId字段）
        Map<Long, Long> routeCountMap = orderDetails.stream()
                .filter(detail -> detail.getRouteId() != null) // 过滤掉无路线ID的任务
                .collect(Collectors.groupingBy(
                        OrderDetail::getRouteId, // 按路线ID分组
                        Collectors.counting()    // 统计每组数量
                ));

        // 3. 批量查询路线信息（名称、所属景区）
        List<RouteStat> result = new ArrayList<>();
        if (!routeCountMap.isEmpty()) {
            // 提取所有路线ID
            ArrayList<Long> routeIds = new ArrayList<>(routeCountMap.keySet());

            // 批量查询路线信息（名称、景区ID）
            List<CpRoute> routes = cpRouteMapper.listRoutesByIds(routeIds);
            Map<Long, CpRoute> routeInfoMap = routes.stream()
                    .collect(Collectors.toMap(CpRoute::getId, route -> route));

            // 提取所有景区ID（用于批量查询景区名称）
            Set<Long> scenicIds = routes.stream()
                    .map(CpRoute::getScenicId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            // 批量查询景区名称
            Map<Long, String> scenicNameMap = new HashMap<>();
            if (!scenicIds.isEmpty()) {
                List<EmScenic> scenics = emScenicMapper.listByIds(new ArrayList<>(scenicIds));
                scenicNameMap = scenics.stream()
                        .collect(Collectors.toMap(EmScenic::getId, EmScenic::getName, (existing, replacement) -> existing));
            }
            // 4. 组装结果
            for (Map.Entry<Long, Long> entry : routeCountMap.entrySet()) {
                Long routeId = entry.getKey();
                Long taskCount = entry.getValue();

                RouteStat stat = new RouteStat();
                stat.setRouteId(routeId);
                stat.setCount(taskCount);

                // 设置路线名称和景区名称
                CpRoute route = routeInfoMap.get(routeId);
                if (route != null) {
                    stat.setRouteName(route.getName());
                    Long scenicId = route.getScenicId();
                    if (scenicId != null) {
                        stat.setScenicName(scenicNameMap.getOrDefault(scenicId, "未知景区"));
                    } else {
                        stat.setScenicName("未知景区");
                    }
                } else {
                    // 路线不存在的情况
                    stat.setRouteName("未知路线");
                    stat.setScenicName("未知景区");
                }

                result.add(stat);
            }
        }
        return result;
    }

    /**
     * 构建空结果（无任务时）
     */
    private <T> OrderDetailAnalysisResult<T> buildEmptyResult() {
        OrderDetailAnalysisResult<T> result = new OrderDetailAnalysisResult<>();

        // 任务统计指标
        result.setTotalTaskCount(0L);

        // 分项状态计数
        result.setNotStartedTaskCount(0L);
        result.setProcessingTaskCount(0L);
        result.setCompletedTaskCount(0L);
        result.setFailedTaskCount(0L);

        // 状态比率
        result.setNotStartedRate(BigDecimal.ZERO);
        result.setProcessingRate(BigDecimal.ZERO);
        result.setCompletionRate(BigDecimal.ZERO);
        result.setFailedRate(BigDecimal.ZERO);

        // 路线分布、分页和时间序列数据
        result.setRouteDistribution(Collections.emptyList());
        result.setPageInfo(new PageInfo());
        result.setOrderDetailList(Collections.emptyList());
        result.setTimeSeriesData(null);

        return result;
    }

}
