package com.pm.web.controller.buildingEquipmentMonitoring;

import com.pm.common.config.PageData;
import com.pm.common.core.controller.BaseController;
import com.pm.interfaceInfo.service.InterfaceInfoService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 建筑设备监控
 */
@RestController
@RequestMapping("/buildingEquipmentMonitoring/info")
public class BuildingEquipmentMonitoringController extends BaseController {


    /**
     * 查询url 访问接口
     */
    @Autowired
    private InterfaceInfoService interfaceInfoService;


    public static List<Map<String, Object>> generateDeviceData() {
        return Arrays.asList(
                // 基础设备（正常状态）
                createDeviceEntry(
                        "DEV-001", "主控制器", "CONTROLLER", "MK-2000",
                        "100,200,150", "1F", "中央控制室",
                        "正常", "#52c41a",
                        "/models/controller.obj", "{\"speed\":1.0,\"rotation\":0}",
                        null, null, null,
                        "MQTT", "START/STOP/REBOOT"
                ),
                // 传感器设备（警告状态）
                createDeviceEntry(
                        "DEV-002", "温度传感器A", "SENSOR", "TEMP-100",
                        "150,300,180", "1F", "东侧走廊",
                        "警告", "#faad14",
                        "/models/sensor.obj", "{\"pulse\":true}",
                        "WARN-001", "温度异常（45℃）", "2025-06-05 09:30:15",
                        "HTTP", "READ/RESET/CALIBRATE"
                ),
                // 执行器设备（故障状态）
                createDeviceEntry(
                        "DEV-003", "通风扇B", "ACTUATOR", "FAN-3000",
                        "200,150,220", "2F", "南侧机房",
                        "故障", "#f5222d",
                        "/models/fan.obj", "{\"speed\":0,\"angle\":90}",
                        "ERR-002", "电机过载", "2025-06-05 11:15:40",
                        "Modbus", "START/STOP/SET_SPEED"
                ),
                // 广播设备（正常状态）
                createDeviceEntry(
                        "DEV-004", "扬声器Z", "BROADCASTER", "SPEAKER-500",
                        "300,200,250", "1F", "大厅",
                        "正常", "#52c41a",
                        "/models/speaker.obj", "{\"volume\":75}",
                        null, null, null,
                        "TCP", "PLAY/STOP/SET_VOLUME"
                ),
                // 监控设备（正常状态）
                createDeviceEntry(
                        "DEV-005", "摄像头C", "MONITOR", "CAM-200",
                        "180,120,300", "3F", "西侧入口",
                        "正常", "#52c41a",
                        "/models/camera.obj", "{\"rotation\":180,\"zoom\":1.5}",
                        null, null, null,
                        "RTSP", "ROTATE/ZOOM/RECORD"
                ),
                // 新增15条模拟数据（包含不同状态和位置）
                createDeviceEntry(
                        "DEV-006", "烟雾报警器D", "ALARM", "SMOKE-100",
                        "120,280,170", "1F", "消防通道",
                        "警告", "#faad14",
                        "/models/alarm.obj", "{\"blink\":true}",
                        "WARN-003", "烟雾浓度异常", "2025-06-05 13:45:22",
                        "ZigBee", "TEST/RESET/SILENCE"
                ),
                createDeviceEntry(
                        "DEV-007", "温度传感器E", "SENSOR", "TEMP-100",
                        "170,320,190", "1F", "东侧机房",
                        "正常", "#52c41a",
                        "/models/sensor.obj", "{\"pulse\":true}",
                        null, null, null,
                        "HTTP", "READ/RESET/CALIBRATE"
                ),
                createDeviceEntry(
                        "DEV-008", "紧急按钮F", "INPUT", "BUTTON-50",
                        "250,180,160", "2F", "电梯厅",
                        "正常", "#52c41a",
                        "/models/button.obj", "{\"pressed\":false}",
                        null, null, null,
                        "TCP", "PRESS/RELEASE/TEST"
                ),
                createDeviceEntry(
                        "DEV-009", "通风扇G", "ACTUATOR", "FAN-3000",
                        "220,160,230", "2F", "北侧机房",
                        "故障", "#f5222d",
                        "/models/fan.obj", "{\"speed\":0,\"angle\":45}",
                        "ERR-004", "扇叶损坏", "2025-06-05 14:20:35",
                        "Modbus", "START/STOP/SET_SPEED"
                ),
                createDeviceEntry(
                        "DEV-010", "扬声器H", "BROADCASTER", "SPEAKER-500",
                        "310,210,260", "1F", "会议室",
                        "正常", "#52c41a",
                        "/models/speaker.obj", "{\"volume\":60}",
                        null, null, null,
                        "TCP", "PLAY/STOP/SET_VOLUME"
                ),
                createDeviceEntry(
                        "DEV-011", "摄像头I", "MONITOR", "CAM-200",
                        "190,130,310", "3F", "东侧走廊",
                        "正常", "#52c41a",
                        "/models/camera.obj", "{\"rotation\":270,\"zoom\":1.0}",
                        null, null, null,
                        "RTSP", "ROTATE/ZOOM/RECORD"
                ),
                createDeviceEntry(
                        "DEV-012", "湿度传感器J", "SENSOR", "HUMI-200",
                        "130,290,180", "1F", "消防通道",
                        "正常", "#52c41a",
                        "/models/sensor.obj", "{\"pulse\":true}",
                        null, null, null,
                        "HTTP", "READ/RESET/CALIBRATE"
                ),
                createDeviceEntry(
                        "DEV-013", "门禁控制器K", "CONTROLLER", "DOOR-1000",
                        "280,170,150", "2F", "财务室",
                        "警告", "#faad14",
                        "/models/controller.obj", "{\"lock\":true}",
                        "WARN-005", "多次无效刷卡", "2025-06-05 15:10:55",
                        "MQTT", "UNLOCK/LOCK/RESET"
                ),
                createDeviceEntry(
                        "DEV-014", "消防栓控制器L", "CONTROLLER", "FIRE-500",
                        "160,240,165", "1F", "东侧楼梯间",
                        "正常", "#52c41a",
                        "/models/controller.obj", "{\"status\":\"idle\"}",
                        null, null, null,
                        "CAN", "TEST/ACTIVATE/RESET"
                ),
                createDeviceEntry(
                        "DEV-015", "空调控制器M", "CONTROLLER", "AC-3000",
                        "230,210,240", "2F", "南侧办公室",
                        "正常", "#52c41a",
                        "/models/controller.obj", "{\"temp\":24,\"mode\":\"cool\"}",
                        null, null, null,
                        "Modbus", "SET_TEMP/SET_MODE/START/STOP"
                ),
                createDeviceEntry(
                        "DEV-016", "扬声器N", "BROADCASTER", "SPEAKER-500",
                        "320,220,270", "1F", "餐厅",
                        "故障", "#f5222d",
                        "/models/speaker.obj", "{\"volume\":0}",
                        "ERR-006", "音频输出异常", "2025-06-05 16:30:10",
                        "TCP", "PLAY/STOP/SET_VOLUME"
                ),
                createDeviceEntry(
                        "DEV-017", "摄像头O", "MONITOR", "CAM-200",
                        "200,140,320", "3F", "南侧走廊",
                        "正常", "#52c41a",
                        "/models/camera.obj", "{\"rotation\":90,\"zoom\":2.0}",
                        null, null, null,
                        "RTSP", "ROTATE/ZOOM/RECORD"
                ),
                createDeviceEntry(
                        "DEV-018", "压力传感器P", "SENSOR", "PRESS-150",
                        "140,300,195", "1F", "西侧机房",
                        "正常", "#52c41a",
                        "/models/sensor.obj", "{\"pulse\":true}",
                        null, null, null,
                        "HTTP", "READ/RESET/CALIBRATE"
                ),
                createDeviceEntry(
                        "DEV-019", "紧急广播Q", "BROADCASTER", "EMG-1000",
                        "270,190,170", "2F", "大厅",
                        "正常", "#52c41a",
                        "/models/speaker.obj", "{\"volume\":100}",
                        null, null, null,
                        "TCP", "PLAY/STOP/SET_VOLUME"
                ),
                createDeviceEntry(
                        "DEV-020", "主备控制器R", "CONTROLLER", "MK-2000",
                        "110,210,160", "1F", "中央控制室",
                        "正常", "#52c41a",
                        "/models/controller.obj", "{\"speed\":0.8,\"rotation\":180}",
                        null, null, null,
                        "MQTT", "START/STOP/REBOOT"
                )
        );
    }

