/**
 * @file UIInitializationManager.cpp
 * @brief UI初始化管理器实现
 * @author BattlefieldExplorationSystem Team
 * @date 2024-01-01
 * @version 2.0
 */

#include "ui/UIInitializationManager.h"
#include "ui/main/MainWindow.h"
#include "ui/components/DeviceListPanel.h"
#include "ui/components/SystemLogPanel.h"
#include "ui/components/RightFunctionPanel.h"
#include "utils/ConfigManager.h"
#include "utils/SystemLogger.h"

// C++标准库头文件
#include <random>

// Qt头文件
#include <QApplication>
#include <QDesktopWidget>
#include <QGuiApplication>
#include <QRandomGenerator>
#include <QScreen>
#include <QSplitter>
#include <QTimer>
#include <QVBoxLayout>

// WindowGeometryCalculator 实现

WindowGeometryCalculator::WindowGeometry 
WindowGeometryCalculator::calculateOptimalGeometry(ConfigManager& config)
{
    WindowGeometry geometry;
    
    // 从配置获取基本尺寸
    geometry.minWidth = config.getValue<int>("ui/min_window_width", MainWindow::MIN_WINDOW_WIDTH);
    geometry.minHeight = config.getValue<int>("ui/min_window_height", MainWindow::MIN_WINDOW_HEIGHT);
    
    // 获取屏幕几何信息
    QRect screenGeometry = getScreenGeometry();
    int margin = config.getValue<int>("ui/window_margin", MainWindow::WINDOW_MARGIN);
    
    // 计算窗口尺寸（屏幕尺寸减去边距）
    geometry.width = screenGeometry.width() - margin;
    geometry.height = screenGeometry.height() - margin;
    
    // 确保不小于最小尺寸
    geometry.width = std::max(geometry.width, geometry.minWidth);
    geometry.height = std::max(geometry.height, geometry.minHeight);
    
    // 计算居中位置
    QPoint centerPos = calculateCenterPosition(screenGeometry.size(), QSize(geometry.width, geometry.height));
    geometry.x = centerPos.x();
    geometry.y = centerPos.y();
    
    return geometry;
}

void WindowGeometryCalculator::applyGeometry(QWidget* window, const WindowGeometry& geometry)
{
    if (!window) {
        return;
    }
    
    // 设置最小尺寸
    window->setMinimumSize(geometry.minWidth, geometry.minHeight);
    
    // 设置窗口大小和位置
    window->resize(geometry.width, geometry.height);
    window->move(geometry.x, geometry.y);
}

QRect WindowGeometryCalculator::getScreenGeometry()
{
    // 使用现代化的屏幕获取方法
    QScreen* primaryScreen = QGuiApplication::primaryScreen();
    if (primaryScreen) {
        return primaryScreen->availableGeometry();
    }
    
    // 回退到旧方法（兼容性）
    return QApplication::desktop()->screenGeometry();
}

QPoint WindowGeometryCalculator::calculateCenterPosition(const QSize& screenSize, const QSize& windowSize)
{
    int x = (screenSize.width() - windowSize.width()) / 2;
    int y = (screenSize.height() - windowSize.height()) / 2;
    return QPoint(x, y);
}

// UIComponentBuilder 实现

UIComponentBuilder::UIComponentBuilder(MainWindow* mainWindow)
    : m_mainWindow(mainWindow)
    , m_built(false)
{
    if (!m_mainWindow) {
        throw std::invalid_argument("MainWindow cannot be null");
    }
}

UIComponentBuilder& UIComponentBuilder::buildSystemLogPanel()
{
    m_systemLogPanel = std::make_unique<SystemLogPanel>(m_mainWindow);
    
    // 从配置获取面板约束
    ConfigManager& config = ConfigManager::getInstance();
    int minHeight = config.getValue<int>("ui/log_panel_min_height", MainWindow::LOG_PANEL_MIN_HEIGHT);
    int maxHeight = config.getValue<int>("ui/log_panel_max_height", MainWindow::LOG_PANEL_MAX_HEIGHT);
    
    m_systemLogPanel->setMinimumHeight(minHeight);
    m_systemLogPanel->setMaximumHeight(maxHeight);
    
    return *this;
}

UIComponentBuilder& UIComponentBuilder::buildDeviceListPanel()
{
    m_deviceListPanel = std::make_unique<DeviceListPanel>(m_mainWindow);
    
    // 从配置获取面板约束
    ConfigManager& config = ConfigManager::getInstance();
    int minHeight = config.getValue<int>("ui/device_panel_min_height", MainWindow::DEVICE_PANEL_MIN_HEIGHT);
    
    m_deviceListPanel->setMinimumHeight(minHeight);
    
    return *this;
}

