/**
 * @file MainWindow.cpp
 * @brief 战场探索系统主控制界面实现
 * @author CasualtySightPlus Team
 * @date 2024-01-01
 * @version 2.0
 */

#include "ui/main/MainWindow.h"
#include "build/ui_MainWindow.h"
#include "ui/dialogs/DeviceDialog.h"
#include "utils/SystemLogger.h"
#include "styles/ModernStyleManager.h"

// Qt GUI头文件
#include <QWebEngineView>
#include <QString>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QGridLayout>
#include <QDir>
#include <QUrl>
#include <QWebEnginePage>
#include <QMessageBox>
#include <QComboBox>
#include <QTime>
#include <QDebug>
#include <QFileInfo>
#include <QBrush>
#include <QColor>
#include <QApplication>
#include <QDesktopWidget>

// Qt SQL头文件
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QLineEdit>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QHeaderView>
#include <QQuickWidget>
#include <QTimer>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QSplitter>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_ui(new Ui::MainWindow)
    , m_deviceListPanel(nullptr)
    , m_systemLogPanel(nullptr)
    , m_rightFunctionPanel(nullptr)
    , m_leftPanelSplitter(nullptr)
    , m_intelligenceUI(nullptr)
{
    m_ui->setupUi(this);
    
    setupUI();
    setupStyle();
    connectSignals();

    // 初始化现代样式管理器
    initializeModernStyles();

    // 初始化默认数据
    m_robotList.append(qMakePair(QString("Alice"), QString("192.168.0.1")));
    m_robotList.append(qMakePair(QString("Bob"), QString("192.168.0.2")));
}

MainWindow::~MainWindow()
{
    if (m_intelligenceUI) {
        delete m_intelligenceUI;
        m_intelligenceUI = nullptr;
    }
    delete m_ui;
}

void MainWindow::setupUI()
{
    // 设置窗口最小尺寸
    this->setMinimumSize(1400, 1000);
    
    // 窗口接近全屏显示
    QRect screenGeometry = QApplication::desktop()->screenGeometry();
    int width = screenGeometry.width() - 100;  // 留50px边距
    int height = screenGeometry.height() - 100; // 留50px边距
    this->resize(width, height);
    
    // 窗口居中显示
    int x = (screenGeometry.width() - this->width()) / 2;
    int y = (screenGeometry.height() - this->height()) / 2;
    this->move(x, y);
    
    // 初始化随机数生成器
    qsrand(QTime::currentTime().msec());
    
    // 创建并集成SystemLogPanel和DeviceListPanel到左侧面板
    setupSystemLogPanel();
    
    // 创建并集成右侧功能面板
    setupRightFunctionPanel();
    
    // 恢复地图显示控制
    setupMapDisplay();
    // 注意：原有的重复设备管理按钮已被移除，功能集成在DeviceListPanel中
    
    // 记录系统启动日志
    SystemLogger::getInstance()->logInfo("系统启动完成");
}

void MainWindow::setupSystemLogPanel()
{
    // 创建系统日志面板
    m_systemLogPanel = new SystemLogPanel(this);
    
    // 创建设备列表面板
    m_deviceListPanel = new DeviceListPanel(this);
    
    // 创建垂直分割器
    m_leftPanelSplitter = new QSplitter(Qt::Vertical, this);
    
    // 设置系统日志面板的高度限制
    m_systemLogPanel->setMinimumHeight(200);
    m_systemLogPanel->setMaximumHeight(400);
    
    // 设置设备管理面板的高度限制
    m_deviceListPanel->setMinimumHeight(300);
    
    // 添加面板到分割器
    m_leftPanelSplitter->addWidget(m_systemLogPanel);
    m_leftPanelSplitter->addWidget(m_deviceListPanel);
    
    // 设置分割比例 (35% : 65%)
    m_leftPanelSplitter->setSizes(QList<int>() << 350 << 650);
    
    // 设置分割器样式
    m_leftPanelSplitter->setStyleSheet(
        "QSplitter::handle {"
        "  background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "              stop:0 rgba(82, 194, 242, 0.3),"
        "              stop:0.5 rgba(82, 194, 242, 0.8),"
        "              stop:1 rgba(82, 194, 242, 0.3));"
        "  border-radius: 2px;"
        "  height: 8px;"
        "}"
        "QSplitter::handle:hover {"
        "  background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
        "              stop:0 rgba(82, 194, 242, 0.5),"
        "              stop:0.5 rgba(82, 194, 242, 1.0),"
        "              stop:1 rgba(82, 194, 242, 0.5));"
        "}"
    );
    
    // 获取左侧面板的布局
    QVBoxLayout *leftLayout = qobject_cast<QVBoxLayout*>(m_ui->leftPanel->layout());
    if (leftLayout) {
        // 简单的方法：隐藏原有控件而不是删除，避免内存管理问题
        for (int i = 0; i < leftLayout->count(); ++i) {
            QLayoutItem *item = leftLayout->itemAt(i);
            if (item && item->widget()) {
                item->widget()->hide();
            }
        }
        
        // 将分割器添加到左侧面板
        leftLayout->addWidget(m_leftPanelSplitter);
        
        // 连接DeviceListPanel信号
        connect(m_deviceListPanel, &DeviceListPanel::deviceSelected, 
                this, &MainWindow::onDeviceSelected);
        connect(m_deviceListPanel, &DeviceListPanel::deviceControlRequested, 
                this, &MainWindow::onDeviceControlRequested);
        connect(m_deviceListPanel, &DeviceListPanel::deviceLocationRequested, 
                this, &MainWindow::onDeviceLocationRequested);
        connect(m_deviceListPanel, &DeviceListPanel::deviceDetailsRequested, 
                this, &MainWindow::onDeviceDetailsRequested);
        connect(m_deviceListPanel, &DeviceListPanel::addDeviceRequested, 
                this, &MainWindow::onAddDeviceRequested);
        
        qDebug() << "SystemLogPanel and DeviceListPanel integrated with QSplitter (35%:65%)";
        SystemLogger::getInstance()->logInfo("系统日志面板初始化完成");
    } else {
        qWarning() << "Failed to get left panel layout";
        SystemLogger::getInstance()->logError("左侧面板布局获取失败");
    }
}

