#include "recorder_example_app.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QScreen>
#include <QStandardPaths>
#include <QDir>
#include <QDateTime>
#include <QKeySequence>
#include <QShortcut>
#include <QStorageInfo>
#include <QDebug>

RecorderExampleApp::RecorderExampleApp(QWidget* parent)
    : QMainWindow(parent)
    , m_recorderWidget(nullptr)
    , m_centralWidget(nullptr)
    , m_mainLayout(nullptr)
    , m_mainSplitter(nullptr)
    , m_menuBar(nullptr)
    , m_fileMenu(nullptr)
    , m_recordMenu(nullptr)
    , m_viewMenu(nullptr)
    , m_helpMenu(nullptr)
    , m_mainToolBar(nullptr)
    , m_recordToolBar(nullptr)
    , m_statusBar(nullptr)
    , m_statusLabel(nullptr)
    , m_recordingTimeLabel(nullptr)
    , m_fileSizeLabel(nullptr)
    , m_bitrateLabel(nullptr)
    , m_diskSpaceLabel(nullptr)
    , m_recordingProgress(nullptr)
    , m_trayIcon(nullptr)
    , m_trayMenu(nullptr)
    , m_showHideAction(nullptr)
    , m_trayExitAction(nullptr)
    , m_statusUpdateTimer(nullptr)
    , m_recordingTimer(nullptr)
    , m_diskSpaceTimer(nullptr)
    , m_isRecording(false)
    , m_isPaused(false)
    , m_isPreviewActive(false)
    , m_recordingStartTime(0)
    , m_recordingDuration(0)
    , m_settings(nullptr)
    , m_minimizeToTray(true)
    , m_closeToTray(true)
    , m_autoStartPreview(false)
    , m_showRecordingTime(true)
    , m_showFileSize(true)
    , m_showBitrate(true)
    , m_showDiskSpace(true) {
    
    setWindowTitle("AV录制器示例应用");
    setWindowIcon(QIcon(":/icons/recorder.png"));
    resize(1200, 800);
    
    // 居中显示
    QScreen* screen = QApplication::primaryScreen();
    if (screen) {
        QRect screenGeometry = screen->availableGeometry();
        int x = (screenGeometry.width() - width()) / 2;
        int y = (screenGeometry.height() - height()) / 2;
        move(x, y);
    }
    
    // 初始化设置
    m_settings = new QSettings("AV", "RecorderExample", this);
    
    // RecorderModule已移除，现在使用RecorderMainWidget内部的录制器
    
    // 初始化UI
    initializeUI();
    connectSignals();
    setupShortcuts();
    
    // 加载设置
    loadSettings();
    
    // 初始化定时器
    m_statusUpdateTimer = new QTimer(this);
    m_statusUpdateTimer->setInterval(1000); // 每秒更新一次
    connect(m_statusUpdateTimer, &QTimer::timeout, this, &RecorderExampleApp::updateStatusBar);
    m_statusUpdateTimer->start();
    
    m_recordingTimer = new QTimer(this);
    m_recordingTimer->setInterval(1000); // 每秒更新一次
    connect(m_recordingTimer, &QTimer::timeout, this, &RecorderExampleApp::updateRecordingTime);
    
    m_diskSpaceTimer = new QTimer(this);
    m_diskSpaceTimer->setInterval(30000); // 每30秒检查一次磁盘空间
    connect(m_diskSpaceTimer, &QTimer::timeout, this, &RecorderExampleApp::checkDiskSpace);
    m_diskSpaceTimer->start();
    
    // 创建系统托盘
    if (QSystemTrayIcon::isSystemTrayAvailable()) {
        createSystemTray();
    }
    
    // 初始化UI状态
    updateUI();
    
    // 自动开始预览
    if (m_autoStartPreview) {
        QTimer::singleShot(1000, this, &RecorderExampleApp::onStartPreview);
    }
}

RecorderExampleApp::~RecorderExampleApp() {
    saveSettings();
    
    // RecorderModule清理代码已移除
}

