#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>


ControllerWindow::ControllerWindow(const bool isRunAsRoot, QWidget *parent)
    : QMainWindow(parent)
{
    // // 系统托盘图标 未来实现
    // QSystemTrayIcon *Tray = new QSystemTrayIcon(this);
    // Tray->show();

    QWidget *mainWidget = new QWidget(this);
    setCentralWidget(mainWidget);
    setWindowTitle("性能控制器");
    setMinimumWidth(420);

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

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

    cpuModelLabel = new QLabel("CPU型号: " + QString::fromStdString(CPUController::getCpuModelName()), this);

    QVBoxLayout *layout = new QVBoxLayout(mainWidget);

    cpuSmtStatusLabel = new QLabel("超线程状态: 检测中...", this);

    coreOnlineCountLabel = new QLabel("CPU在线核心数量: 检测中...", this);

    cpuSmtToggleButton = new QPushButton("切换超线程状态", this);

    cpuBoostStatusLabel = new QLabel("CPU睿频状态: 检测中...", this);

    cpuBoostToggleButton = new QPushButton("切换CPU睿频状态", this);

    QHBoxLayout *cpuMaxFreqLayout = new QHBoxLayout();
    QLabel *cpuMaxFreqLabel = new QLabel("CPU 最高频率: ", this);
    cpuMaxFreqComboBox = new QComboBox(this);
    // 暂时只考虑全大核的CPU，直接获取CPU0的频率
    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;

    cpuMaxFreqLayout->addWidget(cpuMaxFreqLabel, 1);
    cpuMaxFreqLayout->addWidget(cpuMaxFreqComboBox, 2);

    QHBoxLayout *cpuMinFreqLayout = new QHBoxLayout();
    QLabel *cpuMinFreqLabel = new QLabel("CPU 最低频率: ", this);
    cpuMinFreqComboBox = new QComboBox(this);
    // 暂时只考虑全大盒的CPU，直接获取CPU0的频率
    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;

    cpuMinFreqLayout->addWidget(cpuMinFreqLabel, 1);
    cpuMinFreqLayout->addWidget(cpuMinFreqComboBox, 2);

    layout->addWidget(cpuModelLabel);
    layout->addWidget(cpuSmtStatusLabel);
    layout->addWidget(coreOnlineCountLabel);
    layout->addWidget(cpuSmtToggleButton);
    layout->addWidget(cpuBoostStatusLabel);
    layout->addWidget(cpuBoostToggleButton);

    layout->addLayout(cpuMaxFreqLayout);
    layout->addLayout(cpuMinFreqLayout);


    fanController = new FanController();
    fanController->findFanPaths();
    std::vector<PwmFan> fans = fanController->getFans();

    QLabel *fanLabel = new QLabel("风扇曲线：", this);
    layout->addWidget(fanLabel);

    // 目前部分OEM设备还未适配，如果找不到风扇设备直接不显示
    if (!fans.empty() && isRunAsRoot)
    {

        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);
        }

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

        layout->addWidget(fanComboBox);

        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(500, 300);

        // 曲线编辑器曲线改变时刷新
        connect(fanCurveEditor, &CurveEditor::curveChanged, this, [&](const QVector<CurvePoint> &points)
                {
                    int index = fanComboBox->currentIndex();

                    if (index < 0 || index >= fanCurves.size())
                    {
                        qDebug() << "错误的风扇索引:" << index;
                        return;
                    }

                    fanCurves[index] = points;

                    // // 设置风扇曲线
                    // //fanController->setFanCurve(fans[fanComboBox->currentIndex()], fanCurves[fanComboBox->currentIndex()]);

                    // for (const auto &p : points)
                    // {
                    //     // qDebug() << QString("CPU温度: %1°C -> 风扇速度: %2%").arg(p.x).arg(p.y);
                    // }
                });

        // 风扇曲线编辑器鼠标释放时刷新
        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()]);

        layout->addWidget(fanCurveEditor);
    }
    else
    {
        QLabel *fanLabeltip = new QLabel("未找到任何PWM散热风扇，请检查设备是否支持，并确保已安装相应的驱动程序。", this);
        layout->addWidget(fanLabeltip);
    }


    // 反馈按钮
    QPushButton *feedbackButton = new QPushButton("提交issue反馈", this);
    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反馈");
        }
    });
    layout->addWidget(feedbackButton);

    // 版本信息
    QLabel *authorLabel = new QLabel("版本：0.0.1-ok1 作者：DSOE1024 欢迎在源码仓库提交issue反馈", this);
    layout->addWidget(authorLabel);

    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);

    updateUI();

}

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

    // 更新UI显示
    updateUI();
    cpuSmtToggleButton->setEnabled(true);
}

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

    // 更新UI显示
    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 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 = cpuMaxFreqComboBox->itemData(index).toInt();
    qDebug() << "Setting CPU 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("CPU核心在线数量: %1").arg(coreCount));

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

    cpuBoostStatusLabel->setText(QString("CPU睿频状态: %1").arg(boostStatus ? "已开启" : "已关闭"));
}

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

ControllerWindow::~ControllerWindow()
{
}
