/**
 * @file DeviceListPanel.cpp
 * @brief 设备列表面板组件实现
 * @author CasualtySightPlus Team
 * @date 2024-12-01
 * @version 1.0
 */

#include "ui/components/DeviceListPanel.h"
#include "utils/SystemLogger.h"

// Qt GUI头文件
#include <QDebug>
#include <QMessageBox>
#include <QApplication>
#include <QSplitter>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QHeaderView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QDialog>

// Qt SQL头文件
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

DeviceListPanel::DeviceListPanel(QWidget *parent)
    : QWidget(parent)
    , m_titleLabel(nullptr)
    , m_deviceCountLabel(nullptr)
    , m_addUAVButton(nullptr)
    , m_addDogButton(nullptr)
    , m_refreshButton(nullptr)
    , m_scrollArea(nullptr)
    , m_scrollWidget(nullptr)
    , m_deviceListLayout(nullptr)
    , m_mainLayout(nullptr)
    , m_headerLayout(nullptr)
    , m_buttonLayout(nullptr)
    , m_currentFilterType(DeviceFilterType::All)
    , m_isMonitoringActive(false)
    , m_uavDatabase(nullptr)
    , m_dogDatabase(nullptr)
    , m_totalDeviceCount(0)
    , m_onlineDeviceCount(0)
    , m_uavCount(0)
    , m_dogCount(0)
{
    // 初始化数据库连接
    m_uavDatabase = UAVDatabase::getInstance();
    m_dogDatabase = DogDatabase::getInstance();
    
    // 创建状态监控定时器
    m_statusMonitorTimer = new QTimer(this);
    m_statusMonitorTimer->setInterval(STATUS_MONITOR_INTERVAL);
    
    setupUI();
    setupStyle();
    connectSignals();
    
    // 初始加载设备列表
    refreshDeviceList();
    
    qDebug() << "DeviceListPanel created successfully";
}

DeviceListPanel::~DeviceListPanel()
{
    stopStatusMonitoring();
    clearAllDeviceCards();
    qDebug() << "DeviceListPanel destroyed";
}

void DeviceListPanel::setupUI()
{
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(PANEL_PADDING, PANEL_PADDING, PANEL_PADDING, PANEL_PADDING);
    m_mainLayout->setSpacing(12);
    
    // === 头部区域 ===
    m_headerLayout = new QHBoxLayout();
    
    // 面板标题
    m_titleLabel = new QLabel("🎯 设备管理中心");
    m_titleLabel->setFont(QFont("Arial", 18, QFont::Bold));

    // 设备数量标签
    m_deviceCountLabel = new QLabel("设备: 0");
    m_deviceCountLabel->setFont(QFont("Arial", 12));
    
    m_headerLayout->addWidget(m_titleLabel);
    m_headerLayout->addStretch();
    m_headerLayout->addWidget(m_deviceCountLabel);
    
    // 搜索和过滤区域已删除
    
    // === 操作按钮区域 ===
    m_buttonLayout = new QHBoxLayout();
    
    m_addUAVButton = new QPushButton("🚁 +无人机");
    m_addUAVButton->setMaximumHeight(60);  // 调大按钮
    m_addUAVButton->setMaximumWidth(110);  // 合理调整按钮宽度
    m_addUAVButton->setMinimumWidth(110);  // 设置最小宽度确保文字显示完整
    m_addUAVButton->setToolTip("添加新的无人机设备");
    
    m_addDogButton = new QPushButton("🐕 +机器狗");
    m_addDogButton->setMaximumHeight(60);  // 调大按钮
    m_addDogButton->setMaximumWidth(110);  // 合理调整按钮宽度
    m_addDogButton->setMinimumWidth(110);  // 设置最小宽度确保文字显示完整
    m_addDogButton->setToolTip("添加新的机器狗设备");
    
    m_deleteDeviceButton = new QPushButton("🗑️ 删除");
    m_deleteDeviceButton->setMaximumHeight(60);
    m_deleteDeviceButton->setMaximumWidth(90);  // 合理调整按钮宽度
    m_deleteDeviceButton->setMinimumWidth(90);  // 设置最小宽度确保文字显示完整
    m_deleteDeviceButton->setToolTip("删除现有设备");
    
    m_refreshButton = new QPushButton("🔄");
    m_refreshButton->setMaximumHeight(50);  // 调大刷新按钮
    m_refreshButton->setMaximumWidth(50);   // 保持紧凑的刷新按钮
    m_refreshButton->setMinimumWidth(50);   // 设置最小宽度
    m_refreshButton->setToolTip("刷新设备列表");
    
    // 添加按钮间距
    m_buttonLayout->addWidget(m_addUAVButton);
    m_buttonLayout->addSpacing(5);  // 添加5px间距
    m_buttonLayout->addWidget(m_addDogButton);
    m_buttonLayout->addSpacing(5);  // 添加5px间距
    m_buttonLayout->addWidget(m_deleteDeviceButton);  // 添加删除按钮
    m_buttonLayout->addStretch();   // 弹性空间
    m_buttonLayout->addWidget(m_refreshButton);
    
    // === 设备列表滚动区域 ===
    m_scrollArea = new QScrollArea();
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setMinimumHeight(300); // 确保足够的显示空间
    
    m_scrollWidget = new QWidget();
    m_deviceListLayout = new QVBoxLayout(m_scrollWidget);
    m_deviceListLayout->setSpacing(8); // 减小间距使卡片更紧凑
    m_deviceListLayout->setContentsMargins(4, 4, 4, 4); // 小边距
    m_deviceListLayout->addStretch(); // 底部弹性空间
    
    m_scrollArea->setWidget(m_scrollWidget);
    
    // === 组装主布局 ===
    m_mainLayout->addLayout(m_headerLayout);
    
    // 添加分隔线
    QLabel *separatorLine = new QLabel();
    separatorLine->setFixedHeight(2);
    separatorLine->setStyleSheet("background-color: rgba(82, 194, 242, 0.3);");
    m_mainLayout->addWidget(separatorLine);
    
    m_mainLayout->addLayout(m_buttonLayout);
    m_mainLayout->addWidget(m_scrollArea, 1); // 占据剩余空间
}

