/**
 * @file DeviceCard.cpp
 * @brief 设备卡片组件实现
 * @author CasualtySightPlus Team
 * @date 2024-12-01
 * @version 1.0
 */

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

// Qt GUI头文件
#include <QMouseEvent>
#include <QPainter>
#include <QLinearGradient>
#include <QBrush>
#include <QPen>
#include <QFont>
#include <QFontMetrics>
#include <QApplication>
#include <QDebug>
#include <QPropertyAnimation>
#include <QGraphicsDropShadowEffect>
#include <QEasingCurve>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>

DeviceCard::DeviceCard(const DeviceInfo &device, QWidget *parent)
    : QWidget(parent)
    , m_deviceInfo(device)
    , m_currentStatus(device.status)
    , m_isSelected(false)
    , m_isHovered(false)
    , m_deviceIconLabel(nullptr)
    , m_deviceNameLabel(nullptr)
    , m_statusLabel(nullptr)
    , m_statusIndicator(nullptr)
    , m_locationLabel(nullptr)
    , m_networkLabel(nullptr)
    , m_detailsButton(nullptr)
    , m_controlButton(nullptr)
    , m_locationButton(nullptr)
    , m_mainLayout(nullptr)
    , m_headerLayout(nullptr)
    , m_infoLayout(nullptr)
    , m_buttonLayout(nullptr)
    , m_hoverAnimation(nullptr)
    , m_scaleAnimation(nullptr)
    , m_shadowEffect(nullptr)
{
    setupUI();
    setupStyle();
    setupAnimations(); // 添加动画初始化
    connectSignals();
    
    // 设置卡片基本属性
    setFixedSize(CARD_WIDTH, CARD_HEIGHT);
    setMouseTracking(true);
    setAttribute(Qt::WA_Hover, true);
    
    qDebug() << "DeviceCard created for device:" << device.name;
    SystemLogger::getInstance()->logDebug(QString("创建设备卡片: %1").arg(device.name));
}

DeviceCard::~DeviceCard()
{
    qDebug() << "DeviceCard destroyed for device:" << m_deviceInfo.name;
}

