/*
 * Copyright (C) 2018 Tianjin KYLIN Information Technology 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 "lockwidget.h"

#include "powermanager.h"
#include "ui_lockwidget.h"
#include <QDir>
#include <QDateTime>
#include <QTimer>
#include <QDebug>
#include <QBitmap>
#include <QPluginLoader>
#include <QPainterPath>
#include <QtConcurrent/QtConcurrentRun>
#include <QScrollArea>
#include <QScrollBar>
#include <QMenu>
#include <QWidgetAction>
#include <imageutil.h>
#include <QtX11Extras/QX11Info>
#include <kylin-nm/kynetworkicon.h>
#include <QGSettings>
#include "authdialog.h"
#include "virtualkeyboardwidget.h"
#include "configuration.h"
#include "users.h"
#include "displaymanager.h"
#include "config.h"
#include "commonfunc.h"
#include "hoverwidget.h"
#include "kylinnm.h"
#include "mytabwidget.h"
#include "klabel.h"
#include "rootWindowBackground.h"
#include "configuration.h"

#include <QtX11Extras/QX11Info>
#include <X11/Xlib.h>
#include <X11/XKBlib.h>

#define GSETTINGS_SCHEMA_MATE_BG "org.mate.background"
#define KEY_PICTURE_FILENAME "pictureFilename"
#define KEY_PICTURE_OPTIONS "pictureOptions"
#define KEY_PRIMARY_COLOR "primaryColor"
#define TIME_TYPE_SCHEMA "org.ukui.control-center.panel.plugins"
#define CONFIG_FILE "/etc/lightdm/ukui-greeter.conf"
#define ON_TAB_SHEET "QPushButton{background-color: rgba(255,255,255,15%); border-radius: 4px; border: 2px solid #2C73C8;}"
#define ON_NORMAL_SHEET "QPushButton{text-align:center;color: rgba(255, 255, 255, 255);border: none;border-radius: 4px;outline: none;} \
                        QPushButton::hover{background-color: rgba(255,255,255,15%);} \
                        QPushButton::pressed {background-color: rgba(255,255,255,40%);}\
                        QPushButton::checked {background-color: rgba(255, 255, 255, 40%);}"
float scale;
LockWidget::LockWidget(QWidget *parent)
    : QWidget(parent),
      ui(new Ui::LockWidget),
      usersMenu(nullptr),
      scrollArea(nullptr),
      configuration(Configuration::instance()),
      users(new Users(this)),
      displayManager(new DisplayManager(this)),
      timeType(24),
      m_kylinNM(nullptr)
{
    scale = 1.0;
    ui->setupUi(this);
   // m_kylinNM->installEventFilter(this);

    if(users->getUsers().count() < 2){
        ui->btnSwitchUser->hide();
    }
    UserItem user = users->getUserByName(getenv("USER"));
    authDialog = new AuthDialog(user, this);
    authDialog->installEventFilter(this);
    connect(authDialog, &AuthDialog::authenticateCompete,
            this, &LockWidget::onAuthenticateCompete);
    connect(authDialog,&AuthDialog::clickPassword,
            this,&LockWidget::onClickPassword);
    connect(authDialog,&AuthDialog::loginOptionClicked,
            this,&LockWidget::resetNavigation);
    connect(authDialog,&AuthDialog::showMessageBtn,
            this,&LockWidget::onShowMessageBtn);
//    connect(this, &LockWidget::capsLockChanged,
//            authDialog, &AuthDialog::onCapsLockChanged);

//    connect(m_kylinNM, &KylinNM::onConnectChanged, this,[=](){
//        updateNetIcon(m_kylinNM->getConnectStatus());
//    });
    curFontSize = configuration->getFontSize();
    this->installEventFilter(this);
    initUI();

    if(users->getUsers().count() < 2){
        is_switchBtn = false;
        ui->btnSwitchUser->hide();
    }

    if(horAT != KEYBOARDBTN) {
        if(is_batteryBtn)
            horAT = BATTERYBTN;
        else if(!is_batteryBtn && is_switchBtn)
            horAT = SWITCHBTN;
        else
            horAT = NETWORKBTN;
    }
}

LockWidget::~LockWidget()
{
    delete ui;
}

void LockWidget::closeEvent(QCloseEvent *event)
{
    qDebug() << "LockWidget::closeEvent";
    authDialog->close();

    return QWidget::closeEvent(event);
}

bool LockWidget::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == 2){
        if(obj == mkylinNM)
            return true;

        if(vKeyboard && obj == vKeyboard)
            return true;

        if (vKeyboard && obj != vKeyboard && obj != ui->btnKeyboard && obj != btnNetworkManager  && obj != ui->btnPowerManager && vKeyboard->isVisible()) {
            hideBottomPlugins();
        }

        if(obj == ui->btnPowerManager || obj == ui->btnSwitchUser || obj == btnNetworkManager || obj == ui->btnBatteryStatus || obj == ui->btnKeyboard) {
            authDialog->setFocusin(REMOVE);
            return false;
        }

        if(tabAt != LINEEDIT) {
            authDialog->setFocusin(REMOVE);
            if(tabAt == BOTTMBTN) {
                tabAt = LINEEDIT;
                setBottomBtnSheet();
                tabAt = BOTTMBTN;
            }
        }

        if(mBatteryWidget && mBatteryWidget->isVisible()) {
            setCheckedSheet(BATTERYBTN, false);
            at_plugins = false;
        }

        if(scrollArea && scrollArea->isVisible()) {
            setCheckedSheet(SWITCHBTN,false);
            at_plugins = false;
        }

        if(vKeyboard && vKeyboard->isVisible()) {
            vKeyboard->hide();
            at_plugins = false;
        }

        if(m_kylinNM && m_kylinNM->isVisible()) {
            setCheckedSheet(NETWORKBTN, false);
            at_plugins = false;
        }

        if(powermanager && powermanager->isVisible()){
            showPowerManager();
        }
    }

    if (obj == scrollContents ){
        if (event->type() == 76 ) {
            usersMenu->show();
            //qDebug()<<"````````````````````````````````````````````"<<event->type();
        }
    }
/*
    if(event->type() == QEvent::WindowActivate){
        if(!isNetFinished){
            isNetFinished = true;
            QTimer::singleShot(1000, this, [=](){
                  loadNetPlugin();
//                m_kylinNM = new KylinNM(this);
//                m_kylinNM->installEventFilter(this);
//                connect(m_kylinNM, &KylinNM::onConnectChanged, this,[=](){
//                    updateNetIcon(m_kylinNM->getConnectStatus());
//                });
//                m_kylinNM->hide();
//                QtConcurrent::run([=](){
//                    updateNetIcon(getNetStatus());
//                });
            });
        }
    }
*/
    return false;
}

void LockWidget::setStartupMode(bool mode)
{
    m_isStartupMode = mode;
    if (powermanager) {
        powermanager->setStartupMode(m_isStartupMode);
    }
    if (m_isStartupMode) {
        m_futureLoadDeskBg = QtConcurrent::run([=](){
            setRootWindow();
        });
    }
}

void LockWidget::key_enter_release(int key)
{
    if (tabAt == BOTTMBTN) {
        switch (horAT) {
        case BATTERYBTN:
            showBattery();
            ui->btnBatteryStatus->setStyleSheet(ON_NORMAL_SHEET);
            break;
        case SWITCHBTN:
            if(scrollArea && scrollArea->isVisible()) {
                if(authDialog)
                {
                    if(list.at(nowAt)->objectName() != getenv("USER"))
                        authDialog->stopAuth();
                }
                if(list.at(nowAt)->objectName() == "Guest")
                {
                    displayManager->switchToGuest();
                }
                else if(list.at(nowAt)->objectName() == "SwitchUser")
                {
                    displayManager->switchToGreeter();
                }
                else
                {
                    if(list.at(nowAt)->objectName() != getenv("USER"))
                        displayManager->switchToUser(list.at(nowAt)->objectName());
                }
            } else {
                ui->btnSwitchUser->setStyleSheet(ON_NORMAL_SHEET);
                showUserMenu();
            }
            break;
        case NETWORKBTN:
            if(!m_kylinNM || !(m_kylinNM && m_kylinNM->isVisible()))
                showNetManager(true);
            btnNetworkManager->setStyleSheet(ON_NORMAL_SHEET);
            authDialog->setFocusin(REMOVE);
            break;
        case KEYBOARDBTN:
            if(!vKeyboard || !(vKeyboard && vKeyboard->isVisible()))
                showVirtualKeyboard();
            ui->btnSwitchUser->setStyleSheet(ON_NORMAL_SHEET);
            break;
        case POWERBTN:
            showPowerManager(true);
            break;
        default:
            break;
        }
    } else if (tabAt == BIOBTN) {
        authDialog->setClick();
    } else if (tabAt == ENTERBTN) {
        authDialog->checkPassword();
        tabAt = LINEEDIT;
    } else if (tabAt == POWERMANAGER) {
        powermanager->keyBdRelease(key);
    }
}

