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

#include "ui/components/DeviceCard.h"

// Qt GUI头文件
#include <QMouseEvent>
#include <QPainter>
#include <QLinearGradient>
#include <QBrush>
#include <QPen>
#include <QFont>
#include <QFontMetrics>
#include <QApplication>
#include <QDebug>

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_signalLabel(nullptr)
    , m_batteryLabel(nullptr)
    , m_signalProgressBar(nullptr)
    , m_batteryProgressBar(nullptr)
    , m_detailsButton(nullptr)
    , m_controlButton(nullptr)
    , m_locationButton(nullptr)
    , m_mainLayout(nullptr)
    , m_headerLayout(nullptr)
    , m_infoLayout(nullptr)
    , m_buttonLayout(nullptr)
{
    setupUI();
    setupStyle();
    connectSignals();
    
    // 设置卡片基本属性
    setFixedSize(CARD_WIDTH, CARD_HEIGHT);
    setMouseTracking(true);
    setAttribute(Qt::WA_Hover, true);
    
    qDebug() << "DeviceCard created for device:" << 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(6); // 减小间距
    
    // === 头部区域 ===
    m_headerLayout = new QHBoxLayout();
    m_headerLayout->setSpacing(8);
    
    // 设备图标
    m_deviceIconLabel = new QLabel();
    m_deviceIconLabel->setFixedSize(24, 24);
    m_deviceIconLabel->setScaledContents(true);
    updateDeviceIcon();
    
    // 设备名称
    m_deviceNameLabel = new QLabel(m_deviceInfo.name);
    m_deviceNameLabel->setFont(QFont("Arial", 12, QFont::Bold));
    m_deviceNameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    
    // 状态指示器（圆点）
    m_statusIndicator = new QLabel("●");
    m_statusIndicator->setFixedSize(16, 16);
    m_statusIndicator->setAlignment(Qt::AlignCenter);
    
    // 状态文本
    m_statusLabel = new QLabel(getStatusText(m_currentStatus));
    m_statusLabel->setFont(QFont("Arial", 9));
    
    m_headerLayout->addWidget(m_deviceIconLabel);
    m_headerLayout->addWidget(m_deviceNameLabel);
    m_headerLayout->addStretch();
    m_headerLayout->addWidget(m_statusIndicator);
    m_headerLayout->addWidget(m_statusLabel);
    
    // === 信息区域 ===
    m_infoLayout = new QGridLayout();
    m_infoLayout->setSpacing(4);
    
    // 位置信息 - 简化显示
    QLabel *locationIcon = new QLabel("📍");
    locationIcon->setFixedSize(14, 14);
    locationIcon->setAlignment(Qt::AlignCenter);
    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", 8));
    
    // 网络信息 - 简化显示
    QLabel *networkIcon = new QLabel("🌐");
    networkIcon->setFixedSize(14, 14);
    networkIcon->setAlignment(Qt::AlignCenter);
    m_networkLabel = new QLabel(m_deviceInfo.ipAddress);
    m_networkLabel->setFont(QFont("Arial", 8));
    
    // 信号强度 - 更紧凑
    QLabel *signalIcon = new QLabel("📶");
    signalIcon->setFixedSize(14, 14);
    signalIcon->setAlignment(Qt::AlignCenter);
    m_signalLabel = new QLabel(QString("%1%").arg(m_deviceInfo.signalStrength));
    m_signalLabel->setFont(QFont("Arial", 8));
    m_signalProgressBar = new QProgressBar();
    m_signalProgressBar->setRange(0, 100);
    m_signalProgressBar->setValue(m_deviceInfo.signalStrength);
    m_signalProgressBar->setFixedHeight(6);
    m_signalProgressBar->setTextVisible(false);
    
    // 电量水平 - 更紧凑
    QLabel *batteryIcon = new QLabel("🔋");
    batteryIcon->setFixedSize(14, 14);
    batteryIcon->setAlignment(Qt::AlignCenter);
    m_batteryLabel = new QLabel(QString("%1%").arg(m_deviceInfo.batteryLevel));
    m_batteryLabel->setFont(QFont("Arial", 8));
    m_batteryProgressBar = new QProgressBar();
    m_batteryProgressBar->setRange(0, 100);
    m_batteryProgressBar->setValue(m_deviceInfo.batteryLevel);
    m_batteryProgressBar->setFixedHeight(6);
    m_batteryProgressBar->setTextVisible(false);
    
    // 添加到网格布局
    m_infoLayout->addWidget(locationIcon, 0, 0);
    m_infoLayout->addWidget(m_locationLabel, 0, 1, 1, 2);
    m_infoLayout->addWidget(networkIcon, 1, 0);
    m_infoLayout->addWidget(m_networkLabel, 1, 1, 1, 2);
    m_infoLayout->addWidget(signalIcon, 2, 0);
    m_infoLayout->addWidget(m_signalLabel, 2, 1);
    m_infoLayout->addWidget(m_signalProgressBar, 2, 2);
    m_infoLayout->addWidget(batteryIcon, 3, 0);
    m_infoLayout->addWidget(m_batteryLabel, 3, 1);
    m_infoLayout->addWidget(m_batteryProgressBar, 3, 2);
    
    // === 操作按钮区域 ===
    m_buttonLayout = new QHBoxLayout();
    m_buttonLayout->setSpacing(4);
    
    m_detailsButton = new QPushButton("详");
    m_detailsButton->setFixedSize(32, 20);
    m_detailsButton->setToolTip("设备详情");
    m_detailsButton->setFont(QFont("Arial", 8));
    
    m_controlButton = new QPushButton("控");
    m_controlButton->setFixedSize(32, 20);
    m_controlButton->setToolTip("设备控制");
    m_controlButton->setFont(QFont("Arial", 8));
    
    m_locationButton = new QPushButton("位");
    m_locationButton->setFixedSize(32, 20);
    m_locationButton->setToolTip("设备定位");
    m_locationButton->setFont(QFont("Arial", 8));
    
    m_buttonLayout->addWidget(m_detailsButton);
    m_buttonLayout->addWidget(m_controlButton);
    m_buttonLayout->addWidget(m_locationButton);
    m_buttonLayout->addStretch();
    
    // === 组装主布局 ===
    m_mainLayout->addLayout(m_headerLayout);
    
    // 添加分隔线
    QLabel *separatorLine = new QLabel();
    separatorLine->setFixedHeight(1);
    separatorLine->setStyleSheet("background-color: rgba(82, 194, 242, 0.3);");
    m_mainLayout->addWidget(separatorLine);
    
    m_mainLayout->addLayout(m_infoLayout);
    m_mainLayout->addLayout(m_buttonLayout);
    m_mainLayout->addStretch();
}