UIComponentBuilder& UIComponentBuilder::buildRightFunctionPanel()
{
    m_rightFunctionPanel = std::make_unique<RightFunctionPanel>(m_mainWindow);
    
    return *this;
}

UIComponentBuilder& UIComponentBuilder::buildSplitterLayout()
{
    if (!m_systemLogPanel || !m_deviceListPanel) {
        throw std::runtime_error("System log panel and device list panel must be built first");
    }
    
    // 创建垂直分割器
    m_leftPanelSplitter = std::make_unique<QSplitter>(Qt::Vertical, m_mainWindow);
    
    // 添加面板到分割器
    m_leftPanelSplitter->addWidget(m_systemLogPanel.get());
    m_leftPanelSplitter->addWidget(m_deviceListPanel.get());
    
    // 配置分割器
    configureSplitterStyle();
    setupPanelConstraints();
    
    return *this;
}

bool UIComponentBuilder::finalize()
{
    if (m_built) {
        return true;
    }
    
    // 验证所有必要组件都已构建
    if (!m_systemLogPanel || !m_deviceListPanel || !m_rightFunctionPanel || !m_leftPanelSplitter) {
        return false;
    }
    
    m_built = true;
    return true;
}

void UIComponentBuilder::configureSplitterStyle()
{
    if (!m_leftPanelSplitter) {
        return;
    }
    
    // 设置现代化的分割器样式
    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));"
        "}"
    );
}

void UIComponentBuilder::setupPanelConstraints()
{
    if (!m_leftPanelSplitter) {
        return;
    }
    
    // 从配置获取分割比例
    ConfigManager& config = ConfigManager::getInstance();
    int logRatio = config.getValue<int>("ui/splitter_log_ratio", MainWindow::SPLITTER_RATIO_LOG);
    int deviceRatio = config.getValue<int>("ui/splitter_device_ratio", MainWindow::SPLITTER_RATIO_DEVICE);
    
    // 设置分割比例
    m_leftPanelSplitter->setSizes(QList<int>() << logRatio << deviceRatio);
}

// SignalConnectionManager 实现

SignalConnectionManager::SignalConnectionManager(QObject* parent)
    : QObject(parent)
{
}

void SignalConnectionManager::connectDevicePanelSignals(DeviceListPanel* devicePanel, MainWindow* mainWindow)
{
    if (!devicePanel || !mainWindow) {
        return;
    }
    
    // 使用现代化信号槽连接语法
    makeConnection(devicePanel, &DeviceListPanel::deviceSelected,
                  mainWindow, &MainWindow::onDeviceSelected);
    
    makeConnection(devicePanel, &DeviceListPanel::deviceControlRequested,
                  mainWindow, &MainWindow::onDeviceControlRequested);
    
    makeConnection(devicePanel, &DeviceListPanel::deviceLocationRequested,
                  mainWindow, &MainWindow::onDeviceLocationRequested);
    
    makeConnection(devicePanel, &DeviceListPanel::deviceDetailsRequested,
                  mainWindow, &MainWindow::onDeviceDetailsRequested);
    
    makeConnection(devicePanel, &DeviceListPanel::addDeviceRequested,
                  mainWindow, &MainWindow::onAddDeviceRequested);
}