void LockWidget::key_tab_release(int key)
{
    if(key == Qt::Key_Tab) {
        if (at_plugins) {
            authDialog->setFocusin(REMOVE);
            return;
        }
        switch (tabAt) {
        case LINEEDIT:
            authDialog->setFocusin(IN_LIGIN);
            tabAt = ENTERBTN;
            break;
        case MESSAGEBTN :
            tabAt = BOTTMBTN;
            authDialog->setFocusin(REMOVE);
            if(is_batteryBtn) {
                horAT = BATTERYBTN;
                setBottomBtnSheet();
            } else if(users->getUsers().count() > 1){
                horAT = SWITCHBTN;
                setBottomBtnSheet();
            } else {
                horAT =NETWORKBTN;
                setBottomBtnSheet();
            }
            break;
        case ENTERBTN:
            if(authDialog->getBioNum() >1) {
                authDialog->setFocusin(BIO_RIGHT);
                tabAt = BIOBTN;
            } else {
                tabAt = BOTTMBTN;
                authDialog->setFocusin(REMOVE);
                if(is_batteryBtn){
                    horAT = BATTERYBTN;
                } else if(users->getUsers().count() > 1){
                    horAT = SWITCHBTN;
                } else {
                    horAT =NETWORKBTN;
                }
                setBottomBtnSheet();
            }
            break;
        case BIOBTN:
            tabAt = BOTTMBTN;
            authDialog->setFocusin(REMOVE);
            if(is_batteryBtn) {
                horAT = BATTERYBTN;
                setBottomBtnSheet();
            } else if(users->getUsers().count() > 1){
                horAT = SWITCHBTN;
                setBottomBtnSheet();
            } else {
                horAT =NETWORKBTN;
                setBottomBtnSheet();
            }
            break;
        case BOTTMBTN:
            if(!at_power) {
                if(!authDialog->getLineeditStatus()) {
                    authDialog->setFocusin(IN_LINEEDIT);
                    tabAt = LINEEDIT;
                } else {
                    authDialog->setFocusin(ON_MESSAGEBTN);
                    tabAt = MESSAGEBTN;
                }
                setBottomBtnSheet();
            } else if (at_power) {
                powermanager->keyBdRelease(Qt::Key_Right);
                tabAt = POWERMANAGER;
                setBottomBtnSheet();
            }
            break;
        case POWERMANAGER:
            powermanager->clearStatus();
            tabAt = BOTTMBTN;
            if(is_batteryBtn) {
                horAT = BATTERYBTN;
                setBottomBtnSheet();
            } else if(users->getUsers().count() > 1){
                horAT = SWITCHBTN;
                setBottomBtnSheet();
            } else {
                horAT =NETWORKBTN;
                setBottomBtnSheet();
            }
            break;
        case EMPTY:
            authDialog->setFocusin(IN_LINEEDIT);
            tabAt = LINEEDIT;
            setBottomBtnSheet();
        }
    }
}

void LockWidget::key_shiftTab_release()
{
    if (at_plugins) {
        authDialog->setFocusin(REMOVE);
        return;
    }
    switch (tabAt) {
    case LINEEDIT:
        tabAt = BOTTMBTN;
        authDialog->setFocusin(REMOVE);
        if(is_batteryBtn)
            horAT = BATTERYBTN;
        else if(users->getUsers().count() > 1){
            horAT = SWITCHBTN;
        } else {
            horAT =NETWORKBTN;
        }
        setBottomBtnSheet();
        break;
    case MESSAGEBTN :
        tabAt = BOTTMBTN;
        authDialog->setFocusin(REMOVE);
        if(is_batteryBtn) {
            horAT = BATTERYBTN;
            setBottomBtnSheet();
        } else if(users->getUsers().count() > 1){
            horAT = SWITCHBTN;
            setBottomBtnSheet();
        } else {
            horAT =NETWORKBTN;
            setBottomBtnSheet();
        }
        break;
    case ENTERBTN:
        authDialog->setFocusin(IN_LINEEDIT);
        tabAt = LINEEDIT;
        setBottomBtnSheet();
        break;
    case BIOBTN:
        authDialog->setFocusin(IN_LIGIN);
        tabAt = ENTERBTN;
        break;
    case BOTTMBTN:
        if(!at_power) {
            if(!authDialog->getLineeditStatus()) {
                if(authDialog->getBioNum() >1) {
                    authDialog->setFocusin(BIO_RIGHT);
                    tabAt = BIOBTN;
                } else {
                    authDialog->setFocusin(IN_LIGIN);
                    tabAt = ENTERBTN;
                }
            } else {
                authDialog->setFocusin(ON_MESSAGEBTN);
                tabAt = MESSAGEBTN;
            }
            setBottomBtnSheet();
        } else {
            powermanager->keyBdRelease(Qt::Key_Right);
            tabAt = POWERMANAGER;
        }
        setBottomBtnSheet();
        break;
    case POWERMANAGER:
        powermanager->clearStatus();
        tabAt = BOTTMBTN;
        if(is_batteryBtn) {
            horAT = BATTERYBTN;
            setBottomBtnSheet();
        } else if(users->getUsers().count() > 1){
            horAT = SWITCHBTN;
            setBottomBtnSheet();
        } else {
            horAT =NETWORKBTN;
            setBottomBtnSheet();
        }
        break;
    case EMPTY:
        authDialog->setFocusin(IN_LINEEDIT);
        tabAt = LINEEDIT;
        setBottomBtnSheet();
    }
}

void LockWidget::key_LR_release(int key)
{
    if(key == Qt::Key_Right) {
        if(tabAt == BOTTMBTN) {
            if (at_plugins)
                return;
            switch (horAT) {
            case BATTERYBTN:
                if(is_switchBtn)
                    horAT = SWITCHBTN;
                else
                    horAT = NETWORKBTN;
                break;
            case SWITCHBTN:
                horAT = NETWORKBTN;
                break;
            case NETWORKBTN:
                if (ui->btnKeyboard->isHidden()) {
                    horAT = POWERBTN;
                } else {
                    horAT = KEYBOARDBTN;
                }
                break;
            case KEYBOARDBTN:
                horAT = POWERBTN;
                break;
            case POWERBTN:
                if(is_batteryBtn)
                    horAT = BATTERYBTN;
                else if(is_switchBtn)
                    horAT = SWITCHBTN;
                else
                    horAT = NETWORKBTN;
                break;
            default:
                break;
            }
            setBottomBtnSheet();
        } else if (tabAt == BIOBTN) {
            authDialog->setFocusin(BIO_RIGHT);
        } else if (tabAt == POWERMANAGER) {
            powermanager->keyBdRelease(Qt::Key_Right);
        }
    } else if (key == Qt::Key_Left) {
        if(tabAt == BOTTMBTN) {
            if (at_plugins)
                return;
            switch (horAT) {
            case BATTERYBTN:
                horAT = POWERBTN;
                break;
            case SWITCHBTN:
                if(is_batteryBtn)
                    horAT = BATTERYBTN;
                else
                    horAT = POWERBTN;
                break;
            case NETWORKBTN:
                if(is_switchBtn)
                    horAT = SWITCHBTN;
                else if(is_batteryBtn)
                    horAT = BATTERYBTN;
                else
                    horAT = POWERBTN;;
                break;
            case KEYBOARDBTN:
                horAT = NETWORKBTN;
                break;
            case POWERBTN:
                if (ui->btnKeyboard->isHidden()) {
                    horAT = NETWORKBTN;
                } else {
                    horAT = KEYBOARDBTN;
                }
                break;
            default:
                break;
            }
            setBottomBtnSheet();
        } else if (tabAt == BIOBTN) {
            authDialog->setFocusin(BIO_LEFT);
        } else if (tabAt == POWERMANAGER) {
            powermanager->keyBdRelease(Qt::Key_Left);
        }
    }
}

void LockWidget::setBottomBtnSheet()
{
    if (tabAt == BOTTMBTN) {
        switch (horAT) {
        case BATTERYBTN:
            ui->btnBatteryStatus->setStyleSheet(ON_TAB_SHEET);
            ui->btnSwitchUser->setStyleSheet(ON_NORMAL_SHEET);
            btnNetworkManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnKeyboard->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnPowerManager->setStyleSheet(ON_NORMAL_SHEET);
            break;
        case SWITCHBTN:
            ui->btnSwitchUser->setStyleSheet(ON_TAB_SHEET);
            btnNetworkManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnKeyboard->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnPowerManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnBatteryStatus->setStyleSheet(ON_NORMAL_SHEET);
            break;
        case NETWORKBTN:
            btnNetworkManager->setStyleSheet(ON_TAB_SHEET);
            ui->btnKeyboard->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnPowerManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnSwitchUser->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnBatteryStatus->setStyleSheet(ON_NORMAL_SHEET);
            break;
        case KEYBOARDBTN:
            ui->btnKeyboard->setStyleSheet(ON_TAB_SHEET);
            ui->btnPowerManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnSwitchUser->setStyleSheet(ON_NORMAL_SHEET);
            btnNetworkManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnBatteryStatus->setStyleSheet(ON_NORMAL_SHEET);
            break;
        case POWERBTN:
            ui->btnPowerManager->setStyleSheet(ON_TAB_SHEET);
            ui->btnSwitchUser->setStyleSheet(ON_NORMAL_SHEET);
            btnNetworkManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnKeyboard->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnBatteryStatus->setStyleSheet(ON_NORMAL_SHEET);
            break;
        default:
            ui->btnSwitchUser->setStyleSheet(ON_NORMAL_SHEET);
            btnNetworkManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnKeyboard->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnPowerManager->setStyleSheet(ON_NORMAL_SHEET);
            ui->btnBatteryStatus->setStyleSheet(ON_NORMAL_SHEET);
            break;
        }
    } else {
        ui->btnSwitchUser->setStyleSheet(ON_NORMAL_SHEET);
        btnNetworkManager->setStyleSheet(ON_NORMAL_SHEET);
        ui->btnKeyboard->setStyleSheet(ON_NORMAL_SHEET);
        ui->btnPowerManager->setStyleSheet(ON_NORMAL_SHEET);
        ui->btnBatteryStatus->setStyleSheet(ON_NORMAL_SHEET);
    }
}