void DeviceListPanel::setupStyle()
{
    // 面板整体样式 - 更现代的军用风格
    setStyleSheet(
        "DeviceListPanel {"
        "    background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1,"
        "                stop:0 rgb(15, 22, 32), stop:1 rgb(25, 35, 45));"
        "    border: 1px solid rgba(82, 194, 242, 0.3);"
        "    border-radius: 8px;"
        "}"
    );
    
    // 标题样式 - 增强军用特色
    m_titleLabel->setStyleSheet(
        "QLabel {"
        "    color: rgb(255, 255, 255);"
        "    background: transparent;"
        "    border: none;"
        "    font-weight: bold;"
        "    text-shadow: 0px 1px 2px rgba(0, 0, 0, 0.8);"
        "}"
    );
    
    // 设备数量标签样式 - 添加背景和边框
    m_deviceCountLabel->setStyleSheet(
        "QLabel {"
        "    color: rgb(82, 194, 242);"
        "    background: rgba(82, 194, 242, 0.1);"
        "    border: 1px solid rgba(82, 194, 242, 0.3);"
        "    border-radius: 4px;"
        "    padding: 2px 6px;"
        "    font-weight: bold;"
        "}"
    );
    
    // 搜索框和过滤框样式已删除
    
    // 按钮统一样式 - 军用风格
    QString buttonStyle = 
        "QPushButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 rgba(45, 65, 95, 0.8), "
        "                stop:1 rgba(25, 40, 65, 0.8));"
        "    color: rgb(220, 230, 242);"
        "    border: 2px solid rgba(82, 194, 242, 0.5);"
        "    border-radius: 6px;"
        "    padding: 10px 16px;"
        "    font-size: 14px;"
        "    font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 rgba(82, 194, 242, 0.6), "
        "                stop:1 rgba(45, 120, 180, 0.6));"
        "    border-color: rgba(82, 194, 242, 0.8);"
        "    color: white;"
        "}"
        "QPushButton:pressed {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 rgba(82, 194, 242, 0.8), "
        "                stop:1 rgba(45, 120, 180, 0.8));"
        "    border-color: rgba(82, 194, 242, 1.0);"
        "}";
    
    m_addUAVButton->setStyleSheet(buttonStyle);
    m_addDogButton->setStyleSheet(buttonStyle);
    m_deleteDeviceButton->setStyleSheet(buttonStyle);
    m_refreshButton->setStyleSheet(buttonStyle);
    
    // 滚动区域样式
    m_scrollArea->setStyleSheet(
        "QScrollArea {"
        "    background: transparent;"
        "    border: none;"
        "}"
        "QScrollBar:vertical {"
        "    background: rgba(25, 35, 45, 0.5);"
        "    width: 8px;"
        "    border-radius: 4px;"
        "}"
        "QScrollBar::handle:vertical {"
        "    background: rgba(82, 194, 242, 0.6);"
        "    border-radius: 4px;"
        "    min-height: 20px;"
        "}"
        "QScrollBar::handle:vertical:hover {"
        "    background: rgba(82, 194, 242, 0.8);"
        "}"
        "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {"
        "    border: none;"
        "    background: none;"
        "}"
    );
}

void DeviceListPanel::connectSignals()
{
    // 搜索和过滤信号已删除
    
    // 按钮信号
    connect(m_addUAVButton, &QPushButton::clicked, this, &DeviceListPanel::onAddUAVClicked);
    connect(m_addDogButton, &QPushButton::clicked, this, &DeviceListPanel::onAddDogClicked);
    connect(m_deleteDeviceButton, &QPushButton::clicked, this, &DeviceListPanel::onDeleteDeviceClicked);
    connect(m_refreshButton, &QPushButton::clicked, this, &DeviceListPanel::refreshDeviceList);
    
    // 状态监控定时器
    connect(m_statusMonitorTimer, &QTimer::timeout, this, &DeviceListPanel::onStatusMonitorTimer);
}

QString DeviceListPanel::getSelectedDeviceId() const
{
    return m_selectedDeviceId;
}

int DeviceListPanel::getDeviceCountByType(const QString &type) const
{
    if (type == "uav") return m_uavCount;
    else if (type == "dog") return m_dogCount;
    else return m_totalDeviceCount;
}