void DeviceCard::setupUI()
{
    // 创建主布局 - 增加垂直间距
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(PADDING, PADDING, PADDING, PADDING);
    m_mainLayout->setSpacing(18); // 增加间距以适应更大的卡片
    
    // === 头部区域 ===
    m_headerLayout = new QHBoxLayout();
    m_headerLayout->setSpacing(8); // 减少间距，让名称更靠左
    m_headerLayout->setContentsMargins(0, 0, 0, 0); // 移除边距

    // 设备图标 - 增大尺寸提高区分度
    m_deviceIconLabel = new QLabel();
    m_deviceIconLabel->setFixedSize(40, 40); // 增大图标尺寸
    m_deviceIconLabel->setScaledContents(true);
    m_deviceIconLabel->setAlignment(Qt::AlignCenter);
    updateDeviceIcon();

    // 设备名称 - 调整字体和位置
    m_deviceNameLabel = new QLabel(m_deviceInfo.name);
    m_deviceNameLabel->setFont(QFont("Arial", 15, QFont::Bold)); // 稍微减小字体
    m_deviceNameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_deviceNameLabel->setWordWrap(false); // 禁用换行
    m_deviceNameLabel->setMinimumWidth(140); // 增加最小宽度，确保名称完整显示
    m_deviceNameLabel->setMaximumHeight(20); // 限制高度，防止换行
    m_deviceNameLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // 左对齐，垂直居中
    m_deviceNameLabel->setContentsMargins(0, 0, 0, 0); // 恢复正常边距

    // 状态指示器（圆点）- 增大尺寸提高可见性
    m_statusIndicator = new QLabel("●");
    m_statusIndicator->setFixedSize(28, 28); // 增大状态指示器
    m_statusIndicator->setAlignment(Qt::AlignCenter);
    m_statusIndicator->setFont(QFont("Arial", 22)); // 增大字体

    // 状态文本 - 适当调整字体
    m_statusLabel = new QLabel(getStatusText(m_currentStatus));
    m_statusLabel->setFont(QFont("Arial", 13, QFont::Bold));
    m_statusLabel->setMinimumWidth(40); // 确保状态文本有足够空间
    
    m_headerLayout->addWidget(m_deviceIconLabel);
    m_headerLayout->addWidget(m_deviceNameLabel, 1); // 给名称更多空间
    m_headerLayout->addWidget(m_statusIndicator);
    m_headerLayout->addWidget(m_statusLabel);
    
    // === 信息和按钮区域 - 水平布局 ===
    QHBoxLayout *contentLayout = new QHBoxLayout();
    contentLayout->setSpacing(20);

    // 左侧：信息区域
    m_infoLayout = new QGridLayout();
    m_infoLayout->setSpacing(12);

    // 位置信息 - 增大显示
    QLabel *locationIcon = new QLabel("📍");
    locationIcon->setFixedSize(24, 24);
    locationIcon->setAlignment(Qt::AlignCenter);
    locationIcon->setFont(QFont("Arial", 16));
    m_locationLabel = new QLabel(QString("%1,%2").arg(m_deviceInfo.longitude, 0, 'f', 2).arg(m_deviceInfo.latitude, 0, 'f', 2));
    m_locationLabel->setFont(QFont("Arial", 13));

    // 网络信息 - 增大显示
    QLabel *networkIcon = new QLabel("🌐");
    networkIcon->setFixedSize(24, 24);
    networkIcon->setAlignment(Qt::AlignCenter);
    networkIcon->setFont(QFont("Arial", 16));
    m_networkLabel = new QLabel(m_deviceInfo.ipAddress);
    m_networkLabel->setFont(QFont("Arial", 13));

    // 添加到网格布局
    m_infoLayout->addWidget(locationIcon, 0, 0);
    m_infoLayout->addWidget(m_locationLabel, 0, 1);
    m_infoLayout->addWidget(networkIcon, 1, 0);
    m_infoLayout->addWidget(m_networkLabel, 1, 1);

    // 创建信息区域容器
    QWidget *infoWidget = new QWidget();
    infoWidget->setLayout(m_infoLayout);

    // 右侧：操作按钮区域
    m_buttonLayout = new QVBoxLayout();
    m_buttonLayout->setSpacing(6);

    m_detailsButton = new QPushButton("详情");
    m_detailsButton->setFixedSize(60, 32);
    m_detailsButton->setToolTip("设备详情");
    m_detailsButton->setFont(QFont("Arial", 12, QFont::Bold));

    m_controlButton = new QPushButton(getConnectionButtonText());
    m_controlButton->setFixedSize(60, 32);
    m_controlButton->setToolTip(getConnectionButtonTooltip());
    m_controlButton->setFont(QFont("Arial", 12, QFont::Bold));

    m_locationButton = new QPushButton("定位");
    m_locationButton->setFixedSize(60, 32);
    m_locationButton->setToolTip("设备定位");
    m_locationButton->setFont(QFont("Arial", 12, QFont::Bold));

    m_buttonLayout->addWidget(m_detailsButton);
    m_buttonLayout->addWidget(m_controlButton);
    m_buttonLayout->addWidget(m_locationButton);

    // 创建按钮区域容器
    QWidget *buttonWidget = new QWidget();
    buttonWidget->setLayout(m_buttonLayout);

    // 添加到水平布局
    contentLayout->addWidget(infoWidget, 1); // 信息区域占更多空间
    contentLayout->addWidget(buttonWidget, 0); // 按钮区域固定大小
    
    // === 组装主布局 ===
    m_mainLayout->addLayout(m_headerLayout);

    // 添加分隔线
    QLabel *separatorLine = new QLabel();
    separatorLine->setFixedHeight(3);
    separatorLine->setStyleSheet("background-color: rgba(82, 194, 242, 0.6); margin: 4px 0px; border-radius: 1px;");
    m_mainLayout->addWidget(separatorLine);

    // 添加新的内容布局（信息和按钮水平排列）
    m_mainLayout->addLayout(contentLayout);
    m_mainLayout->addStretch();
}

