package com.aps.service.Algorithm;

import com.aps.common.util.ProductionDeepCopyUtil;
import com.aps.entity.Algorithm.OrderSortRule;
import com.aps.entity.basic.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 增强版订单排序服务（最终版：严格匹配条件数格式）
 */
@Slf4j
@Service
public class OrderSortService {

    // 字段提取器映射（静态常量，所有实例共享）
    private static final Map<String, Function<Order, ?>> FIELD_EXTRACTORS = new HashMap<>();

    /**
     * 初始化字段提取器（使用Spring的PostConstruct）
     */
    @PostConstruct
    public void initializeFieldExtractors() {
        registerFieldExtractor("id", Order::getId);


        registerFieldExtractor("startDate", Order -> {
            // 直接返回LocalDate，处理null情况
            return Optional.ofNullable(Order.getStartDate())
                    .map(LocalDateTime::toLocalDate)
                    .orElse(null);
        });
        registerFieldExtractor("dueDate", Order -> {
            // 直接返回LocalDate，处理null情况
            return Optional.ofNullable(Order.getDueDate())
                    .map(LocalDateTime::toLocalDate)
                    .orElse(null);
        });



        registerFieldExtractor("groupStartDate", Order -> {
            // 直接返回LocalDate，处理null情况
            return Optional.ofNullable(Order.getGroupStartDate())
                    .map(LocalDateTime::toLocalDate)
                    .orElse(null);
        });
        registerFieldExtractor("groupDueDate", Order -> {
            // 直接返回LocalDate，处理null情况
            return Optional.ofNullable(Order.getGroupDueDate())
                    .map(LocalDateTime::toLocalDate)
                    .orElse(null);
        });
        registerFieldExtractor("priority", Order::getPriority);
        registerFieldExtractor("materialCode", Order::getMaterialCode);
        registerFieldExtractor("serie", Order::getSerie);
        registerFieldExtractor("orderCode", Order::getOrderCode);
    }

    /**
     * 注册字段提取器（统一处理字段名小写）
     */
    private void registerFieldExtractor(String fieldName, Function<Order, ?> extractor) {
        FIELD_EXTRACTORS.put(fieldName.toLowerCase(), extractor);
    }


    /**
     * 分配优先级（更新原列表）
     */
    public void assignPriority(List<Order> orders, OrderSortRule rule) {
        Objects.requireNonNull(orders, "Orders list must not be null");
        Objects.requireNonNull(rule, "Sort rule must not be null");

        if (CollectionUtils.isEmpty(orders)) {
            return;
        }

        log.debug("[OrderSort] assignPriority start: orderCount={}, enabled={}, conditionCount={}",
                orders.size(),
                rule.isEnabled(),
                rule.getConditions() == null ? 0 : rule.getConditions().size());

        List<Order> sortedOrders = assignPriorityValues(new ArrayList<>(orders), rule);
        orders.clear();
        orders.addAll(sortedOrders);
    }

