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

import com.aiotagro.cattletrade.business.dto.DeliverListDto;
import com.aiotagro.cattletrade.business.dto.DeliveryAddDto;
import com.aiotagro.cattletrade.business.dto.DeliveryCreateDto;
import com.aiotagro.cattletrade.business.dto.DeliveryEditDto;
import com.aiotagro.cattletrade.business.dto.DeliveryQueryDto;
import com.aiotagro.cattletrade.business.dto.yingyan.YingyanStayPoint;
import com.aiotagro.cattletrade.business.dto.yingyan.YingyanTrackPoint;
import com.aiotagro.cattletrade.business.entity.*;
import com.aiotagro.cattletrade.business.mapper.*;
import com.aiotagro.cattletrade.business.service.BaiduYingyanService;
import com.aiotagro.cattletrade.business.service.IDeliveryService;
import com.aiotagro.cattletrade.business.service.IDeliveryDeviceService;
import com.aiotagro.cattletrade.business.service.IXqClientService;
import com.aiotagro.cattletrade.business.vo.DeliveryLogVo;
import com.aiotagro.cattletrade.constant.WarningStatusAdminEnum;
import com.aiotagro.common.core.utils.DateUtils;
import com.aiotagro.common.core.utils.EnumUtil;
import com.aiotagro.common.core.utils.SecurityUtil;
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.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * 运送清单表 服务实现类
 *
 *
 * @author admin
 * @since 2024-12-26
 */
@Service
public class DeliveryServiceImpl extends ServiceImpl<DeliveryMapper, Delivery> implements IDeliveryService {

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

    @Autowired
    private DeliveryDeviceMapper deliveryDeviceMapper;
    @Autowired
    private WarningLogMapper warningLogMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private JbqClientMapper jbqClientMapper;
    @Autowired
    private JbqServerMapper jbqServerMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberDriverMapper memberDriverMapper;
    @Autowired
    private IDeliveryDeviceService deliveryDeviceService;

    @Autowired
    private BaiduYingyanService baiduYingyanService;
    @Autowired
    private IXqClientService xqClientService;
    @Autowired
    private com.aiotagro.cattletrade.business.mapper.OrderMapper orderMapper;
    @Autowired
    private com.aiotagro.cattletrade.business.mapper.VehicleMapper vehicleMapper;