int DeviceListPanel::getOnlineDeviceCount() const
{
    return m_onlineDeviceCount;
}

void DeviceListPanel::refreshDeviceList()
{
    qDebug() << "Refreshing device list...";
    SystemLogger::getInstance()->logInfo("正在刷新设备列表...");
    
    // 清除现有设备卡片
    clearAllDeviceCards();
    
    // 从数据库加载设备
    m_allDevices = loadDevicesFromDatabase();
    
    // 创建设备卡片
    for (const auto &device : m_allDevices) {
        DeviceCard *card = createDeviceCard(device);
        if (card) {
            m_deviceCards[device.id] = card;
        }
    }
    
    // 应用当前的搜索和过滤条件
    applySearchAndFilter();
    
    // 更新统计信息
    updateDeviceCountStats();
    
    qDebug() << "Device list refreshed. Total devices:" << m_allDevices.size();
    SystemLogger::getInstance()->logSuccess(QString("设备列表刷新完成，共加载 %1 个设备").arg(m_allDevices.size()));
}

void DeviceListPanel::addDevice(const DeviceInfo &device)
{
    // 检查设备是否已存在
    if (m_deviceCards.contains(device.id)) {
        qWarning() << "Device already exists:" << device.id;
        return;
    }
    
    // 添加到设备列表
    m_allDevices.append(device);
    
    // 创建设备卡片
    DeviceCard *card = createDeviceCard(device);
    if (card) {
        m_deviceCards[device.id] = card;
        
        // 应用搜索和过滤
        applySearchAndFilter();
        updateDeviceCountStats();
        
        qDebug() << "Device added:" << device.name;
        SystemLogger::getInstance()->logSuccess(QString("设备已添加: %1").arg(device.name));
    }
}

void DeviceListPanel::removeDevice(const QString &deviceId)
{
    if (!m_deviceCards.contains(deviceId)) {
        qWarning() << "Device not found:" << deviceId;
        return;
    }
    
    // 获取设备名称用于日志
    QString deviceName = "未知设备";
    for (const auto &device : m_allDevices) {
        if (device.id == deviceId) {
            deviceName = device.name;
            break;
        }
    }
    
    // 移除设备卡片
    DeviceCard *card = m_deviceCards.take(deviceId);
    card->deleteLater();
    
    // 从设备列表中移除
    for (int i = m_allDevices.size() - 1; i >= 0; --i) {
        if (m_allDevices[i].id == deviceId) {
            m_allDevices.removeAt(i);
            break;
        }
    }
    
    // 清除选择状态
    if (m_selectedDeviceId == deviceId) {
        m_selectedDeviceId.clear();
    }
    
    updateDeviceCountStats();
    
    qDebug() << "Device removed:" << deviceId;
    SystemLogger::getInstance()->logWarning(QString("设备已移除: %1").arg(deviceName));
}

void DeviceListPanel::updateDevice(const DeviceInfo &device)
{
    if (!m_deviceCards.contains(device.id)) {
        qWarning() << "Device not found for update:" << device.id;
        return;
    }
    
    // 更新设备信息
    for (auto &existingDevice : m_allDevices) {
        if (existingDevice.id == device.id) {
            existingDevice = device;
            break;
        }
    }
    
    // 更新设备卡片
    DeviceCard *card = m_deviceCards[device.id];
    card->updateDeviceInfo(device);
    
    updateDeviceCountStats();
    
    qDebug() << "Device updated:" << device.name;
}

void DeviceListPanel::updateDeviceStatus(const QString &deviceId, DeviceStatus status)
{
    if (!m_deviceCards.contains(deviceId)) {
        qWarning() << "Device not found for status update:" << deviceId;
        return;
    }
    
    // 更新设备状态
    for (auto &device : m_allDevices) {
        if (device.id == deviceId) {
            device.status = status;
            break;
        }
    }
    
    // 更新设备卡片状态
    DeviceCard *card = m_deviceCards[deviceId];
    card->updateDeviceStatus(status);
    
    updateDeviceCountStats();
    
    qDebug() << "Device status updated:" << deviceId << "status:" << static_cast<int>(status);
}

void DeviceListPanel::startStatusMonitoring()
{
    if (!m_isMonitoringActive) {
        m_statusMonitorTimer->start();
        m_isMonitoringActive = true;
        qDebug() << "Status monitoring started";
    }
}

void DeviceListPanel::stopStatusMonitoring()
{
    if (m_isMonitoringActive) {
        m_statusMonitorTimer->stop();
        m_isMonitoringActive = false;
        qDebug() << "Status monitoring stopped";
    }
}

DeviceCard* DeviceListPanel::createDeviceCard(const DeviceInfo &device)
{
    DeviceCard *card = new DeviceCard(device, this);
    
    // 连接设备卡片信号
    connect(card, &DeviceCard::deviceSelected, this, &DeviceListPanel::onDeviceCardSelected);
    connect(card, &DeviceCard::deviceControlRequested, this, &DeviceListPanel::onDeviceCardControlRequested);
    connect(card, &DeviceCard::deviceLocationRequested, this, &DeviceListPanel::onDeviceCardLocationRequested);
    connect(card, &DeviceCard::deviceDetailsRequested, this, &DeviceListPanel::onDeviceCardDetailsRequested);
    connect(card, &DeviceCard::deviceStatusChanged, this, &DeviceListPanel::onDeviceStatusChanged);
    
    return card;
}