void DeviceCard::setupStyle()
{
    // 基础卡片样式（移除CSS悬停样式，使用动画实现）
    QString cardStyle = QString(
        "DeviceCard {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "                stop:0 rgba(45, 65, 95, 0.9),"
        "                stop:1 rgba(25, 40, 65, 0.9));"
        "    border: 2px solid rgba(82, 194, 242, 0.4);"
        "    border-radius: %1px;"
        "}"
    ).arg(BORDER_RADIUS);
    
    setStyleSheet(cardStyle);
    
    // 设备名称样式
    m_deviceNameLabel->setStyleSheet(
        "QLabel {"
        "    color: rgb(220, 230, 242);"
        "    font-weight: bold;"
        "    background: transparent;"
        "    border: none;"
        "    padding: 2px;"
        "    min-height: 20px;"
        "}"
    );
    
    // 状态标签样式
    m_statusLabel->setStyleSheet(
        "QLabel {"
        "    color: rgb(180, 190, 200);"
        "    background: transparent;"
        "    border: none;"
        "}"
    );
    
    // 信息标签样式
    QString infoLabelStyle = 
        "QLabel {"
        "    color: rgb(160, 170, 180);"
        "    background: transparent;"
        "    border: none;"
        "}";
    
    m_locationLabel->setStyleSheet(infoLabelStyle);
    m_networkLabel->setStyleSheet(infoLabelStyle);
    
    // 按钮样式 - 优化为更清晰的显示
    QString buttonStyle =
        "QPushButton {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "                stop:0 rgba(82, 194, 242, 0.3),"
        "                stop:1 rgba(45, 120, 180, 0.3));"
        "    color: rgb(230, 240, 250);"
        "    border: 2px solid rgba(82, 194, 242, 0.5);"
        "    border-radius: 6px;"
        "    font-size: 12px;"
        "    font-weight: bold;"
        "    padding: 2px;"
        "}"
        "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.9);"
        "    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));"
        "}";
    
    m_detailsButton->setStyleSheet(buttonStyle);
    m_controlButton->setStyleSheet(buttonStyle);
    m_locationButton->setStyleSheet(buttonStyle);
    
    // 更新状态颜色
    updateStatusColor();
}

void DeviceCard::setupAnimations()
{
    // 创建阴影效果
    m_shadowEffect = new QGraphicsDropShadowEffect(this);
    m_shadowEffect->setBlurRadius(15);
    m_shadowEffect->setColor(QColor(82, 194, 242, 100));
    m_shadowEffect->setOffset(0, 3);
    setGraphicsEffect(m_shadowEffect);
    
    // 创建悬停动画（阴影模糊半径）
    m_hoverAnimation = new QPropertyAnimation(m_shadowEffect, "blurRadius", this);
    m_hoverAnimation->setDuration(200);
    m_hoverAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    // 创建缩放动画（会在需要时手动创建）
    m_scaleAnimation = nullptr;
}