void RecorderExampleApp::closeEvent(QCloseEvent* event) {
    if (m_closeToTray && m_trayIcon && m_trayIcon->isVisible()) {
        hide();
        showMessage("录制器", "应用程序已最小化到系统托盘", QSystemTrayIcon::Information);
        event->ignore();
    } else {
        if (confirmExit()) {
            saveSettings();
            event->accept();
        } else {
            event->ignore();
        }
    }
}

void RecorderExampleApp::changeEvent(QEvent* event) {
    QMainWindow::changeEvent(event);
    
    if (event->type() == QEvent::WindowStateChange) {
        if (isMinimized() && m_minimizeToTray && m_trayIcon && m_trayIcon->isVisible()) {
            hide();
            event->ignore();
        }
    }
}

bool RecorderExampleApp::eventFilter(QObject* obj, QEvent* event) {
    Q_UNUSED(obj)
    Q_UNUSED(event)
    return QMainWindow::eventFilter(obj, event);
}

void RecorderExampleApp::onNewRecording() {
    if (m_isRecording) {
        int ret = QMessageBox::question(this, "新建录制", 
                                       "当前正在录制，是否停止当前录制并开始新的录制？",
                                       QMessageBox::Yes | QMessageBox::No,
                                       QMessageBox::No);
        if (ret == QMessageBox::Yes) {
            onStopRecording();
        } else {
            return;
        }
    }
    
    // 重置状态
    m_currentRecordingFile.clear();
    m_recordingDuration = 0;
    updateWindowTitle();
    updateUI();
}

void RecorderExampleApp::onOpenRecording() {
    QString fileName = QFileDialog::getOpenFileName(this, "打开录制文件", 
                                                   QStandardPaths::writableLocation(QStandardPaths::MoviesLocation),
                                                   "视频文件 (*.mp4 *.avi *.mkv *.mov);;所有文件 (*.*)");
    
    if (!fileName.isEmpty()) {
        // TODO: 实现播放录制文件的功能
        QMessageBox::information(this, "打开录制文件", 
                                 QString("将打开文件: %1\n\n此功能待实现").arg(fileName));
    }
}

void RecorderExampleApp::onSaveRecording() {
    if (m_currentRecordingFile.isEmpty()) {
        QMessageBox::information(this, "保存录制", "当前没有录制文件");
        return;
    }
    
    QString fileName = QFileDialog::getSaveFileName(this, "保存录制文件", 
                                                   m_currentRecordingFile,
                                                   "视频文件 (*.mp4 *.avi *.mkv *.mov);;所有文件 (*.*)");
    
    if (!fileName.isEmpty() && fileName != m_currentRecordingFile) {
        // TODO: 实现文件复制或移动
        QMessageBox::information(this, "保存录制文件", 
                                 QString("将保存到: %1\n\n此功能待实现").arg(fileName));
    }
}

void RecorderExampleApp::onExportRecording() {
    if (m_currentRecordingFile.isEmpty()) {
        QMessageBox::information(this, "导出录制", "当前没有录制文件");
        return;
    }
    
    // TODO: 实现录制文件导出功能
    QMessageBox::information(this, "导出录制文件", "导出功能待实现");
}

void RecorderExampleApp::onSettings() {
    if (m_recorderWidget) {
        m_recorderWidget->openSettings();
    }
}

void RecorderExampleApp::onAbout() {
    QMessageBox::about(this, "关于 AV录制器", 
                      "<h3>AV录制器示例应用</h3>"
                      "<p>版本: 1.0.0</p>"
                      "<p>这是一个基于重构后的AV录制器模块的示例应用程序。</p>"
                      "<p>功能特性:</p>"
                      "<ul>"
                      "<li>音频录制</li>"
                      "<li>视频录制</li>"
                      "<li>音视频同步录制</li>"
                      "<li>实时预览</li>"
                      "<li>硬件加速</li>"
                      "<li>多种编码格式支持</li>"
                      "</ul>"
                      "<p>© 2024 AV录制器团队</p>");
}

