/*
 * 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, 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 <http://www.gnu.org/licenses/>.
 *
**/
#include "theme.h"
#include "ui_theme.h"
#include "radioproxystyle.h"

#include <QGSettings>
#include <QDebug>
#include <QtDBus/QDBusConnection>
#include <QtConcurrent>
#include <QRadioButton>

#include "iconlabel.h"

#include "cursor/xcursortheme.h"
#include "../../../shell/customstyle.h"
#include "ukcccommon.h"
using namespace ukcc;

// GTK主题
#define THEME_GTK_SCHEMA "org.mate.interface"
#define MODE_GTK_KEY     "gtk-theme"
#define ICON_GTK_KEY     "icon-theme"

#define BG_MATE_SCHEMA   "org.mate.background"
#define BG_FILE_KEY      "picture-filename"

// QT主题
#define THEME_QT_SCHEMA  "org.ukui.style"
#define MODE_QT_KEY      "style-name"
#define THEME_TRAN_KEY   "menu-transparency"
#define PEONY_TRAN_KEY   "peony-side-bar-transparency"
#define ICON_QT_KEY      "icon-theme-name"
#define WIDGET_QT_KEY    "widget-theme-name"
#define COLOR_QT_KEY     "theme-color"
#define WINDOW_RAIDUS    "window-radius"

#define GLOBAL_SCHEMA    "org.ukui.globaltheme.settings"
#define GLOBAL_NAME_KEY  "global-theme-name"
#define ISMODIFY_KEY     "is-modified"

#define ICONTHEMEPATH       "/usr/share/icons/"
#define SYSTHEMEPATH        "/usr/share/themes/"
#define CURSORS_THEMES_PATH "/usr/share/icons/"

#define CURSOR_THEME_SCHEMA "org.ukui.peripherals-mouse"
#define CURSOR_THEME_KEY    "cursor-theme"

// 透明度设置
#define PERSONALSIE_SCHEMA        "org.ukui.control-center.personalise"
#define PERSONALSIE_TRAN_KEY      "transparency"
#define PERSONALSIE_BLURRY_KEY    "blurry"
#define PERSONALSIE_EFFECT_KEY    "effect"
#define PERSONALSIE_SAVE_TRAN_KEY "save-transparency"

// 自动主题设置
#define AUTO_SCHEMA               "org.ukui.SettingsDaemon.plugins.color"
#define COLOR_KEY_AUTO_THEME      "theme-schedule-automatic"

const QString kDefCursor =           "DMZ-White";
const QString UbuntuVesionEnhance =  "22.04";
const QString kXder =                "XRender";

const int transparency = 85;
//保存关闭特效模式之前的透明度
int save_trans = 0;

const QStringList blackList       {"Adwaita", "bloom", "default", "hicolor", "HighContrast", "locolor", "LoginIcons", "ubuntu-mono-dark", "ubuntu-mono-light"};
const QStringList effectList      {"blur", "kwin4_effect_maximize", "zoom"};
const QStringList kIconsList      {"computer.png", "user-trash.png", "system-file-manager.png", "ukui-control-center.png", "kylin-software-center.png", "kylin-video.png", "kylin-assistant.png"};
const QStringList kIntelIconList  {"computer.png", "kylin-software-center.png", "ukui-control-center.png", "kylin-weather.png", "calendar-app.png", "kylin-camera.png"};

const QStringList defaultIconList {"kylin-startmenu.png", "kylin-software-center.png", "indicator-china-weather.png", "burner.png", "kylin-music.png", "kylin-photo-viewer.png"};
const QStringList heyinIconList   {"kylin-alarm-clock.png", "kylin-clipboard.png", "ukui-control-center.png", "kylin-calendar.png", "kylin-ipmsg.png", "kylin-photo-viewer.png"};
const QStringList classicIconList {"kylin-startmenu.png", "kylin-software-center.png", "kylin-alarm-clock.png", "indicator-china-weather.png", "yhkylin-backup-tools.png", "kylin-clipboard.png"};
namespace {

    // Preview cursors
    const char * const cursor_names[] =
    {
        "bd_double_arrow",
        "dnd-none",
        "left_ptr",
        "hand2",
        "watch",
        "crosshair",
    };

    const int numCursors = 6;     // The number of cursors from the above list to be previewed
}

Theme::Theme() : mFirstLoad(true)
{
    pluginName = tr("Theme");
    pluginType = PERSONALIZED;
}

Theme::~Theme()
{
    if (!mFirstLoad) {
        delete ui;
        ui = nullptr;
    }
}

QString Theme::plugini18nName() {
    return pluginName;
}

int Theme::pluginTypes() {
    return pluginType;
}

QWidget *Theme::pluginUi() {
    if (mFirstLoad) {
        mFirstLoad = false;
        ui = new Ui::Theme;
        pluginWidget = new QWidget;
        pluginWidget->setAttribute(Qt::WA_DeleteOnClose);
        ui->setupUi(pluginWidget);
        initThemeUi();
        setupGSettings();

        isUpgrade();
        setupComponent();
        setupSettings();
        initThemeMode();
        initIconTheme();
        initCursorTheme();
        initEffectMode();
        initConnection();
        initSearchText();
        hideComponent();
    }
    return pluginWidget;
}

const QString Theme::name() const {

    return QStringLiteral("Theme");
}

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

QIcon Theme::icon() const
{
    return QIcon::fromTheme("ukui-note-color-symbolic");
}

bool Theme::isEnable() const
{
    return true;
}