QList<DeviceInfo> DeviceListPanel::loadDevicesFromDatabase()
{
    QList<DeviceInfo> devices;
    
    qDebug() << "Loading devices from database...";
    
    // 尝试从真实数据库加载数据
    bool databaseAvailable = false;
    
    try {
        qDebug() << "Attempting to connect to unified devices database...";
        
        // 创建数据库连接
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "DeviceListPanel_Connection");
        db.setHostName("localhost");
        db.setPort(3306);
        db.setDatabaseName("Client");
        db.setUserName("root");
        db.setPassword("hzk200407140238");
        
        if (db.open()) {
            qDebug() << "Successfully connected to Client database";
            SystemLogger::getInstance()->logSuccess("成功连接到数据库");
            
            QSqlQuery query(db);
            QString sql = "SELECT id, name, device_type, state, ip, port, longitude, latitude, signal_strength, battery_level FROM devices";
            
            if (query.exec(sql)) {
                qDebug() << "Successfully executed query on devices table";
                
                while (query.next()) {
                    DeviceInfo device;
                    device.id = query.value("id").toString();
                    device.name = query.value("name").toString();
                    device.type = query.value("device_type").toString();
                    device.ipAddress = query.value("ip").toString();
                    device.port = query.value("port").toInt();
                    device.longitude = query.value("longitude").toDouble();
                    device.latitude = query.value("latitude").toDouble();
                    device.signalStrength = query.value("signal_strength").toInt();
                    device.batteryLevel = query.value("battery_level").toInt();
                    
                    // 状态转换：0=离线, 1=在线
                    int state = query.value("state").toInt();
                    switch (state) {
                        case 1: device.status = DeviceStatus::Online; break;
                        case 0:
                        default: device.status = DeviceStatus::Offline; break;
                    }
                    
                    device.lastHeartbeat = QDateTime::currentDateTime();
                    device.createdAt = QDateTime::currentDateTime();
                    device.updatedAt = QDateTime::currentDateTime();
                    
                    devices.append(device);
                    qDebug() << "Loaded device from database:" << device.name << "(" << device.type << ")"; 
                }
                
                databaseAvailable = true;
                qDebug() << "Successfully loaded" << devices.size() << "devices from unified database";
            } else {
                qWarning() << "Failed to execute query:" << query.lastError().text();
            }
            
            db.close();
        } else {
            qWarning() << "Failed to connect to Client database:" << db.lastError().text();
            SystemLogger::getInstance()->logError("数据库连接失败");
        }
    } catch (const std::exception& e) {
        qWarning() << "Database connection exception:" << e.what();
        databaseAvailable = false;
    } catch (...) {
        qWarning() << "Unknown database connection error, using test data";
        databaseAvailable = false;
    }
    
    if (!databaseAvailable) {
        qWarning() << "Database not available, no devices loaded.";
        qDebug() << "Please ensure MySQL is running and Client database exists with devices table.";
    
    // 数据库不可用时不加载任何设备
    
    }
    
    return devices;
}

bool DeviceListPanel::deleteDeviceFromDatabase(const QString &deviceId)
{
    qDebug() << "Attempting to delete device from database:" << deviceId;
    
    // 创建数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "DeviceListPanel_Delete_Connection");
    db.setHostName("localhost");
    db.setPort(3306);
    db.setDatabaseName("Client");
    db.setUserName("root");
    db.setPassword("hzk200407140238");
    
    bool success = false;
    
    if (db.open()) {
        qDebug() << "Successfully connected to database for deletion";
        
        QSqlQuery query(db);
        query.prepare("DELETE FROM devices WHERE id = ?");
        query.addBindValue(deviceId);
        
        if (query.exec()) {
            if (query.numRowsAffected() > 0) {
                qDebug() << "Successfully deleted device from database:" << deviceId;
                SystemLogger::getInstance()->logSuccess("设备从数据库中删除成功");
                success = true;
                
                // 从内存中移除设备
                for (int i = m_allDevices.size() - 1; i >= 0; --i) {
                    if (m_allDevices[i].id == deviceId) {
                        m_allDevices.removeAt(i);
                        break;
                    }
                }
                
                // 删除设备卡片
                if (m_deviceCards.contains(deviceId)) {
                    DeviceCard *card = m_deviceCards[deviceId];
                    m_deviceCards.remove(deviceId);
                    m_deviceListLayout->removeWidget(card);
                    card->deleteLater();
                }
                
                // 清除选择（如果删除的是当前选中的设备）
                if (m_selectedDeviceId == deviceId) {
                    m_selectedDeviceId.clear();
                }
                
                // 更新统计信息
                updateDeviceCountStats();
                
            } else {
                qWarning() << "No device found with ID:" << deviceId;
            }
        } else {
            qWarning() << "Failed to execute delete query:" << query.lastError().text();
            SystemLogger::getInstance()->logError("数据库删除操作失败");
        }
        
        db.close();
    } else {
        qWarning() << "Failed to connect to database for deletion:" << db.lastError().text();
        SystemLogger::getInstance()->logError("删除操作数据库连接失败");
    }
    
    // 清理数据库连接
    QSqlDatabase::removeDatabase("DeviceListPanel_Delete_Connection");
    
    return success;
}