    private static Map<String, Object> createDeviceEntry(
            String deviceId, String deviceName, String deviceType, String model,
            String location, String floor, String area,
            String status, String statusColor,
            String modelPath, String animationParams,
            String alarmCode, String alarmDescription, String triggerTime,
            String controlProtocol, String commandSet
    ) {
        Map<String, Object> data = new HashMap<>();
        data.put("deviceId", deviceId); // 设备ID
        data.put("deviceName", deviceName); // 设备名称
        data.put("deviceType", deviceType); // 设备类型
        data.put("model", model); // 型号
        data.put("location", location); // 安装位置(X,Y,Z坐标)
        data.put("floor", floor); // 楼层
        data.put("area", area); // 区域
        data.put("status", status); // 运行状态(正常/警告/故障)
        data.put("statusColor", statusColor); // 状态颜色值
        data.put("modelPath", modelPath); // 模型文件路径
        data.put("animationParams", animationParams); // 动画参数
        data.put("alarmCode", alarmCode); // 当前告警代码
        data.put("alarmDescription", alarmDescription); // 告警描述
        data.put("triggerTime", triggerTime); // 触发时间
        data.put("controlProtocol", controlProtocol); // 设备控制协议
        data.put("commandSet", commandSet); // 指令集
        return data;
    }




