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

#include "ui/main/MainWindow.h"
#include "build/ui_MainWindow.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>
#include <QLineEdit>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QHeaderView>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_ui(new Ui::MainWindow)
    // , m_intelligenceUI(nullptr)  // 暂时注释掉
{
    m_ui->setupUi(this);
    
    setupUI();
    setupStyle();
    connectSignals();
    
    // 初始化默认数据
    m_robotList.append(qMakePair(QString("Alice"), QString("192.168.0.1")));
    m_robotList.append(qMakePair(QString("Bob"), QString("192.168.0.2")));
}

MainWindow::~MainWindow()
{
    delete m_ui;
}

void MainWindow::setupUI()
{
    // 设置窗口最小尺寸
    this->setMinimumSize(1200, 800);
    
    // 窗口居中显示
    this->resize(1400, 900);
    QRect screenGeometry = QApplication::desktop()->screenGeometry();
    int x = (screenGeometry.width() - this->width()) / 2;
    int y = (screenGeometry.height() - this->height()) / 2;
    this->move(x, y);
    
    // 初始化随机数生成器
    qsrand(QTime::currentTime().msec());
    
    // 控制地图显示
    mapDisplayControl(m_ui->mapbutton, m_ui->MapDisplayer, m_ui->gridLayout_3);
    // 控制添加机器人
    addRobotControl(m_ui->addrobot);
    // 控制机器人列表
    robotsInfosControl(m_ui->robottab);
}

void MainWindow::setupStyle()
{
    // 设置按钮样式 - 现代化军用风格
    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);"
                          "  padding: 10px 18px;"
                          "  border-radius: 8px;"
                          "  font-size: 14px;"
                          "  font-weight: bold;"
                          "  text-align: left;"
                          "}"
                          "QPushButton:hover {"
                          "  background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                          "              stop:0 rgba(82, 194, 242, 0.7), "
                          "              stop:1 rgba(45, 120, 180, 0.7));"
                          "  border: 2px solid 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.9), "
                          "              stop:1 rgba(45, 120, 180, 0.9));"
                          "  border: 2px solid rgba(82, 194, 242, 1.0);"
                          "}";
    
    // 应用样式到所有按钮
    m_ui->robottab->setStyleSheet(buttonStyle);
    m_ui->robotlocation->setStyleSheet(buttonStyle);
    m_ui->addrobot->setStyleSheet(buttonStyle);
    m_ui->mapbutton->setStyleSheet(buttonStyle);
    m_ui->addUAV->setStyleSheet(buttonStyle);
    m_ui->UAVtab->setStyleSheet(buttonStyle);
    m_ui->UAVview->setStyleSheet(buttonStyle);
    m_ui->robotView->setStyleSheet(buttonStyle);
    m_ui->robotMapping->setStyleSheet(buttonStyle);
    m_ui->smartNavigation->setStyleSheet(buttonStyle);
    m_ui->intelligence->setStyleSheet(buttonStyle);
    
    // 注意：人脸识别相关按钮已移除样式设置
}

void MainWindow::connectSignals()
{
    // 连接按钮信号
    connect(m_ui->addUAV, &QPushButton::clicked, this, &MainWindow::onAddUAVClicked);
    connect(m_ui->UAVtab, &QPushButton::clicked, this, &MainWindow::onUAVTabClicked);
    connect(m_ui->robotlocation, &QPushButton::clicked, this, &MainWindow::onRobotLocationClicked);
    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);
    
    // 注意：人脸识别相关信号连接已移除
}

void MainWindow::mapDisplayControl(QPushButton *btnCtr, QWidget *target, QGridLayout *layout)
{
    // 创建堆栈部件
    QStackedWidget *stackedWidget = new QStackedWidget(this);
    
    // 创建背景板部件
    QWidget *backgroundWidget = new QWidget(this);
    QPixmap backgroundPixmap(":/image/res/image/MapBackGround.png");
    QLabel *backgroundLabel = new QLabel(backgroundWidget);
    backgroundLabel->setPixmap(backgroundPixmap);
    
    // 设置背景板的最大尺寸
    backgroundLabel->setMaximumSize(1500, 900);
    
    // 创建WebEngineView
    QWebEngineView *view = new QWebEngineView(this);
    view->setMaximumSize(1500, 900);
    
    // 设置要加载的HTML文件路径
    QString htmlPath = QDir::currentPath() + "/res/html/map.html";
    QUrl url = QUrl::fromLocalFile(htmlPath);
    
    // 加载HTML页面
    view->load(url);
    
    // 等待页面加载完成
    connect(view, &QWebEngineView::loadFinished, [view](bool success) {
        if (success) {
            qDebug() << "地图页面加载成功";
            // 调用JavaScript函数初始化地图
            view->page()->runJavaScript("initMap();", [](const QVariant &result) {
                qDebug() << "地图初始化完成";
            });
        } else {
            qDebug() << "地图页面加载失败";
        }
    });
    
    // 添加部件到堆栈
    stackedWidget->addWidget(backgroundWidget);
    stackedWidget->addWidget(view);
    
    // 设置初始显示为背景板
    stackedWidget->setCurrentWidget(backgroundWidget);
    
    // 连接按钮点击事件
    connect(btnCtr, &QPushButton::clicked, [stackedWidget, view]() {
        if (stackedWidget->currentIndex() == 0) {
            stackedWidget->setCurrentWidget(view);
        } else {
            stackedWidget->setCurrentIndex(0);
        }
    });
    
    // 添加到布局
    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(400, 300);
    
    QVBoxLayout *layout = new QVBoxLayout();
    
    // 添加输入字段
    QFormLayout *formLayout = new QFormLayout();
    QLineEdit *nameEdit = new QLineEdit();
    QLineEdit *ipEdit = new QLineEdit();
    
    formLayout->addRow("机器人名称:", nameEdit);
    formLayout->addRow("IP地址:", ipEdit);
    
    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, nameEdit, ipEdit]() {
        QString name = nameEdit->text().trimmed();
        QString ip = ipEdit->text().trimmed();
        
        if (!name.isEmpty() && !ip.isEmpty()) {
            m_robotList.append(qMakePair(name, ip));
            QMessageBox::information(this, "成功", "机器人添加成功！");
            dialog->accept();
        } 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(400, 300);
    
    QVBoxLayout *layout = new QVBoxLayout();
    
    // 添加输入字段
    QFormLayout *formLayout = new QFormLayout();
    QLineEdit *nameEdit = new QLineEdit();
    QLineEdit *ipEdit = new QLineEdit();
    
    formLayout->addRow("无人机名称:", nameEdit);
    formLayout->addRow("IP地址:", ipEdit);
    
    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, nameEdit, ipEdit]() {
        QString name = nameEdit->text().trimmed();
        QString ip = ipEdit->text().trimmed();
        
        if (!name.isEmpty() && !ip.isEmpty()) {
            m_uavList.append(qMakePair(name, ip));
            QMessageBox::information(this, "成功", "无人机添加成功！");
            dialog->accept();
        } 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()
{
    // 暂时注释掉 IntelligenceUI 相关功能，待实现
    /*
    if (!m_intelligenceUI) {
        m_intelligenceUI = new IntelligenceUI(this);
    }
    m_intelligenceUI->show();
    m_intelligenceUI->activateWindow();
    m_intelligenceUI->raise();
    */
    qDebug() << "Intelligence UI feature not implemented yet";
}