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

import com.aiotagro.cattletrade.business.entity.Order;
import com.aiotagro.cattletrade.business.entity.SysUser;
import com.aiotagro.cattletrade.business.mapper.OrderMapper;
import com.aiotagro.cattletrade.business.mapper.MemberMapper;
import com.aiotagro.cattletrade.business.mapper.SysUserMapper;
import com.aiotagro.cattletrade.business.service.IOrderService;
import com.aiotagro.common.core.utils.SecurityUtil;
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 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.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 订单管理服务实现类
 *
 * @author System
 * @date 2025-01-20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

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

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private com.aiotagro.cattletrade.business.mapper.DeliveryMapper deliveryMapper;

    /**
     * 分页查询订单列表
     */
    @Override
    public PageResultResponse<Order> 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;
        Integer settlementType = params.get("settlementType") != null ? (Integer) params.get("settlementType") : null;
        String buyerName = params.get("buyerName") != null ? (String) params.get("buyerName") : null;
        String sellerName = params.get("sellerName") != null ? (String) params.get("sellerName") : null;
        String startTime = params.get("startTime") != null ? (String) params.get("startTime") : null;
        String endTime = params.get("endTime") != null ? (String) params.get("endTime") : null;
        String deliveryNumber = params.get("deliveryNumber") != null ? (String) params.get("deliveryNumber") : null;
        String startLocation = params.get("startLocation") != null ? (String) params.get("startLocation") : null;
        String endLocation = params.get("endLocation") != null ? (String) params.get("endLocation") : null;
        String firmPrice = params.get("firmPrice") != null ? (String) params.get("firmPrice") : null;

        logger.info("分页查询订单列表，页码：{}，每页数量：{}，买方：{}，卖方：{}，结算方式：{}，运单号：{}，起始地：{}，目的地：{}，单价：{}", 
                    pageNum, pageSize, buyerName, sellerName, settlementType, deliveryNumber, startLocation, endLocation, firmPrice);

        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(settlementType != null, Order::getSettlementType, settlementType);
        
        // 时间范围查询
        if (startTime != null && !startTime.isEmpty()) {
            // 如果没有时间部分，添加00:00:00
            String startTimeStr = startTime;
            if (startTimeStr.matches("\\d{4}-\\d{2}-\\d{2}")) {
                startTimeStr = startTimeStr + " 00:00:00";
            }
            queryWrapper.ge(Order::getCreateTime, startTimeStr);
        }
        if (endTime != null && !endTime.isEmpty()) {
            // 如果没有时间部分，添加23:59:59
            String endTimeStr = endTime;
            if (endTimeStr.matches("\\d{4}-\\d{2}-\\d{2}")) {
                endTimeStr = endTimeStr + " 23:59:59";
            }
            queryWrapper.le(Order::getCreateTime, endTimeStr);
        }
        
        queryWrapper.orderByDesc(Order::getCreateTime);

        List<Order> filteredList;
        long total;
        
        // 为了保持买卖关系链的完整性，统一采用先查询所有数据、排序、再分页的方式
        // 这样可以确保同一deliveryId的订单链条不会被分页截断
        // 先查询所有符合条件的数据（不包含需要填充信息的过滤条件）
        List<Order> allList = orderMapper.selectList(queryWrapper);
        
        // 批量填充关联信息（优化性能）
        fillOrderInfoBatch(allList);
        
        // 进行过滤（针对需要填充信息后才能过滤的字段）
        filteredList = allList;
        if (buyerName != null && !buyerName.trim().isEmpty()) {
            filteredList = filteredList.stream()
                .filter(order -> order.getBuyerName() != null && order.getBuyerName().contains(buyerName.trim()))
                .collect(java.util.stream.Collectors.toList());
        }
        if (sellerName != null && !sellerName.trim().isEmpty()) {
            filteredList = filteredList.stream()
                .filter(order -> order.getSellerName() != null && order.getSellerName().contains(sellerName.trim()))
                .collect(java.util.stream.Collectors.toList());
        }
        if (deliveryNumber != null && !deliveryNumber.trim().isEmpty()) {
            filteredList = filteredList.stream()
                .filter(order -> order.getDeliveryNumber() != null && order.getDeliveryNumber().contains(deliveryNumber.trim()))
                .collect(java.util.stream.Collectors.toList());
        }
        if (startLocation != null && !startLocation.trim().isEmpty()) {
            filteredList = filteredList.stream()
                .filter(order -> order.getStartLocation() != null && order.getStartLocation().contains(startLocation.trim()))
                .collect(java.util.stream.Collectors.toList());
        }
        if (endLocation != null && !endLocation.trim().isEmpty()) {
            filteredList = filteredList.stream()
                .filter(order -> order.getEndLocation() != null && order.getEndLocation().contains(endLocation.trim()))
                .collect(java.util.stream.Collectors.toList());
        }
        if (firmPrice != null && !firmPrice.trim().isEmpty()) {
            filteredList = filteredList.stream()
                .filter(order -> {
                    java.math.BigDecimal price = order.getFirmPriceFromDelivery() != null ? order.getFirmPriceFromDelivery() : order.getFirmPrice();
                    if (price == null) {
                        return false;
                    }
                    return price.toString().contains(firmPrice.trim());
                })
                .collect(java.util.stream.Collectors.toList());
        }
        
        // 获取总数（排序前）
        total = filteredList.size();
        
        logger.info("查询到{}条订单记录，过滤后{}条", allList.size(), total);

        // 优化排序：按运送清单分组，同链路内按买卖关系链排序
        // 排序规则：1. 有deliveryId的订单按deliveryId分组，相同deliveryId的订单放在一起
        //          2. 按deliveryId排序（null值放在最后）
        //          3. 同一deliveryId内的订单按买卖关系链排序：
        //             - 如果订单A的卖方等于订单B的买方，则B排在A后面
        //             - 形成链条：订单1 -> 订单2 -> 订单3
        List<Order> sortedList = new ArrayList<>();
        
        // 按deliveryId分组
        java.util.Map<Integer, List<Order>> deliveryGroups = new java.util.HashMap<>();
        List<Order> noDeliveryOrders = new ArrayList<>();
        
        for (Order order : filteredList) {
            Integer deliveryId = order.getDeliveryId();
            if (deliveryId == null) {
                noDeliveryOrders.add(order);
            } else {
                deliveryGroups.computeIfAbsent(deliveryId, k -> new ArrayList<>()).add(order);
            }
        }
        
        // 对每个deliveryId组内的订单按买卖关系链排序
        List<Integer> sortedDeliveryIds = new ArrayList<>(deliveryGroups.keySet());
        sortedDeliveryIds.sort(Integer::compareTo);
        
        for (Integer deliveryId : sortedDeliveryIds) {
            List<Order> groupOrders = deliveryGroups.get(deliveryId);
            List<Order> sortedGroup = sortOrdersByChain(groupOrders);
            sortedList.addAll(sortedGroup);
        }
        
        // 没有deliveryId的订单按创建时间倒序，放在最后
        noDeliveryOrders.sort((o1, o2) -> {
            if (o1.getCreateTime() != null && o2.getCreateTime() != null) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
            return 0;
        });
        sortedList.addAll(noDeliveryOrders);
        
        filteredList = sortedList;
        logger.info("订单列表排序完成，共{}条记录，已按买卖关系链排序", filteredList.size());

        // 排序后再进行分页，确保同一链条的订单不会被分到不同页
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, filteredList.size());
        if (startIndex < filteredList.size()) {
            filteredList = filteredList.subList(startIndex, endIndex);
            logger.info("分页后{}条记录（第{}页，每页{}条）", filteredList.size(), pageNum, pageSize);
        } else {
            filteredList = new ArrayList<>();
            logger.info("分页后0条记录（超出范围）");
        }

        // 构建分页结果
        return new PageResultResponse<>(total, filteredList);
    }

    /**
     * 新增订单
     */
    @Override
    @Transactional
    public AjaxResult addOrder(Order order) {
        logger.info("开始新增订单，买方：{}，卖方：{}，结算方式：{}，约定价格：{}，运送清单ID：{}", 
            order.getBuyerId(), order.getSellerId(), order.getSettlementType(), order.getFirmPrice(), order.getDeliveryId());

        try {
            // 验证结算方式
            if (order.getSettlementType() == null || order.getSettlementType() < 1 || order.getSettlementType() > 3) {
                logger.error("结算方式无效：{}", order.getSettlementType());
                return AjaxResult.error("结算方式无效");
            }

            // 验证约定价格（firm_price 字段是 NOT NULL）
            if (order.getFirmPrice() == null) {
                logger.error("约定价格不能为空");
                return AjaxResult.error("约定价格不能为空");
            }
            // 确保约定价格不为负数
            if (order.getFirmPrice().compareTo(java.math.BigDecimal.ZERO) < 0) {
                logger.error("约定价格不能小于0：{}", order.getFirmPrice());
                return AjaxResult.error("约定价格不能小于0");
            }

            // 如果提供了deliveryId，验证运送清单是否存在
            if (order.getDeliveryId() != null) {
                com.aiotagro.cattletrade.business.entity.Delivery delivery = deliveryMapper.selectById(order.getDeliveryId());
                if (delivery == null) {
                    logger.error("运送清单不存在，ID：{}", order.getDeliveryId());
                    return AjaxResult.error("运送清单不存在");
                }
                logger.info("订单将关联到运送清单，运送清单ID：{}，运单号：{}", order.getDeliveryId(), delivery.getDeliveryNumber());
            }

            // 设置创建人和创建时间
            Integer userId = SecurityUtil.getCurrentUserId();
            order.setCreatedBy(userId);
            order.setCreateTime(new Date());

            // 插入数据库
            int result = orderMapper.insert(order);

            if (result > 0) {
                if (order.getDeliveryId() != null) {
                    logger.info("新增订单成功并关联运送清单，订单ID：{}，运送清单ID：{}", order.getId(), order.getDeliveryId());
                } else {
                    logger.info("新增订单成功，订单ID：{}", order.getId());
                }
                // 返回订单ID，方便前端更新关联关系
                Map<String, Object> data = new HashMap<>();
                data.put("id", order.getId());
                return AjaxResult.success("新增订单成功", data);
            } else {
                logger.error("新增订单失败");
                return AjaxResult.error("新增订单失败");
            }
        } catch (Exception e) {
            logger.error("新增订单异常：{}", e.getMessage(), e);
            return AjaxResult.error("新增订单失败：" + e.getMessage());
        }
    }

    /**
     * 更新订单信息
     */
    @Override
    @Transactional
    public AjaxResult updateOrder(Order order) {
        if (order.getId() == null) {
            logger.error("订单ID不能为空");
            return AjaxResult.error("订单ID不能为空");
        }

        logger.info("开始更新订单，订单ID：{}，约定价格：{}", order.getId(), order.getFirmPrice());

        try {
            // 验证订单是否存在
            Order existingOrder = orderMapper.selectById(order.getId());
            if (existingOrder == null) {
                logger.error("订单不存在，ID：{}", order.getId());
                return AjaxResult.error("订单不存在");
            }

            // 验证结算方式
            if (order.getSettlementType() != null && (order.getSettlementType() < 1 || order.getSettlementType() > 3)) {
                logger.error("结算方式无效：{}", order.getSettlementType());
                return AjaxResult.error("结算方式无效");
            }

            // 验证约定价格（如果提供了）
            if (order.getFirmPrice() != null) {
                // 确保约定价格不为负数
                if (order.getFirmPrice().compareTo(java.math.BigDecimal.ZERO) < 0) {
                    logger.error("约定价格不能小于0：{}", order.getFirmPrice());
                    return AjaxResult.error("约定价格不能小于0");
                }
            } else {
                // 如果更新时没有提供 firm_price，保留原有值（因为字段是 NOT NULL）
                order.setFirmPrice(existingOrder.getFirmPrice());
            }

            // 设置更新人和更新时间
            try {
                Integer userId = SecurityUtil.getCurrentUserId();
                order.setUpdatedBy(userId);
            } catch (Exception e) {
                logger.warn("获取当前用户失败，使用订单原有创建人：{}", e.getMessage());
                // 如果无法获取当前用户，使用原订单的 created_by
                if (existingOrder.getCreatedBy() != null) {
                    order.setUpdatedBy(existingOrder.getCreatedBy());
                }
            }
            order.setUpdateTime(new Date());

            // 更新数据库
            int result = orderMapper.updateById(order);

            if (result > 0) {
                logger.info("更新订单成功，订单ID：{}", order.getId());
                return AjaxResult.success("更新订单成功");
            } else {
                logger.error("更新订单失败");
                return AjaxResult.error("更新订单失败");
            }
        } catch (Exception e) {
            logger.error("更新订单异常：{}", e.getMessage(), e);
            return AjaxResult.error("更新订单失败：" + e.getMessage());
        }
    }

    /**
     * 删除订单（逻辑删除）
     * 删除订单时，同时更新delivery表中order_id字段，移除对应的订单ID
     */
    @Override
    @Transactional
    public AjaxResult deleteOrder(Integer id) {
        if (id == null) {
            logger.error("订单ID不能为空");
            return AjaxResult.error("订单ID不能为空");
        }

        logger.info("开始删除订单，订单ID：{}", id);

        try {
            // 查询订单是否存在
            Order order = orderMapper.selectById(id);
            if (order == null) {
                logger.error("订单不存在，ID：{}", id);
                return AjaxResult.error("订单不存在");
            }

            // 在删除订单之前，先更新delivery表中order_id字段，移除该订单ID
            String orderIdStr = String.valueOf(id);
            try {
                // 查询所有order_id字段包含该订单ID的delivery记录
                // 使用LIKE查询匹配：开头、中间、结尾或单独存在
                com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.aiotagro.cattletrade.business.entity.Delivery> wrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
                wrapper.and(w -> w
                    .eq(com.aiotagro.cattletrade.business.entity.Delivery::getOrderId, orderIdStr) // 单独存在
                    .or()
                    .like(com.aiotagro.cattletrade.business.entity.Delivery::getOrderId, orderIdStr + ",") // 开头
                    .or()
                    .like(com.aiotagro.cattletrade.business.entity.Delivery::getOrderId, "," + orderIdStr + ",") // 中间
                    .or()
                    .like(com.aiotagro.cattletrade.business.entity.Delivery::getOrderId, "," + orderIdStr) // 结尾
                );
                wrapper.isNotNull(com.aiotagro.cattletrade.business.entity.Delivery::getOrderId);
                wrapper.ne(com.aiotagro.cattletrade.business.entity.Delivery::getOrderId, "");
                
                List<com.aiotagro.cattletrade.business.entity.Delivery> deliveryList = deliveryMapper.selectList(wrapper);
                
                if (deliveryList != null && !deliveryList.isEmpty()) {
                    logger.info("找到{}条运送清单包含订单ID：{}", deliveryList.size(), id);
                    
                    // 更新每条delivery记录的order_id字段
                    for (com.aiotagro.cattletrade.business.entity.Delivery delivery : deliveryList) {
                        String currentOrderId = delivery.getOrderId();
                        if (currentOrderId != null && !currentOrderId.trim().isEmpty()) {
                            // 将order_id字符串按逗号分割
                            List<String> orderIdList = new ArrayList<>(Arrays.asList(currentOrderId.split(",")));
                            // 去除空白并过滤空字符串
                            orderIdList = orderIdList.stream()
                                .map(String::trim)
                                .filter(oid -> !oid.isEmpty())
                                .collect(Collectors.toList());
                            
                            // 移除该订单ID
                            orderIdList.remove(orderIdStr);
                            
                            // 如果还有订单ID，重新组合；否则设置为null
                            if (!orderIdList.isEmpty()) {
                                // 排序并去重
                                orderIdList = orderIdList.stream()
                                    .distinct()
                                    .sorted((a, b) -> Integer.compare(Integer.parseInt(a), Integer.parseInt(b)))
                                    .collect(Collectors.toList());
                                String newOrderId = String.join(",", orderIdList);
                                delivery.setOrderId(newOrderId);
                                logger.info("更新运送清单order_id：deliveryId={}, 原值={}, 新值={}", 
                                    delivery.getId(), currentOrderId, newOrderId);
                            } else {
                                delivery.setOrderId(null);
                                logger.info("更新运送清单order_id：deliveryId={}, 原值={}, 新值=null（已清空）", 
                                    delivery.getId(), currentOrderId);
                            }
                            
                            // 更新delivery记录
                            deliveryMapper.updateById(delivery);
                        }
                    }
                    logger.info("成功更新{}条运送清单的order_id字段", deliveryList.size());
                } else {
                    logger.info("未找到包含订单ID {} 的运送清单记录", id);
                }
            } catch (Exception e) {
                logger.error("更新delivery表order_id字段失败，订单ID：{}，错误：{}", id, e.getMessage(), e);
                // 不阻止删除流程，只记录错误
            }

            // 逻辑删除（通过update方法设置is_delete=1）
            // MyBatis-Plus的@TableLogic会自动处理
            int result = orderMapper.deleteById(id);

            if (result > 0) {
                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 getOrderDetail(Integer id) {
        if (id == null) {
            return AjaxResult.error("订单ID不能为空");
        }

        logger.info("查询订单详情，订单ID：{}", id);

        Order order = orderMapper.selectById(id);
        if (order == null) {
            logger.error("订单不存在，ID：{}", id);
            return AjaxResult.error("订单不存在");
        }

        // 填充关联信息
        fillOrderInfo(order);

        return AjaxResult.success(order);
    }

    /**
     * 批量填充订单关联信息（优化性能，减少数据库查询次数）
     */
    private void fillOrderInfoBatch(List<Order> orders) {
        if (orders == null || orders.isEmpty()) {
            return;
        }

        // 收集所有需要查询的ID
        java.util.Set<Integer> buyerIds = new java.util.HashSet<>();
        java.util.Set<Integer> sellerIds = new java.util.HashSet<>();
        java.util.Set<Integer> creatorIds = new java.util.HashSet<>();
        java.util.Set<Integer> deliveryIds = new java.util.HashSet<>();

        for (Order order : orders) {
            // 收集买方ID
            if (order.getBuyerId() != null && !order.getBuyerId().isEmpty()) {
                Arrays.stream(order.getBuyerId().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .forEach(id -> {
                        try {
                            buyerIds.add(Integer.parseInt(id));
                        } catch (NumberFormatException e) {
                            logger.warn("无效的买方ID：{}", id);
                        }
                    });
            }
            // 收集卖方ID
            if (order.getSellerId() != null && !order.getSellerId().isEmpty()) {
                Arrays.stream(order.getSellerId().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .forEach(id -> {
                        try {
                            sellerIds.add(Integer.parseInt(id));
                        } catch (NumberFormatException e) {
                            logger.warn("无效的卖方ID：{}", id);
                        }
                    });
            }
            // 收集创建人ID
            if (order.getCreatedBy() != null) {
                creatorIds.add(order.getCreatedBy());
            }
            // 收集运送清单ID
            if (order.getDeliveryId() != null) {
                deliveryIds.add(order.getDeliveryId());
            }
        }

        // 批量查询买方信息
        java.util.Map<Integer, String> buyerNameMap = new java.util.HashMap<>();
        if (!buyerIds.isEmpty()) {
            List<Map<String, Object>> buyerList = memberMapper.selectMemberUserByIds(new ArrayList<>(buyerIds));
            for (Map<String, Object> buyer : buyerList) {
                Object idObj = buyer.get("id");
                Integer id = null;
                if (idObj != null) {
                    if (idObj instanceof Integer) {
                        id = (Integer) idObj;
                    } else if (idObj instanceof Long) {
                        id = ((Long) idObj).intValue();
                    } else if (idObj instanceof Number) {
                        id = ((Number) idObj).intValue();
                    }
                }
                String username = (String) buyer.get("username");
                if (id != null && username != null) {
                    buyerNameMap.put(id, username);
                }
            }
        }

        // 批量查询卖方信息
        java.util.Map<Integer, String> sellerNameMap = new java.util.HashMap<>();
        if (!sellerIds.isEmpty()) {
            List<Map<String, Object>> sellerList = memberMapper.selectMemberUserByIds(new ArrayList<>(sellerIds));
            for (Map<String, Object> seller : sellerList) {
                Object idObj = seller.get("id");
                Integer id = null;
                if (idObj != null) {
                    if (idObj instanceof Integer) {
                        id = (Integer) idObj;
                    } else if (idObj instanceof Long) {
                        id = ((Long) idObj).intValue();
                    } else if (idObj instanceof Number) {
                        id = ((Number) idObj).intValue();
                    }
                }
                String username = (String) seller.get("username");
                if (id != null && username != null) {
                    sellerNameMap.put(id, username);
                }
            }
        }

        // 批量查询创建人信息
        java.util.Map<Integer, String> creatorNameMap = new java.util.HashMap<>();
        if (!creatorIds.isEmpty()) {
            List<SysUser> creatorList = sysUserMapper.selectBatchIds(creatorIds);
            for (SysUser user : creatorList) {
                if (user != null && user.getId() != null && user.getName() != null) {
                    creatorNameMap.put(user.getId(), user.getName());
                }
            }
        }

        // 批量查询运送清单信息
        java.util.Map<Integer, com.aiotagro.cattletrade.business.entity.Delivery> deliveryMap = new java.util.HashMap<>();
        if (!deliveryIds.isEmpty()) {
            try {
                List<com.aiotagro.cattletrade.business.entity.Delivery> deliveryList = deliveryMapper.selectBatchIds(new ArrayList<>(deliveryIds));
                for (com.aiotagro.cattletrade.business.entity.Delivery delivery : deliveryList) {
                    if (delivery != null && delivery.getId() != null) {
                        deliveryMap.put(delivery.getId(), delivery);
                    }
                }
            } catch (Exception e) {
                logger.warn("批量查询运送清单信息失败：{}", e.getMessage());
            }
        }

        // 批量填充订单信息
        for (Order order : orders) {
            // 填充买方名称
            if (order.getBuyerId() != null && !order.getBuyerId().isEmpty()) {
                String buyerNames = Arrays.stream(order.getBuyerId().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(id -> {
                        try {
                            Integer buyerId = Integer.parseInt(id);
                            return buyerNameMap.getOrDefault(buyerId, "");
                        } catch (NumberFormatException e) {
                            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(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(id -> {
                        try {
                            Integer sellerId = Integer.parseInt(id);
                            return sellerNameMap.getOrDefault(sellerId, "");
                        } catch (NumberFormatException e) {
                            return "";
                        }
                    })
                    .filter(name -> !name.isEmpty())
                    .collect(Collectors.joining(", "));
                order.setSellerName(sellerNames);
            }

            // 填充创建人名称
            if (order.getCreatedBy() != null) {
                String creatorName = creatorNameMap.get(order.getCreatedBy());
                if (creatorName != null) {
                    order.setCreatedByName(creatorName);
                }
            }

            // 填充运送清单信息
            if (order.getDeliveryId() != null) {
                com.aiotagro.cattletrade.business.entity.Delivery delivery = deliveryMap.get(order.getDeliveryId());
                if (delivery != null) {
                    order.setDeliveryNumber(delivery.getDeliveryNumber());
                    order.setStartLocation(delivery.getStartLocation());
                    order.setEndLocation(delivery.getEndLocation());
                    order.setDeliveryStatus(delivery.getStatus());
                    // 如果订单本身没有firmPrice，使用运送清单的firmPrice
                    if (order.getFirmPrice() == null && delivery.getFirmPrice() != null) {
                        order.setFirmPriceFromDelivery(java.math.BigDecimal.valueOf(delivery.getFirmPrice()));
                    } else if (delivery.getFirmPrice() != null) {
                        // 如果订单有firmPrice，也填充运送清单的firmPrice用于显示
                        order.setFirmPriceFromDelivery(java.math.BigDecimal.valueOf(delivery.getFirmPrice()));
                    }
                }
            }

            // 填充结算方式描述
            if (order.getSettlementType() != null) {
                switch (order.getSettlementType()) {
                    case 1:
                        order.setSettlementTypeDesc("上车重量");
                        break;
                    case 2:
                        order.setSettlementTypeDesc("下车重量");
                        break;
                    case 3:
                        order.setSettlementTypeDesc("按肉价结算");
                        break;
                    default:
                        order.setSettlementTypeDesc("未知");
                        break;
                }
            }
        }
    }

    /**
     * 按买卖关系链排序订单
     * 规则：如果订单A的卖方等于订单B的买方，则B排在A后面
     * 支持买方/卖方为多个名称（逗号分隔）的情况
     * 
     * @param orders 同一deliveryId的订单列表
     * @return 排序后的订单列表
     */
    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;
            }
            // 分割并trim，支持 ", " 或 "," 分隔
            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)) {
                        logger.debug("名称匹配：{} == {}", trimmed1, trimmed2);
                        return true;
                    }
                }
            }
            return false;
        };
        
        // 记录所有订单的买卖方信息用于调试
        logger.info("开始排序订单，共{}条", remaining.size());
        for (Order order : remaining) {
            logger.info("订单ID：{}，买方：{}，卖方：{}", order.getId(), order.getBuyerName(), order.getSellerName());
        }
        
        // 找到链条的起点：没有其他订单的卖方等于这个订单的买方
        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)) {
                    logger.info("订单{}不是起点，因为订单{}的卖方({})等于订单{}的买方({})", 
                        order.getId(), other.getId(), otherSellerName, order.getId(), buyerName);
                    isStart = false;
                    break;
                }
            }
            
            if (isStart) {
                logger.info("找到起点订单：{}，买方：{}", order.getId(), buyerName);
                startOrder = order;
                break;
            }
        }
        
        // 如果没有找到起点（可能是循环链或没有匹配关系），使用第一个订单作为起点
        if (startOrder == null) {
            logger.warn("未找到起点订单，使用第一个订单作为起点");
            startOrder = remaining.get(0);
        }
        
        // 从起点开始构建链条
        result.add(startOrder);
        remaining.remove(startOrder);
        logger.info("添加起点订单：{}", startOrder.getId());
        
        // 按照买卖关系链依次添加订单，支持多个独立链条
        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)) {
                        logger.info("找到下一个订单：{}（当前订单{}的卖方{} == 订单{}的买方{}）", 
                            nextOrder.getId(), currentOrder.getId(), currentSellerName, nextOrder.getId(), nextBuyerName);
                        result.add(nextOrder);
                        remaining.remove(nextOrder);
                        found = true;
                        break;
                    }
                }
            }
            
            // 如果当前链条无法继续，尝试从剩余订单中找新的起点构建新链条
            if (!found) {
                logger.info("当前链条无法继续，当前订单{}的卖方：{}，剩余{}个订单，尝试构建新链条", 
                    currentOrder.getId(), currentSellerName, remaining.size());
                
                // 从剩余订单中找新的起点
                Order newStartOrder = 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) {
                        logger.info("找到新链条起点订单：{}，买方：{}", order.getId(), buyerName);
                        newStartOrder = order;
                        break;
                    }
                }
                
                // 如果找到新起点，开始构建新链条
                if (newStartOrder != null) {
                    result.add(newStartOrder);
                    remaining.remove(newStartOrder);
                    logger.info("添加新链条起点订单：{}", newStartOrder.getId());
                    // 继续循环，从新起点开始构建链条
                    continue;
                } else {
                    // 如果找不到新起点，将剩余订单按创建时间倒序添加
                    logger.info("未找到新链条起点，将剩余订单按创建时间排序");
                    for (Order rem : remaining) {
                        logger.info("剩余订单{}，买方：{}，卖方：{}", rem.getId(), rem.getBuyerName(), rem.getSellerName());
                    }
                    remaining.sort((o1, o2) -> {
                        if (o1.getCreateTime() != null && o2.getCreateTime() != null) {
                            return o2.getCreateTime().compareTo(o1.getCreateTime());
                        }
                        return 0;
                    });
                    result.addAll(remaining);
                    break;
                }
            }
        }
        
        logger.info("排序完成，最终顺序：{}", result.stream().map(o -> String.valueOf(o.getId())).collect(Collectors.joining(" -> ")));
        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);
        }

        // 填充创建人名称
        if (order.getCreatedBy() != null) {
            SysUser user = sysUserMapper.selectById(order.getCreatedBy());
            if (user != null) {
                order.setCreatedByName(user.getName());
            }
        }

        // 填充结算方式描述
        if (order.getSettlementType() != null) {
            switch (order.getSettlementType()) {
                case 1:
                    order.setSettlementTypeDesc("上车重量");
                    break;
                case 2:
                    order.setSettlementTypeDesc("下车重量");
                    break;
                case 3:
                    order.setSettlementTypeDesc("按肉价结算");
                    break;
                default:
                    order.setSettlementTypeDesc("未知");
                    break;
            }
        }
    }

    /**
     * 批量导入订单
     */
    @Override
    @Transactional
    public AjaxResult batchImportOrders(List<Map<String, Object>> orders) {
        logger.info("开始批量导入订单，共{}条", orders.size());

        int successCount = 0;
        int failCount = 0;
        List<String> failMessages = new ArrayList<>();

        for (int i = 0; i < orders.size(); i++) {
            Map<String, Object> orderMap = orders.get(i);
            try {
                // 构建Order对象
                Order order = new Order();
                
                // 设置买方ID
                Object buyerIdObj = orderMap.get("buyerId");
                if (buyerIdObj != null) {
                    order.setBuyerId(String.valueOf(buyerIdObj));
                } else {
                    throw new RuntimeException("买方ID不能为空");
                }

                // 设置卖方ID
                Object sellerIdObj = orderMap.get("sellerId");
                if (sellerIdObj != null) {
                    order.setSellerId(String.valueOf(sellerIdObj));
                } else {
                    throw new RuntimeException("卖方ID不能为空");
                }

                // 设置结算方式（默认为1-上车重量）
                Object settlementTypeObj = orderMap.get("settlementType");
                if (settlementTypeObj != null) {
                    Integer settlementType = null;
                    if (settlementTypeObj instanceof Integer) {
                        settlementType = (Integer) settlementTypeObj;
                    } else if (settlementTypeObj instanceof Number) {
                        settlementType = ((Number) settlementTypeObj).intValue();
                    } else {
                        settlementType = Integer.parseInt(String.valueOf(settlementTypeObj));
                    }
                    if (settlementType < 1 || settlementType > 3) {
                        throw new RuntimeException("结算方式无效，必须为1-3");
                    }
                    order.setSettlementType(settlementType);
                } else {
                    order.setSettlementType(1); // 默认上车重量
                }

                // 设置约定价格
                Object firmPriceObj = orderMap.get("firmPrice");
                if (firmPriceObj != null) {
                    java.math.BigDecimal firmPrice = null;
                    if (firmPriceObj instanceof java.math.BigDecimal) {
                        firmPrice = (java.math.BigDecimal) firmPriceObj;
                    } else if (firmPriceObj instanceof Number) {
                        firmPrice = new java.math.BigDecimal(String.valueOf(firmPriceObj));
                    } else {
                        firmPrice = new java.math.BigDecimal(String.valueOf(firmPriceObj));
                    }
                    if (firmPrice.compareTo(java.math.BigDecimal.ZERO) < 0) {
                        throw new RuntimeException("约定价格不能小于0");
                    }
                    order.setFirmPrice(firmPrice);
                } else {
                    throw new RuntimeException("约定价格不能为空");
                }

                // 设置创建人和创建时间
                Integer userId = SecurityUtil.getCurrentUserId();
                order.setCreatedBy(userId);
                order.setCreateTime(new Date());

                // 插入数据库
                int result = orderMapper.insert(order);
                if (result > 0) {
                    successCount++;
                    logger.info("第{}条订单导入成功，订单ID：{}", i + 1, order.getId());
                } else {
                    failCount++;
                    failMessages.add(String.format("第%d条：插入数据库失败", i + 1));
                    logger.error("第{}条订单导入失败：插入数据库失败", i + 1);
                }
            } catch (Exception e) {
                failCount++;
                String errorMsg = String.format("第%d条：%s", i + 1, e.getMessage());
                failMessages.add(errorMsg);
                logger.error("第{}条订单导入失败：{}", i + 1, e.getMessage(), e);
            }
        }

        logger.info("批量导入完成：成功{}条，失败{}条", successCount, failCount);

        // 构建返回结果
        Map<String, Object> result = new java.util.HashMap<>();
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("failMessages", failMessages);

        if (failCount == 0) {
            return AjaxResult.success("批量导入成功，共导入" + successCount + "条订单", result);
        } else {
            return AjaxResult.success("批量导入完成：成功" + successCount + "条，失败" + failCount + "条", result);
        }
    }

    /**
     * 批量更新订单的delivery_id字段
     *
     * @param deliveryId 运送清单ID
     * @param orderIds 订单ID列表
     * @return AjaxResult
     */
    @Override
    @Transactional
    public AjaxResult updateOrderDeliveryId(Integer deliveryId, List<Integer> orderIds) {
        try {
            logger.info("批量更新订单delivery_id，运送清单ID：{}，订单ID列表：{}", deliveryId, orderIds);

            if (orderIds == null || orderIds.isEmpty()) {
                logger.warn("订单ID列表为空，跳过更新");
                return AjaxResult.success("订单ID列表为空，无需更新");
            }

            if (deliveryId == null) {
                logger.error("运送清单ID不能为空");
                return AjaxResult.error("运送清单ID不能为空");
            }

            // 批量更新订单的delivery_id
            int successCount = 0;
            int failCount = 0;
            List<String> failMessages = new ArrayList<>();

            for (Integer orderId : orderIds) {
                try {
                    Order order = orderMapper.selectById(orderId);
                    if (order == null) {
                        failCount++;
                        failMessages.add("订单ID " + orderId + " 不存在");
                        logger.warn("订单不存在，ID：{}", orderId);
                        continue;
                    }

                    order.setDeliveryId(deliveryId);
                    order.setUpdateTime(new Date());
                    try {
                        order.setUpdatedBy(SecurityUtil.getCurrentUserId());
                    } catch (Exception e) {
                        logger.warn("获取当前用户失败，使用订单原有创建人：{}", e.getMessage());
                        if (order.getCreatedBy() != null) {
                            order.setUpdatedBy(order.getCreatedBy());
                        }
                    }

                    int result = orderMapper.updateById(order);
                    if (result > 0) {
                        successCount++;
                        logger.info("更新订单delivery_id成功，订单ID：{}，运送清单ID：{}", orderId, deliveryId);
                    } else {
                        failCount++;
                        failMessages.add("订单ID " + orderId + " 更新失败");
                        logger.warn("更新订单delivery_id失败，订单ID：{}", orderId);
                    }
                } catch (Exception e) {
                    failCount++;
                    failMessages.add("订单ID " + orderId + " 更新异常：" + e.getMessage());
                    logger.error("更新订单delivery_id异常，订单ID：{}，错误：{}", orderId, e.getMessage(), e);
                }
            }

            logger.info("批量更新订单delivery_id完成，成功：{}条，失败：{}条", successCount, failCount);

            // 同步更新delivery表的order_id字段（将所有关联的订单ID用逗号连接）
            if (successCount > 0) {
                try {
                    // 查询该运送清单当前关联的所有订单ID
                    LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>()
                        .eq(Order::getDeliveryId, deliveryId)
                        .select(Order::getId)
                        .orderByAsc(Order::getId);
                    List<Order> associatedOrders = orderMapper.selectList(queryWrapper);
                    
                    // 将所有订单ID用逗号连接
                    String orderIdStr = associatedOrders.stream()
                        .map(order -> String.valueOf(order.getId()))
                        .collect(Collectors.joining(","));
                    
                    // 更新delivery表的order_id字段
                    com.aiotagro.cattletrade.business.entity.Delivery delivery = deliveryMapper.selectById(deliveryId);
                    if (delivery != null) {
                        delivery.setOrderId(orderIdStr);
                        deliveryMapper.updateById(delivery);
                        logger.info("同步更新运送清单order_id成功，运送清单ID：{}，订单ID列表：{}", deliveryId, orderIdStr);
                    } else {
                        logger.warn("运送清单不存在，无法更新order_id，运送清单ID：{}", deliveryId);
                    }
                } catch (Exception e) {
                    logger.error("同步更新运送清单order_id失败，运送清单ID：{}，错误：{}", deliveryId, e.getMessage(), e);
                    // 不抛出异常，只记录日志，因为订单的delivery_id已经更新成功
                }
            }

            if (failCount == 0) {
                return AjaxResult.success("批量更新成功，共更新" + successCount + "条订单");
            } else {
                Map<String, Object> result = new java.util.HashMap<>();
                result.put("successCount", successCount);
                result.put("failCount", failCount);
                result.put("failMessages", failMessages);
                return AjaxResult.success("批量更新完成：成功" + successCount + "条，失败" + failCount + "条", result);
            }
        } catch (Exception e) {
            logger.error("批量更新订单delivery_id异常：{}", e.getMessage(), e);
            return AjaxResult.error("批量更新订单delivery_id失败：" + e.getMessage());
        }
    }

    /**
     * 解除订单与运送清单的关联（将订单的deliveryId设置为null）
     *
     * @param orderId 订单ID
     * @return AjaxResult
     */
    @Override
    @Transactional
    public AjaxResult unbindOrderFromDelivery(Integer orderId) {
        try {
            logger.info("解除订单与运送清单的关联，订单ID：{}", orderId);

            if (orderId == null) {
                logger.error("订单ID不能为空");
                return AjaxResult.error("订单ID不能为空");
            }

            // 查询订单是否存在
            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                logger.error("订单不存在，ID：{}", orderId);
                return AjaxResult.error("订单不存在");
            }

            // 如果订单没有关联运送清单，直接返回成功
            if (order.getDeliveryId() == null) {
                logger.info("订单未关联运送清单，无需解除，订单ID：{}", orderId);
                return AjaxResult.success("订单未关联运送清单，无需解除");
            }

            Integer oldDeliveryId = order.getDeliveryId();
            
            // 将deliveryId设置为null
            order.setDeliveryId(null);
            order.setUpdateTime(new Date());
            try {
                order.setUpdatedBy(SecurityUtil.getCurrentUserId());
            } catch (Exception e) {
                logger.warn("获取当前用户失败，使用订单原有创建人：{}", e.getMessage());
                if (order.getCreatedBy() != null) {
                    order.setUpdatedBy(order.getCreatedBy());
                }
            }

            int result = orderMapper.updateById(order);
            if (result > 0) {
                // 同步更新delivery表的order_id字段（移除该订单ID）
                if (oldDeliveryId != null) {
                    try {
                        com.aiotagro.cattletrade.business.entity.Delivery delivery = deliveryMapper.selectById(oldDeliveryId);
                        if (delivery != null && delivery.getOrderId() != null && !delivery.getOrderId().trim().isEmpty()) {
                            // 从order_id字符串中移除当前订单ID
                            String orderIdStr = delivery.getOrderId();
                            List<String> orderIdList = new ArrayList<>(Arrays.asList(orderIdStr.split(",")));
                            orderIdList.remove(String.valueOf(orderId));
                            
                            // 更新order_id字段
                            if (orderIdList.isEmpty()) {
                                delivery.setOrderId(null);
                            } else {
                                delivery.setOrderId(String.join(",", orderIdList));
                            }
                            deliveryMapper.updateById(delivery);
                            logger.info("同步更新运送清单order_id成功，移除订单ID：{}，运送清单ID：{}", orderId, oldDeliveryId);
                        }
                    } catch (Exception e) {
                        logger.error("同步更新运送清单order_id失败，运送清单ID：{}，错误：{}", oldDeliveryId, e.getMessage(), e);
                        // 不抛出异常，只记录日志
                    }
                }
                
                logger.info("解除订单与运送清单关联成功，订单ID：{}，原运送清单ID：{}", orderId, oldDeliveryId);
                return AjaxResult.success("解除关联成功");
            } else {
                logger.error("解除订单与运送清单关联失败，订单ID：{}", orderId);
                return AjaxResult.error("解除关联失败");
            }
        } catch (Exception e) {
            logger.error("解除订单与运送清单关联异常，订单ID：{}，错误：{}", orderId, e.getMessage(), e);
            return AjaxResult.error("解除关联失败：" + e.getMessage());
        }
    }
}

