package com.aiotagro.cattletrade.business.controller;

import com.aiotagro.cattletrade.business.entity.IotDeviceData;
import com.aiotagro.cattletrade.business.entity.Delivery;
import com.aiotagro.cattletrade.business.mapper.IotDeviceDataMapper;
import com.aiotagro.cattletrade.business.service.IDeliveryService;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * IoT设备代理控制器
 * 用于代理调用外部IoT设备API
 *
 * @author System
 * @date 2025-01-16
 */
@RestController
@RequestMapping("/iotDevice")
public class IotDeviceProxyController {

    private static final Logger logger = LoggerFactory.getLogger(IotDeviceProxyController.class);
    
           @Autowired
           private IotDeviceDataMapper iotDeviceDataMapper;
           
           @Autowired
           private IDeliveryService deliveryService;
    
    /**
     * 查询IoT设备列表（从本地数据库）
     */
    @PostMapping("/queryList")
    public AjaxResult queryList(@RequestBody Map<String, Object> params) {
        try {
            logger.info("查询IoT设备数据，参数: {}", params);
            if (params == null) {
                params = new HashMap<>();
            }
            
            // 构建查询条件
            QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
            
            // 只查询正常状态的设备（is_delet=0）
            queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
            
            // 根据设备类型查询
            if (params.containsKey("type") && params.get("type") != null) {
                Integer deviceType = (Integer) params.get("type");
                queryWrapper.eq("device_type", deviceType);
                // 只有当 allotType 参数存在且为 "unassigned" 时，才限制 delivery_id 为空
                // 这是为了在创建运送清单时只显示未绑定的设备
                // 硬件管理页面（eartag.vue, host.vue, collar.vue）不传递 allotType，会显示所有设备
                if (params.containsKey("allotType") && "unassigned".equals(params.get("allotType"))) {
                    queryWrapper.isNull("delivery_id");
                    logger.info("查询未绑定的设备，类型: {}", deviceType);
                } else {
                    logger.info("查询所有设备（包括已分配的），类型: {}", deviceType);
                }
            }
            
            // 根据设备ID查询
            if (params.containsKey("deviceId") && params.get("deviceId") != null && 
                !String.valueOf(params.get("deviceId")).trim().isEmpty()) {
                queryWrapper.eq("device_id", params.get("deviceId"));
            }
            
            // 根据SN查询（项圈页面使用）
            if (params.containsKey("sn") && params.get("sn") != null && 
                !String.valueOf(params.get("sn")).trim().isEmpty()) {
                queryWrapper.eq("device_id", params.get("sn"));
            }
            
            // 号段范围查询
            String startNo = (String) params.get("startNo");
            String endNo = (String) params.get("endNo");
            
            if (startNo != null && !startNo.trim().isEmpty() && 
                endNo != null && !endNo.trim().isEmpty()) {
                logger.info("号段范围查询: {} - {}", startNo, endNo);
                
                // 验证号段格式（假设设备ID是数字）
                try {
                    long startNum = Long.parseLong(startNo.trim());
                    long endNum = Long.parseLong(endNo.trim());
                    
                    if (startNum <= endNum) {
                        // 使用BETWEEN查询
                        queryWrapper.between("CAST(device_id AS UNSIGNED)", startNum, endNum);
                        logger.info("添加号段范围条件: {} - {}", startNum, endNum);
                    } else {
                        logger.warn("开始号段不能大于结束号段: {} > {}", startNum, endNum);
                    }
                } catch (NumberFormatException e) {
                    logger.warn("号段格式错误，跳过号段查询: startNo={}, endNo={}", startNo, endNo);
                }
            } else if (startNo != null && !startNo.trim().isEmpty()) {
                // 只有开始号段，查询大于等于该号段的设备
                try {
                    long startNum = Long.parseLong(startNo.trim());
                    queryWrapper.ge("CAST(device_id AS UNSIGNED)", startNum);
                    logger.info("添加起始号段条件: >={}", startNum);
                } catch (NumberFormatException e) {
                    logger.warn("起始号段格式错误，跳过号段查询: startNo={}", startNo);
                }
            } else if (endNo != null && !endNo.trim().isEmpty()) {
                // 只有结束号段，查询小于等于该号段的设备
                try {
                    long endNum = Long.parseLong(endNo.trim());
                    queryWrapper.le("CAST(device_id AS UNSIGNED)", endNum);
                    logger.info("添加结束号段条件: <={}", endNum);
                } catch (NumberFormatException e) {
                    logger.warn("结束号段格式错误，跳过号段查询: endNo={}", endNo);
                }
            }
            
            // 分页参数
            Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
            Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
            
            // 查询总数
            Long total = iotDeviceDataMapper.selectCount(queryWrapper);
            
            // 分页查询
            queryWrapper.last("LIMIT " + ((pageNum - 1) * pageSize) + ", " + pageSize);
            List<IotDeviceData> deviceList = iotDeviceDataMapper.selectList(queryWrapper);
            
            // 转换为前端需要的格式
            List<Map<String, Object>> resultList = deviceList.stream().map(device -> {
                Map<String, Object> deviceMap = new HashMap<>();
                deviceMap.put("deviceId", device.getDeviceId());
                deviceMap.put("type", device.getDeviceType());
                deviceMap.put("name", device.getDeviceName());
                deviceMap.put("voltage", device.getVoltage());
                deviceMap.put("battery", device.getBatteryPercentage());
                deviceMap.put("temperature", device.getTemperature());
                deviceMap.put("steps", device.getSteps());
                deviceMap.put("sameDaySteps", device.getSameDaySteps());
                deviceMap.put("signal", device.getSignalStrength());
                deviceMap.put("rsrp", device.getRsrp());
                deviceMap.put("gpsState", device.getGpsState());
                deviceMap.put("latitude", device.getLatitude());
                deviceMap.put("longitude", device.getLongitude());
                deviceMap.put("altitude", device.getAltitude());
                deviceMap.put("status", device.getStatus());
                deviceMap.put("ver", device.getVersion());
                deviceMap.put("uptime", device.getUptime());
                deviceMap.put("carNumber", device.getCarNumber());
                deviceMap.put("deliveryId", device.getDeliveryId());
                deviceMap.put("tenantId", device.getTenantId());
                
                // 关联查询delivery表信息
                if (device.getDeliveryId() != null) {
                    Delivery delivery = deliveryService.getById(device.getDeliveryId());
                    if (delivery != null) {
                        deviceMap.put("deliveryNumber", delivery.getDeliveryNumber());
                        deviceMap.put("deliveryTitle", delivery.getDeliveryTitle());
                        // 如果设备表中的carNumber为空，使用delivery表中的车牌号
                        if (device.getCarNumber() == null || device.getCarNumber().trim().isEmpty()) {
                            deviceMap.put("carNumber", delivery.getLicensePlate());
                        }
                    }
                } else {
                    deviceMap.put("deliveryNumber", null);
                    deviceMap.put("deliveryTitle", null);
                }
                
                return deviceMap;
            }).collect(java.util.stream.Collectors.toList());
            
            Map<String, Object> result = new HashMap<>();
            result.put("rows", resultList);
            result.put("total", total);
            
            logger.info("查询到设备数据: {} 条", resultList.size());
            return AjaxResult.success("操作成功", result);
            
        } catch (Exception e) {
                   logger.error("查询IoT设备数据失败", e);
                   return AjaxResult.error("查询设备数据失败：" + e.getMessage());
               }
           }
           
