#include <fancontroller.h>
#include <controllerwindow.h>
#include <QSystemTrayIcon>
#include <QDebug>
#include <QProcess>
#include <qdebug.h>
#include <qglobal.h>
#include <qlabel.h>
#include <qwidget.h>
#include <unistd.h>
#include <QMessageBox>
#include <cpucontroller.h>
#include <curveeditor.h>
#include <batterycontroller.h>
#include <qcoreapplication.h>
#include <thermalcontroller.h>
#include <QDesktopServices>
#include <QUrl>
#include <QGroupBox>
#include <QFrame>


ControllerWindow::ControllerWindow(const bool isRunAsRoot, QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *mainWidget = new QWidget(this);
    setCentralWidget(mainWidget);
    setWindowTitle("性能控制器");
    setMinimumWidth(480);
    
    // 设置应用样式
    setStyleSheet("QGroupBox { font-weight: bold; margin-top: 12px; }"
                  "QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 5px 0 5px; }"
                  "QLabel { margin: 2px; }"
                  "QPushButton { padding: 6px; min-width: 80px; }");

    qDebug() << CPUController::getLogicalToClusterMap();

    BatteryController *batteryController = new BatteryController();
    qDebug() << batteryController->getBatteryStatus();
    qDebug() << batteryController->getBatteryLevel();

    QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget);
    mainLayout->setSpacing(12);
    mainLayout->setContentsMargins(16, 16, 16, 16);

    // CPU信息组
    QGroupBox *cpuInfoGroup = new QGroupBox("CPU信息", this);
    QVBoxLayout *cpuInfoLayout = new QVBoxLayout(cpuInfoGroup);
    
    cpuModelLabel = new QLabel("型号: " + QString::fromStdString(CPUController::getCpuModelName()), this);
    cpuSmtStatusLabel = new QLabel("超线程状态: 检测中...", this);
    coreOnlineCountLabel = new QLabel("在线核心数量: 检测中...", this);
    cpuBoostStatusLabel = new QLabel("睿频状态: 检测中...", this);
    
    cpuInfoLayout->addWidget(cpuModelLabel);
    cpuInfoLayout->addWidget(cpuSmtStatusLabel);
    cpuInfoLayout->addWidget(coreOnlineCountLabel);
    cpuInfoLayout->addWidget(cpuBoostStatusLabel);

    // CPU控制组
    QGroupBox *cpuControlGroup = new QGroupBox("CPU控制", this);
    QGridLayout *cpuControlLayout = new QGridLayout(cpuControlGroup);
    
    cpuSmtToggleButton = new QPushButton("切换超线程", this);
    cpuBoostToggleButton = new QPushButton("切换睿频", this);

    // 频率控制
    QLabel *cpuMaxFreqLabel = new QLabel("最高频率:", this);
    cpuMaxFreqComboBox = new QComboBox(this);
    std::vector<int> maxfreqs = CPUController::getAvailableFrequencies(0);
    qDebug() << maxfreqs;
    for (int freq : maxfreqs)
    {
        cpuMaxFreqComboBox->addItem(QString::number(freq / 1000) + " MHz");
        cpuMaxFreqComboBox->setItemData(cpuMaxFreqComboBox->count() - 1, freq);
    }
    cpuMaxFreqComboBox->setCurrentIndex(maxfreqs.size() - 1);
    cpuMaxFreqTmpIndex = maxfreqs.size() - 1;

    QLabel *cpuMinFreqLabel = new QLabel("最低频率:", this);
    cpuMinFreqComboBox = new QComboBox(this);
    std::vector<int> minFreqs = CPUController::getAvailableFrequencies(0);
    for (int freq : minFreqs)
    {
        cpuMinFreqComboBox->addItem(QString::number(freq / 1000) + " MHz");
        cpuMinFreqComboBox->setItemData(cpuMinFreqComboBox->count() - 1, freq);
    }
    cpuMinFreqComboBox->setCurrentIndex(0);
    cpuMinFreqTmpIndex = 0;

    // 添加到网格布局
    cpuControlLayout->addWidget(cpuSmtToggleButton, 0, 0);
    cpuControlLayout->addWidget(cpuBoostToggleButton, 0, 1);
    cpuControlLayout->addWidget(cpuMaxFreqLabel, 1, 0);
    cpuControlLayout->addWidget(cpuMaxFreqComboBox, 1, 1);
    cpuControlLayout->addWidget(cpuMinFreqLabel, 2, 0);
    cpuControlLayout->addWidget(cpuMinFreqComboBox, 2, 1);

    // 风扇控制组
    fanController = new FanController();
    fanController->findFanPaths();
    std::vector<PwmFan> fans = fanController->getFans();

    QGroupBox *fanControlGroup = new QGroupBox("风扇控制", this);
    QVBoxLayout *fanControlLayout = new QVBoxLayout(fanControlGroup);

    if (!fans.empty() && isRunAsRoot)
    {
        // 风扇选择
        QHBoxLayout *fanSelectLayout = new QHBoxLayout();
        QLabel *fanSelectLabel = new QLabel("选择风扇:", this);
        fanComboBox = new QComboBox(this);
        
        for (const auto &fan : fans)
        {
            std::string fanName = fan.fanName;
            if (fanName.find("CPU") != std::string::npos || fanName.find("Processor") != std::string::npos)
            {
                fanName += " （CPU风扇）";
            }
            if (fanName.find("Motherboard") != std::string::npos)
            {
                fanName += " （主板风扇）";
            }
            fanComboBox->addItem(QString(fanName.c_str()));

            // 初始化风扇曲线
            QVector<CurvePoint> initPoints = {
                {20.0, 20.0},
                {40.0, 30.0},
                {60.0, 60.0},
                {75.0, 75.0}};
            fanCurves.push_back(initPoints);
        }

        fanSelectLayout->addWidget(fanSelectLabel);
        fanSelectLayout->addWidget(fanComboBox);
        fanSelectLayout->addStretch();

        // 曲线编辑器
        fanCurveEditor = new CurveEditor(this);
        fanCurveEditor->setXTickTag("CPU温度(°C)");
        fanCurveEditor->setYTickTag("风扇速度(%)");
        fanCurveEditor->setGridHeight(10);
        fanCurveEditor->setGridWidth(10);
        fanCurveEditor->setYTickStep(10);
        fanCurveEditor->setXTickStep(10);
        fanCurveEditor->setYTickRange(10, 100);
        fanCurveEditor->setXTickRange(0, 100);
        fanCurveEditor->setSize(450, 280);

        // 连接信号
        connect(fanComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [&](int index)
                { fanCurveEditor->setPoints(fanCurves[index]); });

        connect(fanCurveEditor, &CurveEditor::curveChanged, this, [&](const QVector<CurvePoint> &points)
                {
                    int index = fanComboBox->currentIndex();
                    if (index >= 0 && index < fanCurves.size())
                    {
                        fanCurves[index] = points;
                    }
                });

        connect(fanCurveEditor, &CurveEditor::curveReleased, this, [&](){
            fanController->setFanCurve(fanController->getFans()[fanComboBox->currentIndex()], fanCurves[fanComboBox->currentIndex()]);
        });

        // 设置初始曲线
        fanCurveEditor->setPoints(fanCurves[fanComboBox->currentIndex()]);
        fanController->setFanCurve(fans[fanComboBox->currentIndex()], fanCurves[fanComboBox->currentIndex()]);

        fanControlLayout->addLayout(fanSelectLayout);
        fanControlLayout->addWidget(fanCurveEditor);
    }
    else
    {
        QLabel *fanWarningLabel = new QLabel("未找到PWM散热风扇\n请检查设备支持情况并确保驱动程序已安装", this);
        fanWarningLabel->setAlignment(Qt::AlignCenter);
        fanWarningLabel->setStyleSheet("color: #666; padding: 20px;");
        fanControlLayout->addWidget(fanWarningLabel);
    }

    // 底部信息区域
    QFrame *bottomFrame = new QFrame(this);
    bottomFrame->setFrameShape(QFrame::HLine);
    bottomFrame->setStyleSheet("color: #ddd;");

    QHBoxLayout *bottomLayout = new QHBoxLayout();
    
    QPushButton *feedbackButton = new QPushButton("提交反馈", this);
    feedbackButton->setToolTip("在代码仓库提交issue反馈问题或建议");
    
    QLabel *versionLabel = new QLabel("版本 0.0.1-ok1 | 作者 DSOE1024", this);
    versionLabel->setStyleSheet("color: #666; font-size: 11px;");

    bottomLayout->addWidget(feedbackButton);
    bottomLayout->addStretch();
    bottomLayout->addWidget(versionLabel);

    // 添加到主布局
    mainLayout->addWidget(cpuInfoGroup);
    mainLayout->addWidget(cpuControlGroup);
    mainLayout->addWidget(fanControlGroup);
    mainLayout->addWidget(bottomFrame);
    mainLayout->addLayout(bottomLayout);

    // 连接信号
    connect(cpuSmtToggleButton, &QPushButton::clicked, this, &ControllerWindow::toggleCpuSMT);
    connect(cpuBoostToggleButton, &QPushButton::clicked, this, &ControllerWindow::toggleCpuBoost);
    connect(cpuMaxFreqComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ControllerWindow::setCpuMaxFreq);
    connect(cpuMinFreqComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ControllerWindow::setCpuMinFreq);
    connect(feedbackButton, &QPushButton::clicked, this, [&]()
    {
        bool isOpen = QDesktopServices::openUrl(QUrl("https://gitee.com/openkylin/ukui-perf-controller/issues/new?issue"));
        if (!isOpen)
        {
            QMessageBox::critical(this, "错误", "无法打开浏览器，请手动访问 https://gitee.com/openkylin/ukui-perf-controller/issues/ 提交issue反馈");
        }
    });

    updateUI();
}