void DeviceCard::animateStatusChange(DeviceStatus oldStatus, DeviceStatus newStatus)
{
    // 状态指示器闪烁动画
    QPropertyAnimation *flashAnimation = new QPropertyAnimation(m_statusIndicator, "windowOpacity", this);
    flashAnimation->setDuration(300);
    flashAnimation->setKeyValueAt(0, 1.0);
    flashAnimation->setKeyValueAt(0.5, 0.3);
    flashAnimation->setKeyValueAt(1, 1.0);
    flashAnimation->setEasingCurve(QEasingCurve::InOutQuad);
    
    // 卡片边框闪烁效果
    QPropertyAnimation *borderAnimation = new QPropertyAnimation(this);
    borderAnimation->setDuration(500);
    
    // 根据状态变化类型选择不同的动画效果
    QString notificationColor;
    if (newStatus == DeviceStatus::Online && oldStatus != DeviceStatus::Online) {
        // 设备上线 - 绿色闪烁
        notificationColor = "rgba(0, 255, 127, 0.8)";
    } else if (newStatus == DeviceStatus::Offline) {
        // 设备离线 - 红色闪烁
        notificationColor = "rgba(255, 68, 68, 0.8)";
    } else if (newStatus == DeviceStatus::Warning) {
        // 设备警告 - 黄色闪烁
        notificationColor = "rgba(255, 215, 0, 0.8)";
    } else {
        // 其他状态变化 - 蓝色闪烁
        notificationColor = "rgba(82, 194, 242, 0.8)";
    }
    
    // 设置临时的闪烁样式
    connect(flashAnimation, &QPropertyAnimation::valueChanged, this, [this, notificationColor](const QVariant &value) {
        QString flashStyle = QString(
            "DeviceCard {"
            "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
            "                stop:0 rgba(45, 65, 95, 0.9),"
            "                stop:1 rgba(25, 40, 65, 0.9));"
            "    border: 3px solid %1;"
            "    border-radius: %2px;"
            "}"
        ).arg(notificationColor).arg(BORDER_RADIUS);
        
        setStyleSheet(flashStyle);
    });
    
    // 动画结束后恢复正常样式并更新状态颜色
    connect(flashAnimation, &QPropertyAnimation::finished, this, [this, flashAnimation]() {
        // 恢复默认样式
        QString defaultStyle = QString(
            "DeviceCard {"
            "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
            "                stop:0 rgba(45, 65, 95, 0.9),"
            "                stop:1 rgba(25, 40, 65, 0.9));"
            "    border: 2px solid rgba(82, 194, 242, 0.4);"
            "    border-radius: %1px;"
            "}"
        ).arg(BORDER_RADIUS);
        
        setStyleSheet(defaultStyle);
        
        // 更新状态颜色
        updateStatusColor();
        
        // 清理动画对象
        flashAnimation->deleteLater();
    });
    
    // 启动动画
    flashAnimation->start();
}

void DeviceCard::connectSignals()
{
    connect(m_detailsButton, &QPushButton::clicked, this, &DeviceCard::onDetailsClicked);
    connect(m_controlButton, &QPushButton::clicked, this, &DeviceCard::onControlClicked);
    connect(m_locationButton, &QPushButton::clicked, this, &DeviceCard::onLocationClicked);
}

void DeviceCard::updateDeviceInfo(const DeviceInfo &device)
{
    m_deviceInfo = device;
    
    // 更新界面显示
    m_deviceNameLabel->setText(device.name);
    m_locationLabel->setText(formatCoordinates(device.longitude, device.latitude));
    m_networkLabel->setText(QString("%1:%2").arg(device.ipAddress).arg(device.port));
    
    updateDeviceIcon();
    updateDeviceStatus(device.status);
    
    qDebug() << "DeviceCard updated for device:" << device.name;
}

void DeviceCard::updateDeviceStatus(DeviceStatus status)
{
    if (m_currentStatus != status) {
        DeviceStatus oldStatus = m_currentStatus;
        m_currentStatus = status;
        m_statusLabel->setText(getStatusText(status));
        
        // 更新连接按钮文本和提示
        m_controlButton->setText(getConnectionButtonText());
        m_controlButton->setToolTip(getConnectionButtonTooltip());
        
        // 添加状态变化动画效果
        animateStatusChange(oldStatus, status);
        
        qDebug() << "Device status updated with animation:" << m_deviceInfo.name 
                 << "from" << static_cast<int>(oldStatus) << "to" << static_cast<int>(status);
    }
}



void DeviceCard::updateLocation(double longitude, double latitude)
{
    m_deviceInfo.longitude = longitude;
    m_deviceInfo.latitude = latitude;
    m_locationLabel->setText(formatCoordinates(longitude, latitude));
}

void DeviceCard::setSelected(bool selected)
{
    if (m_isSelected != selected) {
        m_isSelected = selected;
        update(); // 触发重绘
        
        if (selected) {
            emit deviceSelected(m_deviceInfo.id);
        }
    }
}