    /**
     * 计算两个订单之间的换线成本
     */
    private double calculateChangeoverCost(Order order1, Order order2) {
        if (order1 == null || order2 == null) {
            return Double.MAX_VALUE;
        }

        double cost = 0.0;

        // 1. 工艺路线不同，增加换线成本
        if (!Objects.equals(order1.getRoutingId(), order2.getRoutingId())) {
            cost += 100.0;
        }

        // 2. 物料系列不同，增加换线成本
        if (!Objects.equals(order1.getSerie(), order2.getSerie())) {
            cost += 50.0;
        }

        // 3. 物料代码不同，增加换线成本
        if (!Objects.equals(order1.getMaterialCode(), order2.getMaterialCode())) {
            cost += 25.0;
        }

        return cost;
    }
    /**
     * 基于最小化换线成本的排序
     */
    private List<Order> sortByMinimizeChangeover(List<Order> orders) {
        if (CollectionUtils.isEmpty(orders)) {
            return new ArrayList<>();
        }

        // 定义阈值：当订单数量小于等于这个值时，遍历所有起始点
        int threshold = 10;

        if (orders.size() <= threshold) {
            // 订单数量较少，遍历所有起始点
            return sortByMinimizeChangeoverWithAllStarts(orders);
        } else {
            // 订单数量较多，使用局部搜索
            return sortByMinimizeChangeoverWithLocalSearch(orders);
        }
    }
    /**
     * 基于遍历所有起始点的最小化换线排序
     */
    private List<Order> sortByMinimizeChangeoverWithAllStarts(List<Order> orders) {
        if (CollectionUtils.isEmpty(orders)) {
            return new ArrayList<>();
        }



        List<Map.Entry<List<Order>, Double>> results = IntStream.range(0, orders.size())
                .parallel()
                .mapToObj(i -> {
                    List<Order> sortedOrders= generateInitialSolution(ProductionDeepCopyUtil.deepCopyList(orders) ,i);
                    // 计算总换线成本
                    double totalCost = calculateTotalChangeoverCost(sortedOrders);
                    return new AbstractMap.SimpleEntry<>(sortedOrders, totalCost);
                })
                .collect(Collectors.toList());

        List<Order> bestSortedOrders = null;
        double minTotalCost = Double.MAX_VALUE;

        for (Map.Entry<List<Order>, Double> entry : results) {
            if (entry.getValue() < minTotalCost) {
                minTotalCost = entry.getValue();
                bestSortedOrders = entry.getKey();
            }
        }

        return bestSortedOrders;
    }




    /**
     * 基于局部搜索的最小化换线排序
     */
    private List<Order> sortByMinimizeChangeoverWithLocalSearch(List<Order> orders) {
        if (CollectionUtils.isEmpty(orders)) {
            return new ArrayList<>();
        }

        // 1. 生成多个初始解，选择最优的一个


        // 尝试多个随机起始点
        Set<Integer> selectedIndices = new HashSet<>();
        Random random = new Random();
        int maxAttempts = Math.min(5, orders.size());

        while (selectedIndices.size() < maxAttempts) {
            int randomIndex = random.nextInt(orders.size());
            selectedIndices.add(randomIndex);
        }
        List<Map.Entry<List<Order>, Double>> initialSolutions = selectedIndices.parallelStream()
                .map(index -> {
                    List<Order> initialSolution = generateInitialSolution(ProductionDeepCopyUtil.deepCopyList(orders), index);
                    double initialCost = calculateTotalChangeoverCost(initialSolution);
                    return new AbstractMap.SimpleEntry<>(initialSolution, initialCost);
                })
                .collect(Collectors.toList());

        // 选择最优初始解
        List<Order> bestInitialSolution = null;
        double bestInitialCost = Double.MAX_VALUE;

        for (Map.Entry<List<Order>, Double> entry : initialSolutions) {
            if (entry.getValue() < bestInitialCost) {
                bestInitialCost = entry.getValue();
                bestInitialSolution = entry.getKey();
            }
        }

        List<Order> currentSolution = bestInitialSolution != null ? bestInitialSolution : generateInitialSolution(orders,0);
        double currentCost = bestInitialCost;

        // 2. 局部搜索（允许所有相邻订单交换）
        boolean improved;
        int maxIterations = 50;
        int iteration = 0;

//        do {
//            improved = false;
//            List<Order> bestNeighbor = new ArrayList<>(currentSolution);
//            double bestNeighborCost = currentCost;
//
//            // 遍历所有相邻订单对，尝试交换
//            for (int i = 0; i < currentSolution.size() - 1; i++) {
//                // 交换相邻订单
//                List<Order> neighbor = new ArrayList<>(currentSolution);
//                Collections.swap(neighbor, i, i + 1);
//
//
//                double neighborCost = calculateTotalChangeoverCost2(neighbor);
//
//                // 如果交换后成本更低，更新最佳邻居
//                if (neighborCost < bestNeighborCost) {
//                    bestNeighbor = neighbor;
//                    bestNeighborCost = neighborCost;
//                    improved = true;
//                }
//            }
//
//            // 如果找到更优解，更新当前解
//            if (improved) {
//                currentSolution = bestNeighbor;
//              //  assignChangeoverPriority(currentSolution);
//                currentCost = bestNeighborCost;
//            }
//
//            iteration++;
//        } while (improved && iteration < maxIterations);

        do {
            improved = false;
            List<Order> bestNeighbor = new ArrayList<>(currentSolution);
            double bestNeighborCost = currentCost;

            // 并行处理邻域搜索
            List<Order> finalCurrentSolution = currentSolution;
            List<Map.Entry<List<Order>, Double>> neighbors = IntStream.range(0, currentSolution.size() - 1)
                    .parallel()
                    .mapToObj(i -> {
                        // 交换相邻订单
                        List<Order> neighbor = new ArrayList<>(finalCurrentSolution);
                        Collections.swap(neighbor, i, i + 1);

                        double neighborCost = calculateTotalChangeoverCost2(neighbor);
                        return new AbstractMap.SimpleEntry<>(neighbor, neighborCost);
                    })
                    .collect(Collectors.toList());

            // 找到最佳邻居
            for (Map.Entry<List<Order>, Double> entry : neighbors) {
                if (entry.getValue() < bestNeighborCost) {
                    bestNeighbor = entry.getKey();
                    bestNeighborCost = entry.getValue();
                    improved = true;
                }
            }

            // 如果找到更优解，更新当前解
            if (improved) {
                currentSolution = bestNeighbor;
                currentCost = bestNeighborCost;
            }

            iteration++;
        } while (improved && iteration < maxIterations);


        return currentSolution;
    }
    /**
     * 计算订单序列的总换线成本
     */
    /**
     * 计算订单序列的总换线成本（考虑ChangeoverPriority分组）
     */
    private double calculateTotalChangeoverCost2(List<Order> orders) {
        if (CollectionUtils.isEmpty(orders) || orders.size() <= 1) {
            return 0.0;
        }

        double totalCost = 0.0;

        // 首先为订单分配ChangeoverPriority
        assignChangeoverPriority(orders);


        totalCost=calculateTotalChangeoverCost(orders);
        return totalCost;
    }