           /**
            * 查询IoT设备定位信息
            */
           @PostMapping("/getLocation")
           public AjaxResult getLocation(@RequestBody Map<String, Object> params) {
               try {
                   logger.info("查询IoT设备定位信息，参数: {}", params);
                   if (params == null) {
                       params = new HashMap<>();
                   }
                   
                   String deviceId = (String) params.get("deviceId");
                   if (deviceId == null || deviceId.trim().isEmpty()) {
                       return AjaxResult.error("设备ID不能为空");
                   }
                   
                   // 构建查询条件
                   QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
                   // 只查询正常状态的设备
                   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("未找到对应的设备信息");
                   }
                   
                   // 检查是否有定位信息
                   if (device.getLatitude() == null || device.getLongitude() == null || 
                       device.getLatitude().trim().isEmpty() || device.getLongitude().trim().isEmpty()) {
                       return AjaxResult.error("该设备暂无定位信息");
                   }
                   
                   Map<String, Object> result = new HashMap<>();
                   result.put("deviceId", device.getDeviceId());
                   result.put("latitude", device.getLatitude());
                   result.put("longitude", device.getLongitude());
                   result.put("altitude", device.getAltitude());
                   result.put("gpsState", device.getGpsState());
                   result.put("updateTime", device.getUptime());
                   
                   logger.info("查询到设备定位信息: {}", device.getDeviceId());
                   return AjaxResult.success("操作成功", result);
                   
               } catch (Exception e) {
                   logger.error("查询IoT设备定位信息失败", e);
                   return AjaxResult.error("查询设备定位信息失败：" + e.getMessage());
               }
           }
           
           /**
            * 查询设备列表（支持查询可分配设备和已分配设备）
            * allotType=0: 查询可分配设备（未分配给装车订单的设备）
            * allotType=1: 查询已分配设备（已分配给装车订单的设备）
            */
           @PostMapping("/getAssignableDevices")
           public AjaxResult getAssignableDevices(@RequestBody Map<String, Object> params) {
               try {
                   // 根据allotType显示不同的日志信息
                   Object allotTypeObj = params != null ? params.get("allotType") : null;
                   String allotType = allotTypeObj != null ? String.valueOf(allotTypeObj) : "0";
                   String logMessage = "1".equals(allotType) ? "查询已分配设备列表" : "查询可分配设备列表";
                   logger.info("{}, 参数: {}", logMessage, params);
                   
                   if (params == null) {
                       params = new HashMap<>();
                   }
                   
                   // 构建查询条件
                   QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
                   
                   // 只查询正常状态的设备（is_delet=0）
                   queryWrapper.and(wrapper -> wrapper.eq("is_delet", 0).or().isNull("is_delet"));
                   
                   // 根据设备类型过滤
                   if (params.containsKey("deviceType") && params.get("deviceType") != null) {
                       Object deviceTypeObj = params.get("deviceType");
                       Integer deviceType;
                       if (deviceTypeObj instanceof String) {
                           deviceType = Integer.parseInt((String) deviceTypeObj);
                       } else if (deviceTypeObj instanceof Integer) {
                           deviceType = (Integer) deviceTypeObj;
                       } else {
                           deviceType = null;
                       }
                       if (deviceType != null) {
                           queryWrapper.eq("device_type", deviceType);
                       }
                   }
                   
                   // 根据设备ID搜索
                   if (params.containsKey("deviceId") && params.get("deviceId") != null && 
                       !String.valueOf(params.get("deviceId")).trim().isEmpty()) {
                       queryWrapper.like("device_id", params.get("deviceId"));
                   }

                   // 根据租户ID过滤
                   if (params.containsKey("tenantId") && params.get("tenantId") != null) {
                       Object tenantIdObj = params.get("tenantId");
                       Integer tenantId;
                       if (tenantIdObj instanceof String) {
                           tenantId = Integer.parseInt((String) tenantIdObj);
                       } else if (tenantIdObj instanceof Integer) {
                           tenantId = (Integer) tenantIdObj;
                       } else {
                           tenantId = null;
                       }
                       if (tenantId != null) {
                           queryWrapper.eq("tenant_id", tenantId);
                       }
                   }
                   // 注意：装车订单分配设备时，不限制tenant_id，只限制delivery_id
                   
                   // 根据分配状态过滤（allotType）
                   if (params.containsKey("allotType") && params.get("allotType") != null) {
                       if (allotTypeObj instanceof String) {
                           allotType = (String) allotTypeObj;
                       } else {
                           allotType = String.valueOf(allotTypeObj);
                       }
                       
                       // ✅ 检查是否是租户分配模式（通过 mode 参数判断）
                       // 注意：租户模式和装车订单模式是完全独立的！
                       String mode = params.containsKey("mode") ? String.valueOf(params.get("mode")) : "delivery";
                       boolean isTenantMode = "tenant".equals(mode);
                       
                       logger.info("分配模式判断 - mode: {}, isTenantMode: {}, allotType: {}", mode, isTenantMode, allotType);
                       
                       if ("0".equals(allotType)) {
                           if (isTenantMode) {
                               // 租户模式-未分配：仅查询 tenant_id 为空的设备（忽略 delivery_id）
                               queryWrapper.and(wrapper -> wrapper.isNull("tenant_id").or().eq("tenant_id", ""));
                               logger.info("租户模式-未分配: 查询 tenant_id 为空的设备");
                           } else {
                               // 装车订单模式-未分配：仅查询 delivery_id 为空的设备（忽略 tenant_id）
                               queryWrapper.and(wrapper -> wrapper.isNull("delivery_id").or().eq("delivery_id", ""));
                               logger.info("装车订单模式-未分配: 查询 delivery_id 为空的设备");
                           }
                       } else if ("1".equals(allotType)) {
                           if (isTenantMode) {
                               // 租户模式-已分配：仅查询 tenant_id 不为空的设备（忽略 delivery_id）
                               queryWrapper.and(wrapper -> wrapper.isNotNull("tenant_id").and(w -> w.ne("tenant_id", "")));
                               logger.info("租户模式-已分配: 查询 tenant_id 不为空的设备");
                           } else {
                               // 装车订单模式-已分配：仅查询 delivery_id 不为空的设备（忽略 tenant_id）
                               queryWrapper.and(wrapper -> wrapper.isNotNull("delivery_id").and(w -> w.ne("delivery_id", "")));
                               logger.info("装车订单模式-已分配: 查询 delivery_id 不为空的设备");
                           }
                       }
                   } else {
                       // 如果没有传递allotType参数，默认查询未分配给装车订单的设备（不限制tenant_id）
                       queryWrapper.and(wrapper -> wrapper.isNull("delivery_id").or().eq("delivery_id", ""));
                       logger.info("未传递 allotType，默认查询 delivery_id 为空的设备");
                   }
                   
                   // 分页参数
                   Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
                   Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
                   
                   // 查询总数
                   Long total = iotDeviceDataMapper.selectCount(queryWrapper);
                   
                   // 分页查询
                   queryWrapper.last("LIMIT " + ((pageNum - 1) * pageSize) + ", " + pageSize);
                   List<IotDeviceData> deviceList = iotDeviceDataMapper.selectList(queryWrapper);
                   
                   // 转换为前端需要的格式
                   final String finalAllotType = allotType; // 创建final变量供lambda使用
                   List<Map<String, Object>> resultList = deviceList.stream().map(device -> {
                       Map<String, Object> deviceMap = new HashMap<>();
                       deviceMap.put("deviceId", device.getDeviceId());
                       deviceMap.put("deviceType", device.getDeviceType());
                       deviceMap.put("deviceName", device.getDeviceName());
                       deviceMap.put("voltage", device.getVoltage());
                       deviceMap.put("batteryPercentage", device.getBatteryPercentage());
                       deviceMap.put("temperature", device.getTemperature());
                       deviceMap.put("status", device.getStatus());
                       deviceMap.put("tenantId", device.getTenantId());
                       
                       // 根据allotType判断分配状态
                       boolean isAssigned;
                       if ("0".equals(finalAllotType)) {
                           // 未分配：根据delivery_id和tenant_id判断
                           isAssigned = device.getDeliveryId() != null || device.getTenantId() != null;
                       } else {
                           // 已分配：根据delivery_id和tenant_id判断
                           isAssigned = device.getDeliveryId() != null || device.getTenantId() != null;
                       }
                       deviceMap.put("isAssigned", isAssigned);
                       
                       // 如果有delivery_id，添加deliveryNumber字段
                       if (device.getDeliveryId() != null) {
                           // 这里可以根据delivery_id查询delivery表获取deliveryNumber
                           // 暂时使用delivery_id作为deliveryNumber
                           deviceMap.put("deliveryNumber", "DEL" + device.getDeliveryId());
                       }
                       
                       return deviceMap;
                   }).collect(java.util.stream.Collectors.toList());
                   
                   Map<String, Object> result = new HashMap<>();
                   result.put("rows", resultList);
                   result.put("total", total);
                   
                   logger.info("查询到设备: {} 条", resultList.size());
                   return AjaxResult.success("操作成功", result);
                   
               } catch (Exception e) {
                   logger.error("查询设备列表失败", e);
                   return AjaxResult.error("查询设备列表失败：" + e.getMessage());
               }
           }
           
           /**
            * 分配设备到装车订单
            */
           @PostMapping("/assignDevices")
           public AjaxResult assignDevices(@RequestBody Map<String, Object> params) {
               try {
                   logger.info("分配设备到装车订单，参数: {}", params);
                   if (params == null) {
                       params = new HashMap<>();
                   }
                   
                   @SuppressWarnings("unchecked")
                   List<String> deviceIds = (List<String>) params.get("deviceIds");
                   Integer deliveryId = (Integer) params.get("deliveryId");
                   String carNumber = (String) params.get("carNumber");
                   
                   if (deviceIds == null || deviceIds.isEmpty()) {
                       return AjaxResult.error("请选择要分配的设备");
                   }
                   
                   // 如果是取消分配（deliveryId为null），则不需要验证装车订单
                   Delivery delivery = null;
                   if (deliveryId != null) {
                       // 验证装车订单是否存在
                       logger.info("查询装车订单ID: {}", deliveryId);
                       delivery = deliveryService.getById(deliveryId);
                       if (delivery == null) {
                           logger.error("装车订单不存在，ID: {}", deliveryId);
                           return AjaxResult.error("装车订单不存在，ID: " + deliveryId);
                       }
                       logger.info("找到装车订单: {}", delivery.getDeliveryNumber());
                   } else {
                       logger.info("取消设备分配");
                   }
                   
                   int successCount = 0;
                   int failedCount = 0;
                   StringBuilder errorMessage = new StringBuilder();
                   
                   // 批量更新设备
                   for (String deviceId : deviceIds) {
                       try {
                           QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
                           queryWrapper.eq("device_id", deviceId);
                           IotDeviceData device = iotDeviceDataMapper.selectOne(queryWrapper);
                           
                           if (device != null) {
                               device.setDeliveryId(deliveryId); // 存储装车订单ID（null表示取消分配）
                               device.setCarNumber(carNumber);
                               device.setUpdateTime(LocalDateTime.now());
                               
                               iotDeviceDataMapper.updateById(device);
                               successCount++;
                               logger.debug("设备 {} 分配成功", deviceId);
                           } else {
                               failedCount++;
                               errorMessage.append("设备 ").append(deviceId).append(" 不存在; ");
                           }
                       } catch (Exception e) {
                           failedCount++;
                           errorMessage.append("设备 ").append(deviceId).append(" 分配失败: ").append(e.getMessage()).append("; ");
                           logger.error("设备 {} 分配失败", deviceId, e);
                       }
                   }
                   
                   String operation = deliveryId != null ? "分配" : "取消分配";
                   String resultMessage = String.format("设备%s完成！成功: %d, 失败: %d", operation, successCount, failedCount);
                   if (failedCount > 0) {
                       resultMessage += "。失败原因: " + errorMessage.toString();
                   }
                   
                   logger.info("设备分配结果: {}", resultMessage);
                   return AjaxResult.success(resultMessage);
                   
               } catch (Exception e) {
                   logger.error("分配设备到装车订单失败", e);
                   return AjaxResult.error("分配设备失败：" + e.getMessage());
               }
           }

           /**
            * 分配设备到租户
            */
           @PostMapping("/assignDevicesToTenant")
           public AjaxResult assignDevicesToTenant(@RequestBody Map<String, Object> params) {
               try {
                   logger.info("分配设备到租户，参数: {}", params);
                   if (params == null) {
                       params = new HashMap<>();
                   }

                   @SuppressWarnings("unchecked")
                   List<String> deviceIds = (List<String>) params.get("deviceIds");
                   Integer tenantId = (Integer) params.get("tenantId");

                   if (deviceIds == null || deviceIds.isEmpty()) {
                       return AjaxResult.error("请选择要分配的设备");
                   }

                   if (tenantId == null) {
                       return AjaxResult.error("租户ID不能为空");
                   }

                   int successCount = 0;
                   int failedCount = 0;
                   StringBuilder errorMessage = new StringBuilder();

                   // 批量更新设备
                   for (String deviceId : deviceIds) {
                       try {
                           QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
                           queryWrapper.eq("device_id", deviceId);
                           IotDeviceData device = iotDeviceDataMapper.selectOne(queryWrapper);

                           if (device != null) {
                               device.setTenantId(tenantId);
                               device.setUpdateTime(LocalDateTime.now());

                               iotDeviceDataMapper.updateById(device);
                               successCount++;
                               logger.debug("设备 {} 分配给租户 {} 成功", deviceId, tenantId);
                           } else {
                               failedCount++;
                               errorMessage.append("设备 ").append(deviceId).append(" 不存在; ");
                           }
                       } catch (Exception e) {
                           failedCount++;
                           errorMessage.append("设备 ").append(deviceId).append(" 分配失败: ").append(e.getMessage()).append("; ");
                           logger.error("设备 {} 分配给租户 {} 失败", deviceId, tenantId, e);
                       }
                   }

                   String resultMessage = String.format("设备分配完成！成功: %d, 失败: %d", successCount, failedCount);
                   if (failedCount > 0) {
                       resultMessage += "。失败原因: " + errorMessage.toString();
                   }

                   logger.info("设备分配给租户结果: {}", resultMessage);
                   return AjaxResult.success(resultMessage);

               } catch (Exception e) {
                   logger.error("分配设备到租户失败", e);
                   return AjaxResult.error("分配设备失败：" + e.getMessage());
               }
           }

           /**
            * 解绑设备（将tenant_id设置为空）
            */
           @PostMapping("/unassignDevicesFromTenant")
           public AjaxResult unassignDevicesFromTenant(@RequestBody Map<String, Object> params) {
               try {
                   logger.info("解绑设备，参数: {}", params);
                   if (params == null) {
                       params = new HashMap<>();
                   }

                   @SuppressWarnings("unchecked")
                   List<String> deviceIds = (List<String>) params.get("deviceIds");

                   if (deviceIds == null || deviceIds.isEmpty()) {
                       return AjaxResult.error("请选择要解绑的设备");
                   }

                   int successCount = 0;
                   int failedCount = 0;
                   StringBuilder errorMessage = new StringBuilder();

                   // 批量更新设备
                   for (String deviceId : deviceIds) {
                       try {
                           QueryWrapper<IotDeviceData> queryWrapper = new QueryWrapper<>();
                           queryWrapper.eq("device_id", deviceId);
                           IotDeviceData device = iotDeviceDataMapper.selectOne(queryWrapper);

                           if (device != null) {
                               logger.info("解绑前设备 {} 的tenant_id: {}", deviceId, device.getTenantId());
                               
                               // 使用LambdaUpdateWrapper直接更新，确保null值也能被更新
                               LambdaUpdateWrapper<IotDeviceData> updateWrapper = new LambdaUpdateWrapper<>();
                               updateWrapper.eq(IotDeviceData::getDeviceId, deviceId)
                                          .set(IotDeviceData::getTenantId, null)
                                          .set(IotDeviceData::getUpdateTime, LocalDateTime.now());
                               
                               int updateResult = iotDeviceDataMapper.update(null, updateWrapper);
                               logger.info("设备 {} 解绑更新结果: {}", deviceId, updateResult);
                               
                               // 验证更新结果
                               QueryWrapper<IotDeviceData> verifyWrapper = new QueryWrapper<>();
                               verifyWrapper.eq("device_id", deviceId);
                               IotDeviceData verifyDevice = iotDeviceDataMapper.selectOne(verifyWrapper);
                               logger.info("解绑后设备 {} 的tenant_id: {}", deviceId, verifyDevice != null ? verifyDevice.getTenantId() : "null");
                               
                               successCount++;
                               logger.debug("设备 {} 解绑成功", deviceId);
                           } else {
                               failedCount++;
                               errorMessage.append("设备 ").append(deviceId).append(" 不存在; ");
                           }
                       } catch (Exception e) {
                           failedCount++;
                           errorMessage.append("设备 ").append(deviceId).append(" 解绑失败: ").append(e.getMessage()).append("; ");
                           logger.error("设备 {} 解绑失败", deviceId, e);
                       }
                   }

                   String resultMessage = String.format("设备解绑完成！成功: %d, 失败: %d", successCount, failedCount);
                   if (failedCount > 0) {
                       resultMessage += "。失败原因: " + errorMessage.toString();
                   }

                   logger.info("设备解绑结果: {}", resultMessage);
                   return AjaxResult.success(resultMessage);

               } catch (Exception e) {
                   logger.error("解绑设备失败", e);
                   return AjaxResult.error("解绑设备失败：" + e.getMessage());
               }
           }
       }