void LockWidget::key_OB_release(int key)
{
    QString focus = "focus";
    QString normal = "normal";
    if(key == Qt::Key_Up){ // "Up"
        for(int i = 0; i < list.count(); i++){
            if(nowAt == i){
                if(i == 0)
                    return ;
                list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                list.at(i-1)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                          "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                nowAt = i-1;

                /*else if(i == 0){
                    list.last()->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                              "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                    nowAt = list.count() -1;
                }*/
            }
        }
    } else if(key == Qt::Key_Down) { // "Down"
        for(int i = list.count(); i >= 0; i--){
            if(nowAt == i){
                if(i == list.count() - 1)
                    return ;
                list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                list.at(i+1)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                          "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                nowAt = i+1;
                /*else if(i == list.count() - 1){
                    list.first()->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                              "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
                    nowAt = 0;
                }*/
            }
        }
    }
}

void LockWidget::resetNavigation()
{
    tabAt = LINEEDIT;
    setBottomBtnSheet();
    authDialog->setFocusin(IN_LINEEDIT);
}

void LockWidget::startAuth()
{
    if(authDialog)
    {
        authDialog->startAuth();
        if (isTableMode && !(vKeyboard && vKeyboard->isVisible())) {
            showVirtualKeyboard();
        }
    }
}

void LockWidget::stopAuth()
{
    if(authDialog)
    {
        authDialog->stopAuth();
    }
}

void LockWidget::setX11Focus()
{
    if(authDialog){
        //authDialog->setX11Focus();
    }
}

void LockWidget::initUI()
{
    setFocusProxy(authDialog);

    if(QGSettings::isSchemaInstalled(TIME_TYPE_SCHEMA)){
    	QGSettings *time_type = new QGSettings(TIME_TYPE_SCHEMA);
        QStringList keys = time_type->keys();
    	if (keys.contains("hoursystem")) {
        	timeType = time_type->get("hoursystem").toInt();
        }
        if (keys.contains("date")) {
            dateType = time_type->get("date").toString();
        }
    }

    //显示系统时间
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [&]{
        if(timeType == 12)
            ui->lblTime->setText(QDateTime::currentDateTime().toString("A hh:mm"));
        else
            ui->lblTime->setText(QDateTime::currentDateTime().toString("hh:mm"));

        if(dateType == "cn")
            ui->lblDate->setText(QDate::currentDate().toString("yyyy/MM/dd ddd").replace("周","星期"));
        else
            ui->lblDate->setText(QDate::currentDate().toString("yyyy-MM-dd ddd").replace("周","星期"));
    });

    if(timeType == 12)
    	ui->lblTime->setText(QDateTime::currentDateTime().toString("A hh:mm"));
    else
        ui->lblTime->setText(QDateTime::currentDateTime().toString("hh:mm"));

    ui->lblTime->setFontSize(36);
    ui->lblTime->setAlignment(Qt::AlignCenter);
    ui->lblTime->adjustSize();
    timer->start(1000);

//    QString date = QDate::currentDate().toString("yyyy/MM/dd ddd");
//    qDebug() << "current date: " << date;
//    ui->lblDate->setText(date);
    if(dateType == "cn")
        ui->lblDate->setText(QDate::currentDate().toString("yyyy/MM/dd ddd").replace("周","星期"));
    else
        ui->lblDate->setText(QDate::currentDate().toString("yyyy-MM-dd ddd").replace("周","星期"));

    ui->lblDate->setFontSize(18);
    ui->lblDate->setAlignment(Qt::AlignCenter);
    ui->lblDate->adjustSize();
    ui->widgetTime->adjustSize();

    //电池电量显示icon
    batInterface = new QDBusInterface(
        "org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.DBus.Properties", QDBusConnection::systemBus(), this);

    QString batteryPath = "";
    dface = new QDBusInterface(UPOWER_SERVICE, UPOWER_PATH, UPOWER_INTERFACE, QDBusConnection::systemBus(), this);
    QDBusReply<QList<QDBusObjectPath>> reply = dface->call("EnumerateDevices");
    if (dface->isValid()) {
        for (QDBusObjectPath op : reply.value()) {
            if (op.path().contains("battery_")) {
                batteryPath = op.path();
                qDebug() << "battery path is :" << batteryPath;
                break;
            }
        }
    } else {
        qDebug() << "Enumerate devices failed";
    }

    iface = new QDBusInterface(UPOWER_SERVICE, batteryPath, FREEDESKTOP_UPOWER, QDBusConnection::systemBus());
    if (dface->isValid()) {
        QDBusReply<QVariant> reply = batInterface->call("Get", "org.freedesktop.UPower", "LidIsPresent");
        if (reply.isValid()) {
            if (true == reply.value().toBool()) {
                setBatteryIcon(getBatteryIconName());
                QDBusConnection::systemBus().connect(
                    UPOWER_SERVICE, batteryPath, FREEDESKTOP_UPOWER, "PropertiesChanged", this, SLOT(dealMessage(QDBusMessage)));
                ui->btnBatteryStatus->setFixedSize(48,48);
                ui->btnBatteryStatus->setIconSize(QSize(24,24));
                ui->btnBatteryStatus->setFocusPolicy(Qt::NoFocus);
                ui->btnBatteryStatus->installEventFilter(this);
                ui->btnBatteryStatus->setCheckable(true);
                ui->btnBatteryStatus->raise();
                mBatteryWidget = new BatteryWidget(QPoint(ui->btnBatteryStatus->x(), ui->btnBatteryStatus->y()), this);
                mBatteryWidget->hide();
                connect(ui->btnBatteryStatus,&QPushButton::clicked
                    ,this,&LockWidget::showBattery);
            } else {
                ui->btnBatteryStatus->hide();
                is_batteryBtn = false;
            }
        } else {
            ui->btnBatteryStatus->hide();
            is_batteryBtn = false;
        }
    } else {
        ui->btnBatteryStatus->hide();
        is_batteryBtn = false;
    }

    //电源管理
    ui->btnPowerManager->setIcon(QIcon(":/image/assets/shutdown.svg"));
    ui->btnPowerManager->setFixedSize(48,48);
    ui->btnPowerManager->setIconSize(QSize(24,24));
    ui->btnPowerManager->setFocusPolicy(Qt::NoFocus);
    ui->btnPowerManager->installEventFilter(this);

    connect(ui->btnPowerManager,&QPushButton::clicked
        ,this,&LockWidget::showPowerManager);


//    QtConcurrent::run([=](){
//        updateNetIcon(getNetStatus());
//    });

    btnNetworkManager = new KyNetworkIcon(this); 
    btnNetworkManager->setStyleSheet("QPushButton{text-align:center;color: rgba(255, 255, 255, 255);border: none;border-radius: 4px;outline: none;} \
                                      QPushButton::hover{background-color: rgba(255,255,255,15%);} \
                                      QPushButton::pressed {background-color: rgba(255,255,255,40%);}\
                                      QPushButton::checked {background-color: rgba(255, 255, 255, 40%);}");
    btnNetworkManager->setCheckable(true);
    btnNetworkManager->setFixedSize(48,48);
    btnNetworkManager->setIconSize(QSize(24,24));
    btnNetworkManager->setFocusPolicy(Qt::NoFocus);
//    ui->btnNetworkManager->setStyleSheet("QPushButton:Hover{border-radius:24px;background-color:rgba(255, 255, 255, 0.15);}"
//                                       "QPushButton:Pressed{border-radius:24px;background-color:rgba(255, 255, 255, 0.05);}");
    btnNetworkManager->installEventFilter(this);
    btnNetworkManager->setCursor(Qt::PointingHandCursor);

    connect(btnNetworkManager,&QPushButton::clicked
            ,this, [&,this](){
        this->showNetManager();
        this->setCursor(Qt::ArrowCursor);
    });

    ui->btnKeyboard->setIcon(QIcon(":/image/assets/keyboard.svg"));
    ui->btnKeyboard->setFixedSize(48, 48);
    ui->btnKeyboard->setIconSize(QSize(24, 24));
    ui->btnKeyboard->setFocusPolicy(Qt::NoFocus);
    ui->btnKeyboard->installEventFilter(this);

    connect(ui->btnKeyboard, &QPushButton::clicked,
            this, &LockWidget::showVirtualKeyboard);

    //用户切换
    if(displayManager->canSwitch())
    {
        //initUserMenu();
        ui->btnSwitchUser->setIcon(QIcon(":/image/assets/switchuser.svg"));
        ui->btnSwitchUser->setIconSize(QSize(24, 24));
        ui->btnSwitchUser->setFixedSize(48, 48);
        ui->btnSwitchUser->setFocusPolicy(Qt::NoFocus);
        ui->btnSwitchUser->setCheckable(true);
        ui->btnSwitchUser->raise();

        connect(ui->btnSwitchUser, &QPushButton::clicked,
                this, &LockWidget::showUserMenu);
    }
    //监听物理键盘插拔
    libswitch = new LibinputSwitchEvent;
    isTableMode  = libswitch->geInitDevicesStatus();
    if(isTableMode && !(vKeyboard && vKeyboard->isVisible())) {
        showVirtualKeyboard();
    }
    connect(libswitch , &LibinputSwitchEvent::tabletModeStatusChanged, this, [ = ](int tablet_mode) {
        isTableMode = tablet_mode;
        qInfo()<<"TableMode:"<<isTableMode;
        if(isTableMode && tabAt == LINEEDIT && !(vKeyboard && vKeyboard->isVisible())) {
//            QTimer::singleShot(1000, this, [=]{
//                if (this->isTableMode) {
//                    showVirtualKeyboard();
//                    QTimer::singleShot(500, this, [&, this](){
//                        authDialog->setFocusin(IN_LINEEDIT);
//                    });
//                }
//            });
        } else if (!isTableMode && (tabAt == BOTTMBTN && horAT == KEYBOARDBTN) && (vKeyboard && vKeyboard->isVisible())) {
            QTimer::singleShot(100, this, [=]{
                if (!this->isTableMode) {
                    hideBottomPlugins();
                }
            });
        }
    });
}

