#include "CANClient.h"

#include <QDateTime>
#include <QDebug>
#include <QTimer>
#include <QByteArray>
#include <QString>
#include <QUuid>
#include <QEventLoop>

// ============ CAN通讯日志开关 ============
// 取消下面的注释可以禁用CAN日志
// #define CAN_LOG_DISABLED
#ifdef CAN_LOG_DISABLED
#undef qDebug
#undef qInfo
#undef qWarning
#undef qCritical
#define qDebug() QNoDebug()
#define qInfo() QNoDebug()
#define qWarning() QNoDebug()
#define qCritical() QNoDebug()
#endif
// ========================================

#define CAN_SLEEP_TIME 50

// 十六进制转字符串
std::string hexToString(uint8_t hex) {
    return QString("%1").arg(hex, 2, 16, QChar('0')).toUpper().toStdString();
}

// 十六进制转字符串（重载）
std::string hexToString(uint16_t hex) {
    return QString("%1").arg(hex, 4, 16, QChar('0')).toUpper().toStdString();
}

// ============ CAN接口配置模式选择 ============
// 根据你的环境选择一种模式（取消注释对应的define）
//
// 模式1: CAN-USB适配器（本地开发，如CANable、PEAK-USB等）
//        使用前需在终端执行：
//        SLCAN类型: sudo slcand -o -c -s8 /dev/ttyACM0 can0 && sudo ip link set up can0
//        原生类型:  sudo ip link set can0 type can bitrate 1000000 && sudo ip link set up can0
// #define CAN_MODE_USB_ADAPTER

// 模式2: 虚拟CAN（无硬件纯软件测试）
//        使用前需执行: sudo modprobe vcan && sudo ip link add dev can0 type vcan && sudo ip link set up can0
//#define CAN_MODE_VIRTUAL

// 模式3: 物理CAN（生产环境，板载CAN控制器）
 #define CAN_MODE_PHYSICAL
// ============================================

CANReturnKeyDevices CANClient::returnDevicesInfo;

CANClient::CANClient(QObject *parent)
    : QThread(parent)
{
    qWarning() << "========== CANClient 构造函数开始 ==========";
    
#if defined(CAN_MODE_VIRTUAL)
    qInfo() << "[CAN] 模式: 虚拟CAN (软件测试)";
    // 虚拟CAN不需要额外配置，假设已在终端创建好vcan接口
#elif defined(CAN_MODE_USB_ADAPTER)
    qInfo() << "[CAN] 模式: CAN-USB适配器 (本地开发)";
    // CAN-USB适配器：假设已通过slcand或驱动配置好can0接口
    // 仅尝试启动接口（如果尚未启动）
    system("ip link set can0 up 2>/dev/null");
#elif defined(CAN_MODE_PHYSICAL)
    qInfo() << "[CAN] 模式: 物理CAN (生产环境)";
    // 物理CAN：需要完整配置
    system("ifconfig can0 down");
    system("ip link set up can0 type can bitrate 1000000 restart-ms 100");
#else
    qWarning() << "[CAN] 警告: 未选择CAN模式，使用默认物理CAN配置";
    system("ifconfig can0 down");
    system("ip link set up can0 type can bitrate 1000000 restart-ms 100");
#endif

    // 初始化插件
    pluginItemInit();
    // 初始化比特率和设备
    bitrateItemInit();

    connectDevice();

//    m_readControlTimer = new QTimer(this);
//    m_readControlTimer->setInterval(300);
//    connect(m_readControlTimer, &QTimer::timeout, this, [this]() {
//        readKeyBaseControlStatusAsync();
//        msleep(CAN_SLEEP_TIME);
//        readLockControlStatusAsync();
//        msleep(CAN_SLEEP_TIME);
//    });
//    m_readControlTimer->start();

//    m_readStatusTimer = new QTimer(this);
//    m_readStatusTimer->setInterval(200);
//    connect(m_readStatusTimer, &QTimer::timeout, this, [this]() {
//        readKeyRFIDStatusAsync();
//        msleep(CAN_SLEEP_TIME);
//        readLockRFIDStatusAsync();
//        msleep(CAN_SLEEP_TIME);
//        readKeyBaseStatusAsync();
//        msleep(CAN_SLEEP_TIME);
//        readLockStatusAsync();
//        msleep(CAN_SLEEP_TIME);
//    });
//    m_readStatusTimer->start();

    connect(this, &CANClient::workingKeyChanged, this, &CANClient::slotWorkingKeyChanged);
    connect(this, &CANClient::workingLocksChanged, this, &CANClient::slotWorkingLocksChanged);

    connect(this, &CANClient::keyBaseStatusRead, this, &CANClient::slotUpdateKeyBaseStatus);
    connect(this, &CANClient::keyBaseControlStatusRead, this, &CANClient::slotUpdateKeyBaseControl);
    connect(this, &CANClient::lockControlStatusRead, this, &CANClient::slotUpdateLockedStatus);
}

CANClient::~CANClient()
{
    // 停止线程并释放资源
    stopThreadAndRelease();
    if (m_CanDevice) {
        // 断开信号槽连接
        disconnect(m_CanDevice, &QCanBusDevice::framesReceived, this, &CANClient::receivedFrames);
        if (m_CanDevice->state() == QCanBusDevice::ConnectedState) {
            m_CanDevice->disconnectDevice();
        }
        delete m_CanDevice;
        m_CanDevice = nullptr;
    }
}

void CANClient::connectDevice()
{
    qInfo() << "[CAN] connectDevice() 开始连接...";
    qInfo() << "[CAN] 插件:" << m_pluginsName << "接口:" << m_canInterfaceName;
    
    QMutexLocker locker(&m_mutex);
    if (!m_CanDevice) {
        qCritical() << "[CAN] 设备实例为空，无法执行连接/断开操作！";
        return;
    }

    if (!m_canBusStatus) {
        // 连接CAN设备
        if (!m_CanDevice->connectDevice()) {
            qCritical() << "[CAN] 打开CAN设备失败！原因：" << m_CanDevice->errorString();
            emit signalCanBusStatusChanged(false);
            return;
        }

        qInfo() << "[CAN] ✓ 设备连接成功！接口:" << m_canInterfaceName;

        // 连接信号槽（避免重复连接）
        disconnect(m_CanDevice, &QCanBusDevice::framesReceived, this, &CANClient::receivedFrames);
        connect(m_CanDevice, &QCanBusDevice::framesReceived, this, &CANClient::receivedFrames);

        disconnect(m_CanDevice, &QCanBusDevice::errorOccurred, this, &CANClient::canDeviceErrors);
        connect(m_CanDevice, &QCanBusDevice::errorOccurred, this, &CANClient::canDeviceErrors);

        m_canBusStatus = true;
        emit signalCanBusStatusChanged(true);
    }
    else {
        // 断开CAN设备
        m_CanDevice->disconnectDevice();
        m_canBusStatus = false;
        qInfo() << "CAN设备已断开连接！设备名：" << m_canInterfaceName;
        emit signalCanBusStatusChanged(false);
    }
}

void CANClient::run()
{
    qInfo() << "CAN监听线程启动！";

    while (m_threadstatus) {
        for (int i = 0; i < 10; i++) {
            readDeviceInfoAsync(i);
            msleep(CAN_SLEEP_TIME);
        }
        readKeyBaseStatusAsync();
        msleep(CAN_SLEEP_TIME);
        readLockStatusAsync();
        msleep(CAN_SLEEP_TIME);

        readKeyBaseControlStatusAsync();
        msleep(CAN_SLEEP_TIME);
        readLockControlStatusAsync();
        msleep(CAN_SLEEP_TIME);

        readKeyRFIDStatusAsync();
        msleep(CAN_SLEEP_TIME);
        readLockRFIDStatusAsync();
        msleep(CAN_SLEEP_TIME);
    }
    qInfo() << "CAN监听线程退出！";
}

void CANClient::pluginItemInit()
{
    // 获取系统中所有QCanBus插件
    m_canBusPlugins = QCanBus::instance()->plugins();
    if (!m_canBusPlugins.contains(m_pluginsName)) {
        qCritical() << "未找到指定的CAN插件：" << m_pluginsName
                    << "，可用插件：" << m_canBusPlugins;
        return;
    }
    qInfo() << "已加载CAN插件列表：" << m_canBusPlugins;

    // 获取指定插件的可用设备接口
    m_canBusInterfaces = QCanBus::instance()->availableDevices(m_pluginsName);
    qInfo() << "可用CAN设备接口数量：" << m_canBusInterfaces.count();
}

void CANClient::bitrateItemInit()
{
    qWarning() << "[CAN] bitrateItemInit() 开始";
    
    // 选择第一个可用的CAN接口，无则使用默认can0
    if (!m_canBusInterfaces.isEmpty()) {
        m_canInterfaceName = m_canBusInterfaces.first().name();
        qWarning() << "[CAN] 使用检测到的接口:" << m_canInterfaceName;
    }
    else {
        qWarning() << "[CAN] 无可用CAN设备接口，使用默认接口：" << m_canInterfaceName;
    }

    // 创建CAN设备实例
    if (m_CanDevice) { // 避免重复创建
        delete m_CanDevice;
        m_CanDevice = nullptr;
    }
    
    qInfo() << "[CAN] 创建设备实例，插件:" << m_pluginsName << "接口:" << m_canInterfaceName;
    
    QString errorString;
    m_CanDevice = QCanBus::instance()->createDevice(m_pluginsName, m_canInterfaceName, &errorString);
    if (!m_CanDevice) {
        qCritical() << "[CAN] 创建设备实例失败！插件：" << m_pluginsName
                    << "，接口：" << m_canInterfaceName
                    << "，错误：" << errorString;
        return;
    }
    
    qInfo() << "[CAN] ✓ 设备实例创建成功";

    // 配置CAN设备参数
#if defined(CAN_MODE_VIRTUAL)
    // 虚拟CAN不需要设置比特率
    qInfo() << "[CAN] 虚拟CAN模式，跳过比特率设置";
#else
    // 物理CAN需要设置比特率
    m_CanDevice->setConfigurationParameter(QCanBusDevice::BitRateKey, m_bitrate);
#endif
    m_CanDevice->setConfigurationParameter(QCanBusDevice::LoopbackKey, false);       // 关闭回环
    m_CanDevice->setConfigurationParameter(QCanBusDevice::ReceiveOwnKey, false);    // 不接收自己发送的帧
}