void DeviceListPanel::applySearchAndFilter()
{
    qDebug() << "Applying search and filter. Keyword:" << m_currentSearchKeyword
             << "Filter:" << static_cast<int>(m_currentFilterType);
    
    // 隐藏所有设备卡片
    for (auto card : m_deviceCards) {
        card->hide();
        m_deviceListLayout->removeWidget(card);
    }
    
    // 根据条件显示匹配的设备卡片
    for (const auto &device : m_allDevices) {
        if (isDeviceMatchFilter(device)) {
            DeviceCard *card = m_deviceCards[device.id];
            if (card) {
                m_deviceListLayout->insertWidget(m_deviceListLayout->count() - 1, card);
                card->show();
            }
        }
    }
}

bool DeviceListPanel::isDeviceMatchFilter(const DeviceInfo &device) const
{
    // 检查搜索关键词
    if (!m_currentSearchKeyword.isEmpty()) {
        if (!device.name.contains(m_currentSearchKeyword, Qt::CaseInsensitive) &&
            !device.ipAddress.contains(m_currentSearchKeyword, Qt::CaseInsensitive)) {
            return false;
        }
    }
    
    // 检查过滤类型
    switch (m_currentFilterType) {
        case DeviceFilterType::UAV:
            return device.type == "uav";
        case DeviceFilterType::Dog:
            return device.type == "dog";
        case DeviceFilterType::Online:
            return device.isOnline();
        case DeviceFilterType::Offline:
            return !device.isOnline();
        case DeviceFilterType::All:
        default:
            return true;
    }
}

void DeviceListPanel::updateDeviceCountStats()
{
    m_totalDeviceCount = m_allDevices.size();
    m_onlineDeviceCount = 0;
    m_uavCount = 0;
    m_dogCount = 0;
    
    for (const auto &device : m_allDevices) {
        if (device.isOnline()) {
            m_onlineDeviceCount++;
        }
        if (device.type == "uav") {
            m_uavCount++;
        } else if (device.type == "dog") {
            m_dogCount++;
        }
    }
    
    // 更新显示
    m_deviceCountLabel->setText(QString("设备: %1 (在线: %2)")
                                .arg(m_totalDeviceCount)
                                .arg(m_onlineDeviceCount));
    
    // 发送统计信号
    emit deviceCountChanged(m_totalDeviceCount, m_onlineDeviceCount);
}

void DeviceListPanel::clearAllDeviceCards()
{
    for (auto card : m_deviceCards) {
        card->deleteLater();
    }
    m_deviceCards.clear();
    m_allDevices.clear();
    m_selectedDeviceId.clear();
}

// 搜索相关槽函数已删除

void DeviceListPanel::onAddUAVClicked()
{
    emit addDeviceRequested("uav");
}

void DeviceListPanel::onAddDogClicked()
{
    emit addDeviceRequested("dog");
}