void Theme::initThemeUi()
{
    mThemeModeFrame = new QFrame(pluginWidget);
    mThemeModeFrame->setMinimumHeight(156);
    mThemeModeFrame->setFrameShape(QFrame::Shape::Box);

    FlowLayout *hLyt = new FlowLayout(mThemeModeFrame, 20, 40, 24);
    mThemeModeLabel = new TitleLabel(mThemeModeFrame);

    mLightBtn = new ThemeButton(tr("Light"), QPixmap(QString("://img/plugins/theme/%1.png").arg("light")), mThemeModeFrame);
    mLightBtn->setObjectName("lighttheme");
    mDarkBtn = new ThemeButton(tr("Dark"),QPixmap(QString("://img/plugins/theme/%1.png").arg("dark")), mThemeModeFrame);
    mDarkBtn->setObjectName("darktheme");
    mDefaultBtn = new ThemeButton(tr("Default"), QPixmap(QString("://img/plugins/theme/%1.png").arg("default")),mThemeModeFrame);
    mDefaultBtn->setObjectName("defaulttheme");
    mAutoBtn = new ThemeButton(tr("Auto"), QPixmap(QString("://img/plugins/theme/%1.png").arg("auto")),mThemeModeFrame);
    mAutoBtn->setObjectName("autotheme");

    mThemeModeBtnGroup = new QButtonGroup(this);

    mThemeModeBtnGroup->addButton(mLightBtn);
    mThemeModeBtnGroup->addButton(mDarkBtn);
    mThemeModeBtnGroup->addButton(mDefaultBtn);
    mThemeModeBtnGroup->addButton(mAutoBtn);

    buildThemeModeBtn(mLightBtn);
    buildThemeModeBtn(mDarkBtn);
    buildThemeModeBtn(mDefaultBtn);
    buildThemeModeBtn(mAutoBtn);

    hLyt->addWidget(mLightBtn);
    hLyt->addWidget(mDarkBtn);
    hLyt->addWidget(mAutoBtn);

    ui->thememodeLayout->addWidget(mThemeModeLabel);
    ui->thememodeLayout->addSpacing(8);
    ui->thememodeLayout->addWidget(mThemeModeFrame);

    mEffectLabel = new TitleLabel(pluginWidget);
    mEffectLabel->setText(tr("Effect setting"));

    mEffectGroup = new SettingGroup(pluginWidget);

    //~ contents_path /Theme/Performance mode
    mEffectWidget = new SwitchWidget(tr("Performance mode"), mEffectGroup);
    //~ contents_path /Theme/Transparency
    mTranWidget   = new SliderWidget(tr("Transparency"), false, mEffectGroup);
    //~ contents_path /Theme/Corner
    mCornerWidget = new ComboxWidget(tr("Corner"), mEffectGroup);

#ifndef Nile
    mCornerWidget->setVisible(false);
#endif

    mTranWidget->setLeftPixmap(QPixmap("://img/plugins/theme/opacity-currency.svg"));
    mTranWidget->setRightPixmap(QPixmap("://img/plugins/theme/opaque-light.svg"));
    mTranWidget->slider()->setRange(35, 100);

    mCornerWidget->comboBox()->addItem(tr("Right angle"), 0);
    mCornerWidget->comboBox()->addItem(tr("Small"), 6);
    mCornerWidget->comboBox()->addItem(tr("Big"), 12);

    mEffectGroup->addWidget(mEffectWidget);
    mEffectGroup->addWidget(mTranWidget);
    mEffectGroup->addWidget(mCornerWidget);

    ui->effectLyt->addWidget(mEffectLabel);
    ui->effectLyt->addWidget(mEffectGroup);
}

void Theme::initSearchText() {
    //~ contents_path /Theme/Window Theme
    mThemeModeLabel->setText(tr("Window Theme"));
    //~ contents_path /Theme/Icon theme
    mThemeIconLabel->setText(tr("Icon theme"));
    if (mThemeCursorLabel != nullptr) {
        //~ contents_path /Theme/Cursor theme
        mThemeCursorLabel->setText(tr("Cursor theme"));
    }
}

void Theme::setupSettings() {
    if (UkccCommon::isOpenkylin()) {
       m_kwinFile = QDir::homePath() + "/.config/kwinrc";
    } else {
       m_kwinFile = QDir::homePath() + "/.config/ukui-kwinrc";
    }

    kwinSettings = new QSettings(m_kwinFile, QSettings::IniFormat, this);

    QStringList keys = kwinSettings->childGroups();
    kwinSettings->beginGroup("Plugins");
    bool kwin = kwinSettings->value("blurEnabled", kwin).toBool();

    if (!kwinSettings->childKeys().contains("blurEnabled") || isBlurEffect()) {
        kwin = true;
    } else {
        kwin = false;
    }

    kwinSettings->endGroup();

    mEffectWidget->setChecked(kwin);

    if (mEffectWidget->isChecked()) {
        mTranWidget->setVisible(true);
    } else {
        mTranWidget->setVisible(false);
    }

    if (keys.contains("Compositing")) {
        kwinSettings->beginGroup("Compositing");
        QString xder;
        bool kwinOG = false;
        bool kwinEN = true;
        xder = kwinSettings->value("Backend", xder).toString();
        kwinOG = kwinSettings->value("OpenGLIsUnsafe", kwinOG).toBool();
        kwinEN = kwinSettings->value("Enabled", kwinEN).toBool();
        if (xder == kXder || kwinOG || !kwinEN) {
            mEffectGroup->setVisible(false);
            mEffectLabel->setVisible(false);
            setEffectStatus(false);
        } else {
        }
        kwinSettings->endGroup();
    } else {
    }
}

void Theme::setupComponent() {

    mIsOpenkylin = UkccCommon::isOpenkylin();
    mDarkBtn->setVisible(!UkccCommon::isCommunity());

    mDefaultBtn->setProperty("value", "ukui-default");
    mLightBtn->setProperty("value", "ukui-light");
    mDarkBtn->setProperty("value", "ukui-dark");
    mAutoBtn->setProperty("value", "ukui-auto");

    initGlobalTheme();
    initControlTheme();
#if SP2
    initJumpTheme();
#endif
}

void Theme::buildThemeModeBtn(ThemeButton *button)
{
    connect(mThemeModeBtnGroup, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), [=](QAbstractButton * eBtn){
        emit button->btnCheckedSignals(eBtn == button ? true : false);
    });
}

void Theme::initThemeMode() {
    // 获取当前主题
    QString currentThemeMode = qtSettings->get(MODE_QT_KEY).toString();
    bool isAutoTheme = getAutoTheme();

    if (isAutoTheme) {
        mThemeModeBtnGroup->buttonClicked(mAutoBtn);
        emit mAutoBtn->clicked();
    } else if ("ukui-white" == currentThemeMode || "ukui-default" == currentThemeMode) {
        mThemeBtnGroup->buttonClicked(mDefaultBtn);
        emit mDefaultBtn->clicked();
    } else if ("ukui-dark" == currentThemeMode || "ukui-black" == currentThemeMode) {
        mThemeModeBtnGroup->buttonClicked(mDarkBtn);
        emit mDarkBtn->clicked();
    } else {
        mThemeModeBtnGroup->buttonClicked(mLightBtn);
        emit mLightBtn->clicked();
    }
}

