#include "../include/cpp/data_praser.h"
#include <cstring>  // 添加 memcpy 头文件
#include <sstream>  // 添加 stringstream 头文件
#include <iomanip>  // 添加 iomanip 头文件
#include <iostream> // 添加 iostream 头文件
#include <jni.h>
#include <android/log.h>
#include <map>

// 辅助函数：从字节数组读取小端整数
template <typename T>
T read_le(const uint8_t* data) {
    T value = 0;
    for (size_t i = 0; i < sizeof(T); ++i) {
        value |= static_cast<T>(data[i]) << (i * 8);
    }
    return value;
}

// 脑电设备解析 (0x4230)
SensorData parse_eeg(const uint8_t* data) {
    SensorData result;
    result.data_type = DataType::EEG;
    result.packet_sn = read_le<uint16_t>(data);
    
    // 跳过 DataType(2) 和 data_len(2)
    const uint8_t* payload = data + 6;
    
    // 导联状态
    std::memcpy(result.lead_status.status, payload, 2);
    payload += 2;
    
    // 解析EEG数据 (6通道 × 14采样点)   
    auto& eeg_data = result.channel_data.emplace<std::vector<std::vector<float>>>();
    eeg_data.resize(6);
    
    for (int ch = 0; ch < 6; ++ch) {
        eeg_data[ch].reserve(14);
        for (int i = 0; i < 14; ++i) {
            int16_t adc_value = read_le<int16_t>(payload); 
            payload += 2;
            eeg_data[ch].push_back(adc_value * 0.318f); // 转换为μV
        }
    }
    
    // 解析EOG数据 (2通道 × 14采样点)
    for (int ch = 0; ch < 2; ++ch) {
        eeg_data.push_back({}); // 添加新通道
        for (int i = 0; i < 14; ++i) {
            int16_t adc_value = read_le<int16_t>(payload);
            payload += 2;
            eeg_data.back().push_back(adc_value * 0.318f); // 转换为μV
        }
    }
    
    // 跳过预留区(6字节)
    payload += 6;

    // 赋值原始二进制数据
    result.raw_data.assign(data, data + 6 + 2 + 6 * 14 * 2 + 2 * 14 * 2 + 6);

    return result;
}

// 心电设备解析 (0x4211)
SensorData parse_ecg_emg(const uint8_t* data) {
    SensorData result;
    result.data_type = DataType::ECG_2LEAD;
    result.packet_sn = read_le<uint16_t>(data);
    
    // 跳过 data_type(2) 和 data_len(2)
    const uint8_t* payload = data + 6;
    
    // 导联状态
    std::memcpy(result.lead_status.status, payload, 2);
    payload += 2;
    
    // 解析数据 (多通道混合)
    auto& channels = result.channel_data.emplace<std::vector<std::vector<float>>>();
    
    // ECG1 (25采样点)
    channels.push_back({});
    for (int i = 0; i < 25; ++i) {
        int16_t adc_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(adc_value * 0.318f); // μV
    }
    
    // ECG2 (25采样点)
    channels.push_back({});
    for (int i = 0; i < 25; ++i) {
        int16_t adc_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(adc_value * 0.318f); // μV
    }
    
    // EMG1 (25采样点)
    channels.push_back({});
    for (int i = 0; i < 25; ++i) {
        int16_t adc_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(adc_value * 0.318f); // μV
    }
    
    // EMG2 (25采样点)
    channels.push_back({});
    for (int i = 0; i < 25; ++i) {
        int16_t adc_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(adc_value * 0.318f); // μV
    }
    
    // 呼吸温度 (5采样点)
    channels.push_back({});
    for (int i = 0; i < 5; ++i) {
        int16_t temp_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(temp_value * 0.477f); // 存储所有采样点
    }
    
    // 呼吸阻抗1 (5采样点)
    channels.push_back({});
    for (int i = 0; i < 5; ++i) {
        int16_t imp_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(static_cast<float>(imp_value)); // 原始值
    }
    
    // 呼吸阻抗2 (5采样点)
    channels.push_back({});
    for (int i = 0; i < 5; ++i) {
        int16_t imp_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(static_cast<float>(imp_value)); // 原始值
    }
    
    // 赋值原始二进制数据
    result.raw_data.assign(data, data + 238); // 完整238字节

    return result;
}