void CANClient::receivedFrames()
{
//    qDebug() << "[CAN] receivedFrames() 被调用";
    QMutexLocker locker(&m_mutex);
    if (!m_CanDevice || m_CanDevice->state() == QCanBusDevice::UnconnectedState) {
        return;
    }

    // 异步读取所有帧，无阻塞
    while (m_CanDevice && m_CanDevice->framesAvailable()) {
        QCanBusFrame respFrame = m_CanDevice->readFrame();
        // ========== 检测设备主动上报的NFC数据（归还流程） ==========
        // 当CAN设备检测到钥匙/锁插入时，会主动发送包含NFC卡号的帧
//        handleDeviceInsertionFrame(respFrame);
        // =========================================================
        // 匹配请求并执行回调
        QMutexLocker reqLocker(&m_requestMutex);
        if (!m_requestMap.isEmpty()) {
            QString realRequestKey;
            for (auto iter = m_requestMap.begin(); iter != m_requestMap.end(); ++iter) {
                QString requestKey = iter.key();
                QList<QString> requestInfo = requestKey.split("_");
                if (requestInfo.length() < 3) {
                    continue;
                }
                bool ok;
                quint16 sendFrameId = requestInfo[1].toInt(&ok, 16);
                QByteArray sendPayloadIndex = QByteArray::fromHex(requestInfo[2].toLatin1());
                if (sendFrameId - CAN_SDO_SEND_IDENTIFIER_HEADER == respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER &&
                        sendPayloadIndex.toHex().toUpper() == respFrame.payload().mid(1, 3).toHex().toUpper()) {
                    realRequestKey = requestKey;
                    break;
                }
            }
            if (!realRequestKey.isEmpty()) {
                CANResponseCallback callback = m_requestMap.take(realRequestKey);
                // 异步执行回调
                QMetaObject::invokeMethod(this, [=]() {
                    callback(respFrame);
                }, Qt::QueuedConnection);
            }
        }
    }
}

void CANClient::canDeviceErrors(QCanBusDevice::CanBusError error) const
{
    Q_UNUSED(error);
    if (m_CanDevice) {
        qCritical() << "CAN设备错误：" << m_CanDevice->errorString()
                    << "错误类型：" << static_cast<int>(error);
    }
}

void CANClient::handleDeviceInsertionFrame(const QCanBusFrame& frame)
{
    // ========== 检测设备主动上报的NFC数据 ==========
    // 
    // TODO: 根据实际CAN协议调整帧ID和数据格式
    // 当前假设设备会发送包含NFC卡号的PDO帧
    //
    // 常见的帧格式（需根据实际设备协议确认）：
    // - 帧ID: 0x180 + NodeID (TPDO1) 或自定义ID
    // - 数据: [设备类型, 插槽, NFC卡号(4字节)]
    //
    // 调试时可以打开下面的日志查看收到的帧
    // ================================================
    
    if (!frame.isValid()) return;
    
    quint32 frameId = frame.frameId();
    QByteArray payload = frame.payload();
    
    // 调试日志：显示所有收到的CAN帧
    qDebug() << "[CAN收帧] ID:" << QString("0x%1").arg(frameId, 3, 16, QChar('0'))
             << "Data:" << payload.toHex().toUpper();
    
    // ========== 方案1: 检测SDO响应中的NFC数据 ==========
    // 当收到包含NFC索引的SDO响应时触发
    if (frameId >= 0x581 && frameId <= 0x5FF && payload.length() >= 8) {
        quint8 cmd = static_cast<quint8>(payload[0]);
        quint16 index = static_cast<quint16>(static_cast<uint8_t>(payload[1])) |
                        (static_cast<quint16>(static_cast<uint8_t>(payload[2])) << 8);
        quint8 subIndex = static_cast<quint8>(payload[3]);
        
        qDebug() << "[CAN解析] cmd:" << QString("0x%1").arg(cmd, 2, 16, QChar('0'))
                 << "index:" << QString("0x%1").arg(index, 4, 16, QChar('0'))
                 << "subIndex:" << subIndex;
        
        // 检测钥匙NFC数据 (索引 0x6020=左钥匙, 0x6024=右钥匙)
        if ((index == 0x6020 || index == 0x6024) && (cmd == 0x43 || cmd == 0x4B || cmd == 0x4F)) {
            QByteArray nfcData = payload.mid(4, 4);
            QString nfcId = parseRFIDCard(nfcData);
            
            if (!nfcId.isEmpty() && nfcId != "00000000") {
                int slotIndex = (index == 0x6020) ? 0 : 1;  // 左=0, 右=1
                qInfo() << "[归还检测-CAN帧] 检测到钥匙NFC:" << nfcId << "插槽:" << slotIndex;
                emit nfcDeviceDetected(nfcId, "key", slotIndex);
            }
        }
        
        // 检测锁NFC数据 (索引 0x60F0-0x60F4 或根据实际协议)
        if (index >= 0x60F0 && index <= 0x60F4 && (cmd == 0x43 || cmd == 0x4B || cmd == 0x4F)) {
            QByteArray nfcData = payload.mid(4, 4);
            QString nfcId = parseRFIDCard(nfcData);
            
            if (!nfcId.isEmpty() && nfcId != "00000000") {
                int slotIndex = index - 0x60F0;  // 0-4号锁
                qInfo() << "[归还检测-CAN帧] 检测到锁NFC:" << nfcId << "插槽:" << slotIndex;
                emit nfcDeviceDetected(nfcId, "lock", slotIndex);
            }
        }
    }
    
    // ========== 方案2: 检测自定义PDO帧（根据实际协议调整） ==========
    // 如果设备使用自定义帧ID上报，在这里添加检测逻辑
    // 例如: 帧ID = 0x200 表示钥匙插入事件
    //
    // if (frameId == 0x200 && payload.length() >= 5) {
    //     quint8 deviceType = static_cast<quint8>(payload[0]);  // 0=钥匙, 1=锁
    //     quint8 slotIndex = static_cast<quint8>(payload[1]);
    //     QByteArray nfcData = payload.mid(2, 4);
    //     QString nfcId = parseRFIDCard(nfcData);
    //     
    //     if (!nfcId.isEmpty() && nfcId != "00000000") {
    //         QString type = (deviceType == 0) ? "key" : "lock";
    //         qInfo() << "[归还检测-PDO] 设备插入:" << type << "插槽:" << slotIndex << "NFC:" << nfcId;
    //         emit nfcDeviceDetected(nfcId, type, slotIndex);
    //     }
    // }
}

void CANClient::slotUpdateKeyBaseStatus(quint8 nodeId, const CANKeyBaseStatus &status)
{
    if (!status.success) return;

    QMutexLocker locker(&m_insertDataMutex);

    if (m_keyBaseStatus.find(nodeId) == m_keyBaseStatus.end()) {
        m_keyBaseStatus.insert(nodeId, status);
    }
    else {
        m_keyBaseStatus[nodeId] = status;
    }
}

void CANClient::slotUpdateKeyBaseControl(quint8 nodeId, const CANKeyBaseControlStatus &status)
{
    if (!status.success) return;

    QMutexLocker locker(&m_insertDataMutex);
    m_keyBaseControlStatus.insert(nodeId, status);

    if (m_keyBaseStatus.find(nodeId) == m_keyBaseStatus.end()) return;

    bool isWrite = false;
    CANKeyBaseChargeStatus writeStatus;

    if (m_keyBaseStatus[nodeId].leftHasKey && !status.leftLocked) {
        writeStatus.leftLocked = true;
        writeStatus.leftWorking = true;
        writeStatus.leftChargeEnable = true;
        writeStatus.leftChargeState = ChargeState::Charging;
        isWrite = true;

        if (m_keyRFIDStatus.find(nodeId) != m_keyRFIDStatus.end()) {
            QString rightKeyRFID = m_keyRFIDStatus[nodeId].rightKeyRFID;
            returnDevicesInfo.keysMap.insert(rightKeyRFID, nodeId);
            emit signalReturnKey();
        }
    }
//    else if (!m_keyBaseStatus[nodeId].leftHasKey && status.leftLocked) {
//        writeStatus.leftLocked = false;
//        writeStatus.leftWorking = true;
//        writeStatus.leftChargeEnable = false;
//        writeStatus.leftChargeState = ChargeState::Charging;
//        isWrite = true;
//    }
    if (m_keyBaseStatus[nodeId].rightHasKey && !status.rightLocked) {
        writeStatus.rightLocked = true;
        writeStatus.rightWorking = true;
        writeStatus.rightChargeEnable = true;
        writeStatus.rightChargeState = ChargeState::Charging;
        isWrite = true;

        if (m_keyRFIDStatus.find(nodeId) != m_keyRFIDStatus.end()) {
            QString rightKeyRFID = m_keyRFIDStatus[nodeId].rightKeyRFID;
            returnDevicesInfo.keysMap.insert(rightKeyRFID, nodeId);
            emit signalReturnKey();
        }
    }
//    else if (!m_keyBaseStatus[nodeId].rightHasKey && status.rightLocked) {
//        writeStatus.rightLocked = false;
//        writeStatus.rightWorking = true;
//        writeStatus.rightChargeEnable = false;
//        writeStatus.rightChargeState = ChargeState::Charging;
//        isWrite = true;
//    }

    if (isWrite) {
        writeKeyBaseChargeControlAsync(writeStatus);
        msleep(CAN_SLEEP_TIME);
    }
}

void CANClient::slotUpdateLockedStatus(quint8 nodeId, const CANLocksControl &status)
{
    if (!status.success) return;

    QMutexLocker locker(&m_insertDataMutex);
    m_locksControl.insert(nodeId, status);
    if (m_locksControlStatus.find(nodeId) == m_locksControlStatus.end()) return;

    bool isWrite = false;
    CANLocksControl writeStatus;
    for (int i = 0; i < status.lockNums.length(); i++) {
        int lockNum = status.lockNums[i];
        QMap<int, bool> lockHasKeyMap = m_locksControlStatus[nodeId].lockHasKeyMap;
        QMap<int, bool> lockLockedMap = status.lockLockedMap;
        if ((lockHasKeyMap.find(lockNum) != lockHasKeyMap.end() && lockHasKeyMap[lockNum]) &&
                (lockLockedMap.find(lockNum) != lockLockedMap.end() && !lockLockedMap[lockNum])) {
            writeStatus.lockNums.append(lockNum);
            writeStatus.lockLockedMap.insert(lockNum, true);
            writeStatus.lockWorkMap.insert(lockNum, true);
            isWrite = true;

            if (m_locksRFIDStatus.find(nodeId) != m_locksRFIDStatus.end()) {
                QMap<int, QString> lockRFIDInfo = m_locksRFIDStatus[nodeId].lockRFIDMap;
                if (lockRFIDInfo.find(lockNum) != lockRFIDInfo.end()) {
                    returnDevicesInfo.locksMap.insert(lockRFIDInfo[lockNum], nodeId);
                    emit signalReturnKey();
                }
            }
        }
//        else if ((lockHasKeyMap.find(lockNum) != lockHasKeyMap.end() && !lockHasKeyMap[lockNum]) &&
//                 (lockLockedMap.find(lockNum) != lockLockedMap.end() && lockLockedMap[lockNum])) {
//            writeStatus.lockNums.append(lockNum);
//            writeStatus.lockLockedMap.insert(lockNum, false);
//            writeStatus.lockWorkMap.insert(lockNum, true);
//            isWrite = true;
//        }
    }
    if (isWrite) {
        writeLockBuckleAsync(writeStatus);
        msleep(CAN_SLEEP_TIME);
    }
}