void RecorderExampleApp::onExit() {
    if (confirmExit()) {
        QApplication::quit();
    }
}

void RecorderExampleApp::onStartRecording() {
    if (m_recorderWidget) {
        m_recorderWidget->startRecording();
    }
}

void RecorderExampleApp::onStopRecording() {
    if (m_recorderWidget) {
        m_recorderWidget->stopRecording();
    }
}

void RecorderExampleApp::onPauseRecording() {
    if (m_recorderWidget) {
        m_recorderWidget->pauseRecording();
    }
}

void RecorderExampleApp::onResumeRecording() {
    if (m_recorderWidget) {
        m_recorderWidget->resumeRecording();
    }
}

void RecorderExampleApp::onStartPreview() {
    if (m_recorderWidget) {
        m_recorderWidget->startPreview();
    }
}

void RecorderExampleApp::onStopPreview() {
    if (m_recorderWidget) {
        m_recorderWidget->stopPreview();
    }
}

void RecorderExampleApp::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) {
    switch (reason) {
    case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
        onShowHide();
        break;
    default:
        break;
    }
}

void RecorderExampleApp::onShowHide() {
    if (isVisible()) {
        hide();
    } else {
        show();
        raise();
        activateWindow();
    }
}

// 录制器状态变化处理函数已移除
// 现在应该连接到RecorderMainWidget的相应信号

// 录制器错误和统计信息处理函数已移除
// 现在应该连接到RecorderMainWidget的相应信号

void RecorderExampleApp::updateStatusBar() {
    if (!m_statusBar) return;
    
    // 更新状态标签
    if (m_statusLabel) {
        QString status;
        if (m_isRecording) {
            status = m_isPaused ? "录制已暂停" : "正在录制";
        } else if (m_isPreviewActive) {
            status = "预览中";
        } else {
            status = "就绪";
        }
        m_statusLabel->setText(status);
    }
    
    // 更新磁盘空间
    if (m_diskSpaceLabel && m_showDiskSpace) {
        checkDiskSpace();
    }
}

void RecorderExampleApp::updateRecordingTime() {
    if (!m_isRecording || m_isPaused) return;
    
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    m_recordingDuration = (currentTime - m_recordingStartTime) / 1000;
    
    if (m_recordingTimeLabel && m_showRecordingTime) {
        m_recordingTimeLabel->setText(QString("录制时间: %1").arg(formatTime(m_recordingDuration)));
    }
    
    // 更新进度条（如果设置了最大录制时长）
    if (m_recordingProgress) {
        // TODO: 根据设置的最大录制时长更新进度
    }
}

void RecorderExampleApp::checkDiskSpace() {
    if (!m_diskSpaceLabel || !m_showDiskSpace) return;
    
    QString outputDir = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
    QStorageInfo storage(outputDir);
    
    if (storage.isValid()) {
        qint64 availableBytes = storage.bytesAvailable();
        QString diskSpace = QString("可用空间: %1").arg(formatFileSize(availableBytes));
        m_diskSpaceLabel->setText(diskSpace);
        
        // 检查磁盘空间是否不足（小于1GB）
        if (availableBytes < 1024 * 1024 * 1024) {
            m_diskSpaceLabel->setStyleSheet("color: red;");
            if (m_isRecording) {
                showMessage("磁盘空间不足", "可用磁盘空间不足1GB，建议停止录制", QSystemTrayIcon::Warning);
            }
        } else {
            m_diskSpaceLabel->setStyleSheet("");
        }
    }
}

