/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */
#include "power.h"
#include "powermacrodata.h"

#include <QDebug>
#include <QTranslator>

Power::Power() : m_firstLoad(true)
{
    QTranslator *translator = new QTranslator(this);
    translator->load("/usr/share/ukui-power-manager/power-plugin/translations/" + QLocale::system().name());
    QApplication::installTranslator(translator);

    m_pluginName = tr("Power");
    m_pluginType = SYSTEM;
}

Power::~Power() {}

QString Power::plugini18nName()
{
    return m_pluginName;
}

int Power::pluginTypes()
{
    return m_pluginType;
}

QWidget * Power::pluginUi()
{
    if (m_firstLoad) {
        m_pluginWidget = new QWidget;
        m_pluginWidget->setAttribute(Qt::WA_DeleteOnClose);

        const QByteArray styleID(STYLE_FONT_SCHEMA);
        const QByteArray powerManagerID(POWER_MANAGER_SETTINGS);
        const QByteArray sessionID(SCREENSAVER_SCHEMA);
        const QByteArray procID(PROC_MANAGER);
        if (QGSettings::isSchemaInstalled(procID)) {
            m_procManagerSettings = new QGSettings(procID, QByteArray(), this);
        }

        if (QGSettings::isSchemaInstalled(powerManagerID)
        && QGSettings::isSchemaInstalled(styleID)
        && QGSettings::isSchemaInstalled(sessionID)) {
            m_powerManagerSettings = new QGSettings(powerManagerID, QByteArray(), this);
            m_styleSettings = new QGSettings(styleID, QByteArray(), this);
            m_screenSettings = new QGSettings(sessionID, QByteArray(), this);

            checkMachineType();
            initLogin1DBus();
            initUpowerDBus();

            initPluginWidget(m_pluginWidget);
            setupLableText();
            setupComboBoxText();
            initWidgetValue();
            connectWidgetSignals();

            setVisibleBySecurity();
            QDBusConnection::sessionBus().connect(
                        QString(), QString("/"), "org.ukui.ukcc.session.interface",
                        "configChanged", this, SLOT(setVisibleBySecurity()));

            connect(m_powerManagerSettings, &QGSettings::changed,
                    this, &Power::dealUPMSettingsChanged);

            connect(m_screenSettings, &QGSettings::changed, [=](QString key) {
                if (SLEEP_ACTIVATION_ENABLED == key) {
                    m_wakeUpComputerNeedPwdBtn->setChecked(m_screenSettings->get(key).toBool());
                } else if (CLOSE_ACTIVATION_ENABLED == key) {
                    m_wakeUpDisplayNeedPwdBtn->setChecked(m_screenSettings->get(key).toBool());
                }
            });

            if (m_procManagerSettings != nullptr &&
                m_procManagerSettings->keys().contains("resourceLimitEnable")) {
                connect(m_procManagerSettings, &QGSettings::changed, [=](QString key) {
                    if (RESOURCE_LIMIT_ENABLE == key) {
                        m_generalPowerDRSBtn->setChecked(m_procManagerSettings->get(key).toBool());
                    }
                });
            }

            connect(m_styleSettings, &QGSettings::changed, [=](QString key) {
                if("systemFont" == key || "systemFontSize" == key) {
                    setupLableText();
                }
            });
            m_firstLoad = false;
        }
    }

    return m_pluginWidget;
}

const QString Power::name() const {

    return QStringLiteral("Power");
}

bool Power::isShowOnHomePage() const
{
    return true;
}

QIcon Power::icon() const
{
    return QIcon::fromTheme("system-shutdown-symbolic");
}

QString Power::translationPath() const
{
    return "/usr/share/ukui-power-manager/power-plugin/translations/%1.ts";
}

bool Power::isEnable() const
{
#ifdef KY_SDK_SYSINFO
    QString cloudPlatForm = QString(QLatin1String(""));
    QString hostType = QString(QLatin1String(""));
    cloudPlatForm = QString(QLatin1String(kdk_system_get_hostCloudPlatform()));
    hostType = QString(QLatin1String(kdk_system_get_hostVirtType()));

    return !(cloudPlatForm == "huawei" || cloudPlatForm == "ctyun" || hostType != "none");
#endif

    return true;
}

void Power::checkMachineType()
{
#ifdef KY_SDK_SYSINFO
    quint32 productFeature = kdk_system_get_productFeatures();
    if (MACHINE_TYPE_ONLY_TABLET == productFeature ||
        MACHINE_TYPE_PC_AND_TABLET == productFeature) {
        m_isTablet = true;
        qDebug() << "machine is tablet:" << m_isTablet;
    }
#else
    m_isTablet = false;
#endif

    if ("wayland" == qgetenv("XDG_SESSION_TYPE")) {
       m_isWayland = true;
       qDebug() << "machine is wayland:" << m_isWayland;
    }
}

void Power::initLogin1DBus()
{
    QDBusInterface login1Dbus("org.freedesktop.login1",
                              "/org/freedesktop/login1",
                              "org.freedesktop.login1.Manager",
                              QDBusConnection::systemBus());

    QDBusReply<QString> reply = login1Dbus.call("CanSuspend");
    if (reply.isValid()) {
        if ("yes" == reply.value()) {
            m_canSuspend = true;
            qDebug() << "system can syspend:" << m_canSuspend;
        }
    }

    reply = login1Dbus.call("CanHibernate");
    if (reply.isValid()) {
        if ("yes" == reply.value()) {
            m_canHibernate = true;
            qDebug() << "system can hibernate:" << m_canHibernate;
        }
    }
}

void Power::initUpowerDBus()
{
    m_hasBattery = false;
    m_hasLid = false;
    m_batteryOnline = false;

    QDBusInterface dBusInterface("org.freedesktop.UPower",
                                 "/org/freedesktop/UPower",
                                 "org.freedesktop.UPower",
                                 QDBusConnection::systemBus());

    QDBusReply<QList<QDBusObjectPath>> reply = dBusInterface.call("EnumerateDevices");
    if (dBusInterface.isValid()) {
        for (QDBusObjectPath dBusObjectPath : reply.value()) {
            int upDeviceType = getDeviceType(dBusObjectPath.path());
            qDebug() << "device type:" << upDeviceType;
            if (POWER_SUPPLY_TYPE_BATTERY == upDeviceType) {
                m_hasBattery = true;
                qDebug() << "battery dBusObjectPath:" << dBusObjectPath.path();
                break;
            }
        }
    }

    QDBusInterface upowerProperties("org.freedesktop.UPower",
                                    "/org/freedesktop/UPower",
                                    "org.freedesktop.DBus.Properties",
                                    QDBusConnection::systemBus());
    QDBusMessage msg = upowerProperties.call("GetAll", "org.freedesktop.UPower");
    if (msg.type() == QDBusMessage::ReplyMessage) {
        const QDBusArgument &dbusArgs = msg.arguments().at(0).value<QDBusArgument>();
        QMap<QString, QVariant> map;
        dbusArgs >> map;

        m_hasLid = map.value(QString("LidIsPresent")).toBool();
        qDebug() << "system has lid:" << m_hasLid;

        m_batteryOnline = map.value(QString("OnBattery")).toBool();
        qDebug() << "battery online state:" << m_batteryOnline;
    }

    QDBusConnection::systemBus().connect("org.freedesktop.UPower",
                                         "/org/freedesktop/UPower",
                                         "org.freedesktop.DBus.Properties",
                                         "PropertiesChanged",
                                         this,
                                         SLOT(dealUPowerDBusMessage(QDBusMessage)));
}

