#include "lockwidget.h"
#include <QPixmap>
#include <QPainter>
#include <QScreen>
#include <QPainterPath>
#include <QDebug>
#include <QProcess>
#include <QKeyEvent>
#include <QListView>
#include <QListWidget>
#include <QPalette>
#include <QScrollBar>
#include <QLabel>
#include <QPushButton>
#include "poweritemwidget.h"
#include "useritemwidget.h"
#include "mylistwidget.h"
#include "userlistwidget.h"
#include "sessionlistwidget.h"
#include "statusbutton.h"
#include "../lock-dialog/lockdialogmodel.h"
#include "iconedit.h"
#include "commonfunc.h"
#include "authdialog.h"
#include "powerlistwidget.h"
#include "timewidget.h"
#include "networkbutton.h"
#include "definetypes.h"
#include "mynetworkwidget.h"
#include "batterywidget.h"
#include "VirtualKeyboard/src/virtualkeyboardwidget.h"
#include "blockwidget.h"
#include "pluginsloader.h"
#include "global_utils.h"

#define BLUR_RADIUS 300
#define RIGHT_MARGIN 24
#define BOTTOM_MARGIN 24

#define PREFIX QString(RESOURCE_PATH)
#define IMAGE_DIR PREFIX+"/images/"
float scale;
LockWidget::LockWidget(LockDialogModel *model, QWidget *parent)
    : QWidget(parent)
    , m_modelLockDialog(model)
{
    scale = 1.0;
    UserInfoPtr ptrUser = m_modelLockDialog->findUserByName(m_modelLockDialog->defaultUserName());
    if (ptrUser) {
        m_curUserInfo = *ptrUser;
    }
    initUI();
    initConnections();
    initUsdMediaKeys();
    installEventFilter(this);
}

bool LockWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyRelease) {
        MyListWidget *listWidget = qobject_cast<MyListWidget *>(obj);
        if (listWidget) {
            if (listWidget && listWidget->hasFocus()) {   //Tab键切入时，设置焦点状态
                listWidget->setCurrentRow(listWidget->currentRow(), QItemSelectionModel::SelectionFlag::SelectCurrent);
                listWidget->currentItemChanged(listWidget->currentItem(), nullptr);
            } else {    //Tab键切出时，清空焦点状态
                listWidget->setCurrentRow(listWidget->currentRow(), QItemSelectionModel::SelectionFlag::Clear);
            }
        }
    } else if (event->type() == QEvent::MouseButtonPress) {
        /// TODO
        if(m_userListWidget && m_userListWidget->isVisible()){
            if (obj != m_userListWidget) {
                onShowUserListWidget();
            }
        }
        if(m_powerListWidget && m_powerListWidget->isVisible()){
            if (obj != m_powerListWidget) {
                onShowPowerListWidget();
            }
        }

        //这段代码没看懂，但是如果注释掉的话，点击网络窗口，网络窗口会隐藏
        if(m_networkWidget &&  m_networkWidget == obj){
            return true;
        }

        if(m_networkWidget && m_networkWidget->isVisible()){
            if (m_networkWidget != obj){
                onShowNetworkWidget();
            }
        }

        if(m_virtualKeyboardWidget && m_virtualKeyboardWidget->isVisible()){
            if (m_virtualKeyboardWidget != obj){
                onShowVirtualKeyboard();
            }
        }

        if(m_sessionListWidget && m_sessionListWidget->isVisible()){
            if (m_sessionListWidget != obj){
                onShowSessionListWidget();
            }
        }

        if(batteryWidget && batteryWidget->isVisible()){
            if (batteryWidget != obj){
                onShowBatteryWidget();
            }
        }
    }

    return false;
}

bool LockWidget::exitSubWidget()
{
    bool allExited = true;
    if(m_userListWidget && m_userListWidget->isVisible()){
        m_userListWidget->hide();
        m_userButton->setClickedStatus(NORMAL);
        allExited = false;
    }
    if(m_powerListWidget && m_powerListWidget->isVisible()){
        authDialog->setFocus();
        authDialog->show();
        authDialog->lower();
        m_powerListWidget->hide();
        m_powerManagerButton->setClickedStatus(NORMAL);
        allExited = false;
    }
    if(m_networkWidget && m_networkWidget->isVisible()){
        m_networkWidget->hide();
        m_networkButton->setClickedStatus(NORMAL);
//        sendNetPluginVisible(false);
        allExited = false;
    }
    if (m_virtualKeyboardWidget && m_virtualKeyboardWidget->isVisible()) {
        m_virtualKeyboardWidget->hide();
        m_virKbButton->setClickedStatus(NORMAL);
        allExited = false;
    }
    if (batteryWidget && batteryWidget->isVisible()) {
        batteryWidget->hide();
        m_batteryonButton->setClickedStatus(NORMAL);
        allExited = false;
    }
    if (m_sessionListWidget && m_sessionListWidget->isVisible()) {
        m_sessionListWidget->hide();
        m_sessionButton->setClickedStatus(NORMAL);
        allExited = false;
    }
    authDialog->setFocus();

    return allExited;
}

void LockWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(this->geometry(), background);
    QPainterPath path;
    painter.setOpacity(0.25);
    painter.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    painter.setClipping(true);
    painter.setPen(Qt::transparent);
    path.addRect(this->rect());
    path.setFillRule(Qt::WindingFill);
    painter.setBrush(QColor("#000000"));
    painter.setPen(Qt::transparent);
    painter.drawPath(path);
    return QWidget::paintEvent(event);
}

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

    authDialog->setGeometry((width()-this->geometry().width())/2, 148*scale, \
                        this->width(), (height() - 150*scale - (24 + 48 + 16)*scale));
    authDialog->updateAuthSize();

    m_timeWidget->updateUI();
    m_timeWidget->move((width() - m_timeWidget->width())/2, 48*scale);
    if (m_userListWidget) {
        m_userListWidget->setMaxHeight(height()/2);
        m_userListWidget->updateWidgetSize();
        qDebug()<<"m_userListWidget:"<<m_userListWidget->geometry();
    }

    m_powerListWidget->move((width() - m_powerListWidget->width())/2,  (height() - m_powerListWidget->height())/2 - BOTTOM_MARGIN*scale);

    updateBottomButton();
    if (m_curUserInfo.isLoggedIn() && m_sessionButton) {
        buttonListWidget->setFixedSize(QSize(48*(buttonListWidget->count() - 1) + buttonListWidget->spacing()*2*(buttonListWidget->count() - 1), 64));
    } else {
        buttonListWidget->setFixedSize(QSize(48*buttonListWidget->count() + buttonListWidget->spacing()*2*buttonListWidget->count(), 64));
    }
    buttonListWidget->move(width() - buttonListWidget->width() - RIGHT_MARGIN*scale, height() - buttonListWidget->height() - BOTTOM_MARGIN*scale);

    if (m_sessionListWidget) {
        m_sessionListWidget->setMaxHeight(height()/2);
        m_sessionListWidget->updateWidgetSize();
        m_sessionListWidget->move(this->width() - m_sessionListWidget->width() - RIGHT_MARGIN*scale,
                                  height()- BOTTOM_MARGIN*scale - buttonListWidget->height() - buttonListWidget->spacing()*scale*2 - m_sessionListWidget->height());
    }

    if(m_networkWidget){
        m_networkWidget->setGeometry(this->width() - m_networkWidget->width() - RIGHT_MARGIN*scale,
                               this->height() - m_networkWidget->height() - BOTTOM_MARGIN*scale - buttonListWidget->spacing()*scale*2 - buttonListWidget->height(),
                               m_networkWidget->width(),
                               m_networkWidget->height());
    }
    if (batteryWidget) {
            batteryWidget->move(this->width() - batteryWidget->width() - RIGHT_MARGIN*scale,
                                       height() - BOTTOM_MARGIN*scale - buttonListWidget->height() - buttonListWidget->spacing()*scale - batteryWidget->height());
    }

    if (m_userListWidget) {
        m_userListWidget->move(width() - m_userListWidget->width() - RIGHT_MARGIN,
                           height()- BOTTOM_MARGIN*scale - buttonListWidget->height() - buttonListWidget->spacing()*scale - m_userListWidget->height());
    }
    onSetVirkeyboardPos();
}

void LockWidget::keyReleaseEvent(QKeyEvent *e)
{
    if (e->key() == Qt::Key_K) {
        if(e->modifiers() & Qt::ControlModifier)
            onShowVirtualKeyboard();
    }


    if (m_modelLockDialog->isUseWayland()) {
        // 监听按键事件实现快捷键功能
        switch (e->key()) {
        case Qt::Key_VolumeMute:
            Q_EMIT m_modelLockDialog->usdExternalDoAction(MIC_MUTE_KEY);
            break;
        case Qt::Key_VolumeDown:
            Q_EMIT m_modelLockDialog->usdExternalDoAction(VOLUME_DOWN_KEY);
            break;
        case Qt::Key_VolumeUp:
            Q_EMIT m_modelLockDialog->usdExternalDoAction(VOLUME_UP_KEY);
            break;
        case Qt::Key_MonBrightnessUp:
            Q_EMIT m_modelLockDialog->usdExternalDoAction(BRIGHT_UP_KEY);
            break;
        case Qt::Key_MonBrightnessDown:
            Q_EMIT m_modelLockDialog->usdExternalDoAction(BRIGHT_DOWN_KEY);
            break;
        case Qt::Key_TouchpadOn:
            Q_EMIT m_modelLockDialog->usdExternalDoAction(TOUCHPAD_ON_KEY);
            break;
        case Qt::Key_TouchpadOff:
            Q_EMIT m_modelLockDialog->usdExternalDoAction(TOUCHPAD_OFF_KEY);
            break;
        default:
            break;
        }

        //  实现锁屏截图功能
        QKeySequence keySequence = QKeySequence(e->modifiers() + e->key());
        if (keySequence == listFromString(m_areaScreenShot)) {
            Q_EMIT m_modelLockDialog->usdExternalDoAction(AREA_SCREENSHOT_KEY);
        } else if (keySequence == listFromString(m_areaScreenShot2)) {
            Q_EMIT m_modelLockDialog->usdExternalDoAction(AREA_SCREENSHOT_KEY);
        } else if (keySequence == listFromString(m_screenShot)) {
            Q_EMIT m_modelLockDialog->usdExternalDoAction(SCREENSHOT_KEY);
        } else if (keySequence == listFromString(m_screenShot2)) {
            Q_EMIT m_modelLockDialog->usdExternalDoAction(SCREENSHOT_KEY);
        } else if (keySequence == listFromString(m_windowScreenshot)) {
            Q_EMIT m_modelLockDialog->usdExternalDoAction(WINDOW_SCREENSHOT_KEY);
        }
    }
}