// 血氧设备解析(0x4302)
SensorData parse_ppg(const uint8_t* data) {
    SensorData result;
    result.data_type = DataType::PPG;
    result.packet_sn = read_le<uint16_t>(data);
    
    // 跳过 DataType(2) 和 data_len(2)
    const uint8_t* payload = data + 6;
    
    // 读取生命体征
    result.additional.hr = *payload++;
    result.additional.spo2 = *payload++;
    
    // 注意：温度值放大100倍存储，需要除以100
    int16_t temp_raw = read_le<int16_t>(payload);
    result.additional.temperature = static_cast<float>(temp_raw) / 100.0f;
    payload += 2;
    
    // 解析红光数据 (57采样点)
    auto& channels = result.channel_data.emplace<std::vector<std::vector<float>>>();
    channels.push_back({});
    for (int i = 0; i < 57; ++i) {
        int16_t adc_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(adc_value * 0.879f); // mV
    }
    
    // 解析红外光数据(57采样点)
    channels.push_back({});
    for (int i = 0; i < 57; ++i) {
        int16_t adc_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(adc_value * 0.879f); // mV
    }

    // 赋值原始二进制数据
    result.raw_data.assign(data, data + 6 + 4 + 57 * 2 * 2);

    return result;
}

// 12导联心电解析 (0x4402)
SensorData parse_12lead_ecg(const uint8_t* data) {
    SensorData result;
    result.data_type = DataType::ECG_12LEAD;
    result.packet_sn = read_le<uint16_t>(data);
    
    // 跳过 DataType(2) 和 data_len(2)
    const uint8_t* payload = data + 6;
    
    // 导联状态(按文档说明处理STAT寄存器)
    uint8_t stat_dh = payload[0];  // STAT.DH
    uint8_t stat_dm = payload[1];  // STAT.DM   
    
    // 正确拼接方式: (STAT.DH << 4) | (STAT.DM >> 4)
    result.lead_status.status[0] = (stat_dh << 4) | (stat_dm >> 4) ;

    result.lead_status.status[1] = 0;  // 第二个字节未使用
    payload += 2;
    
    // 解析8通道ECG数据
    auto& channels = result.channel_data.emplace<std::vector<std::vector<float>>>();
    channels.resize(8);
    
    for (int ch = 0; ch < 8; ++ch) {
        channels[ch].reserve(14);
        for (int i = 0; i < 14; ++i) {
            int16_t adc_value = read_le<int16_t>(payload);
            payload += 2;
            channels[ch].push_back(adc_value * 0.318f); //原始数据进行量纲转换
        }   
    }
    
    // GPIO状态(取低4位)
    result.additional.gpio_state = *payload & 0x0F;
    payload += 1;
    
    // 跳过预留区(5字节)
    payload += 5;

    // 赋值原始二进制数据
    result.raw_data.assign(data, data + 6 + 2 + 8 * 14 * 2 + 1 + 5);

    return result;
}

// 单通道心电解析 (0x4401) - PW_ECG-SL
SensorData parse_pw_ecg_sl(const uint8_t* data) {
    SensorData result;
    result.data_type = DataType::PW_ECG_SL;
    result.packet_sn = read_le<uint16_t>(data);
    
    // 跳过 DataType(2) 和 data_len(2)
    const uint8_t* payload = data + 6;
    
    // 导联脱落状态 (1字节，高4位+中4位)
    result.lead_status.status[0] = *payload;
    result.lead_status.status[1] = 0;  // 第二个字节未使用
    payload += 1;
    
    // 解析单通道ECG数据 (115个采样点)
    auto& channels = result.channel_data.emplace<std::vector<std::vector<float>>>();
    channels.resize(1); // 单通道
    channels[0].reserve(115);
    
    for (int i = 0; i < 115; ++i) {
        int16_t adc_value = read_le<int16_t>(payload);
        payload += 2;
        channels[0].push_back(adc_value * 0.288f); // 转换为μV，与12导联心电保持一致
    }
    
    // 跳过预留1字节
    payload += 1;

    // 赋值原始二进制数据
    result.raw_data.assign(data, data + 6 + 1 + 115 * 2 + 1);

    return result;
}


// 数字听诊解析 (0x1102)
SensorData parse_stethoscope(const uint8_t* data) {
    SensorData result;
    result.data_type = DataType::STETHOSCOPE;
    result.packet_sn = read_le<uint16_t>(data);
    
    // 跳过 DataType(2) 和 data_len(2)
    const uint8_t* payload = data + 6;
    
    // 解析双通道音频数据
    auto& channels = result.channel_data.emplace<std::vector<std::vector<float>>>();
    channels.resize(2);
    
    // 通道1数据 (116采样点)
    for (int i = 0; i < 116; ++i) {
        int8_t sample = static_cast<int8_t>(*payload++);
        channels[0].push_back(sample * 0.146f); // mV
    }
    
    // 通道2数据 (116采样点)
    for (int i = 0; i < 116; ++i) {
        int8_t sample = static_cast<int8_t>(*payload++);
        channels[1].push_back(sample * 0.146f); // mV
    }

    // 赋值原始二进制数据
    result.raw_data.assign(data, data + 6 + 116 * 2);

    return result;
}