    /**
     * 生成初始解（使用贪心算法）
     */
    private List<Order> generateInitialSolution(List<Order> orders,int i) {
            if (CollectionUtils.isEmpty(orders)) {
                return new ArrayList<>();
            }

            List<Order> sortedOrders = new ArrayList<>();
            List<Order> remainingOrders = new ArrayList<>(orders);

            // 选择第一个订单作为起始点
            Order currentOrder = remainingOrders.remove(i);
            currentOrder.setChangeoverPriority(1);
            sortedOrders.add(currentOrder);
            int priority=2;
            // 每次选择与当前最后一个订单换线成本最低的订单
            while (!remainingOrders.isEmpty()) {
                double minCost = Double.MAX_VALUE;
                List<Order> bestOrders = new ArrayList<>();

                // 找到换线成本最低的所有订单
                for (Order order : remainingOrders) {
                    double cost = calculateChangeoverCost(currentOrder, order);

                    if (cost < minCost) {
                        minCost = cost;
                        order.setChangeoverCost(cost);
                        if(minCost==0){
                            order.setChangeoverPriority(currentOrder.getChangeoverPriority());
                        }else {
                            order.setChangeoverPriority(priority);
                        }
                        bestOrders.clear();
                        bestOrders.add(order);
                    } else if (cost == minCost) {
                        order.setChangeoverCost(cost);
                        if(minCost==0){
                            order.setChangeoverPriority(currentOrder.getChangeoverPriority());
                        }else {
                            order.setChangeoverPriority(priority);
                        }
                        bestOrders.add(order);
                    }
                }

                // 如果有多个成本相同的订单，将它们作为一组添加
                if (!bestOrders.isEmpty()) {
                    sortedOrders.addAll(bestOrders);
                    remainingOrders.removeAll(bestOrders);
                    // 更新当前订单为最后添加的订单
                    currentOrder = bestOrders.get(bestOrders.size() - 1);
                    if(minCost!=0) {
                        priority++;
                    }
                } else {
                    // 以防万一，添加剩余的第一个订单
                    Order nextOrder = remainingOrders.remove(0);
                    sortedOrders.add(nextOrder);
                    currentOrder = nextOrder;
                    if(minCost!=0) {
                        priority++;
                    }
                }
            }

            return sortedOrders;
        }


