package com.aiotagro.cattletrade.business.service.impl;

import com.aiotagro.cattletrade.business.entity.Delivery;
import com.aiotagro.cattletrade.business.entity.Order;
import com.aiotagro.cattletrade.business.entity.SalesOverview;
import com.aiotagro.cattletrade.business.mapper.DeliveryMapper;
import com.aiotagro.cattletrade.business.mapper.MemberMapper;
import com.aiotagro.cattletrade.business.mapper.OrderMapper;
import com.aiotagro.cattletrade.business.mapper.SalesOverviewMapper;
import com.aiotagro.cattletrade.business.service.ISalesOverviewService;
import com.aiotagro.common.core.utils.StringUtils;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 销售概览服务实现类
 *
 * @author System
 * @date 2025-01-20
 */
@Service
public class SalesOverviewServiceImpl extends ServiceImpl<SalesOverviewMapper, SalesOverview> implements ISalesOverviewService {

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

    @Autowired
    private SalesOverviewMapper salesOverviewMapper;

    @Autowired
    private DeliveryMapper deliveryMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MemberMapper memberMapper;

    /**
     * 分页查询销售概览列表
     */
    @Override
    public PageResultResponse<SalesOverview> pageQuery(Map<String, Object> params) {
        Integer pageNum = params.get("pageNum") != null ? (Integer) params.get("pageNum") : 1;
        Integer pageSize = params.get("pageSize") != null ? (Integer) params.get("pageSize") : 10;

        logger.info("分页查询销售概览列表，页码：{}，每页数量：{}", pageNum, pageSize);

        PageHelper.startPage(pageNum, pageSize);
        LambdaQueryWrapper<SalesOverview> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(SalesOverview::getCreateTime);

        List<SalesOverview> list = this.list(queryWrapper);
        long total = this.count(queryWrapper);

        logger.info("查询成功，共{}条记录", total);

        return new PageResultResponse<>(total, list);
    }