void CANClient::slotWorkingKeyChanged()
{
    if (m_workingKey) {
        disconnect(this, &CANClient::keyBaseControlStatusRead, this, &CANClient::slotUpdateKeyBaseControl);
    }
    else {
        connect(this, &CANClient::keyBaseControlStatusRead, this, &CANClient::slotUpdateKeyBaseControl);
    }
}

void CANClient::slotWorkingLocksChanged()
{
    if (m_workingLocks) {
        disconnect(this, &CANClient::lockControlStatusRead, this, &CANClient::slotUpdateLockedStatus);
    }
    else {
        connect(this, &CANClient::lockControlStatusRead, this, &CANClient::slotUpdateLockedStatus);
    }
}

void CANClient::stopThreadAndRelease()
{
    // 停止线程循环
    m_threadstatus = false;
    wait(); // 等待线程退出

    // 释放CAN设备资源
    QMutexLocker locker(&m_mutex);
    if (m_CanDevice) {
        if (m_CanDevice->state() == QCanBusDevice::ConnectedState) {
            m_CanDevice->disconnectDevice();
        }
        delete m_CanDevice;
        m_CanDevice = nullptr;
    }
    m_canBusStatus = false;
}

void CANClient::sendFrameAsync(const QCanBusFrame& frame, CANResponseCallback callback)
{
    QMutexLocker locker(&m_mutex);
    if (!m_CanDevice || m_CanDevice->state() == QCanBusDevice::UnconnectedState) {
        qWarning() << "[Send] CAN设备未连接";
        // 回调返回空帧表示失败
        callback(QCanBusFrame());
        return;
    }

    // 生成唯一请求ID，绑定回调
    QUuid requestId = QUuid::createUuid();
    QMutexLocker reqLocker(&m_requestMutex);
    QString strFramId = QString::number(frame.frameId(), 16);
    QString strPayload = QString::fromUtf8(frame.payload().mid(1, 3).toHex().toUpper());
    QString requestKey = requestId.toString() + "_" + strFramId + "_" + strPayload;
    m_requestMap.insert(requestKey, callback);

    // 发送帧（异步，无阻塞）
    if (!m_CanDevice->writeFrame(frame)) {
        qWarning() << "[Send] 发送失败：" << m_CanDevice->errorString() << QString::number(frame.frameId(), 16) << frame.payload().toHex().toUpper();
        m_requestMap.remove(requestKey);
        callback(QCanBusFrame());
        return;
    }

    // 存储帧ID和请求ID的映射
    Q_UNUSED(requestId);
}

QCanBusFrame CANClient::buildReadFrame(quint8 nodeId, quint16 index, quint8 subIndex)
{
    // SDO读报文结构：BYTE0=子索引，BYTE1-2=对象索引（小端），BYTE3=命令字，BYTE4-7=0
    QByteArray payload(8, 0x00);
    payload[0] = CAN_SDO_READ_SEND_BYTE;
    payload[1] = static_cast<uint8_t>(index & 0xFF);         // 索引低字节（小端）
    payload[2] = static_cast<uint8_t>((index >> 8) & 0xFF); // 索引高字节（小端）
    payload[3] = subIndex;

    quint32 frameId = CAN_SDO_SEND_IDENTIFIER_HEADER + nodeId;
    QCanBusFrame frame(frameId, payload);
    frame.setFrameType(QCanBusFrame::DataFrame); // 数据帧
    frame.setExtendedFrameFormat(false);
    frame.setLocalEcho(true);
    frame.setTimeStamp(QDateTime::currentMSecsSinceEpoch());

//    qDebug() << "发送Read-CAN帧 FrameId: 0x" << QString::number(frameId, 16) << "Data：" << payload.toHex().toUpper();

    return frame;
}

QCanBusFrame CANClient::buildWriteFrame(quint8 nodeId, quint16 index, quint8 subIndex, const QByteArray& data, quint8 byteCount)
{
    // SDO写报文结构：BYTE0=子索引，BYTE1-2=对象索引（小端），BYTE3=命令字，BYTE4-7=数据（小端）
    QByteArray payload(8, 0x00);
    payload[1] = static_cast<uint8_t>(index & 0xFF);         // 索引低字节（小端）
    payload[2] = static_cast<uint8_t>((index >> 8) & 0xFF); // 索引高字节（小端）
    payload[3] = subIndex;

    if (byteCount == 0) {
        // 根据数据长度设置命令字
        if (data.length() == 1) payload[0] = CAN_SDO_WRITE_SEND_BYTE_1;
        else if (data.length() == 2) payload[0] = CAN_SDO_WRITE_SEND_BYTE_2;
        else if (data.length() == 4) payload[0] = CAN_SDO_WRITE_SEND_BYTE_4;
        else {
            qWarning() << "[Build Write Frame] 数据长度不支持（仅1/2/4字节）";
            return QCanBusFrame();
        }
    }
    else {
        if (byteCount == 1) payload[0] = CAN_SDO_WRITE_SEND_BYTE_1;
        else if (byteCount == 2) payload[0] = CAN_SDO_WRITE_SEND_BYTE_2;
        else if (byteCount == 4) payload[0] = CAN_SDO_WRITE_SEND_BYTE_4;
        else {
            qWarning() << "[Build Write Frame] 数据长度不支持（仅1/2/4字节）";
            return QCanBusFrame();
        }
    }

    // 填充数据（小端模式）
    memcpy(payload.data() + 4, data.data(), data.length());

    // 帧ID：SDO_TX_ID=0x600+Node_ID
    quint32 frameId = CAN_SDO_SEND_IDENTIFIER_HEADER + nodeId;
    QCanBusFrame frame(frameId, payload);
    frame.setFrameType(QCanBusFrame::DataFrame);
    frame.setExtendedFrameFormat(false);
    frame.setLocalEcho(true);
    frame.setTimeStamp(QDateTime::currentMSecsSinceEpoch());

//    qDebug() << "发送Write-CAN帧 FrameId: 0x" << QString::number(frameId, 16) << "Data：" << payload.toHex().toUpper();

    return frame;
}

quint16 CANClient::parseLittleEndian16(const QByteArray& data)
{
    if (data.length() < 2) return 0;
    return (static_cast<quint16>(static_cast<uint8_t>(data[1])) << 8) | static_cast<uint8_t>(data[0]);
}

quint32 CANClient::parseLittleEndian32(const QByteArray& data)
{
    if (data.length() < 4) return 0;
    return (static_cast<quint32>(static_cast<uint8_t>(data[3])) << 24)
         | (static_cast<quint32>(static_cast<uint8_t>(data[2])) << 16)
         | (static_cast<quint32>(static_cast<uint8_t>(data[1])) << 8)
         | static_cast<uint8_t>(data[0]);
}

double CANClient::parseTemperature(const QByteArray& data)
{
    if (data.length() < 4) return 0.0;
    // 左温度（bit0-15），右温度（bit16-31）
    qint16 tempLeft = static_cast<qint16>((static_cast<uint8_t>(data[1]) << 8) | static_cast<uint8_t>(data[0]));
    qint16 tempRight = static_cast<qint16>((static_cast<uint8_t>(data[3]) << 8) | static_cast<uint8_t>(data[2]));
    qInfo() << "[Temperature] 左：" << tempLeft / 10.0 << "℃，右：" << tempRight / 10.0 << "℃";
    return tempLeft / 10.0;
}

double CANClient::parseHumidity(const QByteArray& data)
{
    if (data.length() < 2) return 0.0;
    quint16 humi = parseLittleEndian16(data);
    double result = humi / 10.0;
    qInfo() << "[Humidity] " << result << "%";
    return result;
}

QString CANClient::parseRFIDCard(const QByteArray& data)
{
    if (data.length() < 4) return "";
    quint32 cardNum = parseLittleEndian32(data);
    QString cardStr = QString("%1").arg(cardNum, 8, 16, QChar('0')).toUpper();
    return cardStr;
}

bool CANClient::verifyNodeID(quint8 deviceNodeId, quint8& returnNodeId)
{
    if (!m_deviceOfNodeId.values().contains(deviceNodeId)) {
        return false;
    }

    quint8 nodeId = 0;
    for (auto iter = m_deviceOfNodeId.begin(); iter != m_deviceOfNodeId.end(); ++iter) {
        if (iter.value() == deviceNodeId) {
            nodeId = iter.key();
            break;
        }
    }
    returnNodeId = nodeId;
    return true;
}

bool CANClient::checkLockNumValid(int lockNum)
{
    if (lockNum < 0 || lockNum > 4) {
        qWarning() << "[Check] 无效锁扣编号：" << lockNum << "（仅支持1-5号）";
        return false;
    }
    return true;
}

bool CANClient::checkRGBChannelValid(int channel)
{
    if (channel < 1 || channel > 4) {
        qWarning() << "[Check] 无效RGB通道：" << channel << "（仅支持1-4路）";
        return false;
    }
    return true;
}

bool CANClient::checkBrightnessValid(int bright)
{
    if (bright < 0 || bright > 100) {
        qWarning() << "[Check] 无效亮度值：" << bright << "（仅支持0-100）";
        return false;
    }
    return true;
}