void LockWidget::initUI()
{
    // 检查并获取第三方认证插件配置信息
    if (PluginsLoader::instance().findModulesByType(LoginPluginInterface::MODULETYPE_AUTH).size() > 0) {
        LoginAuthInterface *plugin = dynamic_cast<LoginAuthInterface *>(PluginsLoader::instance() \
                                                                        .findModulesByType(LoginPluginInterface::MODULETYPE_AUTH) \
                                                                        .values().first());
        QJsonObject rootObj;
        rootObj["MsgType"] = "GetInformations";
        rootObj["Key"] = "Configures";
        QString strMsg = plugin->onMessage(QJsonDocument(rootObj).toJson());
        onGetCustomPluginMsg(strMsg);
    }

    authDialog = new AuthDialog(m_modelLockDialog, m_curUserInfo, this);
    authDialog->installEventFilter(this);
    initTimeWidget();
    initPowerWidget();
    initButtonWidget();
    initBlockWidget();
//    authDialog->setFocus();
 //    Q_EMIT m_modelLockDialog->setCurrentUser(m_modelLockDialog->defaultUserName());
}

void LockWidget::initConnections()
{
    connect(m_modelLockDialog, &LockDialogModel::usersInfoChanged, this, &LockWidget::onUsersInfoChanged);
    connect(m_modelLockDialog, &LockDialogModel::currentUserChanged, this, &LockWidget::onCurUserChanged);
    connect(m_modelLockDialog, &LockDialogModel::currentSessionChanged, this, &LockWidget::onSessionChanged);
    connect(m_modelLockDialog, &LockDialogModel::sessionActiveChanged, this, &LockWidget::onSessionActiveChanged);
    if (authDialog) {
        connect(authDialog, SIGNAL(authSucceed(QString)), this, SIGNAL(authSucceed(QString)));
        connect(authDialog, &AuthDialog::userChangedByManual,
                this, &LockWidget::onUserChangedByManual);
        connect(authDialog, &AuthDialog::customRequestAccount,
                this, &LockWidget::onCustomRequestAccount);
    }
}
void LockWidget::initTimeWidget()
{
    m_timeWidget = new TimeWidget(m_modelLockDialog, this);
    m_timeWidget->move((width() - m_timeWidget->width())/2, 0);

}
void LockWidget::initUserWidget()
{
    if (!m_userListWidget) {
        m_userListWidget = new UserListWidget(m_modelLockDialog, this);
        m_userListWidget->installEventFilter(this);
        m_userListWidget->setMaxHeight(height()/2);
        m_userListWidget->updateWidgetSize();
        m_userListWidget->hide();
        connect(m_userListWidget, &UserListWidget::userSelected, m_modelLockDialog, [=](QString strUserName){
            SwitchToUser(strUserName);
        });
        m_userListWidget->clearFocus();
        m_userListWidget->move(width() - m_userListWidget->width() - RIGHT_MARGIN,
                           height()- BOTTOM_MARGIN*scale - buttonListWidget->height() - buttonListWidget->spacing()*scale - m_userListWidget->height());
    }
}

void LockWidget::initSessionWidget()
{
    if (!m_sessionListWidget) {
        m_sessionListWidget = new SessionListWidget(m_modelLockDialog, this);
        m_sessionListWidget->installEventFilter(this);
        m_sessionListWidget->setMaxHeight(height()/2);
        m_sessionListWidget->updateWidgetSize();
        m_sessionListWidget->hide();
        connect(m_sessionListWidget, &SessionListWidget::sessionSelected, m_modelLockDialog, &LockDialogModel::setCurrentSession);
        m_sessionListWidget->clearFocus();
        if (buttonListWidget) {
            m_sessionListWidget->move(this->width() - m_sessionListWidget->width() - RIGHT_MARGIN*scale,
                                      height()- BOTTOM_MARGIN*scale - buttonListWidget->height() - buttonListWidget->spacing()*scale*2 - m_sessionListWidget->height());
        }
    }
}

void LockWidget::initPowerWidget()
{
    m_powerListWidget = new PowerListWidget(m_modelLockDialog,this);
    m_powerListWidget->setMaximumHeight(height()/2);
    m_powerListWidget->move((width() - m_powerListWidget->width())/2,  (height()-m_powerListWidget->height())/2-80);
    m_powerListWidget->hide();
    connect(m_powerListWidget, &MyListWidget::currentItemChanged, this, &LockWidget::onPowerItemChanged);
    connect(m_powerListWidget, &PowerListWidget::showInhibitWarning, this, &LockWidget::onShowInhibitWarning);
    connect(m_powerListWidget, &PowerListWidget::mulUsersLogined, this, &LockWidget::onMulUsersLogined);
    connect(m_powerListWidget, &PowerListWidget::itemClicked, this, &LockWidget::onShowPowerListWidget);
    m_powerListWidget->clearFocus();
}