// 鼾声解析 (0x4212)
SensorData parse_snore(const uint8_t* data) {
    SensorData result;
    result.data_type = DataType::SNORE;
    result.packet_sn = read_le<uint16_t>(data);
    
    // 跳过 data_type(2) + data_len(2)
    const uint8_t* payload = data + 6;
    
    // 解析鼾声数据 (232字节)
    auto& channels = result.channel_data.emplace<std::vector<float>>();
    
    // 高效转换: 直接使用 reinterpret_cast
    const int8_t* snore_data = reinterpret_cast<const int8_t*>(payload);
    for (int i = 0; i < 232; ++i) {
        channels.push_back(static_cast<float>(snore_data[i]));
    }

    // 赋值原始二进制数据
    result.raw_data.assign(data, data + 6 + 232);

    return result;
}

// 呼吸/姿态/环境光解析(0x4213)
SensorData parse_respiration(const uint8_t* data) {
    SensorData result;
    result.data_type = DataType::RESPIRATION;
    result.packet_sn = read_le<uint16_t>(data);
    
    // 跳过 DataType(2) 和 data_len(2)
    const uint8_t* payload = data + 6;
    
    // 解析呼吸气流数据 (114采样点)
    auto& channels = result.channel_data.emplace<std::vector<std::vector<float>>>();
    channels.push_back({});
    
    for (int i = 0; i < 114; ++i) {
        int16_t adc_value = read_le<int16_t>(payload);
        payload += 2;
        channels.back().push_back(adc_value * 0.1f); // 实际单位
    }
    
    // 解析附加数据
    result.additional.movement = read_le<uint16_t>(payload); // 运动强度
    payload += 2;
    
    result.additional.posture = *payload++; // 姿态数据
    result.additional.ambient_light = *payload++; // 环境光数据

    // 赋值原始二进制数据
    result.raw_data.assign(data, data + 6 + 114 * 2 + 2 + 1 + 1);

    return result;
}