void RecorderExampleApp::initializeUI() {
    // 创建中央部件
    m_centralWidget = new QWidget();
    setCentralWidget(m_centralWidget);
    
    // 创建主布局
    m_mainLayout = new QVBoxLayout(m_centralWidget);
    m_mainLayout->setContentsMargins(4, 4, 4, 4);
    m_mainLayout->setSpacing(4);
    
    // 创建录制器主部件
    m_recorderWidget = new RecorderMainWidget(this);
    
    // 初始化录制器主部件
    if (!m_recorderWidget->initialize()) {
        QMessageBox::critical(this, "错误", "初始化录制器失败");
        // 可以选择退出应用或者禁用录制功能
    }
    
    // 添加到布局
    m_mainLayout->addWidget(m_recorderWidget);
    
    // 创建菜单栏
    createMenuBar();
    
    // 创建工具栏
    createToolBar();
    
    // 创建状态栏
    createStatusBar();
    
    // 设置样式
    // setStyleSheet(R"(
    //     QMainWindow {
    //         background-color: #2b2b2b;
    //         color: #fff;
    //     }
    //     QMenuBar {
    //         background-color: #333;
    //         color: #fff;
    //         border-bottom: 1px solid #555;
    //     }
    //     QMenuBar::item {
    //         background-color: transparent;
    //         padding: 4px 8px;
    //     }
    //     QMenuBar::item:selected {
    //         background-color: #0a84ff;
    //     }
    //     QMenu {
    //         background-color: #333;
    //         color: #fff;
    //         border: 1px solid #555;
    //     }
    //     QMenu::item {
    //         padding: 4px 20px;
    //     }
    //     QMenu::item:selected {
    //         background-color: #0a84ff;
    //     }
    //     QToolBar {
    //         background-color: #333;
    //         border: 1px solid #555;
    //         spacing: 2px;
    //     }
    //     QToolButton {
    //         background-color: #444;
    //         border: 1px solid #666;
    //         border-radius: 3px;
    //         color: #fff;
    //         padding: 4px;
    //     }
    //     QToolButton:hover {
    //         background-color: #555;
    //     }
    //     QToolButton:pressed {
    //         background-color: #333;
    //     }
    //     QStatusBar {
    //         background-color: #333;
    //         color: #fff;
    //         border-top: 1px solid #555;
    //     }
    //     QLabel {
    //         color: #fff;
    //     }
    //     QProgressBar {
    //         border: 1px solid #555;
    //         border-radius: 3px;
    //         background-color: #444;
    //         text-align: center;
    //     }
    //     QProgressBar::chunk {
    //         background-color: #0a84ff;
    //         border-radius: 2px;
    //     }
    // )");
}