    public static List<Map<String, Object>> generateConfigurationData() {
        return Arrays.asList(
                // 主控制室组态图
                createConfigEntry(
                        "CFG-001", "/configs/main_control_room.dwg", "V1.2",
                        Arrays.asList(
                                createDeviceBinding("DEV-001", 100, 200),
                                createDeviceBinding("DEV-002", 150, 180)
                        ),
                        Arrays.asList(
                                createMonitorParam("温度", 23.5, "℃"),
                                createMonitorParam("压力", 1.2, "MPa")
                        ),
                        "{\"温度\": {\"low\":\"#ffd700\", \"high\":\"#ff4500\"}, \"压力\": {\"low\":\"#90ee90\", \"high\":\"#ff6347\"}",
                        "{\"温度\": {\"blink\": true, \"threshold\": 30}, \"压力\": {\"blink\": false, \"threshold\": 1.5}}",
                        "NUMERIC",
                        "SCENE-001",
                        "{\"x\": 50, \"y\": 30, \"zoom\": 1.2}"
                ),
                // 空调系统组态图
                createConfigEntry(
                        "CFG-002", "/configs/air_conditioning.dwg", "V2.0",
                        Arrays.asList(
                                createDeviceBinding("DEV-015", 80, 160),
                                createDeviceBinding("DEV-016", 220, 90)
                        ),
                        Arrays.asList(
                                createMonitorParam("电流", 5.8, "A"),
                                createMonitorParam("风速", 4.2, "m/s")
                        ),
                        "{\"电流\": {\"low\":\"#add8e6\", \"high\":\"#ff0000\"}, \"风速\": {\"low\":\"#f0e68c\", \"high\":\"#483d8b\"}}",
                        "{\"电流\": {\"blink\": true, \"threshold\": 6.0}, \"风速\": {\"blink\": true, \"threshold\": 5.0}}",
                        "PERCENTAGE",
                        "SCENE-002",
                        "{\"x\": 80, \"y\": 60, \"rotation\": 90}"
                ),
                // 消防系统组态图
                createConfigEntry(
                        "CFG-003", "/configs/fire_system.dwg", "V1.1",
                        Arrays.asList(
                                createDeviceBinding("DEV-006", 120, 250),
                                createDeviceBinding("DEV-014", 280, 110)
                        ),
                        Arrays.asList(
                                createMonitorParam("烟雾浓度", 0.3, "ppm"),
                                createMonitorParam("水压", 0.8, "MPa")
                        ),
                        "{\"烟雾浓度\": {\"low\":\"#ffffff\", \"high\":\"#ff0000\"}, \"水压\": {\"low\":\"#40e0d0\", \"high\":\"#ffd700\"}}",
                        "{\"烟雾浓度\": {\"blink\": true, \"threshold\": 0.5}, \"水压\": {\"blink\": false, \"threshold\": 0.6}}",
                        "DECIMAL",
                        "SCENE-003",
                        "{\"x\": 150, \"y\": 180, \"zoom\": 1.5}"
                ),
                // 新增7条模拟数据
                createConfigEntry(
                        "CFG-004", "/configs/water_system.dwg", "V1.3",
                        Arrays.asList(createDeviceBinding("DEV-008", 90, 190)),
                        Arrays.asList(createMonitorParam("流量", 30.2, "m³/h")),
                        "{\"流量\": {\"low\":\"#87ceeb\", \"high\":\"#ff69b4\"}}",
                        "{\"流量\": {\"blink\": true, \"threshold\": 35.0}}",
                        "NUMERIC",
                        "SCENE-004",
                        "{\"x\": 70, \"y\": 40, \"zoom\": 1.0}"
                ),
                createConfigEntry(
                        "CFG-005", "/configs/elevator_system.dwg", "V2.1",
                        Arrays.asList(createDeviceBinding("DEV-003", 170, 130), createDeviceBinding("DEV-009", 240, 150)),
                        Arrays.asList(createMonitorParam("电压", 220, "V"), createMonitorParam("负载率", 65, "%")),
                        "{\"电压\": {\"low\":\"#9370db\", \"high\":\"#ff8c00\"}, \"负载率\": {\"low\":\"#98fb98\", \"high\":\"#ff4500\"}}",
                        "{\"电压\": {\"blink\": false, \"threshold\": 240}, \"负载率\": {\"blink\": true, \"threshold\": 80}}",
                        "PERCENTAGE",
                        "SCENE-005",
                        "{\"x\": 120, \"y\": 90, \"rotation\": 0}"
                ),
                createConfigEntry(
                        "CFG-006", "/configs/lighting_system.dwg", "V1.0",
                        Arrays.asList(createDeviceBinding("DEV-004", 210, 230), createDeviceBinding("DEV-010", 300, 170)),
                        Arrays.asList(createMonitorParam("照度", 500, "lux"), createMonitorParam("开关状态", 1, "布尔")),
                        "{\"照度\": {\"low\":\"#f5f5dc\", \"high\":\"#ffff00\"}, \"开关状态\": {\"low\":\"#d3d3d3\", \"high\":\"#00ff00\"}}",
                        "{\"照度\": {\"blink\": true, \"threshold\": 600}, \"开关状态\": {\"blink\": false, \"threshold\": 0}}",
                        "NUMERIC",
                        "SCENE-001",
                        "{\"x\": 180, \"y\": 110, \"zoom\": 0.8}"
                ),
                createConfigEntry(
                        "CFG-007", "/configs/power_system.dwg", "V1.5",
                        Arrays.asList(createDeviceBinding("DEV-005", 140, 280), createDeviceBinding("DEV-011", 260, 200)),
                        Arrays.asList(createMonitorParam("频率", 50, "Hz"), createMonitorParam("功率因数", 0.92, "-")),
                        "{\"频率\": {\"low\":\"#4682b4\", \"high\":\"#ff00ff\"}, \"功率因数\": {\"low\":\"#f08080\", \"high\":\"#2e8b57\"}}",
                        "{\"频率\": {\"blink\": false, \"threshold\": 51}, \"功率因数\": {\"blink\": true, \"threshold\": 0.95}}",
                        "DECIMAL",
                        "SCENE-003",
                        "{\"x\": 200, \"y\": 160, \"zoom\": 1.3}"
                ),
                createConfigEntry(
                        "CFG-008", "/configs/factory_area.dwg", "V3.0",
                        Arrays.asList(createDeviceBinding("DEV-012", 110, 300), createDeviceBinding("DEV-018", 190, 220)),
                        Arrays.asList(createMonitorParam("湿度", 55, "%"), createMonitorParam("气压", 101.3, "kPa")),
                        "{\"湿度\": {\"low\":\"#8470ff\", \"high\":\"#ffd700\"}, \"气压\": {\"low\":\"#add8e6\", \"high\":\"#ff6347\"}}",
                        "{\"湿度\": {\"blink\": true, \"threshold\": 60}, \"气压\": {\"blink\": false, \"threshold\": 100.0}}",
                        "PERCENTAGE",
                        "SCENE-006",
                        "{\"x\": 60, \"y\": 70, \"rotation\": 45}"
                ),
                createConfigEntry(
                        "CFG-009", "/configs/laboratory.dwg", "V1.4",
                        Arrays.asList(createDeviceBinding("DEV-013", 230, 140), createDeviceBinding("DEV-017", 290, 270)),
                        Arrays.asList(createMonitorParam("PH值", 7.2, "-"), createMonitorParam("浊度", 5.0, "NTU")),
                        "{\"PH值\": {\"low\":\"#ff0000\", \"high\":\"#0000ff\"}, \"浊度\": {\"low\":\"#f5f5f5\", \"high\":\"#a9a9a9\"}}",
                        "{\"PH值\": {\"blink\": true, \"threshold\": 7.5}, \"浊度\": {\"blink\": true, \"threshold\": 8.0}}",
                        "DECIMAL",
                        "SCENE-002",
                        "{\"x\": 130, \"y\": 80, \"zoom\": 1.1}"
                ),
                createConfigEntry(
                        "CFG-010", "/configs/warehouse.dwg", "V1.1",
                        Arrays.asList(createDeviceBinding("DEV-019", 160, 120), createDeviceBinding("DEV-020", 250, 180)),
                        Arrays.asList(createMonitorParam("库存量", 850, "件"), createMonitorParam("出入库速率", 30, "件/h")),
                        "{\"库存量\": {\"low\":\"#ff69b4\", \"high\":\"#00ff7f\"}, \"出入库速率\": {\"low\":\"#8b4513\", \"high\":\"#40e0d0\"}}",
                        "{\"库存量\": {\"blink\": false, \"threshold\": 500}, \"出入库速率\": {\"blink\": true, \"threshold\": 50}}",
                        "NUMERIC",
                        "SCENE-004",
                        "{\"x\": 90, \"y\": 50, \"zoom\": 0.9}"
                ),
                createConfigEntry(
                        "CFG-010", "/configs/warehouse.dwg", "V1.1",
                        Arrays.asList(createDeviceBinding("DEV-019", 160, 120), createDeviceBinding("DEV-020", 250, 180)),
                        Arrays.asList(createMonitorParam("库存量", 850, "件"), createMonitorParam("出入库速率", 30, "件/h")),
                        "{\"库存量\": {\"low\":\"#ff69b4\", \"high\":\"#00ff7f\"}, \"出入库速率\": {\"low\":\"#8b4513\", \"high\":\"#40e0d0\"}}",
                        "{\"库存量\": {\"blink\": false, \"threshold\": 500}, \"出入库速率\": {\"blink\": true, \"threshold\": 50}}",
                        "NUMERIC",
                        "SCENE-004",
                        "{\"x\": 90, \"y\": 50, \"zoom\": 0.9}"
                ),
                createConfigEntry(
                        "CFG-010", "/configs/warehouse.dwg", "V1.1",
                        Arrays.asList(createDeviceBinding("DEV-019", 160, 120), createDeviceBinding("DEV-020", 250, 180)),
                        Arrays.asList(createMonitorParam("库存量", 850, "件"), createMonitorParam("出入库速率", 30, "件/h")),
                        "{\"库存量\": {\"low\":\"#ff69b4\", \"high\":\"#00ff7f\"}, \"出入库速率\": {\"low\":\"#8b4513\", \"high\":\"#40e0d0\"}}",
                        "{\"库存量\": {\"blink\": false, \"threshold\": 500}, \"出入库速率\": {\"blink\": true, \"threshold\": 50}}",
                        "NUMERIC",
                        "SCENE-004",
                        "{\"x\": 90, \"y\": 50, \"zoom\": 0.9}"
                )
        );
    }