// 统一解析入口函数 - 支持多个包头和数据包格式
std::vector<SensorData> parse_device_data(const std::vector<uint8_t>& file_data) {
    const size_t PACKET_SIZE = 238;  // 每个数据包固定大小
    const size_t RESPONSE_HEADER_SIZE = 10; // 响应包头大小 (2功能码+ 2数据长度 + 4实际采集点数+2CRC校验)
    const uint16_t FUNCTION_CODE = 0x0010; // 获取数据功能码
    
    const size_t file_size = file_data.size();
    const uint8_t* ptr = file_data.data();
    const uint8_t* end_ptr = ptr + file_size;
    std::map<DataType, std::vector<SensorData>> grouped_data;
    std::vector<SensorData> results;
    
    while (ptr < end_ptr) {
        // 检查是否有响应包头
        bool has_response_header = false;
        size_t remaining = end_ptr - ptr;

        // 确保有足够的空间检查包头
        if (remaining >= RESPONSE_HEADER_SIZE) {
            // 读取功能码(小端)
            uint16_t func_code = read_le<uint16_t>(ptr);
            // 读取数据长度 (小端)
            uint16_t data_len = read_le<uint16_t>(ptr + 2);

            // 检查是否符合0x0010响应包特征
            if (func_code == FUNCTION_CODE && data_len == 0x0004) {
                has_response_header = true;
                std::cout << "检测到响应帧头: 功能码=0x" << std::hex << func_code 
                          << ", 数据长度=0x" << data_len << std::dec << std::endl;

                // 读取实际数据点数 (小端)
                uint32_t actual_points = read_le<uint32_t>(ptr + 4);
                std::cout << "实际数据点数: " << actual_points << std::endl;
                
                // 读取CRC校验 (小端)
                uint16_t crc = read_le<uint16_t>(ptr + 8);
                
                // 验证CRC校验
                uint16_t calculated_crc = calculate_crc16(ptr, 8);
                if (crc != calculated_crc) {
                    std::cerr << "警告: CRC校验失败，预期: 0x" << std::hex << calculated_crc 
                              << ", 实际: 0x" << crc << std::dec << std::endl;
                    // 可以选择跳过这个响应帧或继续处理
                }

                // 计算期望的数据长度(实际点数 * 包大小)
                size_t expected_data_size = actual_points * PACKET_SIZE;
                size_t remaining_after_header = remaining - RESPONSE_HEADER_SIZE;

                // 验证数据长度是否匹配
                if (remaining_after_header < expected_data_size) {
                    std::string error = "包头数据不足: 预期 " +
                                        std::to_string(expected_data_size) +
                                        " 字节, 实际 " +
                                        std::to_string(remaining_after_header) +
                                        " 字节";
                    throw std::runtime_error(error);
                }

                // 跳过包头
                ptr += RESPONSE_HEADER_SIZE;

                // 处理包头后的数据包
                for (uint32_t i = 0; i < actual_points; i++) {
                    if (end_ptr - ptr < static_cast<ptrdiff_t>(PACKET_SIZE)) {
                        throw std::runtime_error("数据包不完整");
                    }

                    // 读取数据类型标识
                    const uint16_t data_type = read_le<uint16_t>(ptr + 2);

                    switch (data_type) {
                        case 0x4230:
                            grouped_data[DataType::EEG].push_back(parse_eeg(ptr));
                            break;
                        case 0x4211:
                            grouped_data[DataType::ECG_2LEAD].push_back(parse_ecg_emg(ptr));
                            break;
                        case 0x4212:
                            grouped_data[DataType::SNORE].push_back(parse_snore(ptr));
                            break;
                        case 0x4213:
                            grouped_data[DataType::RESPIRATION].push_back(parse_respiration(ptr));
                            break;
                        case 0x4401:
                            grouped_data[DataType::PW_ECG_SL].push_back(parse_pw_ecg_sl(ptr));
                            break;
                        case 0x4402:
                            grouped_data[DataType::ECG_12LEAD].push_back(parse_12lead_ecg(ptr));
                            break;
                        case 0x4302:
                            grouped_data[DataType::PPG].push_back(parse_ppg(ptr));
                            break;
                        case 0x1102:
                            grouped_data[DataType::STETHOSCOPE].push_back(parse_stethoscope(ptr));
                            break;
                        default:
                            // 对于未知类型，记录警告但继续处理
                            std::cerr << "警告: 未知设备类型: 0x" << std::hex << data_type 
                                      << std::dec << ", 跳过此数据包" << std::endl;
                            ptr += PACKET_SIZE;
                            continue;
                    }
                    ptr += PACKET_SIZE;
                }
            }
        }
        
        // 如果没有检测到响应包头，尝试按线数据包处理
        if (!has_response_header) {
            // 检查是否有完整的数据包
            if (remaining >= PACKET_SIZE) {
                // 读取数据类型标识
                const uint16_t data_type = read_le<uint16_t>(ptr + 2);
                
                switch (data_type) {
                    case 0x4230: 
                        grouped_data[DataType::EEG].push_back(parse_eeg(ptr));
                        break;
                    case 0x4211: 
                        grouped_data[DataType::ECG_2LEAD].push_back(parse_ecg_emg(ptr));
                        break;
                    case 0x4212: 
                        grouped_data[DataType::SNORE].push_back(parse_snore(ptr));
                        break;
                    case 0x4213: 
                        grouped_data[DataType::RESPIRATION].push_back(parse_respiration(ptr));
                        break;
                    case 0x4401: 
                        grouped_data[DataType::PW_ECG_SL].push_back(parse_pw_ecg_sl(ptr));
                        break;
                    case 0x4402: 
                        grouped_data[DataType::ECG_12LEAD].push_back(parse_12lead_ecg(ptr));
                        break;
                    case 0x4302: 
                        grouped_data[DataType::PPG].push_back(parse_ppg(ptr));
                        break;
                    case 0x1102:
                        grouped_data[DataType::STETHOSCOPE].push_back(parse_stethoscope(ptr));
                        break;
                    default:
                        // 如果不是已知类型，跳过这个包继续处理
                        ptr += PACKET_SIZE;
                        continue;
                }
                ptr += PACKET_SIZE;
            } else {
                // 剩余数据不足一个包，但大于0，发出警告
                break; // 结束处理
            }
        }
    }
    
    // 直接构建最终结果，避免中间存储
    std::vector<SensorData> final_results;
    
    // 按数据类型分组处理，合并通道数据
    for (auto& [data_type, packets] : grouped_data) {
        if (packets.empty()) continue;
        
        // 检查第一个数据包的通道数据类型
        bool isMultiChannel = std::holds_alternative<std::vector<std::vector<float>>>(packets[0].channel_data);
        bool isSingleChannel = std::holds_alternative<std::vector<float>>(packets[0].channel_data);
        
        if (isMultiChannel) {
            // 处理多通道数据 (vector<vector<float>>)
            SensorData full_data = packets[0];
            full_data.channel_data = std::vector<std::vector<float>>();
            
            // 获取通道数量
            size_t num_channels = 0;
            if (auto* channels = std::get_if<std::vector<std::vector<float>>>(&packets[0].channel_data)) {
                num_channels = channels->size();
                full_data.channel_data.emplace<std::vector<std::vector<float>>>(num_channels);
            }
            
            // 合并所有数据包中的通道数据
            auto& full_channels = std::get<std::vector<std::vector<float>>>(full_data.channel_data);
            for (size_t ch = 0; ch < num_channels; ch++) {
                for (auto& packet : packets) {
                    if (auto* channels = std::get_if<std::vector<std::vector<float>>>(&packet.channel_data)) {
                        if (ch < channels->size()) {
                            full_channels[ch].insert(full_channels[ch].end(), 
                                                    (*channels)[ch].begin(), 
                                                    (*channels)[ch].end());
                        }
                    }
                }
            }
            
            final_results.push_back(full_data);
            
        } else if (isSingleChannel) {
            // 处理单通道数据 (vector<float>) - 合并所有数据包的单通道数据
            SensorData full_data = packets[0];
            full_data.channel_data = std::vector<float>();
            
            auto& full_channel = full_data.channel_data.emplace<std::vector<float>>();
            
            // 合并所有数据包的单通道数据
            for (auto& packet : packets) {
                if (auto* channel = std::get_if<std::vector<float>>(&packet.channel_data)) {
                    full_channel.insert(full_channel.end(), channel->begin(), channel->end());
                }
            }
            
            final_results.push_back(full_data);
            
        } else {
            // 没有通道数据，直接添加第一个数据包
            final_results.push_back(packets[0]);
        }
    }
    
    return final_results;
}