void LockWidget::netInPutStatus()
{
    if(isTableMode && !(vKeyboard && vKeyboard->isVisible()))
        showVirtualKeyboard();
}

void LockWidget::showVirtualKeyboard()
{
    tabAt = LINEEDIT;
    setBottomBtnSheet();
    tabAt = BOTTMBTN;
    horAT = KEYBOARDBTN;
    if(!vKeyboard){
        vKeyboard = new VirtualKeyboardWidget(this);
        vKeyboard->installEventFilter(this);
        vKeyboard->hide();

        connect(vKeyboard, &VirtualKeyboardWidget::aboutToClose,
            this, &LockWidget::hideBottomPlugins);
        connect(vKeyboard, &VirtualKeyboardWidget::aboutToFloat,
                this, &LockWidget::netResetLocation);
    }

    vKeyboard->setVisible(vKeyboard->isHidden());

    if(!vKeyboard->isHidden()){
    	vKeyboard->raise();
        //authDialog->setFocusin(IN_LINEEDIT);
        at_plugins = true;
        if(m_kylinNM && m_kylinNM->isVisible() && !vKeyboard->getFloatStatus()) {
            m_kylinNM->move(this->width() - m_kylinNM->width() - 20,
                                        this->height() - m_kylinNM->height() - vKeyboard->height());
            m_kylinNM->raise();
        } else
            authDialog->setFocusin(IN_LINEEDIT);
        if(scrollArea && scrollArea->isVisible())
            setCheckedSheet(SWITCHBTN, false);
        if(mBatteryWidget && mBatteryWidget->isVisible())
            setCheckedSheet(BATTERYBTN, false);
    }
    vKeyboard->raise();
    //setVirkeyboardPos();
}

void LockWidget::netResetLocation()
{
    if (m_kylinNM && m_kylinNM->isVisible()) {
        if (vKeyboard->getFloatStatus()) {
            m_kylinNM->move(this->width() - m_kylinNM->width() - 20,
                                              this->height() - m_kylinNM->height() - 72 - 8) ;
        } else {
            m_kylinNM->move(this->width() - m_kylinNM->width() - 20,
                                        this->height() - m_kylinNM->height() - vKeyboard->height());
        }
        m_kylinNM->raise();
    }
    if (vKeyboard && vKeyboard->isVisible()) {
        vKeyboard->raise();
    }
}

void LockWidget::showUserMenu()
{
    if(!usersMenu){
        initUserMenu();
    }
    tabAt = LINEEDIT;
    setBottomBtnSheet();
    tabAt = BOTTMBTN;
    horAT = SWITCHBTN;

    if(scrollArea && scrollArea->isVisible()){
        setCheckedSheet(SWITCHBTN,false);
        at_plugins = false;
        authDialog->setFocusin(REMOVE);
    } else {
        setCheckedSheet(SWITCHBTN, true);
        at_plugins = true;
        authDialog->setFocusin(REMOVE);
        if(m_kylinNM && m_kylinNM->isVisible())
            setCheckedSheet(NETWORKBTN, false);
        if(mBatteryWidget && mBatteryWidget->isVisible())
            setCheckedSheet(BATTERYBTN, false);
         scrollArea->setFocus();
    }
}

void LockWidget::showPowerManager(bool keynavigation)
{
    if(!powermanager){
        powermanager = new PowerManager(getLoginedNum(), this);
        powermanager->setStartupMode(m_isStartupMode);
        sureWidget = new SureWindow(this);
        powermanager->hide();
        connect(powermanager,SIGNAL(lock())
                ,this,SLOT(showPowerManager()));
        connect(powermanager,SIGNAL(switchToUser())
                ,this,SLOT(switchToGreeter()));
        connect(powermanager, SIGNAL(showInhibitWarning(QVector<InhibitInfo::InhibitorInfo>&,int)),
                this,SLOT(showWarning(QVector<InhibitInfo::InhibitorInfo>&,int)));
        connect(powermanager, SIGNAL(mulUsersLogined(int)),
                this,SLOT(switchToSureDialog(int)));
        connect(powermanager, SIGNAL(clickedSuspend())
                , this,  SLOT(resetNavigation()));
        sureWidget->adjustSize();
        sureWidget->move((width()-sureWidget->geometry().width())/2, (height()-sureWidget->geometry().height())/2);
        sureWidget->hide();
        connect(sureWidget, SIGNAL(cantelButtonclicked()),
            this, SLOT(hideSureDialog()));
        connect(sureWidget, SIGNAL(confirmButtonclicked()),
            this, SLOT(confirmClicked()));
    }

    if(m_kylinNM && m_kylinNM->isVisible())
        setCheckedSheet(NETWORKBTN, false);
    if(scrollArea && scrollArea->isVisible())
        setCheckedSheet(SWITCHBTN,false);
    if(mBatteryWidget && mBatteryWidget->isVisible())
        setCheckedSheet(BATTERYBTN, false);
    if(sureWidget && sureWidget->isVisible())
        sureWidget->hide();
    if (!at_power && (vKeyboard && vKeyboard->isVisible())) {
        m_isShowKeyboard = true;
        hideBottomPlugins();
    } else if (!at_power && (vKeyboard && !vKeyboard->isVisible())) {
        m_isShowKeyboard = false;
    }
    if(powermanager->isVisible()){
        authDialog->show();
        powermanager->hide();
        if(!authDialog->getLineeditStatus()) {
            tabAt = LINEEDIT;
            authDialog->setFocusin(IN_LINEEDIT);
            if (m_isShowKeyboard && isTableMode && !(vKeyboard && vKeyboard->isVisible())) {
                showVirtualKeyboard();
            }
        } else {
            tabAt = MESSAGEBTN;
            authDialog->setFocusin(ON_MESSAGEBTN);
        }
        //setBottomBtnSheet();
        powermanager->clearStatus();
        at_power = false;
    }
    else{
        authDialog->hide();
        powermanager->show();
        if(keynavigation){
            powermanager->keyBdRelease(Qt::Key_Right);
            tabAt = POWERMANAGER;
            setBottomBtnSheet();
        } else {
            tabAt = LINEEDIT;
            setBottomBtnSheet();
            tabAt = BOTTMBTN;
            horAT = POWERBTN;
        }
        at_power = true;
#ifndef USE_INTEL
        powermanager->showNormalSize();
#endif
        powermanager->setGeometry((width()-powermanager->width())/2,
                                  (height()-powermanager->height())/2,
                                  powermanager->width(),powermanager->height());
    }
}

void LockWidget::setCheckedSheet(int type, bool show)
{
    switch (type) {
    case BATTERYBTN:
        if(show) {
            mBatteryWidget->show();
            ui->btnBatteryStatus->setChecked(true);
        } else {
            mBatteryWidget->hide();
            ui->btnBatteryStatus->setChecked(false);
        }
        break;
    case SWITCHBTN:
        if(show) {
            scrollArea->show();
            ui->btnSwitchUser->setChecked(true);
        } else {
            scrollArea->hide();
            ui->btnSwitchUser->setChecked(false);
        }
        break;
    case NETWORKBTN:
        if(show) {
            m_kylinNM->show();
            btnNetworkManager->setChecked(true);
        } else {
            m_kylinNM->hide();
            btnNetworkManager->setChecked(false);
        }
        break;
    default:
        break;
    }
}

void LockWidget::showWarning(QVector<InhibitInfo::InhibitorInfo> &wlist, int type)
{
    powermanagerType = type;
    if(m_kylinNM && m_kylinNM->isVisible())
        setCheckedSheet(NETWORKBTN, false);
    if(scrollArea && scrollArea->isVisible())
        setCheckedSheet(SWITCHBTN, false);

    authDialog->hide();
    powermanager->hide();
    sureWidget->show();
    sureWidget->setFocus();
    ui->widgetTime->hide();
    ui->btnPowerManager->hide();
    btnNetworkManager->hide();
    ui->btnSwitchUser->hide();
    ui->btnKeyboard->hide();
    ui->btnBatteryStatus->hide();

    sureWidget->setWarning(wlist, type);
}