    private static Map<String, Object> createConfigEntry(
            String configId, String drawingPath, String version,
            List<Map<String, Object>> deviceBindings,
            List<Map<String, Object>> monitorParams,
            String colorThresholds,
            String blinkRules,
            String displayFormat,
            String associatedSceneId,
            String hotspotParams
    ) {
        Map<String, Object> data = new HashMap<>();
        data.put("configId", configId); // 组态图ID
        data.put("drawingPath", drawingPath); // 图纸路径
        data.put("version", version); // 版本号
        data.put("deviceBindings", deviceBindings); // 设备绑定信息
        data.put("monitorParams", monitorParams); // 监控参数
        data.put("colorThresholds", colorThresholds); // 颜色阈值
        data.put("blinkRules", blinkRules); // 闪烁规则
        data.put("displayFormat", displayFormat); // 数值显示格式
        data.put("associatedSceneId", associatedSceneId); // 关联的三维场景ID
        data.put("hotspotParams", hotspotParams); // 热点跳转参数
        return data;
    }

    private static Map<String, Object> createDeviceBinding(String deviceId, int x, int y) {
        Map<String, Object> binding = new HashMap<>();
        binding.put("deviceId", deviceId);
        binding.put("x", x);
        binding.put("y", y);
        return binding;
    }

    private static Map<String, Object> createMonitorParam(String name, double value, String unit) {
        Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        param.put("value", value);
        param.put("unit", unit);
        return param;
    }

    public static List<Map<String, Object>> generateAreaData() {
        return Arrays.asList(
                // 一级区域：园区
                createAreaEntry(
                        "AREA-001", "智慧园区", null, 1,
                        Arrays.asList(
                                createDeviceStat("CONTROLLER", 5, 90.0, 2.0),
                                createDeviceStat("SENSOR", 20, 95.0, 1.0),
                                createDeviceStat("ACTUATOR", 8, 87.5, 5.0)
                        ),
                        "{\"lat\":30.123,\"lng\":120.456,\"heatData\":[[100,200,0.8],[150,180,0.6]]}",
                        "0.85,1200,92",
                        "CONTROLLER,SENSOR",
                        "在线,故障"
                ),
                createAreaEntry(
                        "AREA-001", "智慧园区", null, 1,
                        Arrays.asList(
                                createDeviceStat("CONTROLLER", 5, 90.0, 2.0),
                                createDeviceStat("SENSOR", 20, 95.0, 1.0),
                                createDeviceStat("ACTUATOR", 8, 87.5, 5.0)
                        ),
                        "{\"lat\":30.123,\"lng\":120.456,\"heatData\":[[100,200,0.8],[150,180,0.6]]}",
                        "0.85,1200,92",
                        "CONTROLLER,SENSOR",
                        "在线,故障"
                ),
                createAreaEntry(
                        "AREA-001", "智慧园区", null, 1,
                        Arrays.asList(
                                createDeviceStat("CONTROLLER", 5, 90.0, 2.0),
                                createDeviceStat("SENSOR", 20, 95.0, 1.0),
                                createDeviceStat("ACTUATOR", 8, 87.5, 5.0)
                        ),
                        "{\"lat\":30.123,\"lng\":120.456,\"heatData\":[[100,200,0.8],[150,180,0.6]]}",
                        "0.85,1200,92",
                        "CONTROLLER,SENSOR",
                        "在线,故障"
                ),
                // 二级区域：1号大楼
                createAreaEntry(
                        "AREA-002", "1号大楼", "AREA-001", 2,
                        Arrays.asList(
                                createDeviceStat("CONTROLLER", 2, 100.0, 0.0),
                                createDeviceStat("SENSOR", 8, 98.0, 0.0),
                                createDeviceStat("BROADCASTER", 3, 90.0, 0.0)
                        ),
                        "{\"lat\":30.124,\"lng\":120.457,\"heatData\":[[80,160,0.9],[220,90,0.7]]}",
                        "0.78,800,95",
                        "SENSOR,BROADCASTER",
                        "在线"
                ),createAreaEntry(
                        "AREA-002", "1号大楼", "AREA-001", 2,
                        Arrays.asList(
                                createDeviceStat("CONTROLLER", 2, 100.0, 0.0),
                                createDeviceStat("SENSOR", 8, 98.0, 0.0),
                                createDeviceStat("BROADCASTER", 3, 90.0, 0.0)
                        ),
                        "{\"lat\":30.124,\"lng\":120.457,\"heatData\":[[80,160,0.9],[220,90,0.7]]}",
                        "0.78,800,95",
                        "SENSOR,BROADCASTER",
                        "在线"
                ),
                // 二级区域：2号大楼
                createAreaEntry(
                        "AREA-003", "2号大楼", "AREA-001", 2,
                        Arrays.asList(
                                createDeviceStat("ACTUATOR", 5, 80.0, 10.0),
                                createDeviceStat("MONITOR", 6, 92.0, 3.0),
                                createDeviceStat("ALARM", 4, 95.0, 0.0)
                        ),
                        "{\"lat\":30.125,\"lng\":120.458,\"heatData\":[[120,250,0.7],[280,110,0.5]]}",
                        "0.91,1500,88",
                        "ACTUATOR,MONITOR",
                        "在线,故障"
                ),
                // 三级区域：1楼大厅（AREA-002子区域）
                createAreaEntry(
                        "AREA-004", "1楼大厅", "AREA-002", 3,
                        Arrays.asList(
                                createDeviceStat("SENSOR", 3, 100.0, 0.0),
                                createDeviceStat("BROADCASTER", 2, 100.0, 0.0)
                        ),
                        "{\"lat\":30.1245,\"lng\":120.4572,\"heatData\":[[210,230,0.95],[300,170,0.9]]}",
                        "0.88,300,98",
                        "SENSOR",
                        "在线"
                ),
                // 三级区域：2楼机房（AREA-003子区域）
                createAreaEntry(
                        "AREA-005", "2楼机房", "AREA-003", 3,
                        Arrays.asList(
                                createDeviceStat("ACTUATOR", 3, 75.0, 15.0),
                                createDeviceStat("MONITOR", 4, 90.0, 5.0)
                        ),
                        "{\"lat\":30.1255,\"lng\":120.4583,\"heatData\":[[170,130,0.6],[240,150,0.8]]}",
                        "0.95,2000,85",
                        "ACTUATOR",
                        "故障"
                ),
                // 新增5个区域数据
                createAreaEntry(
                        "AREA-006", "3号大楼", "AREA-001", 2,
                        Arrays.asList(
                                createDeviceStat("INPUT", 2, 100.0, 0.0),
                                createDeviceStat("ALARM", 5, 96.0, 0.0)
                        ),
                        "{\"lat\":30.126,\"lng\":120.459,\"heatData\":[[110,300,0.8],[190,220,0.7]]}",
                        "0.82,600,94",
                        "INPUT,ALARM",
                        "在线"
                ),
                createAreaEntry(
                        "AREA-007", "地下车库", "AREA-001", 2,
                        Arrays.asList(
                                createDeviceStat("SENSOR", 10, 90.0, 2.0),
                                createDeviceStat("ACTUATOR", 4, 85.0, 5.0)
                        ),
                        "{\"lat\":30.122,\"lng\":120.455,\"heatData\":[[90,190,0.7],[140,280,0.6]]}",
                        "0.75,1000,90",
                        "SENSOR,ACTUATOR",
                        "在线,故障"
                ),
                createAreaEntry(
                        "AREA-008", "实验室", "AREA-003", 3,
                        Arrays.asList(
                                createDeviceStat("MONITOR", 3, 95.0, 0.0),
                                createDeviceStat("ALARM", 2, 100.0, 0.0)
                        ),
                        "{\"lat\":30.1258,\"lng\":120.4588,\"heatData\":[[230,140,0.9],[290,270,0.8]]}",
                        "0.90,1800,93",
                        "MONITOR",
                        "在线"
                ),
                createAreaEntry(
                        "AREA-009", "会议室", "AREA-002", 3,
                        Arrays.asList(
                                createDeviceStat("BROADCASTER", 2, 100.0, 0.0),
                                createDeviceStat("SENSOR", 1, 100.0, 0.0)
                        ),
                        "{\"lat\":30.1242,\"lng\":120.4575,\"heatData\":[[310,210,0.98],[320,220,0.95]]}",
                        "0.85,200,99",
                        "BROADCASTER",
                        "在线"
                ),
                createAreaEntry(
                        "AREA-0010", "天台", "AREA-003", 3,
                        Arrays.asList(
                                createDeviceStat("ACTUATOR", 1, 100.0, 0.0),
                                createDeviceStat("SENSOR", 1, 100.0, 0.0)
                        ),
                        "{\"lat\":30.1259,\"lng\":120.4589,\"heatData\":[[160,120,1.0],[250,180,0.9]]}",
                        "0.99,50,100",
                        "ACTUATOR,SENSOR",
                        "在线"
                )
        );
    }