void Power::initPluginWidget(QWidget *widget)
{
    qDebug() << "init power page";
    // 整体布局
    QVBoxLayout *verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setSpacing(8);
    verticalLayout->setContentsMargins(0, 0, 0, 0);

    qDebug() << "init general power main page";
    m_generalPowerTitleLabel = new TitleLabel(widget);
    //~ contents_path /Power/General
    m_generalPowerTitleLabel->setText(tr("General"));
    verticalLayout->addWidget(m_generalPowerTitleLabel);
    generalPowerSettingsFrame(widget);
    verticalLayout->addWidget(m_generalPowerFrame);

    qDebug() << "init dynamic resource scheduling main page";
    generalPowerDRSSettingsFrame(widget);
    verticalLayout->addWidget(m_generalPowerDRSFrame);

    m_spacerItem = new QSpacerItem(20, 24, QSizePolicy::Fixed);
    verticalLayout->addSpacerItem(m_spacerItem);

    qDebug() << "init power plan main page";
    m_powerPlanTitleLabel = new TitleLabel(widget);
    //~ contents_path /Power/Select power plan
    m_powerPlanTitleLabel->setText(tr("Select power plan"));
    verticalLayout->addWidget(m_powerPlanTitleLabel);
    powerPlanSettingsFrame(widget);
    verticalLayout->addWidget(m_powerPlanFrame);

    verticalLayout->addSpacing(24);

    qDebug() << "init battery save plan main page";
    m_batterySavePlanTitleLabel = new TitleLabel(widget);
    //~ contents_path /Power/Battery saving plan
    m_batterySavePlanTitleLabel->setText(tr("Battery saving plan"));
    verticalLayout->addWidget(m_batterySavePlanTitleLabel);
    batterySavePlanSettingsFrame(widget);
    verticalLayout->addWidget(m_batterySavePlanFrame);
    if (false == m_hasBattery || false == m_batteryOnline) {
        m_batterySavePlanTitleLabel->hide();
        m_batterySavePlanFrame->hide();
    }

    verticalLayout->addStretch();
}

void Power::generalPowerSettingsFrame(QWidget *widget)
{
    initMainFrame(widget, &m_generalPowerFrame, &m_generalPowerLayout);

    qDebug() << "init UI: wake up computer need pwd";
    addButtonSubFrame(m_generalPowerFrame, &m_wakeUpComputerNeedPwdFrame,
                      m_generalPowerLayout, &m_wakeUpComputerNeedPwdLine,
                      &m_wakeUpComputerNeedPwdLabel, &m_wakeUpComputerNeedPwdBtn,
                      "sleepwaken");
    if (false == m_canSuspend && false == m_canHibernate) {
        m_wakeUpComputerNeedPwdFrame->hide();
        m_wakeUpComputerNeedPwdLine->hide();
    }

    qDebug() << "init UI: wake up display need pwd";
    addButtonSubFrame(m_generalPowerFrame, &m_wakeUpDisplayNeedPwdFrame,
                      m_generalPowerLayout, &m_wakeUpDisplayNeedPwdLine,
                      &m_wakeUpDisplayNeedPwdLabel, &m_wakeUpDisplayNeedPwdBtn,
                      "lockwaken");

    qDebug() << "init UI: power key action";
    addComboBoxSubFrame(m_generalPowerFrame, &m_powerKeyActionFrame,
                        m_generalPowerLayout, &m_powerKeyActionLine,
                        &m_powerKeyActionLabel, &m_powerKeyActionComboBox,
                        "powerkey");
    if (true == m_isTablet) {
        m_powerKeyActionFrame->hide();
        m_powerKeyActionLine->hide();
    }

    qDebug() << "init UI: idle turn off display";
    addComboBoxSubFrame(m_generalPowerFrame, &m_idleTurnOffDisplayFrame,
                        m_generalPowerLayout, &m_idleTurnOffDisplayLine,
                        &m_idleTurnOffDisplayLabel, &m_idleTurnOffDisplayComboBox,
                        "idleTurnOffDisplay");

    qDebug() << "init UI: idle suspend";
    addComboBoxSubFrame(m_generalPowerFrame, &m_idleSuspendFrame,
                        m_generalPowerLayout, &m_idleSuspendLine,
                        &m_idleSuspendLabel, &m_idleSuspendComboBox,
                        "idleSuspend");
    if (false == m_canSuspend) {
        m_idleSuspendFrame->hide();
        m_idleSuspendLine->hide();
    }

    qDebug() << "init UI: close lid action";
    addComboBoxSubFrame(m_generalPowerFrame, &m_closeLidActionFrame,
                        m_generalPowerLayout, &m_closeLidActionLine,
                        &m_closeLidActionLabel, &m_closeLidActionComboBox,
                        "closeLidAction");
    if (false == m_hasLid) {
        m_closeLidActionFrame->hide();
        m_closeLidActionLine->hide();
    }
}