void CANClient::readDeviceInfoAsync(quint8 nodeId)
{
    QCanBusFrame frame = buildReadFrame(nodeId, CAN_DEVICE_INDEX, CAN_DEVICE_SUBINDEX);

    sendFrameAsync(frame, [this, nodeId](const QCanBusFrame& respFrame) {
        quint16 deviceTypeCode = 0;
        bool success = false;

        // 响应有效性校验
        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_DEVICE_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_DEVICE_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            // 校验响应命令字（4字节读成功：0x43）
            uint8_t respCmd = static_cast<uint8_t>(respFrame.payload()[0]);
            if (respCmd != CAN_SDO_READ_RECEIVE_BYTE_2) {
                qWarning() << "[DeviceType] 响应命令字错误：0x" << QString::number(respCmd, 16);
                emit deviceInfoRead(false, nodeId);
                return;
            }
            QByteArray data = respFrame.payload().mid(4, CAN_DEVICE_BYTE_COUNT);
            deviceTypeCode = parseLittleEndian16(data);

            quint8 nodeId = respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER;
//            QMutexLocker locker(&m_frameNodeIdMutex);
            // 设备类型码映射
            switch (deviceTypeCode) {
                case CAN_DEVICE_EKEY_NODEID:
                    m_deviceOfNodeId[nodeId] = CAN_DEVICE_EKEY_NODEID;
                    break;
                case CAN_DEVICE_LOCK_NODEID:
                    m_deviceOfNodeId[nodeId] = CAN_DEVICE_LOCK_NODEID;
                    break;
                case CAN_DEVICE_CKEY_NODEID:
                     m_deviceOfNodeId[nodeId] = CAN_DEVICE_CKEY_NODEID;
                    break;
                case CAN_DEVICE_CABINET_NODEID:
                     m_deviceOfNodeId[nodeId] = CAN_DEVICE_CABINET_NODEID;
                    break;
                case CAN_DEVICE_FOUR_LIGHT_NODEID:
                     m_deviceOfNodeId[nodeId] = CAN_DEVICE_FOUR_LIGHT_NODEID;
                    break;
                default:
                    break;
            }

            success = true;
//            qInfo() << "[DeviceType] 读取成功：类型=" << nodeId << "，编码=0x" << QString::number(deviceTypeCode, 16).toUpper();
        }
        else {
            qWarning() << "[DeviceType] 读取失败：无有效响应";
        }
        quint8 successNodeId = respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER;
        // 发射信号返回结果（异步回调）
        emit deviceInfoRead(success, successNodeId);
    });
}

void CANClient::readKeyBaseStatusAsync()
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_EKEY_NODEID, nodeId)) {
        CANKeyBaseStatus emptyStatus;
        emit keyBaseStatusRead(nodeId, emptyStatus);
        return;
    }

    QCanBusFrame frame = buildReadFrame(nodeId, CAN_EKEY_STATUS_INDEX, CAN_EKEY_STATUS_SUBINDEX);
//    qDebug() << "发送readKeyBaseStatusAsync帧 FrameId: 0x" << QString::number(frame.frameId(), 16) << "Data：" << frame.payload().toHex().toUpper();
    sendFrameAsync(frame, [this, nodeId](const QCanBusFrame& respFrame) {
        CANKeyBaseStatus status;

        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_EKEY_STATUS_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_EKEY_STATUS_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, CAN_EKEY_STATUS_BYTE_COUNT);
            uint8_t leftByte = static_cast<uint8_t>(data[0]);
            uint8_t rightByte = static_cast<uint8_t>(data[1]);

            status.leftHasKey = (leftByte & 0x01) != 0;
            status.leftCharging = (leftByte & 0x02) != 0;
            status.rightHasKey = (rightByte & 0x01) != 0;
            status.rightCharging = (rightByte & 0x02) != 0;
//            qDebug() << respFrame.payload().toHex();
            status.success = true;

//            qInfo() << "[KeyBase] 左钥匙：" << (status.leftHasKey ? "有" : "无")
//                    << "，左充电：" << (status.leftCharging ? "充电中" : "未充电")
//                    << "; 右钥匙：" << (status.rightHasKey ? "有" : "无")
//                    << "，右充电：" << (status.rightCharging ? "充电中" : "未充电");
            QMutexLocker locker(&m_insertDataMutex);

//            bool prevLeftHasKey = false, prevRightHasKey = false;
//            if (m_keyBaseStatus.find(nodeId) != m_keyBaseStatus.end()) {
//                prevLeftHasKey = m_keyBaseStatus[nodeId].leftHasKey;
//                prevRightHasKey = m_keyBaseStatus[nodeId].rightHasKey;
//            }

//            if (!m_keyBaseStatus.isEmpty()) {
//                if (!prevLeftHasKey && status.leftHasKey) {
//                    qInfo() << "[归还检测] 检测到左钥匙插入！";

//                    if (m_keyRFIDStatus.find(nodeId) != m_keyRFIDStatus.end() &&
//                        !m_keyRFIDStatus[nodeId].leftKeyRFID.isEmpty() &&
//                        m_keyRFIDStatus[nodeId].leftKeyRFID != "00000000") {
//                        qInfo() << "[归还检测] 左钥匙：NFC卡号:" << m_keyRFIDStatus[nodeId].leftKeyRFID;

////                        emit nfcDeviceDetected(m_keyRFIDStatus[nodeId].leftKeyRFID, "key", 0);
//                    } else {
//                        qWarning() << "[归还检测] 左钥匙存在但无法读取NFC";
//                        emit nfcDeviceError("key", 0);
//                    }
//                }
//                else if (prevLeftHasKey && !status.leftHasKey) {
//                    qInfo() << "[取出检测] 检测到左钥匙取出！";
//                    if (m_keyRFIDStatus.find(nodeId) != m_keyRFIDStatus.end() &&
//                        !m_keyRFIDStatus[nodeId].leftKeyRFID.isEmpty() &&
//                        m_keyRFIDStatus[nodeId].leftKeyRFID != "00000000") {
//                        qInfo() << "[取出检测] 左钥匙：NFC卡号:" << m_keyRFIDStatus[nodeId].leftKeyRFID;

//                        emit signalPopDevices(m_keyRFIDStatus[nodeId].leftKeyRFID, "key", 0);
//                    } else {
//                        qWarning() << "[取出检测] 左钥匙存在但无法读取NFC";
//                        emit nfcDeviceError("key", 0);
//                    }
//                }
//            }
        }
        else {
            qWarning() << "[KeyBase] 读取状态失败";
        }

        // 发送结果信号（异步回调）
        emit keyBaseStatusRead(nodeId, status);
    });
}

void CANClient::readKeyBaseControlStatusAsync()
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_EKEY_NODEID, nodeId)) {
        CANKeyBaseControlStatus emptyStatus;
        emit keyBaseControlStatusRead(nodeId, emptyStatus);
        return;
    }

    QCanBusFrame frame = buildReadFrame(nodeId, CAN_FASTENER_CONTROL_INDEX, CAN_FASTENER_CONTROL_SUBINDEX);
    sendFrameAsync(frame, [this, nodeId](const QCanBusFrame& respFrame) {
        CANKeyBaseControlStatus status;

        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_FASTENER_CONTROL_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_FASTENER_CONTROL_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, CAN_CFASTENER_CONTROL_BYTE_COUNT);
            uint8_t statusByte = static_cast<uint8_t>(data[0]);
            uint8_t buckleByte = static_cast<uint8_t>(data[1]);

            // 基础状态
            status.leftLocked = (statusByte & 0x01) != 0;
            status.leftCharging = (statusByte & 0x02) != 0;
            status.rightLocked = (statusByte & 0x10) != 0;
            status.rightCharging = (statusByte & 0x20) != 0;

            // 故障状态
            status.leftBuckleFault = (buckleByte & 0x01) != 0;
            status.rightBuckleFault = (buckleByte & 0x04) != 0;

            status.success = true;

//            bool prevLeftHasKey = false, prevRightHasKey = false;
//            if (m_keyBaseControlStatus.find(nodeId) != m_keyBaseControlStatus.end()) {
//                prevLeftHasKey = m_keyBaseControlStatus[nodeId].leftLocked;
//                prevRightHasKey = m_keyBaseControlStatus[nodeId].rightLocked;
//            }

//            if (!m_keyBaseControlStatus.isEmpty()) {
//                if (!prevLeftHasKey && status.leftLocked) {
//                    qInfo() << "[归还检测] 检测到左钥匙插入！";

//                    if (m_keyRFIDStatus.find(nodeId) != m_keyRFIDStatus.end() &&
//                        !m_keyRFIDStatus[nodeId].leftKeyRFID.isEmpty() &&
//                        m_keyRFIDStatus[nodeId].leftKeyRFID != "00000000") {
//                        qInfo() << "[归还检测] 左钥匙：NFC卡号:" << m_keyRFIDStatus[nodeId].leftKeyRFID;

//                        emit nfcDeviceDetected(m_keyRFIDStatus[nodeId].leftKeyRFID, "key", 0);
//                    } else {
//                        qWarning() << "[归还检测] 左钥匙存在但无法读取NFC";
//                        emit nfcDeviceError("key", 0);
//                    }
//                }
//            }

//            qInfo() << "[KeyBase] 左钥匙：" << (status.leftLocked ? "锁住" : "未锁")
//                    << "，左充电：" << (status.leftCharging ? "充电中" : "未充电") << (status.leftBuckleFault ? "故障" : "正常")
//                    << "; 右钥匙：" << (status.rightLocked ? "锁住" : "未锁")
//                    << "，右充电：" << (status.rightCharging ? "充电中" : "未充电") << (status.rightBuckleFault ? "故障" : "正常");
        }
        else {
            qWarning() << "[KeyBase] 读取状态失败";
        }

        // 发送结果信号（异步回调）
        emit keyBaseControlStatusRead(nodeId, status);
    });
}