void DeviceCard::refreshStatus()
{
    // 这里可以添加从数据库刷新状态的逻辑
    qDebug() << "Refreshing status for device:" << m_deviceInfo.name;
    
    // 暂时使用模拟数据
    // 实际实现中应该从DeviceManager或数据库获取最新状态
    updateDeviceStatus(m_currentStatus);
}

void DeviceCard::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        bool newSelected = !m_isSelected;
        setSelected(newSelected);
        if (newSelected) {
            SystemLogger::getInstance()->logInfo(QString("选中设备: %1").arg(m_deviceInfo.name));
        }
        event->accept();
    }
    QWidget::mousePressEvent(event);
}

void DeviceCard::enterEvent(QEvent *event)
{
    m_isHovered = true;
    
    // 启动悬停动画效果
    if (m_hoverAnimation && m_shadowEffect) {
        m_hoverAnimation->setStartValue(15);
        m_hoverAnimation->setEndValue(25);
        m_hoverAnimation->start();
        
        // 更新阴影颜色为更亮的蓝色
        m_shadowEffect->setColor(QColor(82, 194, 242, 150));
    }
    
    // 更新卡片背景以实现更明显的悬停效果
    QString enhancedHoverStyle = QString(
        "DeviceCard {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "                stop:0 rgba(82, 194, 242, 0.4),"
        "                stop:1 rgba(45, 120, 180, 0.4));"
        "    border: 2px solid rgba(82, 194, 242, 1.0);"
        "    border-radius: %1px;"
        "}"
    ).arg(BORDER_RADIUS);
    
    setStyleSheet(enhancedHoverStyle);
    
    update();
    QWidget::enterEvent(event);
}

void DeviceCard::leaveEvent(QEvent *event)
{
    m_isHovered = false;
    
    // 停止悬停动画效果
    if (m_hoverAnimation && m_shadowEffect) {
        m_hoverAnimation->setStartValue(25);
        m_hoverAnimation->setEndValue(15);
        m_hoverAnimation->start();
        
        // 恢复阴影颜色
        m_shadowEffect->setColor(QColor(82, 194, 242, 100));
    }
    
    // 恢复卡片默认背景
    QString defaultStyle = QString(
        "DeviceCard {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
        "                stop:0 rgba(45, 65, 95, 0.9),"
        "                stop:1 rgba(25, 40, 65, 0.9));"
        "    border: 2px solid rgba(82, 194, 242, 0.4);"
        "    border-radius: %1px;"
        "}"
    ).arg(BORDER_RADIUS);
    
    setStyleSheet(defaultStyle);
    
    update();
    QWidget::leaveEvent(event);
}

void DeviceCard::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);
    
    // 如果被选中，绘制选中边框
    if (m_isSelected) {
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);
        
        QPen pen(QColor(82, 194, 242), 3);
        painter.setPen(pen);
        painter.setBrush(Qt::NoBrush);
        painter.drawRoundedRect(rect().adjusted(1, 1, -1, -1), BORDER_RADIUS, BORDER_RADIUS);
    }
}

void DeviceCard::onDetailsClicked()
{
    qDebug() << "Details clicked for device:" << m_deviceInfo.name;
    SystemLogger::getInstance()->logInfo(QString("查看设备详情: %1").arg(m_deviceInfo.name));
    emit deviceDetailsRequested(m_deviceInfo.id);
}