void DeviceCard::setupStyle()
{
    // 基础卡片样式
    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;"
        "}"
        "DeviceCard:hover {"
        "    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));"
        "    border-color: rgba(82, 194, 242, 0.8);"
        "}"
    ).arg(BORDER_RADIUS);
    
    setStyleSheet(cardStyle);
    
    // 设备名称样式
    m_deviceNameLabel->setStyleSheet(
        "QLabel {"
        "    color: rgb(220, 230, 242);"
        "    font-weight: bold;"
        "    background: transparent;"
        "    border: none;"
        "}"
    );
    
    // 状态标签样式
    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);
    m_signalLabel->setStyleSheet(infoLabelStyle);
    m_batteryLabel->setStyleSheet(infoLabelStyle);
    
    // 进度条样式
    QString progressBarStyle = 
        "QProgressBar {"
        "    border: 1px solid rgba(82, 194, 242, 0.5);"
        "    border-radius: 3px;"
        "    background-color: rgba(25, 35, 45, 0.8);"
        "    text-align: center;"
        "}"
        "QProgressBar::chunk {"
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "                stop:0 #00FF7F, stop:0.7 #FFD700, stop:1 #FF4444);"
        "    border-radius: 3px;"
        "}";
    
    m_signalProgressBar->setStyleSheet(progressBarStyle);
    m_batteryProgressBar->setStyleSheet(progressBarStyle);
    
    // 按钮样式
    QString buttonStyle = 
        "QPushButton {"
        "    background: rgba(82, 194, 242, 0.2);"
        "    color: rgb(220, 230, 242);"
        "    border: 1px solid rgba(82, 194, 242, 0.4);"
        "    border-radius: 4px;"
        "    font-size: 12px;"
        "}"
        "QPushButton:hover {"
        "    background: rgba(82, 194, 242, 0.4);"
        "    border-color: rgba(82, 194, 242, 0.8);"
        "}"
        "QPushButton:pressed {"
        "    background: rgba(82, 194, 242, 0.6);"
        "}";
    
    m_detailsButton->setStyleSheet(buttonStyle);
    m_controlButton->setStyleSheet(buttonStyle);
    m_locationButton->setStyleSheet(buttonStyle);
    
    // 更新状态颜色
    updateStatusColor();
}

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));
    m_signalProgressBar->setValue(device.signalStrength);
    m_batteryProgressBar->setValue(device.batteryLevel);
    
    updateDeviceIcon();
    updateDeviceStatus(device.status);
    
    qDebug() << "DeviceCard updated for device:" << device.name;
}