void Power::generalPowerDRSSettingsFrame(QWidget *widget)
{
    m_generalPowerDRSFrame = new QFrame(widget);
    m_generalPowerDRSFrame->setMinimumSize(QSize(550, 0));
    m_generalPowerDRSFrame->setMaximumSize(QSize(16777215, 16777215));
    m_generalPowerDRSFrame->setFrameShape(QFrame::Box);

    m_DRSHBoxLayout = new QHBoxLayout(m_generalPowerDRSFrame);
    m_DRSHBoxLayout->setContentsMargins(16, 0, 16, 0);

    m_generalPowerDRSLabel = new QLabel(m_generalPowerDRSFrame);
    m_generalPowerDRSLabel->setAlignment(Qt::AlignBottom);
    m_generalPowerDRSLabel->setFixedWidth(550);

    m_DRSDetialLabel = new FixLabel(widget);
    m_DRSDetialLabel->setText(tr("Reduce the occupation of backend running program resources and ensure smooth operation of key and focus applications."));
    m_DRSDetialLabel->setFixedWidth(550);
    m_DRSDetialLabel->setAlignment(Qt::AlignTop);

    QVBoxLayout *DRSLabelLayout = new QVBoxLayout(m_generalPowerDRSFrame);
    DRSLabelLayout->setSpacing(0);
    DRSLabelLayout->setContentsMargins(0,0,0,0);
    DRSLabelLayout->addWidget(m_generalPowerDRSLabel);
    DRSLabelLayout->addWidget(m_DRSDetialLabel);

    m_generalPowerDRSBtn = new KSwitchButton(m_generalPowerDRSFrame);

    m_DRSHBoxLayout->addLayout(DRSLabelLayout);
    m_DRSHBoxLayout->addStretch();
    m_DRSHBoxLayout->addWidget(m_generalPowerDRSBtn);

#ifndef UKCC2309
    m_generalPowerDRSFrame->hide();
#endif
}

void Power::powerPlanSettingsFrame(QWidget *widget)
{
    initMainFrame(widget, &m_powerPlanFrame, &m_powerPlanLayout);

    qDebug() << "init UI: ac policy";
    addComboBoxSubFrame(m_powerPlanFrame, &m_acPolicyFrame,
                        m_powerPlanLayout, &m_acPolicyLine,
                        &m_acPolicyLabel, &m_acPolicyComboBox,
                        "acPolicy");

    qDebug() << "init UI: battery policy";
    addComboBoxSubFrame(m_powerPlanFrame, &m_batteryPolicyFrame,
                        m_powerPlanLayout, &m_batteryPolicyLine,
                        &m_batteryPolicyLabel, &m_batteryPolicyComboBox,
                        "batteryPolicy");
    if (false == m_hasBattery) {
        m_batteryPolicyFrame->hide();
        m_batteryPolicyLine->hide();
    }
}

void Power::batterySavePlanSettingsFrame(QWidget *widget)
{
    initMainFrame(widget, &m_batterySavePlanFrame, &m_batterySavePlanLayout);

    qDebug() << "init UI: battery save switch";
    addButtonSubFrame(m_batterySavePlanFrame, &m_batterySaveSwitchFrame,
                      m_batterySavePlanLayout, &m_batterySaveSwitchLine,
                      &m_batterySaveSwitchLabel, &m_batterySaveSwitchBtn,
                      "batterySaveSwitch");

    qDebug() << "init UI: low power auto battery save switch";
    addButtonSubFrame(m_batterySavePlanFrame, &m_lowPowerAutoBatterySaveSwitchFrame,
                      m_batterySavePlanLayout, &m_lowPowerAutoBatterySaveSwitchLine,
                      &m_lowPowerAutoBatterySaveSwitchLabel, &m_lowPowerAutoBatterySaveSwitchBtn,
                      "lowPowerAutoBatterySaveSwitch");

    qDebug() << "init UI: reduce brightness switch";
    addButtonSubFrame(m_batterySavePlanFrame, &m_reduceBrightnessSwitchFrame,
                      m_batterySavePlanLayout, &m_reduceBrightnessSwitchLine,
                      &m_reduceBrightnessSwitchLabel, &m_reduceBrightnessSwitchBtn,
                      "reduceBrightnessSwitch");

    qDebug() << "init UI: low power notification";
    addComboBoxSubFrame(m_batterySavePlanFrame, &m_lowPowerNotificationFrame,
                      m_batterySavePlanLayout, &m_lowPowerNotificationLine,
                      &m_lowPowerNotificationLabel, &m_lowPowerNotificationComboBox,
                      "lowPowerNotification");

    qDebug() << "init UI: critical percentage action";
    criticalPercentageActionFrame();

    qDebug() << "init UI: show battery time";
    addButtonSubFrame(m_batterySavePlanFrame, &m_showBatteryTimeFrame,
                      m_batterySavePlanLayout, &m_showBatteryTimeLine,
                      &m_showBatteryTimeLabel, &m_showBatteryTimeBtn,
                      "showBatteryTime");
    m_showBatteryTimeFrame->hide();
    m_showBatteryTimeLine->hide();
}

void Power::criticalPercentageActionFrame()
{
    m_criticalPercentageActionFrame = new QFrame(m_batterySavePlanFrame);
    setFrame_Noframe(m_criticalPercentageActionFrame);

    m_criticalPercentageLable = new QLabel(m_criticalPercentageActionFrame);
    m_criticalPercentageLable->setFixedHeight(60);
    m_criticalPercentageActionLabel = new QLabel(m_criticalPercentageActionFrame);
    m_criticalPercentageActionLabel->setFixedSize(370,60);

    QHBoxLayout *criticalPercentageActionLayout = new QHBoxLayout(m_criticalPercentageActionFrame);
    criticalPercentageActionLayout->setContentsMargins(16, 0, 16, 0);

    m_criticalPercentageComboBox = new QComboBox(m_criticalPercentageActionFrame);
    m_criticalPercentageComboBox->setObjectName("criticalPercentage");
    m_criticalPercentageComboBox->setFixedWidth(80);
    m_criticalPercentageActionComboBox = new QComboBox(m_criticalPercentageActionFrame);
    m_criticalPercentageActionComboBox->setObjectName("criticalPercentageAction");
    m_criticalPercentageActionComboBox->setMinimumWidth(200);

    criticalPercentageActionLayout->setSpacing(8);
    criticalPercentageActionLayout->addWidget(m_criticalPercentageLable);
    criticalPercentageActionLayout->addWidget(m_criticalPercentageComboBox);
    criticalPercentageActionLayout->addWidget(m_criticalPercentageActionLabel);
    criticalPercentageActionLayout->addStretch();
    criticalPercentageActionLayout->addWidget(m_criticalPercentageActionComboBox);

    m_batterySavePlanLayout->addWidget(m_criticalPercentageActionFrame);
    m_criticalPercentageActionLine = setLine(m_batterySavePlanFrame);
    m_batterySavePlanLayout->addWidget(m_criticalPercentageActionLine);
}

void Power::initMainFrame(
        QWidget *widget,
        QFrame **mainFrame,
        QVBoxLayout **vBoxLayout)
{
    (*mainFrame) = new QFrame(widget);
    (*mainFrame)->setMinimumSize(QSize(550, 0));
    (*mainFrame)->setMaximumSize(QSize(16777215, 16777215));
    (*mainFrame)->setFrameShape(QFrame::Box);

    (*vBoxLayout) = new QVBoxLayout(*mainFrame);
    (*vBoxLayout)->setContentsMargins(0, 0, 0, 0);
    (*vBoxLayout)->setSpacing(0);
}