void RecorderExampleApp::createMenuBar() {
    m_menuBar = menuBar();
    
    // 文件菜单
    m_fileMenu = m_menuBar->addMenu("文件(&F)");
    
    m_newAction = new QAction(QIcon(":/icons/new.png"), "新建录制(&N)", this);
    m_newAction->setShortcut(QKeySequence::New);
    m_newAction->setStatusTip("开始新的录制");
    
    m_openAction = new QAction(QIcon(":/icons/open.png"), "打开录制(&O)", this);
    m_openAction->setShortcut(QKeySequence::Open);
    m_openAction->setStatusTip("打开录制文件");
    
    m_saveAction = new QAction(QIcon(":/icons/save.png"), "保存录制(&S)", this);
    m_saveAction->setShortcut(QKeySequence::Save);
    m_saveAction->setStatusTip("保存当前录制");
    
    m_exportAction = new QAction(QIcon(":/icons/export.png"), "导出录制(&E)", this);
    m_exportAction->setStatusTip("导出录制文件");
    
    m_fileMenu->addAction(m_newAction);
    m_fileMenu->addSeparator();
    m_fileMenu->addAction(m_openAction);
    m_fileMenu->addAction(m_saveAction);
    m_fileMenu->addAction(m_exportAction);
    m_fileMenu->addSeparator();
    
    m_settingsAction = new QAction(QIcon(":/icons/settings.png"), "设置(&T)", this);
    m_settingsAction->setShortcut(QKeySequence::Preferences);
    m_settingsAction->setStatusTip("打开设置对话框");
    m_fileMenu->addAction(m_settingsAction);
    
    m_fileMenu->addSeparator();
    
    m_exitAction = new QAction(QIcon(":/icons/exit.png"), "退出(&X)", this);
    m_exitAction->setShortcut(QKeySequence::Quit);
    m_exitAction->setStatusTip("退出应用程序");
    m_fileMenu->addAction(m_exitAction);
    
    // 录制菜单
    m_recordMenu = m_menuBar->addMenu("录制(&R)");
    
    m_startRecordingAction = new QAction(QIcon(":/icons/record.png"), "开始录制(&S)", this);
    m_startRecordingAction->setShortcut(QKeySequence("F9"));
    m_startRecordingAction->setStatusTip("开始录制");
    
    m_stopRecordingAction = new QAction(QIcon(":/icons/stop.png"), "停止录制(&T)", this);
    m_stopRecordingAction->setShortcut(QKeySequence("F10"));
    m_stopRecordingAction->setStatusTip("停止录制");
    m_stopRecordingAction->setEnabled(false);
    
    m_pauseRecordingAction = new QAction(QIcon(":/icons/pause.png"), "暂停录制(&P)", this);
    m_pauseRecordingAction->setShortcut(QKeySequence("F11"));
    m_pauseRecordingAction->setStatusTip("暂停录制");
    m_pauseRecordingAction->setEnabled(false);
    
    m_resumeRecordingAction = new QAction(QIcon(":/icons/resume.png"), "恢复录制(&R)", this);
    m_resumeRecordingAction->setShortcut(QKeySequence("F12"));
    m_resumeRecordingAction->setStatusTip("恢复录制");
    m_resumeRecordingAction->setEnabled(false);
    
    m_recordMenu->addAction(m_startRecordingAction);
    m_recordMenu->addAction(m_stopRecordingAction);
    m_recordMenu->addSeparator();
    m_recordMenu->addAction(m_pauseRecordingAction);
    m_recordMenu->addAction(m_resumeRecordingAction);
    m_recordMenu->addSeparator();
    
    m_startPreviewAction = new QAction(QIcon(":/icons/preview.png"), "开始预览(&V)", this);
    m_startPreviewAction->setStatusTip("开始视频预览");
    
    m_stopPreviewAction = new QAction(QIcon(":/icons/stop_preview.png"), "停止预览(&W)", this);
    m_stopPreviewAction->setStatusTip("停止视频预览");
    m_stopPreviewAction->setEnabled(false);
    
    m_recordMenu->addAction(m_startPreviewAction);
    m_recordMenu->addAction(m_stopPreviewAction);
    
    // 视图菜单
    m_viewMenu = m_menuBar->addMenu("视图(&V)");
    
    // 自动启动预览选项
    QAction* autoPreviewAction = new QAction("自动启动预览(&P)", this);
    autoPreviewAction->setCheckable(true);
    autoPreviewAction->setChecked(m_autoStartPreview);
    connect(autoPreviewAction, &QAction::toggled, this, [this](bool checked) {
        m_autoStartPreview = checked;
        m_settings->setValue("autoStartPreview", m_autoStartPreview);
    });
    m_viewMenu->addAction(autoPreviewAction);
    
    // 帮助菜单
    m_helpMenu = m_menuBar->addMenu("帮助(&H)");
    
    m_aboutAction = new QAction(QIcon(":/icons/about.png"), "关于(&A)", this);
    m_aboutAction->setStatusTip("关于此应用程序");
    
    m_aboutQtAction = new QAction("关于Qt(&Q)", this);
    m_aboutQtAction->setStatusTip("关于Qt框架");
    
    m_helpMenu->addAction(m_aboutAction);
    m_helpMenu->addAction(m_aboutQtAction);
}