    /**
     * 为排序后的订单分配ChangeoverPriority
     */
    private void assignChangeoverPriority(List<Order> orders) {
        if (CollectionUtils.isEmpty(orders)) {
            return;
        }

        int priority = 1;
        orders.get(0).setChangeoverPriority(priority);

        for (int i = 1; i < orders.size(); i++) {
            double cost = calculateChangeoverCost(orders.get(i - 1), orders.get(i));

            if (cost > 0) {//成本为0 ，则在同一级
                priority++;
                orders.get(i).setChangeoverCost(cost);
            }else {
                orders.get(i).setChangeoverCost(orders.get(i - 1).getChangeoverCost());
            }
            orders.get(i).setChangeoverPriority(priority);
        }
    }

    /**
     * 计算订单序列的总换线成本
     */
    private double calculateTotalChangeoverCost(List<Order> orders) {
        if (CollectionUtils.isEmpty(orders) || orders.size() <= 1) {
            return 0.0;
        }

        double totalCost = 0.0;
        // 001>002  2 cost 75
        // 001>003  2 cost 75
        //有一点问题，相同ChangeoverPriority 直接换型应该是0,002>003, 然而对象中存的是，
        // 001>002，001>003 ，所以相同ChangeoverPriority 不加成本了
        // 只计算不同优先级组之间的换线成本
        for (int i = 0; i < orders.size() - 1; i++) {
            Order currentOrder = orders.get(i);
            Order nextOrder = orders.get(i + 1);

            // 只有当两个订单的ChangeoverPriority不同时，才计算换线成本
            if (currentOrder.getChangeoverPriority() != nextOrder.getChangeoverPriority()) {
                totalCost += orders.get(i + 1).getChangeoverCost();
            }
        }
        return totalCost;
    }