void DeviceListPanel::onDeleteDeviceClicked()
{
    qDebug() << "Delete device button clicked";
    
    // 创建删除设备对话框
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("删除设备");
    dialog->resize(500, 400);
    dialog->setModal(true);
    
    QVBoxLayout *layout = new QVBoxLayout(dialog);
    
    // 设置对话框样式
    dialog->setStyleSheet(
        "QDialog {"
        "    background-color: rgb(240, 240, 240);"
        "    color: rgb(50, 50, 50);"
        "}"
    );
    
    // 标题标签
    QLabel *titleLabel = new QLabel("选择要删除的设备:");
    titleLabel->setStyleSheet(
        "QLabel {"
        "    font-weight: bold;"
        "    font-size: 16px;"
        "    color: rgb(50, 50, 50);"
        "    background-color: transparent;"
        "    margin-bottom: 10px;"
        "    padding: 5px;"
        "}"
    );
    layout->addWidget(titleLabel);
    
    // 设备列表
    QTableWidget *deviceTable = new QTableWidget();
    deviceTable->setColumnCount(3);
    QStringList headers;
    headers << "设备ID" << "设备名称" << "设备类型";
    deviceTable->setHorizontalHeaderLabels(headers);
    
    // 设置表格属性
    deviceTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    deviceTable->setSelectionMode(QAbstractItemView::SingleSelection);
    deviceTable->horizontalHeader()->setStretchLastSection(true);
    deviceTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    // 隐藏行号列（垂直表头）
    deviceTable->verticalHeader()->setVisible(false);
    
    // 设置表格样式
    deviceTable->setStyleSheet(
        "QTableWidget {"
        "    background-color: white;"
        "    alternate-background-color: rgb(245, 245, 245);"
        "    color: rgb(50, 50, 50);"
        "    gridline-color: rgb(200, 200, 200);"
        "    selection-background-color: rgb(0, 120, 215);"
        "    selection-color: white;"
        "    border: 1px solid rgb(180, 180, 180);"
        "    border-radius: 4px;"
        "}"
        "QHeaderView::section {"
        "    background-color: rgb(230, 230, 230);"
        "    color: rgb(50, 50, 50);"
        "    padding: 8px;"
        "    border: 1px solid rgb(180, 180, 180);"
        "    font-weight: bold;"
        "}"
        "QTableWidget::item {"
        "    padding: 8px;"
        "    color: rgb(50, 50, 50);"
        "}"
        "QTableWidget::item:selected {"
        "    background-color: rgb(0, 120, 215);"
        "    color: white;"
        "}"
    );
    
    // 从数据库加载所有设备
    QList<DeviceInfo> allDevices = loadDevicesFromDatabase();
    deviceTable->setRowCount(allDevices.size());
    
    for (int i = 0; i < allDevices.size(); ++i) {
        const DeviceInfo &device = allDevices[i];
        
        deviceTable->setItem(i, 0, new QTableWidgetItem(device.id));
        deviceTable->setItem(i, 1, new QTableWidgetItem(device.name));
        
        QString deviceTypeText;
        if (device.type == "uav") {
            deviceTypeText = "🚁 无人机";
        } else if (device.type == "dog") {
            deviceTypeText = "🐕 机器狗";
        } else {
            deviceTypeText = device.type;
        }
        deviceTable->setItem(i, 2, new QTableWidgetItem(deviceTypeText));
    }
    
    layout->addWidget(deviceTable);
    
    // 按钮区域
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *deleteBtn = new QPushButton("删除选中设备");
    QPushButton *cancelBtn = new QPushButton("取消");
    
    deleteBtn->setStyleSheet(
        "QPushButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 rgba(220, 53, 69, 0.8), "
        "                stop:1 rgba(180, 40, 55, 0.8));"
        "    color: white;"
        "    border: 2px solid rgba(220, 53, 69, 0.5);"
        "    border-radius: 6px;"
        "    padding: 10px 16px;"
        "    font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 rgba(220, 53, 69, 1.0), "
        "                stop:1 rgba(180, 40, 55, 1.0));"
        "    border-color: rgba(220, 53, 69, 0.8);"
        "}"
        "QPushButton:pressed {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 rgba(180, 40, 55, 1.0), "
        "                stop:1 rgba(140, 30, 45, 1.0));"
        "}"
    );
    
    cancelBtn->setStyleSheet(
        "QPushButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 rgba(45, 65, 95, 0.8), "
        "                stop:1 rgba(25, 40, 65, 0.8));"
        "    color: rgb(220, 230, 242);"
        "    border: 2px solid rgba(82, 194, 242, 0.5);"
        "    border-radius: 6px;"
        "    padding: 10px 16px;"
        "    font-weight: bold;"
        "}"
        "QPushButton:hover {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "                stop:0 rgba(82, 194, 242, 0.6), "
        "                stop:1 rgba(45, 120, 180, 0.6));"
        "    border-color: rgba(82, 194, 242, 0.8);"
        "    color: white;"
        "}"
    );
    
    buttonLayout->addStretch();
    buttonLayout->addWidget(deleteBtn);
    buttonLayout->addWidget(cancelBtn);
    layout->addLayout(buttonLayout);
    
    // 连接信号
    connect(deleteBtn, &QPushButton::clicked, [this, dialog, deviceTable, allDevices]() {
        int selectedRow = deviceTable->currentRow();
        if (selectedRow >= 0 && selectedRow < allDevices.size()) {
            const DeviceInfo &selectedDevice = allDevices[selectedRow];
            
            // 确认删除
            QMessageBox confirmBox(dialog);
            confirmBox.setWindowTitle("确认删除");
            confirmBox.setText(QString("确定要删除设备 '%1' (%2) 吗？")
                .arg(selectedDevice.name)
                .arg(selectedDevice.id));
            confirmBox.setInformativeText("此操作不可恢复！");
            confirmBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
            confirmBox.setDefaultButton(QMessageBox::No);
            confirmBox.setIcon(QMessageBox::Question);
            
            // 设置确认对话框样式
            confirmBox.setStyleSheet(
                "QMessageBox {"
                "    background-color: rgb(240, 240, 240);"
                "    color: rgb(50, 50, 50);"
                "}"
                "QMessageBox QLabel {"
                "    color: rgb(50, 50, 50);"
                "    font-size: 14px;"
                "    background-color: transparent;"
                "}"
                "QMessageBox QPushButton {"
                "    background-color: rgb(225, 225, 225);"
                "    color: rgb(50, 50, 50);"
                "    border: 1px solid rgb(180, 180, 180);"
                "    border-radius: 4px;"
                "    padding: 8px 16px;"
                "    font-size: 14px;"
                "    min-width: 80px;"
                "}"
                "QMessageBox QPushButton:hover {"
                "    background-color: rgb(200, 200, 200);"
                "}"
                "QMessageBox QPushButton:pressed {"
                "    background-color: rgb(180, 180, 180);"
                "}"
            );
            
            int reply = confirmBox.exec();
            
            if (reply == QMessageBox::Yes) {
                // 执行删除操作
                if (deleteDeviceFromDatabase(selectedDevice.id)) {
                    QMessageBox successBox(dialog);
                    successBox.setWindowTitle("成功");
                    successBox.setText("设备删除成功！");
                    successBox.setIcon(QMessageBox::Information);
                    successBox.setStandardButtons(QMessageBox::Ok);
                    
                    // 设置成功对话框样式
                    successBox.setStyleSheet(
                        "QMessageBox {"
                        "    background-color: rgb(240, 240, 240);"
                        "    color: rgb(50, 50, 50);"
                        "}"
                        "QMessageBox QLabel {"
                        "    color: rgb(50, 50, 50);"
                        "    font-size: 14px;"
                        "    background-color: transparent;"
                        "}"
                        "QMessageBox QPushButton {"
                        "    background-color: rgb(76, 175, 80);"
                        "    color: white;"
                        "    border: none;"
                        "    border-radius: 4px;"
                        "    padding: 8px 16px;"
                        "    font-size: 14px;"
                        "    min-width: 80px;"
                        "    font-weight: bold;"
                        "}"
                        "QMessageBox QPushButton:hover {"
                        "    background-color: rgb(67, 160, 71);"
                        "}"
                        "QMessageBox QPushButton:pressed {"
                        "    background-color: rgb(56, 142, 60);"
                        "}"
                    );
                    
                    successBox.exec();
                    
                    // 刷新设备列表
                    refreshDeviceList();
                    
                    dialog->accept();
                } else {
                    QMessageBox errorBox(dialog);
                    errorBox.setWindowTitle("错误");
                    errorBox.setText("删除设备失败！");
                    errorBox.setIcon(QMessageBox::Warning);
                    errorBox.setStandardButtons(QMessageBox::Ok);
                    
                    // 设置错误对话框样式
                    errorBox.setStyleSheet(
                        "QMessageBox {"
                        "    background-color: rgb(240, 240, 240);"
                        "    color: rgb(50, 50, 50);"
                        "}"
                        "QMessageBox QLabel {"
                        "    color: rgb(50, 50, 50);"
                        "    font-size: 14px;"
                        "    background-color: transparent;"
                        "}"
                        "QMessageBox QPushButton {"
                        "    background-color: rgb(244, 67, 54);"
                        "    color: white;"
                        "    border: none;"
                        "    border-radius: 4px;"
                        "    padding: 8px 16px;"
                        "    font-size: 14px;"
                        "    min-width: 80px;"
                        "    font-weight: bold;"
                        "}"
                        "QMessageBox QPushButton:hover {"
                        "    background-color: rgb(229, 57, 53);"
                        "}"
                        "QMessageBox QPushButton:pressed {"
                        "    background-color: rgb(211, 47, 47);"
                        "}"
                    );
                    
                    errorBox.exec();
                }
            }
        } else {
            QMessageBox warningBox(dialog);
            warningBox.setWindowTitle("提示");
            warningBox.setText("请先选择要删除的设备！");
            warningBox.setIcon(QMessageBox::Information);
            warningBox.setStandardButtons(QMessageBox::Ok);
            
            // 设置提示对话框样式
            warningBox.setStyleSheet(
                "QMessageBox {"
                "    background-color: rgb(240, 240, 240);"
                "    color: rgb(50, 50, 50);"
                "}"
                "QMessageBox QLabel {"
                "    color: rgb(50, 50, 50);"
                "    font-size: 14px;"
                "    background-color: transparent;"
                "}"
                "QMessageBox QPushButton {"
                "    background-color: rgb(33, 150, 243);"
                "    color: white;"
                "    border: none;"
                "    border-radius: 4px;"
                "    padding: 8px 16px;"
                "    font-size: 14px;"
                "    min-width: 80px;"
                "    font-weight: bold;"
                "}"
                "QMessageBox QPushButton:hover {"
                "    background-color: rgb(30, 136, 229);"
                "}"
                "QMessageBox QPushButton:pressed {"
                "    background-color: rgb(25, 118, 210);"
                "}"
            );
            
            warningBox.exec();
        }
    });
    
    connect(cancelBtn, &QPushButton::clicked, dialog, &QDialog::reject);
    
    // 显示对话框
    dialog->exec();
    delete dialog;
}