    private static Map<String, Object> createAreaEntry(
            String areaId, String areaName, String parentAreaId, int level,
            List<Map<String, Object>> deviceStats,
            String heatmapData,
            String keyMetrics,
            String deviceFilters,
            String statusFilters
    ) {
        Map<String, Object> data = new HashMap<>();
        data.put("areaId", areaId); // 区域ID
        data.put("areaName", areaName); // 区域名称
        data.put("parentAreaId", parentAreaId); // 父区域ID
        data.put("level", level); // 层级
        data.put("deviceStats", deviceStats); // 设备统计
        data.put("heatmapData", heatmapData); // 位置热力图数据
        data.put("keyMetrics", keyMetrics); // 关键指标（平均能耗,最大负载,健康指数）
        data.put("deviceFilters", deviceFilters); // 设备类型过滤器
        data.put("statusFilters", statusFilters); // 状态过滤器
        return data;
    }

    private static Map<String, Object> createDeviceStat(
            String deviceType, double count, double onlineRate, double faultRate
    ) {
        Map<String, Object> stat = new HashMap<>();
        stat.put("deviceType", deviceType);
        stat.put("count", count);
        stat.put("onlineRate", onlineRate);
        stat.put("faultRate", faultRate);
        return stat;
    }


    public static List<Map<String, Object>> generateControlCommands() {
        return Arrays.asList(
                // 基础指令
                createCommandEntry(
                        "CMD-001", Arrays.asList("DEV-001", "DEV-002"), "SET_TEMPERATURE", "{\"targetTemp\":24}",
                        "SUCCESS", "2025-06-03 10:05:23", "陈俊杰", "192.168.1.101",
                        "调整主控制室温度", "ON", 500, "NONE",
                        "每天08:00自动执行", "办公模式", "与消防系统联动"
                ),
                createCommandEntry(
                        "CMD-002", Arrays.asList("DEV-015"), "SET_SPEED", "{\"speedLevel\":3}",
                        "PENDING", "2025-06-03 10:12:45", "林思彤", "192.168.1.102",
                        "设置空调风速", "WAITING", 0, "NONE",
                        "每周一09:00", "节能模式", "无"
                ),
                createCommandEntry(
                        "CMD-003", Arrays.asList("DEV-006", "DEV-014"), "TRIGGER_ALARM", "{}",
                        "FAILED", "2025-06-03 10:20:18", "陈俊杰", "192.168.1.101",
                        "测试消防报警", "ERROR", 800, "ALARM_MODULE_FAILURE",
                        "火灾检测触发", "紧急模式", "切断非消防电源"
                ),
                createCommandEntry(
                        "CMD-004", Arrays.asList("DEV-008"), "START_PUMP", "{}",
                        "SUCCESS", "2025-06-03 11:00:00", "王伟东", "192.168.1.103",
                        "启动水泵", "OK", 300, "NONE",
                        "水位低于阈值时", "供水模式", "联动水位传感器"
                ),
                createCommandEntry(
                        "CMD-005", Arrays.asList("DEV-003", "DEV-009"), "ADJUST_VOLTAGE", "{\"voltage\":220}",
                        "PENDING", "2025-06-03 13:15:30", "林思彤", "192.168.1.102",
                        "调整电梯电压", "IDLE", 0, "NONE",
                        "每月15日维护", "检修模式", "无"
                ),
                // 新增指令（6-10）
                createCommandEntry(
                        "CMD-006", Arrays.asList("DEV-004"), "TURN_ON_LIGHT", "{}",
                        "SUCCESS", "2025-06-03 14:45:12", "黄雅琪", "192.168.1.104",
                        "打开照明系统", "COMPLETED", 200, "NONE",
                        "日落自动开启", "照明模式", "联动光照传感器"
                ),
                createCommandEntry(
                        "CMD-007", Arrays.asList("DEV-005"), "STOP_GENERATOR", "{}",
                        "FAILED", "2025-06-03 15:23:47", "陈俊杰", "192.168.1.101",
                        "停止备用发电机", "TIMEOUT", 1200, "COMMUNICATION_ERROR",
                        "市电恢复时", "备用模式", "联动电力监测"
                ),
                createCommandEntry(
                        "CMD-008", Arrays.asList("DEV-012", "DEV-018"), "SET_HUMIDITY", "{\"humidity\":55}",
                        "SUCCESS", "2025-06-03 16:08:59", "王伟东", "192.168.1.103",
                        "调节工厂湿度", "DONE", 450, "NONE",
                        "每小时自动调节", "生产模式", "无"
                ),
                createCommandEntry(
                        "CMD-009", Arrays.asList("DEV-013"), "CALIBRATE_PH", "{\"offset\":-0.1}",
                        "PROCESSING", "2025-06-03 17:30:00", "黄雅琪", "192.168.1.104",
                        "校准实验室PH值", "CALIBRATING", 600, "NONE",
                        "每周三17:00", "校准模式", "联动水质监测"
                ),
                createCommandEntry(
                        "CMD-010", Arrays.asList("DEV-019", "DEV-020"), "RESET_DEVICE", "{}",
                        "SUCCESS", "2025-06-03 18:00:00", "赵宇航", "192.168.1.105",
                        "重置仓库设备", "RESET_OK", 350, "NONE",
                        "设备异常时自动", "重置模式", "联动设备状态检测"
                ),
                // 新增指令（11-15）
                createCommandEntry(
                        "CMD-011", Arrays.asList("DEV-021"), "UPDATE_FIRMWARE", "{\"version\":\"v2.3.1\"}",
                        "SUCCESS", "2025-06-03 09:30:15", "周文静", "192.168.1.106",
                        "升级传感器固件", "UPDATED", 1500, "NONE",
                        "每月1日自动升级", "维护模式", "无"
                ),
                createCommandEntry(
                        "CMD-012", Arrays.asList("DEV-022", "DEV-023"), "OPEN_VALVE", "{\"degree\":75}",
                        "FAILED", "2025-06-03 12:45:32", "王伟东", "192.168.1.103",
                        "打开排水阀", "VALVE_ERROR", 900, "MECHANICAL_FAILURE",
                        "水位超过阈值时", "防洪模式", "联动水位传感器"
                ),
                createCommandEntry(
                        "CMD-013", Arrays.asList("DEV-024"), "SET_FREQUENCY", "{\"hz\":50}",
                        "PENDING", "2025-06-03 14:20:10", "林思彤", "192.168.1.102",
                        "设置电机频率", "WAITING_CONFIRM", 0, "NONE",
                        "根据负载自动调整", "智能模式", "联动功率监测"
                ),
                createCommandEntry(
                        "CMD-014", Arrays.asList("DEV-025"), "ENABLE_SECURITY", "{}",
                        "SUCCESS", "2025-06-03 17:15:45", "吴思远", "192.168.1.107",
                        "启用安防系统", "SECURED", 400, "NONE",
                        "下班后自动启用", "安防模式", "联动摄像头"
                ),
                createCommandEntry(
                        "CMD-015", Arrays.asList("DEV-026", "DEV-027"), "SWITCH_MODE", "{\"mode\":\"auto\"}",
                        "PROCESSING", "2025-06-03 18:30:20", "陈俊杰", "192.168.1.101",
                        "切换自动模式", "SWITCHING", 700, "NONE",
                        "日出/日落自动切换", "智能模式", "联动光照传感器"
                )
        );
    }