void LockWidget::initButtonWidget()
{
    buttonListWidget = new MyListWidget(this);
    buttonListWidget->installEventFilter(this);
    buttonListWidget->setFlow(QListWidget::LeftToRight);
    buttonListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    buttonListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    QString buttonListStyle = "QListWidget{ background:rgba(255, 255, 255, 0%); border: 0px;}"
                             "QListWidget::item{border-radius: 4px; background:rgba(255, 255, 255, 0%);}";
    buttonListWidget->setStyleSheet(buttonListStyle);
    buttonListWidget->setSpacing(8);

    if (m_modelLockDialog->sessionsInfo().count() > 1) {
        m_sessionButton = new StatusButton(this, BOTBUTTON);
        m_btnItemSession = new QListWidgetItem();
        m_btnItemSession->setSizeHint(QSize(48, 48));
        buttonListWidget->insertItem(buttonListWidget->count(), m_btnItemSession);
        buttonListWidget->setItemWidget(m_btnItemSession, m_sessionButton);
        buttonListWidget->addItem(m_btnItemSession);
        m_sessionButton->setObjectName("BtnSession");
        if (m_curUserInfo.isLoggedIn()) {
            buttonListWidget->setItemHidden(m_btnItemSession, true);
        } else {
            buttonListWidget->setItemHidden(m_btnItemSession, false);
        }
        QString strCurSession = m_modelLockDialog->currentSession();
        QString sessionPrefix = strCurSession.left(strCurSession.indexOf('-'));
        if(strCurSession == "ukui-wayland")
            sessionPrefix = "ukui_wayland";
        strCurSession = IMAGE_DIR + QString("badges/%1_badge.svg")
                .arg(sessionPrefix.toLower());
        QFile iconFile(strCurSession);
        if(!iconFile.exists()){
            strCurSession = IMAGE_DIR + QString("badges/unknown_badge.svg");
        }
        QPixmap ssIcon(strCurSession);
        ssIcon = scaledPixmap(ssIcon);
        ssIcon = ssIcon.scaled(32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        ssIcon = PixmapToRound(ssIcon, 16);
        m_sessionButton->setIcon(ssIcon);
        connect(m_sessionButton, &StatusButton::clicked, this, [this]() {
            onShowSessionListWidget();
        });
    }

    if (m_modelLockDialog->getIsBattery()) {
        m_batteryonButton = new StatusButton(this, BOTBUTTON);
        QListWidgetItem *buttonItem = new QListWidgetItem();
        buttonItem->setSizeHint(QSize(48, 48));
        buttonListWidget->insertItem(buttonListWidget->count(), buttonItem);
        buttonListWidget->setItemWidget(buttonItem, m_batteryonButton);
        QPixmap batteryIcon = drawSymbolicColoredPixmap(QIcon::fromTheme(m_modelLockDialog->getBatteryIconName()).pixmap(QSize(24, 24)), "white");
        m_batteryonButton->setIcon(batteryIcon);
        connect(m_modelLockDialog, &LockDialogModel::batteryStatusChanged, this, [=](const QString &iconName) {
            QPixmap batteryIcon = drawSymbolicColoredPixmap(QIcon::fromTheme(iconName).pixmap(QSize(24, 24)), "white");
            m_batteryonButton->setIcon(batteryIcon);
        });
        buttonListWidget->addItem(buttonItem);
        connect(m_batteryonButton, &StatusButton::clicked, this, [this]() {
            onShowBatteryWidget();
        });
    }

    m_userButton = new StatusButton(this, BOTBUTTON);
    m_btnItemUser = new QListWidgetItem();
    m_btnItemUser->setSizeHint(QSize(48, 48));
    buttonListWidget->insertItem(buttonListWidget->count(), m_btnItemUser);
    buttonListWidget->setItemWidget(m_btnItemUser, m_userButton);
    m_userButton->setIcon(QIcon(":/image/assets/switchuser.svg"));
    buttonListWidget->addItem(m_btnItemUser);
    connect(m_userButton, &StatusButton::clicked, this, [this]() {
        onShowUserListWidget();
    });
    if (m_modelLockDialog->usersInfo().count() > 1 || m_modelLockDialog->findUserByName("*login")) {
        buttonListWidget->setItemHidden(m_btnItemUser, false);
    } else {
        buttonListWidget->setItemHidden(m_btnItemUser, true);
    }

    m_networkButton = new NetWorkButton(this);
    QListWidgetItem *buttonItem = new QListWidgetItem();
    buttonItem->setSizeHint(QSize(48, 48));
    buttonListWidget->insertItem(buttonListWidget->count(), buttonItem);
    buttonListWidget->setItemWidget(buttonItem, m_networkButton);
    buttonListWidget->addItem(buttonItem);
    connect(m_networkButton, &NetWorkButton::clicked, this, [this]() {
        onShowNetworkWidget();
    });

    /*
    connect(buttonWidget, &KyNetworkIcon::updateIconHidden
            ,this, [buttonWidget,this](bool status){
        if (status) {
            buttonWidget->hide();
        } else {
            buttonWidget->show();
        }
    });
    if (buttonWidget->checkIconIsHidden()) {
        buttonWidget->hide();
    }
    */

    m_virKbButton = new StatusButton(this, BOTBUTTON);
    QListWidgetItem *kyeboardItem = new QListWidgetItem();
    kyeboardItem->setSizeHint(QSize(48, 48));
    buttonListWidget->insertItem(buttonListWidget->count(), kyeboardItem);
    buttonListWidget->setItemWidget(kyeboardItem, m_virKbButton);
    m_virKbButton->setIcon(QIcon(":/image/assets/keyboard.svg"));
    buttonListWidget->addItem(kyeboardItem);
    connect(m_virKbButton, &StatusButton::clicked, this, [this]() {
        onShowVirtualKeyboard();
    });

    if (m_powerListWidget->count() > 1 ) {
        m_powerManagerButton = new StatusButton(this, BOTBUTTON);
        QListWidgetItem *buttonItem = new QListWidgetItem();
        buttonItem->setSizeHint(QSize(48, 48));
        buttonListWidget->insertItem(buttonListWidget->count(), buttonItem);
        buttonListWidget->setItemWidget(buttonItem, m_powerManagerButton);
        m_powerManagerButton->setIcon(QIcon(":/image/assets/shutdown.svg"));
        buttonListWidget->addItem(buttonItem);
        connect(m_powerManagerButton, &StatusButton::clicked, this, [this]() {
            onShowPowerListWidget();
        });
    }

    if (m_curUserInfo.isLoggedIn() && m_sessionButton) {
        buttonListWidget->setFixedSize(QSize(48*(buttonListWidget->count() - 1) + buttonListWidget->spacing()*2*(buttonListWidget->count() - 1), 64));
    } else {
        buttonListWidget->setFixedSize(QSize(48*buttonListWidget->count() + buttonListWidget->spacing()*2*buttonListWidget->count(), 64));
    }
    buttonListWidget->move(width()- RIGHT_MARGIN -buttonListWidget->width(), height() - BOTTOM_MARGIN - buttonListWidget->spacing());
    connect(buttonListWidget, &MyListWidget::currentItemChanged, this, &LockWidget::onButtonItemChanged);
    connect(buttonListWidget, &MyListWidget::itemClicked, this, &LockWidget::onButtonItemClicked);
    buttonListWidget->clearFocus();
}

void LockWidget::initBlockWidget()
{
    m_blockWidget = new BlockWidget(m_modelLockDialog, this);
    m_blockWidget->setGeometry(this->geometry());
    m_blockWidget->hide();
    connect(m_blockWidget, SIGNAL(cancelButtonclicked()),
        this, SLOT(onCancelBtnClicked()));
    connect(m_blockWidget, SIGNAL(confirmButtonclicked()),
        this, SLOT(onConfirmBtnClicked()));
}

void LockWidget::initUsdMediaKeys()
{
    m_areaScreenShot = m_modelLockDialog->getUsdAreaScreenShotKey();
    m_areaScreenShot2 = m_modelLockDialog->getUsdAreaScreenShot2Key();
    m_screenShot = m_modelLockDialog->getUsdScreenShotKey();
    m_screenShot2 = m_modelLockDialog->getUsdScreenShot2Key();
    m_windowScreenshot = m_modelLockDialog->getUsdwindowScreenshotKey();
    connect(m_modelLockDialog, &LockDialogModel::usdMediaKeysChanged, this, &LockWidget::onUsdMediaKeysChanged);
}

const QKeySequence LockWidget::listFromString(QString keys)
{
    keys.replace("<", "");
    keys.replace(">", "+");
    keys.replace("Win", "Meta", Qt::CaseInsensitive);
    keys.replace("Start", "Meta", Qt::CaseInsensitive);
    keys.replace("PrtSc", "Print", Qt::CaseInsensitive);
    return QKeySequence(keys);
}

void LockWidget::updateBottomButton()
{
    QList<StatusButton *> statusButton = this->findChildren<StatusButton *>();
    for (auto button : statusButton) {
        if (button->getButtonTyoe() == POWERBUTTON) {
            button->setFixedSize(130*scale, 130*scale);
            button->setIconSize(QSize(130*scale, 130*scale));
        } else {
            button->setFixedSize(48*scale, 48*scale);
            button->setIconSize(QSize(24*scale, 24*scale));
        }
    }
    QList<NetWorkButton *> networkButton = this->findChildren<NetWorkButton *>();
    for (auto button : networkButton) {
        button->setFixedSize(48*scale, 48*scale);
        button->setIconSize(QSize(24*scale, 24*scale));
    }
}

void LockWidget::onPowerItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    QWidget *currentWidget = m_powerListWidget->itemWidget(current);
    PowerItemWidget *currentItem = dynamic_cast<PowerItemWidget *>(currentWidget);
    if (currentItem) {
        currentItem->setSelected(SELECT);
    }
    if (previous) {
        QWidget *previousWidget = m_powerListWidget->itemWidget(previous);
        PowerItemWidget *previousItem = dynamic_cast<PowerItemWidget *>(previousWidget);
        if (previousItem) {
            previousItem->setSelected(NORMAL);
        }
    }
}