void Theme::initIconTheme() {
    mThemeIconFrame = new QFrame(pluginWidget);
    mThemeIconFrame->setMinimumHeight(156);
    mThemeIconFrame->setFrameShape(QFrame::Shape::Box);

    FlowLayout *fLyt = new FlowLayout(mThemeIconFrame, 0, 40, 0);
    fLyt->setContentsMargins(16, 16, 0, 4);
    mThemeIconLabel = new TitleLabel();

    // 构建图标主题Widget Group，方便更新选中/非选中状态
    mThemeIconBtnGroup = new QButtonGroup;

    //构建图标主题QDir
    QStringList iconThemes = getSystemIconThemes();
    foreach (QString themedir, iconThemes) {
        if (("ukui-icon-theme-default" == themedir) || ("ukui-hp" == themedir)) {
            initIconThemeWidget(themedir, fLyt);
            break;
        }
    }
    foreach (QString themedir, iconThemes) {
        if (("ukui-icon-theme-fashion" == themedir)) {
            initIconThemeWidget(themedir, fLyt);
            break;
        }
    }
    foreach (QString themedir, iconThemes) {
        if (("ukui-icon-theme-classical" == themedir)) {
            initIconThemeWidget(themedir, fLyt);
            break;
        }
    }
    foreach (QString themedir, iconThemes) {
        if ((UkccCommon::isCommunity() && (!themedir.compare("ukui") || !themedir.compare("ukui-classical") || !themedir.compare("ukui-fashion"))) ||
            (!UkccCommon::isCommunity()) ||
            (UkccCommon::isTablet() && (!themedir.compare("ukui") || themedir.startsWith("ukui-classical")))) {

            if (("ukui-icon-theme-basic" == themedir)  || ("ukui-icon-theme-default" == themedir) || ("ukui-hp" == themedir)
                ||("ukui-icon-theme-fashion" == themedir) || ("ukui-icon-theme-classical" == themedir)) {
                  continue;
            }
            if (blackList.contains(themedir))
                continue;
            initIconThemeWidget(themedir, fLyt);
        }
    }

    connect(mThemeIconBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(iconThemeBtnClickSlot(QAbstractButton*)));

    ui->iconverLyt->addWidget(mThemeIconLabel);
    ui->iconverLyt->addWidget(mThemeIconFrame);
    ui->iconverLyt->addSpacing(40);
}

void Theme::initControlTheme()
{
    if (!qtSettings->keys().contains("themeColor")) {
        return;
    }

    QString colorName = qtSettings->get(COLOR_QT_KEY).toString();

    mControlMap.insert("daybreakBlue", QColor(55, 144, 250));
    mControlMap.insert("jamPurple",    QColor(114, 46, 209));
    mControlMap.insert("magenta",      QColor(235, 48, 150));
    mControlMap.insert("sunRed",       QColor(243, 34, 45));
    mControlMap.insert("sunsetOrange", QColor(246, 140, 39));
    mControlMap.insert("dustGold",     QColor(255, 217, 102));
    mControlMap.insert("polarGreen",   QColor(82, 196, 41));

    mControlLabel = new TitleLabel();
    mControlLabel->setMaximumWidth(100);
    mControlLabel->setText(tr("Corlor"));

    mControlHLyt = new QHBoxLayout();
    mControlHLyt->addWidget(mControlLabel);
    mControlHLyt->addSpacing(32);

    mControlFrame = new QFrame(pluginWidget);
    mControlFrame->setMinimumHeight(60);
    mControlFrame->setFrameShape(QFrame::Shape::Box);

    QMap<QString, QColor>::const_iterator it = mControlMap.constBegin();
    while (it != mControlMap.constEnd()) {

        QRadioButton *radioBtn = new QRadioButton(mControlFrame);
        mRadioBtnList.append(radioBtn);
        radioBtn->setToolTip(dullTranslation(it.key()));
        radioBtn->setProperty("key", it.key());
        RadioProxystyle *style = new RadioProxystyle(it.value());
        radioBtn->setStyle(style);

        if (!colorName.compare(radioBtn->property("key").toString())) {
            radioBtn->setChecked(true);
        }

        mControlHLyt->addWidget(radioBtn);

        connect(radioBtn, &QRadioButton::clicked, this, [=] {
            const QString& value = radioBtn->property("key").toString();
            qtSettings->set(COLOR_QT_KEY, value);
            revokeGlobalThemeSlot("getQtAccentRole", value);
            qApp->setStyle(new InternalStyle("ukui"));
            UkccCommon::buriedSettings(name(), "set accent color", QString("settings"), value);
        });
        it++;
    }

    mControlHLyt->addStretch();
    mControlFrame->setLayout(mControlHLyt);
    ui->controlLyt->addWidget(mControlFrame);
}

void Theme::initCursorTheme(){
    if (UkccCommon::isTablet() || UkccCommon::isWayland())
        return;

    mThemeCursorFrame = new QFrame(pluginWidget);
    mThemeCursorFrame->setMinimumHeight(156);
    mThemeCursorFrame->setFrameShape(QFrame::Shape::Box);

    FlowLayout *fLyt = new FlowLayout(mThemeCursorFrame, 0, 40, 0);
    fLyt->setContentsMargins(16, 16, 0, 4);

    mThemeCursorLabel = new TitleLabel(mThemeCursorFrame);

    QStringList cursorThemes = getSystemCursorThemes();

    mThemeCursorBtnGroup = new QButtonGroup(this);

    for (QString cursor : cursorThemes){
        if (cursor == "dark-sense") {
            initCursorThemeWidget(cursor , fLyt);
            break;
        }
    }
    for (QString cursor : cursorThemes){
        if (cursor == "DMZ-White") {
            initCursorThemeWidget(cursor , fLyt);
            break;
        }
     }
    for (QString cursor : cursorThemes){
        if (cursor == "dark-sense" || cursor == "DMZ-White") {
            continue;
        }
        initCursorThemeWidget(cursor, fLyt);
    }

    connect(mThemeCursorBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(cursorThemeBtnClickSlot(QAbstractButton*)));

    ui->cursorVerLayout->addWidget(mThemeCursorLabel);
    ui->cursorVerLayout->addWidget(mThemeCursorFrame);
    ui->cursorVerLayout->addSpacing(40);
}

void Theme::initEffectMode()
{
    if (qtSettings->keys().contains("windowRadius")) {
        int radius = qtSettings->get(WINDOW_RAIDUS).toInt();
        mCornerWidget->setCurrentIndex(mCornerWidget->comboBox()->findData(radius));
    }

    mTranWidget->slider()->setValue(static_cast<int>(personliseGsettings->get(PERSONALSIE_TRAN_KEY).toDouble() * 100.0));
}

void Theme::initGlobalTheme()
{
    if (mGlobalSettings == nullptr) {
        return;
    }
    const QString globalName = mGlobalSettings->get("global-theme-name").toString();

    mSwitchFrame = new QFrame(pluginWidget);
    mSwitchFrame->setMinimumHeight(196);
    mSwitchFrame->setFrameShape(QFrame::Shape::Box);

    mFLyt = new FlowLayout(mSwitchFrame, 0, 40, 0);
    mFLyt->setContentsMargins(16, 16, 0, 4);
    mSwitchLabel = new TitleLabel();
    mSwitchLabel->setText(tr("Theme"));

    ui->switchLyt->addWidget(mSwitchLabel);
    mGlobalthemehelper = GlobalThemeHelper::getInstance();

    mThemeBtnGroup = new QButtonGroup(this);

    QList<GlobalTheme *> globalThemes = mGlobalthemehelper->getAllGlobalThemes();
    QList<GlobalTheme *> sorthemes = sortGlobalTheme(globalThemes);

    for (GlobalTheme *theme: sorthemes) {

        mGlobalthemehelper->loadThumbnail(theme);

        QString themeName = theme->getThemeName();
        QString i18nName  = theme->getLocaleThemeName();

        ThemeButton *btn = new ThemeButton(i18nName, mSwitchFrame);
        btn->setObjectName(themeName);
        btn->setProperty("value", themeName);
        btn->setRect(QSize(200, 164));
        mThemeBtnGroup->addButton(btn);

        mGlobalMap.insert(i18nName, btn);

        if (globalName == themeName) {
            mPrePicUnit = btn;
            btn->setBtnClicked(true);
            mThemeBtnGroup->buttonClicked(btn);
        }

        if (!themeName.compare("custom")) {
            mCustomPicUnit = btn;
        }

        mFLyt->addWidget(btn);

        connect(theme, &GlobalTheme::thumbnailLoaded, this, [=]{
            btn->setPixmap(theme->getThumbnail());
            btn->update();
        });
    }
    ui->switchLyt->addWidget(mSwitchFrame);
    ui->switchLyt->addSpacing(40);
    connect(mThemeBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(changeGlobalThemeSlot(QAbstractButton*)));
    connect(mGlobalthemehelper, &GlobalThemeHelper::globalThemesChanged, this, &Theme::changeGlobalDirSlot);
}