void MainWindow::setupRightFunctionPanel()
{
    // 创建右侧功能面板
    m_rightFunctionPanel = new RightFunctionPanel(this);
    
    // 获取右侧面板的布局
    QVBoxLayout *rightLayout = qobject_cast<QVBoxLayout*>(m_ui->rightPanel->layout());
    if (rightLayout) {
        // 彻底清除原有控件，避免UI冗余
        QLayoutItem *item;
        while ((item = rightLayout->takeAt(0)) != nullptr) {
            if (item->widget()) {
                item->widget()->deleteLater();
            }
            delete item;
        }
        
        // 将右侧功能面板添加到右侧面板
        rightLayout->addWidget(m_rightFunctionPanel);
        
        // 连接右侧功能面板信号
        // 战场探索模块信号
        connect(m_rightFunctionPanel, &RightFunctionPanel::startMapping, 
                this, &MainWindow::onStartMapping);
        connect(m_rightFunctionPanel, &RightFunctionPanel::stopMapping, 
                this, &MainWindow::onStopMapping);
        connect(m_rightFunctionPanel, &RightFunctionPanel::startNavigation, 
                this, &MainWindow::onStartNavigation);
        connect(m_rightFunctionPanel, &RightFunctionPanel::stopNavigation, 
                this, &MainWindow::onStopNavigation);
        connect(m_rightFunctionPanel, &RightFunctionPanel::startPhotoTransmission, 
                this, &MainWindow::onStartPhotoTransmission);
        connect(m_rightFunctionPanel, &RightFunctionPanel::stopPhotoTransmission, 
                this, &MainWindow::onStopPhotoTransmission);
        connect(m_rightFunctionPanel, &RightFunctionPanel::startPersonRecognition, 
                this, &MainWindow::onStartPersonRecognition);
        connect(m_rightFunctionPanel, &RightFunctionPanel::stopPersonRecognition, 
                this, &MainWindow::onStopPersonRecognition);
        
        // 情报传输模块信号
        connect(m_rightFunctionPanel, &RightFunctionPanel::openIntelligenceUI, 
                this, &MainWindow::onIntelligenceClicked);
        
        // 敌情统计模块信号
        connect(m_rightFunctionPanel, &RightFunctionPanel::refreshEnemyStats, 
                this, &MainWindow::onRefreshEnemyStats);
        connect(m_rightFunctionPanel, &RightFunctionPanel::requestAIAnalysis, 
                this, &MainWindow::onRequestAIAnalysis);
        connect(m_rightFunctionPanel, &RightFunctionPanel::exportReport, 
                this, &MainWindow::onExportReport);
        
        qDebug() << "RightFunctionPanel integrated successfully";
        SystemLogger::getInstance()->logInfo("右侧功能面板初始化完成");
        
        // 模拟初始化一些设备状态
        QTimer::singleShot(1000, [this]() {
            m_rightFunctionPanel->updateDeviceStatus("🐕 机器狗", true, 85);
            m_rightFunctionPanel->updateDeviceStatus("🚁 无人机", true, 92);
            m_rightFunctionPanel->updateEnemyStats(3, "中");
        });
        
    } else {
        qWarning() << "Failed to get right panel layout";
        SystemLogger::getInstance()->logError("右侧面板布局获取失败");
    }
}

void MainWindow::setupDeviceListPanel()
{
    // 此方法已被setupSystemLogPanel()替代，保留以兼容可能的调用
    qDebug() << "setupDeviceListPanel() is deprecated, use setupSystemLogPanel() instead";
}

void MainWindow::setupStyle()
{
    // 注意：样式设置已迁移到ModernStyleManager
    // 在initializeModernStyles()方法中统一管理

    // 设置菜单栏样式 - 与整体界面保持一致
    setupMenuBarStyle();

    // 设置状态栏样式 - 与整体界面保持一致
    setupStatusBarStyle();

    SystemLogger::getInstance()->logInfo("基础样式设置完成，现代样式将在initializeModernStyles()中应用");
}

void MainWindow::setupMenuBarStyle()
{
    // 设置菜单栏样式，与整体界面保持一致的军用风格
    QString menuBarStyle =
        "QMenuBar {"
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, "
        "                stop:0 rgba(20, 30, 42, 0.98), "
        "                stop:1 rgba(35, 50, 65, 0.98));"
        "    color: rgb(240, 248, 255);"
        "    border-bottom: 3px solid rgba(82, 194, 242, 0.8);"
        "    font-size: 20px;"
        "    font-weight: bold;"
        "    font-family: 'Microsoft YaHei', 'SimHei', sans-serif;"
        "    padding: 15px 25px;"
        "    min-height: 50px;"
        "    height: 50px;"
        "}"
        "QMenuBar::item {"
        "    background: transparent;"
        "    color: rgb(240, 248, 255);"
        "    padding: 15px 25px;"
        "    margin: 4px 8px;"
        "    border-radius: 10px;"
        "    font-size: 20px;"
        "    font-weight: bold;"
        "    min-width: 100px;"
        "    text-align: center;"
        "}"
        "QMenuBar::item:selected {"
        "    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: 1px solid rgba(82, 194, 242, 0.8);"
        "    color: white;"
        "}"
        "QMenuBar::item: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: 1px solid rgba(82, 194, 242, 1.0);"
        "}"
        "QMenu {"
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, "
        "                stop:0 rgba(25, 35, 45, 0.95), "
        "                stop:1 rgba(35, 50, 65, 0.95));"
        "    color: rgb(220, 230, 242);"
        "    border: 2px solid rgba(82, 194, 242, 0.6);"
        "    border-radius: 8px;"
        "    font-size: 14px;"
        "    font-weight: 500;"
        "    padding: 8px;"
        "}"
        "QMenu::item {"
        "    background: transparent;"
        "    padding: 8px 16px;"
        "    margin: 2px;"
        "    border-radius: 4px;"
        "    min-width: 120px;"
        "}"
        "QMenu::item:selected {"
        "    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: 1px solid rgba(82, 194, 242, 0.8);"
        "    color: white;"
        "}";

    m_ui->menubar->setStyleSheet(menuBarStyle);
}

void MainWindow::setupStatusBarStyle()
{
    // 设置状态栏样式，与整体界面保持一致的军用风格
    QString statusBarStyle =
        "QStatusBar {"
        "    background: qlineargradient(x1:0, y1:0, x2:1, y2:1, "
        "                stop:0 rgba(15, 22, 32, 0.95), "
        "                stop:1 rgba(25, 35, 45, 0.95));"
        "    color: rgb(180, 200, 220);"
        "    border-top: 2px solid rgba(82, 194, 242, 0.6);"
        "    font-size: 14px;"
        "    font-weight: 500;"
        "    font-family: 'Microsoft YaHei', 'SimHei', sans-serif;"
        "    padding: 6px 16px;"
        "    min-height: 25px;"
        "}"
        "QStatusBar::item {"
        "    border: none;"
        "    background: transparent;"
        "}";

    m_ui->statusbar->setStyleSheet(statusBarStyle);

    // 设置状态栏默认消息
    m_ui->statusbar->showMessage("战场探索系统 - 就绪状态", 0);
}