void LockWidget::switchToSureDialog(int type)
{
    powermanagerType = type;
    if(m_kylinNM && m_kylinNM->isVisible())
        setCheckedSheet(NETWORKBTN, false);
    if(scrollArea && scrollArea->isVisible())
        setCheckedSheet(SWITCHBTN, false);

    authDialog->hide();
    powermanager->hide();
    sureWidget->show();
    sureWidget->setFocus();
    ui->widgetTime->hide();
    ui->btnPowerManager->hide();
    btnNetworkManager->hide();
    ui->btnSwitchUser->hide();
    ui->btnKeyboard->hide();
    ui->btnBatteryStatus->hide();

    sureWidget->setTips(tr("Multiple users are logged in at the same time.Are you sure you want to reboot this system?"));
}

void LockWidget::hideSureDialog()
{
    sureWidget->hide();
    powermanager->show();
    ui->widgetTime->show();
    ui->btnPowerManager->show();
    btnNetworkManager->show();
    ui->btnSwitchUser->show();
    ui->btnKeyboard->show();
    ui->btnBatteryStatus->show();
}

void LockWidget::confirmClicked()
{
    if(m_kylinNM && m_kylinNM->isVisible())
        setCheckedSheet(NETWORKBTN, false);
    if(scrollArea && scrollArea->isVisible())
        setCheckedSheet(SWITCHBTN, false);
    if(mBatteryWidget && mBatteryWidget->isVisible())
        setCheckedSheet(BATTERYBTN, false);
    sureWidget->hide();
    powermanager->hide();
    authDialog->show();
    ui->widgetTime->show();
    ui->btnPowerManager->show();
    btnNetworkManager->show();
    ui->btnSwitchUser->show();
    ui->btnKeyboard->show();
    ui->btnBatteryStatus->show();
    powermanager->doEvent(powermanagerType);
}

void LockWidget::showNetManager(bool keynavigation)
{
    if(!keynavigation) {
        tabAt = LINEEDIT;
        setBottomBtnSheet();
        tabAt = BOTTMBTN;
        horAT = NETWORKBTN;
    }
    if(!m_kylinNM){
	/*这里放在点击按钮后加载，一个原因是启动优化，另一个原因是如果放在构造函数中加载，则必须
	 * 先让网络窗口显示出来一次，否则会在锁屏程序退出时，锁屏窗口在closeEvent中崩溃，原因未知
	 * 同时，可以尽量降低在未操作网络时，网络程序对锁屏窗口的影响*/
	loadNetPlugin();
	m_kylinNM->hide();
    }

    if(m_kylinNM->isVisible())
    {
        setCheckedSheet(NETWORKBTN, false);
    } else {
        setCheckedSheet(NETWORKBTN, true);
        if(scrollArea && scrollArea->isVisible())
            setCheckedSheet(SWITCHBTN, false);
        if(mBatteryWidget && mBatteryWidget->isVisible())
            setCheckedSheet(BATTERYBTN, false);
        m_kylinNM->setGeometry(this->width() - m_kylinNM->width() - 20,
                               this->height() - m_kylinNM->height() - 72 - 8,
                               m_kylinNM->width(),
                               m_kylinNM->height());
        m_kylinNM->raise();
        if (vKeyboard && vKeyboard->isVisible()) {
            vKeyboard->raise();
        }
        m_kylinNM->setFocus();
        /*在150%缩放下，点击网络弹窗左上角有线连接部分，authDialog会收到点击事件导致网络弹窗隐藏，
         * 这里只调用m_kylinNM->raise()仍会有问题，需要再调用一次authDialog->lower()才行，原因未知*/
        if(authDialog && authDialog->isVisible()){
            authDialog->lower();
            authDialog->clearFocus();
        }

        if(mBatteryWidget && mBatteryWidget->isVisible()) {
            mBatteryWidget->lower();
            mBatteryWidget->clearFocus();
        }
        at_plugins = true;

        //m_kylinNM->updateWifiList();
    }
}

void LockWidget::onClickPassword()
{
    tabAt = LINEEDIT;
    if(is_switchBtn)
        horAT = SWITCHBTN;
    else
        horAT = NETWORKBTN;
    setBottomBtnSheet();
    authDialog->setFocusin(IN_LINEEDIT);

    if(m_kylinNM && m_kylinNM->isVisible()) {
        setCheckedSheet(NETWORKBTN, false);
        at_plugins = false;
    }

    if(scrollArea && scrollArea->isVisible()) {
        setCheckedSheet(SWITCHBTN, false);
        at_plugins = false;
    }
    if(isTableMode) {
        if(!(vKeyboard && vKeyboard->isVisible()))
            showVirtualKeyboard();
    }
//    if(vKeyboard && vKeyboard->isVisible()) {
//        vKeyboard->hide();
//        at_plugins = false;
//    }
}

void LockWidget::onShowMessageBtn(bool is_show)
{
    if(is_show) {
        tabAt = MESSAGEBTN;
        authDialog->setFocusin(ON_MESSAGEBTN);
    }
}

void LockWidget::showBattery()
{
    if(mBatteryWidget->isVisible()) {
        setCheckedSheet(BATTERYBTN, false);
        at_plugins = false;
    } else {
        setCheckedSheet(BATTERYBTN, true);
        at_plugins = true;
    }

    tabAt = LINEEDIT;
    setBottomBtnSheet();
    tabAt = BOTTMBTN;
    horAT = BATTERYBTN;
    if(scrollArea && scrollArea->isVisible()){
        setCheckedSheet(SWITCHBTN, false);
    } else if (m_kylinNM && m_kylinNM->isVisible()){
        setCheckedSheet(NETWORKBTN, false);
    }
}

void LockWidget::hideBottomPlugins()
{
    if(scrollArea && scrollArea->isVisible())
        setCheckedSheet(SWITCHBTN, false);

    if(vKeyboard && vKeyboard->isVisible()) {
        vKeyboard->hide();
        at_plugins = false;
    }
    if(m_kylinNM && m_kylinNM->isVisible()) {
        m_kylinNM->move(this->width() - m_kylinNM->width() - 20,
                                    this->height() - m_kylinNM->height()  - 72 - 8);
        tabAt = BOTTMBTN;
        horAT = NETWORKBTN;
        setCheckedSheet(NETWORKBTN, true);
        at_plugins = true;
        authDialog->setFocusin(REMOVE);
        return ;
    }
    //tabAt = EMPTY;
    if(!authDialog->getLineeditStatus())
        tabAt = LINEEDIT;
    setBottomBtnSheet();
}

void LockWidget::setBatteryIcon(QString str)
{
    QPixmap pixmap = QIcon::fromTheme(str).pixmap(QSize(24, 24));
    QImage img = pixmap.toImage();
    for (int x = 0; x < img.width(); x++) {
        for (int y = 0; y < img.height(); y++) {
            QColor color = img.pixelColor(x, y);
            color.setRed(255);
            color.setGreen(255);
            color.setBlue(255);
            img.setPixelColor(x, y, color);
        }
    }
    ui->btnBatteryStatus->setIcon(QPixmap::fromImage(img));
}

void LockWidget::dealMessage(QDBusMessage)
{
    setBatteryIcon(getBatteryIconName());
}

int LockWidget::getNetStatus()
{
    int ret = -1;
    QString actLanName = "--";
    QString actWifiName = "--";

    activecon *act = kylin_network_get_activecon_info();
    int index = 0;
    while (act[index].con_name != NULL) {
        if (QString(act[index].type) == "ethernet" || QString(act[index].type) == "802-3-ethernet") {
            actLanName = QString(act[index].con_name);
        }
        if (QString(act[index].type) == "wifi" || QString(act[index].type) == "802-11-wireless") {
            actWifiName = QString(act[index].con_name);
        }
        index ++;
    }

    // 设置图标
    if (actLanName != "--") {
        ret = 0;
    } else if (actWifiName != "--") {
        ret = 1;
    } else {
        ret = -1;
    }
    qDebug() << "[KylinNM] [getConnectStatus] getConnectStatus = " << ret;
    //KylinDBus::checkConnectivity();
    return ret;
}

void LockWidget::updateNetIcon(int status)
{
    switch(status) {
    case 0:
        //有线
        btnNetworkManager->setIcon(QIcon(":/image/assets/intel/icon-wired.png"));
        break;
    case 1:
        //无线
        btnNetworkManager->setIcon(QIcon(":/image/assets/intel/icon-wifi.png"));
        break;
    case 2:
        //有线+无线
        btnNetworkManager->setIcon(QIcon(":/image/assets/intel/icon-wired.png"));
        break;
    default:
        //无连接
        btnNetworkManager->setIcon(QIcon(":/image/assets/intel/icon-no-signal.png"));
    }
}

