package com.aiotagro.cattletrade.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.aiotagro.cattletrade.business.entity.DeliveryDevice;
import com.aiotagro.cattletrade.business.entity.IotDeviceData;
import com.aiotagro.cattletrade.business.entity.SysTenant;
import com.aiotagro.cattletrade.business.entity.JbqClientLog;
import com.aiotagro.cattletrade.business.entity.JbqServerLog;
import com.aiotagro.cattletrade.business.entity.XqClientLog;
import com.aiotagro.cattletrade.business.mapper.IotDeviceDataMapper;
import com.aiotagro.cattletrade.business.mapper.SysTenantMapper;
import com.aiotagro.cattletrade.business.mapper.JbqClientLogMapper;
import com.aiotagro.cattletrade.business.mapper.JbqServerLogMapper;
import com.aiotagro.cattletrade.business.mapper.XqClientLogMapper;
import com.aiotagro.cattletrade.business.service.IDeliveryDeviceService;
import com.aiotagro.cattletrade.business.service.IotDeviceLogSyncService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.aiotagro.common.core.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * <p>
 * 运单设备表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-12-26
 */
@RestController
@RequestMapping("/deliveryDevice")
public class DeliveryDeviceController {

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

    @Autowired
    private IDeliveryDeviceService deliveryDeviceService;

    @Autowired
    private IotDeviceDataMapper iotDeviceDataMapper;
    
    @Autowired
    private SysTenantMapper sysTenantMapper;
    
    @Autowired
    private JbqClientLogMapper jbqClientLogMapper;
    
    @Autowired
    private JbqServerLogMapper jbqServerLogMapper;
    
    @Autowired
    private XqClientLogMapper xqClientLogMapper;
    
    @Autowired
    private IotDeviceLogSyncService iotDeviceLogSyncService;