void LockWidget::onButtonItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    QWidget *currentWidget = buttonListWidget->itemWidget(current);
    StatusButton *currentItem = dynamic_cast<StatusButton *>(currentWidget);
    NetWorkButton *netItem = dynamic_cast<NetWorkButton *>(currentWidget);
    if (currentItem)
        currentItem->setClickedStatus(SELECT);
    if (netItem) {
        netItem->setClickedStatus(SELECT);
    }
    if (previous) {
        QWidget *previousWidget = buttonListWidget->itemWidget(previous);
        StatusButton *previousItem = dynamic_cast<StatusButton *>(previousWidget);
        NetWorkButton *previousNetItem = dynamic_cast<NetWorkButton *>(previousWidget);
        if (previousItem)
            previousItem->setClickedStatus(NORMAL);
        if (previousNetItem) {
            previousNetItem->setClickedStatus(NORMAL);
        }
    }
}

void LockWidget::onButtonItemClicked(QListWidgetItem *item)
{
    QWidget *widget = buttonListWidget->itemWidget(item);
    StatusButton *currentItem = dynamic_cast<StatusButton *>(widget);
    if (currentItem) {
        currentItem->setClickedStatus(CLICKED);
        currentItem->clicked();
    }
    if (currentItem == m_powerManagerButton) {
        for (int i = 0; i < buttonListWidget->count(); i++) {
            if (!buttonListWidget->isRowHidden(i)) {
                buttonListWidget->setCurrentRow(i, QItemSelectionModel::SelectionFlag::Clear);
                buttonListWidget->currentItemChanged(buttonListWidget->item(i), buttonListWidget->item(i));
                break;
            }
        }
    }
    NetWorkButton *netItem = dynamic_cast<NetWorkButton *>(widget);
    if (netItem) {
        netItem->setClickedStatus(CLICKED);
        netItem->clicked();
    }
}