void MainWindow::connectSignals()
{
    // 连接按钮信号
    // 注意：原有的重复设备管理按钮信号已被移除
    connect(m_ui->UAVview, &QPushButton::clicked, this, &MainWindow::onUAVViewClicked);
    connect(m_ui->robotView, &QPushButton::clicked, this, &MainWindow::onRobotViewClicked);
    connect(m_ui->robotMapping, &QPushButton::clicked, this, &MainWindow::onRobotMappingClicked);
    connect(m_ui->smartNavigation, &QPushButton::clicked, this, &MainWindow::onSmartNavigationClicked);
    connect(m_ui->intelligence, &QPushButton::clicked, this, &MainWindow::onIntelligenceClicked);
    
    // DeviceListPanel信号已在setupDeviceListPanel中连接
    
    // 注意：人脸识别相关信号连接已移除
}

void MainWindow::mapDisplayControl(QPushButton *btnCtr, QWidget *, QGridLayout *layout)
{
    // 创建堆栈部件
    QStackedWidget *stackedWidget = new QStackedWidget(this);
    
    // 创建WebEngineView - 调整地图显示大小
    QWebEngineView *view = new QWebEngineView(this);
    view->setMinimumSize(800, 600);  // 确保最小尺寸
    view->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    // 创建备用的QML地图视图
    QQuickWidget *qmlMapWidget = new QQuickWidget(this);
    qmlMapWidget->setMinimumSize(800, 600);
    qmlMapWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    qmlMapWidget->setSource(QUrl::fromLocalFile(QDir::currentPath() + "/res/qml/MAP.qml"));
    
    // 创建错误显示部件
    QWidget *errorWidget = new QWidget(this);
    QVBoxLayout *errorLayout = new QVBoxLayout(errorWidget);
    QLabel *errorLabel = new QLabel("地图加载中...\n请检查网络连接", errorWidget);
    errorLabel->setAlignment(Qt::AlignCenter);
    errorLabel->setStyleSheet(
        "QLabel {"
        "  color: rgb(82, 194, 242);"
        "  font-size: 18px;"
        "  background: rgba(25, 35, 45, 0.9);"
        "  border: 2px solid rgba(82, 194, 242, 0.6);"
        "  border-radius: 10px;"
        "  padding: 30px;"
        "  font-weight: bold;"
        "}"
    );
    errorLayout->addWidget(errorLabel);
    errorWidget->setMinimumSize(800, 600);
    errorWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    // 设置要加载的HTML文件路径
    QString htmlPath = QDir::currentPath() + "/res/html/map.html";
    QUrl url = QUrl::fromLocalFile(htmlPath);
    
    // 加载HTML页面
    view->load(url);
    
    // 等待页面加载完成
    connect(view, &QWebEngineView::loadFinished, [this, view, stackedWidget, errorLabel](bool success) {
        if (success) {
            qDebug() << "地图页面加载成功";
            errorLabel->setText("地图加载成功！");
            // 调用JavaScript函数初始化地图
            view->page()->runJavaScript("initMap();", [this, stackedWidget, view](const QVariant &) {
                qDebug() << "地图初始化完成";
                // 地图加载成功后切换到地图视图
                stackedWidget->setCurrentWidget(view);
                // 初始化设备标记
                QTimer::singleShot(1000, this, &MainWindow::initializeDeviceMarkersOnMap);
            });
        } else {
            qDebug() << "地图页面加载失败，使用QML地图";
            errorLabel->setText("网络地图加载失败\n使用离线地图");
            // 如果HTML地图加载失败，切换到QML地图
            QTimer::singleShot(2000, [stackedWidget]() {
                if (stackedWidget->count() > 1) {
                    stackedWidget->setCurrentIndex(1); // 切换到QML地图
                }
            });
        }
    });
    
    // 添加部件到堆栈
    stackedWidget->addWidget(errorWidget);    // 0: 错误/加载页面
    stackedWidget->addWidget(qmlMapWidget);   // 1: QML地图
    stackedWidget->addWidget(view);           // 2: Web地图
    
    // 设置初始显示为加载页面
    stackedWidget->setCurrentWidget(errorWidget);
    
    // 连接按钮点击事件 - 在不同地图间切换
    connect(btnCtr, &QPushButton::clicked, [stackedWidget, btnCtr]() {
        int currentIndex = stackedWidget->currentIndex();
        int nextIndex = (currentIndex + 1) % stackedWidget->count();
        stackedWidget->setCurrentIndex(nextIndex);
        
        // 更新按钮文字提示
        if (btnCtr) {
            switch (nextIndex) {
                case 0: btnCtr->setText("🗺️ 加载中"); break;
                case 1: btnCtr->setText("🗺️ 离线地图"); break;
                case 2: btnCtr->setText("🗺️ 在线地图"); break;
            }
        }
    });
    
    // 添加到布局
    layout->addWidget(stackedWidget);
}

void MainWindow::addRobotControl(QPushButton *btnCtr)
{
    connect(btnCtr, &QPushButton::clicked, this, &MainWindow::onAddRobotClicked);
}

void MainWindow::robotsInfosControl(QPushButton *btnCtr)
{
    connect(btnCtr, &QPushButton::clicked, this, &MainWindow::onRobotTabClicked);
}