    private static Map<String, Object> createCommandEntry(
            String cmdId, List<String> targetDevices, String cmdType, String params,
            String status, String timestamp, String operatorId, String ipAddress,
            String operationDetail, String feedbackStatus, int executionTime, String errorCode,
            String scheduleTask, String sceneMode, String linkageRule
    ) {
        Map<String, Object> data = new HashMap<>();
        data.put("cmdId", cmdId);
        data.put("targetDevices", targetDevices);
        data.put("cmdType", cmdType);
        data.put("params", params);
        data.put("status", status);
        data.put("timestamp", timestamp);
        data.put("operatorId", operatorId);
        data.put("ipAddress", ipAddress);
        data.put("operationDetail", operationDetail);
        data.put("feedbackStatus", feedbackStatus);
        data.put("executionTime", executionTime);
        data.put("errorCode", errorCode);
        data.put("scheduleTask", scheduleTask);
        data.put("sceneMode", sceneMode);
        data.put("linkageRule", linkageRule);
        return data;
    }



    @GetMapping("/generateDeviceConfigurationData")
    public Map<String, Object> getGenerateDeviceConfigurationData() throws Exception {
        List<Map<String, Object>> data = generateConfigurationData();
        PageData pd = this.getPageData();
        String deviceId = pd.getString("deviceId");
        String version = pd.getString("version");
        String configId = pd.getString("configId");
        String displayFormat = pd.getString("displayFormat");
        // 条件过滤    configId: '',
        //  version: '',
        if (deviceId != null && !deviceId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("deviceId").toString().contains(deviceId))
                    .collect(Collectors.toList());
        }
        if (version != null && !version.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("version").toString().contains(version))
                    .collect(Collectors.toList());
        }
        if (configId != null && !configId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("configId").toString().contains(configId))
                    .collect(Collectors.toList());
        }
        if (displayFormat != null && !displayFormat.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("displayFormat").toString().contains(displayFormat))
                    .collect(Collectors.toList());
        }

        // 分页逻辑
        int total = data.size();
        int fromIndex = (pd.getInteger("pageNum") - 1) * pd.getInteger("pageSize");
        int toIndex = Math.min(fromIndex + pd.getInteger("pageSize"), total);
        List<Map<String, Object>> pageData = data.subList(fromIndex, toIndex);

        // 返回结果
        Map<String, Object> response = Map.of(
                "msg", "操作成功",
                "code", 200,
                "data", Map.of("list", pageData,"total", total)
        );
        return response;
    }
    @GetMapping("/generateDeviceData")
    public Map<String, Object> getGenerateDeviceData() throws Exception {
        List<Map<String, Object>> data = generateDeviceData();
        PageData pd = this.getPageData();
        String deviceName = pd.getString("deviceName");
        String deviceType = pd.getString("deviceType");
        String floor = pd.getString("floor");
        String area = pd.getString("area");
        String status = pd.getString("status");
        // 条件过滤
        if (deviceName != null && !deviceName.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("deviceName").toString().contains(deviceName))
                    .collect(Collectors.toList());
        }
        if (deviceType != null && !deviceType.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("deviceType").toString().contains(deviceType))
                    .collect(Collectors.toList());
        }
        if (floor != null && !floor.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("floor").toString().contains(floor))
                    .collect(Collectors.toList());
        }
        if (area != null && !area.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("area").toString().contains(area))
                    .collect(Collectors.toList());
        }
        if (status != null && !status.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("status").toString().contains(status))
                    .collect(Collectors.toList());
        }

        // 分页逻辑
        int total = data.size();
        int fromIndex = (pd.getInteger("pageNum") - 1) * pd.getInteger("pageSize");
        int toIndex = Math.min(fromIndex + pd.getInteger("pageSize"), total);
        List<Map<String, Object>> pageData = data.subList(fromIndex, toIndex);

        // 返回结果
        Map<String, Object> response = Map.of(
                "msg", "操作成功",
                "code", 200,
                "data", Map.of("list", pageData,"total", total)
        );
        return response;
    }

    @GetMapping("/generateAreaData")
    public Map<String, Object> getGenerateAreaData() throws Exception {
        List<Map<String, Object>> data = generateAreaData();
        PageData pd = this.getPageData();

        // 过滤条件
        String areaName = pd.getString("areaName");
        String level = pd.getString("level");
        String deviceType = pd.getString("deviceType");
        String status = pd.getString("status");

        // 应用过滤
        if (areaName != null && !areaName.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("areaName").toString().contains(areaName))
                    .collect(Collectors.toList());
        }
        if (level != null && !level.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("level").toString().equals(level))
                    .collect(Collectors.toList());
        }
        if (status != null && !status.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("status").toString().equals(status))
                    .collect(Collectors.toList());
        }

        // 根据设备类型和状态过滤
        if (deviceType != null && !deviceType.isEmpty()) {
            data = data.stream()
                    .filter(area -> {
                        List<Map<String, Object>> deviceStats = (List<Map<String, Object>>) area.get("deviceStats");
                        return deviceStats.stream().anyMatch(stat -> stat.get("deviceType").equals(deviceType));
                    })
                    .collect(Collectors.toList());
        }

        // 分页逻辑
        int total = data.size();
        int fromIndex = (pd.getInteger("pageNum") - 1) * pd.getInteger("pageSize");
        int toIndex = Math.min(fromIndex + pd.getInteger("pageSize"), total);
        List<Map<String, Object>> pageData = data.subList(fromIndex, toIndex);

        return Map.of(
                "msg", "操作成功",
                "code", 200,
                "data", Map.of("list", pageData, "total", total)
        );
    }
    @GetMapping("/getAreaStats")
    public Map<String, Object> getAreaStats() throws Exception {
        List<Map<String, Object>> allAreas = generateAreaData();

        // 计算统计数据
        int totalAreas = allAreas.size();
        int totalDevices = 0;
        int onlineDevices = 0;
        double totalHealthIndex = 0;

        for (Map<String, Object> area : allAreas) {
            List<Map<String, Object>> deviceStats = (List<Map<String, Object>>) area.get("deviceStats");
            for (Map<String, Object> stat : deviceStats) {
                // 安全地获取count值，处理可能的类型问题
                Number countNum = (Number) stat.get("count");
                int count = countNum != null ? countNum.intValue() : 0;

                // 安全地获取onlineRate值
                Number onlineRateNum = (Number) stat.get("onlineRate");
                double onlineRate = onlineRateNum != null ? onlineRateNum.doubleValue() : 0.0;

                totalDevices += count;
                onlineDevices += (int) (count * onlineRate / 100);
            }

            String keyMetrics = (String) area.get("keyMetrics");
            if (keyMetrics != null) {
                String[] metrics = keyMetrics.split(",");
                if (metrics.length >= 3) {
                    try {
                        totalHealthIndex += Double.parseDouble(metrics[2].trim());
                    } catch (NumberFormatException e) {
                        // 忽略解析错误
                    }
                }
            }
        }

        double onlineRate = totalDevices > 0 ? (double) onlineDevices / totalDevices * 100 : 0;
        double avgHealthIndex = totalAreas > 0 ? totalHealthIndex / totalAreas : 0;

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalAreas", totalAreas);
        stats.put("totalDevices", totalDevices);
        stats.put("onlineDevices", onlineDevices);
        stats.put("onlineRate", Math.round(onlineRate * 10) / 10.0);
        stats.put("avgHealthIndex", Math.round(avgHealthIndex));

        return Map.of(
                "msg", "操作成功",
                "code", 200,
                "data", stats
        );
    }


    @GetMapping("/generateCommandsData")
    public Map<String, Object> getGenerateCommandsData() throws Exception {
        List<Map<String, Object>> data = generateControlCommands();
        PageData pd = this.getPageData();
        String cmdId = pd.getString("cmdId");
        String cmdType = pd.getString("cmdType");
        String operatorId = pd.getString("operatorId");
        String feedbackStatus = pd.getString("feedbackStatus");
        String status = pd.getString("status");
        String startTime = pd.getString("startTime");
        String endTime = pd.getString("endTime");
        data = filterByDateRange(data, startTime, endTime);
        // 条件过滤
        if (cmdId != null && !cmdId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("cmdId").toString().contains(cmdId))
                    .collect(Collectors.toList());
        }
        if (cmdType != null && !cmdType.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("cmdType").toString().contains(cmdType))
                    .collect(Collectors.toList());
        }
        if (operatorId != null && !operatorId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("operatorId").toString().contains(operatorId))
                    .collect(Collectors.toList());
        }
        if (feedbackStatus != null && !feedbackStatus.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("feedbackStatus").toString().contains(feedbackStatus))
                    .collect(Collectors.toList());
        }
        if (status != null && !status.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("status").toString().contains(status))
                    .collect(Collectors.toList());
        }

        // 分页逻辑
        int total = data.size();
        int fromIndex = (pd.getInteger("pageNum") - 1) * pd.getInteger("pageSize");
        int toIndex = Math.min(fromIndex + pd.getInteger("pageSize"), total);
        List<Map<String, Object>> pageData = data.subList(fromIndex, toIndex);

        // 返回结果
        Map<String, Object> response = Map.of(
                "msg", "操作成功",
                "code", 200,
                "data", Map.of("list", pageData,"total", total)
        );
        return response;
    }

    // 1. 获取指令统计数据
    @GetMapping("/getCommandStats")
    public Map<String, Object> getCommandStats() throws Exception {
        List<Map<String, Object>> allCommands = generateControlCommands();

        // 计算统计数据
        long todayTotal = allCommands.size(); // 实际应该过滤今天的数据
        long successCount = allCommands.stream()
                .filter(cmd -> "SUCCESS".equals(cmd.get("status")))
                .count();
        long failedCount = allCommands.stream()
                .filter(cmd -> "FAILED".equals(cmd.get("status")))
                .count();

        // 计算平均响应时间
        double avgResponseTime = allCommands.stream()
                .mapToInt(cmd -> (Integer) cmd.get("executionTime"))
                .average()
                .orElse(0.0);

        Map<String, Object> stats = new HashMap<>();
        stats.put("todayTotal", todayTotal);
        stats.put("successCount", successCount);
        stats.put("failedCount", failedCount);
        stats.put("avgResponseTime", Math.round(avgResponseTime));

        return Map.of(
                "msg", "操作成功",
                "code", 200,
                "data", stats
        );
    }

    // 2. 重试指令
    @PostMapping("/retryCommand/{cmdId}")
    public Map<String, Object> retryCommand(@PathVariable String cmdId) throws Exception {
        // 在实际应用中，这里应该：
        // 1. 查找指令
        // 2. 验证指令状态是否可以重试
        // 3. 创建新的重试任务
        // 4. 更新指令状态

        // 模拟重试逻辑
        List<Map<String, Object>> commands = generateControlCommands();
        Optional<Map<String, Object>> command = commands.stream()
                .filter(cmd -> cmdId.equals(cmd.get("cmdId")))
                .findFirst();

        if (command.isPresent() && "FAILED".equals(command.get().get("status"))) {
            // 模拟重试成功
            return Map.of(
                    "msg", "重试指令已发送",
                    "code", 200,
                    "data", Map.of("cmdId", cmdId, "newStatus", "RETRYING")
            );
        } else {
            return Map.of(
                    "msg", "指令不存在或状态不允许重试",
                    "code", 400,
                    "data", null
            );
        }
    }

    // 3. 取消指令
    @PostMapping("/cancelCommand/{cmdId}")
    public Map<String, Object> cancelCommand(@PathVariable String cmdId) throws Exception {
        // 模拟取消逻辑
        List<Map<String, Object>> commands = generateControlCommands();
        Optional<Map<String, Object>> command = commands.stream()
                .filter(cmd -> cmdId.equals(cmd.get("cmdId")))
                .findFirst();

        if (command.isPresent()) {
            String status = (String) command.get().get("status");
            if ("PENDING".equals(status) || "PROCESSING".equals(status)) {
                return Map.of(
                        "msg", "指令已取消",
                        "code", 200,
                        "data", Map.of("cmdId", cmdId, "newStatus", "CANCELED")
                );
            } else {
                return Map.of(
                        "msg", "只能取消待执行或执行中的指令",
                        "code", 400,
                        "data", null
                );
            }
        } else {
            return Map.of(
                    "msg", "指令不存在",
                    "code", 404,
                    "data", null
            );
        }
    }

    // 4. 导出指令数据
    @GetMapping("/exportCommands")
    public void exportCommands(HttpServletResponse response) throws Exception {
        PageData pd = this.getPageData();

        // 获取过滤后的数据
        List<Map<String, Object>> data = generateControlCommands();

        // 应用过滤条件（复用您现有的过滤逻辑）
        String cmdId = pd.getString("cmdId");
        String cmdType = pd.getString("cmdType");
        String operatorId = pd.getString("operatorId");
        String feedbackStatus = pd.getString("feedbackStatus");
        String status = pd.getString("status");

        if (cmdId != null && !cmdId.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("cmdId").toString().contains(cmdId))
                    .collect(Collectors.toList());
        }
        if (cmdType != null && !cmdType.isEmpty()) {
            data = data.stream()
                    .filter(item -> item.get("cmdType").toString().contains(cmdType))
                    .collect(Collectors.toList());
        }
        // ... 其他过滤条件

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("控制指令数据_" + System.currentTimeMillis(), "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        // 使用EasyExcel导出（如果您使用的是其他Excel库，请相应调整）
        try (OutputStream outputStream = response.getOutputStream()) {
            // 创建Excel数据
            List<List<String>> excelData = new ArrayList<>();

            // 添加表头
            excelData.add(Arrays.asList(
                    "指令ID", "目标设备", "指令类型", "状态", "操作员",
                    "执行时间", "执行耗时(ms)", "反馈状态", "错误代码"
            ));

            // 添加数据行
            for (Map<String, Object> cmd : data) {
                List<String> row = Arrays.asList(
                        cmd.get("cmdId").toString(),
                        cmd.get("targetDevices").toString(),
                        mapCmdTypeForExport((String) cmd.get("cmdType")),
                        mapStatusForExport((String) cmd.get("status")),
                        cmd.get("operatorId").toString(),
                        cmd.get("timestamp").toString(),
                        cmd.get("executionTime").toString(),
                        mapFeedbackStatusForExport((String) cmd.get("feedbackStatus")),
                        cmd.get("errorCode").toString()
                );
                excelData.add(row);
            }

            // 如果使用POI，这里是简单的实现示例
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("控制指令数据");

            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);

            // 写入数据
            for (int i = 0; i < excelData.size(); i++) {
                Row row = sheet.createRow(i);
                List<String> rowData = excelData.get(i);
                for (int j = 0; j < rowData.size(); j++) {
                    Cell cell = row.createCell(j);
                    cell.setCellValue(rowData.get(j));
                    if (i == 0) {
                        cell.setCellStyle(headerStyle);
                    }
                }
            }

            // 自动调整列宽
            for (int i = 0; i < excelData.get(0).size(); i++) {
                sheet.autoSizeColumn(i);
            }

            workbook.write(outputStream);
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println("{\"msg\":\"导出失败\",\"code\":500}");
        }
    }

    // 辅助方法：状态映射
    private String mapStatusForExport(String status) {
        Map<String, String> statusMap = Map.of(
                "PENDING", "待执行",
                "PROCESSING", "执行中",
                "SUCCESS", "成功",
                "FAILED", "失败",
                "RETRYING", "重试中",
                "CANCELED", "已取消"
        );
        return statusMap.getOrDefault(status, status);
    }

    // 辅助方法：指令类型映射
    private String mapCmdTypeForExport(String type) {
        Map<String, String> typeMap = Map.of(
                "SET_PARAM", "参数设置",
                "TRIGGER_ALARM", "报警触发",
                "START_STOP", "设备启停",
                "CALIBRATE", "校准操作",
                "RESET", "设备重置"
        );
        return typeMap.getOrDefault(type, type);
    }

    // 辅助方法：反馈状态映射
    private String mapFeedbackStatusForExport(String status) {
        Map<String, String> feedbackMap = Map.of(
                "OK", "正常响应",
                "TIMEOUT", "响应超时",
                "ERROR", "响应错误"
        );
        return feedbackMap.getOrDefault(status, status);
    }

    // 5. 添加时间范围过滤的辅助方法
    private List<Map<String, Object>> filterByDateRange(List<Map<String, Object>> data, String startTime, String endTime) {
        if (startTime == null || endTime == null || startTime.isEmpty() || endTime.isEmpty()) {
            return data;
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start = sdf.parse(startTime);
            Date end = sdf.parse(endTime);

            return data.stream()
                    .filter(cmd -> {
                        try {
                            Date cmdTime = sdf.parse((String) cmd.get("timestamp"));
                            return !cmdTime.before(start) && !cmdTime.after(end);
                        } catch (Exception e) {
                            return false;
                        }
                    })
                    .collect(Collectors.toList());
        } catch (Exception e) {
            return data;
        }
    }

}