void ControllerWindow::toggleCpuSMT()
{
    cpuSmtToggleButton->setEnabled(false);
    CPUController::getCpuSMTStatus() ? CPUController::disableCpuSMT() : CPUController::enableCpuSMT();
    updateUI();
    cpuSmtToggleButton->setEnabled(true);
}

void ControllerWindow::toggleCpuBoost()
{
    cpuBoostToggleButton->setEnabled(false);
    CPUController::getCpuBoostStatus() ? CPUController::disableCpuBoost() : CPUController::enableCpuBoost();
    updateUI();
    cpuBoostToggleButton->setEnabled(true);
}

void ControllerWindow::setCpuMaxFreq(int index)
{
    if (index > cpuMinFreqComboBox->currentIndex())
    {
        QMessageBox::critical(this, "错误", "最高频率不能低于最低频率");
        cpuMaxFreqComboBox->blockSignals(true);
        cpuMaxFreqComboBox->setCurrentIndex(cpuMaxFreqTmpIndex);
        cpuMaxFreqComboBox->blockSignals(false);
        return;
    }
    
    int freq = cpuMaxFreqComboBox->itemData(index).toInt();
    qDebug() << "Setting CPU max frequency to " << freq;

    if (!CPUController::setAllCpuMaxFrequency(freq))
    {
        QMessageBox::critical(this, "错误", "无法设置CPU频率，请授予管理员权限");
        cpuMaxFreqComboBox->blockSignals(true);
        cpuMaxFreqComboBox->setCurrentIndex(cpuMaxFreqTmpIndex);
        cpuMaxFreqComboBox->blockSignals(false);
    }
    else
    {
        cpuMaxFreqTmpIndex = index;
    }
}