void MainWindow::onAddRobotClicked()
{
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("添加机器人");
    dialog->resize(450, 400);
    
    QVBoxLayout *layout = new QVBoxLayout();
    
    // 添加输入字段
    QFormLayout *formLayout = new QFormLayout();
    QLineEdit *deviceIdEdit = new QLineEdit();
    QLineEdit *nameEdit = new QLineEdit();
    QLineEdit *ipEdit = new QLineEdit();
    QSpinBox *portEdit = new QSpinBox();
    QDoubleSpinBox *longitudeEdit = new QDoubleSpinBox();
    QDoubleSpinBox *latitudeEdit = new QDoubleSpinBox();
    
    // 设置端口号范围和默认值
    portEdit->setRange(1000, 65535);
    portEdit->setValue(9090);
    
    // 从系统配置获取地图中心位置作为默认值
    double defaultLongitude = 116.4; // 默认经度
    double defaultLatitude = 39.9;   // 默认纬度
    
    // 尝试从数据库获取配置的地图中心位置
    QSqlDatabase configDb = QSqlDatabase::addDatabase("QMYSQL", "TempConnection_Config_Robot");
    configDb.setHostName("localhost");
    configDb.setPort(3306);
    configDb.setDatabaseName("Client"); 
    configDb.setUserName("root");
    configDb.setPassword("hzk200407140238");
    
    if (configDb.open()) {
        QSqlQuery configQuery(configDb);
        // 获取默认中心经度
        configQuery.prepare("SELECT config_value FROM system_config WHERE config_key = 'map.default_center_lon'");
        if (configQuery.exec() && configQuery.next()) {
            defaultLongitude = configQuery.value(0).toDouble();
        }
        // 获取默认中心纬度
        configQuery.prepare("SELECT config_value FROM system_config WHERE config_key = 'map.default_center_lat'");
        if (configQuery.exec() && configQuery.next()) {
            defaultLatitude = configQuery.value(0).toDouble();
        }
        configDb.close();
    }
    QSqlDatabase::removeDatabase("TempConnection_Config_Robot");
    
    // 设置经纬度范围和精度
    longitudeEdit->setRange(-180.0, 180.0);
    longitudeEdit->setDecimals(6);
    longitudeEdit->setValue(defaultLongitude);
    longitudeEdit->setSuffix("°E");  // 添加经度单位
    longitudeEdit->setToolTip(QString("默认地图中心经度: %1°E").arg(defaultLongitude));
    
    latitudeEdit->setRange(-90.0, 90.0);
    latitudeEdit->setDecimals(6);
    latitudeEdit->setValue(defaultLatitude);
    latitudeEdit->setSuffix("°N");   // 添加纬度单位
    latitudeEdit->setToolTip(QString("默认地图中心纬度: %1°N").arg(defaultLatitude));
    
    // 自动生成设备ID
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "TempConnection_DOG_ID_Add");
    db.setHostName("localhost");
    db.setPort(3306);
    db.setDatabaseName("Client"); 
    db.setUserName("root");
    db.setPassword("hzk200407140238");
    
    QString suggestedId = "DOG001";
    if (db.open()) {
        QSqlQuery query(db);
        query.exec("SELECT COUNT(*) FROM devices WHERE device_type = 'dog'");
        if (query.next()) {
            int count = query.value(0).toInt();
            suggestedId = QString("DOG%1").arg(count + 1, 3, 10, QChar('0'));
        }
        db.close();
    }
    QSqlDatabase::removeDatabase("TempConnection_DOG_ID_Add");
    
    deviceIdEdit->setText(suggestedId);
    
    // 设置输入框占位符和样式
    deviceIdEdit->setStyleSheet("QLineEdit { color: #333; } QLineEdit:focus { border: 2px solid #52C2F2; }");
    nameEdit->setPlaceholderText("请输入机器人名称");
    nameEdit->setStyleSheet("QLineEdit { color: #333; } QLineEdit:focus { border: 2px solid #52C2F2; }");
    ipEdit->setPlaceholderText("例如: 192.168.1.200");
    ipEdit->setStyleSheet("QLineEdit { color: #333; } QLineEdit:focus { border: 2px solid #52C2F2; }");
    
    // 为经纬度输入框设置样式
    longitudeEdit->setStyleSheet("QDoubleSpinBox { color: #666; } QDoubleSpinBox:focus { border: 2px solid #52C2F2; }");
    latitudeEdit->setStyleSheet("QDoubleSpinBox { color: #666; } QDoubleSpinBox:focus { border: 2px solid #52C2F2; }");
    
    formLayout->addRow("设备ID:", deviceIdEdit);
    formLayout->addRow("机器人名称:", nameEdit);
    formLayout->addRow("IP地址:", ipEdit);
    formLayout->addRow("端口号:", portEdit);
    formLayout->addRow("经度 (地图中心):", longitudeEdit);
    formLayout->addRow("纬度 (地图中心):", latitudeEdit);
    
    layout->addLayout(formLayout);
    
    // 添加按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *confirmBtn = new QPushButton("确认");
    QPushButton *cancelBtn = new QPushButton("取消");
    
    buttonLayout->addWidget(confirmBtn);
    buttonLayout->addWidget(cancelBtn);
    layout->addLayout(buttonLayout);
    
    connect(confirmBtn, &QPushButton::clicked, [this, dialog, deviceIdEdit, nameEdit, ipEdit, portEdit, longitudeEdit, latitudeEdit]() {
        QString deviceId = deviceIdEdit->text().trimmed();
        QString name = nameEdit->text().trimmed();
        QString ip = ipEdit->text().trimmed();
        int port = portEdit->value();
        double longitude = longitudeEdit->value();
        double latitude = latitudeEdit->value();
        
        if (!deviceId.isEmpty() && !name.isEmpty() && !ip.isEmpty()) {
            // 保存到数据库，设备状态默认为0（离线）
            if (addDeviceToDatabase(deviceId, name, "dog", ip, port, 0, longitude, latitude)) {
                m_robotList.append(qMakePair(name, ip));
                QMessageBox::information(this, "成功", "机器人添加成功！");
                
                // 记录成功日志
                SystemLogger::getInstance()->logSuccess(QString("机器人添加成功: %1 (%2)").arg(name).arg(deviceId));
                
                // 刷新设备列表
                if (m_deviceListPanel) {
                    m_deviceListPanel->refreshDeviceList();
                }
                
                dialog->accept();
            } else {
                QMessageBox::warning(this, "错误", "保存到数据库失败！");
                SystemLogger::getInstance()->logError(QString("机器人添加失败: %1 - 数据库保存失败").arg(name));
            }
        } else {
            QMessageBox::warning(this, "错误", "请填写完整信息！");
        }
    });
    
    connect(cancelBtn, &QPushButton::clicked, dialog, &QDialog::reject);
    
    dialog->setLayout(layout);
    dialog->exec();
    delete dialog;
}

void MainWindow::onRobotTabClicked()
{
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("机器人列表");
    dialog->resize(500, 400);
    
    QVBoxLayout *layout = new QVBoxLayout();
    QTableWidget *table = new QTableWidget(m_robotList.size(), 2);
    
    QStringList headers;
    headers << "机器人名称" << "IP地址";
    table->setHorizontalHeaderLabels(headers);
    
    // 设置表格属性
    table->horizontalHeader()->setStretchLastSection(true);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    for (int i = 0; i < m_robotList.size(); ++i) {
        table->setItem(i, 0, new QTableWidgetItem(m_robotList[i].first));
        table->setItem(i, 1, new QTableWidgetItem(m_robotList[i].second));
    }
    
    layout->addWidget(table);
    
    QPushButton *closeBtn = new QPushButton("关闭");
    connect(closeBtn, &QPushButton::clicked, dialog, &QDialog::accept);
    layout->addWidget(closeBtn);
    
    dialog->setLayout(layout);
    dialog->exec();
    delete dialog;
}