void Power::addButtonSubFrame(
        QFrame *fatherFrame, QFrame **subFrame,
        QVBoxLayout *vBoxLayout, QFrame **lineBetween,
        QLabel **subFrameLabel, KSwitchButton **button,
        const QString &buttonName)
{
    (*subFrame) = new QFrame(fatherFrame);
    setFrame_Noframe(*subFrame);

    QHBoxLayout *SubFrameLayout = new QHBoxLayout(*subFrame);
    SubFrameLayout->setContentsMargins(16, 0, 16, 0);

    (*subFrameLabel) = new QLabel(*subFrame);
    (*subFrameLabel)->setFixedSize(550,60);

    (*button) = new KSwitchButton(*subFrame);
    (*button)->setObjectName(buttonName);

    SubFrameLayout->addWidget(*subFrameLabel);
    SubFrameLayout->addStretch();
    SubFrameLayout->addWidget(*button);

    vBoxLayout->addWidget(*subFrame);
    (*lineBetween) = setLine(fatherFrame);
    vBoxLayout->addWidget(*lineBetween);
}

void Power::addComboBoxSubFrame(
        QFrame *fatherFrame, QFrame **subFrame,
        QVBoxLayout *vBoxLayout, QFrame **lineBetween,
        QLabel **subFrameLabel, QComboBox **comboBox,
        const QString &comboBoxName)
{
    (*subFrame) = new QFrame(fatherFrame);
    setFrame_Noframe(*subFrame);

    QHBoxLayout *SubFrameLayout = new QHBoxLayout(*subFrame);
    SubFrameLayout->setContentsMargins(16, 0, 16, 0);

    (*subFrameLabel) = new QLabel(*subFrame);
    (*subFrameLabel)->setFixedSize(550,59);

    (*comboBox) = new QComboBox(*subFrame);
    (*comboBox)->setObjectName(comboBoxName);
    (*comboBox)->setMinimumWidth(200);

    SubFrameLayout->addWidget(*subFrameLabel);
    SubFrameLayout->addStretch();
    SubFrameLayout->addWidget(*comboBox);

    vBoxLayout->addWidget(*subFrame);
    (*lineBetween) = setLine(fatherFrame);
    vBoxLayout->addWidget(*lineBetween);
}

void Power::setFrame_Noframe(QFrame *frame)
{
    frame->setMinimumSize(QSize(550, 60));
    frame->setFrameShape(QFrame::NoFrame);
}

bool Power::QLabelSetText(QLabel *label, QString string)
{
    bool is_over_length = false;
    QFontMetrics fontMetrics(label->font());
    int fontSize = fontMetrics.width(string);
    QString str = string;
    if (fontSize > (label->width()-5)) {
        str = fontMetrics.elidedText(string, Qt::ElideRight, label->width());
        is_over_length = true;
    }
    label->setText(str);
    return is_over_length;
}

QFrame *Power::setLine(QFrame *frame)
{
    QFrame *line = new QFrame(frame);
    line->setFixedHeight(1);
    line->setLineWidth(0);
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    return line;
}

void Power::setupLableText()
{
    QString str;
    if (true == m_canHibernate && true == m_canSuspend) {
        str = tr("Require password when sleep/hibernate");
    } else {
        if (true == m_canHibernate) {
            str = tr("Require password when hibernate");
        }
        if (true == m_canSuspend) {
            str = tr("Require password when sleep");
        }
    }

    if (QLabelSetText(m_wakeUpComputerNeedPwdLabel, str)) {
        m_wakeUpComputerNeedPwdLabel->setToolTip(str);
    }

    if (QLabelSetText(m_wakeUpDisplayNeedPwdLabel, tr("Password required when waking up the screen"))) {
        m_wakeUpDisplayNeedPwdLabel->setToolTip(tr("Password required when waking up the screen"));
    }

    if (QLabelSetText(m_powerKeyActionLabel, tr("Press the power button"))) {
        m_powerKeyActionLabel->setToolTip("Press the power button");
    }

    if (QLabelSetText(m_idleTurnOffDisplayLabel, tr("Time to close display"))) {
        m_idleTurnOffDisplayLabel->setToolTip(tr("Time to close display"));
    }

    if (QLabelSetText(m_idleSuspendLabel, tr("Time to sleep"))) {
        m_idleSuspendLabel->setToolTip(tr("Time to sleep"));
    }

    if (QLabelSetText(m_closeLidActionLabel, tr("Notebook cover"))) {
        m_closeLidActionLabel->setToolTip(tr("Notebook cover"));
    }

    if (QLabelSetText(m_generalPowerDRSLabel, tr("Dynamic resource scheduling"))) {
        m_generalPowerDRSLabel->setToolTip(tr("Dynamic resource scheduling"));
    }

    if (QLabelSetText(m_acPolicyLabel, tr("Using power"))) {
        m_acPolicyLabel->setToolTip(tr("Using power"));
    }

    if (QLabelSetText(m_batteryPolicyLabel, tr("Using battery"))) {
        m_batteryPolicyLabel->setToolTip(tr("Using power"));
    }

    if (QLabelSetText(m_batterySaveSwitchLabel, tr("Open battery saving"))) {
        m_batterySaveSwitchLabel->setToolTip(tr("Open battery saving"));
    }

    if (QLabelSetText(m_lowPowerAutoBatterySaveSwitchLabel, tr("Automatically run saving mode when low battery"))) {
        m_lowPowerAutoBatterySaveSwitchLabel->setToolTip(tr("Automatically run saving mode when low battery"));
    }

    if (QLabelSetText(m_reduceBrightnessSwitchLabel, tr("Auto display brightness level"))) {
        m_lowPowerAutoBatterySaveSwitchLabel->setToolTip(tr("Auto display brightness level"));
    }

    if (QLabelSetText(m_lowPowerNotificationLabel, tr("Low battery notification"))) {
        m_lowPowerNotificationLabel->setToolTip(tr("Low battery notification"));
    }

    if (QLabelSetText(m_criticalPercentageLable, tr("Battery level is lower than"))) {
        m_criticalPercentageLable->setToolTip(tr("Battery level is lower than"));
    }

    m_criticalPercentageActionLabel->setText(tr("Run"));
}