    /**
     * 新增销售概览
     */
    @Override
    @Transactional
    public AjaxResult addSalesOverview(SalesOverview salesOverview) {
        try {
            logger.info("新增销售概览");

            Date now = new Date();

            salesOverview.setCreateTime(now);
            salesOverview.setUpTime(now);

            int result = salesOverviewMapper.insert(salesOverview);
            if (result > 0) {
                logger.info("新增销售概览成功，ID：{}", salesOverview.getId());
                return AjaxResult.success("新增成功", salesOverview);
            } else {
                logger.error("新增销售概览失败：插入数据库失败");
                return AjaxResult.error("新增失败");
            }
        } catch (Exception e) {
            logger.error("新增销售概览失败：{}", e.getMessage(), e);
            return AjaxResult.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 更新销售概览信息
     */
    @Override
    @Transactional
    public AjaxResult updateSalesOverview(SalesOverview salesOverview) {
        try {
            logger.info("更新销售概览，ID：{}", salesOverview.getId());

            if (salesOverview.getId() == null) {
                logger.error("更新失败：销售概览ID不能为空");
                return AjaxResult.error("销售概览ID不能为空");
            }

            SalesOverview existing = this.getById(salesOverview.getId());
            if (existing == null) {
                logger.error("更新失败：销售概览不存在，ID：{}", salesOverview.getId());
                return AjaxResult.error("销售概览不存在");
            }

            salesOverview.setUpTime(new Date());

            boolean result = this.updateById(salesOverview);
            if (result) {
                logger.info("更新销售概览成功，ID：{}", salesOverview.getId());
                return AjaxResult.success("更新成功", salesOverview);
            } else {
                logger.error("更新销售概览失败：更新数据库失败");
                return AjaxResult.error("更新失败");
            }
        } catch (Exception e) {
            logger.error("更新销售概览失败：{}", e.getMessage(), e);
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除销售概览
     */
    @Override
    @Transactional
    public AjaxResult deleteSalesOverview(Integer id) {
        try {
            logger.info("删除销售概览，ID：{}", id);

            if (id == null) {
                logger.error("删除失败：销售概览ID不能为空");
                return AjaxResult.error("销售概览ID不能为空");
            }

            SalesOverview existing = this.getById(id);
            if (existing == null) {
                logger.error("删除失败：销售概览不存在，ID：{}", id);
                return AjaxResult.error("销售概览不存在");
            }

            boolean result = this.removeById(id);
            if (result) {
                logger.info("删除销售概览成功，ID：{}", id);
                return AjaxResult.success("删除成功");
            } else {
                logger.error("删除销售概览失败：删除数据库失败");
                return AjaxResult.error("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除销售概览失败：{}", e.getMessage(), e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 查询销售概览详情
     */
    @Override
    public AjaxResult getSalesOverviewDetail(Integer id) {
        try {
            logger.info("查询销售概览详情，ID：{}", id);

            if (id == null) {
                logger.error("查询失败：销售概览ID不能为空");
                return AjaxResult.error("销售概览ID不能为空");
            }

            SalesOverview salesOverview = this.getById(id);
            if (salesOverview == null) {
                logger.error("查询失败：销售概览不存在，ID：{}", id);
                return AjaxResult.error("销售概览不存在");
            }

            return AjaxResult.success("查询成功", salesOverview);
        } catch (Exception e) {
            logger.error("查询销售概览详情失败：{}", e.getMessage(), e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 计算统计数据并保存
     */
    @Override
    @Transactional
    public AjaxResult calculateStatistics() {
        try {
            logger.info("开始计算销售概览统计数据");

            // 查询所有有订单关联的delivery（order_id不为空）
            LambdaQueryWrapper<Delivery> deliveryWrapper = new LambdaQueryWrapper<>();
            deliveryWrapper.isNotNull(Delivery::getOrderId);
            deliveryWrapper.ne(Delivery::getOrderId, "");
            List<Delivery> deliveries = deliveryMapper.selectList(deliveryWrapper);

            logger.info("查询到{}个有订单关联的运送清单", deliveries.size());

            BigDecimal totalProcurementAmount = BigDecimal.ZERO; // 采购总额
            BigDecimal totalSalesAmount = BigDecimal.ZERO; // 销售总额
            BigDecimal totalAccountsReceivable = BigDecimal.ZERO; // 应收货款总额
            BigDecimal totalActualPayment = BigDecimal.ZERO; // 实收货款总额
            int totalPurchase = 0; // 采购数量（头）
            int totalOrder = 0; // 采购单数（车）
            int totalSales = 0; // 销售单数（单）

            // 遍历每个delivery计算金额
            for (Delivery delivery : deliveries) {
                try {
                    String orderIdStr = delivery.getOrderId();
                    if (StringUtils.isEmpty(orderIdStr)) {
                        logger.warn("运送清单{}的order_id为空，跳过", delivery.getId());
                        continue;
                    }

                    // 解析订单ID列表
                    List<Integer> orderIds = Arrays.stream(orderIdStr.split(","))
                            .map(String::trim)
                            .filter(s -> !s.isEmpty())
                            .map(Integer::parseInt)
                            .collect(Collectors.toList());

                    if (orderIds.isEmpty()) {
                        logger.warn("运送清单{}的order_id解析后为空，跳过", delivery.getId());
                        continue;
                    }

                    // 查询关联的订单
                    List<Order> orders = orderMapper.selectBatchIds(orderIds);
                    if (orders == null || orders.isEmpty()) {
                        logger.warn("运送清单{}关联的订单不存在，跳过", delivery.getId());
                        continue;
                    }

                    // 过滤未删除的订单
                    orders = orders.stream()
                            .filter(order -> order.getIsDelete() == null || order.getIsDelete() == 0)
                            .collect(Collectors.toList());

                    if (orders.isEmpty()) {
                        logger.warn("运送清单{}关联的订单全部已删除，跳过", delivery.getId());
                        continue;
                    }

                    // 填充订单信息（买方名称、卖方名称）
                    for (Order order : orders) {
                        fillOrderInfo(order);
                    }

                    // 按链路排序订单
                    List<Order> sortedOrders = sortOrdersByChain(orders);
                    if (sortedOrders == null || sortedOrders.isEmpty()) {
                        logger.warn("运送清单{}的订单排序后为空，跳过", delivery.getId());
                        continue;
                    }

                    // 获取第一个订单（起始订单，用于计算采购金额）
                    Order firstOrder = sortedOrders.get(0);
                    // 获取最后一个订单（用于计算销售金额）
                    Order lastOrder = sortedOrders.get(sortedOrders.size() - 1);

                    logger.info("运送清单{}：起始订单ID={}，最后订单ID={}", delivery.getId(), firstOrder.getId(), lastOrder.getId());

                    // 计算采购金额
                    BigDecimal procurementAmount = calculateOrderAmount(delivery, firstOrder);
                    if (procurementAmount != null) {
                        totalProcurementAmount = totalProcurementAmount.add(procurementAmount);
                        logger.info("运送清单{}：采购金额={}", delivery.getId(), procurementAmount);
                    }

                    // 计算销售金额
                    BigDecimal salesAmount = calculateOrderAmount(delivery, lastOrder);
                    if (salesAmount != null) {
                        totalSalesAmount = totalSalesAmount.add(salesAmount);
                        logger.info("运送清单{}：销售金额={}", delivery.getId(), salesAmount);
                    }

                    // 计算应收货款（取最后一个订单的约定价格 × 重量）
                    BigDecimal accountsReceivableAmount = calculateAccountsReceivable(delivery, lastOrder);
                    if (accountsReceivableAmount != null) {
                        totalAccountsReceivable = totalAccountsReceivable.add(accountsReceivableAmount);
                        logger.info("运送清单{}：应收货款={}", delivery.getId(), accountsReceivableAmount);
                    }

                    // 计算实收货款（取最后一个订单的预付款）
                    BigDecimal actualPaymentAmount = calculateActualPayment(lastOrder);
                    if (actualPaymentAmount != null) {
                        totalActualPayment = totalActualPayment.add(actualPaymentAmount);
                        logger.info("运送清单{}：实收货款={}", delivery.getId(), actualPaymentAmount);
                    }

                    // 累计采购数量
                    if (delivery.getRatedQuantity() != null) {
                        totalPurchase += delivery.getRatedQuantity();
                    }

                    totalOrder++; // 采购单数
                    totalSales++; // 销售单数

                } catch (Exception e) {
                    logger.error("计算运送清单{}的统计数据失败：{}", delivery.getId(), e.getMessage(), e);
                    // 继续处理下一个delivery
                }
            }

            // 计算利润
            BigDecimal profits = totalSalesAmount.subtract(totalProcurementAmount);

            // 计算未收货款
            BigDecimal uncollectedPayment = totalAccountsReceivable.subtract(totalActualPayment);

            logger.info("计算完成：采购总额={}，销售总额={}，利润={}，采购数量={}，采购单数={}，销售单数={}，应收货款={}，实收货款={}，未收货款={}",
                    totalProcurementAmount, totalSalesAmount, profits, totalPurchase, totalOrder, totalSales,
                    totalAccountsReceivable, totalActualPayment, uncollectedPayment);

            // 创建或更新销售概览记录
            SalesOverview salesOverview = new SalesOverview();
            // 注意：新增时不要设置 id，让数据库自动生成
            salesOverview.setToalProcurementAmount(totalProcurementAmount);
            salesOverview.setToalSalesAmount(totalSalesAmount);
            salesOverview.setProfits(profits);
            salesOverview.setTotalPurchase(totalPurchase);
            salesOverview.setTotalOrder(totalOrder);
            salesOverview.setTotalSales(totalSales);
            salesOverview.setAccountsReceivable(totalAccountsReceivable);
            salesOverview.setActualPayment(totalActualPayment);
            salesOverview.setUncollectedPayment(uncollectedPayment);

            Date now = new Date();
            salesOverview.setCreateTime(now);
            salesOverview.setUpTime(now);

            // 保存或更新（如果已存在则更新，否则新增）
            LambdaQueryWrapper<SalesOverview> wrapper = new LambdaQueryWrapper<>();
            List<SalesOverview> existing = this.list(wrapper);
            if (!existing.isEmpty()) {
                // 更新第一条记录
                SalesOverview existingRecord = existing.get(0);
                salesOverview.setId(existingRecord.getId()); // 更新时需要设置ID
                this.updateById(salesOverview);
                logger.info("更新销售概览记录，ID：{}", existingRecord.getId());
            } else {
                // 新增记录 - 确保 id 为 null，让数据库自动生成
                salesOverview.setId(null); // 明确设置为 null，确保使用数据库自增
                boolean saved = this.save(salesOverview);
                if (saved) {
                    logger.info("新增销售概览记录成功，ID：{}", salesOverview.getId());
                } else {
                    logger.error("新增销售概览记录失败");
                    return AjaxResult.error("保存统计数据失败");
                }
            }

            return AjaxResult.success("计算成功", salesOverview);

        } catch (Exception e) {
            logger.error("计算销售概览统计数据失败：{}", e.getMessage(), e);
            return AjaxResult.error("计算失败：" + e.getMessage());
        }
    }

    /**
     * 计算订单金额
     *
     * @param delivery 运送清单
     * @param order    订单
     * @return 金额（元）
     */
    private BigDecimal calculateOrderAmount(Delivery delivery, Order order) {
        try {
            // 检查单价
            if (order.getFirmPrice() == null || order.getFirmPrice().compareTo(BigDecimal.ZERO) <= 0) {
                logger.warn("订单{}的单价为空或无效，跳过计算", order.getId());
                return null;
            }

            // 检查结算方式
            Integer settlementType = order.getSettlementType();
            if (settlementType == null) {
                logger.warn("订单{}的结算方式为空，跳过计算", order.getId());
                return null;
            }

            BigDecimal weight = null; // 重量（斤）

            // 根据结算方式计算重量
            if (settlementType == 1) {
                // 1-上车重量：使用发车牛只重量
                weight = calculateDepartureCattleWeight(delivery);
            } else if (settlementType == 2) {
                // 2-下车重量：使用落地牛只重量
                weight = calculateLandingCattleWeight(delivery);
            } else {
                // 3-按肉价结算：暂不支持，跳过
                logger.warn("订单{}的结算方式为按肉价结算，暂不支持计算", order.getId());
                return null;
            }

            if (weight == null || weight.compareTo(BigDecimal.ZERO) <= 0) {
                logger.warn("订单{}的重量计算失败或为0，跳过计算", order.getId());
                return null;
            }

            // 金额 = 单价（元/斤）× 重量（斤）
            BigDecimal amount = order.getFirmPrice().multiply(weight);
            amount = amount.setScale(2, RoundingMode.HALF_UP); // 保留2位小数

            logger.info("订单{}：单价={}，重量={}，金额={}", order.getId(), order.getFirmPrice(), weight, amount);

            return amount;

        } catch (Exception e) {
            logger.error("计算订单{}的金额失败：{}", order.getId(), e.getMessage(), e);
            return null;
        }
    }

    /**
     * 计算应收货款
     * 取最后一个订单的约定价格 × 重量（根据结算方式）
     *
     * @param delivery 运送清单
     * @param lastOrder 链路中最后一个订单
     * @return 应收货款（元）
     */
    private BigDecimal calculateAccountsReceivable(Delivery delivery, Order lastOrder) {
        try {
            // 检查单价
            if (lastOrder.getFirmPrice() == null || lastOrder.getFirmPrice().compareTo(BigDecimal.ZERO) <= 0) {
                logger.warn("订单{}的单价为空或无效，跳过应收货款计算", lastOrder.getId());
                return null;
            }

            // 检查结算方式
            Integer settlementType = lastOrder.getSettlementType();
            if (settlementType == null) {
                logger.warn("订单{}的结算方式为空，跳过应收货款计算", lastOrder.getId());
                return null;
            }

            BigDecimal weight = null; // 重量（斤）

            // 根据结算方式计算重量
            if (settlementType == 1) {
                // 1-上车重量：使用发车牛只重量
                weight = calculateDepartureCattleWeight(delivery);
            } else if (settlementType == 2) {
                // 2-下车重量：使用落地牛只重量
                weight = calculateLandingCattleWeight(delivery);
            } else {
                // 3-按肉价结算：暂不支持，跳过
                logger.warn("订单{}的结算方式为按肉价结算，跳过应收货款计算", lastOrder.getId());
                return null;
            }

            if (weight == null || weight.compareTo(BigDecimal.ZERO) <= 0) {
                logger.warn("订单{}的重量计算失败或为0，跳过应收货款计算", lastOrder.getId());
                return null;
            }

            // 应收货款 = 约定价格（元/斤）× 重量（斤）
            BigDecimal accountsReceivable = lastOrder.getFirmPrice().multiply(weight);
            accountsReceivable = accountsReceivable.setScale(2, RoundingMode.HALF_UP); // 保留2位小数

            logger.info("订单{}：约定价格={}，重量={}，应收货款={}", lastOrder.getId(), lastOrder.getFirmPrice(), weight, accountsReceivable);

            return accountsReceivable;

        } catch (Exception e) {
            logger.error("计算订单{}的应收货款失败：{}", lastOrder.getId(), e.getMessage(), e);
            return null;
        }
    }

    /**
     * 计算实收货款（预付款）
     * 取最后一个订单的预付款
     *
     * @param lastOrder 链路中最后一个订单
     * @return 实收货款（元）
     */
    private BigDecimal calculateActualPayment(Order lastOrder) {
        try {
            if (lastOrder.getAdvancePayment() == null) {
                logger.warn("订单{}的预付款为空，跳过实收货款计算", lastOrder.getId());
                return null;
            }

            BigDecimal actualPayment = lastOrder.getAdvancePayment();
            if (actualPayment.compareTo(BigDecimal.ZERO) < 0) {
                logger.warn("订单{}的预付款为负数，跳过实收货款计算", lastOrder.getId());
                return null;
            }

            logger.info("订单{}：预付款={}，实收货款={}", lastOrder.getId(), actualPayment, actualPayment);

            return actualPayment;

        } catch (Exception e) {
            logger.error("计算订单{}的实收货款失败：{}", lastOrder.getId(), e.getMessage(), e);
            return null;
        }
    }

    /**
     * 计算发车牛只重量（斤）
     * 发车牛只重量 = (装车过磅重量 - 空车过磅重量) × 2（kg转斤）
     */
    private BigDecimal calculateDepartureCattleWeight(Delivery delivery) {
        try {
            String emptyWeightStr = delivery.getEmptyWeight();
            String entruckWeightStr = delivery.getEntruckWeight();

            if (StringUtils.isEmpty(emptyWeightStr) || StringUtils.isEmpty(entruckWeightStr)) {
                logger.warn("运送清单{}的空车过磅重量或装车过磅重量为空", delivery.getId());
                return null;
            }

            BigDecimal emptyWeight = new BigDecimal(emptyWeightStr);
            BigDecimal entruckWeight = new BigDecimal(entruckWeightStr);

            if (emptyWeight.compareTo(BigDecimal.ZERO) <= 0 || entruckWeight.compareTo(emptyWeight) <= 0) {
                logger.warn("运送清单{}的重量数据无效：空车={}，装车={}", delivery.getId(), emptyWeight, entruckWeight);
                return null;
            }

            // 发车牛只重量（kg）= 装车过磅重量 - 空车过磅重量
            BigDecimal cattleWeightKg = entruckWeight.subtract(emptyWeight);
            // 转换为斤：kg × 2
            BigDecimal cattleWeightJin = cattleWeightKg.multiply(new BigDecimal("2"));
            cattleWeightJin = cattleWeightJin.setScale(2, RoundingMode.HALF_UP);

            logger.info("运送清单{}：发车牛只重量={}kg={}斤", delivery.getId(), cattleWeightKg, cattleWeightJin);

            return cattleWeightJin;

        } catch (Exception e) {
            logger.error("计算运送清单{}的发车牛只重量失败：{}", delivery.getId(), e.getMessage(), e);
            return null;
        }
    }

    /**
     * 计算落地牛只重量（斤）
     * 落地牛只重量 = (落地过磅重量 - 空车过磅重量) × 2（kg转斤）
     */
    private BigDecimal calculateLandingCattleWeight(Delivery delivery) {
        try {
            String emptyWeightStr = delivery.getEmptyWeight();
            String landingWeightStr = delivery.getLandingEntruckWeight();

            if (StringUtils.isEmpty(emptyWeightStr) || StringUtils.isEmpty(landingWeightStr)) {
                logger.warn("运送清单{}的空车过磅重量或落地过磅重量为空", delivery.getId());
                return null;
            }

            BigDecimal emptyWeight = new BigDecimal(emptyWeightStr);
            BigDecimal landingWeight = new BigDecimal(landingWeightStr);

            if (emptyWeight.compareTo(BigDecimal.ZERO) <= 0 || landingWeight.compareTo(emptyWeight) <= 0) {
                logger.warn("运送清单{}的重量数据无效：空车={}，落地={}", delivery.getId(), emptyWeight, landingWeight);
                return null;
            }

            // 落地牛只重量（kg）= 落地过磅重量 - 空车过磅重量
            BigDecimal cattleWeightKg = landingWeight.subtract(emptyWeight);
            // 转换为斤：kg × 2
            BigDecimal cattleWeightJin = cattleWeightKg.multiply(new BigDecimal("2"));
            cattleWeightJin = cattleWeightJin.setScale(2, RoundingMode.HALF_UP);

            logger.info("运送清单{}：落地牛只重量={}kg={}斤", delivery.getId(), cattleWeightKg, cattleWeightJin);

            return cattleWeightJin;

        } catch (Exception e) {
            logger.error("计算运送清单{}的落地牛只重量失败：{}", delivery.getId(), e.getMessage(), e);
            return null;
        }
    }

    /**
     * 按买卖关系链排序订单
     * 复用OrderServiceImpl中的逻辑
     */
    private List<Order> sortOrdersByChain(List<Order> orders) {
        if (orders == null || orders.size() <= 1) {
            return orders;
        }

        List<Order> result = new ArrayList<>();
        List<Order> remaining = new ArrayList<>(orders);

        // 辅助方法：检查两个名称是否匹配（支持逗号分隔的多个名称）
        java.util.function.BiFunction<String, String, Boolean> namesMatch = (name1, name2) -> {
            if (name1 == null || name2 == null) {
                return false;
            }
            String[] names1 = name1.split(",\\s*");
            String[] names2 = name2.split(",\\s*");
            for (String n1 : names1) {
                String trimmed1 = n1.trim();
                if (trimmed1.isEmpty()) {
                    continue;
                }
                for (String n2 : names2) {
                    String trimmed2 = n2.trim();
                    if (trimmed1.equals(trimmed2)) {
                        return true;
                    }
                }
            }
            return false;
        };

        // 找到链条的起点：没有其他订单的卖方等于这个订单的买方
        Order startOrder = null;
        for (Order order : remaining) {
            String buyerName = order.getBuyerName();
            if (buyerName == null || buyerName.trim().isEmpty()) {
                continue;
            }

            boolean isStart = true;
            for (Order other : remaining) {
                if (order == other) {
                    continue;
                }
                String otherSellerName = other.getSellerName();
                if (otherSellerName != null && namesMatch.apply(buyerName, otherSellerName)) {
                    isStart = false;
                    break;
                }
            }

            if (isStart) {
                startOrder = order;
                break;
            }
        }

        if (startOrder == null) {
            startOrder = remaining.get(0);
        }

        result.add(startOrder);
        remaining.remove(startOrder);

        // 按照买卖关系链依次添加订单
        while (!remaining.isEmpty()) {
            Order currentOrder = result.get(result.size() - 1);
            boolean found = false;
            String currentSellerName = currentOrder.getSellerName();

            if (currentSellerName != null && !currentSellerName.trim().isEmpty()) {
                for (Order nextOrder : remaining) {
                    String nextBuyerName = nextOrder.getBuyerName();
                    if (nextBuyerName != null && namesMatch.apply(currentSellerName, nextBuyerName)) {
                        result.add(nextOrder);
                        remaining.remove(nextOrder);
                        found = true;
                        break;
                    }
                }
            }

            if (!found) {
                // 如果当前链条无法继续，将剩余订单按创建时间倒序添加
                remaining.sort((o1, o2) -> {
                    if (o1.getCreateTime() != null && o2.getCreateTime() != null) {
                        return o2.getCreateTime().compareTo(o1.getCreateTime());
                    }
                    return 0;
                });
                result.addAll(remaining);
                break;
            }
        }

        return result;
    }

    /**
     * 填充订单关联信息（买方名称、卖方名称）
     */
    private void fillOrderInfo(Order order) {
        // 填充买方名称
        if (order.getBuyerId() != null && !order.getBuyerId().isEmpty()) {
            String buyerNames = Arrays.stream(order.getBuyerId().split(","))
                    .map(buyerId -> {
                        try {
                            Map<String, Object> memberUser = memberMapper.selectMemberUserById(Integer.parseInt(buyerId.trim()));
                            if (memberUser != null && memberUser.get("username") != null) {
                                return (String) memberUser.get("username");
                            }
                        } catch (Exception e) {
                            logger.warn("查询买方信息失败，买方ID：{}", buyerId);
                        }
                        return "";
                    })
                    .filter(name -> !name.isEmpty())
                    .collect(Collectors.joining(", "));
            order.setBuyerName(buyerNames);
        }

        // 填充卖方名称
        if (order.getSellerId() != null && !order.getSellerId().isEmpty()) {
            String sellerNames = Arrays.stream(order.getSellerId().split(","))
                    .map(sellerId -> {
                        try {
                            Map<String, Object> memberUser = memberMapper.selectMemberUserById(Integer.parseInt(sellerId.trim()));
                            if (memberUser != null && memberUser.get("username") != null) {
                                return (String) memberUser.get("username");
                            }
                        } catch (Exception e) {
                            logger.warn("查询卖方信息失败，卖方ID：{}", sellerId);
                        }
                        return "";
                    })
                    .filter(name -> !name.isEmpty())
                    .collect(Collectors.joining(", "));
            order.setSellerName(sellerNames);
        }
    }
}