void SignalConnectionManager::connectRightPanelSignals(RightFunctionPanel* rightPanel, MainWindow* mainWindow)
{
    if (!rightPanel || !mainWindow) {
        return;
    }
    
    // 战场探索模块信号
    makeConnection(rightPanel, &RightFunctionPanel::startMapping,
                  mainWindow, &MainWindow::onStartMapping);
    
    makeConnection(rightPanel, &RightFunctionPanel::stopMapping,
                  mainWindow, &MainWindow::onStopMapping);
    
    makeConnection(rightPanel, &RightFunctionPanel::startNavigation,
                  mainWindow, &MainWindow::onStartNavigation);
    
    makeConnection(rightPanel, &RightFunctionPanel::stopNavigation,
                  mainWindow, &MainWindow::onStopNavigation);
    
    makeConnection(rightPanel, &RightFunctionPanel::startPhotoTransmission,
                  mainWindow, &MainWindow::onStartPhotoTransmission);
    
    makeConnection(rightPanel, &RightFunctionPanel::stopPhotoTransmission,
                  mainWindow, &MainWindow::onStopPhotoTransmission);
    
    makeConnection(rightPanel, &RightFunctionPanel::startPersonRecognition,
                  mainWindow, &MainWindow::onStartPersonRecognition);
    
    makeConnection(rightPanel, &RightFunctionPanel::stopPersonRecognition,
                  mainWindow, &MainWindow::onStopPersonRecognition);
    
    // 情报传输模块信号
    makeConnection(rightPanel, &RightFunctionPanel::startVoiceCall,
                  mainWindow, &MainWindow::onStartVoiceCall);
    
    makeConnection(rightPanel, &RightFunctionPanel::endVoiceCall,
                  mainWindow, &MainWindow::onEndVoiceCall);
    
    // 敌情统计模块信号
    makeConnection(rightPanel, &RightFunctionPanel::refreshEnemyStats,
                  mainWindow, &MainWindow::onRefreshEnemyStats);
    
    makeConnection(rightPanel, &RightFunctionPanel::requestAIAnalysis,
                  mainWindow, &MainWindow::onRequestAIAnalysis);
    
    makeConnection(rightPanel, &RightFunctionPanel::exportReport,
                  mainWindow, &MainWindow::onExportReport);
}

void SignalConnectionManager::connectConfigManagerSignals(ConfigManager* configManager, MainWindow* mainWindow)
{
    if (!configManager || !mainWindow) {
        return;
    }
    
    // 配置变更信号连接
    makeConnection(configManager, &ConfigManager::configurationChanged,
                  mainWindow, [mainWindow](const QString& key) {
                      qDebug() << "Configuration changed:" << key;
                      // 可以在这里添加配置变更的处理逻辑
                  });
}

void SignalConnectionManager::disconnectAll()
{
    for (const auto& connection : m_connections) {
        QObject::disconnect(connection);
    }
    m_connections.clear();
}

template<typename Sender, typename Signal, typename Receiver, typename Slot>
void SignalConnectionManager::makeConnection(Sender* sender, Signal signal, Receiver* receiver, Slot slot,
                                           Qt::ConnectionType connectionType)
{
    if (!sender || !receiver) {
        return;
    }
    
    auto connection = QObject::connect(sender, signal, receiver, slot, connectionType);
    if (connection) {
        m_connections.push_back(connection);
    }
}

// UIInitializationManager 实现

UIInitializationManager::UIInitializationManager(MainWindow* mainWindow, QObject* parent)
    : QObject(parent)
    , m_mainWindow(mainWindow)
    , m_configManager(&ConfigManager::getInstance())
    , m_initialized(false)
{
    if (!m_mainWindow) {
        throw std::invalid_argument("MainWindow cannot be null");
    }
    
    // 创建子管理器
    m_componentBuilder = std::make_unique<UIComponentBuilder>(m_mainWindow);
    m_connectionManager = std::make_unique<SignalConnectionManager>(this);
    m_initializationTimer = std::make_unique<QTimer>(this);
}

UIInitializationManager::~UIInitializationManager() = default;

bool UIInitializationManager::initializeUI()
{
    if (m_initialized) {
        qWarning() << "UI already initialized";
        return true;
    }
    
    qDebug() << "Starting UI initialization...";
    SystemLogger::getInstance()->logInfo("开始UI初始化");
    
    int currentStep = 0;
    
    // 步骤1：初始化窗口几何
    emit initializationProgress(++currentStep, TOTAL_INIT_STEPS, "初始化窗口几何");
    if (!initializeWindowGeometry()) {
        emit initializationCompleted(false);
        return false;
    }
    
    // 步骤2：设置随机数生成器
    emit initializationProgress(++currentStep, TOTAL_INIT_STEPS, "设置随机数生成器");
    setupRandomGenerator();
    
    // 步骤3：初始化UI组件
    emit initializationProgress(++currentStep, TOTAL_INIT_STEPS, "初始化UI组件");
    if (!initializeComponents()) {
        emit initializationCompleted(false);
        return false;
    }
    
    // 步骤4：建立信号连接
    emit initializationProgress(++currentStep, TOTAL_INIT_STEPS, "建立信号连接");
    if (!initializeSignalConnections()) {
        emit initializationCompleted(false);
        return false;
    }
    
    // 步骤5：初始化样式和主题
    emit initializationProgress(++currentStep, TOTAL_INIT_STEPS, "初始化样式和主题");
    if (!initializeStyleAndTheme()) {
        emit initializationCompleted(false);
        return false;
    }
    
    // 步骤6：最终初始化
    emit initializationProgress(++currentStep, TOTAL_INIT_STEPS, "完成最终初始化");
    if (!finalizeInitialization()) {
        emit initializationCompleted(false);
        return false;
    }
    
    // 验证初始化结果
    if (!validateInitialization()) {
        emit initializationCompleted(false);
        return false;
    }
    
    m_initialized = true;
    
    qDebug() << "UI initialization completed successfully";
    SystemLogger::getInstance()->logSuccess("UI初始化完成");
    
    emit initializationCompleted(true);
    return true;
}