void CANClient::readLockStatusAsync()
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_LOCK_NODEID, nodeId)) {
        emit lockStatusRead(nodeId, CANLockControlStatus());
        return;
    }

    // 构建SDO读帧：索引0x6010（锁状态），子索引0x00，1字节数据
    QCanBusFrame frame = buildReadFrame(nodeId, CAN_LOCK_STATUS_INDEX, CAN_LOCK_STATUS_SUBINDEX);

    // 异步发送帧，通过回调处理响应
    sendFrameAsync(frame, [this, nodeId](const QCanBusFrame& respFrame) {
        CANLockControlStatus status;

        // 响应有效性校验
        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_LOCK_STATUS_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_LOCK_STATUS_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.payload()[3]) == CAN_LOCK_STATUS_SUBINDEX &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            // 解析响应数据：BYTE4为状态字节，bit0-4对应1-5号锁
            QByteArray data = respFrame.payload().mid(4, CAN_LOCK_STATUS_BYTE_COUNT);
            uint8_t statusByte = static_cast<uint8_t>(data[0]);

            // 提取1-5号锁的状态（bit0=1号，bit1=2号...bit4=5号）
            for (int i = 0; i < 5; i++) {
                bool hasKey = (statusByte & (0x01 << i)) != 0;
                status.lockNums.append(i);
                status.lockHasKeyMap.insert(i, hasKey);
//                qInfo() << "[Lock] " << (i+1) << "号锁位：" << (hasKey ? "有锁" : "无锁");
            }
//            qDebug() << "FrameId: 0x" << QString::number(respFrame.frameId(), 16) << "Data：" << respFrame.payload().toHex().toUpper();
            status.success = true;
            
//            // ========== 检测锁插入（用于归还流程） ==========
//            QMutexLocker locker(&m_insertDataMutex);
            
//            // 获取之前的锁状态
//            QMap<int, bool> prevLockHasKeyMap;
//            if (m_locksControlStatus.find(nodeId) != m_locksControlStatus.end()) {
//                prevLockHasKeyMap = m_locksControlStatus[nodeId].lockHasKeyMap;
//            }
//            if (!m_locksControlStatus.isEmpty()) {
//                // 检测每个锁位的插入（从无到有）
//                for (int i = 0; i < 5; i++) {
//                    bool prevHasLock = prevLockHasKeyMap.contains(i) ? prevLockHasKeyMap[i] : false;
//                    bool currHasLock = status.lockHasKeyMap.contains(i) ? status.lockHasKeyMap[i] : false;

//                    if (!prevHasLock && currHasLock) {
//                        qInfo() << "[归还检测] 检测到" << (i+1) << "号锁插入！";
//                        // 锁插入，获取NFC卡号
//                        if (m_locksRFIDStatus.find(nodeId) != m_locksRFIDStatus.end() &&
//                            m_locksRFIDStatus[nodeId].lockRFIDMap.contains(i) &&
//                            !m_locksRFIDStatus[nodeId].lockRFIDMap[i].isEmpty() &&
//                            m_locksRFIDStatus[nodeId].lockRFIDMap[i] != "00000000") {
//                            qInfo() << "[归还检测]" << (i+1) << "号锁NFC卡号:" << m_locksRFIDStatus[nodeId].lockRFIDMap[i];

//                            emit nfcDeviceDetected(m_locksRFIDStatus[nodeId].lockRFIDMap[i], "lock", i);
//                            emit signalLockNfcDeviceDetected(m_locksRFIDStatus[nodeId].lockRFIDMap[i]);
//                        } else {
//                            qWarning() << "[归还检测]" << (i+1) << "号锁存在但无法读取NFC";
//                            emit nfcDeviceError("lock", i);
//                        }
//                    }
//                    else if (prevHasLock && !currHasLock) {
//                        qInfo() << "[取出检测] 检测到"  << (i+1) << "号锁取出！";
//                        qDebug() << m_locksRFIDStatus[nodeId].lockRFIDMap[i];
//                        if (m_locksRFIDStatus.find(nodeId) != m_locksRFIDStatus.end() &&
//                            m_locksRFIDStatus[nodeId].lockRFIDMap.contains(i) &&
//                            !m_locksRFIDStatus[nodeId].lockRFIDMap[i].isEmpty() &&
//                            m_locksRFIDStatus[nodeId].lockRFIDMap[i] != "00000000") {
//                            qInfo() << "[取出检测]" << (i+1) << "号锁NFC卡号:" << m_locksRFIDStatus[nodeId].lockRFIDMap[i];

//                            emit signalPopDevices(m_locksRFIDStatus[nodeId].lockRFIDMap[i], "lock", i);
//                        } else {
//                            qWarning() << "[取出检测]" << (i+1) << "号锁存在但无法读取NFC";
//                            emit nfcDeviceError("lock", i);
//                        }
//                    }
//                }
//            }
//            // ====================================================
            
            if (m_locksControlStatus.find(nodeId) == m_locksControlStatus.end()) {
                m_locksControlStatus.insert(nodeId, status);
            }
            else {
                m_locksControlStatus[nodeId] = status;
            }
        }
        else {
            qWarning() << "[Lock] 读取5路锁状态失败：无有效响应";
        }

        // 发射信号返回结果（异步回调，不阻塞）
        emit lockStatusRead(nodeId, status);
    });
}

void CANClient::readLockControlStatusAsync()
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_LOCK_NODEID, nodeId)) {
        emit lockControlStatusRead(nodeId, CANLocksControl());
        return;
    }

    QCanBusFrame frame = buildReadFrame(nodeId, CAN_LOCK_CONTROL_INDEX, CAN_LOCK_CONTROL_SUBINDEX);
    sendFrameAsync(frame, [this, nodeId](const QCanBusFrame& respFrame) {
        CANLocksControl status;

        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_LOCK_CONTROL_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_LOCK_CONTROL_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.payload()[3]) == CAN_LOCK_CONTROL_SUBINDEX &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, CAN_LOCK_CONTROL_BYTE_COUNT);
            uint8_t statusByte = static_cast<uint8_t>(data[0]);
            uint8_t faultByte = static_cast<uint8_t>(data[1]);

            for (int i = 0; i < 5; i++) {
                bool isLocked = (statusByte & (0x01 << i)) != 0;
                status.lockNums.append(i);
                status.lockLockedMap.insert(i, isLocked);
                // 故障状态
                status.lockWorkMap.insert(i, (faultByte & (0x01 << i)) != 0);
//                qInfo() << "[Lock] " << (i+1) << "号锁：是否锁定=" << isLocked << "，故障=" << status.lockWorkMap[i];
            }
            status.success = true;
        }
        else {
            qWarning() << "[Lock] 读取失败：无有效响应";
        }
        emit lockControlStatusRead(nodeId, status);
    });
}

void CANClient::writeSingleLockBuckleAsync(const CANSingleLockStatus& status)
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_LOCK_NODEID, nodeId)) {
        return;
    }

    if (!checkLockNumValid(status.lockNum)) {
        emit lockBuckleWrite(false, status.lockNum, status.isLocked);
        return;
    }

    uint8_t dataByte = 0x00;
    dataByte |= status.isLocked ? (0x01 << status.lockNum) : 0x00;
    QByteArray data;
    data.append(dataByte);

    uint8_t workByte = 0x00;
    workByte |= status.isWorking ? (0x01 << status.lockNum) : 0x00;
    data.append(workByte);

    QCanBusFrame frame = buildWriteFrame(nodeId, CAN_LOCK_CONTROL_INDEX, CAN_LOCK_CONTROL_SUBINDEX, data);
    sendFrameAsync(frame, [this, status, nodeId, frame](const QCanBusFrame& respFrame) {
        uint8_t lowByte = static_cast<uint8_t>(CAN_LOCK_CONTROL_INDEX & 0xFF);         // 索引低字节（小端）
        uint8_t highByte = static_cast<uint8_t>((CAN_LOCK_CONTROL_INDEX >> 8) & 0xFF); // 索引高字节（小端
        if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
              static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
              static_cast<uint8_t>(respFrame.payload()[3]) == CAN_LOCK_CONTROL_SUBINDEX &&
              static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
            return;
        }

        bool success = respFrame.isValid() && static_cast<uint8_t>(respFrame.payload()[0]) == CAN_SDO_WRITE_RECEIVE_BYTE_SUCCESS;
//        qDebug() << "发送Write-CAN帧 FrameId: 0x" << QString::number(frame.frameId(), 16) << "Data：" << frame.payload().toHex().toUpper() << QString::number(respFrame.payload()[0], 16);
        emit lockBuckleWrite(success, status.lockNum, status.isLocked);
        if (success) {
//            qInfo() << "[Lock] " << status.lockNum+1 << "号锁扣：" << (status.isLocked ? "锁住" : "解锁");
        }
        else {
            qWarning() << "[Lock] " << status.lockNum+1 << "号锁扣写入失败";
        }
    });
}

void CANClient::writeLockBuckleAsync(const CANLocksControl &status)
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_LOCK_NODEID, nodeId)) {
        return;
    }

    uint8_t dataByte = 0x00;
    uint8_t workByte = 0x00;

    for (int i = 0 ; i < status.lockNums.length(); i++) {
        int lockNum = status.lockNums[i];
        if (!(status.lockLockedMap.find(lockNum) != status.lockLockedMap.end() &&
              status.lockWorkMap.find(lockNum) != status.lockWorkMap.end())) {
            return;
        }

        dataByte |= status.lockLockedMap[lockNum] ? (0x01 << lockNum) : 0x00;
        workByte |= status.lockWorkMap[lockNum] ? (0x01 << lockNum) : 0x00;
    }
    QByteArray data;
    data.append(dataByte);
    data.append(workByte);

    QCanBusFrame frame = buildWriteFrame(nodeId, CAN_LOCK_CONTROL_INDEX, CAN_LOCK_CONTROL_SUBINDEX, data);
    sendFrameAsync(frame, [this, status, nodeId](const QCanBusFrame& respFrame) {
        uint8_t lowByte = static_cast<uint8_t>(CAN_LOCK_CONTROL_INDEX & 0xFF);         // 索引低字节（小端）
        uint8_t highByte = static_cast<uint8_t>((CAN_LOCK_CONTROL_INDEX >> 8) & 0xFF); // 索引高字节（小端
        if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
              static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
              static_cast<uint8_t>(respFrame.payload()[3]) == CAN_LOCK_CONTROL_SUBINDEX &&
              static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
            return;
        }
        bool success = respFrame.isValid() && static_cast<uint8_t>(respFrame.payload()[0]) != CAN_SDO_READ_RECEIVE_BYTE_ERROR;
        QList<QString> lockRfids;
        if (success) {
            if (m_locksRFIDStatus.find(nodeId) != m_locksRFIDStatus.end()) {
                msleep(500);
                QMap<int, QString> lockRfidMap = m_locksRFIDStatus[nodeId].lockRFIDMap;
                for (int i = 0 ; i < status.lockNums.length(); i++) {
                    int lockNum = status.lockNums[i];
                    if (lockRfidMap.find(lockNum) == lockRfidMap.end()) {
                        continue;
                    }
                    lockRfids.append(lockRfidMap[lockNum]);
                }
            }
            for (int i = 0 ; i < status.lockNums.length(); i++) {
                qInfo() << "[Lock] " << status.lockNums[i] << "号锁扣：" << (status.lockLockedMap[status.lockNums[i]] ? "锁住" : "解锁");
            }
        }
        else {
            for (int i = 0 ; i < status.lockNums.length(); i++) {
                qWarning() << "[Lock] " << status.lockNums[i] << "号锁扣写入失败";
            }
        }
        emit lockBuckleWritten(success, lockRfids);
    });
}