void MainWindow::onSpecifiedRobotTabClicked()
{
    QMessageBox::information(this, "提示", "切换到指定机器人页面功能正在开发中");
}

void MainWindow::onAddUAVClicked()
{
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("添加无人机");
    dialog->resize(450, 400);
    
    QVBoxLayout *layout = new QVBoxLayout();
    
    // 添加输入字段
    QFormLayout *formLayout = new QFormLayout();
    QLineEdit *deviceIdEdit = new QLineEdit();
    QLineEdit *nameEdit = new QLineEdit();
    QLineEdit *ipEdit = new QLineEdit();
    QSpinBox *portEdit = new QSpinBox();
    QDoubleSpinBox *longitudeEdit = new QDoubleSpinBox();
    QDoubleSpinBox *latitudeEdit = new QDoubleSpinBox();
    
    // 设置端口号范围和默认值
    portEdit->setRange(1000, 65535);
    portEdit->setValue(8080);
    
    // 从系统配置获取地图中心位置作为默认值
    double defaultLongitude = 116.4; // 默认经度
    double defaultLatitude = 39.9;   // 默认纬度
    
    // 尝试从数据库获取配置的地图中心位置
    QSqlDatabase configDb = QSqlDatabase::addDatabase("QMYSQL", "TempConnection_Config");
    configDb.setHostName("localhost");
    configDb.setPort(3306);
    configDb.setDatabaseName("Client"); 
    configDb.setUserName("root");
    configDb.setPassword("hzk200407140238");
    
    if (configDb.open()) {
        QSqlQuery configQuery(configDb);
        // 获取默认中心经度
        configQuery.prepare("SELECT config_value FROM system_config WHERE config_key = 'map.default_center_lon'");
        if (configQuery.exec() && configQuery.next()) {
            defaultLongitude = configQuery.value(0).toDouble();
        }
        // 获取默认中心纬度
        configQuery.prepare("SELECT config_value FROM system_config WHERE config_key = 'map.default_center_lat'");
        if (configQuery.exec() && configQuery.next()) {
            defaultLatitude = configQuery.value(0).toDouble();
        }
        configDb.close();
    }
    QSqlDatabase::removeDatabase("TempConnection_Config");
    
    // 设置经纬度范围和精度
    longitudeEdit->setRange(-180.0, 180.0);
    longitudeEdit->setDecimals(6);
    longitudeEdit->setValue(defaultLongitude);
    longitudeEdit->setSuffix("°E");  // 添加经度单位
    longitudeEdit->setToolTip(QString("默认地图中心经度: %1°E").arg(defaultLongitude));
    
    latitudeEdit->setRange(-90.0, 90.0);
    latitudeEdit->setDecimals(6);
    latitudeEdit->setValue(defaultLatitude);
    latitudeEdit->setSuffix("°N");   // 添加纬度单位
    latitudeEdit->setToolTip(QString("默认地图中心纬度: %1°N").arg(defaultLatitude));
    
    // 自动生成设备ID
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "TempConnection_UAV_ID");
    db.setHostName("localhost");
    db.setPort(3306);
    db.setDatabaseName("Client"); 
    db.setUserName("root");
    db.setPassword("hzk200407140238");
    
    QString suggestedId = "UAV001";
    if (db.open()) {
        QSqlQuery query(db);
        query.exec("SELECT COUNT(*) FROM devices WHERE device_type = 'uav'");
        if (query.next()) {
            int count = query.value(0).toInt();
            suggestedId = QString("UAV%1").arg(count + 1, 3, 10, QChar('0'));
        }
        db.close();
    }
    QSqlDatabase::removeDatabase("TempConnection_UAV_ID");
    
    deviceIdEdit->setText(suggestedId);
    
    // 设置输入框占位符和样式
    deviceIdEdit->setStyleSheet("QLineEdit { color: #333; } QLineEdit:focus { border: 2px solid #52C2F2; }");
    nameEdit->setPlaceholderText("请输入无人机名称");
    nameEdit->setStyleSheet("QLineEdit { color: #333; } QLineEdit:focus { border: 2px solid #52C2F2; }");
    ipEdit->setPlaceholderText("例如: 192.168.1.100");
    ipEdit->setStyleSheet("QLineEdit { color: #333; } QLineEdit:focus { border: 2px solid #52C2F2; }");
    
    // 为经纬度输入框设置样式
    longitudeEdit->setStyleSheet("QDoubleSpinBox { color: #666; } QDoubleSpinBox:focus { border: 2px solid #52C2F2; }");
    latitudeEdit->setStyleSheet("QDoubleSpinBox { color: #666; } QDoubleSpinBox:focus { border: 2px solid #52C2F2; }");
    
    formLayout->addRow("设备ID:", deviceIdEdit);
    formLayout->addRow("无人机名称:", nameEdit);
    formLayout->addRow("IP地址:", ipEdit);
    formLayout->addRow("端口号:", portEdit);
    formLayout->addRow("经度 (地图中心):", longitudeEdit);
    formLayout->addRow("纬度 (地图中心):", latitudeEdit);
    
    layout->addLayout(formLayout);
    
    // 添加按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *confirmBtn = new QPushButton("确认");
    QPushButton *cancelBtn = new QPushButton("取消");
    
    buttonLayout->addWidget(confirmBtn);
    buttonLayout->addWidget(cancelBtn);
    layout->addLayout(buttonLayout);
    
    connect(confirmBtn, &QPushButton::clicked, [this, dialog, deviceIdEdit, nameEdit, ipEdit, portEdit, longitudeEdit, latitudeEdit]() {
        QString deviceId = deviceIdEdit->text().trimmed();
        QString name = nameEdit->text().trimmed();
        QString ip = ipEdit->text().trimmed();
        int port = portEdit->value();
        double longitude = longitudeEdit->value();
        double latitude = latitudeEdit->value();
        
        if (!deviceId.isEmpty() && !name.isEmpty() && !ip.isEmpty()) {
            // 保存到数据库，设备状态默认为0（离线）
            if (addDeviceToDatabase(deviceId, name, "uav", ip, port, 0, longitude, latitude)) {
                m_uavList.append(qMakePair(name, ip));
                QMessageBox::information(this, "成功", "无人机添加成功！");
                
                // 记录成功日志
                SystemLogger::getInstance()->logSuccess(QString("无人机添加成功: %1 (%2)").arg(name).arg(deviceId));
                
                // 刷新设备列表
                if (m_deviceListPanel) {
                    m_deviceListPanel->refreshDeviceList();
                }
                
                dialog->accept();
            } else {
                QMessageBox::warning(this, "错误", "保存到数据库失败！");
                SystemLogger::getInstance()->logError(QString("无人机添加失败: %1 - 数据库保存失败").arg(name));
            }
        } else {
            QMessageBox::warning(this, "错误", "请填写完整信息！");
        }
    });
    
    connect(cancelBtn, &QPushButton::clicked, dialog, &QDialog::reject);
    
    dialog->setLayout(layout);
    dialog->exec();
    delete dialog;
}