QList<GlobalTheme *> Theme::sortGlobalTheme(const QList<GlobalTheme *> &globalThemes)
{
    QList<GlobalTheme *> tmpGlogbalThemes;
    GlobalTheme *heyin = nullptr;
    GlobalTheme *lightSeeking = nullptr;

    for (GlobalTheme *theme: globalThemes) {
        if (theme->getThemeName() == "Light-Seeking") {
            lightSeeking = theme;
        } else if (theme->getThemeName() == "HeYin"){
            heyin = theme;
        } else {
            tmpGlogbalThemes.append(theme);
        }
    }
    if (heyin != nullptr) tmpGlogbalThemes.prepend(heyin);
    if (lightSeeking != nullptr) tmpGlogbalThemes.prepend(lightSeeking);

    return tmpGlogbalThemes;
}

void Theme::initJumpTheme()
{
    mJumpLabel  = new TitleLabel(pluginWidget);
    mJumpLabel->setText(tr("Other"));
    mRelatedGroup = new SettingGroup(pluginWidget);
    mWallWidget = new PushButtonWidget(tr("Wallpaper"), mRelatedGroup);
    mWallWidget->setObjectName("Wallpaper");
    mWallWidget->setButtonText(tr("Set"));
    mBeepWidget = new PushButtonWidget(tr("Beep"), mRelatedGroup);
    mBeepWidget->setObjectName("Beep");
    mBeepWidget->setButtonText(tr("Set"));
    mRelatedGroup->addWidget(mWallWidget);
    mRelatedGroup->addWidget(mBeepWidget);

    ui->jumpLyt->setSpacing(8);
    ui->jumpLyt->addWidget(mJumpLabel);
    ui->jumpLyt->addWidget(mRelatedGroup);

    connect(mWallWidget, &PushButtonWidget::clicked, this, [=]{
        UkccCommon::buriedSettings(name(), "set wallpaper", QString("clicked"));
        jumpFunctionSlot("wallpaper");
    });

    connect(mBeepWidget, &PushButtonWidget::clicked, this, [=]{
        UkccCommon::buriedSettings(name(), "set beep", QString("clicked"));
        jumpFunctionSlot("audio");
    });
}

void Theme::initConnection()
{
    connect(mEffectWidget, &SwitchWidget::stateChanged, [this](bool checked) {
        UkccCommon::buriedSettings(name(), "whether open effect mode", QString("settings"), checked ? "true" : "false");
        revokeGlobalThemeSlot("getBlurEnabled", checked ? "true" : "false");
        revokeGlobalThemeSlot("getSupportBlur", "true");

        changeEffectSlot(checked);

        revokeGlobalThemeSlot("getTransparencyBlur", checked ? QString::number(save_trans) : "100");
        revokeGlobalThemeSlot("getSupportTransparency", "true");
    });
    connect(mMateBgSettings, &QGSettings::changed, this, [=](const QString &key) {
        if (key == "pictureFilename" && mGlobalthemehelper != nullptr) {
            const QString& value = mMateBgSettings->get(key).toString();
            mGlobalthemehelper->updateCustomThemeSetting("getWallPaperPath", value);
        }
    });

    // 监听主题改变
    connect(qtSettings, &QGSettings::changed, this, [=](const QString &key) {
        QString currentThemeMode = qtSettings->get(key).toString();
        if (key == "styleName") {
            // 获取当前主题
            if (mAutoSettings) {
                setThemeBtnStatus();
            }
        }

        if (key == "iconThemeName") {
            QString icoName = qtSettings->get(ICON_QT_KEY).toString();
            foreach (QAbstractButton *btn, mThemeIconBtnGroup->buttons()) {
                if (btn->property("value").isValid() && btn->property("value") == icoName) {
                    disconnect(mThemeIconBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(iconThemeBtnClickSlot(QAbstractButton*)));
                    btn->click();
                    connect(mThemeIconBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(iconThemeBtnClickSlot(QAbstractButton*)));
                }
            }
        }

        if (key == "themeColor") {
            updateAccentColorSlot(currentThemeMode);
        }

        if (key == "windowRadius") {
            updateRadiusStatus(qtSettings->get(key).toInt());
        }
    });

    connect(gtkSettings,&QGSettings::changed,this,[=] (const QString &key) {
       if(key == "iconTheme") {
           QString icoName = qtSettings->get(ICON_QT_KEY).toString();
           foreach (QAbstractButton *btn, mThemeIconBtnGroup->buttons()) {
               if (btn->property("value").isValid() && btn->property("value") == icoName) {
                   disconnect(mThemeIconBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(iconThemeBtnClickSlot(QAbstractButton*)));
                   btn->click();
                   connect(mThemeIconBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(iconThemeBtnClickSlot(QAbstractButton*)));
               }
           }
       }
    });

    if (!UkccCommon::isWayland()) {
        connect(curSettings, &QGSettings::changed, this, [=](const QString &key) {
            if (key == "cursorTheme") {
                QString cursorTheme = curSettings->get(CURSOR_THEME_KEY).toString();
                foreach (QAbstractButton *btn, mThemeCursorBtnGroup->buttons()) {
                    if (btn->property("value").isValid() && btn->property("value") == cursorTheme) {
                        disconnect(mThemeCursorBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(cursorThemeBtnClickSlot(QAbstractButton*)));
                        btn->click();
                        connect(mThemeCursorBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(cursorThemeBtnClickSlot(QAbstractButton*)));
                    }
                }
            }
        });
    }

    connect(personliseGsettings, &QGSettings::changed,this,[=] (const QString &key) {
        if (key == "effect") {
            if (UkccCommon::isOpenkylin())
                qApp->setStyle(new InternalStyle("ukui"));
            bool effectEnabled = personliseGsettings->get("effect").toBool();
            mEffectWidget->blockSignals(true);
            mEffectWidget->setChecked(effectEnabled);
            mEffectWidget->blockSignals(false);
       }
    });

    if (mAutoSettings) {
        connect(mAutoSettings, &QGSettings::changed, this, [=](const QString &key) {
            if (key == "themeScheduleAutomatic") {
                bool isAutoTheme = getAutoTheme();
                if (isAutoTheme) {
                    if (!mAutoBtn->isChecked()) {
                        emit mAutoBtn->click();
                    }
                } else {
                    setThemeBtnStatus();
                }
             }
        });
    }

    connect(mThemeModeBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(themeBtnClickSlot(QAbstractButton*)));

    connect(mTranWidget->slider(), &KSlider::valueChanged, this, [=](int value) {
        changeTranpancySlot(value);
        revokeGlobalThemeSlot("getTransparencyBlur", QString::number(value, 10));
        revokeGlobalThemeSlot("getSupportTransparency", "true");
        UkccCommon::buriedSettings(name(), "set transparency", QString("select"), QString::number(value));
    });

    connect(mCornerWidget, &ComboxWidget::currentIndexChanged, this, [=](int index) {
        int value = mCornerWidget->comboBox()->itemData(index).toInt();
        setRadiusSlot(value);
        revokeGlobalThemeSlot("getRadiusValue", QString::number(value));
        UkccCommon::buriedSettings(name(), "set radiusValue", QString("settings"), QString::number(value));
    });
}