void CANClient::readTemperatureAsync()
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_EKEY_NODEID, nodeId)) {
        return;
    }

    QCanBusFrame frame = buildReadFrame(nodeId, CAN_EKEY_TEMPERATURE_INDEX, CAN_EKEY_TEMPERATURE_SUBINDEX);
    sendFrameAsync(frame, [this, nodeId](const QCanBusFrame& respFrame) {
        double leftTemp = 0.0, rightTemp = 0.0;
        bool success = false;

        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_EKEY_TEMPERATURE_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_EKEY_TEMPERATURE_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, 4);
            qint16 leftRaw = static_cast<qint16>((static_cast<uint8_t>(data[1]) << 8) | static_cast<uint8_t>(data[0]));
            qint16 rightRaw = static_cast<qint16>((static_cast<uint8_t>(data[3]) << 8) | static_cast<uint8_t>(data[2]));

            leftTemp = leftRaw / 10.0;
            rightTemp = rightRaw / 10.0;
            success = true;

            qInfo() << "[Temperature] 左：" << leftTemp << "℃，右：" << rightTemp << "℃";
        }
        else {
            qWarning() << "[Temperature] 读取失败";
        }

        emit temperatureRead(success, leftTemp, rightTemp);
    });
}

void CANClient::readKeyRFIDStatusAsync()
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_EKEY_NODEID, nodeId)) {
        return;
    }

    // 初始化钥匙RFID状态
    CANKeyRFIDStatus keyStatus;
    keyStatus.leftKeyRFID = "";
    keyStatus.rightKeyRFID = "";
    keyStatus.leftKeyReadSuccess = false;
    keyStatus.rightKeyReadSuccess = false;

    // 读取完成计数（共2个钥匙）
    QSharedPointer<int> readCount(new int(0));
    const int totalKeyNum = 2;

    // ========== 读取左钥匙RFID（索引0x6020） ==========
    QCanBusFrame leftKeyFrame = buildReadFrame(nodeId, CAN_LEFT_EKEY_CARD_INDEX, CAN_LEFT_EKEY_CARD_SUBINDEX);
    sendFrameAsync(leftKeyFrame, [this, keyStatus, readCount, totalKeyNum, nodeId](const QCanBusFrame& respFrame) mutable {
        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_LEFT_EKEY_CARD_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_LEFT_EKEY_CARD_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.payload()[3]) == CAN_LEFT_EKEY_CARD_SUBINDEX &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, CAN_LEFT_EKEY_CARD_BYTE_COUNT);
            keyStatus.leftKeyRFID = parseRFIDCard(data);
            keyStatus.leftKeyReadSuccess = true;

            QMutexLocker locker(&m_insertDataMutex);

            QString prevLeftHasKey;
            if (m_keyRFIDStatus.find(nodeId) != m_keyRFIDStatus.end()) {
                prevLeftHasKey = m_keyRFIDStatus[nodeId].leftKeyRFID;
            }

            QString currHasLock =  parseRFIDCard(data);;
            if (!prevLeftHasKey.isEmpty()) {
                if (prevLeftHasKey != currHasLock && !currHasLock.isEmpty() && currHasLock != "00000000") {
                    qInfo() << "[归还检测] 左钥匙：NFC卡号:" << currHasLock;

                   emit nfcDeviceDetected(currHasLock, "key", 0);
                }
                else if (prevLeftHasKey != currHasLock && (currHasLock.isEmpty() || currHasLock == "00000000")) {
                    qInfo() << "[取出检测] 左钥匙：NFC卡号:" << currHasLock;

                    emit signalPopDevices(prevLeftHasKey, "key", 0);
                }
            }

            if (m_keyRFIDStatus.find(nodeId) == m_keyRFIDStatus.end()) {
                m_keyRFIDStatus.insert(nodeId, keyStatus);
            }
            else {
                m_keyRFIDStatus[nodeId].leftKeyRFID = parseRFIDCard(data);
                m_keyRFIDStatus[nodeId].leftKeyReadSuccess = true;
            }

//            qInfo() << "[KeyRFID] 左钥匙卡号：" << keyStatus.leftKeyRFID;
        }
        else {
            qWarning() << "[KeyRFID] 左钥匙卡号读取失败";
        }

        // 计数+1，全部完成后发射信号
        (*readCount)++;
        if (*readCount == totalKeyNum) {
            keyStatus.success = (keyStatus.leftKeyReadSuccess || keyStatus.rightKeyReadSuccess);
//            emit this->keyRFIDStatusRead(keyStatus);
        }
    });
    msleep(CAN_SLEEP_TIME);
    // ========== 读取右钥匙RFID（索引0x6024） ==========
    QCanBusFrame rightKeyFrame = buildReadFrame(nodeId, CAN_RIGHT_EKEY_CARD_INDEX, CAN_RIGHT_EKEY_CARD_SUBINDEX);
    sendFrameAsync(rightKeyFrame, [this, keyStatus, readCount, totalKeyNum, nodeId](const QCanBusFrame& respFrame) mutable {
        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_RIGHT_EKEY_CARD_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_RIGHT_EKEY_CARD_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.payload()[3]) == CAN_RIGHT_EKEY_CARD_SUBINDEX &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, CAN_RIGHT_EKEY_CARD_BYTE_COUNT);
            keyStatus.rightKeyRFID = parseRFIDCard(data);
            keyStatus.rightKeyReadSuccess = true;

            QMutexLocker locker(&m_insertDataMutex);

            QString prevRightHasKey;
            if (m_keyRFIDStatus.find(nodeId) != m_keyRFIDStatus.end()) {
                prevRightHasKey = m_keyRFIDStatus[nodeId].rightKeyRFID;
            }

            QString currHasLock =  keyStatus.rightKeyRFID;
            if (!prevRightHasKey.isEmpty()) {
                if (prevRightHasKey != currHasLock && !currHasLock.isEmpty() && currHasLock != "00000000") {
                    qInfo() << "[归还检测] 右钥匙：NFC卡号:" << currHasLock;

                   emit nfcDeviceDetected(currHasLock, "key", 1);
                }
                else if (prevRightHasKey != currHasLock && (currHasLock.isEmpty() || currHasLock == "00000000")) {
                    qInfo() << "[取出检测] 右钥匙：NFC卡号:" << currHasLock;

                    emit signalPopDevices(prevRightHasKey, "key", 0);
                }
            }

            if (m_keyRFIDStatus.find(nodeId) == m_keyRFIDStatus.end()) {
                m_keyRFIDStatus.insert(nodeId, keyStatus);
            }
            else {
                m_keyRFIDStatus[nodeId].rightKeyRFID = parseRFIDCard(data);
                m_keyRFIDStatus[nodeId].rightKeyReadSuccess = true;
            }

//            qInfo() << "[KeyRFID] 右钥匙卡号：" << keyStatus.rightKeyRFID;
        }
        else {
            qWarning() << "[KeyRFID] 右钥匙卡号读取失败";
        }

        (*readCount)++;
        if (*readCount == totalKeyNum) {
            keyStatus.success = (keyStatus.leftKeyReadSuccess || keyStatus.rightKeyReadSuccess);
//            emit this->keyRFIDStatusRead(keyStatus);
        }
    });
    msleep(CAN_SLEEP_TIME);
}

void CANClient::readSingleKeyRFIDAsync(bool isLeftKey)
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_EKEY_NODEID, nodeId)) {
        return;
    }

    quint16 rfidIndex = isLeftKey ? CAN_LEFT_EKEY_CARD_INDEX : CAN_RIGHT_EKEY_CARD_INDEX;
    quint8 rfidSubIndex = isLeftKey ? CAN_LEFT_EKEY_CARD_SUBINDEX: CAN_RIGHT_EKEY_CARD_SUBINDEX;
    QCanBusFrame frame = buildReadFrame(nodeId, rfidIndex, rfidSubIndex);

    sendFrameAsync(frame, [this, isLeftKey, rfidIndex, rfidSubIndex, nodeId, frame](const QCanBusFrame& respFrame) {
        bool success = false;
        QString rfidCard = "";

        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(rfidIndex & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((rfidIndex >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.payload()[3]) == rfidSubIndex &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }
//            qDebug() << "send 帧 FrameId: 0x" << QString::number(frame.frameId(), 16) << "Data：" << frame.payload().toHex().toUpper();
//            qDebug() << "帧 FrameId: 0x" << QString::number(respFrame.frameId(), 16) << "Data：" << respFrame.payload().toHex().toUpper();
            QByteArray data = respFrame.payload().mid(4, 4);
            rfidCard = parseRFIDCard(data);
            success = true;
        }

        // 发射单个钥匙RFID信号
        emit singleKeyRFIDRead(isLeftKey, success, rfidCard);
//        qInfo() << "[SingleKeyRFID] " << (isLeftKey ? "左" : "右") << "钥匙：" << (success ? rfidCard : "读取失败");
    });
}