void LockWidget::onPowerItemClicked(QListWidgetItem *item)
{
    QWidget *widget = m_powerListWidget->itemWidget(item);
    PowerItemWidget *currentItem = dynamic_cast<PowerItemWidget *>(widget);
    if (currentItem) {
        currentItem->setSelected(CLICKED);
        currentItem->clicked();
    }
}

void LockWidget::onUsersInfoChanged()
{
    if (buttonListWidget && m_btnItemUser) {
        if (m_modelLockDialog->usersInfo().count() > 1 || m_modelLockDialog->findUserByName("*login")) {
            buttonListWidget->setItemHidden(m_btnItemUser, false);
        } else {
            buttonListWidget->setItemHidden(m_btnItemUser, true);
            if (m_userListWidget && !m_userListWidget->isHidden())
                m_userListWidget->hide();
        }
        if (m_userListWidget) {
            m_userListWidget->move(width() - (m_userListWidget->width()/2 + RIGHT_MARGIN*scale + (m_virKbButton->width() + buttonListWidget->spacing()*scale*2)*4),
                               height()- BOTTOM_MARGIN*scale - buttonListWidget->height() - buttonListWidget->spacing()*scale - m_userListWidget->height());
        }
    }
    UserInfoPtr ptrUser = m_modelLockDialog->findUserByName(m_curUserInfo.name());
    if (ptrUser) {
        m_curUserInfo = *ptrUser;
        if (authDialog) {
            authDialog->onCurUserInfoChanged(m_curUserInfo);
        }
    }
}

void LockWidget::onCurUserChanged(const QString &strUserName)
{
    UserInfoPtr ptrUser = m_modelLockDialog->findUserByName(strUserName);
    if (ptrUser && authDialog) {
        m_curUserInfo = *ptrUser;
        authDialog->onCurUserChanged(m_curUserInfo);
    }
    if (m_btnItemSession && m_curUserInfo.isLoggedIn()) {
        buttonListWidget->setItemHidden(m_btnItemSession, true);
    } else {
        buttonListWidget->setItemHidden(m_btnItemSession, false);
    }
}

void LockWidget::onUserChangedByManual(const QString &userName)
{
    if (m_modelLockDialog && m_modelLockDialog->findUserByName(userName)) {
        if (isCurUserSelf(userName)) {
            Q_EMIT m_modelLockDialog->setCurrentUser(userName);
        } else {
            SwitchToUser(userName);
        }
    } else {

    }
}