void DeviceCard::onControlClicked()
{
    qDebug() << "Connection toggle clicked for device:" << m_deviceInfo.name;
    
    // 切换设备连接状态
    DeviceStatus newStatus;
    if (m_currentStatus == DeviceStatus::Online) {
        // 当前在线，切换为离线
        newStatus = DeviceStatus::Offline;
        qDebug() << "Disconnecting device:" << m_deviceInfo.name;
        SystemLogger::getInstance()->logInfo(QString("正在断开连接: %1").arg(m_deviceInfo.name));
    } else {
        // 当前离线，切换为在线
        newStatus = DeviceStatus::Online;
        qDebug() << "Connecting device:" << m_deviceInfo.name;
        SystemLogger::getInstance()->logInfo(QString("正在连接设备: %1").arg(m_deviceInfo.name));
    }
    
    // 更新数据库中的状态
    if (updateDeviceStatusInDatabase(newStatus)) {
        // 数据库更新成功，更新UI
        updateDeviceStatus(newStatus);
        m_deviceInfo.status = newStatus;
        
        // 更新按钮文本和提示
        m_controlButton->setText(getConnectionButtonText());
        m_controlButton->setToolTip(getConnectionButtonTooltip());
        
        // 发送状态变化信号，通知父组件更新统计信息
        emit deviceStatusChanged(m_deviceInfo.id, newStatus);
        
        qDebug() << "Device status successfully updated:" << m_deviceInfo.name 
                 << "to" << (newStatus == DeviceStatus::Online ? "Online" : "Offline");
        
        // 记录连接状态变更成功
        QString statusText = (newStatus == DeviceStatus::Online) ? "上线" : "离线";
        SystemLogger::getInstance()->logSuccess(QString("设备 %1 已%2").arg(m_deviceInfo.name).arg(statusText));
    } else {
        qWarning() << "Failed to update device status in database for:" << m_deviceInfo.name;
        SystemLogger::getInstance()->logError(QString("设备状态更新失败: %1").arg(m_deviceInfo.name));
        // 可以显示错误提示给用户
    }
}

void DeviceCard::onLocationClicked()
{
    qDebug() << "Location clicked for device:" << m_deviceInfo.name;
    SystemLogger::getInstance()->logInfo(QString("请求设备定位: %1").arg(m_deviceInfo.name));
    emit deviceLocationRequested(m_deviceInfo.id);
}

void DeviceCard::updateStatusColor()
{
    QString color = getStatusColor(m_currentStatus);
    
    // 为状态指示器添加发光效果和阴影
    QString shadowColor;
    switch (m_currentStatus) {
        case DeviceStatus::Online:
            shadowColor = "rgba(0, 255, 127, 0.6)"; // 绿色发光
            break;
        case DeviceStatus::Warning:
            shadowColor = "rgba(255, 215, 0, 0.6)"; // 黄色发光
            break;
        case DeviceStatus::Offline:
            shadowColor = "rgba(255, 68, 68, 0.6)"; // 红色发光
            break;
        default:
            shadowColor = "rgba(136, 136, 136, 0.6)"; // 灰色发光
            break;
    }
    
    m_statusIndicator->setStyleSheet(QString(
        "QLabel {"
        "    color: %1;"
        "    background: qradialgradient(cx:0.5, cy:0.5, radius:0.8,"
        "                 stop:0 %2, stop:1 transparent);"
        "    border-radius: 14px;"
        "    border: 2px solid %1;"
        "    font-weight: bold;"
        "}"
    ).arg(color).arg(shadowColor));
    
    // 更新卡片边框颜色
    QString borderColor;
    switch (m_currentStatus) {
        case DeviceStatus::Online:
            borderColor = "rgba(0, 255, 127, 0.6)";
            break;
        case DeviceStatus::Warning:
            borderColor = "rgba(255, 215, 0, 0.6)";
            break;
        case DeviceStatus::Offline:
            borderColor = "rgba(255, 68, 68, 0.6)";
            break;
        default:
            borderColor = "rgba(136, 136, 136, 0.6)";
            break;
    }
    
    setStyleSheet(styleSheet().replace(QRegExp("border: [^;]*;"), QString("border: 2px solid %1;").arg(borderColor)));
}