void Theme::initIconThemeWidget(QString themedir , FlowLayout *horLyt)
{
    // 获取当前图标主题(以QT为准，后续可以对比GTK两个值)
    QString currentIconTheme = qtSettings->get(ICON_QT_KEY).toString();

    IconTheme curIconTheme(themedir);

    QDir appsDir = QDir(ICONTHEMEPATH + themedir + "/32x32/apps/");
    QDir placesDir = QDir(ICONTHEMEPATH + themedir + "/32x32/places/");
    QDir devicesDir = QDir(ICONTHEMEPATH + themedir + "/32x32/devices/");
    appsDir.setFilter(QDir::Files | QDir::NoSymLinks);
    devicesDir.setFilter(QDir::Files | QDir::NoSymLinks);
    placesDir.setFilter(QDir::Files | QDir::NoSymLinks);

    QStringList showIconsList;
    QStringList realIconsList;

    if (!UkccCommon::isTablet()) {
         realIconsList = defaultIconList;
    } else {
        realIconsList = kIntelIconList;
    }

    for (int i = 0; i < realIconsList.count(); i++) {
        QString iconPath = curIconTheme.iconPath(realIconsList.at(i), 32, qApp->devicePixelRatio());

        if (!iconPath.isEmpty()) {
            showIconsList.append(iconPath);
        } else {
            iconPath = curIconTheme.iconPath("application-x-desktop.png", 32, qApp->devicePixelRatio());
            if (iconPath.isEmpty())
                return;
            showIconsList.append(iconPath);
        }

    }
    ThemeButton *button = new ThemeButton(dullTranslation(themedir.section("-", -1, -1, QString::SectionSkipEmpty)), showIconsList, pluginWidget);
    button->setObjectName(themedir);
    button->setProperty("value", themedir);
     mThemeIconBtnGroup->addButton(button);
    connect(mThemeIconBtnGroup, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), [=](QAbstractButton * eBtn){
        emit button->btnCheckedSignals(eBtn == button ? true : false);
    });
    // 加入Layout
    horLyt->addWidget(button);

    if (themedir == currentIconTheme){
        button->clicked();
        mThemeIconBtnGroup->buttonClicked(button);
    }
}

void Theme::initCursorThemeWidget(QString themedir, FlowLayout *fLyt)
{
    // 获取当前指针主题
    QString currentCursorTheme;
    currentCursorTheme = curSettings->get(CURSOR_THEME_KEY).toString();
    if (themedir == "DMZ-Black" && !mIsUpgrade) return;

    QList<QPixmap> cursorVec;
    QString path = CURSORS_THEMES_PATH + themedir;
    XCursorTheme *cursorTheme = new XCursorTheme(path);

    for(int i = 0; i < numCursors; i++){
        int size = qApp->devicePixelRatio() * 8;
        QImage image = cursorTheme->loadImage(cursor_names[i],size);
        cursorVec.append(QPixmap::fromImage(image));
    }

    ThemeButton *button = new ThemeButton(dullCursorTranslation(themedir), cursorVec, pluginWidget);
    button->setObjectName(themedir);
    button->setProperty("value", themedir);
    mThemeCursorBtnGroup->addButton(button);
    connect(mThemeCursorBtnGroup, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), [=](QAbstractButton * eBtn){
        emit button->btnCheckedSignals(eBtn == button ? true : false);
    });
    // 加入Layout
    fLyt->addWidget(button);

    if (themedir == currentCursorTheme){
        button->clicked();
        mThemeCursorBtnGroup->buttonClicked(button);
    }
}

QStringList Theme::getSystemCursorThemes() {
    QStringList themes;
    QDir themesDir(CURSORS_THEMES_PATH);

    if (themesDir.exists()){
        foreach (QString dirname, themesDir.entryList(QDir::Dirs)){
            if (dirname == "." || dirname == "..")
                continue;
            QDir themeDir(CURSORS_THEMES_PATH + dirname + "/cursors/");
            if (themeDir.exists())
                themes.append(dirname);
        }
    }
    return themes;
}

void Theme::setThemeBtnStatus()
{
    QString currentThemeMode = qtSettings->get(MODE_QT_KEY).toString();
    bool isAutoTheme = getAutoTheme();

    for (QAbstractButton * button : mThemeModeBtnGroup->buttons()) {
        QString propertyName = button->property("value").toString();
        if ("ukui-black" == currentThemeMode) {
            currentThemeMode = "ukui-dark";
        } else if ("ukui-white" == currentThemeMode) {
            currentThemeMode = "ukui-light";
        } else if ("ukui-auto" == propertyName && isAutoTheme && button->isChecked()) {
            return ;
        }

        if (propertyName == currentThemeMode && !isAutoTheme) {
            disconnect(mThemeModeBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(themeBtnClickSlot(QAbstractButton*)));
            button->click();
            connect(mThemeModeBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(themeBtnClickSlot(QAbstractButton*)));
        }
    }
}

QStringList Theme::readFile(QString filepath) {
    QStringList fileCont;
    QFile file(filepath);
    if (file.exists()) {
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qWarning() << "ReadFile() failed to open" << filepath;
            return QStringList();
        }
        QTextStream textStream(&file);
        while (!textStream.atEnd()) {
            QString line= textStream.readLine();
            line.remove('\n');
            fileCont<<line;
        }
        file.close();
        return fileCont;
    } else {
        qWarning() << filepath << " not found"<<endl;
        return QStringList();
    }
}

