package com.fizz.business.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fizz.business.constants.enums.DeviceEnum;
import com.fizz.business.constants.enums.WsTypeEnum;
import com.fizz.business.domain.DeviceSnapshot;
import com.fizz.business.domain.msg.*;
import com.fizz.business.dto.DeviceChartDataDTO;
import com.fizz.business.dto.DeviceFieldTrendDTO;
import com.fizz.business.dto.DeviceHistoryTrendDTO;
import com.fizz.business.mapper.DeviceSnapshotMapper;
import com.fizz.business.utils.WebSocketUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 设备数据快照服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceSnapshotService {

    // 使用ConcurrentHashMap存储最新的测量数据
    private final Map<Class<?>, OpcMessage> latestMeasurements = new ConcurrentHashMap<>();
    private final DeviceSnapshotMapper deviceSnapshotMapper;
    private final ObjectMapper objectMapper;

    /**
     * 更新最新的测量数据
     * @param message 测量数据消息
     */
    public void updateLatestMeasurement(OpcMessage message) {
        if (message != null) {
            latestMeasurements.put(message.getClass(), message);
        }
    }

    /**
     * 创建当前所有设备的数据快照
     */
    @Transactional(rollbackFor = Exception.class)
    public void createDeviceSnapshots() {
        try {
            // 获取当前时间戳
            LocalDateTime now = LocalDateTime.now();

            // 获取最新的测量数据
            AppMeasureEntryMessage entry = (AppMeasureEntryMessage) latestMeasurements.get(AppMeasureEntryMessage.class);
            AppMeasureFurnaceMessage furnace = (AppMeasureFurnaceMessage) latestMeasurements.get(AppMeasureFurnaceMessage.class);
            AppMeasureCoatMessage coat = (AppMeasureCoatMessage) latestMeasurements.get(AppMeasureCoatMessage.class);
            AppMeasureExitMessage exit = (AppMeasureExitMessage) latestMeasurements.get(AppMeasureExitMessage.class);

            if (entry == null && furnace == null && coat == null && exit == null) {
                log.warn("没有可用的测量数据，跳过快照创建");
                return;
            }

            // 为每个设备创建快照
            List<DeviceSnapshot> snapshots = new ArrayList<>();
            for (DeviceEnum device : DeviceEnum.values()) {
                try {
                    DeviceSnapshot snapshot = createDeviceSnapshot(device, now, entry, furnace, coat, exit);
                    if (snapshot != null) {
                        snapshots.add(snapshot);
                    }
                } catch (Exception e) {
                    log.error("创建设备[{}]快照失败: {}", device.name(), e.getMessage(), e);
                }
            }

            // 批量保存快照
            if (!snapshots.isEmpty()) {
                for (DeviceSnapshot snapshot : snapshots) {
                    deviceSnapshotMapper.insert(snapshot);
                }
                log.info("成功创建{}个设备数据快照", snapshots.size());
                
                // 推送所有设备的历史趋势数据
                pushAllDevicesHistoryTrend();

                // 推送设备统计数据
                pushAllChartData();

                // 推送每个设备每个字段的趋势数据（供前端画“点位趋势小图”）
                pushAllDeviceFieldTrends();
            }
        } catch (Exception e) {
            log.error("创建设备数据快照失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 推送所有设备的历史趋势数据（今天一天的数据，10分钟间隔）
     */
    public void pushAllDevicesHistoryTrend() {
        try {
            for (DeviceEnum device : DeviceEnum.values()) {
                DeviceHistoryTrendDTO trendData = getDeviceHistoryTrend(device.name());
                if (trendData != null && trendData.getSeries() != null && !trendData.getSeries().isEmpty()) {
                    WebSocketUtil.sendHistoryTrendMessage(trendData);
                }
            }
        } catch (Exception e) {
            log.error("推送设备历史趋势数据失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 推送设备统计数据
     */
    public void pushAllChartData() {
        try {
            DeviceChartDataDTO chartData = buildAllChartData();
            if (chartData != null) {
                WebSocketUtil.sendChartDataMessage(chartData);
            }
        } catch (Exception e) {
            log.error("推送统计数据失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 推送每个设备每个字段的趋势数据（今天范围，10分钟间隔采样）
     */
    public void pushAllDeviceFieldTrends() {
        try {
            for (DeviceEnum device : DeviceEnum.values()) {
                List<String> fields = device.getParamFields();
                if (fields == null || fields.isEmpty()) continue;
                for (String field : fields) {
                    DeviceFieldTrendDTO dto = getDeviceFieldTrend(device.name(), field);
                    if (dto != null) {
                        WebSocketUtil.sendDeviceFieldTrendMessage(dto);
                    }
                }
            }
        } catch (Exception e) {
            log.error("推送设备字段趋势失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 获取 单设备-单字段 今日趋势与统计（10分钟采样）
     */
    public DeviceFieldTrendDTO getDeviceFieldTrend(String deviceCode, String fieldName) {
        try {
            DeviceEnum device = DeviceEnum.fromName(deviceCode);
            if (device == null) return null;

            // 今天范围
            LocalDate today = LocalDate.now();
            LocalDateTime startTime = today.atStartOfDay();
            LocalDateTime endTime = today.atTime(LocalTime.MAX);

            // 查询今天的快照
            LambdaQueryWrapper<DeviceSnapshot> qw = new LambdaQueryWrapper<DeviceSnapshot>()
                    .eq(DeviceSnapshot::getDeviceCode, deviceCode)
                    .between(DeviceSnapshot::getCreateTime, startTime, endTime)
                    .orderByAsc(DeviceSnapshot::getCreateTime);

            List<DeviceSnapshot> rows = deviceSnapshotMapper.selectList(qw);
            if (rows == null || rows.isEmpty()) return null;

            // 10分钟采样
            List<DeviceSnapshot> sampled = sampleDataByInterval(rows, 10);

            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
            List<String> categories = new ArrayList<>(sampled.size());
            List<Double> data = new ArrayList<>(sampled.size());

            for (DeviceSnapshot s : sampled) {
                categories.add(s.getCreateTime().format(timeFormatter));
                double v = 0.0;
                try {
                    Map<String, Object> json = objectMapper.readValue(s.getSnapshotData(), Map.class);
                    Object raw = json.get(fieldName);
                    if (raw instanceof Number) v = ((Number) raw).doubleValue();
                } catch (Exception ignore) {
                }
                data.add(v);
            }

            // 统计（忽略全0）
            List<Double> valid = new ArrayList<>();
            for (Double v : data) {
                if (v != null && v != 0.0) valid.add(v);
            }

            Double avg = null, max = null, min = null;
            if (!valid.isEmpty()) {
                double sum = 0;
                max = valid.get(0);
                min = valid.get(0);
                for (Double v : valid) {
                    sum += v;
                    if (v > max) max = v;
                    if (v < min) min = v;
                }
                avg = sum / valid.size();
            }

            Double last = data.isEmpty() ? null : data.get(data.size() - 1);

            return DeviceFieldTrendDTO.builder()
                    .deviceCode(deviceCode)
                    .deviceName(device.getDesc())
                    .fieldName(fieldName)
                    // label/unit 目前后端没有统一来源，这里先留空，前端可用 fieldMeta 补齐
                    .fieldLabel(null)
                    .unit(null)
                    .categories(categories)
                    .data(data)
                    .avg(avg)
                    .max(max)
                    .min(min)
                    .last(last)
                    .build();

        } catch (Exception e) {
            log.error("获取设备字段趋势失败, deviceCode={}, fieldName={}, err={}", deviceCode, fieldName, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 构建设备图表数据
     */
    private DeviceChartDataDTO buildAllChartData() {
        try {
            // 1. 设备类型分布饼图
            DeviceChartDataDTO.PieChartData pieChartData = buildDeviceTypePieChart();

            // 2. 数据来源分布条形图
            DeviceChartDataDTO.BarChartData barChartData = buildSourceTypeBarChart();

            // 3. 同类型设备对比折线图（只对比单位相同的设备）
            DeviceChartDataDTO.LineChartData lineChartData = buildSameTypeDeviceCompareChart();

            // 4. 设备统计数据
            List<DeviceChartDataDTO.DeviceStatistics> statistics = buildDeviceStatistics();

            return DeviceChartDataDTO.builder()
                    .deviceTypePieChart(pieChartData)
                    .sourceTypeBarChart(barChartData)
                    .sameTypeDeviceCompareChart(lineChartData)
                    .deviceStatistics(statistics)
                    .build();
        } catch (Exception e) {
            log.error("构建图表数据失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 构建设备类型分布饼图数据
     */
    private DeviceChartDataDTO.PieChartData buildDeviceTypePieChart() {
        Map<String, Integer> distribution = new HashMap<>();
        distribution.put("入口段", 0);
        distribution.put("处理段", 0);
        distribution.put("出口段", 0);
        distribution.put("其他", 0);

        for (DeviceEnum device : DeviceEnum.values()) {
            String sectionType = device.getSectionType().name();
            if ("ENTRY".equals(sectionType)) {
                distribution.put("入口段", distribution.get("入口段") + 1);
            } else if ("PROCESS".equals(sectionType)) {
                distribution.put("处理段", distribution.get("处理段") + 1);
            } else if ("EXIT".equals(sectionType)) {
                distribution.put("出口段", distribution.get("出口段") + 1);
            } else {
                distribution.put("其他", distribution.get("其他") + 1);
            }
        }

        String[] colors = {"#0066cc", "#409eff", "#66b1ff", "#a0cfff"};
        List<DeviceChartDataDTO.PieSeries> series = new ArrayList<>();
        int colorIndex = 0;

        for (Map.Entry<String, Integer> entry : distribution.entrySet()) {
            if (entry.getValue() > 0) {
                series.add(DeviceChartDataDTO.PieSeries.builder()
                        .name(entry.getKey())
                        .data(entry.getValue().doubleValue())
                        .color(colors[colorIndex % colors.length])
                        .build());
                colorIndex++;
            }
        }

        return DeviceChartDataDTO.PieChartData.builder()
                .series(series)
                .build();
    }

    /**
     * 构建数据来源分布条形图数据
     */
    private DeviceChartDataDTO.BarChartData buildSourceTypeBarChart() {
        Map<String, Integer> distribution = new HashMap<>();
        distribution.put("ENTRY", 0);
        distribution.put("FURNACE", 0);
        distribution.put("COAT", 0);
        distribution.put("EXIT", 0);

        for (DeviceEnum device : DeviceEnum.values()) {
            String sourceType = device.getSourceType().name();
            if (distribution.containsKey(sourceType)) {
                distribution.put(sourceType, distribution.get(sourceType) + 1);
            }
        }

        List<String> categories = new ArrayList<>();
        List<Double> data = new ArrayList<>();

        for (Map.Entry<String, Integer> entry : distribution.entrySet()) {
            if (entry.getValue() > 0) {
                categories.add(entry.getKey());
                data.add(entry.getValue().doubleValue());
            }
        }

        return DeviceChartDataDTO.BarChartData.builder()
                .categories(categories)
                .series(Collections.singletonList(
                        DeviceChartDataDTO.BarSeries.builder()
                                .name("设备数量")
                                .data(data)
                                .build()
                ))
                .build();
    }

    /**
     * 构建同类型设备对比折线图数据（只对比单位相同的设备）
     */
    private DeviceChartDataDTO.LineChartData buildSameTypeDeviceCompareChart() {
        // 获取今天的数据
        LocalDate today = LocalDate.now();
        LocalDateTime startTime = today.atStartOfDay();
        LocalDateTime endTime = today.atTime(LocalTime.MAX);

        // 按数据来源分组，同一来源的设备单位相同，可以对比
        Map<String, List<DeviceEnum>> devicesBySource = new HashMap<>();
        for (DeviceEnum device : DeviceEnum.values()) {
            if (device.getParamFields() == null || device.getParamFields().isEmpty()) {
                continue;
            }
            String sourceType = device.getSourceType().name();
            devicesBySource.computeIfAbsent(sourceType, k -> new ArrayList<>()).add(device);
        }

        // 选择设备数量最多的数据源，取前5个设备进行对比
        String selectedSource = devicesBySource.entrySet().stream()
                .max(Map.Entry.comparingByValue((a, b) -> Integer.compare(a.size(), b.size())))
                .map(Map.Entry::getKey)
                .orElse(null);

        if (selectedSource == null || devicesBySource.get(selectedSource).isEmpty()) {
            return null;
        }

        List<DeviceEnum> selectedDevices = devicesBySource.get(selectedSource).stream()
                .limit(5)
                .collect(Collectors.toList());

        List<String> categories = new ArrayList<>();
        List<DeviceChartDataDTO.LineSeries> series = new ArrayList<>();

        // 生成时间轴（最近10个时间点，每10分钟一个）
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
        LocalDateTime now = LocalDateTime.now();
        for (int i = 9; i >= 0; i--) {
            LocalDateTime time = now.minusMinutes(i * 10L);
            categories.add(time.format(timeFormatter));
        }

        // 为每个设备生成数据系列
        for (DeviceEnum device : selectedDevices) {
            if (device.getParamFields() == null || device.getParamFields().isEmpty()) {
                continue;
            }

            // 获取该设备今天的历史数据
            LambdaQueryWrapper<DeviceSnapshot> qw = new LambdaQueryWrapper<DeviceSnapshot>()
                    .eq(DeviceSnapshot::getDeviceCode, device.name())
                    .between(DeviceSnapshot::getCreateTime, startTime, endTime)
                    .orderByAsc(DeviceSnapshot::getCreateTime);

            List<DeviceSnapshot> rows = deviceSnapshotMapper.selectList(qw);
            List<DeviceSnapshot> sampledRows = sampleDataByInterval(rows, 10);

            // 使用第一个字段的数据
            String firstField = device.getParamFields().get(0);
            List<Double> data = new ArrayList<>();

            // 填充数据（如果历史数据不足，用0填充）
            for (int i = 0; i < 10; i++) {
                if (i < sampledRows.size()) {
                    try {
                        Map<String, Object> jsonData = objectMapper.readValue(
                                sampledRows.get(i).getSnapshotData(), Map.class);
                        Object value = jsonData.get(firstField);
                        double numValue = 0.0;
                        if (value instanceof Number) {
                            numValue = ((Number) value).doubleValue();
                        }
                        data.add(numValue);
                    } catch (Exception e) {
                        data.add(0.0);
                    }
                } else {
                    data.add(0.0);
                }
            }

            series.add(DeviceChartDataDTO.LineSeries.builder()
                    .name(device.getDesc())
                    .data(data)
                    .build());
        }

        if (series.isEmpty()) {
            return null;
        }

        return DeviceChartDataDTO.LineChartData.builder()
                .categories(categories)
                .series(series)
                .build();
    }

    /**
     * 构建设备统计数据
     */
    private List<DeviceChartDataDTO.DeviceStatistics> buildDeviceStatistics() {
        List<DeviceChartDataDTO.DeviceStatistics> statistics = new ArrayList<>();
        LocalDate today = LocalDate.now();
        LocalDateTime startTime = today.atStartOfDay();
        LocalDateTime endTime = today.atTime(LocalTime.MAX);

        // 获取最新的测量数据
        AppMeasureEntryMessage entry = (AppMeasureEntryMessage) latestMeasurements.get(AppMeasureEntryMessage.class);
        AppMeasureFurnaceMessage furnace = (AppMeasureFurnaceMessage) latestMeasurements.get(AppMeasureFurnaceMessage.class);
        AppMeasureCoatMessage coat = (AppMeasureCoatMessage) latestMeasurements.get(AppMeasureCoatMessage.class);
        AppMeasureExitMessage exit = (AppMeasureExitMessage) latestMeasurements.get(AppMeasureExitMessage.class);

        for (DeviceEnum device : DeviceEnum.values()) {
            if (device.getParamFields() == null || device.getParamFields().isEmpty()) {
                continue;
            }

            String firstField = device.getParamFields().get(0);

            // 获取当前值
            double currentValue = 0.0;
            switch (device.getSourceType()) {
                case ENTRY:
                    if (entry != null) {
                        currentValue = getFieldValue(entry, firstField);
                    }
                    break;
                case FURNACE:
                    if (furnace != null) {
                        currentValue = getFieldValue(furnace, firstField);
                    }
                    break;
                case COAT:
                    if (coat != null) {
                        currentValue = getFieldValue(coat, firstField);
                    }
                    break;
                case EXIT:
                    if (exit != null) {
                        currentValue = getFieldValue(exit, firstField);
                    }
                    break;
            }

            // 从历史数据中计算统计值
            LambdaQueryWrapper<DeviceSnapshot> qw = new LambdaQueryWrapper<DeviceSnapshot>()
                    .eq(DeviceSnapshot::getDeviceCode, device.name())
                    .between(DeviceSnapshot::getCreateTime, startTime, endTime)
                    .orderByAsc(DeviceSnapshot::getCreateTime);

            List<DeviceSnapshot> rows = deviceSnapshotMapper.selectList(qw);
            List<Double> values = new ArrayList<>();

            for (DeviceSnapshot snapshot : rows) {
                try {
                    Map<String, Object> jsonData = objectMapper.readValue(
                            snapshot.getSnapshotData(), Map.class);
                    Object value = jsonData.get(firstField);
                    if (value instanceof Number) {
                        double numValue = ((Number) value).doubleValue();
                        if (numValue > 0) {
                            values.add(numValue);
                        }
                    }
                } catch (Exception e) {
                    // ignore
                }
            }

            String avg = "—";
            String max = "—";
            String min = "—";

            if (!values.isEmpty()) {
                double avgValue = values.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
                double maxValue = values.stream().mapToDouble(Double::doubleValue).max().orElse(0.0);
                double minValue = values.stream().mapToDouble(Double::doubleValue).min().orElse(0.0);

                avg = String.format("%.2f", avgValue);
                max = String.format("%.2f", maxValue);
                min = String.format("%.2f", minValue);
            }

            statistics.add(DeviceChartDataDTO.DeviceStatistics.builder()
                    .deviceCode(device.name())
                    .deviceName(device.getDesc())
                    .avg(avg)
                    .max(max)
                    .min(min)
                    .current(currentValue > 0 ? String.format("%.2f", currentValue) : "—")
                    .build());
        }

        return statistics;
    }

    /**
     * 获取字段值
     */
    private double getFieldValue(Object message, String fieldName) {
        try {
            java.lang.reflect.Field field = message.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            Object value = field.get(message);
            if (value instanceof Number) {
                return ((Number) value).doubleValue();
            }
        } catch (Exception e) {
            // ignore
        }
        return 0.0;
    }

    /**
     * 获取设备今天一天的历史趋势数据（10分钟间隔采样）
     * @param deviceCode 设备代码
     * @return 历史趋势数据
     */
    public DeviceHistoryTrendDTO getDeviceHistoryTrend(String deviceCode) {
        try {
            // 获取今天开始和结束时间
            LocalDate today = LocalDate.now();
            LocalDateTime startTime = today.atStartOfDay();
            LocalDateTime endTime = today.atTime(LocalTime.MAX);

            // 查询今天的所有快照数据
            LambdaQueryWrapper<DeviceSnapshot> qw = new LambdaQueryWrapper<DeviceSnapshot>()
                    .eq(DeviceSnapshot::getDeviceCode, deviceCode)
                    .between(DeviceSnapshot::getCreateTime, startTime, endTime)
                    .orderByAsc(DeviceSnapshot::getCreateTime);

            List<DeviceSnapshot> rows = deviceSnapshotMapper.selectList(qw);
            if (rows == null || rows.isEmpty()) {
                return null;
            }

            // 按10分钟间隔采样数据
            List<DeviceSnapshot> sampledRows = sampleDataByInterval(rows, 10);

            // 获取设备信息
            DeviceEnum device = DeviceEnum.valueOf(deviceCode);
            if (device == null) {
                return null;
            }

            // 构建历史趋势数据
            List<String> categories = new ArrayList<>();
            Map<String, List<Double>> seriesMap = new HashMap<>();
            List<String> fields = device.getParamFields();

            if (fields == null || fields.isEmpty()) {
                return null;
            }

            // 初始化系列数据
            for (String field : fields) {
                seriesMap.put(field, new ArrayList<>());
            }

            // 处理采样后的数据
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
            for (DeviceSnapshot snapshot : sampledRows) {
                categories.add(snapshot.getCreateTime().format(timeFormatter));

                Map<String, Object> jsonData = new HashMap<>();
                try {
                    jsonData = objectMapper.readValue(snapshot.getSnapshotData(), Map.class);
                } catch (Exception e) {
                    log.warn("解析快照数据失败: {}", snapshot.getSnapshotData());
                }

                for (String field : fields) {
                    Object value = jsonData.get(field);
                    double numValue = 0.0;
                    if (value instanceof Number) {
                        numValue = ((Number) value).doubleValue();
                    }
                    seriesMap.get(field).add(numValue);
                }
            }

            // 构建系列数据（最多6个字段）
            List<DeviceHistoryTrendDTO.SeriesData> series = fields.stream()
                    .limit(6)
                    .map(field -> DeviceHistoryTrendDTO.SeriesData.builder()
                            .fieldName(field)
                            .name(field) // 前端可以根据字段元数据替换为标签
                            .data(seriesMap.get(field))
                            .build())
                    .collect(Collectors.toList());

            return DeviceHistoryTrendDTO.builder()
                    .deviceCode(deviceCode)
                    .deviceName(device.getDesc())
                    .categories(categories)
                    .series(series)
                    .build();

        } catch (Exception e) {
            log.error("获取设备[{}]历史趋势数据失败: {}", deviceCode, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 按时间间隔采样数据（每N分钟取一条）
     * @param rows 原始数据列表
     * @param intervalMinutes 间隔分钟数
     * @return 采样后的数据列表
     */
    private List<DeviceSnapshot> sampleDataByInterval(List<DeviceSnapshot> rows, int intervalMinutes) {
        if (rows == null || rows.isEmpty()) {
            return new ArrayList<>();
        }

        List<DeviceSnapshot> sampled = new ArrayList<>();
        LocalDateTime lastTime = null;

        for (DeviceSnapshot row : rows) {
            LocalDateTime rowTime = row.getCreateTime();

            if (lastTime == null) {
                // 第一条数据
                sampled.add(row);
                lastTime = rowTime;
            } else {
                // 计算时间差（分钟）
                long diffMinutes = java.time.Duration.between(lastTime, rowTime).toMinutes();

                // 如果时间差大于等于间隔，则采样这条数据
                if (diffMinutes >= intervalMinutes) {
                    sampled.add(row);
                    lastTime = rowTime;
                }
            }
        }

        return sampled;
    }

    /**
     * 创建设备快照
     */
    private DeviceSnapshot createDeviceSnapshot(DeviceEnum device, LocalDateTime timestamp,
                                              AppMeasureEntryMessage entry,
                                              AppMeasureFurnaceMessage furnace,
                                              AppMeasureCoatMessage coat,
                                              AppMeasureExitMessage exit) {
        try {
            // 创建快照对象
            DeviceSnapshot snapshot = new DeviceSnapshot();
            snapshot.setCreateTime(timestamp);
            snapshot.setDeviceId(device.getIdx());
            snapshot.setDeviceCode(device.name());
            snapshot.setDeviceName(device.getDesc());
            snapshot.setSectionType(device.getSectionType().name());
            snapshot.setSourceType(device.getSourceType().name());
            snapshot.setBasePosition(device.getBasePosition());

            // 根据设备类型获取对应的测量数据
            ObjectNode dataNode = objectMapper.createObjectNode();
            switch (device.getSourceType()) {
                case ENTRY:
                    if (entry != null) {
                        extractData(entry, device.getParamFields(), dataNode);
                    }
                    break;
                case FURNACE:
                    if (furnace != null) {
                        extractData(furnace, device.getParamFields(), dataNode);
                    }
                    break;
                case COAT:
                    if (coat != null) {
                        extractData(coat, device.getParamFields(), dataNode);
                    }
                    break;
                case EXIT:
                    if (exit != null) {
                        extractData(exit, device.getParamFields(), dataNode);
                    }
                    break;
            }

            // 如果没有数据，则跳过
            if (dataNode.isEmpty()) {
                return null;
            }

            // 设置快照数据
            snapshot.setSnapshotData(dataNode.toString());
            return snapshot;
        } catch (Exception e) {
            log.error("创建设备[{}]快照时发生错误: {}", device.name(), e.getMessage(), e);
            return null;
        }
    }

    /**
     * 从消息对象中提取指定字段的数据
     */
    private void extractData(Object message, List<String> fields, ObjectNode dataNode) {
        if (message == null || fields == null || fields.isEmpty()) {
            return;
        }

        try {
            for (String field : fields) {
                try {
                    // 使用反射获取字段值
                    java.lang.reflect.Field declaredField = message.getClass().getDeclaredField(field);
                    declaredField.setAccessible(true);
                    Object value = declaredField.get(message);

                    // 处理不同类型的值
                    if (value != null) {
                        if (value instanceof Integer) {
                            dataNode.put(field, (Integer) value);
                        } else if (value instanceof Long) {
                            dataNode.put(field, (Long) value);
                        } else if (value instanceof Float) {
                            dataNode.put(field, (Float) value);
                        } else if (value instanceof Double) {
                            dataNode.put(field, (Double) value);
                        } else if (value instanceof Boolean) {
                            dataNode.put(field, (Boolean) value);
                        } else if (value instanceof String) {
                            dataNode.put(field, (String) value);
                        } else if (value instanceof Enum) {
                            dataNode.put(field, value.toString());
                        }
                    }
                } catch (NoSuchFieldException e) {
                    log.trace("字段[{}]在消息[{}]中不存在", field, message.getClass().getSimpleName());
                } catch (Exception e) {
                    log.warn("获取字段[{}]值失败: {}", field, e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("提取数据时发生错误: {}", e.getMessage(), e);
        }
    }
}