void DeviceListPanel::onDeviceCardSelected(const QString &deviceId)
{
    // 清除之前的选择
    if (!m_selectedDeviceId.isEmpty() && m_deviceCards.contains(m_selectedDeviceId)) {
        m_deviceCards[m_selectedDeviceId]->setSelected(false);
    }
    
    m_selectedDeviceId = deviceId;
    emit deviceSelected(deviceId);
}

void DeviceListPanel::onDeviceCardControlRequested(const QString &deviceId)
{
    emit deviceControlRequested(deviceId);
}

void DeviceListPanel::onDeviceCardLocationRequested(const QString &deviceId)
{
    emit deviceLocationRequested(deviceId);
}

void DeviceListPanel::onDeviceCardDetailsRequested(const QString &deviceId)
{
    emit deviceDetailsRequested(deviceId);
}

void DeviceListPanel::onDeviceStatusChanged(const QString &deviceId, DeviceStatus status)
{
    qDebug() << "Device status changed signal received:" << deviceId << "status:" << static_cast<int>(status);
    
    // 更新内部设备列表中的状态
    for (auto &device : m_allDevices) {
        if (device.id == deviceId) {
            device.status = status;
            qDebug() << "Updated device status in internal list:" << device.name;
            break;
        }
    }
    
    // 更新统计信息显示
    updateDeviceCountStats();
}