void CANClient::readLockRFIDStatusAsync()
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_LOCK_NODEID, nodeId)) {
        return;
    }

    // 初始化锁RFID状态
    CANLockRFIDStatus lockStatus;
    for (int i = 0; i < 5; i++) {
        lockStatus.lockRFIDMap.insert(i, "");
        lockStatus.lockReadSuccessMap.insert(i, false);
    }

    // 读取完成计数（共5个锁）
    QSharedPointer<int> readCount(new int(0));
    const int totalLockNum = 5;

    bool isFirst = m_locksRFIDStatus.isEmpty();

    // ========== 读取1-5号锁RFID（索引0x6021~0x6025） ==========
    for (int lockNum = 0; lockNum < 5; lockNum++) {
        quint16 rfidIndex = CAN_LOCK_CARD_INDEX;
        quint8 rfidSubIndex = CAN_LOCK_1_CARD_SUBINDEX + lockNum;
        QCanBusFrame lockFrame = buildReadFrame(nodeId, rfidIndex, rfidSubIndex);

        sendFrameAsync(lockFrame, [this, lockStatus, readCount, isFirst, lockNum, rfidIndex, rfidSubIndex, nodeId](const QCanBusFrame& respFrame) mutable {
            bool readSuccess = false;
            QString rfidCard = "";

            if (respFrame.isValid() && respFrame.payload().length() >= 8) {
                uint8_t lowByte = static_cast<uint8_t>(rfidIndex & 0xFF);         // 索引低字节（小端）
                uint8_t highByte = static_cast<uint8_t>((rfidIndex >> 8) & 0xFF); // 索引高字节（小端
                if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                      static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                      static_cast<uint8_t>(respFrame.payload()[3]) == rfidSubIndex &&
                      static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                    return;
                }

                QByteArray data = respFrame.payload().mid(4, 4);
                rfidCard = parseRFIDCard(data);
                readSuccess = true;

                QMutexLocker locker(&m_insertDataMutex);
                // ========== 检测锁插入（用于归还流程） ==========

                // 获取之前的锁状态
                QMap<int, QString> prevLockHasKeyMap;
                if (m_locksRFIDStatus.find(nodeId) != m_locksRFIDStatus.end()) {
                    prevLockHasKeyMap = m_locksRFIDStatus[nodeId].lockRFIDMap;
                }

                QString prevHasLock = prevLockHasKeyMap.contains(lockNum) ? prevLockHasKeyMap[lockNum] : "";
                QString currHasLock = rfidCard;

                if (!prevHasLock.isEmpty()) {
//                    qInfo() << "[LockRFID] " << prevHasLock << currHasLock;
                    if (prevHasLock != currHasLock && !currHasLock.isEmpty() && currHasLock != "00000000") {
                        qInfo() << "[归还检测] 检测到" << (lockNum+1) << "号锁插入！";
                        qInfo() << "[归还检测]" << (lockNum+1) << "号锁NFC卡号:" << currHasLock;

                        emit nfcDeviceDetected(currHasLock, "lock", lockNum);
                        emit signalLockNfcDeviceDetected(currHasLock);
                    }
                    else if (prevHasLock != currHasLock && (currHasLock.isEmpty() || currHasLock == "00000000")) {
                        qInfo() << "[取出检测] 检测到" << (lockNum+1) << "号锁被取出！";
                        qInfo() << "[取出检测]" << (lockNum+1) << "号锁NFC卡号:" << currHasLock;
                        emit signalPopDevices(prevHasLock, "lock", lockNum);
                    }
                }
                // ====================================================

                if (m_locksRFIDStatus.find(nodeId) == m_locksRFIDStatus.end()) {
                    m_locksRFIDStatus.insert(nodeId, lockStatus);
                }
                else {
                    m_locksRFIDStatus[nodeId].lockRFIDMap.insert(lockNum, rfidCard);
                }

//                qInfo() << "[LockRFID] " << lockNum+1 << "号锁卡号：" << rfidCard;
            }
            else {
                qWarning() << "[LockRFID] " << lockNum << "号锁卡号读取失败";
            }

            // 更新锁RFID状态
            lockStatus.lockRFIDMap.insert(lockNum, rfidCard);
            lockStatus.lockReadSuccessMap.insert(lockNum, readSuccess);

            // 计数+1，全部完成后发射信号
            (*readCount)++;
            if (*readCount == totalLockNum) {
                // 只要有一个锁读取成功，整体标记为成功
                lockStatus.success = lockStatus.lockReadSuccessMap.values().contains(true);
//                emit this->lockRFIDStatusRead(lockStatus);
            }
        });
        msleep(CAN_SLEEP_TIME);
    }
}

void CANClient::readSingleLockRFIDAsync(int lockNum)
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_LOCK_NODEID, nodeId)) {
        return;
    }

    if (!checkLockNumValid(lockNum)) {
        emit singleLockRFIDRead(lockNum, false, "");
        return;
    }

    quint16 rfidIndex = CAN_LOCK_CARD_INDEX;
    quint8 rfidSubIndex = CAN_LOCK_1_CARD_SUBINDEX + lockNum;
    QCanBusFrame frame = buildReadFrame(nodeId, rfidIndex, rfidSubIndex);

    sendFrameAsync(frame, [this, lockNum, rfidIndex, rfidSubIndex, nodeId](const QCanBusFrame& respFrame) {
        bool success = false;
        QString rfidCard = "";

        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(rfidIndex & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((rfidIndex >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.payload()[3]) == rfidSubIndex &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, 4);
            rfidCard = parseRFIDCard(data);
            success = true;
        }

        // 发射单个锁RFID信号
        emit singleLockRFIDRead(lockNum, success, rfidCard);
//        qInfo() << "[SingleLockRFID] " << lockNum << "号锁：" << (success ? rfidCard : "读取失败");
    });
}

void CANClient::readKeyBaseChargeStatusAsync()
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_EKEY_NODEID, nodeId)) {
        return;
    }

    CANKeyBaseChargeStatus chargeStatus;
    chargeStatus.leftChargeEnable = false;
    chargeStatus.rightChargeEnable = false;
    chargeStatus.leftChargeState = ChargeState::Uncharged;
    chargeStatus.rightChargeState = ChargeState::Uncharged;

    // ========== 读取卡扣充电状态 ==========
    QCanBusFrame leftFrame = buildReadFrame(nodeId, CAN_FASTENER_CONTROL_INDEX, CAN_FASTENER_CONTROL_SUBINDEX);
    sendFrameAsync(leftFrame, [this, chargeStatus, nodeId](const QCanBusFrame& respFrame) mutable {
        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_FASTENER_CONTROL_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_FASTENER_CONTROL_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.payload()[3]) == CAN_FASTENER_CONTROL_SUBINDEX &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, CAN_FASTENER_CONTROL_BYTE_COUNT);
            uint8_t statusByte = static_cast<uint8_t>(data[0]);
            uint8_t faultStatusByte = static_cast<uint8_t>(data[1]);
            chargeStatus.leftLocked = (statusByte & 0x01) != 0;
            chargeStatus.rightLocked = (statusByte & 0x10) != 0;
            chargeStatus.leftChargeState = ((statusByte & 0x02) != 0) ? ChargeState::Charging : ChargeState::Uncharged;
            chargeStatus.rightChargeState = ((statusByte & 0x20) != 0) ? ChargeState::Charging : ChargeState::Uncharged;

            chargeStatus.leftWorking = (faultStatusByte & 0x01) != 0;
            chargeStatus.rightWorking = (faultStatusByte & 0x04) != 0;

            chargeStatus.success = true;
//            qInfo() << "[ChargeRead] 左卡扣：使能=" << chargeStateToString(chargeStatus.leftChargeState) << "，实际状态=" << chargeStatus.leftWorking;
        }
        else {
            qWarning() << "[ChargeRead] 左卡扣充电状态读取失败";
        }
    });
}

bool CANClient::openEKey(QString& keyNFC)
{
    CANKeyBaseChargeStatus unlockStatus;
    CANKeyBaseChargeStatus chargeStatus;

    for (auto iter = m_keyBaseStatus.begin(); iter != m_keyBaseStatus.end(); ++iter) {
        if (iter->leftHasKey) {
            chargeStatus.leftLocked = true;
            chargeStatus.leftWorking = true;
            chargeStatus.leftChargeEnable = true;
            chargeStatus.leftChargeState = ChargeState::Charging;

            unlockStatus.leftLocked = true;
            unlockStatus.leftWorking = true;
            unlockStatus.leftChargeEnable = false;
            unlockStatus.leftChargeState = ChargeState::Charging;

            if (m_keyRFIDStatus.find(iter.key()) != m_keyRFIDStatus.end()) {
                keyNFC = m_keyRFIDStatus[iter.key()].leftKeyRFID;
            }
            break;
        }
        if (iter->rightHasKey) {
            chargeStatus.rightLocked = true;
            chargeStatus.rightWorking = true;
            chargeStatus.rightChargeEnable = true;
            chargeStatus.rightChargeState = ChargeState::Charging;

            unlockStatus.rightLocked = true;
            unlockStatus.rightWorking = true;
            unlockStatus.rightChargeEnable = false;
            unlockStatus.rightChargeState = ChargeState::Charging;

            if (m_keyRFIDStatus.find(iter.key()) != m_keyRFIDStatus.end()) {
                keyNFC = m_keyRFIDStatus[iter.key()].rightKeyRFID;
            }
            break;
        }
    }
    writeKeyBaseChargeControlAsync(unlockStatus);
    msleep(500);
    writeKeyBaseChargeControlAsync(chargeStatus);
    msleep(CAN_SLEEP_TIME);
    return true;
}

bool CANClient::unlockEKey()
{
    CANKeyBaseChargeStatus chargeStatus;
    for (auto iter = m_keyBaseStatus.begin(); iter != m_keyBaseStatus.end(); ++iter) {
        if (iter->leftHasKey) {
            chargeStatus.leftLocked = false;
            chargeStatus.leftWorking = true;
            chargeStatus.leftChargeEnable = false;
            chargeStatus.leftChargeState = ChargeState::Charging;

            break;
        }
        if (iter->rightHasKey) {
            chargeStatus.rightLocked = false;
            chargeStatus.rightWorking = true;
            chargeStatus.rightChargeEnable = false;
            chargeStatus.rightChargeState = ChargeState::Charging;

            break;
        }
    }
    if ((!chargeStatus.leftLocked && chargeStatus.leftWorking) || (!chargeStatus.rightLocked && chargeStatus.rightWorking)) {
        writeKeyBaseChargeControlAsync(chargeStatus);
        // 暂停一段时间，防止自动上锁
//        msleep(3000);
        msleep(CAN_SLEEP_TIME);
        return true;
    }

    return false;
}

bool CANClient::getLockRfids(int lockCount, QMap<int, QString> &rfids)
{
    bool isContinue = true;
    // 暂时只处理一个5路锁
    for (auto iter = m_locksControlStatus.begin(); iter != m_locksControlStatus.end(); ++iter) {
        for (auto hasKeyIter = iter->lockHasKeyMap.begin(); hasKeyIter != iter->lockHasKeyMap.end(); ++hasKeyIter) {
            if (hasKeyIter.value()) {
                if (m_locksRFIDStatus.find(iter.key()) == m_locksRFIDStatus.end()) {
                    continue;
                }
                if (m_locksRFIDStatus[iter.key()].lockRFIDMap.find(hasKeyIter.key()) == m_locksRFIDStatus[iter.key()].lockRFIDMap.end()) {
                    continue;
                }
                rfids.insert(hasKeyIter.key(), m_locksRFIDStatus[iter.key()].lockRFIDMap[hasKeyIter.key()]);

                if (rfids.count() >= lockCount) {
                    isContinue = false;
                    break;
                }
            }
        }
        if (!isContinue) {
            break;
        }
    }
    if (rfids.count() < lockCount) return false;

    return true;
}