void Power::setupComboBoxText()
{
    m_powerKeyActionOptions << tr("interactive") << tr("shutdown") << tr("suspend") << tr("hibernate");
    m_powerKeyActionComboBox->insertItem(0, m_powerKeyActionOptions.at(0), "interactive");
    m_powerKeyActionComboBox->insertItem(1, m_powerKeyActionOptions.at(1), "shutdown");
    if (true == m_canSuspend) {
        m_powerKeyActionComboBox->insertItem(2, m_powerKeyActionOptions.at(2), "suspend");
    }
    if (true == m_canHibernate) {
        m_powerKeyActionComboBox->insertItem(3, m_powerKeyActionOptions.at(3), "hibernate");
    }

    m_idleTurnOffDisplayOptions << tr("5min") << tr("10min") << tr("15min") << tr("30min") << tr("1h") << tr("2h") << tr("never");
    m_idleTurnOffDisplayComboBox->insertItem(0, m_idleTurnOffDisplayOptions.at(0), QVariant::fromValue(5));
    m_idleTurnOffDisplayComboBox->insertItem(1, m_idleTurnOffDisplayOptions.at(1), QVariant::fromValue(10));
    m_idleTurnOffDisplayComboBox->insertItem(2, m_idleTurnOffDisplayOptions.at(2), QVariant::fromValue(15));
    m_idleTurnOffDisplayComboBox->insertItem(3, m_idleTurnOffDisplayOptions.at(3), QVariant::fromValue(30));
    m_idleTurnOffDisplayComboBox->insertItem(4, m_idleTurnOffDisplayOptions.at(4), QVariant::fromValue(60));
    m_idleTurnOffDisplayComboBox->insertItem(5, m_idleTurnOffDisplayOptions.at(5), QVariant::fromValue(120));
    m_idleTurnOffDisplayComboBox->insertItem(6, m_idleTurnOffDisplayOptions.at(6), QVariant::fromValue(0));

    m_idleSuspendOptions << tr("10min") << tr("15min") << tr("30min") << tr("1h") << tr("2h") << tr("3h") << tr("never");
    m_idleSuspendComboBox->insertItem(0, m_idleSuspendOptions.at(0), QVariant::fromValue(10));
    m_idleSuspendComboBox->insertItem(1, m_idleSuspendOptions.at(1), QVariant::fromValue(15));
    m_idleSuspendComboBox->insertItem(2, m_idleSuspendOptions.at(2), QVariant::fromValue(30));
    m_idleSuspendComboBox->insertItem(3, m_idleSuspendOptions.at(3), QVariant::fromValue(60));
    m_idleSuspendComboBox->insertItem(4, m_idleSuspendOptions.at(4), QVariant::fromValue(120));
    m_idleSuspendComboBox->insertItem(5, m_idleSuspendOptions.at(5), QVariant::fromValue(180));
    m_idleSuspendComboBox->insertItem(6, m_idleSuspendOptions.at(6), QVariant::fromValue(0));

    m_closeLidActionOptions << tr("nothing") << tr("blank") << tr("shutdown") << tr("suspend") << tr("hibernate");
    m_closeLidActionComboBox->insertItem(0, m_closeLidActionOptions.at(0), "nothing");
    m_closeLidActionComboBox->insertItem(1, m_closeLidActionOptions.at(1), "blank");
    m_closeLidActionComboBox->insertItem(2, m_closeLidActionOptions.at(2), "shutdown");
    if (true == m_canSuspend) {
        m_closeLidActionComboBox->insertItem(3, m_closeLidActionOptions.at(3), "suspend");
    }
    if (false == m_isWayland && true == m_canHibernate) {
        m_closeLidActionComboBox->insertItem(4, m_closeLidActionOptions.at(4), "hibernate");
    }

    m_acPolicyOptions << tr("Balance") << tr("Energy Efficiency")<< tr("Performance");
    m_acPolicyComboBox->insertItem(0, m_acPolicyOptions.at(0), "Balance");
    m_acPolicyComboBox->insertItem(1, m_acPolicyOptions.at(1), "Energy Efficiency");
    m_acPolicyComboBox->insertItem(2, m_acPolicyOptions.at(2), "Performance");

    m_batteryPolicyOptions << tr("Balance") << tr("Energy Efficiency")<< tr("Performance");
    m_batteryPolicyComboBox->insertItem(0, m_batteryPolicyOptions.at(0), "Balance");
    m_batteryPolicyComboBox->insertItem(1, m_batteryPolicyOptions.at(1), "Energy Efficiency");
    m_batteryPolicyComboBox->insertItem(2, m_batteryPolicyOptions.at(2), "Performance");

    m_lowPowerNotificationOptions << "10%" << "20%" << "30%" << "40%";
    for (int i = 0; i < m_lowPowerNotificationOptions.size(); ++i) {
        m_lowPowerNotificationComboBox->insertItem(i, m_lowPowerNotificationOptions.at(i));
    }

    m_criticalPercentageOptions << "5%" << "6%" << "7%" << "8%" << "9%";
    for (int i = 0; i < m_criticalPercentageOptions.size(); ++i) {
        m_criticalPercentageComboBox->insertItem(i, m_criticalPercentageOptions.at(i));
    }

    m_criticalPercentageActionOptions << tr("nothing") << tr("shutdown") << tr("hibernate") << tr("suspend");
    m_criticalPercentageActionComboBox->insertItem(0, m_criticalPercentageActionOptions.at(0), "nothing");
    m_criticalPercentageActionComboBox->insertItem(1, m_criticalPercentageActionOptions.at(1), "shutdown");
    if (true == m_canHibernate) {
        m_criticalPercentageActionComboBox->insertItem(2, m_criticalPercentageActionOptions.at(2), "hibernate");
    }
    if (true == m_canSuspend) {
        m_criticalPercentageActionComboBox->insertItem(3, m_criticalPercentageActionOptions.at(3), "suspend");
    }
}