void RecorderExampleApp::createToolBar() {
    // 主工具栏
    m_mainToolBar = addToolBar("主工具栏");
    m_mainToolBar->setObjectName("MainToolBar");
    m_mainToolBar->addAction(m_newAction);
    m_mainToolBar->addAction(m_openAction);
    m_mainToolBar->addAction(m_saveAction);
    m_mainToolBar->addSeparator();
    m_mainToolBar->addAction(m_settingsAction);
    
    // 录制工具栏
    m_recordToolBar = addToolBar("录制工具栏");
    m_recordToolBar->setObjectName("RecordToolBar");
    m_recordToolBar->addAction(m_startRecordingAction);
    m_recordToolBar->addAction(m_stopRecordingAction);
    m_recordToolBar->addAction(m_pauseRecordingAction);
    m_recordToolBar->addAction(m_resumeRecordingAction);
    m_recordToolBar->addSeparator();
    m_recordToolBar->addAction(m_startPreviewAction);
    m_recordToolBar->addAction(m_stopPreviewAction);
}

void RecorderExampleApp::createStatusBar() {
    m_statusBar = statusBar();
    
    // 状态标签
    m_statusLabel = new QLabel("就绪");
    m_statusBar->addWidget(m_statusLabel);
    
    m_statusBar->addPermanentWidget(new QLabel("|"));
    
    // 录制时间
    if (m_showRecordingTime) {
        m_recordingTimeLabel = new QLabel("录制时间: 00:00:00");
        m_statusBar->addPermanentWidget(m_recordingTimeLabel);
        m_statusBar->addPermanentWidget(new QLabel("|"));
    }
    
    // 文件大小
    if (m_showFileSize) {
        m_fileSizeLabel = new QLabel("文件大小: 0 MB");
        m_statusBar->addPermanentWidget(m_fileSizeLabel);
        m_statusBar->addPermanentWidget(new QLabel("|"));
    }
    
    // 比特率
    if (m_showBitrate) {
        m_bitrateLabel = new QLabel("比特率: 0 kbps");
        m_statusBar->addPermanentWidget(m_bitrateLabel);
        m_statusBar->addPermanentWidget(new QLabel("|"));
    }
    
    // 磁盘空间
    if (m_showDiskSpace) {
        m_diskSpaceLabel = new QLabel("可用空间: 检查中...");
        m_statusBar->addPermanentWidget(m_diskSpaceLabel);
    }
    
    // 录制进度条
    m_recordingProgress = new QProgressBar();
    m_recordingProgress->setVisible(false);
    m_recordingProgress->setMaximumWidth(200);
    m_statusBar->addPermanentWidget(m_recordingProgress);
}

void RecorderExampleApp::createSystemTray() {
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        return;
    }
    
    // 创建托盘图标
    m_trayIcon = new QSystemTrayIcon(this);
    m_trayIcon->setIcon(QIcon(":/icons/recorder.png"));
    m_trayIcon->setToolTip("AV录制器");
    
    // 创建托盘菜单
    m_trayMenu = new QMenu(this);
    
    m_showHideAction = new QAction("显示/隐藏", this);
    m_trayMenu->addAction(m_showHideAction);
    m_trayMenu->addSeparator();
    
    m_trayMenu->addAction(m_startRecordingAction);
    m_trayMenu->addAction(m_stopRecordingAction);
    m_trayMenu->addSeparator();
    
    m_trayExitAction = new QAction("退出", this);
    m_trayMenu->addAction(m_trayExitAction);
    
    m_trayIcon->setContextMenu(m_trayMenu);
    m_trayIcon->show();
}

void RecorderExampleApp::setupShortcuts() {
    // 全局快捷键
    QShortcut* quickRecordShortcut = new QShortcut(QKeySequence("Ctrl+Shift+R"), this);
    connect(quickRecordShortcut, &QShortcut::activated, [this]() {
        if (m_isRecording) {
            onStopRecording();
        } else {
            onStartRecording();
        }
    });
    
    QShortcut* quickPreviewShortcut = new QShortcut(QKeySequence("Ctrl+Shift+P"), this);
    connect(quickPreviewShortcut, &QShortcut::activated, [this]() {
        if (m_isPreviewActive) {
            onStopPreview();
        } else {
            onStartPreview();
        }
    });
}