void LockWidget::loadNetPlugin()
{
    m_kylinNM = new QWidget(this);
    m_kylinNM->setFixedSize(420,480);
    m_kylinNM->setObjectName("m_kylinNM");
    m_kylinNM->setStyleSheet("#m_kylinNM{background-color: white; border-radius:12px;}");

    mkylinNM = new MyTabWidget(m_kylinNM);
    mkylinNM->setFixedSize(420,480);
    mkylinNM->tabBar()->setFixedHeight(40);
    mkylinNM->installEventFilter(this);

    QPluginLoader netloader("/usr/lib/kylin-nm/libnetconnect.so");//有线
    QPluginLoader wlanloader("/usr/lib/kylin-nm/libwlanconnect.so");//无线

    if (netloader.load()) {
        QObject * plugin = netloader.instance();

        if (plugin) {
            Interface * pluginInstance = qobject_cast<Interface *>(plugin);
            // 插件是否启用
            if (!pluginInstance) {
                return;
            }

            pluginInstance->setPluginType(SIMPLE);
            QWidget *widget = pluginInstance->pluginUi();
            mkylinNM->addTab(widget,"");

        } else {
                qDebug() <<  "Load Failed: " << netloader.errorString() << "\n";
                return;
        }
    } else {
        qDebug() <<  "Load Failed: " << netloader.errorString() << "\n";
        return;
    }

    if (wlanloader.load()) {
        QObject * plugin = wlanloader.instance();

        if (plugin) {
            Interface * pluginInstance = qobject_cast<Interface *>(plugin);
            // 插件是否启用
            if (!pluginInstance) {
                return;
            }

            pluginInstance->setPluginType(SIMPLE);
	    /*这里需要先调用setParentWidget，否则会出现网络连接弹窗无法弹出来的问题*/
            pluginInstance->setParentWidget(this);
            QWidget *widget = pluginInstance->pluginUi();
            mkylinNM->addTab(widget,"");

            //  平板模式输入状态下自动调出虚拟键盘
            connect(pluginInstance, SIGNAL(needShowVirtualKeyboard()), this, SLOT(netInPutStatus()));
        } else {
                qDebug() <<  "Load Failed: " << wlanloader.errorString() << "\n";
                return;
        }
    } else {
        qDebug() <<  "Load Failed: " << wlanloader.errorString() << "\n";
        return;
    }


    QHBoxLayout *m_tabBarLayout = new QHBoxLayout(mkylinNM);
    m_tabBarLayout->setContentsMargins(0,0,0,0);
    QLabel *m_lanLabel = new QLabel(tr("LAN"));
    m_lanLabel->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    QLabel *m_wlanLabel = new QLabel(tr("WLAN"));
    m_wlanLabel->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    m_tabBarLayout->addWidget(m_lanLabel);
    m_tabBarLayout->addWidget(m_wlanLabel);
    mkylinNM->tabBar()->setLayout(m_tabBarLayout);
    mkylinNM->tabBar()->setFixedWidth(420);
    QPalette pal = qApp->palette();
    pal.setBrush(QPalette::Background, Qt::white);
//    m_kylinNM->setPalette(pal);
    mkylinNM->widget(0)->setPalette(pal);
    mkylinNM->widget(1)->setPalette(pal);

    m_kylinNM->setGeometry(this->width() - mkylinNM->width() - 20,
                  this->height() - mkylinNM->height() - 72 - 8,
                  mkylinNM->width(),
                  mkylinNM->height());

}

void LockWidget::switchToGreeter()
{
    if(authDialog)
    {
        authDialog->stopAuth();
    }
    displayManager->switchToGreeter();;
}

void LockWidget::setVirkeyboardPos()
{
    if(vKeyboard)
    {
        vKeyboard->setGeometry(0,
                               height() - height()/3,
                               width(), height()/3);

    }
}