void Power::initWidgetValue()
{
    if (m_screenSettings->keys().contains(SLEEP_ACTIVATION_ENABLED)) {
        m_wakeUpComputerNeedPwdBtn->setChecked(
            m_screenSettings->get(SLEEP_ACTIVATION_ENABLED).toBool());
    }

    if (m_screenSettings->keys().contains(CLOSE_ACTIVATION_ENABLED)) {
        m_wakeUpDisplayNeedPwdBtn->setChecked(
            m_screenSettings->get(CLOSE_ACTIVATION_ENABLED).toBool());
    }


    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_BUTTON_POWER)) {
        m_powerKeyActionComboBox->setCurrentIndex(
            m_powerKeyActionComboBox->findData(
                m_powerManagerSettings->get(GSETTINGS_KEY_BUTTON_POWER).toString()));
    }

    QVariant value;
    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_SLEEP_DISPLAY_AC)) {
        value = m_powerManagerSettings->get(GSETTINGS_KEY_SLEEP_DISPLAY_AC);
        if(-1 == value.toInt()) {
            m_idleTurnOffDisplayComboBox->setCurrentIndex(m_idleTurnOffDisplayComboBox->findData(0));
        } else {
            m_idleTurnOffDisplayComboBox->setCurrentIndex(m_idleTurnOffDisplayComboBox->findData(value.toInt() / FIXES));
        }
    }

    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_SLEEP_COMPUTER_AC)) {
        value = m_powerManagerSettings->get(GSETTINGS_KEY_SLEEP_COMPUTER_AC);
        if(-1 == value.toInt()) {
            m_idleSuspendComboBox->setCurrentIndex(m_idleSuspendComboBox->findData(0));
        } else {
            m_idleSuspendComboBox->setCurrentIndex(m_idleSuspendComboBox->findData(value.toInt() / FIXES));
        }
    }


    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_BUTTON_LID_AC)) {
        m_closeLidActionComboBox->setCurrentIndex(
            m_closeLidActionComboBox->findData(
                m_powerManagerSettings->get(GSETTINGS_KEY_BUTTON_LID_AC).toString()));
    }


    if (m_procManagerSettings != nullptr &&
        m_procManagerSettings->keys().contains("resourceLimitEnable")) {
        m_generalPowerDRSBtn->setChecked(m_procManagerSettings->get(RESOURCE_LIMIT_ENABLE).toBool());
    }

    int policy;
    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_POWER_POLICY_AC)) {
        policy = m_powerManagerSettings->get(GSETTINGS_KEY_POWER_POLICY_AC).toInt();
        switch (policy) {
            case power_policy_performance:
                m_acPolicyComboBox->setCurrentIndex(2);
                break;
            case power_policy_balance:
                m_acPolicyComboBox->setCurrentIndex(0);
                break;
            case power_policy_powersave:
                m_acPolicyComboBox->setCurrentIndex(1);
                break;
            default:
                break;
        }
    }

    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_POWER_POLICY_BATTERY)) {
        policy = m_powerManagerSettings->get(GSETTINGS_KEY_POWER_POLICY_BATTERY).toInt();
        switch (policy) {
            case power_policy_performance:
                m_batteryPolicyComboBox->setCurrentIndex(2);
                break;
            case power_policy_balance:
                m_batteryPolicyComboBox->setCurrentIndex(0);
                break;
            case power_policy_powersave:
                m_batteryPolicyComboBox->setCurrentIndex(1);
                break;
            default:
                break;
        }
    }

    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_BATTERY_SAVE_SWITCH)) {
        m_batterySaveSwitchBtn->setChecked(
            m_powerManagerSettings->get(GSETTINGS_KEY_BATTERY_SAVE_SWITCH).toBool());
    }


    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE)) {
        m_lowPowerAutoBatterySaveSwitchBtn->setChecked(
            m_powerManagerSettings->get(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE).toBool());
    }


    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS)) {
        m_reduceBrightnessSwitchBtn->setChecked(
            m_powerManagerSettings->get(GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS).toBool());
    }


    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_PERCENTAGE_LOW)) {
        m_lowPowerNotificationComboBox->setCurrentIndex(
            m_powerManagerSettings->get(GSETTINGS_KEY_PERCENTAGE_LOW).toInt() / 10 - 1);
    }


    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_PERCENTAGE_ACTION)) {
        m_criticalPercentageComboBox->setCurrentIndex(
            m_powerManagerSettings->get(GSETTINGS_KEY_PERCENTAGE_ACTION).toInt() - 5);
    }

    if (m_powerManagerSettings->keys().contains(GSETTINGS_KEY_ACTION_CRITICAL_BATTERY)) {
        m_criticalPercentageActionComboBox->setCurrentIndex(
            m_criticalPercentageActionComboBox->findData(
                m_powerManagerSettings->get(GSETTINGS_KEY_ACTION_CRITICAL_BATTERY).toString()));
    }
}