void LockWidget::onSessionChanged(const QString &strSession)
{
    if (buttonListWidget) {
        for (int n = 0; n < buttonListWidget->count(); n++) {
            QListWidgetItem *item = buttonListWidget->item(n);
            QWidget *widget = buttonListWidget->itemWidget(item);
            if (widget->objectName() == "BtnSession") {
                StatusButton *sButton = qobject_cast<StatusButton*>(widget);
                if (sButton) {
                    QString strCurSession = strSession;
                    QString sessionPrefix = strCurSession.left(strCurSession.indexOf('-'));
                    if(strCurSession == "ukui-wayland")
                        sessionPrefix = "ukui_wayland";
                    strCurSession = IMAGE_DIR + QString("badges/%1_badge.svg")
                            .arg(sessionPrefix.toLower());
                    QFile iconFile(strCurSession);
                    if(!iconFile.exists()){
                        strCurSession = IMAGE_DIR + QString("badges/unknown_badge.svg");
                    }
                    QPixmap ssIcon(strCurSession);
                    ssIcon = scaledPixmap(ssIcon);
                    ssIcon = ssIcon.scaled(32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                    ssIcon = PixmapToRound(ssIcon, 16);
                    sButton->setIcon(ssIcon);
                }
            }
        }
    }
}

void LockWidget::onUsdMediaKeysChanged(const QString &keys, const QString &value)
{
    if (keys == KEY_AREA_SCREENSHOT) {
        m_areaScreenShot = value;
    } else if (keys == KEY_AREA_SCREENSHOT2) {
        m_areaScreenShot2 = value;
    } else if (keys == KEY_SCREEN_SHOT) {
        m_screenShot = value;
    } else if (keys == KEY_SCREEN_SHOT2) {
        m_screenShot2 = value;
    } else if (keys == KEY_WINDOW_SCREENSHOT) {
        m_windowScreenshot = value;
    }
}

void LockWidget::onShowSessionListWidget()
{
    initSessionWidget();
    if (m_sessionListWidget && m_sessionListWidget->isHidden()) {
        m_sessionListWidget->show();
        m_sessionListWidget->setFocus();
        m_sessionButton->setClickedStatus(CLICKED);
        if (m_networkWidget && m_networkWidget->isVisible())
            m_networkWidget->hide();
        if (batteryWidget && batteryWidget->isVisible())
            batteryWidget->hide();
        if (m_userListWidget && m_userListWidget->isVisible())
            m_userListWidget->hide();
    } else {
        m_sessionListWidget->hide();
        m_sessionButton->setClickedStatus(NORMAL);
    }
}

void LockWidget::onShowBatteryWidget()
{
    if (!batteryWidget) {
        batteryWidget = new BatteryWidget(m_modelLockDialog, this);
        batteryWidget->setFixedSize(420, 112);
        if (batteryWidget) {
            batteryWidget->move(this->width() - batteryWidget->width() - RIGHT_MARGIN,
                                this->height() - batteryWidget->height() - BOTTOM_MARGIN - buttonListWidget->spacing()*2 - buttonListWidget->height());
        }
    }

    if (batteryWidget && batteryWidget->isHidden()) {
        batteryWidget->show();
        m_batteryonButton->setClickedStatus(CLICKED);
        if (m_networkWidget && m_networkWidget->isVisible())
            m_networkWidget->hide();
        if (m_userListWidget && m_userListWidget->isVisible())
            m_userListWidget->hide();
        if (m_sessionListWidget && m_sessionListWidget->isVisible())
            m_sessionListWidget->hide();
    } else {
        batteryWidget->hide();
        m_batteryonButton->setClickedStatus(NORMAL);
    }
}

void LockWidget::onShowUserListWidget()
{
    initUserWidget();
    if (m_userListWidget && m_userListWidget->isHidden()) {
        m_userListWidget->show();
        m_userListWidget->setFocus();
        m_userButton->setClickedStatus(CLICKED);
        if (m_networkWidget && m_networkWidget->isVisible())
            m_networkWidget->hide();
        if (batteryWidget && batteryWidget->isVisible())
            batteryWidget->hide();
        if (m_sessionListWidget && m_sessionListWidget->isVisible())
            m_sessionListWidget->hide();
    } else {
        m_userListWidget->hide();
        m_userButton->setClickedStatus(NORMAL);
    }
}

void LockWidget::onShowNetworkWidget()
{
    if (!m_networkWidget) {
        m_networkWidget = new MyNetworkWidget(this);
        m_networkWidget->installEventFilter(this);
    }
    m_networkWidget->setGeometry(this->width() - m_networkWidget->width() - RIGHT_MARGIN*scale,
                                 this->height() - m_networkWidget->height() - BOTTOM_MARGIN*scale - buttonListWidget->spacing()*scale - buttonListWidget->height(),
                           m_networkWidget->width(),
                           m_networkWidget->height());
    if (m_networkWidget && m_networkWidget->isVisible()) {
        m_networkWidget->hide();
        m_networkButton->setClickedStatus(NORMAL);
    } else {
        m_networkWidget->show();
        m_networkButton->setClickedStatus(CLICKED);
        if (m_userListWidget && m_userListWidget->isVisible())
            m_userListWidget->hide();
        if (batteryWidget && batteryWidget->isVisible())
            batteryWidget->hide();
        if (m_sessionListWidget && m_sessionListWidget->isVisible())
            m_sessionListWidget->hide();
    }
}

void LockWidget::onShowVirtualKeyboard()
{
    if(!m_virtualKeyboardWidget){
        m_virtualKeyboardWidget = new VirtualKeyboardWidget(this);
        m_virtualKeyboardWidget->installEventFilter(this);
        m_virtualKeyboardWidget->hide();

        connect(m_virtualKeyboardWidget, &VirtualKeyboardWidget::aboutToClose,
            this, &LockWidget::onHideVirkeyboard);
        connect(m_virtualKeyboardWidget, &VirtualKeyboardWidget::aboutToFloat,
                this, &LockWidget::onNetWorkResetLocation);
    }
    if (m_virtualKeyboardWidget->isHidden()) {
        if (batteryWidget && batteryWidget->isVisible())
            batteryWidget->hide();
        if (m_sessionListWidget && m_sessionListWidget->isVisible())
            m_sessionListWidget->hide();
        if (m_userListWidget && m_userListWidget->isVisible())
            m_userListWidget->hide();
        m_virtualKeyboardWidget->show();
        authDialog->setFocus();
    } else {
        m_virtualKeyboardWidget->hide();
    }

    if(!m_virtualKeyboardWidget->isHidden()){
        if(m_networkWidget && m_networkWidget->isVisible() && !m_virtualKeyboardWidget->getFloatStatus()) {
            m_networkWidget->move(this->width() - m_networkWidget->width() - 20,
                                        this->height() - m_networkWidget->height() - m_virtualKeyboardWidget->height());
            m_networkWidget->raise();
        } else {
        }
        m_virtualKeyboardWidget->raise();
    }
    m_virKbButton->setClickedStatus(NORMAL);
}

void LockWidget::onShowPowerListWidget()
{

    if (m_powerListWidget->isHidden()) {
        m_powerListWidget->show();
        authDialog->hide();
        m_powerListWidget->clearFocus();
    } else {
        m_powerListWidget->hide();
        authDialog->show();
        authDialog->setFocus();
    }
    if (m_userListWidget && m_userListWidget->isVisible())
        m_userListWidget->hide();
    if (m_virtualKeyboardWidget && m_virtualKeyboardWidget->isVisible())
        m_virtualKeyboardWidget->hide();
    if (batteryWidget && batteryWidget->isVisible())
        batteryWidget->hide();
    if (m_networkWidget && m_networkWidget->isVisible())
        m_networkWidget->hide();
    if (m_sessionListWidget && m_sessionListWidget->isVisible())
        m_sessionListWidget->hide();
    m_powerManagerButton->setClickedStatus(NORMAL);
}

void LockWidget::onSetVirkeyboardPos()
{
    if(m_virtualKeyboardWidget)
    {
        m_virtualKeyboardWidget->adjustGeometry();
    }
}

void LockWidget::onNetWorkResetLocation()
{
    if (m_networkWidget && m_networkWidget->isVisible()) {
        if (m_virtualKeyboardWidget->getFloatStatus()) {
            m_networkWidget->move(this->width() - m_networkWidget->width() - RIGHT_MARGIN,
                                              this->height() - m_networkWidget->height() - BOTTOM_MARGIN - buttonListWidget->spacing()  - buttonListWidget->height()) ;
        } else {
            m_networkWidget->move(this->width() - m_networkWidget->width() - RIGHT_MARGIN,
                                        this->height() - m_networkWidget->height() - m_virtualKeyboardWidget->height());
        }
        m_networkWidget->raise();
    }
    if (m_virtualKeyboardWidget && m_virtualKeyboardWidget->isVisible()) {
        m_virtualKeyboardWidget->raise();
    }
}

void LockWidget::onHideVirkeyboard()
{
    if(m_virtualKeyboardWidget && m_virtualKeyboardWidget->isVisible()) {
        m_virtualKeyboardWidget->hide();
    }
    if(m_networkWidget && m_networkWidget->isVisible()) {
        m_networkWidget->move(this->width() - m_networkWidget->width() - RIGHT_MARGIN,
                                    this->height() - m_networkWidget->height() - BOTTOM_MARGIN - buttonListWidget->spacing() - buttonListWidget->height());
    }
}

void LockWidget::onShowInhibitWarning(QStringList list, int type)
{
    m_blockWidget->setGeometry(this->geometry());
    m_blockWidget->setWarning(list, type);
    m_blockWidget->show();
    m_powerListWidget->hide();
}

void LockWidget::onMulUsersLogined(QString inhibitType)
{
    m_inhibitType = inhibitType;
    m_blockWidget->setGeometry(this->geometry());
    m_blockWidget->setTips(tr("Multiple users are logged in at the same time.Are you sure you want to %1 this system?").arg(inhibitType));
    m_blockWidget->show();
    m_powerListWidget->hide();
}

void LockWidget::onConfirmBtnClicked()
{
    m_blockWidget->hide();
    m_powerListWidget->hide();
    authDialog->show();
    buttonListWidget->show();
    Q_EMIT m_modelLockDialog->setPowerManager(m_inhibitType);
}

void LockWidget::onCancelBtnClicked()
{
    m_blockWidget->hide();
    m_powerListWidget->show();
}

void LockWidget::onCustomRequestAccount(QString account)
{
    if(m_modelLockDialog) {
        SwitchToUser(account);
    }
}

void LockWidget::onGetCustomPluginMsg(QString strMsg)
{
    QJsonParseError jsonParseError;
    const QJsonDocument jsonDoc = QJsonDocument::fromJson(strMsg.toUtf8(), &jsonParseError);
    if (jsonParseError.error != QJsonParseError::NoError) {
        qWarning()<<"Parse message json failed!!";
        return ;
    } else {
        QJsonObject rootObj = jsonDoc.object();
        if (rootObj.isEmpty()) {
             qWarning()<<"Message Json is null!!";
             return ;
        } else {
            QJsonObject contentObj = rootObj.value("Content").toObject();
            if (!contentObj.isEmpty()) {
                QJsonObject configObj = contentObj.value("Configures").toObject();
                if (!configObj.isEmpty()) {
                    m_isCustomDefault = configObj.value("DefaultAuth").toBool(false);
                    m_isShowNetwork = configObj.value("ShowNetwork").toBool(true);
                    m_isShowUserSwitch = configObj.value("ShowUserSwitch").toBool(true);
                }
            }
        }
    }
}

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

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

void LockWidget::onSessionActiveChanged(bool isActive)
{
    if (isActive) {
        if (m_timerChkActive && m_timerChkActive->isActive()) {
            m_timerChkActive->stop();
            if (this->isHidden()) {
                this->show();
                update();
            }
        }
//        if(authDialog) {
//            authDialog->stopAuth();
//        }
    }
}

void LockWidget::SwitchToUser(QString strUserName)
{
    if(m_modelLockDialog) {
        int nSwitchRet = Q_EMIT m_modelLockDialog->switchToUser(strUserName);
        if (nSwitchRet != 0) {
            Q_EMIT m_modelLockDialog->setCurrentUser(strUserName);
        } else {
//            if(authDialog) {
//                authDialog->stopAuth();
//            }
            if (!isCurUserSelf(strUserName) && !isHidden()) {
                this->hide();
                update();
                if (!m_timerChkActive) {
                    m_timerChkActive = new QTimer(this);
                    m_timerChkActive->setInterval(10*1000);
                    connect(m_timerChkActive, &QTimer::timeout, this, [&,this](){
                        if (this->isHidden()) {
                            this->show();
                        }
                        m_timerChkActive->stop();
                    });
                } else {
                    if (m_timerChkActive->isActive()) {
                        m_timerChkActive->stop();
                    }
                }
                m_timerChkActive->start();
            }
        }
    }
}