// CRC16校验函数 (Modbus CRC16)
uint16_t calculate_crc16(const uint8_t* data, size_t length) {
    uint16_t crc = 0xFFFF;
    
    for (size_t i = 0; i < length; i++) {
        crc ^= data[i];
        for (int j = 0; j < 8; j++) {
            if (crc & 0x0001) {
                crc = (crc >> 1) ^ 0xA001;
            } else {
                crc = crc >> 1;
            }
        }
    }
    
    return crc;
}

// 工具函数：将数值转换为十六进制字符串
std::string to_hex_string(uint16_t value) {
    std::stringstream ss;
    ss << "0x" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << value;
    return ss.str();
}


// ============================================================================
// 新的流式解析版本 - 用于蓝牙设备数据包
// ============================================================================

// 流式解析器构造函数
StreamParser::StreamParser() : packet_callback_(nullptr), buffer_size_(0), total_packets_(0) {
    // 预分配缓冲区空间，避免频繁重新分配
    buffer_.reserve(1024); // 预分配1KB空间
}

// 流式解析器析构函数
StreamParser::~StreamParser() {
    // 清理资源
    clear();
}

// 添加新接收到的蓝牙数据
void StreamParser::appendData(const uint8_t* data, size_t length) {
    if (data == nullptr || length == 0) {
        return;
    }
    
    // 将新数据添加到缓冲区
    buffer_.insert(buffer_.end(), data, data + length);
    buffer_size_ += length;
    
    // 尝试解析缓冲区中的数据
    parseBuffer();
}

// 检查是否有完整的数据包可用
bool StreamParser::hasCompletePacket() const {
    return !complete_packets_.empty();
}

// 获取下一个完整的数据包
SensorData StreamParser::getNextPacket() {
    if (complete_packets_.empty()) {
        throw std::runtime_error("没有可用的完整数据包");
    }
    
    SensorData packet = complete_packets_.front();
    complete_packets_.pop();
    return packet;
}

// 获取所有可用数据包
std::vector<SensorData> StreamParser::getAllPackets() {
    std::vector<SensorData> result;
    while (!complete_packets_.empty()) {
        result.push_back(complete_packets_.front());
        complete_packets_.pop();
    }
    return result;
}

// 设置数据包处理回调函数
void StreamParser::setPacketCallback(std::function<void(const SensorData&)> callback) {
    packet_callback_ = callback;
}

// 清空缓冲区和队列
void StreamParser::clear() {
    buffer_.clear();
    buffer_size_ = 0;
    while (!complete_packets_.empty()) {
        complete_packets_.pop();
    }
}

// 获取缓冲区状态信息
size_t StreamParser::getBufferSize() const {
    return buffer_.size();
}

size_t StreamParser::getTotalPackets() const {
    return total_packets_;
}