    /**
     * 列表查询
     * @param dto
     * @return
     */
    @Override
    public PageResultResponse<Delivery> pageQuery(DeliveryQueryDto dto) {
        //获取当前登录人id和手机号
        Integer userId = SecurityUtil.getCurrentUserId();
        String currentUserMobile = SecurityUtil.getUserMobile();
        
        // 调试：打印接收到的所有参数
        
        LambdaQueryWrapper<Delivery> wrapper = new LambdaQueryWrapper<>();
        
        // 运输单号模糊查询
        if(StringUtils.isNotEmpty(dto.getDeliveryNumber())){
            wrapper.like(Delivery::getDeliveryNumber, dto.getDeliveryNumber());
        }
        
        // 车牌号精确匹配
        if(StringUtils.isNotEmpty(dto.getLicensePlate())){
            wrapper.eq(Delivery::getLicensePlate, dto.getLicensePlate());
        }
        
        // 状态精确匹配
        if(dto.getStatus() != null){
            wrapper.eq(Delivery::getStatus, dto.getStatus());
        }
        
        // 创建时间精确匹配
        if(StringUtils.isNotEmpty(dto.getCreateTime())){
            try {
                // 将前端发送的时间格式转换为标准格式
                String createTimeStr = dto.getCreateTime() + " 00:00:00";
                Date createDate = DateUtils.parseDate(createTimeStr);
                wrapper.ge(Delivery::getCreateTime, createDate);
                // 添加结束时间（同一天的23:59:59）
                String endTimeStr = dto.getCreateTime() + " 23:59:59";
                Date endDate = DateUtils.parseDate(endTimeStr);
                wrapper.le(Delivery::getCreateTime, endDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        wrapper.orderByDesc(Delivery::getId);
        
        // 判断是否需要数据权限过滤
        boolean needPermissionFilter = !SecurityUtil.isSuperAdmin() && StringUtils.isNotEmpty(currentUserMobile);
        
        List<Delivery> list;
        long total;
        
        if (needPermissionFilter) {
            // 需要权限过滤：先查询所有数据，填充信息，过滤后再分页
            list = this.list(wrapper);
            
            // 填充关联信息（供应商、资金方、采购商、司机等）
            if(CollectionUtils.isNotEmpty(list)){
                list.forEach(delivery -> {
                if(userId.equals(delivery.getCheckBy())){
                    //判断是否需要核验，1：需要核验，2：不需要核验
                    delivery.setIfCheck(1);
                }
                
                // 查询四个角色的手机号（供应商、资金方、采购商、司机）
                try {
                    // 1. 查询供应商信息（supplierId是逗号分隔的字符串）
                    if (StringUtils.isNotEmpty(delivery.getSupplierId())) {
                        String[] supplierIds = delivery.getSupplierId().split(",");
                        List<String> supplierNames = new ArrayList<>();
                        List<String> supplierMobiles = new ArrayList<>();
                        for (String supplierId : supplierIds) {
                            if (StringUtils.isNotEmpty(supplierId.trim())) {
                                try {
                                    Integer sid = Integer.parseInt(supplierId.trim());
                                    // 查询member和member_user表关联数据
                                    Map<String, Object> supplierInfo = memberMapper.selectMemberUserById(sid);
                                    if (supplierInfo != null) {
                                        String username = (String) supplierInfo.get("username");
                                        String mobile = (String) supplierInfo.get("mobile");
                                        if (StringUtils.isNotEmpty(username)) {
                                            supplierNames.add(username);
                                        }
                                        if (StringUtils.isNotEmpty(mobile)) {
                                            supplierMobiles.add(mobile);
                                        }
                                    } else {
                                    }
                                } catch (NumberFormatException e) {
                                }
                            }
                        }
                        if (!supplierNames.isEmpty()) {
                            delivery.setSupplierName(String.join(",", supplierNames));
                        } else if (!supplierMobiles.isEmpty()) {
                            // 如果用户名为空，使用手机号作为备选
                            delivery.setSupplierName(String.join(",", supplierMobiles));
                        }
                        if (!supplierMobiles.isEmpty()) {
                            delivery.setSupplierMobile(String.join(",", supplierMobiles));
                        }
                    }
                    
                    // 2. 查询资金方信息
                    if (delivery.getFundId() != null) {
                        Map<String, Object> fundInfo = memberMapper.selectMemberUserById(delivery.getFundId());
                        if (fundInfo != null) {
                            String username = (String) fundInfo.get("username");
                            String mobile = (String) fundInfo.get("mobile");
                            if (StringUtils.isNotEmpty(username)) {
                                delivery.setFundName(username);
                            } else if (StringUtils.isNotEmpty(mobile)) {
                                // 如果用户名为空，使用手机号作为备选
                                delivery.setFundName(mobile);
                            }
                            if (StringUtils.isNotEmpty(mobile)) {
                                delivery.setFundMobile(mobile);
                            }
                        } else {
                        }
                    }
                    
                    // 3. 查询采购商信息
                    if (delivery.getBuyerId() != null) {
                        Map<String, Object> buyerInfo = memberMapper.selectMemberUserById(delivery.getBuyerId());
                        if (buyerInfo != null) {
                            String username = (String) buyerInfo.get("username");
                            String mobile = (String) buyerInfo.get("mobile");
                            if (StringUtils.isNotEmpty(username)) {
                                delivery.setBuyerName(username);
                            } else if (StringUtils.isNotEmpty(mobile)) {
                                // 如果用户名为空，使用手机号作为备选
                                delivery.setBuyerName(mobile);
                            }
                            if (StringUtils.isNotEmpty(mobile)) {
                                delivery.setBuyerMobile(mobile);
                            }
                        } else {
                        }
                    }
                    
                    // 4. 查询司机手机号（如果有司机ID）
                    if (delivery.getDriverId() != null) {
                        try {
                            Map<String, Object> driverInfo = memberDriverMapper.selectDriverById(delivery.getDriverId());
                            if (driverInfo != null) {
                                String driverName = (String) driverInfo.get("username");
                                String driverMobile = (String) driverInfo.get("mobile");
                                String carImg = (String) driverInfo.get("car_img");
                                
                                if (StringUtils.isNotEmpty(driverMobile)) {
                                    delivery.setDriverMobile(driverMobile);
                                }
                                if (StringUtils.isNotEmpty(driverName)) {
                                    delivery.setDriverName(driverName);
                                }
                                
                                // 优先从车辆表获取车身照片（根据车牌号）
                                // 如果车辆表中没有，再从司机信息中获取作为后备
                                boolean vehiclePhotoSet = false;
                                if (delivery.getLicensePlate() != null && StringUtils.isNotEmpty(delivery.getLicensePlate())) {
                                    try {
                                        Vehicle vehicle = vehicleMapper.selectByLicensePlate(delivery.getLicensePlate());
                                        if (vehicle != null) {
                                            String carFrontPhoto = vehicle.getCarFrontPhoto();
                                            String carRearPhoto = vehicle.getCarRearPhoto();
                                            if (StringUtils.isNotEmpty(carFrontPhoto) || StringUtils.isNotEmpty(carRearPhoto)) {
                                                delivery.setCarFrontPhoto(StringUtils.isNotEmpty(carFrontPhoto) ? carFrontPhoto : null);
                                                delivery.setCarBehindPhoto(StringUtils.isNotEmpty(carRearPhoto) ? carRearPhoto : null);
                                                vehiclePhotoSet = true;
                                                logger.debug("从车辆表获取照片: 车牌号={}, 车头照片={}, 车尾照片={}", 
                                                    delivery.getLicensePlate(), delivery.getCarFrontPhoto(), delivery.getCarBehindPhoto());
                                            }
                                        }
                                    } catch (Exception e) {
                                        logger.error("从车辆表获取照片失败: " + e.getMessage(), e);
                                    }
                                }
                                
                                // 如果车辆表中没有照片，从司机信息中获取作为后备
                                if (!vehiclePhotoSet && carImg != null && !carImg.isEmpty()) {
                                    // 按逗号分割car_img字段，分别映射到车头和车尾照片
                                    String[] carImgUrls = carImg.split(",");
                                    
                                    if (carImgUrls.length >= 2) {
                                        // 逗号前面的URL作为车尾照片
                                        String carBehindPhoto = carImgUrls[0].trim();
                                        // 逗号后面的URL作为车头照片
                                        String carFrontPhoto = carImgUrls[1].trim();
                                        
                                        delivery.setCarBehindPhoto(carBehindPhoto);
                                        delivery.setCarFrontPhoto(carFrontPhoto);
                                    } else if (carImgUrls.length == 1) {
                                        // 只有一个URL时，同时设置为车头和车尾照片
                                        String singlePhoto = carImgUrls[0].trim();
                                        delivery.setCarFrontPhoto(singlePhoto);
                                        delivery.setCarBehindPhoto(singlePhoto);
                                    } else {
                                        // 没有有效URL，设置为null
                                        delivery.setCarFrontPhoto(null);
                                        delivery.setCarBehindPhoto(null);
                                    }
                                } else if (!vehiclePhotoSet) {
                                    // 如果车辆表和司机信息中都没有照片，设置为null
                                    delivery.setCarFrontPhoto(null);
                                    delivery.setCarBehindPhoto(null);
                                }
                            }
                        } catch (Exception e) {
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                // 统计登记设备数量（耳标+项圈）
                Integer currentDeliveryId = delivery.getId();
                if (currentDeliveryId != null) {
                    try {
                        // 统计耳标设备数量
                        LambdaQueryWrapper<DeliveryDevice> earTagWrapper = new LambdaQueryWrapper<>();
                        earTagWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                     .eq(DeliveryDevice::getDeviceType, 2);
                        long earTagCount = deliveryDeviceService.count(earTagWrapper);
                        
                        // 统计项圈设备数量
                        LambdaQueryWrapper<DeliveryDevice> collarWrapper = new LambdaQueryWrapper<>();
                        collarWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                    .eq(DeliveryDevice::getDeviceType, 3);
                        long collarCount = deliveryDeviceService.count(collarWrapper);
                        
                        // 设置总设备数量和耳标数量
                        int totalDeviceCount = (int) (earTagCount + collarCount);
                        delivery.setRegisteredJbqCount(totalDeviceCount);
                        delivery.setEarTagCount((int) earTagCount);
                        
                        // 设置已分配设备数量，与登记设备数量保持一致
                        delivery.setBindJbqCount(totalDeviceCount);
                        
                        // 统计已佩戴设备数量（bandge_status = 1）
                        int wornDeviceCount = 0;
                        try {
                            // 统计已佩戴的耳标设备数量（通过delivery_device表关联）
                            LambdaQueryWrapper<DeliveryDevice> wornEarTagWrapper = new LambdaQueryWrapper<>();
                            wornEarTagWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                            .eq(DeliveryDevice::getDeviceType, 2)
                                            .eq(DeliveryDevice::getIsWare, 1); // 1表示已佩戴
                            long wornEarTagCount = deliveryDeviceService.count(wornEarTagWrapper);
                            
                            // 统计已佩戴的项圈设备数量（通过delivery_device表关联xq_client表）
                            LambdaQueryWrapper<DeliveryDevice> wornCollarWrapper = new LambdaQueryWrapper<>();
                            wornCollarWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                            .eq(DeliveryDevice::getDeviceType, 3);
                            List<DeliveryDevice> collarDevices = deliveryDeviceService.list(wornCollarWrapper);
                            
                            int wornCollarCount = 0;
                            for (DeliveryDevice device : collarDevices) {
                                // 查询xq_client表中的bandge_status
                                LambdaQueryWrapper<XqClient> xqWrapper = new LambdaQueryWrapper<>();
                                xqWrapper.eq(XqClient::getSn, device.getDeviceId());
                                XqClient xqClient = xqClientService.getOne(xqWrapper);
                                if (xqClient != null && xqClient.getBandgeStatus() != null && xqClient.getBandgeStatus() == 1) {
                                    wornCollarCount++;
                                }
                            }
                            
                            wornDeviceCount = (int) (wornEarTagCount + wornCollarCount);
                            delivery.setWareCount(wornDeviceCount);
                        } catch (Exception e) {
                            delivery.setWareCount(0);
                        }
                    } catch (Exception e) {
                        delivery.setRegisteredJbqCount(0);
                        delivery.setBindJbqCount(0);
                        delivery.setWareCount(0);
                    }
                }
            });
            }
            
            // 数据权限过滤：非超级管理员只能看到与自己手机号相关的订单
            list = list.stream().filter(delivery -> {
                boolean hasPermission = false;
                
                // 检查是否是司机
                if (StringUtils.isNotEmpty(delivery.getDriverMobile()) && 
                    currentUserMobile.equals(delivery.getDriverMobile())) {
                    hasPermission = true;
                }
                
                // 检查是否是供应商（可能有多个供应商）
                if (!hasPermission && StringUtils.isNotEmpty(delivery.getSupplierMobile())) {
                    String[] supplierMobiles = delivery.getSupplierMobile().split(",");
                    for (String mobile : supplierMobiles) {
                        if (currentUserMobile.equals(mobile.trim())) {
                            hasPermission = true;
                            break;
                        }
                    }
                }
                
                // 检查是否是资金方
                if (!hasPermission && StringUtils.isNotEmpty(delivery.getFundMobile()) && 
                    currentUserMobile.equals(delivery.getFundMobile())) {
                    hasPermission = true;
                }
                
                // 检查是否是采购商
                if (!hasPermission && StringUtils.isNotEmpty(delivery.getBuyerMobile()) && 
                    currentUserMobile.equals(delivery.getBuyerMobile())) {
                    hasPermission = true;
                }
                
                return hasPermission;
            }).collect(Collectors.toList());
            
            // 获取过滤后的总数
            total = list.size();
            
            // 手动分页
            int startIndex = (dto.getPageNum() - 1) * dto.getPageSize();
            int endIndex = Math.min(startIndex + dto.getPageSize(), list.size());
            if (startIndex < list.size()) {
                list = list.subList(startIndex, endIndex);
            } else {
                list = new ArrayList<>();
            }
        } else {
            // 不需要权限过滤：直接使用PageHelper分页
            Page<Delivery> result = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
            list = this.list(wrapper);
            total = result.getTotal();
            
            // 填充关联信息（供应商、资金方、采购商、司机等）
            if(CollectionUtils.isNotEmpty(list)){
                list.forEach(delivery -> {
                    if(userId.equals(delivery.getCheckBy())){
                        //判断是否需要核验，1：需要核验，2：不需要核验
                        delivery.setIfCheck(1);
                    }
                    
                    // 查询四个角色的手机号（供应商、资金方、采购商、司机）
                    try {
                        // 1. 查询供应商信息（supplierId是逗号分隔的字符串）
                        if (StringUtils.isNotEmpty(delivery.getSupplierId())) {
                            String[] supplierIds = delivery.getSupplierId().split(",");
                            List<String> supplierNames = new ArrayList<>();
                            List<String> supplierMobiles = new ArrayList<>();
                            for (String supplierId : supplierIds) {
                                if (StringUtils.isNotEmpty(supplierId.trim())) {
                                    try {
                                        Integer sid = Integer.parseInt(supplierId.trim());
                                        // 查询member和member_user表关联数据
                                        Map<String, Object> supplierInfo = memberMapper.selectMemberUserById(sid);
                                        if (supplierInfo != null) {
                                            String username = (String) supplierInfo.get("username");
                                            String mobile = (String) supplierInfo.get("mobile");
                                            if (StringUtils.isNotEmpty(username)) {
                                                supplierNames.add(username);
                                            }
                                            if (StringUtils.isNotEmpty(mobile)) {
                                                supplierMobiles.add(mobile);
                                            }
                                        }
                                    } catch (NumberFormatException e) {
                                    }
                                }
                            }
                            if (!supplierNames.isEmpty()) {
                                delivery.setSupplierName(String.join(",", supplierNames));
                            } else if (!supplierMobiles.isEmpty()) {
                                // 如果用户名为空，使用手机号作为备选
                                delivery.setSupplierName(String.join(",", supplierMobiles));
                            }
                            if (!supplierMobiles.isEmpty()) {
                                delivery.setSupplierMobile(String.join(",", supplierMobiles));
                            }
                        }
                        
                        // 2. 查询资金方信息
                        if (delivery.getFundId() != null) {
                            Map<String, Object> fundInfo = memberMapper.selectMemberUserById(delivery.getFundId());
                            if (fundInfo != null) {
                                String username = (String) fundInfo.get("username");
                                String mobile = (String) fundInfo.get("mobile");
                                if (StringUtils.isNotEmpty(username)) {
                                    delivery.setFundName(username);
                                } else if (StringUtils.isNotEmpty(mobile)) {
                                    // 如果用户名为空，使用手机号作为备选
                                    delivery.setFundName(mobile);
                                }
                                if (StringUtils.isNotEmpty(mobile)) {
                                    delivery.setFundMobile(mobile);
                                }
                            }
                        }
                        
                        // 3. 查询采购商信息
                        if (delivery.getBuyerId() != null) {
                            Map<String, Object> buyerInfo = memberMapper.selectMemberUserById(delivery.getBuyerId());
                            if (buyerInfo != null) {
                                String username = (String) buyerInfo.get("username");
                                String mobile = (String) buyerInfo.get("mobile");
                                if (StringUtils.isNotEmpty(username)) {
                                    delivery.setBuyerName(username);
                                } else if (StringUtils.isNotEmpty(mobile)) {
                                    // 如果用户名为空，使用手机号作为备选
                                    delivery.setBuyerName(mobile);
                                }
                                if (StringUtils.isNotEmpty(mobile)) {
                                    delivery.setBuyerMobile(mobile);
                                }
                            }
                        }
                        
                        // 4. 查询司机手机号（如果有司机ID）
                        if (delivery.getDriverId() != null) {
                            try {
                                Map<String, Object> driverInfo = memberDriverMapper.selectDriverById(delivery.getDriverId());
                                if (driverInfo != null) {
                                    String driverName = (String) driverInfo.get("username");
                                    String driverMobile = (String) driverInfo.get("mobile");
                                    String carImg = (String) driverInfo.get("car_img");
                                    
                                    if (StringUtils.isNotEmpty(driverMobile)) {
                                        delivery.setDriverMobile(driverMobile);
                                    }
                                    if (StringUtils.isNotEmpty(driverName)) {
                                        delivery.setDriverName(driverName);
                                    }
                                    
                                    // 优先从车辆表获取车身照片（根据车牌号）
                                    // 如果车辆表中没有，再从司机信息中获取作为后备
                                    boolean vehiclePhotoSet = false;
                                    if (delivery.getLicensePlate() != null && StringUtils.isNotEmpty(delivery.getLicensePlate())) {
                                        try {
                                            Vehicle vehicle = vehicleMapper.selectByLicensePlate(delivery.getLicensePlate());
                                            if (vehicle != null) {
                                                String carFrontPhoto = vehicle.getCarFrontPhoto();
                                                String carRearPhoto = vehicle.getCarRearPhoto();
                                                if (StringUtils.isNotEmpty(carFrontPhoto) || StringUtils.isNotEmpty(carRearPhoto)) {
                                                    delivery.setCarFrontPhoto(StringUtils.isNotEmpty(carFrontPhoto) ? carFrontPhoto : null);
                                                    delivery.setCarBehindPhoto(StringUtils.isNotEmpty(carRearPhoto) ? carRearPhoto : null);
                                                    vehiclePhotoSet = true;
                                                }
                                            }
                                        } catch (Exception e) {
                                            logger.error("从车辆表获取照片失败: " + e.getMessage(), e);
                                        }
                                    }
                                    
                                    // 如果车辆表中没有照片，从司机信息中获取作为后备
                                    if (!vehiclePhotoSet && carImg != null && !carImg.isEmpty()) {
                                        // 按逗号分割car_img字段，分别映射到车头和车尾照片
                                        String[] carImgUrls = carImg.split(",");
                                        
                                        if (carImgUrls.length >= 2) {
                                            // 逗号前面的URL作为车尾照片
                                            String carBehindPhoto = carImgUrls[0].trim();
                                            // 逗号后面的URL作为车头照片
                                            String carFrontPhoto = carImgUrls[1].trim();
                                            
                                            delivery.setCarBehindPhoto(carBehindPhoto);
                                            delivery.setCarFrontPhoto(carFrontPhoto);
                                        } else if (carImgUrls.length == 1) {
                                            // 只有一个URL时，同时设置为车头和车尾照片
                                            String singlePhoto = carImgUrls[0].trim();
                                            delivery.setCarFrontPhoto(singlePhoto);
                                            delivery.setCarBehindPhoto(singlePhoto);
                                        } else {
                                            // 没有有效URL，设置为null
                                            delivery.setCarFrontPhoto(null);
                                            delivery.setCarBehindPhoto(null);
                                        }
                                    } else if (!vehiclePhotoSet) {
                                        // 如果车辆表和司机信息中都没有照片，设置为null
                                        delivery.setCarFrontPhoto(null);
                                        delivery.setCarBehindPhoto(null);
                                    }
                                }
                            } catch (Exception e) {
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                    // 统计登记设备数量（耳标+项圈）
                    Integer currentDeliveryId = delivery.getId();
                    if (currentDeliveryId != null) {
                        try {
                            // 统计耳标设备数量
                            LambdaQueryWrapper<DeliveryDevice> earTagWrapper = new LambdaQueryWrapper<>();
                            earTagWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                         .eq(DeliveryDevice::getDeviceType, 2);
                            long earTagCount = deliveryDeviceService.count(earTagWrapper);
                            
                            // 统计项圈设备数量
                            LambdaQueryWrapper<DeliveryDevice> collarWrapper = new LambdaQueryWrapper<>();
                            collarWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                        .eq(DeliveryDevice::getDeviceType, 3);
                            long collarCount = deliveryDeviceService.count(collarWrapper);
                            
                            // 设置总设备数量和耳标数量
                            int totalDeviceCount = (int) (earTagCount + collarCount);
                            delivery.setRegisteredJbqCount(totalDeviceCount);
                            delivery.setEarTagCount((int) earTagCount);
                            
                            // 设置已分配设备数量，与登记设备数量保持一致
                            delivery.setBindJbqCount(totalDeviceCount);
                            
                            // 统计已佩戴设备数量（bandge_status = 1）
                            int wornDeviceCount = 0;
                            try {
                                // 统计已佩戴的耳标设备数量（通过delivery_device表关联）
                                LambdaQueryWrapper<DeliveryDevice> wornEarTagWrapper = new LambdaQueryWrapper<>();
                                wornEarTagWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                                .eq(DeliveryDevice::getDeviceType, 2)
                                                .eq(DeliveryDevice::getIsWare, 1); // 1表示已佩戴
                                long wornEarTagCount = deliveryDeviceService.count(wornEarTagWrapper);
                                
                                // 统计已佩戴的项圈设备数量（通过delivery_device表关联xq_client表）
                                LambdaQueryWrapper<DeliveryDevice> wornCollarWrapper = new LambdaQueryWrapper<>();
                                wornCollarWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                                .eq(DeliveryDevice::getDeviceType, 3);
                                List<DeliveryDevice> collarDevices = deliveryDeviceService.list(wornCollarWrapper);
                                
                                int wornCollarCount = 0;
                                for (DeliveryDevice device : collarDevices) {
                                    // 查询xq_client表中的bandge_status
                                    LambdaQueryWrapper<XqClient> xqWrapper = new LambdaQueryWrapper<>();
                                    xqWrapper.eq(XqClient::getSn, device.getDeviceId());
                                    XqClient xqClient = xqClientService.getOne(xqWrapper);
                                    if (xqClient != null && xqClient.getBandgeStatus() != null && xqClient.getBandgeStatus() == 1) {
                                        wornCollarCount++;
                                    }
                                }
                                
                                wornDeviceCount = (int) (wornEarTagCount + wornCollarCount);
                                delivery.setWareCount(wornDeviceCount);
                            } catch (Exception e) {
                                delivery.setWareCount(0);
                            }
                        } catch (Exception e) {
                            delivery.setRegisteredJbqCount(0);
                            delivery.setBindJbqCount(0);
                            delivery.setWareCount(0);
                        }
                    }
                });
            }
        }
        
        // 返回分页结果
        return new PageResultResponse<>(total, list);
    }

    /**
     * 我要装车
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public AjaxResult addDelivery(DeliveryAddDto dto) {
        //获取当前登录信息
        Integer userId = SecurityUtil.getCurrentUserId();
        LocalDateTime now = LocalDateTime.now();
        String deliverNo = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        Delivery delivery = new Delivery();
        BeanUtils.copyProperties(dto, delivery);
        delivery.setStatus(1);
        delivery.setDeliveryNumber(deliverNo);
        delivery.setCreatedBy(userId);
        delivery.setCreateTime(new Date());
        List<String> jbqDeviceSn = dto.getJbqDeviceSn();
        if(CollectionUtils.isNotEmpty(jbqDeviceSn)){
            //校验设备是否已注册
            List<JbqClient> deliveryDevices = jbqClientMapper.selectList(new LambdaQueryWrapper<JbqClient>().in(JbqClient::getDeviceId, jbqDeviceSn));
            if(CollectionUtils.isNotEmpty(deliveryDevices)){
                List<String> collect = deliveryDevices.stream().map(JbqClient::getDeviceId).collect(Collectors.toList());
                jbqDeviceSn = collect;
            }else{
                return AjaxResult.error("设备数据有误！");
            }
            delivery.setRegisteredJbqCount(jbqDeviceSn.size());
        }else{
            delivery.setRegisteredJbqCount(0);
        }
        boolean save = this.save(delivery);
        if(save){
            Integer deliveryId = delivery.getId();
            //新增设备
            if(CollectionUtils.isNotEmpty(jbqDeviceSn)){
                jbqDeviceSn.forEach(deviceSn -> {
                        DeliveryDevice deliveryDevice = new DeliveryDevice();
                        deliveryDevice.setDeliveryId(deliveryId);
                        deliveryDevice.setDeviceType(2);
                        deliveryDevice.setDeviceId(deviceSn);
                        deliveryDeviceMapper.insert(deliveryDevice);
                });
            }
            //校验主机是否在系统中存在
            Long serverCount = jbqServerMapper.selectCount(new LambdaQueryWrapper<JbqServer>().eq(JbqServer::getDeviceId, dto.getServerDeviceSn()));
            if(serverCount.intValue() == 1){
                DeliveryDevice deliveryDevice = new DeliveryDevice();
                deliveryDevice.setDeliveryId(deliveryId);
                deliveryDevice.setDeviceType(1);
                deliveryDevice.setDeviceId(dto.getServerDeviceSn());
                deliveryDeviceMapper.insert(deliveryDevice);
            }else{
                throw new IllegalArgumentException("主机未注册！");
            }
        }
        return AjaxResult.success("装车成功！");
    }

    /**
     * 创建运送清单（PC端）
     *
     * @param dto 运送清单创建DTO
     * @return AjaxResult
     */
    @Transactional
    @Override
    public AjaxResult createDelivery(DeliveryCreateDto dto) {
        // 入参日志
        logger.info("创建装车订单: shipperId={}, buyerId={}, plateNumber={}, driverName={}, cattleCount={}", 
            dto.getShipperId(), dto.getBuyerId(), dto.getPlateNumber(), dto.getDriverName(), dto.getCattleCount());
        // 校验时间逻辑
        if (dto.getEstimatedArrivalTime().before(dto.getEstimatedDepartureTime())) {
            return AjaxResult.error("预计到达时间必须晚于出发时间");
        }
        
        // 获取当前登录用户
        Integer userId = SecurityUtil.getCurrentUserId();
        String userName = SecurityUtil.getUserName();
        
        // 生成运输单号
        LocalDateTime now = LocalDateTime.now();
        String deliveryNumber = "YS" + now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        
        // 创建运送清单
        Delivery delivery = new Delivery();
        delivery.setDeliveryNumber(deliveryNumber);
        delivery.setOrderId(dto.getOrderId());
        // 基本信息
        delivery.setLicensePlate(dto.getPlateNumber());
        
        // 设置卖方和买方ID
        if (dto.getShipperId() != null) {
            delivery.setSupplierId(String.valueOf(dto.getShipperId()));
        }
        if (dto.getBuyerId() != null) {
            delivery.setBuyerId(dto.getBuyerId());
        }
        
        // 如果有司机ID，从司机表查询司机信息（仅查询司机姓名和电话，不查询车牌号）
        if (dto.getDriverId() != null) {
            try {
                Map<String, Object> driverInfo = memberDriverMapper.selectDriverById(dto.getDriverId());
                if (driverInfo != null) {
                    String driverUsername = (String) driverInfo.get("username");
                    String driverMobile = (String) driverInfo.get("mobile");
                    String carImg = (String) driverInfo.get("car_img");
                    
                    // 设置司机信息 - 优先使用司机表的username
                    if (StringUtils.isNotEmpty(driverUsername)) {
                        delivery.setDriverName(driverUsername);
                    } else {
                        delivery.setDriverName(dto.getDriverName());
                    }
                    
                    // 设置司机手机号
                    if (StringUtils.isNotEmpty(driverMobile)) {
                        delivery.setDriverMobile(driverMobile);
                    } else {
                        delivery.setDriverMobile(dto.getDriverPhone());
                    }
                    
                    // 设置司机ID
                    delivery.setDriverId(dto.getDriverId());
                    logger.info("设置司机信息: driverId={}, 姓名={}, 手机={}", 
                        dto.getDriverId(), delivery.getDriverName(), delivery.getDriverMobile());
                }
            } catch (Exception e) {
                delivery.setDriverName(dto.getDriverName());
                delivery.setDriverMobile(dto.getDriverPhone());
            }
        } else {
            // 没有司机ID，直接使用DTO中的数据
            delivery.setDriverName(dto.getDriverName());
            delivery.setDriverMobile(dto.getDriverPhone());
        }
        // 地址与坐标
        delivery.setStartLocation(dto.getStartLocation());
        delivery.setStartLon(dto.getStartLon());
        delivery.setStartLat(dto.getStartLat());
        delivery.setEndLocation(dto.getEndLocation());
        delivery.setEndLon(dto.getEndLon());
        delivery.setEndLat(dto.getEndLat());
        // 预计出发时间
        delivery.setEstimatedDepartureTime(dto.getEstimatedDepartureTime());
        // 预计到达时间
        delivery.setEstimatedDeliveryTime(dto.getEstimatedArrivalTime());
        // 装车数量（牛只数量）
        if (dto.getCattleCount() != null && dto.getCattleCount() > 0) {
            delivery.setRatedQuantity(dto.getCattleCount());
            logger.info("设置装车数量: ratedQuantity={}", dto.getCattleCount());
        } else {
            logger.warn("装车数量为空或无效: cattleCount={}, 跳过设置", dto.getCattleCount());
            delivery.setRatedQuantity(null);
        }
        // 过磅重量：将空字符串转换为null，避免数据库DECIMAL字段类型错误
        delivery.setEmptyWeight(StringUtils.isNotEmpty(dto.getEmptyWeight()) ? dto.getEmptyWeight() : null);
        delivery.setEntruckWeight(StringUtils.isNotEmpty(dto.getEntruckWeight()) ? dto.getEntruckWeight() : null);
        delivery.setLandingEntruckWeight(StringUtils.isNotEmpty(dto.getLandingEntruckWeight()) ? dto.getLandingEntruckWeight() : null);
        // 照片
        delivery.setQuarantineTickeyUrl(dto.getQuarantineTickeyUrl());
        delivery.setPoundListImg(dto.getPoundListImg());
        delivery.setEmptyVehicleFrontPhoto(dto.getEmptyVehicleFrontPhoto());
        delivery.setLoadedVehicleFrontPhoto(dto.getLoadedVehicleFrontPhoto());
        delivery.setLoadedVehicleWeightPhoto(dto.getLoadedVehicleWeightPhoto());
        delivery.setDriverIdCardPhoto(dto.getDriverIdCardPhoto());
        delivery.setDestinationPoundListImg(dto.getDestinationPoundListImg());
        delivery.setDestinationVehicleFrontPhoto(dto.getDestinationVehicleFrontPhoto());
        // 视频
        delivery.setEntruckWeightVideo(dto.getEntruckWeightVideo());
        delivery.setEmptyWeightVideo(dto.getEmptyWeightVideo());
        delivery.setEntruckVideo(dto.getCattleLoadingVideo());
        delivery.setControlSlotVideo(dto.getControlSlotVideo());
        delivery.setCattleLoadingCircleVideo(dto.getCattleLoadingCircleVideo());
        delivery.setUnloadCattleVideo(dto.getUnloadCattleVideo());
        delivery.setDestinationWeightVideo(dto.getDestinationWeightVideo());
        
        // 根据车牌号查询车辆照片
        if (StringUtils.isNotEmpty(dto.getPlateNumber())) {
            try {
                Vehicle vehicle = vehicleMapper.selectByLicensePlate(dto.getPlateNumber());
                if (vehicle != null) {
                    // 将空字符串转换为null，避免前端显示问题
                    String carFrontPhoto = vehicle.getCarFrontPhoto();
                    String carRearPhoto = vehicle.getCarRearPhoto();
                    delivery.setCarFrontPhoto(StringUtils.isNotEmpty(carFrontPhoto) ? carFrontPhoto : null);
                    delivery.setCarBehindPhoto(StringUtils.isNotEmpty(carRearPhoto) ? carRearPhoto : null);
                    logger.info("设置车辆照片: 车头照片={}, 车尾照片={}", 
                        delivery.getCarFrontPhoto(), delivery.getCarBehindPhoto());
                }
            } catch (Exception e) {
            }
        }

        delivery.setStatus(1); // 待装车
        delivery.setCreatedBy(userId);
        delivery.setCreateByName(userName);
        delivery.setCreateTime(new Date());
        
        // 保存运送清单
        boolean saved = this.save(delivery);
        logger.info("保存装车订单: deliveryNumber={}, licensePlate={}, driverName={}, status={}, ratedQuantity={}", 
            delivery.getDeliveryNumber(), delivery.getLicensePlate(), delivery.getDriverName(), 
            delivery.getStatus(), delivery.getRatedQuantity());
        if (!saved) {
            return AjaxResult.error("创建失败");
        }
        
        // 如果选择了设备，保存设备关联
        Integer deliveryId = delivery.getId();
        
        // 保存主机设备
        if (dto.getServerId() != null) {
            Long serverCount = jbqServerMapper.selectCount(
                new LambdaQueryWrapper<JbqServer>().eq(JbqServer::getId, dto.getServerId())
            );
            if (serverCount > 0) {
                DeliveryDevice serverDevice = new DeliveryDevice();
                serverDevice.setDeliveryId(deliveryId);
                serverDevice.setDeviceType(1);
                serverDevice.setDeviceId(dto.getServerId().toString());
                deliveryDeviceMapper.insert(serverDevice);
            }
        }
        
        // 保存耳标设备
        if (CollectionUtils.isNotEmpty(dto.getEartagIds())) {
            for (Integer eartagId : dto.getEartagIds()) {
                DeliveryDevice eartagDevice = new DeliveryDevice();
                eartagDevice.setDeliveryId(deliveryId);
                eartagDevice.setDeviceType(2);
                eartagDevice.setDeviceId(eartagId.toString());
                deliveryDeviceMapper.insert(eartagDevice);
            }
        }
        
        // 保存项圈设备
        if (CollectionUtils.isNotEmpty(dto.getCollarIds())) {
            for (Integer collarId : dto.getCollarIds()) {
                DeliveryDevice collarDevice = new DeliveryDevice();
                collarDevice.setDeliveryId(deliveryId);
                collarDevice.setDeviceType(3);
                collarDevice.setDeviceId(collarId.toString());
                deliveryDeviceMapper.insert(collarDevice);
            }
        }
        
        return AjaxResult.success("创建成功", delivery);
    }

    @Override
    public AjaxResult viewDelivery(Integer id) {
        //获取当前登录人id
        Integer userId = SecurityUtil.getCurrentUserId();
        Delivery delivery = this.getById(id);
        if(delivery != null){
            List<DeliveryDevice> deliveryDevices = deliveryDeviceMapper.selectList(new LambdaQueryWrapper<DeliveryDevice>().eq(DeliveryDevice::getDeliveryId, id));
            //耳标设备集合
            List<String> deviceIds = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(deliveryDevices)){
                deliveryDevices.forEach(deliveryDevice -> {
                    if(deliveryDevice.getDeviceType() == 1){
                        delivery.setServerDeviceId(deliveryDevice.getDeviceId());
                    }else if(deliveryDevice.getDeviceType() == 2){
                        deviceIds.add(deliveryDevice.getDeviceId());
                    }
                });
            }
            delivery.setDeviceIds(deviceIds);
            if(userId == delivery.getCheckBy()){
                //判断是否需要核验，1：需要核验，2：不需要核验
                delivery.setIfCheck(1);
            }
        }
        return AjaxResult.success(delivery);
    }

    /**
     * 编辑运送清单
     *
     * @param dto 运送清单编辑DTO
     * @return AjaxResult
     */
    @Transactional
    @Override
    public AjaxResult updateDeliveryInfo(DeliveryEditDto dto) {
        // 获取当前登录用户
        Integer userId = SecurityUtil.getCurrentUserId();
        
        // 入参日志
        logger.info("更新运送清单: deliveryId={}, ratedQuantity={}, quarantineTickeyUrl={}, poundListImg={}, cattleLoadingVideo={}", 
            dto.getDeliveryId(), dto.getRatedQuantity(), dto.getQuarantineTickeyUrl(), 
            dto.getPoundListImg(), dto.getCattleLoadingVideo());
        
        // 查询运送清单是否存在
        Delivery delivery = this.getById(dto.getDeliveryId());
        if (delivery == null) {
            return AjaxResult.error("运送清单不存在");
        }
        
        // 检查权限：只有创建者或超级管理员可以编辑
        if (!SecurityUtil.isSuperAdmin() && !userId.equals(delivery.getCreatedBy())) {
            return AjaxResult.error("无权限编辑此运送清单");
        }
        
        // 更新运送清单信息
        if (dto.getDeliveryTitle() != null) {
            delivery.setDeliveryTitle(dto.getDeliveryTitle());
        }
        if (dto.getRatedQuantity() != null && dto.getRatedQuantity() > 0) {
            delivery.setRatedQuantity(dto.getRatedQuantity());
            logger.info("更新装车数量: ratedQuantity={}", dto.getRatedQuantity());
        } else if (dto.getRatedQuantity() != null && dto.getRatedQuantity() <= 0) {
            logger.warn("装车数量无效: ratedQuantity={}, 跳过更新", dto.getRatedQuantity());
        }
        if (dto.getStartLocation() != null) {
            delivery.setStartLocation(dto.getStartLocation());
        }
        if (dto.getStartLat() != null) {
            delivery.setStartLat(dto.getStartLat());
        }
        if (dto.getStartLon() != null) {
            delivery.setStartLon(dto.getStartLon());
        }
        if (dto.getEndLocation() != null) {
            delivery.setEndLocation(dto.getEndLocation());
        }
        if (dto.getEndLat() != null) {
            delivery.setEndLat(dto.getEndLat());
        }
        if (dto.getEndLon() != null) {
            delivery.setEndLon(dto.getEndLon());
        }
        
        // 更新时间字段
        if (dto.getEstimatedDepartureTime() != null) {
            delivery.setEstimatedDepartureTime(dto.getEstimatedDepartureTime());
        }
        if (dto.getEstimatedArrivalTime() != null) {
            delivery.setEstimatedDeliveryTime(dto.getEstimatedArrivalTime());
        }
        
        // 更新其他业务字段
        if (dto.getSupplierId() != null) {
            delivery.setSupplierId(dto.getSupplierId());
        }
        if (dto.getFundId() != null) {
            delivery.setFundId(dto.getFundId());
        }
        if (dto.getDriverId() != null) {
            delivery.setDriverId(dto.getDriverId());
        }
        if (dto.getDriverMobile() != null) {
            delivery.setDriverMobile(dto.getDriverMobile());
        }
        if (dto.getLicensePlate() != null) {
            String oldLicensePlate = delivery.getLicensePlate();
            String newLicensePlate = StringUtils.isNotEmpty(dto.getLicensePlate()) ? dto.getLicensePlate().trim() : null;
            delivery.setLicensePlate(newLicensePlate);
            logger.info("更新车牌号: oldLicensePlate={}, newLicensePlate={}", oldLicensePlate, newLicensePlate);
            
            // 如果车牌号发生变化，且运单状态为运输中(2)，需要同步更新鹰眼终端名称
            if (StringUtils.isNotEmpty(newLicensePlate) && 
                delivery.getStatus() != null && 
                delivery.getStatus() == 2) {
                
                // 检查车牌号是否真的发生了变化
                boolean licensePlateChanged = oldLicensePlate == null || !newLicensePlate.equals(oldLicensePlate);
                
                if (licensePlateChanged) {
                    String newEntityName = newLicensePlate;
                    String oldEntityName = delivery.getYingyanEntityName();
                    
                    // 更新鹰眼终端名称
                    delivery.setYingyanEntityName(newEntityName);
                    
                    // 如果旧的终端名称存在且与新名称不同，需要重新创建终端
                    if (StringUtils.isNotEmpty(oldEntityName) && !oldEntityName.equals(newEntityName)) {
                        logger.info("车牌号变更，重新创建鹰眼终端: oldEntityName={}, newEntityName={}", oldEntityName, newEntityName);
                        boolean ensureResult = baiduYingyanService.ensureEntity(newEntityName);
                        if (!ensureResult) {
                            logger.warn("运单 {} 重新创建百度鹰眼终端失败，将在后台重试", delivery.getDeliveryNumber());
                        }
                    } else {
                        // 如果之前没有终端名称，直接创建
                        boolean ensureResult = baiduYingyanService.ensureEntity(newEntityName);
                        if (!ensureResult) {
                            logger.warn("运单 {} 创建百度鹰眼终端失败，将在后台重试", delivery.getDeliveryNumber());
                        }
                    }
                }
            }
        }
        if (dto.getBuyerId() != null) {
            delivery.setBuyerId(dto.getBuyerId());
        }
        if (dto.getBuyerPrice() != null) {
            delivery.setBuyerPrice(dto.getBuyerPrice());
        }
        if (dto.getSalePrice() != null) {
            delivery.setSalePrice(dto.getSalePrice());
        }
        if (dto.getFirmPrice() != null) {
            delivery.setFirmPrice(dto.getFirmPrice());
        }
        
        // 更新重量字段：将空字符串转换为null，避免数据库DECIMAL字段类型错误
        // 注意：前端可能传递空字符串""，需要处理这种情况
        if (dto.getEmptyWeight() != null) {
            delivery.setEmptyWeight(StringUtils.isNotEmpty(dto.getEmptyWeight()) ? dto.getEmptyWeight() : null);
        }
        if (dto.getEntruckWeight() != null) {
            delivery.setEntruckWeight(StringUtils.isNotEmpty(dto.getEntruckWeight()) ? dto.getEntruckWeight() : null);
        }
        if (dto.getLandingEntruckWeight() != null) {
            delivery.setLandingEntruckWeight(StringUtils.isNotEmpty(dto.getLandingEntruckWeight()) ? dto.getLandingEntruckWeight() : null);
        }
        
        // 更新照片字段：将空字符串转换为null，避免前端显示问题
        // 注意：前端总是传递字段（即使是空字符串），只有在传递了有效URL时才更新
        if (dto.getQuarantineTickeyUrl() != null) {
            delivery.setQuarantineTickeyUrl(StringUtils.isNotEmpty(dto.getQuarantineTickeyUrl()) ? dto.getQuarantineTickeyUrl() : null);
        }
        if (dto.getPoundListImg() != null) {
            delivery.setPoundListImg(StringUtils.isNotEmpty(dto.getPoundListImg()) ? dto.getPoundListImg() : null);
        }
        if (dto.getEmptyVehicleFrontPhoto() != null) {
            delivery.setEmptyVehicleFrontPhoto(StringUtils.isNotEmpty(dto.getEmptyVehicleFrontPhoto()) ? dto.getEmptyVehicleFrontPhoto() : null);
        }
        if (dto.getLoadedVehicleFrontPhoto() != null) {
            delivery.setLoadedVehicleFrontPhoto(StringUtils.isNotEmpty(dto.getLoadedVehicleFrontPhoto()) ? dto.getLoadedVehicleFrontPhoto() : null);
        }
        if (dto.getLoadedVehicleWeightPhoto() != null) {
            delivery.setLoadedVehicleWeightPhoto(StringUtils.isNotEmpty(dto.getLoadedVehicleWeightPhoto()) ? dto.getLoadedVehicleWeightPhoto() : null);
        }
        if (dto.getDriverIdCardPhoto() != null) {
            delivery.setDriverIdCardPhoto(StringUtils.isNotEmpty(dto.getDriverIdCardPhoto()) ? dto.getDriverIdCardPhoto() : null);
        }
        if (dto.getDestinationPoundListImg() != null) {
            delivery.setDestinationPoundListImg(StringUtils.isNotEmpty(dto.getDestinationPoundListImg()) ? dto.getDestinationPoundListImg() : null);
        }
        if (dto.getDestinationVehicleFrontPhoto() != null) {
            delivery.setDestinationVehicleFrontPhoto(StringUtils.isNotEmpty(dto.getDestinationVehicleFrontPhoto()) ? dto.getDestinationVehicleFrontPhoto() : null);
        }
        
        // 更新视频字段：将空字符串转换为null，避免前端显示问题
        if (dto.getEntruckWeightVideo() != null) {
            delivery.setEntruckWeightVideo(StringUtils.isNotEmpty(dto.getEntruckWeightVideo()) ? dto.getEntruckWeightVideo() : null);
        }
        if (dto.getEmptyWeightVideo() != null) {
            delivery.setEmptyWeightVideo(StringUtils.isNotEmpty(dto.getEmptyWeightVideo()) ? dto.getEmptyWeightVideo() : null);
        }
        if (dto.getCattleLoadingVideo() != null) {
            delivery.setEntruckVideo(StringUtils.isNotEmpty(dto.getCattleLoadingVideo()) ? dto.getCattleLoadingVideo() : null);
        }
        if (dto.getControlSlotVideo() != null) {
            delivery.setControlSlotVideo(StringUtils.isNotEmpty(dto.getControlSlotVideo()) ? dto.getControlSlotVideo() : null);
        }
        if (dto.getCattleLoadingCircleVideo() != null) {
            delivery.setCattleLoadingCircleVideo(StringUtils.isNotEmpty(dto.getCattleLoadingCircleVideo()) ? dto.getCattleLoadingCircleVideo() : null);
        }
        if (dto.getUnloadCattleVideo() != null) {
            delivery.setUnloadCattleVideo(StringUtils.isNotEmpty(dto.getUnloadCattleVideo()) ? dto.getUnloadCattleVideo() : null);
        }
        if (dto.getDestinationWeightVideo() != null) {
            delivery.setDestinationWeightVideo(StringUtils.isNotEmpty(dto.getDestinationWeightVideo()) ? dto.getDestinationWeightVideo() : null);
        }
        
        logger.info("更新文件字段: quarantineTickeyUrl={}, poundListImg={}, cattleLoadingVideo={}", 
            delivery.getQuarantineTickeyUrl(), delivery.getPoundListImg(), delivery.getEntruckVideo());
        
        // 根据车牌号从车辆表重新获取车辆照片（编辑时同步更新照片）
        // 这样即使车辆表中的照片有更新，也能同步到运送清单
        if (delivery.getLicensePlate() != null && StringUtils.isNotEmpty(delivery.getLicensePlate())) {
            try {
                Vehicle vehicle = vehicleMapper.selectByLicensePlate(delivery.getLicensePlate());
                if (vehicle != null) {
                    // 将空字符串转换为null，避免前端显示问题
                    String carFrontPhoto = vehicle.getCarFrontPhoto();
                    String carRearPhoto = vehicle.getCarRearPhoto();
                    delivery.setCarFrontPhoto(StringUtils.isNotEmpty(carFrontPhoto) ? carFrontPhoto : null);
                    delivery.setCarBehindPhoto(StringUtils.isNotEmpty(carRearPhoto) ? carRearPhoto : null);
                    logger.info("更新车辆照片: 车牌号={}, 车头照片={}, 车尾照片={}", 
                        delivery.getLicensePlate(), delivery.getCarFrontPhoto(), delivery.getCarBehindPhoto());
                } else {
                    // 如果车辆表中没有该车牌号的记录，清空照片
                    delivery.setCarFrontPhoto(null);
                    delivery.setCarBehindPhoto(null);
                }
            } catch (Exception e) {
                logger.error("从车辆表获取照片失败: " + e.getMessage(), e);
            }
        }
        
        // 保存更新
        boolean updated = this.updateById(delivery);
        logger.info("更新运送清单成功: deliveryId={}, ratedQuantity={}", dto.getDeliveryId(), delivery.getRatedQuantity());
        if (updated) {
            return AjaxResult.success("编辑成功");
        } else {
            return AjaxResult.error("编辑失败");
        }
    }

    /**
     * 转换前端时间格式为标准格式
     * 将 "Oct 01, 2025" 转换为 "2025-10-01"
     */
    private String convertDateFormat(String dateStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        
        try {
            // 处理 "Oct 01, 2025" 格式
            if (dateStr.contains(",")) {
                String[] parts = dateStr.split(",");
                if (parts.length == 2) {
                    String monthDay = parts[0].trim(); // "Oct 01"
                    String year = parts[1].trim(); // "2025"
                    
                    String[] monthDayParts = monthDay.split(" ");
                    if (monthDayParts.length == 2) {
                        String month = monthDayParts[0]; // "Oct"
                        String day = monthDayParts[1]; // "01"
                        
                        // 月份名称映射
                        String[] monthNames = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
                        int monthNum = 1;
                        for (int i = 0; i < monthNames.length; i++) {
                            if (monthNames[i].equals(month)) {
                                monthNum = i + 1;
                                break;
                            }
                        }
                        
                        return year + "-" + String.format("%02d", monthNum) + "-" + day;
                    }
                }
            }
            
            // 如果已经是标准格式，直接返回
            return dateStr;
        } catch (Exception e) {
            return dateStr; // 转换失败时返回原字符串
        }
    }

    @Override
    public PageResultResponse<Delivery> pageQueryListLog(DeliverListDto dto) {
        //获取当前登录人的信息
        String currentUserMobile = SecurityUtil.getUserMobile();
        
        // 调试：打印接收到的所有参数
        
        // 调试：查询数据库中的所有车牌号
        if(StringUtils.isNotEmpty(dto.getLicensePlate())) {
            List<Delivery> allDeliveries = this.list();
            allDeliveries.forEach(delivery -> {
            });
        }
        
        Page<Delivery> result = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<Delivery> deliveryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        
        // 运单号精确匹配
        if(StringUtils.isNotEmpty(dto.getDeliveryNumber())){
            deliveryLambdaQueryWrapper.eq(Delivery::getDeliveryNumber, dto.getDeliveryNumber());
        }
        // 车牌号精确匹配
        if(StringUtils.isNotEmpty(dto.getLicensePlate())){
            deliveryLambdaQueryWrapper.eq(Delivery::getLicensePlate, dto.getLicensePlate());
        }
        // 创建时间范围查询
        if(StringUtils.isNotEmpty(dto.getStartTime())){
            try {
                // 将前端发送的时间格式转换为标准格式
                String startTimeStr = convertDateFormat(dto.getStartTime()) + " 00:00:00";
                Date startDate = DateUtils.parseDate(startTimeStr);
                deliveryLambdaQueryWrapper.ge(Delivery::getCreateTime, startDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(StringUtils.isNotEmpty(dto.getEndTime())){
            try {
                // 将前端发送的时间格式转换为标准格式
                String endTimeStr = convertDateFormat(dto.getEndTime()) + " 23:59:59";
                Date endDate = DateUtils.parseDate(endTimeStr);
                deliveryLambdaQueryWrapper.le(Delivery::getCreateTime, endDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 核验状态精确匹配
        if(null != dto.getStatus()){
            deliveryLambdaQueryWrapper.eq(Delivery::getStatus, dto.getStatus());
        }
        // 添加订单标题搜索条件（精确匹配）
        if(StringUtils.isNotEmpty(dto.getDeliveryTitle())){
            deliveryLambdaQueryWrapper.eq(Delivery::getDeliveryTitle, dto.getDeliveryTitle());
        }
        // 添加目的地搜索条件（精确匹配）
        if(StringUtils.isNotEmpty(dto.getEndLocation())){
            deliveryLambdaQueryWrapper.eq(Delivery::getEndLocation, dto.getEndLocation());
        }
        deliveryLambdaQueryWrapper.orderByDesc(Delivery::getCreateTime);
        List<Delivery> resList = list(deliveryLambdaQueryWrapper);
        if(CollectionUtils.isNotEmpty(resList)){
            //获取当前的运单Id
            List<Integer> deliveryIds = resList.stream().map(delivery -> delivery.getId()).collect(Collectors.toList());
            //根据当前运单查询最新的一次数量预警记录
            List<WarningLog> warningCountLogs = warningLogMapper.selectList(new LambdaQueryWrapper<WarningLog>().in(WarningLog::getDeliveryId, deliveryIds).last(" and id in(select max(id) from warning_log where warning_type in ('0','2') group by delivery_id)"));
            List<WarningLog> warningRangeLogs = warningLogMapper.selectList(new LambdaQueryWrapper<WarningLog>().in(WarningLog::getDeliveryId, deliveryIds).last(" and id in(select max(id) from warning_log where warning_type in ('1','3') group by delivery_id)"));
            //获取当前登录人的Id
            List<Integer> createByIds = resList.stream()
                .map(delivery -> delivery.getCreatedBy())
                .filter(Objects::nonNull)  // 过滤掉null值
                .distinct()  // 去重
                .collect(Collectors.toList());
            
            final Map<Integer, String> userMap = new HashMap<>();
            if (!createByIds.isEmpty()) {
                List<SysUser> sysUsers = sysUserMapper.selectBatchIds(createByIds);
                userMap.putAll(sysUsers.stream().collect(Collectors.toMap(SysUser::getId, SysUser::getName)));
            }
            resList.forEach(deliveryLogVo -> {
                Integer deliveryId = deliveryLogVo.getId();
                List<String> warningTypes = new ArrayList<>();
                //数量预警解析
                warningCountLogs.forEach(warningLog -> {
                    Integer deliveryLogId = warningLog.getDeliveryId();
                    String warningType = warningLog.getWarningType();
                    if(deliveryId == deliveryLogId){
                        warningTypes.add(EnumUtil.getEnumConstant(WarningStatusAdminEnum.class , Integer.parseInt(warningType)).getDescription());
                        deliveryLogVo.setInventoryJbqCount(warningLog.getInventoryJbqCount());
                    }
                });
                //距离预警解析
                warningRangeLogs.forEach(warningLog -> {
                    Integer deliveryLogId = warningLog.getDeliveryId();
                    String warningType = warningLog.getWarningType();
                    if(deliveryId == deliveryLogId){
                        warningTypes.add(EnumUtil.getEnumConstant(WarningStatusAdminEnum.class , Integer.parseInt(warningType)).getDescription());
                    }
                });
                deliveryLogVo.setWarningTypeList(warningTypes);
                
                // 安全设置创建人名称
                Integer createdBy = deliveryLogVo.getCreatedBy();
                if (createdBy != null) {
                    String createByName = userMap.get(createdBy);
                    deliveryLogVo.setCreateByName(createByName != null ? createByName : "未知用户");
                } else {
                    deliveryLogVo.setCreateByName("未知用户");
                }
                
                // 添加司机信息关联查询逻辑
                if (deliveryLogVo.getDriverId() != null) {
                    try {
                        
                        Map<String, Object> driverInfo = memberDriverMapper.selectDriverById(deliveryLogVo.getDriverId());
                        
                        // 额外调试：检查是否有多个司机记录
                        if (driverInfo != null) {
                            String driverName = (String) driverInfo.get("username");
                            
                            // 不再根据车牌号查询司机，车牌号是独立的模块
                        }

                        if (driverInfo != null) {
                            String driverName = (String) driverInfo.get("username");
                            String carImg = (String) driverInfo.get("car_img");

                            // 设置司机信息
                            deliveryLogVo.setDriverName(driverName);
                            // 注意：车牌号不从司机表获取，车牌号是独立的模块

                            // 强制从司机信息中获取最新的车身照片，确保数据一致性
                            if (carImg != null && !carImg.isEmpty()) {
                                // 按逗号分割car_img字段，分别映射到车头和车尾照片
                                String[] carImgUrls = carImg.split(",");
                                
                                if (carImgUrls.length >= 2) {
                                    // 逗号前面的URL作为车尾照片
                                    String carBehindPhoto = carImgUrls[0].trim();
                                    // 逗号后面的URL作为车头照片
                                    String carFrontPhoto = carImgUrls[1].trim();
                                    
                                    deliveryLogVo.setCarBehindPhoto(carBehindPhoto);
                                    deliveryLogVo.setCarFrontPhoto(carFrontPhoto);
                                } else if (carImgUrls.length == 1) {
                                    // 只有一个URL时，同时设置为车头和车尾照片
                                    String singlePhoto = carImgUrls[0].trim();
                                    deliveryLogVo.setCarFrontPhoto(singlePhoto);
                                    deliveryLogVo.setCarBehindPhoto(singlePhoto);
                                } else {
                                    // 没有有效URL，设置为null
                                    deliveryLogVo.setCarFrontPhoto(null);
                                    deliveryLogVo.setCarBehindPhoto(null);
                                }
                            } else {
                                // 如果司机信息中没有照片，设置为null
                                deliveryLogVo.setCarFrontPhoto(null);
                                deliveryLogVo.setCarBehindPhoto(null);
                            }

                            // 如果车身照片仍然为空，尝试根据司机姓名和车牌号查询其他相关记录
                            if ((deliveryLogVo.getCarFrontPhoto() == null || deliveryLogVo.getCarFrontPhoto().isEmpty()) &&
                                (deliveryLogVo.getCarBehindPhoto() == null || deliveryLogVo.getCarBehindPhoto().isEmpty()) &&
                                driverName != null && deliveryLogVo.getLicensePlate() != null) {
                                // 已废弃：不再根据司机姓名和车牌号查询相关记录
                                // 车牌号和司机是两个独立的模块，车身照片应该从车辆管理模块获取
                                // try {
                                //     Map<String, Object> relatedDriver = memberDriverMapper.selectDriverByNameAndPlate(
                                //         driverName, deliveryLogVo.getLicensePlate());
                                //     if (relatedDriver != null) {
                                //         String relatedCarImg = (String) relatedDriver.get("car_img");
                                //         if (relatedCarImg != null && !relatedCarImg.isEmpty()) {
                                //             deliveryLogVo.setCarFrontPhoto(relatedCarImg);
                                //             deliveryLogVo.setCarBehindPhoto(relatedCarImg);
                                //         }
                                //     }
                                // } catch (Exception e) {
                                // }
                            }
                        } else {
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                }
                
                // 添加核验状态中文映射
                Integer status = deliveryLogVo.getStatus();
                if (status != null) {
                    String statusDesc = getStatusDescription(status);
                    deliveryLogVo.setStatusDesc(statusDesc);
                } else {
                }
                
                // 统计登记设备数量（耳标+项圈）
                Integer currentDeliveryId = deliveryLogVo.getId();
                if (currentDeliveryId != null) {
                    try {
                        // 统计耳标设备数量
                        LambdaQueryWrapper<DeliveryDevice> earTagWrapper = new LambdaQueryWrapper<>();
                        earTagWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                     .eq(DeliveryDevice::getDeviceType, 2);
                        long earTagCount = deliveryDeviceService.count(earTagWrapper);
                        
                        // 统计项圈设备数量
                        LambdaQueryWrapper<DeliveryDevice> collarWrapper = new LambdaQueryWrapper<>();
                        collarWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                    .eq(DeliveryDevice::getDeviceType, 3);
                        long collarCount = deliveryDeviceService.count(collarWrapper);
                        
                        // 设置总设备数量和耳标数量
                        int totalDeviceCount = (int) (earTagCount + collarCount);
                        deliveryLogVo.setRegisteredJbqCount(totalDeviceCount);
                        deliveryLogVo.setEarTagCount((int) earTagCount);
                        
                        // 设置已分配设备数量，与登记设备数量保持一致
                        deliveryLogVo.setBindJbqCount(totalDeviceCount);
                        
                        // 统计已佩戴设备数量（bandge_status = 1）
                        int wornDeviceCount = 0;
                        try {
                            // 统计已佩戴的耳标设备数量（通过delivery_device表关联）
                            LambdaQueryWrapper<DeliveryDevice> wornEarTagWrapper = new LambdaQueryWrapper<>();
                            wornEarTagWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                            .eq(DeliveryDevice::getDeviceType, 2)
                                            .eq(DeliveryDevice::getIsWare, 1); // 1表示已佩戴
                            long wornEarTagCount = deliveryDeviceService.count(wornEarTagWrapper);
                            
                            // 统计已佩戴的项圈设备数量（通过delivery_device表关联xq_client表）
                            LambdaQueryWrapper<DeliveryDevice> wornCollarWrapper = new LambdaQueryWrapper<>();
                            wornCollarWrapper.eq(DeliveryDevice::getDeliveryId, currentDeliveryId)
                                            .eq(DeliveryDevice::getDeviceType, 3);
                            List<DeliveryDevice> collarDevices = deliveryDeviceService.list(wornCollarWrapper);
                            
                            int wornCollarCount = 0;
                            for (DeliveryDevice device : collarDevices) {
                                // 查询xq_client表中的bandge_status
                                LambdaQueryWrapper<XqClient> xqWrapper = new LambdaQueryWrapper<>();
                                xqWrapper.eq(XqClient::getSn, device.getDeviceId());
                                XqClient xqClient = xqClientService.getOne(xqWrapper);
                                if (xqClient != null && xqClient.getBandgeStatus() != null && xqClient.getBandgeStatus() == 1) {
                                    wornCollarCount++;
                                }
                            }
                            
                            wornDeviceCount = (int) (wornEarTagCount + wornCollarCount);
                            deliveryLogVo.setWareCount(wornDeviceCount);
                        } catch (Exception e) {
                            deliveryLogVo.setWareCount(0);
                        }
                    } catch (Exception e) {
                        deliveryLogVo.setRegisteredJbqCount(0);
                        deliveryLogVo.setBindJbqCount(0);
                        deliveryLogVo.setWareCount(0);
                    }
                }
                
                // 查询四个角色的手机号（供应商、资金方、采购商）
                try {
                    // 1. 查询供应商手机号（supplierId是逗号分隔的字符串）
                    if (StringUtils.isNotEmpty(deliveryLogVo.getSupplierId())) {
                        String[] supplierIds = deliveryLogVo.getSupplierId().split(",");
                        List<String> supplierMobiles = new ArrayList<>();
                        for (String supplierId : supplierIds) {
                            if (StringUtils.isNotEmpty(supplierId.trim())) {
                                try {
                                    Integer sid = Integer.parseInt(supplierId.trim());
                                    Member supplier = memberMapper.selectById(sid);
                                    if (supplier != null && StringUtils.isNotEmpty(supplier.getMobile())) {
                                        supplierMobiles.add(supplier.getMobile());
                                    }
                                } catch (NumberFormatException e) {
                                }
                            }
                        }
                        if (!supplierMobiles.isEmpty()) {
                            deliveryLogVo.setSupplierMobile(String.join(",", supplierMobiles));
                        }
                    }
                    
                    // 2. 查询资金方手机号
                    if (deliveryLogVo.getFundId() != null) {
                        Member fund = memberMapper.selectById(deliveryLogVo.getFundId());
                        if (fund != null && StringUtils.isNotEmpty(fund.getMobile())) {
                            deliveryLogVo.setFundMobile(fund.getMobile());
                        }
                    }
                    
                    // 3. 查询采购商手机号
                    if (deliveryLogVo.getBuyerId() != null) {
                        Member buyer = memberMapper.selectById(deliveryLogVo.getBuyerId());
                        if (buyer != null && StringUtils.isNotEmpty(buyer.getMobile())) {
                            deliveryLogVo.setBuyerMobile(buyer.getMobile());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            
            // 数据权限过滤：非超级管理员只能看到与自己手机号相关的订单
            
            if (!SecurityUtil.isSuperAdmin() && StringUtils.isNotEmpty(currentUserMobile)) {
                
                resList = resList.stream().filter(delivery -> {
                    boolean hasPermission = false;
                    
                    
                    // 检查是否是司机
                    if (StringUtils.isNotEmpty(delivery.getDriverMobile()) && 
                        currentUserMobile.equals(delivery.getDriverMobile())) {
                        hasPermission = true;
                    }
                    
                    // 检查是否是供应商（可能有多个供应商）
                    if (!hasPermission && StringUtils.isNotEmpty(delivery.getSupplierMobile())) {
                        String[] supplierMobiles = delivery.getSupplierMobile().split(",");
                        for (String mobile : supplierMobiles) {
                            if (currentUserMobile.equals(mobile.trim())) {
                                hasPermission = true;
                                break;
                            }
                        }
                    }
                    
                    // 检查是否是资金方
                    if (!hasPermission && StringUtils.isNotEmpty(delivery.getFundMobile()) && 
                        currentUserMobile.equals(delivery.getFundMobile())) {
                        hasPermission = true;
                    }
                    
                    // 检查是否是采购商
                    if (!hasPermission && StringUtils.isNotEmpty(delivery.getBuyerMobile()) && 
                        currentUserMobile.equals(delivery.getBuyerMobile())) {
                        hasPermission = true;
                    }
                    
                    if (!hasPermission) {
                    }
                    
                    return hasPermission;
                }).collect(Collectors.toList());
                
            } else if (SecurityUtil.isSuperAdmin()) {
            } else {
            }
        }
        
        // 填充装车订单的关联订单信息
        for (Delivery delivery : resList) {
            if (delivery.getOrderId() != null) {
                com.aiotagro.cattletrade.business.entity.Order order = orderMapper.selectById(delivery.getOrderId());
                if (order != null) {
                    delivery.setOrderInfo(order);
                }
            }
        }
        
        // 更新分页信息
        long filteredTotal = resList.size();
        return new PageResultResponse(filteredTotal, resList);
    }

    @Override
    public PageResultResponse<DeliveryLogVo> pageQueryList(DeliverListDto dto) {
        //获取当前登录人的信息
        String currentUserMobile = SecurityUtil.getUserMobile();
        boolean isSuperAdmin = SecurityUtil.isSuperAdmin();
        
        logger.info("[预警列表查询] 开始查询，参数: pageNum={}, pageSize={}, deliveryNumber={}, licensePlate={}, warningType={}, startTime={}, endTime={}, isSuperAdmin={}", 
            dto.getPageNum(), dto.getPageSize(), dto.getDeliveryNumber(), dto.getLicensePlate(), 
            dto.getWarningType(), dto.getStartTime(), dto.getEndTime(), isSuperAdmin);
        
        Page<Delivery> result = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        if(StringUtils.isNotEmpty(dto.getStartTime())){
            String startTime = dto.getStartTime() + " 00:00:00";
            dto.setStartTime(startTime);
        }
        if(StringUtils.isNotEmpty(dto.getEndTime())){
            String endTime = dto.getEndTime() + " 23:59:59";
            dto.setEndTime(endTime);
        }
        
        List<Delivery> resList = this.baseMapper.getPageWarningLog(dto);
        long totalBeforeFilter = result.getTotal(); // 保存过滤前的总数
        
        logger.info("[预警列表查询] SQL查询结果: 总数={}, 当前页数据量={}", totalBeforeFilter, resList.size());
        
        // ✅ 调试：如果查询结果为空，检查可能的原因
        if (totalBeforeFilter == 0 && resList.isEmpty()) {
            logger.warn("[预警列表查询] ⚠️ 查询结果为空，可能原因：");
            logger.warn("[预警列表查询] 1. delivery 表和 warning_log 表的 delivery_id 不匹配");
            logger.warn("[预警列表查询] 2. warning_log 表中的 delivery_id 在 delivery 表中不存在");
            logger.warn("[预警列表查询] 3. SQL 查询逻辑有问题");
            
            // 检查 warning_log 表中是否有数据
            try {
                long warningLogCount = warningLogMapper.selectCount(null);
                logger.info("[预警列表查询] warning_log 表总记录数: {}", warningLogCount);
                
                // 检查有 delivery_id 的记录数
                QueryWrapper<WarningLog> countWrapper = new QueryWrapper<>();
                countWrapper.in("warning_type", 2,3,4,5,6,7,8,9);
                long validWarningCount = warningLogMapper.selectCount(countWrapper);
                logger.info("[预警列表查询] warning_log 表中预警类型在(2-9)范围内的记录数: {}", validWarningCount);
                
                // 检查 delivery 表中有多少运单
                long deliveryCount = this.count();
                logger.info("[预警列表查询] delivery 表总记录数: {}", deliveryCount);
                
                // ✅ 关键调试：检查 warning_log 表中的 delivery_id 是否在 delivery 表中存在
                QueryWrapper<WarningLog> deliveryIdWrapper = new QueryWrapper<>();
                deliveryIdWrapper.in("warning_type", 2,3,4,5,6,7,8,9);
                deliveryIdWrapper.select("DISTINCT delivery_id");
                List<WarningLog> warningLogsWithDeliveryId = warningLogMapper.selectList(deliveryIdWrapper);
                Set<Integer> warningLogDeliveryIds = warningLogsWithDeliveryId.stream()
                    .map(WarningLog::getDeliveryId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());
                logger.info("[预警列表查询] warning_log 表中不重复的 delivery_id 数量: {}", warningLogDeliveryIds.size());
                
                // 检查这些 delivery_id 在 delivery 表中是否存在
                if (!warningLogDeliveryIds.isEmpty()) {
                    List<Integer> deliveryIds = this.listByIds(new ArrayList<>(warningLogDeliveryIds))
                        .stream()
                        .map(Delivery::getId)
                        .collect(Collectors.toList());
                    logger.info("[预警列表查询] 在 delivery 表中存在的 delivery_id 数量: {}", deliveryIds.size());
                    logger.info("[预警列表查询] 在 delivery 表中存在的 delivery_id: {}", deliveryIds);
                    
                    // 找出不匹配的 delivery_id
                    Set<Integer> missingDeliveryIds = new HashSet<>(warningLogDeliveryIds);
                    missingDeliveryIds.removeAll(deliveryIds);
                    if (!missingDeliveryIds.isEmpty()) {
                        logger.warn("[预警列表查询] ⚠️ warning_log 表中有 {} 个 delivery_id 在 delivery 表中不存在", missingDeliveryIds.size());
                        logger.warn("[预警列表查询] 不匹配的 delivery_id 示例（前10个）: {}", 
                            missingDeliveryIds.stream().limit(10).collect(Collectors.toList()));
                    }
                }
            } catch (Exception e) {
                logger.error("[预警列表查询] 调试查询失败: {}", e.getMessage(), e);
            }
        }
        
        // 数据权限过滤：非超级管理员只能看到与自己手机号相关的订单
        if (!isSuperAdmin && StringUtils.isNotEmpty(currentUserMobile)) {
            int beforeFilterSize = resList.size();
            resList = resList.stream().filter(delivery -> {
                boolean hasPermission = false;
                
                // 检查是否是司机
                if (StringUtils.isNotEmpty(delivery.getDriverMobile()) && 
                    currentUserMobile.equals(delivery.getDriverMobile())) {
                    hasPermission = true;
                }
                
                // 检查是否是供应商（可能有多个供应商）
                if (!hasPermission && StringUtils.isNotEmpty(delivery.getSupplierMobile())) {
                    String[] supplierMobiles = delivery.getSupplierMobile().split(",");
                    for (String mobile : supplierMobiles) {
                        if (currentUserMobile.equals(mobile.trim())) {
                            hasPermission = true;
                            break;
                        }
                    }
                }
                
                // 检查是否是资金方
                if (!hasPermission && StringUtils.isNotEmpty(delivery.getFundMobile()) && 
                    currentUserMobile.equals(delivery.getFundMobile())) {
                    hasPermission = true;
                }
                
                // 检查是否是采购商
                if (!hasPermission && StringUtils.isNotEmpty(delivery.getBuyerMobile()) && 
                    currentUserMobile.equals(delivery.getBuyerMobile())) {
                    hasPermission = true;
                }
                
                return hasPermission;
            }).collect(Collectors.toList());
            
            logger.info("[预警列表查询] 权限过滤后: 过滤前={}, 过滤后={}", beforeFilterSize, resList.size());
        } else if (isSuperAdmin) {
            logger.info("[预警列表查询] 超级管理员，跳过权限过滤");
        } else {
            logger.warn("[预警列表查询] 未获取到用户手机号，跳过权限过滤");
        }
        
        // ✅ 修复：将 Delivery 实体转换为 DeliveryLogVo
        List<DeliveryLogVo> voList = new ArrayList<>();
        for (Delivery delivery : resList) {
            DeliveryLogVo vo = new DeliveryLogVo();
            vo.setId(delivery.getId());
            vo.setDeliveryId(delivery.getId());
            vo.setDeliveryNumber(delivery.getDeliveryNumber());
            vo.setLicensePlate(delivery.getLicensePlate());
            vo.setStatus(delivery.getStatus());
            vo.setCarFrontPhoto(delivery.getCarFrontPhoto());
            vo.setRegisteredJbqCount(delivery.getRegisteredJbqCount());
            vo.setInventoryJbqCount(delivery.getInventoryJbqCount());
            vo.setWarningType(delivery.getWarningType());
            vo.setWarningTime(delivery.getWarningTime());
            vo.setCreateByDesc(delivery.getCreateByName());
            
            // ✅ 新增：填充起始地、目的地、创建时间、预计送达时间、司机姓名、创建人
            vo.setStartLocation(delivery.getStartLocation());
            vo.setEndLocation(delivery.getEndLocation());
            vo.setCreateTime(delivery.getCreateTime());
            vo.setEstimatedDeliveryTime(delivery.getEstimatedDeliveryTime());
            vo.setDriverName(delivery.getDriverName());
            vo.setCreateByName(delivery.getCreateByName());
            
            // 设置预警类型描述
            String warningType = delivery.getWarningType();
            if(StringUtils.isNotEmpty(warningType)){
                try {
                    vo.setWarningTypeDesc(EnumUtil.getEnumConstant(WarningStatusAdminEnum.class , Integer.parseInt(warningType)).getDescription());
                } catch (Exception e) {
                    logger.warn("[预警列表查询] 预警类型解析失败: {}", warningType);
                    vo.setWarningTypeDesc("未知类型");
                }
            }
            
            voList.add(vo);
        }
        
        // ✅ 修复：使用分页查询的总数，而不是过滤后的数量
        // 如果是超级管理员，使用 SQL 查询的总数；否则使用过滤后的数量
        long finalTotal = isSuperAdmin ? totalBeforeFilter : voList.size();
        
        logger.info("[预警列表查询] 最终返回: 总数={}, 数据量={}", finalTotal, voList.size());
        
        return new PageResultResponse<DeliveryLogVo>(finalTotal, voList);
    }

    @Override
    public AjaxResult detail(Integer id) {
        Map<String,Object> resMap = new HashMap<>();
        //查询运单信息
        Delivery delivery = this.getById(id);
        
        // 查询供应商名称
        if (delivery.getSupplierId() != null && !delivery.getSupplierId().isEmpty()) {
            try {
                String[] supplierIds = delivery.getSupplierId().split(",");
                List<String> supplierNames = new ArrayList<>();
                List<String> supplierMobiles = new ArrayList<>();
                for (String supplierId : supplierIds) {
                    if (StringUtils.isNotEmpty(supplierId.trim())) {
                        try {
                            Integer sid = Integer.parseInt(supplierId.trim());
                            // 查询member和member_user表关联数据
                            Map<String, Object> supplierInfo = memberMapper.selectMemberUserById(sid);
                            if (supplierInfo != null) {
                                String username = (String) supplierInfo.get("username");
                                String mobile = (String) supplierInfo.get("mobile");
                                if (StringUtils.isNotEmpty(username)) {
                                    supplierNames.add(username);
                                }
                                if (StringUtils.isNotEmpty(mobile)) {
                                    supplierMobiles.add(mobile);
                                }
                            } else {
                            }
                        } catch (NumberFormatException e) {
                        }
                    }
                }
                if (!supplierNames.isEmpty() && !supplierMobiles.isEmpty()) {
                    // 用户名和手机号都存在，用/号连接
                    List<String> supplierDisplayNames = new ArrayList<>();
                    for (int i = 0; i < Math.max(supplierNames.size(), supplierMobiles.size()); i++) {
                        String name = i < supplierNames.size() ? supplierNames.get(i) : "";
                        String mobile = i < supplierMobiles.size() ? supplierMobiles.get(i) : "";
                        if (!name.isEmpty() && !mobile.isEmpty()) {
                            supplierDisplayNames.add(name + "/" + mobile);
                        } else if (!name.isEmpty()) {
                            supplierDisplayNames.add(name);
                        } else if (!mobile.isEmpty()) {
                            supplierDisplayNames.add(mobile);
                        }
                    }
                    delivery.setSupplierName(String.join(",", supplierDisplayNames));
                } else if (!supplierNames.isEmpty()) {
                    delivery.setSupplierName(String.join(",", supplierNames));
                } else if (!supplierMobiles.isEmpty()) {
                    // 如果用户名为空，使用手机号作为备选
                    delivery.setSupplierName(String.join(",", supplierMobiles));
                }
                if (!supplierMobiles.isEmpty()) {
                    delivery.setSupplierMobile(String.join(",", supplierMobiles));
                }
            } catch (Exception e) {
                System.err.println("详情查询-Error fetching supplier info: " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        // 查询资金方名称
        if (delivery.getFundId() != null) {
            try {
                Map<String, Object> fundInfo = memberMapper.selectMemberUserById(delivery.getFundId());
                if (fundInfo != null) {
                    String username = (String) fundInfo.get("username");
                    String mobile = (String) fundInfo.get("mobile");
                    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(mobile)) {
                        // 用户名和手机号都存在，用/号连接
                        delivery.setFundName(username + "/" + mobile);
                    } else if (StringUtils.isNotEmpty(username)) {
                        delivery.setFundName(username);
                    } else if (StringUtils.isNotEmpty(mobile)) {
                        // 如果用户名为空，使用手机号作为备选
                        delivery.setFundName(mobile);
                    }
                    if (StringUtils.isNotEmpty(mobile)) {
                        delivery.setFundMobile(mobile);
                    }
                } else {
                }
            } catch (Exception e) {
                System.err.println("详情查询-Error fetching fund info: " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        // 查询采购商名称
        if (delivery.getBuyerId() != null) {
            try {
                Map<String, Object> buyerInfo = memberMapper.selectMemberUserById(delivery.getBuyerId());
                if (buyerInfo != null) {
                    String username = (String) buyerInfo.get("username");
                    String mobile = (String) buyerInfo.get("mobile");
                    if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(mobile)) {
                        // 用户名和手机号都存在，用/号连接
                        delivery.setBuyerName(username + "/" + mobile);
                    } else if (StringUtils.isNotEmpty(username)) {
                        delivery.setBuyerName(username);
                    } else if (StringUtils.isNotEmpty(mobile)) {
                        // 如果用户名为空，使用手机号作为备选
                        delivery.setBuyerName(mobile);
                    }
                    if (StringUtils.isNotEmpty(mobile)) {
                        delivery.setBuyerMobile(mobile);
                    }
                } else {
                }
            } catch (Exception e) {
                System.err.println("详情查询-Error fetching buyer info: " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        // 查询司机信息
        if (delivery.getDriverId() != null) {
            try {
                // 根据司机ID直接查询司机信息
                Map<String, Object> driverInfo = memberDriverMapper.selectDriverById(delivery.getDriverId());
                
                if (driverInfo != null) {
                    String driverName = (String) driverInfo.get("username");
                    String carImg = (String) driverInfo.get("car_img");
                    String driverMobile = (String) driverInfo.get("mobile");
                    
                    // 设置司机信息 - 司机姓名和手机号用/号连接
                    if (StringUtils.isNotEmpty(driverName) && StringUtils.isNotEmpty(driverMobile)) {
                        delivery.setDriverName(driverName + "/" + driverMobile);
                    } else if (StringUtils.isNotEmpty(driverName)) {
                        delivery.setDriverName(driverName);
                    } else if (StringUtils.isNotEmpty(driverMobile)) {
                        delivery.setDriverName(driverMobile);
                    }
                    // 注意：车牌号不从司机表获取，车牌号是独立的模块
                    delivery.setDriverMobile(driverMobile);
                    
                    // 优先从车辆表获取车身照片（根据车牌号）
                    // 如果车辆表中没有，再从司机信息中获取作为后备
                    boolean vehiclePhotoSet = false;
                    if (delivery.getLicensePlate() != null && StringUtils.isNotEmpty(delivery.getLicensePlate())) {
                        try {
                            Vehicle vehicle = vehicleMapper.selectByLicensePlate(delivery.getLicensePlate());
                            if (vehicle != null) {
                                String carFrontPhoto = vehicle.getCarFrontPhoto();
                                String carRearPhoto = vehicle.getCarRearPhoto();
                                if (StringUtils.isNotEmpty(carFrontPhoto) || StringUtils.isNotEmpty(carRearPhoto)) {
                                    delivery.setCarFrontPhoto(StringUtils.isNotEmpty(carFrontPhoto) ? carFrontPhoto : null);
                                    delivery.setCarBehindPhoto(StringUtils.isNotEmpty(carRearPhoto) ? carRearPhoto : null);
                                    vehiclePhotoSet = true;
                                    logger.debug("从车辆表获取照片: 车牌号={}, 车头照片={}, 车尾照片={}", 
                                        delivery.getLicensePlate(), delivery.getCarFrontPhoto(), delivery.getCarBehindPhoto());
                                }
                            }
                        } catch (Exception e) {
                            logger.error("从车辆表获取照片失败: " + e.getMessage(), e);
                        }
                    }
                    
                    // 如果车辆表中没有照片，从司机信息中获取作为后备
                    if (!vehiclePhotoSet && carImg != null && !carImg.isEmpty()) {
                        // 按逗号分割car_img字段，分别映射到车头和车尾照片
                        String[] carImgUrls = carImg.split(",");
                        
                        if (carImgUrls.length >= 2) {
                            // 逗号前面的URL作为车尾照片
                            String carBehindPhoto = carImgUrls[0].trim();
                            // 逗号后面的URL作为车头照片
                            String carFrontPhoto = carImgUrls[1].trim();
                            
                            delivery.setCarBehindPhoto(carBehindPhoto);
                            delivery.setCarFrontPhoto(carFrontPhoto);
                        } else if (carImgUrls.length == 1) {
                            // 只有一个URL时，同时设置为车头和车尾照片
                            String singlePhoto = carImgUrls[0].trim();
                            delivery.setCarFrontPhoto(singlePhoto);
                            delivery.setCarBehindPhoto(singlePhoto);
                        } else {
                            // 没有有效URL，设置为null
                            delivery.setCarFrontPhoto(null);
                            delivery.setCarBehindPhoto(null);
                        }
                    } else if (!vehiclePhotoSet) {
                        // 如果车辆表和司机信息中都没有照片，设置为null
                        delivery.setCarFrontPhoto(null);
                        delivery.setCarBehindPhoto(null);
                    }
                    
                    // 已废弃：不再根据司机姓名和车牌号查询相关记录
                    // 车牌号和司机是两个独立的模块，车身照片应该从车辆管理模块获取
                    // if ((delivery.getCarFrontPhoto() == null || delivery.getCarFrontPhoto().isEmpty()) &&
                    //     (delivery.getCarBehindPhoto() == null || delivery.getCarBehindPhoto().isEmpty()) &&
                    //     driverName != null && delivery.getLicensePlate() != null) {
                    //     try {
                    //         Map<String, Object> relatedDriver = memberDriverMapper.selectDriverByNameAndPlate(
                    //             driverName, delivery.getLicensePlate());
                    //         if (relatedDriver != null) {
                    //             String relatedCarImg = (String) relatedDriver.get("car_img");
                    //             String relatedDriverMobile = (String) relatedDriver.get("mobile");
                    //             
                    //             if (relatedCarImg != null && !relatedCarImg.isEmpty()) {
                    //                 delivery.setCarFrontPhoto(relatedCarImg);
                    //                 delivery.setCarBehindPhoto(relatedCarImg); // 使用同一张照片作为前后照片
                    //             }
                    //             
                    //             //             // 如果当前司机手机号为空，使用相关记录的手机号
                    //             //             if ((delivery.getDriverMobile() == null || delivery.getDriverMobile().isEmpty()) && 
                    //             //                 relatedDriverMobile != null && !relatedDriverMobile.isEmpty()) {
                    //             //                 delivery.setDriverMobile(relatedDriverMobile);
                    //             //             }
                    //             //         }
                    //             //     } catch (Exception e) {
                    //             //     }
                    //             // }
                } else {
                }
            } catch (Exception e) {
                // 忽略查询错误，继续处理
                e.printStackTrace();
            }
        } else {
        }
        
        //根据运单信息，查询最新的预警信息
        List<WarningLog> warningLogs = warningLogMapper.selectList(
                new LambdaQueryWrapper<WarningLog>().eq(WarningLog::getDeliveryId, id).notIn(WarningLog::getWarningType, "0","1").orderByDesc(WarningLog::getWarningTime));
        if(CollectionUtils.isNotEmpty(warningLogs)){
            warningLogs.forEach(warningLog -> {
                String warningType = warningLog.getWarningType();
                if(StringUtils.isNotEmpty(warningType)){
                    warningLog.setWarningTypeDesc(EnumUtil.getEnumConstant(WarningStatusAdminEnum.class , Integer.parseInt(warningType)).getDescription());
                }
            });
        }
        //查询核验人名称
        SysUser sysUser = sysUserMapper.selectById(delivery.getCheckBy());
        if(null != sysUser){
            String checkByName = sysUser.getName();
            delivery.setCheckByName(checkByName);
        }
        resMap.put("delivery", delivery);
        resMap.put("warningLog", warningLogs);
        
        //查询主机信息
        DeliveryDevice deliveryDevices = deliveryDeviceMapper.selectOne(new LambdaQueryWrapper<DeliveryDevice>().eq(DeliveryDevice::getDeliveryId, id).eq(DeliveryDevice::getDeviceType, 1).last("limit 1"));
        if(null != deliveryDevices){
            resMap.put("serverIds", deliveryDevices.getDeviceId());
        }else{
            resMap.put("serverIds", "");
        }
        
        // 查询耳标设备信息（类型2）
        List<DeliveryDevice> eartagDevices = deliveryDeviceMapper.selectList(
            new LambdaQueryWrapper<DeliveryDevice>()
                .eq(DeliveryDevice::getDeliveryId, id)
                .eq(DeliveryDevice::getDeviceType, 2)
        );
        List<String> eartagIds = new ArrayList<>();
        if (eartagDevices != null && !eartagDevices.isEmpty()) {
            for (DeliveryDevice device : eartagDevices) {
                if (device.getDeviceId() != null && !device.getDeviceId().isEmpty()) {
                    eartagIds.add(device.getDeviceId());
                }
            }
        }
        resMap.put("eartagIds", eartagIds);
        
        // 查询项圈设备信息（类型3）
        List<DeliveryDevice> collarDevices = deliveryDeviceMapper.selectList(
            new LambdaQueryWrapper<DeliveryDevice>()
                .eq(DeliveryDevice::getDeliveryId, id)
                .eq(DeliveryDevice::getDeviceType, 3)
        );
        List<String> collarIds = new ArrayList<>();
        if (collarDevices != null && !collarDevices.isEmpty()) {
            for (DeliveryDevice device : collarDevices) {
                if (device.getDeviceId() != null && !device.getDeviceId().isEmpty()) {
                    collarIds.add(device.getDeviceId());
                }
            }
        }
        resMap.put("collarIds", collarIds);
        
        // 补充 supplierId 和 buyerId 到返回数据（用于编辑时的下拉框回显）
        if (delivery.getSupplierId() != null && !delivery.getSupplierId().isEmpty()) {
            // 如果有多个供应商，只取第一个作为编辑时的默认值
            String firstSupplierId = delivery.getSupplierId().split(",")[0].trim();
            try {
                resMap.put("supplierId", Integer.parseInt(firstSupplierId));
            } catch (NumberFormatException e) {
                resMap.put("supplierId", null);
            }
        } else {
            resMap.put("supplierId", null);
        }
        
        resMap.put("buyerId", delivery.getBuyerId());
        
        logger.info("加载运送清单详情: deliveryId={}, buyerId={}, eartagIds={}, collarIds={}", 
            id, delivery.getBuyerId(), eartagIds.size(), collarIds.size());
        
        return AjaxResult.success(resMap);
    }

    @Override
    public AjaxResult queryYingyanTrack(Integer deliveryId) {
        if (deliveryId == null) {
            return AjaxResult.error("运单ID不能为空");
        }
        Delivery delivery = this.getById(deliveryId);
        if (delivery == null) {
            return AjaxResult.error("运单不存在");
        }
        if (delivery.getStatus() == null || delivery.getStatus() == 1) {
            return AjaxResult.error("该运单尚未开始运输");
        }
        String entityName = StringUtils.defaultIfBlank(delivery.getYingyanEntityName(), delivery.getLicensePlate());
        if (StringUtils.isBlank(entityName)) {
            return AjaxResult.error("缺少车牌信息，无法查询轨迹");
        }
        // 去除空格，确保格式一致
        entityName = entityName.trim();

        baiduYingyanService.ensureEntity(entityName);

        // ✅ 按照用户要求：使用预计开始时间（estimatedDeliveryTime）作为轨迹查询的起始时间
        // 如果没有 estimatedDeliveryTime，则依次尝试 estimatedDepartureTime、createTime
        long startTime = dateToSeconds(delivery.getEstimatedDeliveryTime());
        if (startTime <= 0) {
            startTime = dateToSeconds(delivery.getEstimatedDepartureTime());
        }
        if (startTime <= 0) {
            startTime = dateToSeconds(delivery.getCreateTime());
        }
        if (startTime <= 0) {
            startTime = System.currentTimeMillis() / 1000 - 12 * 3600;
        }
        
        logger.info("运单 {} 轨迹查询开始时间确定 - estimatedDeliveryTime: {}, estimatedDepartureTime: {}, createTime: {}, 最终使用: {}", 
            delivery.getDeliveryNumber(),
            delivery.getEstimatedDeliveryTime(),
            delivery.getEstimatedDepartureTime(),
            delivery.getCreateTime(),
            new Date(startTime * 1000));

        long endTime = determineTrackEndTime(delivery);
        if (endTime <= startTime) {
            endTime = startTime + 3600;
        }

        // ✅ 使用分段查询方法，支持超过24小时的轨迹查询
        long durationHours = Math.max(1, (endTime - startTime) / 3600);
        logger.info("查询运单 {} 的百度鹰眼轨迹 - entity={}, startTime={}, endTime={}, 时间跨度={}小时", 
            delivery.getDeliveryNumber(), entityName, startTime, endTime, durationHours);
        
        // ✅ 确保终端存在后再查询（重要：如果终端不存在，查询会失败）
        boolean entityExists = baiduYingyanService.ensureEntity(entityName);
        if (!entityExists) {
            logger.error("运单 {} 终端不存在且创建失败，无法查询轨迹 - entity={}, deliveryNumber={}, deliveryId={}", 
                delivery.getDeliveryNumber(), entityName, delivery.getDeliveryNumber(), delivery.getId());
            // 返回空结果，而不是继续查询（因为查询肯定会失败）
            Map<String, Object> data = new HashMap<>();
            data.put("trackPoints", Collections.emptyList());
            data.put("stayPoints", Collections.emptyList());
            data.put("entityName", entityName);
            data.put("startTime", startTime * 1000);
            data.put("endTime", endTime * 1000);
            data.put("status", delivery.getStatus());
            data.put("error", "终端不存在且创建失败，请检查百度鹰眼服务配置或终端名称是否正确");
            return AjaxResult.success(data);
        }
        
        logger.info("运单 {} 终端已确保存在，开始查询轨迹 - entity={}", 
            delivery.getDeliveryNumber(), entityName);
        
        List<long[]> segmentRanges = buildTrackSegments(startTime, endTime);
        logger.info("运单 {} 将分 {} 段调用百度鹰眼接口（每段≤24小时）", delivery.getDeliveryNumber(), segmentRanges.size());

        List<YingyanTrackPoint> mergedTrackPoints = new ArrayList<>();
        List<YingyanStayPoint> mergedStayPoints = new ArrayList<>();
        List<Map<String, Object>> segmentStats = new ArrayList<>();

        for (int i = 0; i < segmentRanges.size(); i++) {
            long[] range = segmentRanges.get(i);
            long segStart = range[0];
            long segEnd = range[1];
            logger.info("运单 {} 调用轨迹接口-第{}段: {} -> {}", 
                delivery.getDeliveryNumber(), i + 1, new Date(segStart * 1000), new Date(segEnd * 1000));

            List<YingyanTrackPoint> segmentTracks = baiduYingyanService.queryTrack(entityName, segStart, segEnd);
            logger.info("运单 {} 第{}段轨迹点数量：{}", delivery.getDeliveryNumber(), i + 1, segmentTracks.size());
            mergedTrackPoints.addAll(segmentTracks);

            List<YingyanStayPoint> segmentStayPoints = baiduYingyanService.queryStayPoints(entityName, segStart, segEnd, 900);
            logger.info("运单 {} 第{}段停留点数量：{}", delivery.getDeliveryNumber(), i + 1, segmentStayPoints.size());
            mergedStayPoints.addAll(segmentStayPoints);

            Map<String, Object> segmentInfo = new HashMap<>();
            segmentInfo.put("index", i + 1);
            segmentInfo.put("startTime", segStart * 1000);
            segmentInfo.put("endTime", segEnd * 1000);
            segmentInfo.put("trackCount", segmentTracks.size());
            segmentInfo.put("stayCount", segmentStayPoints.size());
            segmentStats.add(segmentInfo);
        }

        List<YingyanTrackPoint> trackPoints = dedupTrackPoints(mergedTrackPoints);
        List<YingyanStayPoint> stayPoints = dedupStayPoints(mergedStayPoints);

        logger.info("运单 {} 轨迹查询完成 - 分段:{}段, 合并后轨迹点数:{}, 停留点数:{}", 
            delivery.getDeliveryNumber(), segmentRanges.size(), trackPoints.size(), stayPoints.size());

        YingyanTrackPoint latestPoint = null;
        if (delivery.getStatus() != null && delivery.getStatus() == 2) {
            latestPoint = baiduYingyanService.queryLatestPoint(entityName);
            if (latestPoint != null) {
                logger.info("运单 {} 最新轨迹点：lat={}, lon={}, locTime={}", 
                    delivery.getDeliveryNumber(), latestPoint.getLatitude(), latestPoint.getLongitude(), latestPoint.getLocTime());
            } else {
                logger.warn("运单 {} 查询最新轨迹点返回为空", delivery.getDeliveryNumber());
            }
        } else {
            logger.info("运单 {} 状态为 {}，跳过实时定位查询", delivery.getDeliveryNumber(), delivery.getStatus());
        }

        Map<String, Object> data = new HashMap<>();
        data.put("trackPoints", trackPoints);
        data.put("stayPoints", stayPoints);
        data.put("entityName", entityName);
        data.put("startTime", startTime * 1000);
        data.put("endTime", endTime * 1000);
        data.put("status", delivery.getStatus());
        data.put("segmentStats", segmentStats);
        if (latestPoint != null) {
            data.put("latestPoint", latestPoint);
        }

        return AjaxResult.success(data);
    }

    private long determineTrackEndTime(Delivery delivery) {
        if (delivery.getStatus() != null && delivery.getStatus() == 3) {
            long arrivalTime = dateToSeconds(delivery.getArrivalTime());
            if (arrivalTime > 0) {
                return arrivalTime;
            }
        }
        return System.currentTimeMillis() / 1000;
    }

    private long dateToSeconds(Date date) {
        if (date == null) {
            return 0;
        }
        return date.getTime() / 1000;
    }

    /**
     * 获取核验状态的中文描述
     * @param status 状态码
     * @return 中文描述
     */
    private String getStatusDescription(Integer status) {
        if (status == null) {
            return "未知状态";
        }
        
        switch (status) {
            case 1:
                return "待装车";
            case 2:
                return "已装车/预付款已支付";
            case 3:
                return "已装车/尾款待支付";
            case 4:
                return "已核验/待买家付款";
            case 5:
                return "尾款已付款";
            case 6:
                return "发票待开/进项票";
            case 7:
                return "发票待开/销项";
            default:
                return "未知状态";
        }
    }

    private static final long MAX_SEGMENT_SECONDS = 24 * 60 * 60;

    private List<long[]> buildTrackSegments(long startTime, long endTime) {
        List<long[]> segments = new ArrayList<>();
        long cursor = startTime;
        while (cursor < endTime) {
            long next = Math.min(cursor + MAX_SEGMENT_SECONDS, endTime);
            segments.add(new long[]{cursor, next});
            cursor = next;
        }
        return segments;
    }

    private List<YingyanTrackPoint> dedupTrackPoints(List<YingyanTrackPoint> points) {
        if (CollectionUtils.isEmpty(points)) {
            return Collections.emptyList();
        }
        points.sort(Comparator.comparingLong(YingyanTrackPoint::getLocTime)
            .thenComparingDouble(YingyanTrackPoint::getLatitude)
            .thenComparingDouble(YingyanTrackPoint::getLongitude));
        Set<String> seen = new HashSet<>();
        List<YingyanTrackPoint> unique = new ArrayList<>();
        for (YingyanTrackPoint point : points) {
            String key = point.getLocTime() + "_" + point.getLatitude() + "_" + point.getLongitude();
            if (seen.add(key)) {
                unique.add(point);
            }
        }
        return unique;
    }

    private List<YingyanStayPoint> dedupStayPoints(List<YingyanStayPoint> points) {
        if (CollectionUtils.isEmpty(points)) {
            return Collections.emptyList();
        }
        points.sort(Comparator.comparingLong(YingyanStayPoint::getStartTime)
            .thenComparingLong(YingyanStayPoint::getEndTime));
        Set<String> seen = new HashSet<>();
        List<YingyanStayPoint> unique = new ArrayList<>();
        for (YingyanStayPoint point : points) {
            String key = point.getStartTime() + "_" + point.getEndTime() + "_" + point.getLatitude() + "_" + point.getLongitude();
            if (seen.add(key)) {
                unique.add(point);
            }
        }
        return unique;
    }

}