void LockWidget::initUserMenu()
{
    scrollArea = new QScrollArea(this);
    scrollArea->installEventFilter(this);
//    scrollArea->setAttribute(Qt::WA_TranslucentBackground); //设置背景透明
//    scrollArea->viewport()->setAttribute(Qt::WA_TranslucentBackground); //设置背景透明
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //屏蔽水平滚动条
    scrollArea->setStyleSheet("QScrollArea {background-color: rgba(255,255,255,15%);border-radius:8px;}");
    scrollArea->viewport()->setStyleSheet("background-color:transparent;");
    scrollArea->verticalScrollBar()->setProperty("drawScrollBarGroove", false);
    scrollArea->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
    scrollContents = new QWidget(scrollArea);
    scrollContents->installEventFilter(this);
    scrollArea->setWidget(scrollContents);
    scrollArea->hide();

    if(!usersMenu)
    {
        usersMenu = new QMenu(scrollContents);
        usersMenu->setObjectName("usersMenu");
        usersMenu->setToolTipsVisible(true);
        usersMenu->setStyleSheet("QMenu{background-color: rgb(255,255,255,15%);color: white;border-radius: 8px;width:250px;padding: 5px 5px 5px 5px;} \
                                  QMenu::icon{padding: 2px 5px 2px 5px;}\
                                  QMenu::item{width:225px;border-radius: 4px;height:36px;padding: 2px 10px 2px 10px;} \
                                  QMenu::item:selected {border-radius: 4px;background-color:rgb(255,255,255,40%);} \
                                  QMenu::item:pressed {border-radius: 4px;background-color: rgb(255,255,255,40%);}");

//        usersMenu->setStyleSheet("QMenu{background-color:transparent;color:white;padding:5px 5px 5px 8px}");
                                 //QToolTip{border-radius:4px;background-color:rgb(255,255,255,40%);color:white;}
	//如果没有设置x11属性，则由于弹出菜单受窗口管理器管理，而主窗口不受，在点击菜单又点回主窗口会闪屏。
        usersMenu->setWindowFlags(Qt::X11BypassWindowManagerHint);
        //usersMenu->hide();
        connect(usersMenu, &QMenu::triggered,
                this, &LockWidget::onUserMenuTrigged);
    }

    if(displayManager->getDisplayType() == "gdm"){
//        QAction *action = new QAction(QIcon(users->getDefaultIcon()),
//                                      tr("SwitchUser"), this);
        QWidgetAction *action = new QWidgetAction(usersMenu);
        HoverWidget *widget = new HoverWidget("");
        widget->setStyleSheet("HoverWidget:hover{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
        widget->setObjectName("SwitchUser");
        list.append(widget);
        widget->setFixedSize(240, 40);
        QLabel *iconlabel =new QLabel(widget);
        QPixmap p(users->getDefaultIcon());
        p = scaledPixmap(p);
        p = p.scaled(32*scale,32*scale, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        p = PixmapToRound(p, 16*scale);
        iconlabel->setPixmap(p);
        iconlabel->setGeometry(8,4,32,32);
        KLabel *textlabel =new KLabel(widget);
        textlabel->setFontSize(16);
        textlabel->setGeometry(48,4,190,30);
        action->setToolTip("SwitchUser");
        action->setData("SwitchUser");
        usersMenu->addAction(action);
        list.append(widget);
    }

    else if(displayManager->getDisplayType() == "lightdm"){
        connect(users, &Users::userAdded, this, &LockWidget::onUserAdded);
        connect(users, &Users::userDeleted, this, &LockWidget::onUserDeleted);

        for(auto user : users->getUsers())
        {
            onUserAdded(user);
        }

        if(displayManager->hasGuestAccount())
        {
//            QAction *action = new QAction(QIcon(users->getDefaultIcon()),
//                                      tr("Guest"), this);
            QWidgetAction *action = new QWidgetAction(usersMenu);
            HoverWidget *widget = new HoverWidget("");
            widget->setStyleSheet("HoverWidget:hover{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
            widget->setObjectName("Guest");
            list.append(widget);
            widget->setFixedSize(240, 40);
            QLabel *iconlabel =new QLabel(widget);
            QPixmap p(users->getDefaultIcon());
            p = scaledPixmap(p);
            p = p.scaled(32*scale,32*scale, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
            p = PixmapToRound(p, 16*scale);
            iconlabel->setPixmap(p);
            iconlabel->setGeometry(8,4,32,32);
            KLabel *textlabel =new KLabel(widget);
            textlabel->setFontSize(16);
            textlabel->setGeometry(48,4,190,30);
            action->setData("Guest");
            action->setToolTip("Guest");
            usersMenu->addAction(action);
            list.append(widget);
        }
    }
    UserItem currentUser = users->getUserByName(getenv("USER"));
    for(int i = 0;i < list.count(); i++){
        if(list.at(i)->objectName() == currentUser.name){
            list.at(i)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,40%);border-radius: 6px;}");
            nowAt = i;
        } else {
            list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                      "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
        }
    }
    scrollContents->setFixedSize(usersMenu->width(), usersMenu->height());
    //设置弹出菜单，设置弹出菜单的坐标为切换用户按钮的上方，中间保持一定间隔。
    if(scrollArea){
        if(scrollContents->height() < height()/2){
            scrollArea->setFixedSize(usersMenu->width(), scrollContents->height()+1);
        
	    scrollArea->clearMask();
	}else{
            scrollArea->setFixedSize(usersMenu->width() + 16, height()/2);

	    /*当scrollArea区域小于scrollContent大小时，使用样式表绘制的圆角外部透明部分，会显示出scrollContent的内容
             * 导致圆角外部有阴影，因此使用另一种方式再次绘制圆角，该方式绘制出来的圆角存在一定锯齿，所以只在会有阴影
             * 的情况下执行。*/
            QBitmap bitMap(scrollArea->width(),scrollArea->height()); // 定义一个窗口大小的位图
            bitMap.fill();                                // 填充整个位图
            QPainter painter(&bitMap);                    // 定义绘图设备
            painter.setBrush(Qt::black);                  // 必须定义为黑色
            painter.setPen(Qt::NoPen);                    // 只能为黑色或者不设置画笔
            painter.setRenderHint(QPainter::Antialiasing);// 反走样
            painter.drawRoundedRect(bitMap.rect(),8,8); // 绘制圆角矩形
            scrollArea->setMask(bitMap);
        }
        scrollArea->move(ui->btnSwitchUser->geometry().x()- scrollArea->width()/2 + 24, \
                    height() - 72 - scrollArea->height() - 8);
    }

}

void LockWidget::keyReleaseEvent(QKeyEvent *e)
{
    Q_EMIT keyGlobalRelease(e->key());

/*    if (e->key() == 9) {   // "Escape"

    } else */if(e->key() == Qt::Key_K){
        if(e->modifiers() & Qt::ControlModifier)
            showVirtualKeyboard();
    } else if (e->key() == Qt::Key_Tab) {
        key_tab_release(e->key());
    } else if(e->key() == Qt::Key_Backtab){
        if(e->modifiers() & Qt::ShiftModifier)
            key_shiftTab_release();
    } else if (e->key() == Qt::Key_Up || e->key() == Qt::Key_Down) {  // "Up" "Down"
        if(scrollArea && scrollArea->isVisible())
            key_OB_release(e->key());
    } else if (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right ) { // "Left" "Right"
        key_LR_release(e->key());
    } else if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {  // "Return" "KP_Enter"
        key_enter_release(e->key());
    }
}

/* lockscreen follows cursor */
void LockWidget::resizeEvent(QResizeEvent *event)
{
    QSize size = event->size();
        //重新计算缩放比例
    scale = QString::number(size.width() / 1920.0, 'f', 1).toFloat();

    //系统时间
    ui->widgetTime->move((width()-ui->widgetTime->geometry().width())/2, 59*scale);

    if(sureWidget){
        sureWidget->adjustSize();
        sureWidget->move((width()-sureWidget->geometry().width())/2, (height()-sureWidget->geometry().height())/2);
    }

    //认证窗口
    //设置认证窗口左右居中
    if(scale >= 1.3)
        authDialog->setGeometry((width()-authDialog->geometry().width())/2,height()/(4-0.7*scale), \
                            authDialog->width(), (height()*3/4));
    else if(scale <= 0.9)
        authDialog->setGeometry((width()-authDialog->geometry().width())/2,height()/(4-0.9*scale), \
                                authDialog->width(), (height()*3/4));
    else
        authDialog->setGeometry((width()-authDialog->geometry().width())/2,height()/(4-0.65*scale), \
                                authDialog->width(), (height()*3/4));

    if(scale > 1)
            scale = 1;

    //右下角按钮,x,y的初始值代表距离右下角的距离。
    int x=24,y=72;
    x = x + ui->btnPowerManager->width();
    ui->btnPowerManager->move(width() - x,height() - y);

    if(!ui->btnKeyboard->isHidden()){
        x = x+ui->btnKeyboard->width()+16;
        ui->btnKeyboard->move(width() - x, height() -  y);
    }

    x = x + btnNetworkManager->width()+16;
    btnNetworkManager->move(width() - x, height() - y);

    if(!ui->btnSwitchUser->isHidden()) {
        x = x + ui->btnSwitchUser->width()+16;
        ui->btnSwitchUser->move(width() - x, height() - y);
    }

    x = x + ui->btnBatteryStatus->width()+16;
    ui->btnBatteryStatus->move(width() - x, height() - y);
    setVirkeyboardPos();

    if (mBatteryWidget) {
        mBatteryWidget->setFixedSize(314, 112);
        mBatteryWidget->setPoint(QPoint(width() - 334, ui->btnBatteryStatus->y() - 16));
    }


    if(scrollContents && usersMenu)
        scrollContents->setFixedSize(usersMenu->width(), usersMenu->height());
    //设置弹出菜单，设置弹出菜单的坐标为切换用户按钮的上方，中间保持一定间隔。
    if(scrollArea){
        if(scrollContents->height() < height()/2){
            scrollArea->setFixedSize(usersMenu->width(),scrollContents->height()+1);
        
	    scrollArea->clearMask();
	}else{
            scrollArea->setFixedSize(usersMenu->width() + 16, height()/2);
            
	    QBitmap bitMap(scrollArea->width(),scrollArea->height()); // 定义一个窗口大小的位图
            bitMap.fill();                                // 填充整个位图
            QPainter painter(&bitMap);                    // 定义绘图设备
            painter.setBrush(Qt::black);                  // 必须定义为黑色
            painter.setPen(Qt::NoPen);                    // 只能为黑色或者不设置画笔
            painter.setRenderHint(QPainter::Antialiasing);// 反走样
            painter.drawRoundedRect(bitMap.rect(),8,8); // 绘制圆角矩形
            scrollArea->setMask(bitMap);
	}
        scrollArea->move(ui->btnSwitchUser->geometry().x()- scrollArea->width()/2 + 24, \
                    height() - y - scrollArea->height() - 8);
    }
    
    if(m_kylinNM){
        m_kylinNM->setGeometry(this->width() - m_kylinNM->width() - 20,
                           this->height() - m_kylinNM->height() - y - 8,
                           m_kylinNM->width(),
                           m_kylinNM->height());
    }

    if(powermanager){
#ifndef USE_INTEL
        if(width() < 1280)
            powermanager->showSmallSize();
        else
            powermanager->showNormalSize();
#endif
        powermanager->setGeometry((width()- powermanager->width())/2,
                                  (height()-powermanager->height())/2,
                                  powermanager->width(),powermanager->height());

    }
    if(QX11Info::isPlatformX11()){
        // XSetInputFocus(QX11Info::display(),this->winId(),RevertToParent,CurrentTime);
    }
}


void LockWidget::onUserAdded(const UserItem &user)
{
//    QAction *action = new QAction(QIcon(user.icon), user.realName, this);
//    action->setCheckable(true);

    QWidgetAction *action = new QWidgetAction(usersMenu);
    HoverWidget *widget = new HoverWidget("");
    widget->setStyleSheet("HoverWidget:hover{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
    widget->setObjectName(user.name);
    list.append(widget);
    widget->setFixedSize(240, 40);
    QLabel *iconlabel =new QLabel(widget);
    QPixmap p(user.icon);
    p = scaledPixmap(p);
    p = p.scaled(32*scale,32*scale, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    p = PixmapToRound(p, 16*scale);
    iconlabel->setPixmap(p);
    //iconlabel->setStyleSheet("background-color:transparent;");
    iconlabel->setGeometry(8,4,32,32);
    KLabel *textlabel =new KLabel(widget);
    textlabel->setFontSize(16);
    textlabel->setGeometry(48,4,190,30);
    if(getLoadStatus(user.name)){
        QLabel *statusIcon = new QLabel(widget);
        QPixmap status(":/image/assets/selected.svg");
        status = scaledPixmap(status);
        status = status.scaled(14*scale,14*scale, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        p = PixmapToRound(status, 7*scale);
        statusIcon->setPixmap(status);
        statusIcon->setGeometry(32, 5, 14, 14);
    }
    action->setDefaultWidget(widget);

    textlabel->setElideText(user.realName, textlabel->width());
    action->setData(user.name);
    usersMenu->addAction(action);
    usersMenu->adjustSize();
}

void LockWidget::onUserDeleted(const UserItem &user)
{
    for(auto action : usersMenu->actions())
    {
        if(action->data() == user.name)
            usersMenu->removeAction(action);
    }
}

bool LockWidget::getLoadStatus(const QString &name)
{
    QDBusInterface interface(LG_DBUS_SERVICE,
                                  LG_DBUS_PATH,
                                  LG_DBUS_INTERFACE,
                                  QDBusConnection::systemBus());
    QDBusMessage result = interface.call("ListUsers");
    QList<QVariant> outArgs = result.arguments();
    QVariant first = outArgs.at(0);
    QDBusArgument dbvFirst = first.value<QDBusArgument>();
    QVariant vFirst = dbvFirst.asVariant();
    const QDBusArgument &dbusArgs = vFirst.value<QDBusArgument>();

    QVector<userInfo> loginedUsers;

    dbusArgs.beginArray();
    while (!dbusArgs.atEnd()) {
        userInfo user;
        dbusArgs >> user;
        loginedUsers.push_back(user);
    }
    for (userInfo user : loginedUsers) {
        QDBusInterface userPertyInterface("org.freedesktop.login1",
                                          user.userPath.path(),
                                          "org.freedesktop.DBus.Properties",
                                          QDBusConnection::systemBus());
        QDBusReply<QVariant> reply = userPertyInterface.call("Get", "org.freedesktop.login1.User", "State");
        if (reply.isValid()) {
            QString status = reply.value().toString();
            if ("closing" != status) {
                m_loginedUser.append(user.userName);
            }
        }
    }
    int count = 0;
    for(int i = 0 ;i<m_loginedUser.count();i++)
    {
        if(m_loginedUser.at(i) == name)
            count++;
    }
    if(count > 0)
        return true;
    else
        return false;
}

void LockWidget::onUserMenuTrigged(QAction *action)
{
    qDebug() << action->data().toString() << "selected";

    if(authDialog)
    {
        authDialog->stopAuth();
    }

    QString userName = action->data().toString();
    for (int i =0; i < list.count(); i++)
    {
            if(list.at(i)->objectName() == userName){
                list.at(i)->setStyleSheet("HoverWidget{background-color:rgb(255,255,255,40%);border-radius: 6px;}"
                                          "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,40%);border-radius: 6px;}");
            } else {
                list.at(i)->setStyleSheet("HoverWidget{background-color:transparent;}"
                                          "HoverWidget:hover:!pressed{background-color:rgb(255,255,255,15%);border-radius: 6px;}");
            }
    }
    if(userName == "Guest")
    {
        displayManager->switchToGuest();
    }
    else if(userName == "SwitchUser")
    {
        displayManager->switchToGreeter();
    }
    else
    {
        displayManager->switchToUser(userName);
    }
}

bool LockWidget::exitSubWidget()
{
    bool allExited = true;
    if(mBatteryWidget && mBatteryWidget->isVisible()) {
        setCheckedSheet(BATTERYBTN, false);
        at_plugins = false;
        if(tabAt == BOTTMBTN && horAT == BATTERYBTN)
            ui->btnBatteryStatus->setStyleSheet(ON_TAB_SHEET);
    } else if(scrollArea && scrollArea->isVisible()){
        setCheckedSheet(SWITCHBTN, false);
        at_plugins = false;
        if(tabAt == BOTTMBTN && horAT == SWITCHBTN)
            ui->btnSwitchUser->setStyleSheet(ON_TAB_SHEET);
        allExited = false;
    } else if(m_kylinNM && m_kylinNM->isVisible()){
        setCheckedSheet(NETWORKBTN, false);
        at_plugins = false;
        if(tabAt == BOTTMBTN && horAT == NETWORKBTN)
            btnNetworkManager->setStyleSheet(ON_TAB_SHEET);
        allExited = false;
    } else if(vKeyboard && vKeyboard->isVisible()) {
        vKeyboard->hide();
        at_plugins = false;
        if(tabAt == BOTTMBTN && horAT == KEYBOARDBTN)
            ui->btnKeyboard->setStyleSheet(ON_TAB_SHEET);
        allExited = false;
    } else if(powermanager && powermanager->isVisible()){
        authDialog->show();
        powermanager->hide();
        if(!authDialog->getLineeditStatus()) {
            tabAt = LINEEDIT;
            authDialog->setFocusin(IN_LINEEDIT);
            if(isTableMode && !(vKeyboard && vKeyboard->isVisible())) {
                showVirtualKeyboard();
            }
        } else {
            tabAt = MESSAGEBTN;
            authDialog->setFocusin(ON_MESSAGEBTN);
        }
        setBottomBtnSheet();
        powermanager->clearStatus();
        at_power = false;
        allExited = false;
        return allExited;
    }
    if(tabAt != LINEEDIT && tabAt != MESSAGEBTN && tabAt != ENTERBTN && tabAt != BIOBTN)
        authDialog->setFocusin(REMOVE);
    return allExited;
}

void LockWidget::onActiveLineedit()
{
    if(tabAt == LINEEDIT || (tabAt == BOTTMBTN && horAT == KEYBOARDBTN)) { /*
                                                                            重启时session拉其他组件时会多次设置焦点
                                                                            这个时候如果是平板模式，因为已经弹出了虚拟键盘 tabAt就会是BOTTOM
                                                                            */
        if(authDialog && authDialog->isVisible()) {
            if(!authDialog->getLineeditStatus()) {
                authDialog->setFocusin(IN_LINEEDIT);
//                if(isTableMode && !(vKeyboard && vKeyboard->isVisible()))
//                    showVirtualKeyboard();
            } else {
                tabAt = MESSAGEBTN;
                authDialog->setFocusin(ON_MESSAGEBTN);
            }
        }
    }
}

QString LockWidget::getBatteryIconName()
{
    if (iface->isValid() && dface->isValid()) {
        bool batteryState = false;
        QDBusReply<QVariant> reply = batInterface->call("Get", UPOWER_SERVICE, "OnBattery");
        if (reply.isValid()) {
            batteryState = reply.value().toBool();
        }
        double percentage = -1.0;
        QDBusReply<QVariant> percentage_reply = iface->call("Get", UPOWER_DIVICES_SERVICE, "Percentage");
        if (percentage_reply.isValid()) {
            percentage = percentage_reply.value().toDouble();
        }

        if (true == batteryState) {
            return QString("battery-level-%1-symbolic").arg((int)percentage / 10 * 10);
        } else {
            return QString("battery-level-%1-charging-symbolic").arg((int)percentage / 10 * 10);
        }
    }
    return QString();
}

int LockWidget::getLoginedNum()
{
    if(loginedNum != 0)
        return loginedNum;
    for(auto user : users->getUsers())
    {
        if(getLoadStatus(user.name)){
            loginedNum++;
        }
    }
    return loginedNum;
}

QDBusArgument &operator <<(QDBusArgument &arg, const userInfo &usersInfo)
{
    arg.beginStructure();
    arg << usersInfo.userId
        << usersInfo.userName
        << usersInfo.userPath;
    arg.endStructure();
    return arg;
}
const QDBusArgument &operator >>(const QDBusArgument &arg, userInfo &usersInfo)
{
    arg.beginStructure();
    arg >> usersInfo.userId
        >> usersInfo.userName
        >> usersInfo.userPath;
    arg.endStructure();
    return arg;
}

bool LockWidget::IsDesktopStarted()
{
    QDBusInterface *iface = new QDBusInterface(DESKTOP_DBUS_SERVICE,
                                               DESKTOP_DBUS_PATH,
                                               DESKTOP_DBUS_INTERFACE,
                                               QDBusConnection::sessionBus(),
                                               this);
    if (iface) {
        if (iface->isValid()) {
            delete iface;
            return true;
        }
        delete iface;
    }
    return false;
}

void LockWidget::setRootWindow()
{
    QStringList keysMateBg;
    QString strUserBgFile = "";
    QString strUserBgColor = "";
    QString strUserBgOptions = "";
    if(QGSettings::isSchemaInstalled(GSETTINGS_SCHEMA_MATE_BG)){
        QGSettings *mateBgSettings = new QGSettings(GSETTINGS_SCHEMA_MATE_BG, "", this);
        keysMateBg = mateBgSettings->keys();
        if (keysMateBg.contains(KEY_PICTURE_FILENAME)) {
            strUserBgFile = mateBgSettings->get(KEY_PICTURE_FILENAME).toString();
        }
        if (keysMateBg.contains(KEY_PRIMARY_COLOR)) {
            strUserBgColor = mateBgSettings->get(KEY_PRIMARY_COLOR).toString();
        }
        if (keysMateBg.contains(KEY_PICTURE_OPTIONS)) {
            strUserBgOptions = mateBgSettings->get(KEY_PICTURE_OPTIONS).toString();
        }
        qDebug()<<"User bg info:"<<strUserBgFile<<strUserBgColor<<strUserBgOptions;
        delete mateBgSettings;
        mateBgSettings = nullptr;
    }
    QFile userBackgroundFile(strUserBgFile);
    int nOptions = WNDBG_OPTION_SCALED;
    int nDrawBgType = 0;
    if (strUserBgOptions == "scaled") {
        nOptions = WNDBG_OPTION_SCALED;
    } else if (strUserBgOptions == "stretched") {
        nOptions = WNDBG_OPTION_STRETCHED;
    } else if (strUserBgOptions == "centered") {
        nOptions = WNDBG_OPTION_CENTERED;
    } else if (strUserBgOptions == "wallpaper") {
        nOptions = WNDBG_OPTION_WALLPAPER;
    } else if (strUserBgOptions == "zoom") {
        nOptions = WNDBG_OPTION_ZOOM;
    } else if (strUserBgOptions == "spanned") {
        nOptions = WNDBG_OPTION_SPANNED;
    }
    if(strUserBgFile.isEmpty() || !userBackgroundFile.exists()) {
        if (strUserBgFile.isEmpty()) {
            if (!strUserBgColor.isEmpty() && strUserBgColor.length() == 7 && strUserBgColor.startsWith("#"))
                nDrawBgType = 1;
        }
        strUserBgFile = Configuration::instance()->getDefaultBackgroundName();
    }
    if(nDrawBgType == 0) {
        qDebug()<<"DrawBgFile:"<<strUserBgFile<<nOptions;
        setRootWindowBackground(0, 0, strUserBgFile.toLatin1().data(), nOptions);
    } else {
        strUserBgColor = strUserBgColor.remove(0,1);
        bool ok;
        unsigned int color = strUserBgColor.toUInt(&ok,16);
        qDebug()<<"DrawBgColor:"<<color<<nOptions;
        setRootWindowBackground(1, color, NULL, nOptions);
    }
}

void LockWidget::onAuthenticateCompete()
{
    if (m_isStartupMode) {
        bool isDesktopStarted = IsDesktopStarted();
        qDebug()<<"isDesktopStarted "<<isDesktopStarted;
        if (m_futureLoadDeskBg.isRunning()) {
            m_futureLoadDeskBg.waitForFinished();
        } else {
            if (!m_futureLoadDeskBg.isFinished() && m_futureLoadDeskBg.isStarted()) {
                m_futureLoadDeskBg.waitForFinished();
            }
        }
        if (!isDesktopStarted)
            drawBackground(true);
        else
            drawBackground(false);
        qDebug()<<"drawBackground Complete!!";
    }
    Q_EMIT closed();
}