void MainWindow::onUAVTabClicked()
{
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("无人机列表");
    dialog->resize(500, 400);
    
    QVBoxLayout *layout = new QVBoxLayout();
    QTableWidget *table = new QTableWidget(m_uavList.size(), 2);
    
    QStringList headers;
    headers << "无人机名称" << "IP地址";
    table->setHorizontalHeaderLabels(headers);
    
    // 设置表格属性
    table->horizontalHeader()->setStretchLastSection(true);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    for (int i = 0; i < m_uavList.size(); ++i) {
        table->setItem(i, 0, new QTableWidgetItem(m_uavList[i].first));
        table->setItem(i, 1, new QTableWidgetItem(m_uavList[i].second));
    }
    
    layout->addWidget(table);
    
    QPushButton *closeBtn = new QPushButton("关闭");
    connect(closeBtn, &QPushButton::clicked, dialog, &QDialog::accept);
    layout->addWidget(closeBtn);
    
    dialog->setLayout(layout);
    dialog->exec();
    delete dialog;
}

void MainWindow::onRobotLocationClicked()
{
    QMessageBox::information(this, "机器人定位", "机器人定位功能正在开发中，暂时无法使用");
}

void MainWindow::onUAVViewClicked()
{
    QMessageBox::information(this, "无人机视图", "无人机视图功能正在开发中，暂时无法使用");
}

void MainWindow::onRobotViewClicked()
{
    QMessageBox::information(this, "机器人视图", "机器人视图功能正在开发中，暂时无法使用");
}

void MainWindow::onRobotMappingClicked()
{
    QMessageBox::information(this, "机器人建图", "机器人建图功能正在开发中，暂时无法使用");
}

void MainWindow::onSmartNavigationClicked()
{
    QMessageBox::information(this, "智能导航", "智能导航功能正在开发中，暂时无法使用");
}

void MainWindow::onIntelligenceClicked()
{
    if (!m_intelligenceUI) {
        m_intelligenceUI = new IntelligenceUI(this);
    }
    m_intelligenceUI->show();
    m_intelligenceUI->activateWindow();
    m_intelligenceUI->raise();
}

void MainWindow::onDeviceSelected(const QString &deviceId)
{
    qDebug() << "Device selected:" << deviceId;
    // TODO: 实现设备选中后的处理逻辑
    // 例如：更新地图显示、显示设备详细信息等
}

void MainWindow::onDeviceControlRequested(const QString &deviceId)
{
    qDebug() << "Device control requested for:" << deviceId;
    // TODO: 实现设备控制逻辑
    // 例如：打开设备控制界面、发送控制命令等
    QMessageBox::information(this, "设备控制", 
                             QString("设备控制功能正在开发中\n设备ID: %1").arg(deviceId));
}

void MainWindow::onDeviceLocationRequested(const QString &deviceId)
{
    qDebug() << "Device location requested for:" << deviceId;
    SystemLogger::getInstance()->logInfo(QString("请求设备定位: %1").arg(deviceId));
    
    // 从设备列表面板获取设备信息
    if (m_deviceListPanel) {
        // TODO: 从数据库获取设备的实际位置信息
        // 这里使用测试数据作为示例
        double latitude = 0.0, longitude = 0.0;
        QString deviceName = "Unknown Device";
        QString deviceType = "uav";
        QString status = "Online";
        
        // 根据设备ID获取位置信息（测试数据）
        if (deviceId == "UAV001") {
            latitude = 39.90;
            longitude = 116.40;
            deviceName = "侦察机-01";
            deviceType = "uav";
            status = "Online";
        } else if (deviceId == "UAV002") {
            latitude = 39.92;
            longitude = 116.42;
            deviceName = "侦察机-02";
            deviceType = "uav";
            status = "Warning";
        } else if (deviceId == "DOG001") {
            latitude = 39.88;
            longitude = 116.38;
            deviceName = "巡逻犬-Alpha";
            deviceType = "dog";
            status = "Online";
        } else if (deviceId == "DOG002") {
            latitude = 39.86;
            longitude = 116.44;
            deviceName = "巡逻犬-Beta";
            deviceType = "dog";
            status = "Offline";
        }
        
        if (latitude != 0.0 && longitude != 0.0) {
            // 在地图上添加设备标记并聚焦
            QString jsCode = QString(
                "addDeviceMarker('%1', '%2', '%3', %4, %5, '%6'); "
                "focusOnDevice('%1', %4, %5);"
            ).arg(deviceId)
             .arg(deviceName)
             .arg(deviceType)
             .arg(latitude)
             .arg(longitude)
             .arg(status);
            
            // 查找地图WebEngineView并执行JavaScript
            QList<QWebEngineView*> webViews = this->findChildren<QWebEngineView*>();
            for (auto webView : webViews) {
                if (webView->isVisible()) {
                    webView->page()->runJavaScript(jsCode, [deviceId](const QVariant &result) {
                        qDebug() << "Device location updated on map for:" << deviceId;
                    });
                    break;
                }
            }
            
            qDebug() << QString("设备 %1 定位到位置: (%2, %3)").arg(deviceName).arg(latitude).arg(longitude);
            SystemLogger::getInstance()->logSuccess(QString("设备定位完成: %1 -> (%2, %3)").arg(deviceName).arg(latitude).arg(longitude));
        } else {
            QMessageBox::warning(this, "设备定位", 
                                QString("无法获取设备位置信息\n设备ID: %1").arg(deviceId));
        }
    }
}