    /**
     * 处理排序条件，支持在任意位置应用最小化换线策略
     */
    private void processConditionsWithMinimizeChangeover(List<Order> orders,
                                                         List<OrderSortRule.SortCondition> conditions,
                                                         int conditionIndex,
                                                         Map<String, List<Integer>> priorityPaths) {
        // 递归终止：处理完所有条件后停止
        if (conditionIndex >= conditions.size() || CollectionUtils.isEmpty(orders)) {
            return;
        }

        OrderSortRule.SortCondition currentCondition = conditions.get(conditionIndex);

        // 检查是否是最小化换线策略
        if ("minimize_changeover".equals(currentCondition.getFieldName())) {
            // 应用最小化换线策略
            List<Order> optimizedOrders = sortByMinimizeChangeover(orders);

            // ========== 换线明细日志 ==========
            double totalCost = 0.0;
            StringBuilder costLog = new StringBuilder();
            costLog.append("[换线明细] 序列顺序：\n");
            for (int i = 0; i < optimizedOrders.size(); i++) {
                Order order = optimizedOrders.get(i);
                double costToPrev = (i == 0) ? 0.0 : calculateChangeoverCost(optimizedOrders.get(i - 1), order);
                StringBuilder flags = new StringBuilder();
                if (i > 0) {
                    Order prev = optimizedOrders.get(i - 1);
                    if (!Objects.equals(prev.getRoutingId(), order.getRoutingId())) flags.append("routing变 ");
                    if (!Objects.equals(prev.getSerie(), order.getSerie())) flags.append("serie变 ");
                    if (!Objects.equals(prev.getMaterialCode(), order.getMaterialCode())) flags.append("material变");
                }
//                costLog.append(String.format("  %2d. %s, routingId=%s, serie=%s, materialCode=%s, cost=%.0f %s\n",
//                        (i + 1),
//                        order.getOrderCode(),
//                        order.getRoutingId(),
//                        order.getSerie(),
//                        order.getMaterialCode(),
//                        costToPrev,
//                        flags.toString()));
                totalCost += costToPrev;
            }
           // costLog.append(String.format("[换线明细] 总换线成本 = %.0f\n", totalCost));
          //  log.debug(costLog.toString());
            // ==================================

            // 为最小化换线后的订单分配层级序号
            // 相同成本的订单分配相同的序号

            for (Order order : optimizedOrders) {
                priorityPaths.get(order.getOrderId()).add(order.getChangeoverPriority());
            }

            // 按优先级分组顺序处理
            Map<Integer, List<Order>> priorityGroups = new HashMap<>();
            for (Order order : optimizedOrders) {
                int priority = order.getChangeoverPriority();
                priorityGroups.computeIfAbsent(priority, k -> new ArrayList<>()).add(order);
            }

            List<Integer> sortedPriorities = priorityGroups.keySet().stream()
                    .sorted()
                    .collect(Collectors.toList());

            for (Integer priority : sortedPriorities) {
                List<Order> groupOrders = priorityGroups.get(priority);
                // 递归处理下一个条件
                processConditionsWithMinimizeChangeover(groupOrders, conditions, conditionIndex + 1, priorityPaths);
            }

            // 递归处理下一个条件
          //  processConditionsWithMinimizeChangeover(optimizedOrders, conditions, conditionIndex + 1, priorityPaths);
        } else {
            // 处理普通排序条件
            String fieldName = currentCondition.getFieldName();
            Function<Order, ?> keyExtractor = getFieldExtractor(fieldName);

            if (keyExtractor == null) {
                log.warn("跳过无效排序字段：{}", currentCondition.getFieldName());
                processConditionsWithMinimizeChangeover(orders, conditions, conditionIndex + 1, priorityPaths);
                return;
            }

            // 1. 按当前条件分组 处理null键
            Map<Object, List<Order>> groups = new HashMap<>();
            orders.forEach(order -> {
                Object key = keyExtractor.apply(order);
                groups.computeIfAbsent(key, k -> new ArrayList<>()).add(order);
            });

            // 2. 对分组键排序（关键：按条件配置的方向排序）
            List<Object> sortedKeys = getSortedKeys(groups, currentCondition);

            // 3. 为每个分组分配层级序号（从1开始）
            for (int groupIndex = 0; groupIndex < sortedKeys.size(); groupIndex++) {
                Object key = sortedKeys.get(groupIndex);
                List<Order> groupOrders = groups.get(key);

                // 分配当前层级序号（1、2、3...）
                int levelNumber = groupIndex + 1;
                groupOrders.forEach(order -> priorityPaths.get(order.getOrderId()).add(levelNumber));

                // 递归处理下一级条件
                processConditionsWithMinimizeChangeover(groupOrders, conditions, conditionIndex + 1, priorityPaths);
            }
        }
    }


    private List<Order> sortWithConfiguredStrategy(List<Order> orders, OrderSortRule rule) {
//        if (rule.getConditions().size()==1&&rule.getConditions().get(0).getFieldName().equals("minimize_changeover")) {
//            return sortByMinimizeChangeover(orders);
//        }

        List<Order> currentOrders = new ArrayList<>(orders);
        List<OrderSortRule.SortCondition> conditions = rule.getConditions().stream()
                .sorted(Comparator.comparingInt(OrderSortRule.SortCondition::getSequence))
                .collect(Collectors.toList());

        // 为每个订单初始化优先级路径
        Map<String, List<Integer>> priorityPaths = new HashMap<>();
        currentOrders.forEach(order -> priorityPaths.put(order.getOrderId(), new ArrayList<>()));

        // 处理排序条件
        processConditionsWithMinimizeChangeover(currentOrders, conditions, 0, priorityPaths);

        return applyPriorityFromPaths(currentOrders, priorityPaths);
    }