void Power::connectWidgetSignals()
{
    connect(m_wakeUpComputerNeedPwdBtn, &KSwitchButton::stateChanged, [=](bool checked){
        Power::buriedSettings(name(), "whether password is required for wake-up after sleep", QString("settings"), checked ? "true" : "false");
        m_screenSettings->set(SLEEP_ACTIVATION_ENABLED, checked);
    });

    if (m_screenSettings->keys().contains("closeActivationEnabled")) {
        connect(m_wakeUpDisplayNeedPwdBtn, &KSwitchButton::stateChanged, [=](bool checked){
            Power::buriedSettings(name(), "whether password is required for wake-up screen", QString("settings"), checked ? "true" : "false");
            m_screenSettings->set(CLOSE_ACTIVATION_ENABLED, checked);
        });
    }

    connect(m_powerKeyActionComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Power::buriedSettings(name(), "execute when pressing the power key", QString("select"), m_powerKeyActionComboBox->itemData(index).toString());
        m_powerManagerSettings->set(GSETTINGS_KEY_BUTTON_POWER, m_powerKeyActionComboBox->itemData(index));
    });

    connect(m_idleTurnOffDisplayComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Q_UNUSED(index)
        Power::buriedSettings(name(), "turn off the display after this time period", QString("select"), m_idleTurnOffDisplayComboBox->currentData().toString());
        int closeDisplayTime = m_idleTurnOffDisplayComboBox->currentData(Qt::UserRole).toInt() * 60;
        int sleepComputerTime = m_idleSuspendComboBox->currentData(Qt::UserRole).toInt() * 60;
        if (0 == closeDisplayTime) {
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_AC, -1);
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, -1);
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_AC, -1);
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, -1);
        } else {
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_AC, QVariant(closeDisplayTime));
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, QVariant(closeDisplayTime));
            if (0 != sleepComputerTime && closeDisplayTime > sleepComputerTime) {
                m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_AC, QVariant(closeDisplayTime));
                m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, QVariant(closeDisplayTime));
            }
        }
    });

    connect(m_idleSuspendComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Q_UNUSED(index)
        Power::buriedSettings(name(), "the system go to sleep after this time period", QString("select"), m_idleSuspendComboBox->currentData().toString());
        int closeDisplayTime = m_idleTurnOffDisplayComboBox->currentData(Qt::UserRole).toInt() * 60;
        int sleepComputerTime = m_idleSuspendComboBox->currentData(Qt::UserRole).toInt() * 60;
        if (0 == sleepComputerTime) {
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_AC, -1);
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, -1);
        } else {
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_AC, QVariant(sleepComputerTime));
            m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_COMPUTER_BATTERY, QVariant(sleepComputerTime));
            if (0 == closeDisplayTime || closeDisplayTime > sleepComputerTime) {
                if (10800 == sleepComputerTime) {
                    m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_AC, QVariant(7200));
                    m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, QVariant(7200));
                } else {
                    m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_AC, QVariant(sleepComputerTime));
                    m_powerManagerSettings->set(GSETTINGS_KEY_SLEEP_DISPLAY_BATTERY, QVariant(sleepComputerTime));
                }
            }
        }
    });

    connect(m_closeLidActionComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Power::buriedSettings(name(), "execute when the notebook is closed", QString("select"), m_closeLidActionComboBox->currentData().toString());
        m_powerManagerSettings->set(GSETTINGS_KEY_BUTTON_LID_AC, m_closeLidActionComboBox->itemData(index));
        m_powerManagerSettings->set(GSETTINGS_KEY_BUTTON_LID_BATTERY, m_closeLidActionComboBox->itemData(index));
    });

    connect(m_generalPowerDRSBtn, &KSwitchButton::clicked, this, [=](bool checked){
        Power::buriedSettings(name(), "whether to enable dynamic resource scheduling", QString("select"), checked ? "true" : "false");
        if (m_procManagerSettings != nullptr && m_procManagerSettings->keys().contains("resourceLimitEnable")) {
            m_procManagerSettings->set(RESOURCE_LIMIT_ENABLE, checked);
        }
    });

    connect(m_acPolicyComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Power::buriedSettings(name(), "mode when using power supply", QString("select"), m_acPolicyComboBox->currentData().toString());
        if (index == 0) {
            m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_AC, power_policy_balance);
        }  else if (index == 1) {
            m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_AC, power_policy_powersave);
        } else {
            m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_AC, power_policy_performance);
        }
    });

    connect(m_batteryPolicyComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Power::buriedSettings(name(), "mode when using battery supply", QString("select"), m_batteryPolicyComboBox->currentData().toString());
        if (index == 0) {
            m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_BATTERY, power_policy_balance);
        } else if (index == 1) {
            m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_BATTERY, power_policy_powersave);
        } else {
            m_powerManagerSettings->set(GSETTINGS_KEY_POWER_POLICY_BATTERY, power_policy_performance);
        }
    });

    connect(m_batterySaveSwitchBtn, &KSwitchButton::clicked, this, [=](bool checked){
        Power::buriedSettings(name(), "whether to enable battery save mode", QString("select"), checked ? "true" : "false");
        m_powerManagerSettings->set(GSETTINGS_KEY_BATTERY_SAVE_SWITCH, checked);
    });

    connect(m_lowPowerAutoBatterySaveSwitchBtn, &KSwitchButton::clicked, this, [=](bool checked){
        Power::buriedSettings(name(), "whether the saving mode is autoturned on when the battery is low", QString("select"), checked ? "true" : "false");
        m_powerManagerSettings->set(GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE, checked);
    });

    connect(m_reduceBrightnessSwitchBtn, &KSwitchButton::clicked, this, [=](bool checked){
        Power::buriedSettings(name(), "whether to reduce brightness when battery save mode is enabled", QString("select"), checked ? "true" : "false");
        m_powerManagerSettings->set(GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS, checked);
    });

    connect(m_lowPowerNotificationComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Power::buriedSettings(name(), "notify when the power is lower than this value", QString("select"), m_lowPowerNotificationComboBox->currentData().toString());
        m_powerManagerSettings->set(GSETTINGS_KEY_PERCENTAGE_LOW, (index + 1) * 10);
    });

    connect(m_criticalPercentageComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Power::buriedSettings(name(), "critical battery value", QString("select"), m_criticalPercentageComboBox->currentData().toString());
        m_powerManagerSettings->set(GSETTINGS_KEY_PERCENTAGE_ACTION, index + 5);
    });

    connect(m_criticalPercentageActionComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) {
        Power::buriedSettings(name(), "execute below low battery level", QString("select"), m_criticalPercentageActionComboBox->currentData().toString());
        m_powerManagerSettings->set(GSETTINGS_KEY_ACTION_CRITICAL_BATTERY, m_criticalPercentageActionComboBox->itemData(index));
    });
}