void MainWindow::onDeviceDetailsRequested(const QString &deviceId)
{
    qDebug() << "Device details requested for:" << deviceId;
    
    // 连接数据库获取设备详细信息
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "MainWindow_DeviceDetails");
    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 details:" << db.lastError().text();
        SystemLogger::getInstance()->logError("数据库连接失败 - 无法查询设备详情");
        QMessageBox::warning(this, "错误", "无法连接到数据库");
        return;
    }
    
    // 查询设备信息
    QSqlQuery query(db);
    QString sql = "SELECT name, device_type, ip, port, longitude, latitude, state, "
                  "signal_strength, battery_level, firmware_version, last_heartbeat, "
                  "created_at, updated_at "
                  "FROM devices WHERE id = ?";
    
    query.prepare(sql);
    query.addBindValue(deviceId);
    
    if (!query.exec() || !query.next()) {
        qWarning() << "Failed to query device details:" << query.lastError().text();
        QMessageBox::warning(this, "错误", 
                            QString("无法找到设备信息\n设备ID: %1").arg(deviceId));
        db.close();
        return;
    }
    
    // 获取设备信息
    QString name = query.value("name").toString();
    QString type = query.value("device_type").toString();
    QString ip = query.value("ip").toString();
    int port = query.value("port").toInt();
    double longitude = query.value("longitude").toDouble();
    double latitude = query.value("latitude").toDouble();
    int state = query.value("state").toInt();
    int signalStrength = query.value("signal_strength").toInt();
    int batteryLevel = query.value("battery_level").toInt();
    QString firmwareVersion = query.value("firmware_version").toString();
    QString lastHeartbeat = query.value("last_heartbeat").toString();
    QString createdAt = query.value("created_at").toString();
    QString updatedAt = query.value("updated_at").toString();
    
    db.close();
    
    // 创建并显示设备详情对话框
    DeviceDialog *dialog = new DeviceDialog(this);
    
    // 设置设备信息
    dialog->setDeviceInfo(deviceId, name, type, ip, port, longitude, latitude,
                         state, signalStrength, batteryLevel, firmwareVersion,
                         lastHeartbeat, createdAt, updatedAt);
    
    // 连接设备操作信号
    connect(dialog, &DeviceDialog::deviceConnectRequested, 
            this, &MainWindow::onDeviceControlRequested);
    connect(dialog, &DeviceDialog::deviceDisconnectRequested, 
            this, &MainWindow::onDeviceControlRequested);
    connect(dialog, &DeviceDialog::deviceLocationRequested, 
            this, &MainWindow::onDeviceLocationRequested);
    
    // 显示对话框
    dialog->exec();
    
    // 清理
    dialog->deleteLater();
    
    qDebug() << "Device details dialog shown for:" << deviceId;
}

void MainWindow::onAddDeviceRequested(const QString &deviceType)
{
    qDebug() << "Add device requested, type:" << deviceType;
    
    if (deviceType == "uav") {
        // 调用现有的添加无人机功能
        onAddUAVClicked();
    } else if (deviceType == "dog") {
        // 调用现有的添加机器人功能
        onAddRobotClicked();
    } else {
        QMessageBox::warning(this, "错误", "未知的设备类型: " + deviceType);
    }
}

void MainWindow::setupMapDisplay()
{
    qDebug() << "Setting up map display...";
    SystemLogger::getInstance()->logInfo("开始设置地图显示");
    
    // 创建WebEngineView来显示地图
    QWebEngineView* webView = new QWebEngineView(m_ui->MapDisplayer);
    
    // 设置地图HTML文件路径
    QString mapPath = QApplication::applicationDirPath() + "/res/html/map.html";
    if (!QFile::exists(mapPath)) {
        mapPath = ":/html/res/html/map.html";  // 尝试从资源文件加载
    }
    
    // 加载地图
    webView->load(QUrl::fromLocalFile(mapPath));
    
    // 调整WebView大小以填充MapDisplayer
    QVBoxLayout* layout = new QVBoxLayout(m_ui->MapDisplayer);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(webView);
    m_ui->MapDisplayer->setLayout(layout);
    
    // 地图加载完成后初始化设备标记
    connect(webView, &QWebEngineView::loadFinished, this, [this](bool success) {
        if (success) {
            qDebug() << "Map loaded successfully, initializing device markers...";
            SystemLogger::getInstance()->logSuccess("地图加载完成");
            QTimer::singleShot(1000, this, &MainWindow::initializeDeviceMarkersOnMap);
        } else {
            qDebug() << "Map loading failed!";
            SystemLogger::getInstance()->logError("地图加载失败");
        }
    });
}

void MainWindow::initializeDeviceMarkersOnMap()
{
    qDebug() << "Initializing device markers on map...";
    
    // 定义测试设备数据（与DeviceListPanel中的测试数据对应）
    struct DeviceData {
        QString id;
        QString name;
        QString type;
        double latitude;
        double longitude;
        QString status;
    };
    
    QList<DeviceData> testDevices = {
        {"UAV001", "侦察机-01", "uav", 39.90, 116.40, "Online"},
        {"UAV002", "侦察机-02", "uav", 39.92, 116.42, "Warning"},
        {"DOG001", "巡逻犬-Alpha", "dog", 39.88, 116.38, "Online"},
        {"DOG002", "巡逻犬-Beta", "dog", 39.86, 116.44, "Offline"}
    };
    
    // 查找地图WebEngineView
    QList<QWebEngineView*> webViews = this->findChildren<QWebEngineView*>();
    for (auto webView : webViews) {
        if (webView->isVisible()) {
            // 为每个设备添加标记
            for (const auto &device : testDevices) {
                QString jsCode = QString(
                    "addDeviceMarker('%1', '%2', '%3', %4, %5, '%6');"
                ).arg(device.id)
                 .arg(device.name)
                 .arg(device.type)
                 .arg(device.latitude)
                 .arg(device.longitude)
                 .arg(device.status);
                
                webView->page()->runJavaScript(jsCode, [device](const QVariant &result) {
                    qDebug() << "Device marker added for:" << device.name;
                });
            }
            
            qDebug() << "All device markers initialized on map";
            break;
        }
    }
}

bool MainWindow::addDeviceToDatabase(const QString &deviceId, const QString &name, const QString &type, const QString &ip, int port, int state, double longitude, double latitude)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "MainWindow_AddDevice_Connection");
    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 adding device:" << db.lastError().text();
        SystemLogger::getInstance()->logError("数据库连接失败 - 无法添加设备");
        return false;
    }
    
    QSqlQuery query(db);
    
    // 检查设备ID是否已存在
    query.prepare("SELECT COUNT(*) FROM devices WHERE id = ?");
    query.addBindValue(deviceId);
    if (!query.exec() || !query.next()) {
        qWarning() << "Failed to check device ID uniqueness:" << query.lastError().text();
        db.close();
        return false;
    }
    
    if (query.value(0).toInt() > 0) {
        qWarning() << "Device ID already exists:" << deviceId;
        db.close();
        return false;
    }
    
    // 插入新设备
    QString sql = "INSERT INTO devices (id, name, device_type, state, ip, port, longitude, latitude, signal_strength, battery_level) "
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 100)";
    
    query.prepare(sql);
    query.addBindValue(deviceId);
    query.addBindValue(name);
    query.addBindValue(type);
    query.addBindValue(state);
    query.addBindValue(ip);
    query.addBindValue(port);
    query.addBindValue(longitude);
    query.addBindValue(latitude);
    
    bool success = query.exec();
    if (!success) {
        qWarning() << "Failed to insert device into database:" << query.lastError().text();
    } else {
        qDebug() << "Successfully added device to database:" << deviceId << name << "at" << latitude << "," << longitude;
    }
    
    db.close();
    return success;
}