    /**
     * 根据数据库配置的规则对订单排序
     */
    public List<Order> sortByRule(List<Order> orders, OrderSortRule rule) {
        Objects.requireNonNull(orders, "Orders list must not be null");
        Objects.requireNonNull(rule, "Sort rule must not be null");

        if (CollectionUtils.isEmpty(orders)) {
            return new ArrayList<>();
        }

        if (rule == null || !rule.isEnabled() || CollectionUtils.isEmpty(rule.getConditions())) {
            return new ArrayList<>(orders);
        }

        List<OrderSortRule.SortCondition> sortedConditions = rule.getConditions().stream()
                .sorted(Comparator.comparingInt(OrderSortRule.SortCondition::getSequence))
                .collect(Collectors.toList());

        Comparator<Order> comparator = null;
        for (OrderSortRule.SortCondition condition : sortedConditions) {
            Comparator<Order> currentComparator = createConditionComparator(condition);
            comparator = comparator == null ? currentComparator : comparator.thenComparing(currentComparator);
        }

        return orders.stream()
                .sorted(comparator != null ? comparator : Comparator.comparing(Order::getId))
                .collect(Collectors.toList());
    }

    /**
     * 分配层级化序号式优先级（严格匹配条件数格式）
     */
    public List<Order> assignPriorityValues(List<Order> orders, OrderSortRule rule) {
        Objects.requireNonNull(orders, "Orders list must not be null");
        Objects.requireNonNull(rule, "Sort rule must not be null");

        if (CollectionUtils.isEmpty(orders)) {
            return new ArrayList<>();
        }

        if (rule == null || !rule.isEnabled() || CollectionUtils.isEmpty(rule.getConditions())) {
            return new ArrayList<>(orders);
        }

        boolean hasMinimizeChangeover = rule.getConditions().stream()
                .anyMatch(condition -> "minimize_changeover".equals(condition.getFieldName()));


        if (hasMinimizeChangeover) {

                // 仅使用最小化换线策略

            return sortWithConfiguredStrategy(orders,rule);

        } else {
            // 按条件顺序排序（sequence越小越先执行）
            List<OrderSortRule.SortCondition> sortedConditions = rule.getConditions().stream()
                    .sorted(Comparator.comparingInt(OrderSortRule.SortCondition::getSequence))
                    .collect(Collectors.toList());

            // 为每个订单初始化优先级路径
            Map<String, List<Integer>> priorityPaths = new HashMap<>();
            orders.forEach(order -> priorityPaths.put(order.getOrderId(), new ArrayList<>()));

            // 递归分配层级化优先级（核心逻辑）
            assignHierarchicalPriority(orders, sortedConditions, 0, priorityPaths);

            List<Order> orders1 = applyPriorityFromPaths(orders, priorityPaths);

            // ========== 订单优先级信息（debug）==========
            log.debug("[OrderSort] ========== 订单优先级信息 ==========");
            for (Order order : orders1) {
                log.debug("[OrderSort] 订单编码：{}, 开始时间：{}, 结束时间：{}, 真实优先级：{}, sortKey：{}",
                        order.getOrderCode(),
                        order.getStartDate(),
                        order.getDueDate(),
                        order.getActualPriority(),
                        order.getSortKey());
            }
            log.debug("[OrderSort] ====================================");
            // ==========================================

            return orders1;
        }
    }

    /**
     * 递归分配层级化优先级路径
     */
    private void assignHierarchicalPriority(List<Order> orders,
                                            List<OrderSortRule.SortCondition> conditions,
                                            int conditionIndex,
                                            Map<String, List<Integer>> priorityPaths) {
        // 递归终止：处理完所有条件后停止，不再添加额外序号
        if (conditionIndex >= conditions.size() || CollectionUtils.isEmpty(orders)) {
            return;
        }

        OrderSortRule.SortCondition currentCondition = conditions.get(conditionIndex);
        String fieldName = currentCondition.getFieldName();

        Function<Order, ?> keyExtractor = getFieldExtractor(fieldName);
        if (keyExtractor == null) {
            log.warn("跳过无效排序字段：{}", currentCondition.getFieldName());
            assignHierarchicalPriority(orders, conditions, conditionIndex + 1, priorityPaths);
            return;
        }

        // 1. 按当前条件分组 处理null键
        Map<Object, List<Order>> groups = new HashMap<>();
        orders.forEach(order -> {
            Object key = keyExtractor.apply(order);
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(order);
        });

        // 2. 对分组键排序（关键：按条件配置的方向排序）
        List<Object> sortedKeys = getSortedKeys(groups, currentCondition);

        // 3. 为每个分组分配层级序号（从1开始）
        for (int groupIndex = 0; groupIndex < sortedKeys.size(); groupIndex++) {
            Object key = sortedKeys.get(groupIndex);
            List<Order> groupOrders = groups.get(key);

            // 分配当前层级序号（1、2、3...）
            int levelNumber = groupIndex + 1;
            groupOrders.forEach(order -> priorityPaths.get(order.getOrderId()).add(levelNumber));

            // 递归处理下一级条件
            assignHierarchicalPriority(groupOrders, conditions, conditionIndex + 1, priorityPaths);
        }
    }