void Power::dealUPMSettingsChanged(const QString &key)
{
    if (GSETTINGS_KEY_BUTTON_POWER == key) {
        m_powerKeyActionComboBox->blockSignals(true);
        m_powerKeyActionComboBox->setCurrentIndex(
                    m_powerKeyActionComboBox->findData(
                        m_powerManagerSettings->get(key).toString()));
        m_powerKeyActionComboBox->blockSignals(false);
    } else if (GSETTINGS_KEY_SLEEP_DISPLAY_AC == key) {
        m_idleTurnOffDisplayComboBox->blockSignals(true);
        QVariant value = m_powerManagerSettings->get(key);
        if(-1 == value.toInt()) {
            m_idleTurnOffDisplayComboBox->setCurrentIndex(
                        m_idleTurnOffDisplayComboBox->findData(0));
        } else {
            m_idleTurnOffDisplayComboBox->setCurrentIndex(
                        m_idleTurnOffDisplayComboBox->findData(value.toInt() / FIXES));
        }
        m_idleTurnOffDisplayComboBox->blockSignals(false);
    } else if (GSETTINGS_KEY_SLEEP_COMPUTER_AC == key) {
        m_idleSuspendComboBox->blockSignals(true);
        QVariant value = m_powerManagerSettings->get(key);
        if(-1 == value.toInt()) {
            m_idleSuspendComboBox->setCurrentIndex(
                        m_idleSuspendComboBox->findData(0));
        } else {
            m_idleSuspendComboBox->setCurrentIndex(
                        m_idleSuspendComboBox->findData(value.toInt() / FIXES));
        }
        m_idleSuspendComboBox->blockSignals(false);
    } else if (GSETTINGS_KEY_BUTTON_LID_AC == key) {
        m_closeLidActionComboBox->blockSignals(true);
        m_closeLidActionComboBox->setCurrentIndex(
                    m_closeLidActionComboBox->findData(
                        m_powerManagerSettings->get(key).toString()));
        m_closeLidActionComboBox->blockSignals(false);
    } else if (GSETTINGS_KEY_POWER_POLICY_AC == key) {
        m_acPolicyComboBox->blockSignals(true);
        int policy = m_powerManagerSettings->get(key).toInt();
        switch (policy) {
        case power_policy_performance:
            m_acPolicyComboBox->setCurrentIndex(2);
            break;
        case power_policy_balance:
            m_acPolicyComboBox->setCurrentIndex(0);
            break;
        case power_policy_powersave:
            m_acPolicyComboBox->setCurrentIndex(1);
            break;
        default:
            break;
        }
        m_acPolicyComboBox->blockSignals(false);
    } else if (GSETTINGS_KEY_POWER_POLICY_BATTERY == key) {
        m_batteryPolicyComboBox->blockSignals(true);
        int policy = m_powerManagerSettings->get(key).toInt();
        switch (policy) {
        case power_policy_performance:
            m_batteryPolicyComboBox->setCurrentIndex(2);
            break;
        case power_policy_balance:
            m_batteryPolicyComboBox->setCurrentIndex(0);
            break;
        case power_policy_powersave:
            m_batteryPolicyComboBox->setCurrentIndex(1);
            break;
        default:
            break;
        }
        m_batteryPolicyComboBox->blockSignals(false);
    } else if (GSETTINGS_KEY_BATTERY_SAVE_SWITCH == key) {
        m_batterySaveSwitchBtn->blockSignals(true);
        m_batterySaveSwitchBtn->setChecked(
                    m_powerManagerSettings->get(key).toBool());
        m_batterySaveSwitchBtn->blockSignals(false);
    } else if (GSETTINGS_KEY_LOW_BATTERY_AUTO_SAVE == key) {
        m_lowPowerAutoBatterySaveSwitchBtn->blockSignals(true);
        m_lowPowerAutoBatterySaveSwitchBtn->setChecked(
                    m_powerManagerSettings->get(key).toBool());
        m_lowPowerAutoBatterySaveSwitchBtn->blockSignals(false);
    } else if (GSETTINGS_KEY_BATTERY_SAVE_REDUCE_BRIGHTNESS == key) {
        m_reduceBrightnessSwitchBtn->blockSignals(true);
        m_reduceBrightnessSwitchBtn->setChecked(
                    m_powerManagerSettings->get(key).toBool());
        m_reduceBrightnessSwitchBtn->blockSignals(false);
    } else if (GSETTINGS_KEY_PERCENTAGE_LOW == key) {
        m_lowPowerNotificationComboBox->blockSignals(true);
        m_lowPowerNotificationComboBox->setCurrentIndex(
                    m_powerManagerSettings->get(key).toInt() / 10 - 1);
        m_lowPowerNotificationComboBox->blockSignals(false);
    } else if (GSETTINGS_KEY_PERCENTAGE_ACTION == key) {
        m_criticalPercentageComboBox->blockSignals(true);
        m_criticalPercentageComboBox->setCurrentIndex(
                    m_powerManagerSettings->get(key).toInt() - 5);
        m_criticalPercentageComboBox->blockSignals(false);
    } else if (GSETTINGS_KEY_ACTION_CRITICAL_BATTERY == key) {
        m_criticalPercentageActionComboBox->blockSignals(true);
        m_criticalPercentageActionComboBox->setCurrentIndex(
                    m_criticalPercentageActionComboBox->findData(
                        m_powerManagerSettings->get(key).toString()));
        m_criticalPercentageActionComboBox->blockSignals(false);
    }
}

void Power::dealUPowerDBusMessage(QDBusMessage msg)
{
    const QDBusArgument &dbusArgs = msg.arguments().at(1).value<QDBusArgument>();
    QMap<QString, QVariant> map;
    dbusArgs >> map;

    if (m_hasBattery) {
        if (map.contains("OnBattery")) {
            m_batteryOnline = map.value(QString("OnBattery")).toBool();
            if (m_batteryOnline) {
                m_batterySavePlanTitleLabel->show();
                m_batterySavePlanFrame->show();
            } else {
                m_batterySavePlanTitleLabel->hide();
                m_batterySavePlanFrame->hide();
            }
        }
    }
}

void Power::setVisibleBySecurity()
{
    // 安全管控 免密登录及自动登录设置项的显示与隐藏
    QDBusInterface m_interface("org.ukui.ukcc.session", "/",
                               "org.ukui.ukcc.session.interface",
                               QDBusConnection::sessionBus());

    QDBusReply<QVariantMap> obj_reply = m_interface.call("getModuleHideStatus");
    if (!obj_reply.isValid()) {
        qDebug()<<"execute dbus method getModuleHideStatus failed";
    }

    QVariantMap ModuleMap = obj_reply.value();
    QString moduleSettings = ModuleMap.value(name().toLower() + "Settings").toString();
    QStringList setItems = moduleSettings.split(",");
    qDebug() << "--------------------" << moduleSettings << "===" <<  name().toLower();
    foreach (const QString &setItem, setItems) {
        QStringList item = setItem.split(":");
        qDebug() << "set item Name: " << item.at(0);
        if (item.at(0) == "CloseDisplayFrame") {
            m_wakeUpDisplayNeedPwdFrame->setVisible(item.at(1) == "true");
            m_wakeUpDisplayNeedPwdLine->setVisible(item.at(1) == "true");
        }
        if (item.at(0) == "SleepFrame") {
            m_wakeUpComputerNeedPwdFrame->setVisible(item.at(1) == "true");
            m_wakeUpComputerNeedPwdLine->setVisible(item.at(1) == "true");
        }
    }
}

bool Power::buriedSettings(QString pluginName, QString settingsName, QString action, QString value)
{
    // 埋点数据
    char appName[] = "ukui-control-center";
    QByteArray actiontr = action.toLocal8Bit();  // toLocal8Bit 支持中文
    char *messageType = actiontr.data();

    KBuriedPoint pt[3];
    pt[0].key = "pluginName";
    std::string pluginStr = pluginName.toStdString();
    pt[0].value = pluginStr.c_str();

    pt[1].key = "settingsName";
    std::string settingStr = settingsName.toStdString();
    pt[1].value = settingStr.c_str();

    pt[2].key = "value";
    std::string valueStr = value.toStdString();
    pt[2].value = valueStr.c_str();

    if (kdk_buried_point(appName, messageType, pt, 3) == -1) {
        qDebug() << __FUNCTION__ << "messageType:" << action << "pluginName:" << pluginName
                 << "settingsName:" << settingsName << "value:" << value << "buried point fail !" << __LINE__;
        return false;
    }

    return true;
}

int Power::getDeviceType(const QString &dBusPath)
{
    qDebug() << "device dBus object path:" << dBusPath;

    QDBusInterface dBusInterface("org.freedesktop.UPower",
                                 dBusPath,
                                 "org.freedesktop.DBus.Properties",
                                 QDBusConnection::systemBus());
    QDBusReply<QVariant> reply = dBusInterface.call("Get", "org.freedesktop.UPower.Device", "Type");
    if (reply.isValid()) {
        return reply.value().toInt();
    } else {
        qDebug() << "Get device type failed";
        return 0;
    }
}