// 内部解析方法 - 持续处理缓冲区中的数据
void StreamParser::parseBuffer() {
    // 持续处理直到缓冲区中没有完整的数据包
    while (buffer_.size() >= PACKET_SIZE) {
        // 验证数据包的有效性
        if (!isValidPacket(buffer_.data())) {
            // 无效数据包，跳过第一个字节继续寻找
            buffer_.erase(buffer_.begin());
            continue;
        }
        
        // 提取数据包类型
        uint16_t data_type = read_le<uint16_t>(buffer_.data() + 2);
        SensorData packet;
        
        try {
            // 根据数据类型调用相应的解析函数
            switch (data_type) {
                case 0x4230: 
                    packet = parse_eeg(buffer_.data());
                    break;
                case 0x4211: 
                    packet = parse_ecg_emg(buffer_.data());
                    break;
                case 0x4212: 
                    packet = parse_snore(buffer_.data());
                    break;
                case 0x4213: 
                    packet = parse_respiration(buffer_.data());
                    break;
                case 0x4401: 
                    packet = parse_pw_ecg_sl(buffer_.data());
                    break;
                case 0x4402: 
                    packet = parse_12lead_ecg(buffer_.data());
                    break;
                case 0x4302: 
                    packet = parse_ppg(buffer_.data());
                    break;
                case 0x1102:
                    packet = parse_stethoscope(buffer_.data());
                    break;
                default:
                    // 未知类型，跳过这个包
                    buffer_.erase(buffer_.begin(), buffer_.begin() + PACKET_SIZE);
                    continue; // 继续处理下一个包
            }
            
            // 成功解析，添加到完成包队列
            complete_packets_.push(packet);
            total_packets_++;
            
            // 如果有回调函数，调用它
            if (packet_callback_) {
                packet_callback_(packet);
            }
            
            // 从缓冲区移除已处理的数据包
            buffer_.erase(buffer_.begin(), buffer_.begin() + PACKET_SIZE);
            
        } catch (const std::exception& e) {
            // 解析错误，跳过这个包
            buffer_.erase(buffer_.begin(), buffer_.begin() + PACKET_SIZE);
        }
    }
}

// 验证数据包的有效性
bool StreamParser::isValidPacket(const uint8_t* data) {
    if (data == nullptr) {
        return false;
    }
    
    // 检查数据包长度
    uint16_t data_len = read_le<uint16_t>(data + 4);
    if (data_len != PACKET_SIZE - 6) { // 6字节是头部长度
        return false;
    }
    
    // 检查数据类型是否在有效范围内
    uint16_t data_type = read_le<uint16_t>(data + 2);
    switch (data_type) {
        case 0x4230: // EEG
        case 0x4211: // ECG_2LEAD
        case 0x4212: // SNORE
        case 0x4213: // RESPIRATION
        case 0x4401: // PW_ECG_SL
        case 0x4402: // ECG_12LEAD
        case 0x4302: // PPG
        case 0x1102: // STETHOSCOPE
            return true;
        default:
            return false;
    }
}

// 获取缓冲区中等待处理的数据量
size_t StreamParser::getPendingDataSize() const {
    return buffer_.size();
}

// 检查缓冲区是否为空
bool StreamParser::isBufferEmpty() const {
    return buffer_.empty();
}

// 获取队列中等待处理的数据包数量
size_t StreamParser::getQueuedPacketCount() const {
    return complete_packets_.size();
}

// JNI辅助函数：将Java的byte数组转换为C++的vector
std::vector<uint8_t> convertJavaByteArrayToVector(JNIEnv* env, jbyteArray byteArray) {
    std::vector<uint8_t> result;
    
    if (byteArray == nullptr) {
        return result;
    }
    
    jsize length = env->GetArrayLength(byteArray);
    if (length <= 0) {
        return result;
    }
    
    jbyte* elements = env->GetByteArrayElements(byteArray, nullptr);
    if (elements == nullptr) {
        return result;
    }
    
    result.resize(length);
    for (jsize i = 0; i < length; ++i) {
        result[i] = static_cast<uint8_t>(elements[i]);
    }
    
    env->ReleaseByteArrayElements(byteArray, elements, JNI_ABORT);
    return result;
}