// 右侧功能面板槽函数实现
void MainWindow::onStartMapping()
{
    qDebug() << "Starting autonomous mapping...";
    SystemLogger::getInstance()->logInfo("开始自主建图");
    
    // TODO: 实现自主建图功能
    // 这里应该连接到实际的机器狗建图系统
}

void MainWindow::onStopMapping()
{
    qDebug() << "Stopping autonomous mapping...";
    SystemLogger::getInstance()->logInfo("停止自主建图");
    
    // TODO: 实现停止建图功能
}

void MainWindow::onStartNavigation()
{
    qDebug() << "Starting navigation and obstacle avoidance...";
    SystemLogger::getInstance()->logInfo("开始导航避障");
    
    // TODO: 实现导航避障功能
}

void MainWindow::onStopNavigation()
{
    qDebug() << "Stopping navigation...";
    SystemLogger::getInstance()->logInfo("停止导航避障");
    
    // TODO: 实现停止导航功能
}

void MainWindow::onStartPhotoTransmission()
{
    qDebug() << "Starting photo transmission from UAV...";
    SystemLogger::getInstance()->logInfo("开始无人机照片传输");
    
    // TODO: 实现无人机照片传输功能
    // 这里应该连接到实际的无人机摄像头系统
}

void MainWindow::onStopPhotoTransmission()
{
    qDebug() << "Stopping photo transmission...";
    SystemLogger::getInstance()->logInfo("停止照片传输");
    
    // TODO: 实现停止照片传输功能
}

void MainWindow::onStartPersonRecognition()
{
    qDebug() << "Starting person recognition...";
    SystemLogger::getInstance()->logInfo("开始人物识别");
    
    // TODO: 实现人物识别功能
    // 这里应该连接到AI人物识别系统
}

void MainWindow::onStopPersonRecognition()
{
    qDebug() << "Stopping person recognition...";
    SystemLogger::getInstance()->logInfo("停止人物识别");
    
    // TODO: 实现停止人物识别功能
}



void MainWindow::onRefreshEnemyStats()
{
    qDebug() << "Refreshing enemy statistics...";
    SystemLogger::getInstance()->logInfo("刷新敌情统计");
    
    // TODO: 实现从数据库或AI系统获取最新敌情数据
    // 模拟数据更新
    if (m_rightFunctionPanel) {
        // 模拟随机更新敌情数据
        int enemyCount = qrand() % 10 + 1;
        QStringList threatLevels = {"低", "中", "高"};
        QString threatLevel = threatLevels[qrand() % threatLevels.size()];
        
        m_rightFunctionPanel->updateEnemyStats(enemyCount, threatLevel);
        
        SystemLogger::getInstance()->logInfo(
            QString("敌情统计更新：发现 %1 个目标，威胁等级：%2")
            .arg(enemyCount).arg(threatLevel)
        );
    }
}

void MainWindow::onRequestAIAnalysis()
{
    qDebug() << "Requesting AI analysis...";
    SystemLogger::getInstance()->logInfo("请求AI敌情分析");
    
    // TODO: 实现AI分析功能
    // 这里应该连接到大语言模型进行敌情分析
    
    // 模拟AI分析结果
    QTimer::singleShot(3000, [this]() {
        QString analysisResult = "AI分析结果：当前区域敌情相对稳定，建议继续监控北侧区域，注意东南方向可疑活动。";
        SystemLogger::getInstance()->logInfo("AI分析完成：" + analysisResult);
        
        // 可以通过消息框或状态栏显示分析结果
        QMessageBox::information(this, "AI敌情分析", analysisResult);
    });
}

void MainWindow::onExportReport()
{
    qDebug() << "Exporting battlefield report...";
    SystemLogger::getInstance()->logInfo("导出战场报告");
    
    // TODO: 实现报告导出功能
    // 这里应该生成包含敌情统计、设备状态、任务记录等的完整报告
    
    // 模拟报告导出
    QString reportPath = QString("battlefield_report_%1.pdf")
                        .arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));
    
    SystemLogger::getInstance()->logInfo("报告导出完成：" + reportPath);
    QMessageBox::information(this, "报告导出",
                           QString("战场报告已成功导出到：\n%1").arg(reportPath));
}

void MainWindow::initializeModernStyles()
{
    // 获取现代样式管理器实例
    ModernStyleManager* styleManager = ModernStyleManager::getInstance();

    // 应用现代军事主题
    styleManager->applyTheme(ModernStyleManager::ThemeType::ModernMilitary);

    // 应用主要按钮样式
    if (m_ui->UAVview) {
        styleManager->applyButtonStyle(m_ui->UAVview, ModernStyleManager::ButtonStyle::Primary);
    }

    if (m_ui->robotView) {
        styleManager->applyButtonStyle(m_ui->robotView, ModernStyleManager::ButtonStyle::Primary);
    }

    if (m_ui->robotMapping) {
        styleManager->applyButtonStyle(m_ui->robotMapping, ModernStyleManager::ButtonStyle::Info);
    }

    if (m_ui->smartNavigation) {
        styleManager->applyButtonStyle(m_ui->smartNavigation, ModernStyleManager::ButtonStyle::Success);
    }

    if (m_ui->intelligence) {
        styleManager->applyButtonStyle(m_ui->intelligence, ModernStyleManager::ButtonStyle::Warning);
    }

    // 应用设备面板样式
    if (m_deviceListPanel) {
        styleManager->applyDevicePanelStyle(m_deviceListPanel);
    }

    // 连接主题切换信号
    connect(styleManager, &ModernStyleManager::themeApplied,
            this, [this](ModernStyleManager::ThemeType theme, bool success) {
        if (success) {
            SystemLogger::getInstance()->logInfo("现代主题应用成功");
        } else {
            SystemLogger::getInstance()->logWarning("现代主题应用失败");
        }
    });

    SystemLogger::getInstance()->logInfo("现代样式管理器初始化完成");
}