void DeviceCard::updateDeviceIcon()
{
    QString iconPath = m_deviceInfo.getTypeIconPath();
    QPixmap pixmap(iconPath);
    if (!pixmap.isNull()) {
        m_deviceIconLabel->setPixmap(pixmap.scaled(36, 36, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        // 添加图标背景效果
        m_deviceIconLabel->setStyleSheet(
            "QLabel {"
            "    background: qlineargradient(x1:0, y1:0, x2:1, y2:1,"
            "                stop:0 rgba(82, 194, 242, 0.15),"
            "                stop:1 rgba(45, 120, 180, 0.15));"
            "    border: 2px solid rgba(82, 194, 242, 0.3);"
            "    border-radius: 20px;"
            "    padding: 2px;"
            "}"
        );
    } else {
        qWarning() << "Failed to load device icon:" << iconPath;
        // 设置默认设备图标，根据设备类型选择
        if (m_deviceInfo.type == "uav") {
            m_deviceIconLabel->setText("🚁"); // 无人机图标
            m_deviceIconLabel->setFont(QFont("Arial", 20));
        } else if (m_deviceInfo.type == "dog") {
            m_deviceIconLabel->setText("🐕"); // 机器狗图标
            m_deviceIconLabel->setFont(QFont("Arial", 20));
        } else {
            m_deviceIconLabel->setText("📱"); // 备用图标
            m_deviceIconLabel->setFont(QFont("Arial", 18));
        }
        // 添加图标背景效果
        m_deviceIconLabel->setStyleSheet(
            "QLabel {"
            "    background: qlineargradient(x1:0, y1:0, x2:1, y2:1,"
            "                stop:0 rgba(82, 194, 242, 0.15),"
            "                stop:1 rgba(45, 120, 180, 0.15));"
            "    border: 2px solid rgba(82, 194, 242, 0.3);"
            "    border-radius: 20px;"
            "    padding: 2px;"
            "}"
        );
    }
}

QString DeviceCard::getStatusText(DeviceStatus status) const
{
    switch (status) {
        case DeviceStatus::Online:   return "在线";
        case DeviceStatus::Warning:  return "警告";
        case DeviceStatus::Offline:  return "离线";
        default:                     return "未知";
    }
}

QString DeviceCard::getStatusColor(DeviceStatus status) const
{
    switch (status) {
        case DeviceStatus::Online:   return "#00FF7F";  // 明亮绿色
        case DeviceStatus::Warning:  return "#FFD700";  // 明亮黄色
        case DeviceStatus::Offline:  return "#FF4444";  // 明亮红色
        default:                     return "#A0A0A0";  // 明亮灰色
    }
}

QString DeviceCard::formatCoordinates(double longitude, double latitude) const
{
    return QString("N%1, E%2")
        .arg(latitude, 0, 'f', 2)
        .arg(longitude, 0, 'f', 2);
}

QString DeviceCard::getConnectionButtonText() const
{
    if (m_currentStatus == DeviceStatus::Online) {
        return "断开";
    } else {
        return "连接";
    }
}

QString DeviceCard::getConnectionButtonTooltip() const
{
    if (m_currentStatus == DeviceStatus::Online) {
        return "断开设备连接";
    } else {
        return "连接到设备";
    }
}

bool DeviceCard::updateDeviceStatusInDatabase(DeviceStatus status)
{
    // 创建唯一的数据库连接名称（包含时间戳避免重复）
    QString connectionName = QString("DeviceCard_%1_%2").arg(m_deviceInfo.id).arg(QDateTime::currentMSecsSinceEpoch());
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", connectionName);
    db.setHostName("localhost");
    db.setPort(3306);
    db.setDatabaseName("Client");
    db.setUserName("root");
    db.setPassword("hzk200407140238");
    
    if (!db.open()) {
        qWarning() << "Failed to connect to database for device status update:" << db.lastError().text();
        return false;
    }
    
    QSqlQuery query(db);
    
    // 将DeviceStatus转换为数据库中的state值 (0=离线, 1=在线)
    int stateValue = (status == DeviceStatus::Online) ? 1 : 0;
    
    // 更新设备状态
    QString sql = "UPDATE devices SET state = ? WHERE id = ?";
    query.prepare(sql);
    query.addBindValue(stateValue);
    query.addBindValue(m_deviceInfo.id);
    
    bool success = query.exec();
    if (!success) {
        qWarning() << "Failed to update device status in database:" << query.lastError().text();
    } else {
        qDebug() << "Successfully updated device status in database:" << m_deviceInfo.id 
                 << "state:" << stateValue;
    }
    
    db.close();
    return success;
}