void ControllerWindow::setCpuMinFreq(int index)
{
    if (index < cpuMaxFreqComboBox->currentIndex())
    {
        QMessageBox::critical(this, "错误", "最低频率不能高于最高频率");
        cpuMinFreqComboBox->blockSignals(true);
        cpuMinFreqComboBox->setCurrentIndex(cpuMinFreqTmpIndex);
        cpuMinFreqComboBox->blockSignals(false);
        return;
    }
    
    int freq = cpuMinFreqComboBox->itemData(index).toInt();
    qDebug() << "Setting CPU min frequency to " << freq;

    if (!CPUController::setAllCpuMinFrequency(freq))
    {
        QMessageBox::critical(this, "错误", "无法设置CPU频率，请授予管理员权限");
        cpuMinFreqComboBox->blockSignals(true);
        cpuMinFreqComboBox->setCurrentIndex(cpuMinFreqTmpIndex);
        cpuMinFreqComboBox->blockSignals(false);
    }
    else
    {
        cpuMinFreqTmpIndex = index;
    }
}

void ControllerWindow::updateUI()
{
    bool smtStatus = CPUController::getCpuSMTStatus();
    int coreCount = CPUController::getCpuCoreOnlineCount();
    bool boostStatus = CPUController::getCpuBoostStatus();

    cpuSmtStatusLabel->setText(QString("超线程状态: %1").arg(smtStatus ? "已开启" : "已关闭"));
    coreOnlineCountLabel->setText(QString("在线核心数量: %1").arg(coreCount));
    cpuBoostStatusLabel->setText(QString("睿频状态: %1").arg(boostStatus ? "已开启" : "已关闭"));

    cpuSmtToggleButton->setText(smtStatus ? "关闭超线程" : "开启超线程");
    cpuBoostToggleButton->setText(boostStatus ? "关闭睿频" : "开启睿频");
}

bool ControllerWindow::checkIsRoot()
{
    return getuid() == 0;
}

ControllerWindow::~ControllerWindow()
{
}