void Theme::setupGSettings() {
    const QByteArray id(THEME_GTK_SCHEMA);
    const QByteArray idd(THEME_QT_SCHEMA);
    const QByteArray iid(CURSOR_THEME_SCHEMA);
    const QByteArray iiid(PERSONALSIE_SCHEMA);
    const QByteArray globalID(GLOBAL_SCHEMA);
    const QByteArray bgID(BG_MATE_SCHEMA);
    const QByteArray autoID(AUTO_SCHEMA);

    gtkSettings         = new QGSettings(id,   QByteArray(), this);
    qtSettings          = new QGSettings(idd,  QByteArray(), this);
    curSettings         = new QGSettings(iid,  QByteArray(), this);
    personliseGsettings = new QGSettings(iiid, QByteArray(), this);
    mMateBgSettings     = new QGSettings(bgID, QByteArray(), this);

#ifdef Nile
    mKySettings = kdk_conf2_new("control-center.personalise", NULL);
#endif

    if (QGSettings::isSchemaInstalled(autoID)) {
        mAutoSettings = new QGSettings(autoID, QByteArray(), this);
    }

    if (QGSettings::isSchemaInstalled(globalID)) {
        mGlobalSettings = new QGSettings(globalID, QByteArray(), this);
        connect(mGlobalSettings, &QGSettings::changed, this, &Theme::setCustomGlobalSlot);
    }
}

void Theme::setEffectStatus(bool status)
{
#ifdef Nile
    kdk_conf2_set_boolean(mKySettings, "effect", status);
#else
    personliseGsettings->set(PERSONALSIE_EFFECT_KEY, false);
#endif
}

void Theme::kwinCursorSlot(QString value) {

    QString filename = QDir::homePath() + "/.config/kcminputrc";
    QSettings *mouseSettings = new QSettings(filename, QSettings::IniFormat);

    mouseSettings->beginGroup("Mouse");
    mouseSettings->setValue("cursorTheme", value);
    mouseSettings->endGroup();

    delete mouseSettings;
    mouseSettings = nullptr;

    QDBusMessage message = QDBusMessage::createSignal("/KGlobalSettings", "org.kde.KGlobalSettings", "notifyChange");
    QList<QVariant> args;
    args.append(5);
    args.append(0);
    message.setArguments(args);
    QDBusConnection::sessionBus().send(message);
}

QString Theme::dullCursorTranslation(QString str) {
    if (!QString::compare(str, "blue-crystal")){
        return tr("Blue-Crystal");
    } else if (!QString::compare(str, "lightseeking")) {
        return tr("Light-Seeking");
    } else if (!QString::compare(str, "DMZ-Black")) {
        return tr("DMZ-Black");
    } else if (!QString::compare(str, "DMZ-White")) {
        return tr("DMZ-White");
    } else if (!QString::compare(str, "dark-sense")) {
        return tr("Dark-Sense");
    } else {
        return str;
    }
}

QString Theme::getCursorName() {
    return curSettings->get(CURSOR_THEME_KEY).toString();
}

QString Theme::getGlobalName()
{
    mGlobalName = mGlobalSettings->get(GLOBAL_NAME_KEY).toString();
    return mGlobalName;
}

bool Theme::getAutoTheme()
{
    return mAutoSettings->get(COLOR_KEY_AUTO_THEME).toBool();
}

void Theme::hideComponent()
{
    mDefaultBtn->setVisible(false);

    if (UkccCommon::isTablet()) {
        mTranWidget->setVisible(false);
    }
}

void Theme::clickedCustomTheme()
{
    if (mCustomPicUnit && !mCustomPicUnit->isChecked()) {
        disconnect(mThemeBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(changeGlobalThemeSlot(QAbstractButton*)));
        mCustomPicUnit->setBtnClicked(true);
        mThemeBtnGroup->buttonClicked(mCustomPicUnit);
        connect(mThemeBtnGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(changeGlobalThemeSlot(QAbstractButton*)));
    }

    if (mPrePicUnit && mPrePicUnit != mCustomPicUnit) {
        mPrePicUnit->setBtnClicked(false);
        mPrePicUnit = mCustomPicUnit;
    }
}

void Theme::updateRadiusStatus(int radius)
{
    mCornerWidget->blockSignals(true);
    mCornerWidget->setCurrentIndex(mCornerWidget->comboBox()->findData(radius));
    mCornerWidget->blockSignals(false);
}

bool Theme::isBlurEffect()
{
    QDBusInterface ifc(!mIsOpenkylin ? "org.ukui.KWin" : "org.kde.KWin",
                       "/Effects",
                       !mIsOpenkylin ? "org.ukui.kwin.Effects" : "org.kde.kwin.Effects",
                       QDBusConnection::sessionBus());
    QStringList effects = ifc.property("activeEffects").toStringList();
    return effects.contains("blur");
}

bool Theme::isUpgrade()
{
#ifdef KY_SDK_SYSINFO
    version_t ver= kdk_system_get_version_detaile();
    QString version = QString(ver.update_version);
    mIsUpgrade = (version != "2303");
#else
    mIsUpgrade = false;
#endif
    return mIsUpgrade;
}



QString Theme::dullTranslation(QString str) {
    if (!QString::compare(str, "basic")){
        return tr("basic");
    } else if (!QString::compare(str, "classical")) { // 启典
        return UkccCommon::isTablet() ? tr("classic") : tr("Classic");
    } else if (!QString::compare(str, "default") || !QString::compare(str, "xunguang")) { // 寻光
        return UkccCommon::isTablet() ? tr("basic") : tr("Light-Seeking");
    } else if (!QString::compare(str, "fashion") || !QString::compare(str, "heyin")) {   // 和印
        return tr("HeYin");
    } else if (!QString::compare(str, "hp")) {
        return tr("hp");
    } else if (!QString::compare(str, "ukui")) {
        return UkccCommon::isTablet() ? tr("basic") : tr("ukui");
    } else if (!QString::compare(str, "daybreakBlue")) {
        return tr("daybreakBlue");
    } else if (!QString::compare(str, "jamPurple")) {
        return tr("jamPurple");
    } else if (!QString::compare(str, "magenta")) {
        return tr("magenta");
    } else if (!QString::compare(str, "sunRed")) {
        return tr("sunRed");
    } else if (!QString::compare(str, "sunsetOrange")) {
        return tr("sunsetOrange");
    } else if (!QString::compare(str, "dustGold")) {
        return tr("dustGold");
    } else if (!QString::compare(str, "polarGreen")) {
        return tr("polarGreen");
    } else {
        return str;
    }
}

QStringList Theme::getSystemIconThemes()
{
    QStringList themes;
    QDir themesDir(ICONTHEMEPATH);

    if (themesDir.exists()){
        foreach (QString dirname, themesDir.entryList(QDir::Dirs)){
            if (dirname == "." || dirname == "..")
                continue;
            QFile iconthemefile(ICONTHEMEPATH + dirname + "/icon-theme.cache");
            if (iconthemefile.exists())
                themes.append(dirname);
        }
    }
    return themes;
}