void RecorderExampleApp::connectSignals() {
    // 菜单和工具栏信号
    connect(m_newAction, &QAction::triggered, this, &RecorderExampleApp::onNewRecording);
    connect(m_openAction, &QAction::triggered, this, &RecorderExampleApp::onOpenRecording);
    connect(m_saveAction, &QAction::triggered, this, &RecorderExampleApp::onSaveRecording);
    connect(m_exportAction, &QAction::triggered, this, &RecorderExampleApp::onExportRecording);
    connect(m_settingsAction, &QAction::triggered, this, &RecorderExampleApp::onSettings);
    connect(m_exitAction, &QAction::triggered, this, &RecorderExampleApp::onExit);
    
    connect(m_startRecordingAction, &QAction::triggered, this, &RecorderExampleApp::onStartRecording);
    connect(m_stopRecordingAction, &QAction::triggered, this, &RecorderExampleApp::onStopRecording);
    connect(m_pauseRecordingAction, &QAction::triggered, this, &RecorderExampleApp::onPauseRecording);
    connect(m_resumeRecordingAction, &QAction::triggered, this, &RecorderExampleApp::onResumeRecording);
    connect(m_startPreviewAction, &QAction::triggered, this, &RecorderExampleApp::onStartPreview);
    connect(m_stopPreviewAction, &QAction::triggered, this, &RecorderExampleApp::onStopPreview);
    
    connect(m_aboutAction, &QAction::triggered, this, &RecorderExampleApp::onAbout);
    connect(m_aboutQtAction, &QAction::triggered, qApp, &QApplication::aboutQt);
    
    // 系统托盘信号
    if (m_trayIcon) {
        connect(m_trayIcon, &QSystemTrayIcon::activated, this, &RecorderExampleApp::onTrayIconActivated);
    }
    if (m_showHideAction) {
        connect(m_showHideAction, &QAction::triggered, this, &RecorderExampleApp::onShowHide);
    }
    if (m_trayExitAction) {
        connect(m_trayExitAction, &QAction::triggered, this, &RecorderExampleApp::onExit);
    }
    
    // 录制器主部件信号
    if (m_recorderWidget) {
        // TODO: 连接RecorderMainWidget的信号
        // connect(m_recorderWidget, &RecorderMainWidget::someSignal, 
        //         this, &RecorderExampleApp::someSlot);
    }
}

void RecorderExampleApp::loadSettings() {
    // 窗口设置
    restoreGeometry(m_settings->value("geometry").toByteArray());
    restoreState(m_settings->value("windowState").toByteArray());
    
    // 应用设置
    m_minimizeToTray = m_settings->value("minimizeToTray", true).toBool();
    m_closeToTray = m_settings->value("closeToTray", true).toBool();
    m_autoStartPreview = m_settings->value("autoStartPreview", true).toBool();
    
    // 状态栏设置
    m_showRecordingTime = m_settings->value("showRecordingTime", true).toBool();
    m_showFileSize = m_settings->value("showFileSize", true).toBool();
    m_showBitrate = m_settings->value("showBitrate", true).toBool();
    m_showDiskSpace = m_settings->value("showDiskSpace", true).toBool();
}

void RecorderExampleApp::saveSettings() {
    // 窗口设置
    m_settings->setValue("geometry", saveGeometry());
    m_settings->setValue("windowState", saveState());
    
    // 应用设置
    m_settings->setValue("minimizeToTray", m_minimizeToTray);
    m_settings->setValue("closeToTray", m_closeToTray);
    m_settings->setValue("autoStartPreview", m_autoStartPreview);
    
    // 状态栏设置
    m_settings->setValue("showRecordingTime", m_showRecordingTime);
    m_settings->setValue("showFileSize", m_showFileSize);
    m_settings->setValue("showBitrate", m_showBitrate);
    m_settings->setValue("showDiskSpace", m_showDiskSpace);
    
    m_settings->sync();
}

void RecorderExampleApp::updateUI() {
    // 更新动作状态
    updateActions();
    
    // 更新窗口标题
    updateWindowTitle();
}