bool CANClient::unlockLocks(const QList<int>& lockNums)
{
    CANLocksControl lockStatus;
    bool isContinue = true;
    // 暂时只处理一个5路锁
    for (auto iter = m_locksControlStatus.begin(); iter != m_locksControlStatus.end(); ++iter) {
        for (auto hasKeyIter = iter->lockHasKeyMap.begin(); hasKeyIter != iter->lockHasKeyMap.end(); ++hasKeyIter) {
            if (hasKeyIter.value() && lockNums.contains(hasKeyIter.key())) {
                lockStatus.lockNums.append(hasKeyIter.key());
                lockStatus.lockLockedMap.insert(hasKeyIter.key(), false);
                lockStatus.lockWorkMap.insert(hasKeyIter.key(), true);

                if (lockStatus.lockNums.length() >= lockNums.length()) {
                    isContinue = false;
                    break;
                }
            }
        }
        if (!isContinue) {
            break;
        }
    }
    if (lockStatus.lockNums.length() < lockNums.length()) return false;
    writeLockBuckleAsync(lockStatus);
    msleep(3000);

    return true;
}

bool CANClient::lockingEKey(quint8 nodeId, bool leftKey, bool rightKey)
{
    Q_UNUSED(nodeId);
    CANKeyBaseChargeStatus chargeStatus;

    if (leftKey) {
        chargeStatus.leftLocked = true;
        chargeStatus.leftWorking = true;
        chargeStatus.leftChargeEnable = true;
        chargeStatus.leftChargeState = ChargeState::Charging;

    }
    if (rightKey) {
        chargeStatus.rightLocked = true;
        chargeStatus.rightWorking = true;
        chargeStatus.rightChargeEnable = true;
        chargeStatus.rightChargeState = ChargeState::Charging;
    }
    writeKeyBaseChargeControlAsync(chargeStatus);
    msleep(CAN_SLEEP_TIME);
    return true;
}

void CANClient::unlockEKey(const QString &keyNFC)
{
    CANKeyBaseChargeStatus chargeStatus;

    for (auto iter = m_keyRFIDStatus.begin(); iter != m_keyRFIDStatus.end(); ++iter) {
//        int nodeId = iter.key();
        if (keyNFC == iter->leftKeyRFID) {
            chargeStatus.leftLocked = false;
            chargeStatus.leftWorking = true;
            chargeStatus.leftChargeEnable = false;
            chargeStatus.leftChargeState = ChargeState::Uncharged;

            writeKeyBaseChargeControlAsync(chargeStatus);
            msleep(CAN_SLEEP_TIME);
            return;
        }
        else if (keyNFC == iter->rightKeyRFID) {
            chargeStatus.rightLocked = false;
            chargeStatus.rightWorking = true;
            chargeStatus.rightChargeEnable = false;
            chargeStatus.rightChargeState = ChargeState::Uncharged;

            writeKeyBaseChargeControlAsync(chargeStatus);
            msleep(CAN_SLEEP_TIME);
            return;
        }
    }
}

void CANClient::unlockLock(const QString &lockNFC)
{
    CANLocksControl lockStatus;
    // 暂时只处理一个5路锁
    for (auto iter = m_locksRFIDStatus.begin(); iter != m_locksRFIDStatus.end(); ++iter) {
        for (auto hasKeyIter = iter->lockRFIDMap.begin(); hasKeyIter != iter->lockRFIDMap.end(); ++hasKeyIter) {
            if (hasKeyIter.value() == lockNFC) {
                lockStatus.lockNums.append(hasKeyIter.key());
                lockStatus.lockLockedMap.insert(hasKeyIter.key(), false);
                lockStatus.lockWorkMap.insert(hasKeyIter.key(), true);

                 writeLockBuckleAsync(lockStatus);
                 msleep(50);
                 return;
            }
        }
    }
}

void CANClient::writeKeyBaseChargeControlAsync(CANKeyBaseChargeStatus& chargeStatus)
{
    quint8 nodeId = 0;

    if (!verifyNodeID(CAN_DEVICE_EKEY_NODEID, nodeId)) {
        return;
    }

    // ========== 写入卡扣充电使能 ==========
    uint8_t statusByte = 0x00;
    statusByte = statusByte + (chargeStatus.leftLocked ? 0x01 : 0x00);
    statusByte = statusByte + (chargeStatus.rightLocked ? 0x10 : 0x00);
    statusByte = statusByte + (chargeStatus.leftChargeEnable ? 0x02: 0x00);
    statusByte = statusByte + (chargeStatus.rightChargeEnable ? 0x20 : 0x00);

    uint8_t workingStatusByte = 0x00;
    workingStatusByte = workingStatusByte + (chargeStatus.leftWorking ? 0x01 : 0x00);
    workingStatusByte = workingStatusByte + (chargeStatus.rightWorking ? 0x10 : 0x00);
    workingStatusByte = workingStatusByte + (chargeStatus.leftWorking ? 0x02 : 0x00);
    workingStatusByte = workingStatusByte + (chargeStatus.rightWorking ? 0x20 : 0x00);
//    workingStatusByte = workingStatusByte + (chargeStatus.leftChargeState == ChargeState::Charging ? 0x02 : 0x00);
//    workingStatusByte = workingStatusByte + (chargeStatus.rightChargeState == ChargeState::Charging ? 0x20 : 0x00);


    QByteArray data;
    data.append(static_cast<char>(statusByte));
    data.append(static_cast<char>(workingStatusByte));
    QCanBusFrame leftFrame = buildWriteFrame(nodeId, CAN_FASTENER_CONTROL_INDEX, CAN_FASTENER_CONTROL_SUBINDEX, data);
    qDebug() << "发送Write-CAN帧 FrameId: 0x" << QString::number(leftFrame.frameId(), 16) << "Data：" << leftFrame.payload().toHex().toUpper();
    sendFrameAsync(leftFrame, [this, chargeStatus, nodeId](const QCanBusFrame& respFrame) mutable {
        if (respFrame.isValid() && respFrame.payload().length() >= 8) {
            uint8_t lowByte = static_cast<uint8_t>(CAN_FASTENER_CONTROL_INDEX & 0xFF);         // 索引低字节（小端）
            uint8_t highByte = static_cast<uint8_t>((CAN_FASTENER_CONTROL_INDEX >> 8) & 0xFF); // 索引高字节（小端
            if (!(static_cast<uint8_t>(respFrame.payload()[1]) == lowByte &&
                  static_cast<uint8_t>(respFrame.payload()[2]) == highByte &&
                  static_cast<uint8_t>(respFrame.payload()[3]) == CAN_FASTENER_CONTROL_SUBINDEX &&
                  static_cast<uint8_t>(respFrame.frameId() - CAN_SDO_RECEIVE_IDENTIFIER_HEADER) == nodeId)) {
                return;
            }

            QByteArray data = respFrame.payload().mid(4, CAN_FASTENER_CONTROL_BYTE_COUNT);
            uint8_t statusByte = static_cast<uint8_t>(data[0]);
            uint8_t workingByte = static_cast<uint8_t>(data[1]);
            ChargeState rLeftChargeState = ((workingByte & 0x02) != 0) ? ChargeState::Charging : ChargeState::Uncharged;
//            qInfo() << "[ChargeWrite] 左卡扣充电使能写入成功，实际状态=" << chargeStateToString(rLeftChargeState) << "  工作状态: " << (((workingByte & 0x02) != 0) ? "工作" : "不工作");

            chargeStatus.success = true;
        }
        else {
            chargeStatus.success = false;
            qWarning() << "[ChargeWrite] 左卡扣充电使能写入失败";
        }
        emit keyBaseChargeControlWritten(chargeStatus);
    });
}

void CANClient::testFunc()
{
//    for (int i = 0; i < 5; i++) {
//        CANSingleLockStatus status;
//        status.lockNum = i;
//        status.isWorking = true;
//        status.isLocked = true;
//        writeSingleLockBuckleAsync(status);
//        msleep(50);
//    }

//    CANSingleLockStatus status;
//    status.lockNum = 4;
//    status.isWorking = true;
//    status.isLocked = true;
//    writeSingleLockBuckleAsync(status);
//    msleep(50);
//    readLockControlStatusAsync();

//    CANLocksControl status;
//    for (int i = 0; i < 5; i++) {
//        status.lockNums.append(i);
//        status.lockLockedMap[i] = false;
//        status.lockWorkMap[i] = true;
//    }
//    writeLockBuckleAsync(status);
//    msleep(50);

//    readSingleLockRFIDAsync(0);
//    msleep(50);
//    CANKeyBaseChargeStatus chargeStatus;
//    chargeStatus.leftLocked = false;
//    chargeStatus.leftWorking = true;
//    chargeStatus.leftChargeEnable = true;
//    chargeStatus.leftChargeState = ChargeState::Charging;

//    QTimer* writeTimer = new QTimer(this);
//    connect(writeTimer, &QTimer::timeout, [this]() {
//        CANKeyBaseChargeStatus chargeStatus;
//        chargeStatus.leftLocked = true;
//        chargeStatus.leftWorking = true;
//        chargeStatus.leftChargeEnable = true;
//        chargeStatus.leftChargeState = ChargeState::Charging;

//        writeKeyBaseChargeControlAsync(chargeStatus);
//        msleep(50);
//    });
//    writeTimer->start(300);

//    connect(this, &CANClient::keyBaseChargeControlWritten, [this, writeTimer](const CANKeyBaseChargeStatus& status) {
//        if (status.success) {
//            qInfo() << "[ChargeWrite] 卡扣充电使能写入成功，实际状态=" << chargeStateToString(status.leftChargeState) << "  工作状态: " << ((status.leftWorking) ? "工作" : "不工作");
//            writeTimer->stop();
//        }
//    });
//    readSingleKeyRFIDAsync(true);
//    msleep(50);
//    readSingleKeyRFIDAsync(false);
    //    msleep(50);
}

QString CANClient::getLockRFID(int lockNum)
{
    for (auto iter = m_locksRFIDStatus.begin(); iter != m_locksRFIDStatus.end(); ++iter) {
        CANLockRFIDStatus itemRFID = iter.value();
        if (itemRFID.lockRFIDMap.contains(lockNum) &&
                itemRFID.lockRFIDMap[lockNum].isEmpty() &&
                itemRFID.lockRFIDMap[lockNum] != "00000000") {
            return itemRFID.lockRFIDMap[lockNum];
        }
    }
    readLockRFIDStatusAsync();
    msleep(CAN_SLEEP_TIME);
    return QString();
}