// JNI辅助函数：将C++的SensorData转换为Java对象
jobject convertSensorDataToJava(JNIEnv* env, const SensorData& sensorData) {
    // 获取Java类的引用
    jclass sensorDataClass = env->FindClass("type/SensorData");
    if (sensorDataClass == nullptr) {
        __android_log_print(ANDROID_LOG_ERROR, "DataParser", "Cannot find SensorData class");
        return nullptr;
    }
    
    // 创建Java对象
    jobject javaSensorData = env->AllocObject(sensorDataClass);
    if (javaSensorData == nullptr) {
        __android_log_print(ANDROID_LOG_ERROR, "DataParser", "Cannot create SensorData object");
        return nullptr;
    }
    
    // 获取字段ID
    jfieldID dataTypeField = env->GetFieldID(sensorDataClass, "dataType", "Ltype/SensorData$DataType;");
    jfieldID packetSnField = env->GetFieldID(sensorDataClass, "packetSn", "I");
    jfieldID leadStatusField = env->GetFieldID(sensorDataClass, "leadStatus", "[B");
    jfieldID timestampField = env->GetFieldID(sensorDataClass, "timestamp", "J");
    jfieldID channelDataField = env->GetFieldID(sensorDataClass, "channelData", "Ljava/util/List;");
    jfieldID additionalDataField = env->GetFieldID(sensorDataClass, "additionalData", "Ltype/SensorData$AdditionalData;");
    jfieldID rawDataField = env->GetFieldID(sensorDataClass, "rawData", "[B");
    
    if (dataTypeField == nullptr || packetSnField == nullptr || leadStatusField == nullptr ||
        timestampField == nullptr || channelDataField == nullptr || additionalDataField == nullptr || rawDataField == nullptr) {
        __android_log_print(ANDROID_LOG_ERROR, "DataParser", "Cannot find SensorData fields");
        return nullptr;
    }
    
    // 设置基本字段
    env->SetIntField(javaSensorData, packetSnField, static_cast<jint>(sensorData.packet_sn));
    env->SetLongField(javaSensorData, timestampField, static_cast<jlong>(sensorData.timestamp));
    
    // 设置数据类型
    jclass dataTypeClass = env->FindClass("type/SensorData$DataType");
    if (dataTypeClass != nullptr) {
        // 根据C++的DataType枚举值找到对应的Java枚举值
        const char* enumName = nullptr;
        switch (sensorData.data_type) {
            case DataType::EEG: enumName = "EEG"; break;
            case DataType::ECG_2LEAD: enumName = "ECG_2LEAD"; break;
            case DataType::PPG: enumName = "PPG"; break;
            case DataType::ECG_12LEAD: enumName = "ECG_12LEAD"; break;
            case DataType::MIT_BIH: enumName = "MIT_BIH"; break;
            case DataType::PW_ECG_SL: enumName = "PW_ECG_SL"; break;
            case DataType::STETHOSCOPE: enumName = "STETHOSCOPE"; break;
            case DataType::SNORE: enumName = "SNORE"; break;
            case DataType::RESPIRATION: enumName = "RESPIRATION"; break;
            default: enumName = "EEG"; break; // 默认值
        }
        
        jfieldID enumField = env->GetStaticFieldID(dataTypeClass, enumName, "Ltype/SensorData$DataType;");
        if (enumField != nullptr) {
            jobject enumValue = env->GetStaticObjectField(dataTypeClass, enumField);
            if (enumValue != nullptr) {
                env->SetObjectField(javaSensorData, dataTypeField, enumValue);
            }
        }
    }
    
    // 设置导联状态
    jbyteArray leadStatusArray = env->NewByteArray(2);
    env->SetByteArrayRegion(leadStatusArray, 0, 2, reinterpret_cast<const jbyte*>(sensorData.lead_status.status));
    env->SetObjectField(javaSensorData, leadStatusField, leadStatusArray);
    
    // 设置原始数据
    jbyteArray rawDataArray = env->NewByteArray(static_cast<jsize>(sensorData.raw_data.size()));
    env->SetByteArrayRegion(rawDataArray, 0, static_cast<jsize>(sensorData.raw_data.size()), 
                           reinterpret_cast<const jbyte*>(sensorData.raw_data.data()));
    env->SetObjectField(javaSensorData, rawDataField, rawDataArray);

    // 设置通道数据（处理两种类型：vector<vector<float>> 和 vector<float>）
    if (auto* multiChannels = std::get_if<std::vector<std::vector<float>>>(&sensorData.channel_data)) {
        // 处理多通道数据 (vector<vector<float>>)
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DEBUG: C++到Java转换 - 多通道数据，通道数量: %zu", multiChannels->size());
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DEBUG: C++到Java转换 - 数据类型: %d", static_cast<int>(sensorData.data_type));
        
        jclass arrayListClass = env->FindClass("java/util/ArrayList");
        jmethodID arrayListConstructor = env->GetMethodID(arrayListClass, "<init>", "()V");
        jmethodID addMethod = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z");

        // 创建外层列表 (List<List<Float>>)
        jobject outerList = env->NewObject(arrayListClass, arrayListConstructor);

        for (const auto& channel : *multiChannels) {
            // 创建内层列表 (List<Float>)
            jobject innerList = env->NewObject(arrayListClass, arrayListConstructor);

            // 将浮点数添加到内层列表
            jclass floatClass = env->FindClass("java/lang/Float");
            jmethodID floatConstructor = env->GetMethodID(floatClass, "<init>", "(F)V");

            for (float value : channel) {
                jobject floatObj = env->NewObject(floatClass, floatConstructor, value);
                env->CallBooleanMethod(innerList, addMethod, floatObj);
                env->DeleteLocalRef(floatObj); // 释放本地引用
            }

            // 将内层列表添加到外层列表
            env->CallBooleanMethod(outerList, addMethod, innerList);
            env->DeleteLocalRef(innerList); // 释放本地引用
        }

        env->SetObjectField(javaSensorData, channelDataField, outerList);
        __android_log_print(ANDROID_LOG_INFO, "DataMapper", "DEBUG: C++到Java转换 - 多通道数据设置完成");

    } else if (auto* singleChannel = std::get_if<std::vector<float>>(&sensorData.channel_data)) {
        // 处理单通道数据 (vector<float>) - 将其包装为单通道的多通道格式
        jclass arrayListClass = env->FindClass("java/util/ArrayList");
        jmethodID arrayListConstructor = env->GetMethodID(arrayListClass, "<init>", "()V");
        jmethodID addMethod = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z");

        // 创建外层列表 (List<List<Float>>)
        jobject outerList = env->NewObject(arrayListClass, arrayListConstructor);

        // 创建内层列表 (List<Float>)
        jobject innerList = env->NewObject(arrayListClass, arrayListConstructor);

        // 将浮点数添加到内层列表
        jclass floatClass = env->FindClass("java/lang/Float");
        jmethodID floatConstructor = env->GetMethodID(floatClass, "<init>", "(F)V");

        for (float value : *singleChannel) {
            jobject floatObj = env->NewObject(floatClass, floatConstructor, value);
            env->CallBooleanMethod(innerList, addMethod, floatObj);
            env->DeleteLocalRef(floatObj); // 释放本地引用
        }

        // 将内层列表添加到外层列表
        env->CallBooleanMethod(outerList, addMethod, innerList);
        env->DeleteLocalRef(innerList); // 释放本地引用

        env->SetObjectField(javaSensorData, channelDataField, outerList);

    } else {
        // 没有通道数据，设置为空列表
        jclass arrayListClass = env->FindClass("java/util/ArrayList");
        jmethodID arrayListConstructor = env->GetMethodID(arrayListClass, "<init>", "()V");
        jobject emptyList = env->NewObject(arrayListClass, arrayListConstructor);
        env->SetObjectField(javaSensorData, channelDataField, emptyList);
    }

    // 设置附加数据（简化处理）
    jclass additionalDataClass = env->FindClass("type/SensorData$AdditionalData");
    if (additionalDataClass != nullptr) {
        jobject additionalData = env->AllocObject(additionalDataClass);
        if (additionalData != nullptr) {
            // 设置基本字段
            jfieldID hrField = env->GetFieldID(additionalDataClass, "hr", "I");
            jfieldID spo2Field = env->GetFieldID(additionalDataClass, "spo2", "I");
            jfieldID tempField = env->GetFieldID(additionalDataClass, "temperature", "F");
            
            if (hrField != nullptr) env->SetIntField(additionalData, hrField, sensorData.additional.hr);
            if (spo2Field != nullptr) env->SetIntField(additionalData, spo2Field, sensorData.additional.spo2);
            if (tempField != nullptr) env->SetFloatField(additionalData, tempField, sensorData.additional.temperature);
            
            env->SetObjectField(javaSensorData, additionalDataField, additionalData);
        }
    }
    
    return javaSensorData;
}

// JNI辅助函数：将C++的vector<SensorData>转换为Java的List
jobject convertSensorDataVectorToJavaList(JNIEnv* env, const std::vector<SensorData>& sensorDataVector) {
    // 创建ArrayList
    jclass arrayListClass = env->FindClass("java/util/ArrayList");
    if (arrayListClass == nullptr) {
        __android_log_print(ANDROID_LOG_ERROR, "DataParser", "Cannot find ArrayList class");
        return nullptr;
    }
    
    jmethodID arrayListConstructor = env->GetMethodID(arrayListClass, "<init>", "()V");
    jmethodID addMethod = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z");
    
    if (arrayListConstructor == nullptr || addMethod == nullptr) {
        __android_log_print(ANDROID_LOG_ERROR, "DataParser", "Cannot find ArrayList methods");
        return nullptr;
    }
    
    jobject resultList = env->NewObject(arrayListClass, arrayListConstructor);
    
    // 添加每个SensorData对象
    for (const auto& sensorData : sensorDataVector) {
        jobject javaSensorData = convertSensorDataToJava(env, sensorData);
        if (javaSensorData != nullptr) {
            env->CallBooleanMethod(resultList, addMethod, javaSensorData);
        }
    }
    
    return resultList;
}