void RecorderExampleApp::updateActions() {
    // 录制相关动作
    m_startRecordingAction->setEnabled(!m_isRecording);
    m_stopRecordingAction->setEnabled(m_isRecording);
    m_pauseRecordingAction->setEnabled(m_isRecording && !m_isPaused);
    m_resumeRecordingAction->setEnabled(m_isRecording && m_isPaused);
    
    // 预览相关动作
    m_startPreviewAction->setEnabled(!m_isPreviewActive);
    m_stopPreviewAction->setEnabled(m_isPreviewActive);
    
    // 文件相关动作
    m_saveAction->setEnabled(!m_currentRecordingFile.isEmpty());
    m_exportAction->setEnabled(!m_currentRecordingFile.isEmpty());
}

void RecorderExampleApp::updateWindowTitle() {
    QString title = "AV录制器示例应用";
    
    if (m_isRecording) {
        if (m_isPaused) {
            title += " - 录制已暂停";
        } else {
            title += " - 正在录制";
        }
        
        if (m_recordingDuration > 0) {
            title += QString(" (%1)").arg(formatTime(m_recordingDuration));
        }
    } else if (m_isPreviewActive) {
        title += " - 预览中";
    }
    
    if (!m_currentRecordingFile.isEmpty()) {
        QFileInfo fileInfo(m_currentRecordingFile);
        title += QString(" - %1").arg(fileInfo.fileName());
    }
    
    setWindowTitle(title);
}

QString RecorderExampleApp::formatTime(qint64 seconds) const {
    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    int secs = seconds % 60;
    
    return QString("%1:%2:%3")
           .arg(hours, 2, 10, QChar('0'))
           .arg(minutes, 2, 10, QChar('0'))
           .arg(secs, 2, 10, QChar('0'));
}

QString RecorderExampleApp::formatFileSize(qint64 bytes) const {
    const qint64 KB = 1024;
    const qint64 MB = KB * 1024;
    const qint64 GB = MB * 1024;
    const qint64 TB = GB * 1024;
    
    if (bytes >= TB) {
        return QString("%1 TB").arg(static_cast<double>(bytes) / TB, 0, 'f', 2);
    } else if (bytes >= GB) {
        return QString("%1 GB").arg(static_cast<double>(bytes) / GB, 0, 'f', 2);
    } else if (bytes >= MB) {
        return QString("%1 MB").arg(static_cast<double>(bytes) / MB, 0, 'f', 2);
    } else if (bytes >= KB) {
        return QString("%1 KB").arg(static_cast<double>(bytes) / KB, 0, 'f', 2);
    } else {
        return QString("%1 B").arg(bytes);
    }
}

QString RecorderExampleApp::formatBitrate(qint64 bps) const {
    const qint64 Kbps = 1000;
    const qint64 Mbps = Kbps * 1000;
    
    if (bps >= Mbps) {
        return QString("%1 Mbps").arg(static_cast<double>(bps) / Mbps, 0, 'f', 2);
    } else if (bps >= Kbps) {
        return QString("%1 kbps").arg(static_cast<double>(bps) / Kbps, 0, 'f', 1);
    } else {
        return QString("%1 bps").arg(bps);
    }
}

bool RecorderExampleApp::confirmExit() {
    if (m_isRecording) {
        int ret = QMessageBox::question(this, "确认退出", 
                                       "当前正在录制，确定要退出吗？\n录制将被停止。",
                                       QMessageBox::Yes | QMessageBox::No,
                                       QMessageBox::No);
        
        if (ret == QMessageBox::Yes) {
            onStopRecording();
            return true;
        } else {
            return false;
        }
    }
    
    return true;
}

void RecorderExampleApp::showMessage(const QString& title, const QString& message, 
                                    QSystemTrayIcon::MessageIcon icon) {
    if (m_trayIcon && m_trayIcon->isVisible()) {
        m_trayIcon->showMessage(title, message, icon, 3000);
    }
}