// 重置设置
void Theme::resetBtnClickSlot() {

    emit mThemeModeBtnGroup->buttonClicked(mDefaultBtn);

    curSettings->reset(CURSOR_THEME_KEY);
    QString cursorTheme = kDefCursor;
    QString defaultCursor = getCursorName();
    if (defaultCursor.isEmpty()) {
        curSettings->set(CURSOR_THEME_KEY, kDefCursor);
    } else {
        cursorTheme = defaultCursor;
    }
    kwinCursorSlot(cursorTheme);

    qtSettings->reset(ICON_QT_KEY);
    gtkSettings->reset(ICON_GTK_KEY);

    if (mEffectWidget->isVisible()) {
        mEffectWidget->setChecked(true);
        qtSettings->reset(THEME_TRAN_KEY);
        qtSettings->reset(PEONY_TRAN_KEY);
        personliseGsettings->reset(PERSONALSIE_TRAN_KEY);
        mTranWidget->slider()->setValue(transparency);
    }
}

void Theme::writeKwinSettings(bool change) {
    if (!QFile::exists(m_kwinFile)) {
        return;
    }

    if (!change) {
        kwinSettings->beginGroup("Plugins");
        kwinSettings->setValue("kwin4_effect_maximizeEnabled", false);
        kwinSettings->setValue("blurEnabled", false);
        kwinSettings->endGroup();

        for (int i = 0; i < effectList.length(); i++) {
            QDBusMessage message = QDBusMessage::createMethodCall(!mIsOpenkylin ? "org.ukui.KWin" : "org.kde.KWin",
                                                       "/Effects",
                                                       !mIsOpenkylin ? "org.ukui.kwin.Effects" : "org.kde.kwin.Effects",
                                                       "unloadEffect");
            message << effectList.at(i);
            QDBusConnection::sessionBus().send(message);
        }
    } else {
        kwinSettings->beginGroup("Plugins");
        kwinSettings->setValue("kwin4_effect_maximizeEnabled", true);
        kwinSettings->setValue("blurEnabled", true);
        kwinSettings->endGroup();
        for (int i = 0; i < effectList.length(); i++) {

            QDBusMessage message = QDBusMessage::createMethodCall(!mIsOpenkylin ? "org.ukui.KWin" : "org.kde.KWin",
                                                                  "/Effects",
                                                                  !mIsOpenkylin ? "org.ukui.kwin.Effects" : "org.kde.kwin.Effects",
                                                                  "loadEffect");
            message << effectList.at(i);
            QDBusConnection::sessionBus().send(message);
        }
    }
    kwinSettings->sync();
}

void Theme::themeBtnClickSlot(QAbstractButton *button) {
    // 设置主题
    QString themeMode = button->property("value").toString();
    QString currentThemeMode = qtSettings->get(MODE_QT_KEY).toString();
    QString tmpMode;
    UkccCommon::buriedSettings(name(), "set theme mode", QString("settings"), themeMode);

    if (QString::compare(currentThemeMode, themeMode)) {
        if ("ukui-dark" == themeMode) {
            tmpMode = "ukui-black";
            revokeGlobalThemeSlot("getDefaultLightDarkMode", "dark");
            revokeGlobalThemeSlot("getQtDarkThemeName", themeMode);
            revokeGlobalThemeSlot("getGtkDarkThemeName", tmpMode);
            mAutoSettings->set(COLOR_KEY_AUTO_THEME, false);
        } else if ("ukui-light" == themeMode) {
            tmpMode = "ukui-white";
            revokeGlobalThemeSlot("getDefaultLightDarkMode", "light");
            revokeGlobalThemeSlot("getQtLightThemeName", themeMode);
            revokeGlobalThemeSlot("getGtkLightThemeName", tmpMode);
            mAutoSettings->set(COLOR_KEY_AUTO_THEME, false);
        } else if ("ukui-default" == themeMode) {
            revokeGlobalThemeSlot("getDefaultLightDarkMode", "light");
            revokeGlobalThemeSlot("getQtLightThemeName", themeMode);
            revokeGlobalThemeSlot("getGtkLightThemeName", tmpMode);
            mAutoSettings->set(COLOR_KEY_AUTO_THEME, false);
        } else if (themeMode == "ukui-auto" && button->isChecked()) {
            clickedCustomTheme();
            mAutoSettings->set(COLOR_KEY_AUTO_THEME, true);
            return;
        }
        gtkSettings->set(MODE_GTK_KEY, tmpMode);
        qtSettings->set(MODE_QT_KEY, themeMode);
    }
}

void Theme::changeGlobalThemeSlot(QAbstractButton *button)
{
    QVariant value = button->property("value");
    GlobalTheme *theme = nullptr;
    for (GlobalTheme *globaltheme: mGlobalthemehelper->getAllGlobalThemes()) {
        if (globaltheme->getThemeName() == value)
            theme = globaltheme;
    }
    if (!theme) return;
    UkccCommon::buriedSettings(name(), "set theme", QString("settings"), value.toString());

    if (mPrePicUnit != nullptr) mPrePicUnit->setBtnClicked(false);

    mPrePicUnit = static_cast<ThemeButton *>(button);

    bool supportBlur  = mEffectWidget->isVisible();
    bool blurEnable   = theme->getBlurEnabled();

    bool supportTranspancy = mTranWidget->isVisible();
    int transparency = theme->getTransparencyBlur();
    int radiusValue = theme->getRadiusValue();

    QString globalName = theme->getThemeName();
    QString wallpaper  = theme->getWallPaperPath();
    QString iconName   = theme->getIconThemeName();
    QString cursorName = theme->getCursorThemeName();
    QString widgetName = theme->getWidgetStyleName();
    QString colorTheme = theme->getDefaultLightDarkMode();
    QString accentColor= theme->getQtAccentRole();
    QString gtkColorTheme;

    if (!colorTheme.compare("light")) {
        colorTheme = theme->getQtLightThemeName();
        gtkColorTheme = theme->getGtkLightThemeName();
    } else if (!colorTheme.compare("dark")) {
        colorTheme = theme->getQtDarkThemeName();
        gtkColorTheme = theme->getGtkDarkThemeName();
    } else if (!colorTheme.compare("mixed")) {
        colorTheme = theme->getQtMixedThemeName();
        gtkColorTheme = theme->getGtkLightThemeName();
    }

    mMateBgSettings->set(BG_FILE_KEY, wallpaper);

    mGlobalSettings->set(GLOBAL_NAME_KEY, globalName);
    mGlobalSettings->set(ISMODIFY_KEY, false);

    qtSettings->set(ICON_QT_KEY, iconName);
    qtSettings->set(WIDGET_QT_KEY, widgetName);
    qtSettings->set(MODE_QT_KEY, colorTheme);
    qtSettings->set(COLOR_QT_KEY, accentColor);

    gtkSettings->set(ICON_GTK_KEY, iconName);
    gtkSettings->set(MODE_GTK_KEY, gtkColorTheme);

    curSettings->set(CURSOR_THEME_KEY, cursorName);

    if (mAutoSettings && value != "custom")  {
        mAutoSettings->set(COLOR_KEY_AUTO_THEME, false);
    }

#ifndef OPENKYLIN
    curSettings->set(CURSOR_THEME_KEY, cursorName);
#endif

#ifdef Nile
    qtSettings->set(WINDOW_RAIDUS, radiusValue);
#endif

    if (supportBlur) {
        changeEffectBtnSlot(blurEnable);
    }

    if (supportTranspancy) {
        changeTranpancySliderSlot(transparency);
    }
}