    /**
     * 根据运送清单ID查询耳标列表（从iot_device_data表查询）
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/pageJbqList")
    public AjaxResult pageJbqList(@RequestBody Map<String, Object> params) {
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            // 查询iot_device_data表中delivery_id等于deliveryId且设备类型为2（耳标）的设备
            QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            queryWrapper.eq("delivery_id", deliveryId);
            queryWrapper.eq("device_type", 2); // 2表示耳标类型
            List<IotDeviceData> devices = iotDeviceDataMapper.selectList(queryWrapper);
            
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (IotDeviceData device : devices) {
                Map<String, Object> deviceMap = new HashMap<>();
                deviceMap.put("deviceId", device.getDeviceId());
                deviceMap.put("deviceType", "2");
                deviceMap.put("deviceTypeName", "智能耳标");
                deviceMap.put("deviceVoltage", device.getVoltage());
                deviceMap.put("deviceTemp", device.getTemperature());
                deviceMap.put("latitude", device.getLatitude());
                deviceMap.put("longitude", device.getLongitude());
                deviceMap.put("walkSteps", device.getSteps());
                deviceMap.put("yWalkSteps", device.getSameDaySteps());
                resultList.add(deviceMap);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("rows", resultList);
            result.put("total", resultList.size());
            
            return AjaxResult.success("操作成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询耳标设备列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据运送清单ID查询所有设备列表（从iot_device_data表查询）
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/pageDeviceList")
    public AjaxResult pageDeviceList(@RequestBody Map<String, Object> params) {
        Integer deliveryId = (Integer) params.get("deliveryId");
        Integer deviceType = (Integer) params.get("deviceType");
        
        // deliveryId 和 deviceType 都是可选的
        // 如果只传了 deviceType，则获取所有该类型的设备
        // 如果传了 deliveryId，则获取该订单的设备
        
        try {
            QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
            
            // 只查询正常状态的设备（is_delet=0）
            queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            
            // 如果提供了deliveryId，则查询特定订单的设备
            if (deliveryId != null) {
                queryWrapper.eq("delivery_id", deliveryId);
            }
            
            // 如果提供了deviceType，则过滤设备类型
            if (deviceType != null) {
                queryWrapper.eq("device_type", deviceType);
                
                // 如果是查询智能主机(deviceType=1)且没有提供deliveryId，则只显示未绑定的主机
                if (deviceType == 1 && deliveryId == null) {
                    queryWrapper.isNull("delivery_id");
                }
            }
            
            List<IotDeviceData> devices = iotDeviceDataMapper.selectList(queryWrapper);
            
            List<Map<String, Object>> allDevices = new ArrayList<>();
            
            // 查询delivery_device表中的图片数据（仅当有deliveryId时）
            Map<String, DeliveryDevice> deviceImageMap = new HashMap<>();
            if (deliveryId != null) {
                LambdaQueryWrapper<DeliveryDevice> deliveryDeviceWrapper = new LambdaQueryWrapper<>();
                deliveryDeviceWrapper.eq(DeliveryDevice::getDeliveryId, deliveryId);
                List<DeliveryDevice> deliveryDevices = deliveryDeviceService.list(deliveryDeviceWrapper);
                
                // 创建设备ID到图片数据的映射
                for (DeliveryDevice dd : deliveryDevices) {
                    deviceImageMap.put(dd.getDeviceId(), dd);
                }
            }
            
            // 处理每个设备
            for (IotDeviceData device : devices) {
                Map<String, Object> deviceMap = new HashMap<>();
                deviceMap.put("deviceId", device.getDeviceId());
                deviceMap.put("deviceType", device.getDeviceType().toString());
                
                // 根据设备类型设置设备类型名称
                switch (device.getDeviceType()) {
                    case 1:
                        deviceMap.put("deviceTypeName", "智能主机");
                        break;
                    case 2:
                        deviceMap.put("deviceTypeName", "智能耳标");
                        break;
                    case 4:
                        deviceMap.put("deviceTypeName", "智能项圈");
                        break;
                    default:
                        deviceMap.put("deviceTypeName", "未知设备");
                        break;
                }
                
                // 设备基本信息
                deviceMap.put("deviceVoltage", device.getVoltage());
                deviceMap.put("deviceTemp", device.getTemperature());
                deviceMap.put("battery", device.getBatteryPercentage());
                deviceMap.put("latitude", device.getLatitude());
                deviceMap.put("longitude", device.getLongitude());
                deviceMap.put("walkSteps", device.getSteps());
                deviceMap.put("yWalkSteps", device.getSameDaySteps());
                deviceMap.put("steps", device.getSteps());
                deviceMap.put("ySteps", device.getSameDaySteps());
                deviceMap.put("tenantId", device.getTenantId());
                
                // 添加时间字段
                deviceMap.put("updateTime", device.getUpdateTime() != null ? device.getUpdateTime().toString() : "");
                deviceMap.put("createTime", device.getCreateTime() != null ? device.getCreateTime().toString() : "");
                
                // 添加重量字段
                deviceMap.put("weight", device.getWeight());
                deviceMap.put("bindWeight", device.getWeight()); // 为了兼容前端，同时提供bindWeight字段
                
                // 查询租户名称
                String tenantName = "--";
                if (device.getTenantId() != null) {
                    SysTenant tenant = sysTenantMapper.selectById(device.getTenantId());
                    if (tenant != null) {
                        tenantName = tenant.getName();
                    }
                }
                deviceMap.put("tenantName", tenantName);
                
                // 佩戴状态（项圈设备有佩戴状态，其他设备默认未佩戴）
                if (device.getDeviceType() == 4) {
                    // 项圈设备，可以根据实际业务逻辑设置佩戴状态
                    deviceMap.put("isWare", "0"); // 默认未佩戴，可以根据实际需求调整
                } else {
                    deviceMap.put("isWare", "0"); // 其他设备默认未佩戴
                }
                
                // 获取图片数据
                DeliveryDevice deviceImages = deviceImageMap.get(device.getDeviceId());
                deviceMap.put("frontImg", deviceImages != null ? deviceImages.getFrontImg() : "");
                deviceMap.put("sideImg", deviceImages != null ? deviceImages.getSideImg() : "");
                deviceMap.put("hipImg", deviceImages != null ? deviceImages.getHipImg() : "");
                
                allDevices.add(deviceMap);
            }
            
            return AjaxResult.success("操作成功", allDevices);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询设备列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单绑定的智能主机
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/getOrderHostDevice")
    public AjaxResult getOrderHostDevice(@RequestBody Map<String, Object> params) {
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            
            // 查询该订单绑定的智能主机
            QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            queryWrapper.eq("delivery_id", deliveryId);
            queryWrapper.eq("device_type", 1); // 智能主机
            IotDeviceData hostDevice = iotDeviceDataMapper.selectOne(queryWrapper);
            
            if (hostDevice != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("deviceId", hostDevice.getDeviceId());
                result.put("deviceType", hostDevice.getDeviceType());
                result.put("deliveryId", hostDevice.getDeliveryId());
                result.put("weight", hostDevice.getWeight());
                result.put("battery", hostDevice.getBatteryPercentage());
                result.put("deviceVoltage", hostDevice.getVoltage());
                result.put("deviceTemp", hostDevice.getTemperature());
                result.put("latitude", hostDevice.getLatitude());
                result.put("longitude", hostDevice.getLongitude());
                result.put("updateTime", hostDevice.getUpdateTime());
                result.put("createTime", hostDevice.getCreateTime());
                
                return AjaxResult.success("查询成功", result);
            } else {
                return AjaxResult.success("查询成功", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 测试接口：检查订单设备数据
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/testOrderDevices")
    public AjaxResult testOrderDevices(@RequestBody Map<String, Object> params) {
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            // 查询该订单的所有设备
            QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            queryWrapper.eq("delivery_id", deliveryId);
            List<IotDeviceData> allDevices = iotDeviceDataMapper.selectList(queryWrapper);
            
            Map<String, Object> result = new HashMap<>();
            result.put("deliveryId", deliveryId);
            result.put("totalDevices", allDevices.size());
            
            List<Map<String, Object>> deviceList = new ArrayList<>();
            for (IotDeviceData device : allDevices) {
                
                Map<String, Object> deviceInfo = new HashMap<>();
                deviceInfo.put("deviceId", device.getDeviceId());
                deviceInfo.put("deviceType", device.getDeviceType());
                deviceInfo.put("deliveryId", device.getDeliveryId());
                deviceInfo.put("bindWeight", device.getWeight()); 
                deviceList.add(deviceInfo);
            }
            result.put("devices", deviceList);
            
            return AjaxResult.success("查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新设备delivery_id、weight和car_number
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/updateDeviceDeliveryId")
    public AjaxResult updateDeviceDeliveryId(@RequestBody Map<String, Object> params) {
        String deviceId = (String) params.get("deviceId");
        Integer deliveryId = (Integer) params.get("deliveryId");
        Double weight = params.get("weight") != null ? Double.valueOf(params.get("weight").toString()) : null;
        String carNumber = (String) params.get("carNumber");
        
        if (deviceId == null || deviceId.trim().isEmpty()) {
            return AjaxResult.error("设备ID不能为空");
        }
        
        try {
            
            // 查询设备
            QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            queryWrapper.eq("device_id", deviceId);
            IotDeviceData device = iotDeviceDataMapper.selectOne(queryWrapper);
            
            if (device == null) {
                return AjaxResult.error("设备不存在");
            }
            
            // 使用LambdaUpdateWrapper来更新，支持null值
            LambdaUpdateWrapper<IotDeviceData> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(IotDeviceData::getDeviceId, deviceId);
            
            // 设置delivery_id（可以是null）
            updateWrapper.set(IotDeviceData::getDeliveryId, deliveryId);
            
            // 设置car_number（可以是null）
            updateWrapper.set(IotDeviceData::getCarNumber, carNumber);
            
            // 设置weight（如果有值）
            if (weight != null) {
                updateWrapper.set(IotDeviceData::getWeight, weight);
            }
            
            // 设置更新时间
            updateWrapper.set(IotDeviceData::getUpdateTime, new Date());
            
            int result = iotDeviceDataMapper.update(null, updateWrapper);
            
            if (result > 0) {
                return AjaxResult.success("设备更新成功");
            } else {
                return AjaxResult.error("设备更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新设备失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新设备weight
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/updateDeviceWeights")
    public AjaxResult updateDeviceWeights(@RequestBody Map<String, Object> params) {
        Integer deliveryId = (Integer) params.get("deliveryId");
        List<Map<String, Object>> devices = (List<Map<String, Object>>) params.get("devices");
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        if (devices == null || devices.isEmpty()) {
            return AjaxResult.error("设备列表不能为空");
        }
        
        try {
            
            int successCount = 0;
            for (Map<String, Object> deviceInfo : devices) {
                String deviceId = (String) deviceInfo.get("deviceId");
                Double weight = deviceInfo.get("weight") != null ? Double.valueOf(deviceInfo.get("weight").toString()) : null;
                
                if (deviceId != null && !deviceId.trim().isEmpty()) {
                    QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
                    // 只查询正常状态的设备（is_delet=0）
                    queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
                    queryWrapper.eq("device_id", deviceId);
                    queryWrapper.eq("delivery_id", deliveryId);
                    
                    IotDeviceData device = iotDeviceDataMapper.selectOne(queryWrapper);
                    if (device != null) {
                        device.setWeight(weight);
                        int result = iotDeviceDataMapper.updateById(device);
                        if (result > 0) {
                            successCount++;
                        }
                    }
                }
            }
            
            return AjaxResult.success("批量更新完成", "成功更新 " + successCount + " 个设备的重量");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("批量更新设备重量失败：" + e.getMessage());
        }
    }
    
    /**
     * 清空设备delivery_id、car_number和weight
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/clearDeliveryId")
    public AjaxResult clearDeliveryId(@RequestBody Map<String, Object> params) {
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            
            // 查询所有关联该deliveryId的设备
            QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            queryWrapper.eq("delivery_id", deliveryId);
            List<IotDeviceData> devices = iotDeviceDataMapper.selectList(queryWrapper);
            
            int updatedCount = 0;
            for (IotDeviceData device : devices) {
                logger.info("清空设备关联信息: deviceId={}, 原delivery_id={}, 原car_number={}, 原weight={}", 
                    device.getDeviceId(), device.getDeliveryId(), device.getCarNumber(), device.getWeight());
                // 将delivery_id、car_number和weight都设置为null
                device.setDeliveryId(null);
                device.setCarNumber(null); // 清空车牌号
                device.setWeight(null); // 同时清空weight字段
                iotDeviceDataMapper.updateById(device);
                updatedCount++;
            }
            
            return AjaxResult.success("操作成功", "已清空 " + updatedCount + " 个设备的delivery_id、car_number和weight");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("清空设备delivery_id、car_number和weight失败：" + e.getMessage());
        }
    }

    /**
     * 获取智能耳标日志
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/getEarTagLogs")
    public AjaxResult getEarTagLogs(@RequestBody Map<String, Object> params) {
        String deviceId = (String) params.get("deviceId");
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deviceId == null || deviceId.trim().isEmpty()) {
            return AjaxResult.error("设备ID不能为空");
        }
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            
            // 验证设备是否存在且类型正确
            QueryWrapper<IotDeviceData> deviceQuery = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            deviceQuery.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            deviceQuery.eq("device_id", deviceId);
            deviceQuery.eq("device_type", 2); // 耳标
            deviceQuery.eq("delivery_id", deliveryId);
            IotDeviceData device = iotDeviceDataMapper.selectOne(deviceQuery);
            
            if (device == null) {
                return AjaxResult.error("设备不存在或类型不匹配");
            }
            
            // 查询日志表，按60分钟间隔分组
            QueryWrapper<JbqClientLog> logQuery = new QueryWrapper<>();
            logQuery.eq("device_id", deviceId);
            logQuery.orderByAsc("update_time");
            List<JbqClientLog> logs = jbqClientLogMapper.selectList(logQuery);
            
            
            // 按60分钟间隔分组
            List<Map<String, Object>> groupedLogs = new ArrayList<>();
            SimpleDateFormat hourFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            Map<String, Map<String, Object>> hourGroups = new HashMap<>();
            
            for (JbqClientLog log : logs) {
                String hourKey = hourFormat.format(log.getUpdateTime());
                Map<String, Object> hourGroup = hourGroups.get(hourKey);
                
                if (hourGroup == null) {
                    hourGroup = new HashMap<>();
                    hourGroup.put("hourTime", hourKey);
                    hourGroup.put("deviceId", log.getDeviceId());
                    hourGroup.put("deviceVoltage", log.getDeviceVoltage());
                    hourGroup.put("deviceTemp", log.getDeviceTemp());
                    hourGroup.put("latitude", log.getLatitude());
                    hourGroup.put("longitude", log.getLongitude());
                    hourGroup.put("walkSteps", log.getWalkSteps());
                    hourGroup.put("yWalkSteps", log.getYWalkSteps());
                    hourGroup.put("updateTime", log.getUpdateTime());
                    hourGroups.put(hourKey, hourGroup);
                }
            }
            
            groupedLogs.addAll(hourGroups.values());
            
            return AjaxResult.success("查询成功", groupedLogs);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询智能耳标日志失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取智能项圈日志
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/getCollarLogs")
    public AjaxResult getCollarLogs(@RequestBody Map<String, Object> params) {
        String deviceId = (String) params.get("deviceId");
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deviceId == null || deviceId.trim().isEmpty()) {
            return AjaxResult.error("设备ID不能为空");
        }
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            
            // 验证设备是否存在且类型正确
            QueryWrapper<IotDeviceData> deviceQuery = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            deviceQuery.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            deviceQuery.eq("device_id", deviceId);
            deviceQuery.eq("device_type", 4); // 项圈
            deviceQuery.eq("delivery_id", deliveryId);
            IotDeviceData device = iotDeviceDataMapper.selectOne(deviceQuery);
            
            if (device == null) {
                return AjaxResult.error("设备不存在或类型不匹配");
            }
            
            // 查询日志表，按60分钟间隔分组
            QueryWrapper<XqClientLog> logQuery = new QueryWrapper<>();
            logQuery.eq("device_id", deviceId);
            logQuery.orderByAsc("update_time");
            List<XqClientLog> logs = xqClientLogMapper.selectList(logQuery);
            
            
            // 按60分钟间隔分组
            List<Map<String, Object>> groupedLogs = new ArrayList<>();
            SimpleDateFormat hourFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            Map<String, Map<String, Object>> hourGroups = new HashMap<>();
            
            for (XqClientLog log : logs) {
                String hourKey = hourFormat.format(log.getUpdateTime());
                Map<String, Object> hourGroup = hourGroups.get(hourKey);
                
                if (hourGroup == null) {
                    hourGroup = new HashMap<>();
                    hourGroup.put("hourTime", hourKey);
                    hourGroup.put("deviceId", log.getDeviceId());
                    hourGroup.put("deviceVoltage", log.getDeviceVoltage());
                    hourGroup.put("deviceTemp", log.getDeviceTemp());
                    hourGroup.put("latitude", log.getLatitude());
                    hourGroup.put("longitude", log.getLongitude());
                    hourGroup.put("walkSteps", log.getWalkSteps());
                    hourGroup.put("yWalkSteps", log.getYWalkSteps());
                    hourGroup.put("updateTime", log.getUpdateTime());
                    hourGroups.put(hourKey, hourGroup);
                }
            }
            
            groupedLogs.addAll(hourGroups.values());
            
            return AjaxResult.success("查询成功", groupedLogs);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询智能项圈日志失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取智能主机日志
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/getHostLogs")
    public AjaxResult getHostLogs(@RequestBody Map<String, Object> params) {
        String deviceId = (String) params.get("deviceId");
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deviceId == null || deviceId.trim().isEmpty()) {
            return AjaxResult.error("设备ID不能为空");
        }
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            
            // 验证设备是否存在且类型正确
            QueryWrapper<IotDeviceData> deviceQuery = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            deviceQuery.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            deviceQuery.eq("device_id", deviceId);
            deviceQuery.eq("device_type", 1); // 主机
            deviceQuery.eq("delivery_id", deliveryId);
            IotDeviceData device = iotDeviceDataMapper.selectOne(deviceQuery);
            
            if (device == null) {
                return AjaxResult.error("设备不存在或类型不匹配");
            }
            
            // 查询日志表，按60分钟间隔分组
            QueryWrapper<JbqServerLog> logQuery = new QueryWrapper<>();
            logQuery.eq("device_id", deviceId);
            logQuery.orderByAsc("update_time");
            List<JbqServerLog> logs = jbqServerLogMapper.selectList(logQuery);
            
            
            // 按60分钟间隔分组
            List<Map<String, Object>> groupedLogs = new ArrayList<>();
            SimpleDateFormat hourFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            Map<String, Map<String, Object>> hourGroups = new HashMap<>();
            
            for (JbqServerLog log : logs) {
                String hourKey = hourFormat.format(log.getUpdateTime());
                Map<String, Object> hourGroup = hourGroups.get(hourKey);
                
                if (hourGroup == null) {
                    hourGroup = new HashMap<>();
                    hourGroup.put("hourTime", hourKey);
                    hourGroup.put("deviceId", log.getDeviceId());
                    hourGroup.put("deviceVoltage", log.getDeviceVoltage());
                    hourGroup.put("deviceTemp", log.getDeviceTemp());
                    hourGroup.put("latitude", log.getLatitude());
                    hourGroup.put("longitude", log.getLongitude());
                    hourGroup.put("walkSteps", log.getWalkSteps());
                    hourGroup.put("yWalkSteps", log.getYWalkSteps());
                    hourGroup.put("updateTime", log.getUpdateTime());
                    hourGroups.put(hourKey, hourGroup);
                }
            }
            
            groupedLogs.addAll(hourGroups.values());
            
            return AjaxResult.success("查询成功", groupedLogs);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询智能主机日志失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取智能耳标运动轨迹
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/getEarTagTrajectory")
    public AjaxResult getEarTagTrajectory(@RequestBody Map<String, Object> params) {
        String deviceId = (String) params.get("deviceId");
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deviceId == null || deviceId.trim().isEmpty()) {
            return AjaxResult.error("设备ID不能为空");
        }
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            
            // 验证设备是否存在且类型正确
            QueryWrapper<IotDeviceData> deviceQuery = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            deviceQuery.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            deviceQuery.eq("device_id", deviceId);
            deviceQuery.eq("device_type", 2); // 耳标
            deviceQuery.eq("delivery_id", deliveryId);
            IotDeviceData device = iotDeviceDataMapper.selectOne(deviceQuery);
            
            if (device == null) {
                return AjaxResult.error("设备不存在或类型不匹配");
            }
            
            // 查询轨迹数据，按60分钟间隔分组
            QueryWrapper<JbqClientLog> logQuery = new QueryWrapper<>();
            logQuery.eq("device_id", deviceId);
            logQuery.isNotNull("latitude");
            logQuery.isNotNull("longitude");
            logQuery.ne("latitude", "0");
            logQuery.ne("longitude", "0");
            logQuery.orderByAsc("update_time");
            List<JbqClientLog> logs = jbqClientLogMapper.selectList(logQuery);
            
            
            // 按60分钟间隔分组，提取经纬度和时间戳
            List<Map<String, Object>> trajectoryPoints = new ArrayList<>();
            SimpleDateFormat hourFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            Map<String, Map<String, Object>> hourGroups = new HashMap<>();
            
            for (JbqClientLog log : logs) {
                String hourKey = hourFormat.format(log.getUpdateTime());
                Map<String, Object> hourGroup = hourGroups.get(hourKey);
                
                if (hourGroup == null) {
                    hourGroup = new HashMap<>();
                    hourGroup.put("latitude", log.getLatitude());
                    hourGroup.put("longitude", log.getLongitude());
                    hourGroup.put("timestamp", log.getUpdateTime());
                    hourGroup.put("hourTime", hourKey);
                    hourGroups.put(hourKey, hourGroup);
                }
            }
            
            trajectoryPoints.addAll(hourGroups.values());
            
            return AjaxResult.success("查询成功", trajectoryPoints);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询智能耳标运动轨迹失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取智能项圈运动轨迹
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/getCollarTrajectory")
    public AjaxResult getCollarTrajectory(@RequestBody Map<String, Object> params) {
        String deviceId = (String) params.get("deviceId");
        
        // 安全地转换deliveryId为Integer，支持String和Integer两种类型
        Integer deliveryId = null;
        Object deliveryIdObj = params.get("deliveryId");
        if (deliveryIdObj != null) {
            if (deliveryIdObj instanceof Integer) {
                deliveryId = (Integer) deliveryIdObj;
            } else if (deliveryIdObj instanceof String) {
                try {
                    deliveryId = Integer.parseInt((String) deliveryIdObj);
                } catch (NumberFormatException e) {
                    return AjaxResult.error("运送清单ID格式错误");
                }
            }
        }
        
        if (deviceId == null || deviceId.trim().isEmpty()) {
            return AjaxResult.error("设备ID不能为空");
        }
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            
            // 验证设备是否存在且类型正确
            QueryWrapper<IotDeviceData> deviceQuery = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            deviceQuery.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            deviceQuery.eq("device_id", deviceId);
            deviceQuery.eq("device_type", 4); // 项圈
            deviceQuery.eq("delivery_id", deliveryId);
            IotDeviceData device = iotDeviceDataMapper.selectOne(deviceQuery);
            
            if (device == null) {
                return AjaxResult.error("设备不存在或类型不匹配");
            }
            
            // 查询轨迹数据，按60分钟间隔分组
            QueryWrapper<XqClientLog> logQuery = new QueryWrapper<>();
            logQuery.eq("device_id", deviceId);
            logQuery.isNotNull("latitude");
            logQuery.isNotNull("longitude");
            logQuery.ne("latitude", "0");
            logQuery.ne("longitude", "0");
            
            // 添加日期范围过滤（如果前端传了日期参数）
            if (params.get("startTime") != null && params.get("endTime") != null) {
                String startTime = params.get("startTime").toString();
                String endTime = params.get("endTime").toString();
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date startDate = sdf.parse(startTime);
                    Date endDate = sdf.parse(endTime);
                    logQuery.between("update_time", startDate, endDate);
                } catch (Exception e) {
                }
            }
            
            logQuery.orderByAsc("update_time");
            List<XqClientLog> logs = xqClientLogMapper.selectList(logQuery);
            
            
            // 按60分钟间隔分组，提取经纬度和时间戳
            List<Map<String, Object>> trajectoryPoints = new ArrayList<>();
            SimpleDateFormat hourFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            Map<String, Map<String, Object>> hourGroups = new HashMap<>();
            
            for (XqClientLog log : logs) {
                String hourKey = hourFormat.format(log.getUpdateTime());
                Map<String, Object> hourGroup = hourGroups.get(hourKey);
                
                if (hourGroup == null) {
                    hourGroup = new HashMap<>();
                    hourGroup.put("latitude", log.getLatitude());
                    hourGroup.put("longitude", log.getLongitude());
                    hourGroup.put("timestamp", log.getUpdateTime());
                    hourGroup.put("hourTime", hourKey);
                    hourGroups.put(hourKey, hourGroup);
                }
            }
            
            trajectoryPoints.addAll(hourGroups.values());
            
            return AjaxResult.success("查询成功", trajectoryPoints);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询智能项圈运动轨迹失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取智能主机运动轨迹
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/getHostTrajectory")
    public AjaxResult getHostTrajectory(@RequestBody Map<String, Object> params) {
        String deviceId = (String) params.get("deviceId");
        Integer deliveryId = (Integer) params.get("deliveryId");
        
        if (deviceId == null || deviceId.trim().isEmpty()) {
            return AjaxResult.error("设备ID不能为空");
        }
        
        if (deliveryId == null) {
            return AjaxResult.error("运送清单ID不能为空");
        }
        
        try {
            
            // 验证设备是否存在且类型正确
            QueryWrapper<IotDeviceData> deviceQuery = new QueryWrapper<>();
            // 只查询正常状态的设备（is_delet=0）
            deviceQuery.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            deviceQuery.eq("device_id", deviceId);
            deviceQuery.eq("device_type", 1); // 主机
            deviceQuery.eq("delivery_id", deliveryId);
            IotDeviceData device = iotDeviceDataMapper.selectOne(deviceQuery);
            
            if (device == null) {
                return AjaxResult.error("设备不存在或类型不匹配");
            }
            
            // 查询轨迹数据，按60分钟间隔分组
            QueryWrapper<JbqServerLog> logQuery = new QueryWrapper<>();
            logQuery.eq("device_id", deviceId);
            logQuery.isNotNull("latitude");
            logQuery.isNotNull("longitude");
            logQuery.ne("latitude", "0");
            logQuery.ne("longitude", "0");
            logQuery.orderByAsc("update_time");
            List<JbqServerLog> logs = jbqServerLogMapper.selectList(logQuery);
            
            
            // 按60分钟间隔分组，提取经纬度和时间戳
            List<Map<String, Object>> trajectoryPoints = new ArrayList<>();
            SimpleDateFormat hourFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            Map<String, Map<String, Object>> hourGroups = new HashMap<>();
            
            for (JbqServerLog log : logs) {
                String hourKey = hourFormat.format(log.getUpdateTime());
                Map<String, Object> hourGroup = hourGroups.get(hourKey);
                
                if (hourGroup == null) {
                    hourGroup = new HashMap<>();
                    hourGroup.put("latitude", log.getLatitude());
                    hourGroup.put("longitude", log.getLongitude());
                    hourGroup.put("timestamp", log.getUpdateTime());
                    hourGroup.put("hourTime", hourKey);
                    hourGroups.put(hourKey, hourGroup);
                }
            }
            
            trajectoryPoints.addAll(hourGroups.values());
            
            return AjaxResult.success("查询成功", trajectoryPoints);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("查询智能主机运动轨迹失败：" + e.getMessage());
        }
    }

    /**
     * 手动触发设备日志同步
     * 用于测试和调试
     */
    @SaCheckPermission("delivery:view")
    @PostMapping(value = "/manualSyncDeviceLogs")
    public AjaxResult manualSyncDeviceLogs() {
        try {
            
            // 执行同步
            iotDeviceLogSyncService.syncDeviceDataToLogs();
            
            // 输出统计信息
            iotDeviceLogSyncService.logSyncStatistics();
            
            
            return AjaxResult.success("设备日志同步完成");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("设备日志同步失败：" + e.getMessage());
        }
    }

    /**
     * 获取日志同步统计信息
     */
    @SaCheckPermission("delivery:view")
    @GetMapping(value = "/getLogSyncStatistics")
    public AjaxResult getLogSyncStatistics() {
        try {
            
            // 统计各日志表的记录数
            long hostLogCount = jbqServerLogMapper.selectCount(null);
            long earTagLogCount = jbqClientLogMapper.selectCount(null);
            long collarLogCount = xqClientLogMapper.selectCount(null);
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("hostLogCount", hostLogCount);
            statistics.put("earTagLogCount", earTagLogCount);
            statistics.put("collarLogCount", collarLogCount);
            statistics.put("totalLogCount", hostLogCount + earTagLogCount + collarLogCount);
            
            
            return AjaxResult.success("获取统计信息成功", statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取统计信息失败：" + e.getMessage());
        }
    }

}