    /**
     * 路径转数值：拼接式小数编码
     * [1, 1, 1] → 1.11
     * [1, 1, 20] → 1.120
     * [1, 20, 20] → 1.2020
     *
     * 注意：此编码假设每层分组数不超过9（或不会连续出现导致歧义的组合）
     * 如 [1,12,3] 和 [1,1,23] 都会变成 1.123，会冲突！
     */
    private void convertPriorityPathsToNumeric(List<Order> orders, Map<String, List<Integer>> priorityPaths) {
        for (Order order : orders) {
            List<Integer> path = priorityPaths.get(order.getOrderId());
            if (CollectionUtils.isEmpty(path)) {
                order.setActualPriority(0.0);
                continue;
            }

            try {
                // 第一部分作为整数
                StringBuilder sb = new StringBuilder();
                sb.append(path.get(0));

                // 后续部分直接拼接，不补零
                if (path.size() > 1) {
                    sb.append(".");
                    for (int i = 1; i < path.size(); i++) {
                        sb.append(path.get(i));
                    }
                }

                // 转换为double
                order.setActualPriority(Double.parseDouble(sb.toString()));

            } catch (NumberFormatException e) {
                log.error("优先级格式转换失败：{} → {}", path, e.getMessage());
                order.setActualPriority(0.0);
            }
        }
    }

    /**
     * 将 priorityPaths 应用到订单：写入 sortKey，字典序排序，赋整数 actualPriority
     */
    private List<Order> applyPriorityFromPaths(List<Order> orders, Map<String, List<Integer>> priorityPaths) {
        // Step1: 写入 sortKey
        orders.forEach(order -> order.setSortKey(priorityPaths.get(order.getOrderId())));
        // Step2: 按 sortKey 字典序排序
        orders.sort((o1, o2) -> {
            List<Integer> p1 = o1.getSortKey();
            List<Integer> p2 = o2.getSortKey();
            if (p1 == null && p2 == null) return 0;
            if (p1 == null) return 1;
            if (p2 == null) return -1;
            for (int i = 0; i < Math.min(p1.size(), p2.size()); i++) {
                int cmp = Integer.compare(p1.get(i), p2.get(i));
                if (cmp != 0) return cmp;
            }
            return Integer.compare(p1.size(), p2.size());
        });
        // Step3: 赋整数排名，相同 sortKey 赋相同值
        int rank = 1;
        for (int i = 0; i < orders.size(); i++) {
            if (i > 0) {
                List<Integer> prevKey = orders.get(i - 1).getSortKey();
                List<Integer> currKey = orders.get(i).getSortKey();
                boolean same = (prevKey == null && currKey == null)
                        || (prevKey != null && currKey != null && prevKey.equals(currKey));
                if (!same) {
                    rank++;
                }
            }
            orders.get(i).setActualPriority(rank);
        }
        return orders;
    }

    /**
     * 创建单个条件的比较器
     */
    @SuppressWarnings("unchecked")
    private Comparator<Order> createConditionComparator(OrderSortRule.SortCondition condition) {
        Objects.requireNonNull(condition, "Sort condition must not be null");

        String fieldName = condition.getFieldName();
        // 不再替换为dueDateOnly，直接使用原字段名

        Function<Order, ?> keyExtractor = getFieldExtractor(fieldName);
        if (keyExtractor == null) {
            log.warn("无字段提取器：{}，使用ID排序", condition.getFieldName());
            return Comparator.comparing(Order::getId);
        }

        Comparator<Object> fieldComparator = getFieldComparator(condition, fieldName);
        return (Comparator<Order>) Comparator.comparing(keyExtractor, fieldComparator);
    }