void DeviceListPanel::setSearchKeyword(const QString &keyword)
{
    m_currentSearchKeyword = keyword.trimmed();
    applySearchAndFilter();
}

void DeviceListPanel::setFilterType(DeviceFilterType filterType)
{
    m_currentFilterType = filterType;
    applySearchAndFilter();
}

void DeviceListPanel::selectDevice(const QString &deviceId)
{
    if (m_deviceCards.contains(deviceId)) {
        // 清除之前的选择
        if (!m_selectedDeviceId.isEmpty() && m_deviceCards.contains(m_selectedDeviceId)) {
            m_deviceCards[m_selectedDeviceId]->setSelected(false);
        }
        
        // 设置新选择
        m_selectedDeviceId = deviceId;
        m_deviceCards[deviceId]->setSelected(true);
        
        emit deviceSelected(deviceId);
    }
}

void DeviceListPanel::clearSelection()
{
    if (!m_selectedDeviceId.isEmpty() && m_deviceCards.contains(m_selectedDeviceId)) {
        m_deviceCards[m_selectedDeviceId]->setSelected(false);
    }
    m_selectedDeviceId.clear();
}

void DeviceListPanel::onStatusMonitorTimer()
{
    // 定期检查设备状态
    // 这里可以实现设备状态的定期更新逻辑
    qDebug() << "Status monitor timer triggered";
    
    // TODO: 实现真实的状态检查逻辑
    // 例如：检查设备心跳、网络连接状态等
}

void DeviceListPanel::updateDeviceCount()
{
    // 更新统计数据
    m_totalDeviceCount = m_deviceCards.size();
    m_onlineDeviceCount = 0;
    m_uavCount = 0;
    m_dogCount = 0;
    
    // 统计各类设备数量
    for (const auto& card : m_deviceCards) {
        const DeviceInfo& info = card->getDeviceInfo();
        
        if (info.isOnline()) {
            m_onlineDeviceCount++;
        }
        
        if (info.type == "uav") {
            m_uavCount++;
        } else if (info.type == "dog") {
            m_dogCount++;
        }
    }
    
    // 更新显示文本 - 更详细的信息
    QString statusText = QString("设备: %1 | 在线: %2 | 🚁UAV: %3 | 🤖DOG: %4")
                        .arg(m_totalDeviceCount)
                        .arg(m_onlineDeviceCount)
                        .arg(m_uavCount)
                        .arg(m_dogCount);
    
    m_deviceCountLabel->setText(statusText);
    
    // 根据在线率设置颜色
    double onlineRate = m_totalDeviceCount > 0 ? (double)m_onlineDeviceCount / m_totalDeviceCount : 0.0;
    QString color;
    if (onlineRate >= 0.8) {
        color = "rgb(0, 255, 0)";      // 绿色 - 状态良好
    } else if (onlineRate >= 0.5) {
        color = "rgb(255, 255, 0)";    // 黄色 - 状态一般
    } else {
        color = "rgb(255, 100, 100)";  // 红色 - 状态不佳
    }
    
    m_deviceCountLabel->setStyleSheet(
        QString("QLabel {"
                "    color: %1;"
                "    background: rgba(82, 194, 242, 0.1);"
                "    border: 1px solid rgba(82, 194, 242, 0.3);"
                "    border-radius: 4px;"
                "    padding: 2px 6px;"
                "    font-weight: bold;"
                "    font-size: 11px;"
                "}").arg(color)
    );
    
    // 发送设备数量变化信号
    emit deviceCountChanged(m_totalDeviceCount, m_onlineDeviceCount);
}

void DeviceListPanel::updateDeviceListDisplay()
{
    // 清空现有显示
    for (auto card : m_deviceCards) {
        card->hide();
        m_deviceListLayout->removeWidget(card);
    }
    
    // 根据过滤条件重新显示设备（搜索功能已删除）
    QString searchText = "";
    
    for (auto card : m_deviceCards) {
        const DeviceInfo& info = card->getDeviceInfo();
        bool shouldShow = true;
        
        // 应用搜索过滤
        if (!searchText.isEmpty()) {
            if (!info.name.toLower().contains(searchText) &&
                !info.ipAddress.toLower().contains(searchText) &&
                !info.id.toLower().contains(searchText)) {
                shouldShow = false;
            }
        }
        
        // 应用类型过滤
        switch (m_currentFilterType) {
            case DeviceFilterType::UAV:
                if (info.type != "uav") shouldShow = false;
                break;
            case DeviceFilterType::Dog:
                if (info.type != "dog") shouldShow = false;
                break;
            case DeviceFilterType::Online:
                if (!info.isOnline()) shouldShow = false;
                break;
            case DeviceFilterType::Offline:
                if (info.isOnline()) shouldShow = false;
                break;
            case DeviceFilterType::All:
            default:
                // 显示所有设备
                break;
        }
        
        if (shouldShow) {
            card->show();
            m_deviceListLayout->insertWidget(m_deviceListLayout->count() - 1, card);
        }
    }
    
    // 更新设备计数
    updateDeviceCount();
}

void DeviceListPanel::applyDeviceFilter()
{
    // 过滤功能已简化，默认显示所有设备
    m_currentFilterType = DeviceFilterType::All;
    
    // 更新显示
    updateDeviceListDisplay();
}