void Theme::revokeGlobalThemeSlot(const QString &funcName, const QString &value)
{
    if (mGlobalSettings == nullptr) {
        return;
    }

    if (mGlobalSettings) {
        mGlobalSettings->set(ISMODIFY_KEY, true);
        mGlobalSettings->set(GLOBAL_NAME_KEY, "custom");
    }

    clickedCustomTheme();

    mGlobalthemehelper->updateCustomThemeSetting(funcName, value);
}

void Theme::changeGlobalDirSlot()
{
    GlobalThemeHelper *globalHelper = GlobalThemeHelper::getInstance();
    QMap<QString, GlobalTheme*> actGlobal;
    const QStringList &mapKeys = mGlobalMap.keys();
    for (GlobalTheme *theme: globalHelper->getAllGlobalThemes()) {
        globalHelper->loadThumbnail(theme);
        actGlobal.insert(theme->getLocaleThemeName(), theme);
    }

    QTimer::singleShot(500, this, [=]{
        if (actGlobal.keys().length() > mapKeys.length()) {
            for (QString themeName : actGlobal.keys()) {
                if (!mapKeys.contains(themeName)) {
                    ThemeButton *btn = new ThemeButton(themeName, actGlobal[themeName]->getThumbnail(), mSwitchFrame);
                    QString property = actGlobal[themeName]->getThemeName();
                    btn->setProperty("value", property);
                    btn->setRect(QSize(200, 164));
                    mThemeBtnGroup->addButton(btn);
                    mFLyt->addWidget(btn);
                    mGlobalMap.insert(themeName, btn);
                }
            }
        } else {
            for (QString themeName : mapKeys) {
                if (!actGlobal.keys().contains(themeName)) {
                    ThemeButton *gloablBtn = mGlobalMap[themeName];
                    if (gloablBtn->property("value") == getGlobalName()) {
                        mCustomPicUnit->setBtnClicked(true);
                        mThemeBtnGroup->buttonClicked(mCustomPicUnit);
                    }
                    mThemeBtnGroup->removeButton(gloablBtn);
                    mGlobalMap.remove(themeName);
                    delete gloablBtn;
                }
            }
        }
    });
}

void Theme::changeEffectSlot(bool checked)
{
    if (!checked) {
        save_trans = static_cast<int>(personliseGsettings->get(PERSONALSIE_TRAN_KEY).toDouble() * 100.0);
        personliseGsettings->set(PERSONALSIE_SAVE_TRAN_KEY, save_trans);
        personliseGsettings->set(PERSONALSIE_TRAN_KEY, 1.0);
        qtSettings->set(THEME_TRAN_KEY, 100);
        qtSettings->set(PEONY_TRAN_KEY, 100);
        changeTranpancySliderSlot(100);

        QTimer::singleShot(100, this, [=] {
            writeKwinSettings(checked);
        });
    } else {
        save_trans = personliseGsettings->get(PERSONALSIE_SAVE_TRAN_KEY).toInt();
        changeTranpancySliderSlot(save_trans);
        writeKwinSettings(checked);
    }
    // 提供给外部监听特效接口
    setEffectStatus(checked);
    mTranWidget->setVisible(checked && !UkccCommon::isTablet());
    mCornerWidget->setVisible(checked && !UkccCommon::isTablet());
}

void Theme::changeEffectBtnSlot(bool checked)
{
    mEffectWidget->blockSignals(true);
    mEffectWidget->setChecked(checked);
    mEffectWidget->blockSignals(false);
    changeEffectSlot(checked);
}

void Theme::changeTranpancySlot(int value)
{
    personliseGsettings->set(PERSONALSIE_TRAN_KEY,(static_cast<int>(value) / 100.0));
    qtSettings->set(THEME_TRAN_KEY, value);
    qtSettings->set(PEONY_TRAN_KEY, value);
}

void Theme::changeTranpancySliderSlot(int value)
{
    mTranWidget->slider()->blockSignals(true);
    mTranWidget->slider()->setValue(value);
    mTranWidget->slider()->blockSignals(false);
    changeTranpancySlot(value);
}

void Theme::jumpFunctionSlot(const QString &arg)
{
    QProcess::startDetached("ukui-control-center", QStringList() << "-m" << arg);
}

void Theme::iconThemeBtnClickSlot(QAbstractButton *button)
{
    // 设置图标主题
    QVariant valueVariant = button->property("value");
    UkccCommon::buriedSettings(name(), "set icon theme", QString("settings"), valueVariant.toString());
    qtSettings->set(ICON_QT_KEY, valueVariant);
    gtkSettings->set(ICON_GTK_KEY, valueVariant);

    revokeGlobalThemeSlot("getIconThemeName", valueVariant.toString());
}

void Theme::cursorThemeBtnClickSlot(QAbstractButton *button)
{
    // 设置光标主题
    QVariant valueVariant = button->property("value");
    UkccCommon::buriedSettings(name(), "set cursor theme", QString("settings"), valueVariant.toString());
    curSettings->set(CURSOR_THEME_KEY, valueVariant);
    kwinCursorSlot(valueVariant.toString());
    revokeGlobalThemeSlot("getCursorThemeName", valueVariant.toString());
}

void Theme::updateAccentColorSlot(const QString &color)
{
    for (QRadioButton *btn : mRadioBtnList) {
        if (btn->property("key") == color) {
            btn->blockSignals(true);
            btn->setChecked(true);
            btn->blockSignals(false);
        }
    }
}

void Theme::setCustomGlobalSlot(const QString &key)
{
    QString value = mGlobalSettings->get(key).toString();

    if (mCustomPicUnit != nullptr && value == "custom") {
        clickedCustomTheme();
    }
}

void Theme::setRadiusSlot(int radius)
{
    if (qtSettings->keys().contains("windowRadius")) {
        qtSettings->set(WINDOW_RAIDUS, radius);
    }
}

double Theme::convertToTran(const int value) {
    switch (value) {
    case 1:
        return 0.2;
        break;
    case 2:
        return 0.4;
        break;
    case 3:
        return 0.6;
        break;
    case 4:
        return 0.8;
        break;
    case 5:
        return 1.0;
        break;
    default:
        return 1.0;
        break;
    }
}

int Theme::tranConvertToSlider(const double value) {
    if (0.2 ==  value) {
        return 1;
    } else if (0.4 ==  value) {
        return 2;
    } else if (0.6 ==  value) {
        return 3;
    } else if (0.8 ==  value) {
        return 4;
    } else if (1.0 ==  value) {
        return 5;
    } else {
        return 5;
    }
}