bool UIInitializationManager::initializeWindowGeometry()
{
    try {
        auto geometry = WindowGeometryCalculator::calculateOptimalGeometry(*m_configManager);
        WindowGeometryCalculator::applyGeometry(m_mainWindow, geometry);
        return true;
    } catch (const std::exception& e) {
        qCritical() << "Failed to initialize window geometry:" << e.what();
        return false;
    }
}

bool UIInitializationManager::initializeComponents()
{
    try {
        // 使用建造者模式构建UI组件
        bool success = m_componentBuilder->buildSystemLogPanel()
                                         .buildDeviceListPanel()
                                         .buildRightFunctionPanel()
                                         .buildSplitterLayout()
                                         .finalize();
        
        if (!success) {
            qCritical() << "Failed to build UI components";
            return false;
        }
        
        // 设置地图显示
        m_mainWindow->setupMapDisplay();
        
        return true;
    } catch (const std::exception& e) {
        qCritical() << "Failed to initialize components:" << e.what();
        return false;
    }
}

bool UIInitializationManager::initializeSignalConnections()
{
    try {
        // 连接设备面板信号
        m_connectionManager->connectDevicePanelSignals(
            m_componentBuilder->getDeviceListPanel(), m_mainWindow);
        
        // 连接右侧功能面板信号
        m_connectionManager->connectRightPanelSignals(
            m_componentBuilder->getRightFunctionPanel(), m_mainWindow);
        
        // 连接配置管理器信号
        m_connectionManager->connectConfigManagerSignals(
            m_configManager, m_mainWindow);
        
        return true;
    } catch (const std::exception& e) {
        qCritical() << "Failed to initialize signal connections:" << e.what();
        return false;
    }
}

bool UIInitializationManager::initializeStyleAndTheme()
{
    try {
        setupGlobalStyles();
        return true;
    } catch (const std::exception& e) {
        qCritical() << "Failed to initialize style and theme:" << e.what();
        return false;
    }
}

bool UIInitializationManager::finalizeInitialization()
{
    try {
        // 初始化默认数据（使用配置而非硬编码）
        QString defaultRobotName = m_configManager->getValue<QString>("default/robot_name", "Alice");
        QString defaultRobotIP = m_configManager->getValue<QString>("default/robot_ip", "192.168.0.1");
        
        m_mainWindow->m_robotList.append(qMakePair(defaultRobotName, defaultRobotIP));
        
        defaultRobotName = m_configManager->getValue<QString>("default/robot_name_2", "Bob");
        defaultRobotIP = m_configManager->getValue<QString>("default/robot_ip_2", "192.168.0.2");
        
        m_mainWindow->m_robotList.append(qMakePair(defaultRobotName, defaultRobotIP));
        
        return true;
    } catch (const std::exception& e) {
        qCritical() << "Failed to finalize initialization:" << e.what();
        return false;
    }
}

void UIInitializationManager::setupRandomGenerator()
{
    // Qt 5.15 中 QRandomGenerator::global() 是自动初始化的
    // 不需要手动设置种子，避免"Attempted to overwrite"错误
    qDebug() << "Random generator setup: using Qt built-in initialization";
    
    // 如果需要特定的随机性，可以使用局部生成器：
    // QRandomGenerator localGenerator(QRandomGenerator::global()->generate());
}

void UIInitializationManager::setupGlobalStyles()
{
    // 这里可以设置全局样式
    // 具体样式设置由各个组件自己管理
}

bool UIInitializationManager::validateInitialization()
{
    // 验证关键组件是否正确初始化
    return m_componentBuilder->getSystemLogPanel() != nullptr &&
           m_componentBuilder->getDeviceListPanel() != nullptr &&
           m_componentBuilder->getRightFunctionPanel() != nullptr &&
           m_componentBuilder->getLeftPanelSplitter() != nullptr;
}