    /**
     * 获取字段比较器（支持reverse参数）
     */
    @SuppressWarnings("unchecked")
    private Comparator<Object> getFieldComparator(OrderSortRule.SortCondition condition, String actualFieldName) {
        Objects.requireNonNull(condition, "Sort condition must not be null");

        // 自定义比较器优先
        if (condition.getCustomComparator() != null && !condition.getCustomComparator().isEmpty()) {
            try {
                Class<?> clazz = Class.forName(condition.getCustomComparator());
                Method method = clazz.getMethod("getInstance");
                return (Comparator<Object>) method.invoke(null);
            } catch (Exception e) {
                log.error("自定义比较器加载失败：{}", condition.getCustomComparator(), e);
            }
        }

        // 按字段类型返回比较器
        Function<Order, ?> extractor = getFieldExtractor(actualFieldName);
        if (extractor == null) {
            Comparator<Object> defaultComparator = Comparator.comparing(Object::toString);
            return condition.isReverse() ? defaultComparator.reversed() : defaultComparator;
        }

        try {
            Order sample = new Order();
            Object sampleValue = extractor.apply(sample);

            // 布尔类型排序（支持reverse参数）
            if (sampleValue instanceof Boolean) {
                Comparator<Object> booleanComparator = (Comparator<Object>) (o1, o2) -> {
                    boolean b1 = (Boolean) o1;
                    boolean b2 = (Boolean) o2;
                    return Boolean.compare(b1, b2);
                };

                return condition.isReverse() ? booleanComparator.reversed() : booleanComparator;
            }
            // 日期类型：按时间排序
            else if (sampleValue instanceof LocalDate) {
                Comparator<Object> dateComparator = (Comparator<Object>) Comparator.comparing(o -> (LocalDate) o);
                return condition.isReverse() ? dateComparator.reversed() : dateComparator;
            }
            // 整数类型
            else if (sampleValue instanceof Integer) {
                Comparator<Object> intComparator = (Comparator<Object>) Comparator.comparingInt(o -> (Integer) o);
                return condition.isReverse() ? intComparator.reversed() : intComparator;
            }
            // 长整型
            else if (sampleValue instanceof Long) {
                Comparator<Object> longComparator = (Comparator<Object>) Comparator.comparingLong(o -> (Long) o);
                return condition.isReverse() ? longComparator.reversed() : longComparator;
            }
            // 日期时间类型
            else if (sampleValue instanceof OffsetDateTime) {
                Comparator<Object> dateTimeComparator = (Comparator<Object>) Comparator.comparing(o -> (OffsetDateTime) o);
                return condition.isReverse() ? dateTimeComparator.reversed() : dateTimeComparator;
            }
        } catch (Exception e) {
            log.debug("字段类型推断失败：{}", actualFieldName, e);
        }

        // 默认比较器
        Comparator<Object> defaultComparator = Comparator.comparing(Object::toString);
        return condition.isReverse() ? defaultComparator.reversed() : defaultComparator;
    }

    /**
     * 获取排序后的分组键
     */
    private List<Object> getSortedKeys(Map<Object, List<Order>> groups,
                                       OrderSortRule.SortCondition condition) {
        Objects.requireNonNull(groups, "Groups map must not be null");
        Objects.requireNonNull(condition, "Sort condition must not be null");

        String fieldName = condition.getFieldName();

        Comparator<Object> comparator = getFieldComparator(condition, fieldName);
        return groups.keySet().stream()
                .sorted(comparator)
                .collect(Collectors.toList());
    }

    /**
     * 获取字段提取器
     */
    private Function<Order, ?> getFieldExtractor(String fieldName) {
        return fieldName == null ? null : FIELD_EXTRACTORS.get(fieldName.toLowerCase());
    }

    /**
     * 获取格式化的优先级字符串
     */
    public String getFormattedPriority(double actualPriority) {
        return String.valueOf(actualPriority);
    }
}