void DeviceCard::updateDeviceStatus(DeviceStatus status)
{
    m_currentStatus = status;
    m_statusLabel->setText(getStatusText(status));
    updateStatusColor();
    
    qDebug() << "Device status updated:" << m_deviceInfo.name << "status:" << static_cast<int>(status);
}

void DeviceCard::updateSignalStrength(int strength)
{
    m_deviceInfo.signalStrength = qBound(0, strength, 100);
    m_signalProgressBar->setValue(m_deviceInfo.signalStrength);
    
    // 根据信号强度更新颜色
    QString color;
    if (strength >= 70) color = "#00FF7F";        // 绿色
    else if (strength >= 30) color = "#FFD700";   // 黄色
    else color = "#FF4444";                       // 红色
    
    m_signalProgressBar->setStyleSheet(
        m_signalProgressBar->styleSheet() + 
        QString("QProgressBar::chunk { background-color: %1; }").arg(color)
    );
}

void DeviceCard::updateBatteryLevel(int level)
{
    m_deviceInfo.batteryLevel = qBound(0, level, 100);
    m_batteryProgressBar->setValue(m_deviceInfo.batteryLevel);
    
    // 根据电量水平更新颜色
    QString color;
    if (level >= 50) color = "#00FF7F";          // 绿色
    else if (level >= 20) color = "#FFD700";     // 黄色
    else color = "#FF4444";                      // 红色
    
    m_batteryProgressBar->setStyleSheet(
        m_batteryProgressBar->styleSheet() + 
        QString("QProgressBar::chunk { background-color: %1; }").arg(color)
    );
}

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) {
        setSelected(!m_isSelected);
        event->accept();
    }
    QWidget::mousePressEvent(event);
}

void DeviceCard::enterEvent(QEvent *event)
{
    m_isHovered = true;
    update();
    QWidget::enterEvent(event);
}

void DeviceCard::leaveEvent(QEvent *event)
{
    m_isHovered = false;
    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;
    emit deviceDetailsRequested(m_deviceInfo.id);
}

void DeviceCard::onControlClicked()
{
    qDebug() << "Control clicked for device:" << m_deviceInfo.name;
    emit deviceControlRequested(m_deviceInfo.id);
}

void DeviceCard::onLocationClicked()
{
    qDebug() << "Location clicked for device:" << m_deviceInfo.name;
    emit deviceLocationRequested(m_deviceInfo.id);
}

void DeviceCard::updateStatusColor()
{
    QString color = getStatusColor(m_currentStatus);
    m_statusIndicator->setStyleSheet(QString("QLabel { color: %1; background: transparent; border: none; }").arg(color));
    
    // 更新卡片边框颜色
    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(24, 24, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    } else {
        qWarning() << "Failed to load device icon:" << iconPath;
        m_deviceIconLabel->setText("📱"); // 备用图标
    }
}

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 "#888888";  // 灰色
    }
}

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