#include "traywidget.h"

TrayWidget* TrayWidget::_MSelf = nullptr;
TrayWidget::TrayWidget(bool intel, BluetoothDbus *dBus, QWidget *parent):
    QWidget(parent),
    _SessionDBus(dBus),
    _config(new Config(this)),
    _Intel(intel)
{
    qDebug() << Q_FUNC_INFO;

//    窗管适配
    if (_Intel) {
        setProperty("useStyleWindowManager", false);
    } else {
        setProperty("useSystemStyleBlur", true);
        this->setAttribute(Qt::WA_TranslucentBackground);
    }
    if (QGuiApplication::platformName().startsWith(QLatin1String("wayland"),Qt::CaseInsensitive)) {
        this->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint);
    } else {
        MotifWmHints hints;
        hints.flags = MWM_HINTS_FUNCTIONS|MWM_HINTS_DECORATIONS;
        hints.functions = MWM_FUNC_ALL;
        hints.decorations = MWM_DECOR_BORDER;
        XAtomHelper::getInstance()->setWindowMotifHint(this->winId(), hints);
    }
    installEventFilter(this);
    this->setFocusPolicy(Qt::NoFocus);

    trayicon = new TrayIcon();
    connect(this, &TrayWidget::trayIconStatusChanged, trayicon, &TrayIcon::SetTrayIcon);
    connect(trayicon, &TrayIcon::showTayWidget, this, &TrayWidget::showUI);
    connect(trayicon, &TrayIcon::openBluetoothSettings, this, [=]{
         _SessionDBus->openBluetoothSettings();
    });
    connect(_SessionDBus, &BluetoothDbus::showTrayIcon, this, [=](bool show) {
        trayicon->SetAdapterFlag(show);
        if (!show)
            this->setVisible(show);
    });
    _SessionDBus->getTrayIconShow();

    connect(QApplication::desktop(), &QDesktopWidget::resized, this, [=] {
        setWidgetPosition();
    });
    connect(QApplication::desktop(), &QDesktopWidget::primaryScreenChanged, this, [=] {
        setWidgetPosition();
    });

    QGSettings *setttt = new QGSettings(QString("org.ukui.SettingsDaemon.plugins.xsettings").toLocal8Bit());
    connect(setttt,&QGSettings::changed, this, [=] (const QString &key) {
        if (key == "scalingFactor") {
            repaint();
        }
    });

    if(QGSettings::isSchemaInstalled("org.ukui.style")) {
        StyleSettings = new QGSettings("org.ukui.style");
        connect(StyleSettings,&QGSettings::changed,this,&TrayWidget::GSettingsChanges);
    }

    const QByteArray transparency_id(TRANSPARENCY_SETTINGS);
    if(QGSettings::isSchemaInstalled(transparency_id)) {
        transparency_gsettings = new QGSettings(transparency_id);
    }
    if(QGSettings::isSchemaInstalled(transparency_id)) {
        getTransparency();
        connect(transparency_gsettings,&QGSettings::changed,this,[=](QString key) {
            qDebug() << Q_FUNC_INFO << key;
            if (key == QString(TRANSPARENCY_KEY)) {
                getTransparency();
                this->update();
            }
        });
    }
    QPalette palette;
    if(StyleSettings->get("style-name").toString() == "ukui-light" || StyleSettings->get("style-name").toString() == "ukui-default"){
        palette.setColor(QPalette::Background,QColor(255,255,255, 0));
    }else{
        QColor col(QPalette::Base);
        col.setAlpha(tran);
        palette.setColor(QPalette::Background, col);
    }

    this->setPalette(palette);
    this->setFixedSize(420,520);
    this->setAutoFillBackground(true);
    this->setWindowIcon(QIcon::fromTheme("bluetooth"));
    this->setWindowTitle(tr("bluetooth"));
    pairedDevices = _SessionDBus->getPairedDevices();
    pairedList = _SessionDBus->getPairedDevicesList();
    InitMemberVariables();
    connectUISignalAndSlot();
    layoutAddAllPairedDev();
    if (_Intel) {
        QRect availableGeometry = QApplication::screens().at(0)->geometry();
        qDebug() << availableGeometry.x() << availableGeometry.y();
        move((availableGeometry.x() + (availableGeometry.width() - width())/2), (availableGeometry.y() + (availableGeometry.height() - height())/2));
    }
    emit trayIconStatusChanged(_SessionDBus->isPowered());
    openBluetoothSlot(_SessionDBus->isPowered());
}

TrayWidget *TrayWidget::self( BluetoothDbus *dbus, bool intel)
{
    qDebug() << Q_FUNC_INFO;
    if (!_MSelf) {
        _MSelf = new TrayWidget(intel, dbus, nullptr);
    }
    return _MSelf;
}

TrayWidget::~TrayWidget()
{

}

void TrayWidget::getTransparency() {
    double proportion = transparency_gsettings->get(TRANSPARENCY_KEY).toDouble();
    proportion = ((proportion > 0.85) ? 1 : (proportion + 0.15));
    qDebug() << Q_FUNC_INFO << proportion;
    tran = proportion * 255;
}

void TrayWidget::openBluetoothSlot(bool v)
{
    emit trayIconStatusChanged(v);

    if (v != _SessionDBus->isPowered())
        _SessionDBus->setDefaultAdapterPower(v);

    if (!_Intel && !pairedDevices.size())
        return;
    if (_Intel) {
        if (v) {
            _MStackedWidget->setCurrentIndex(0);
        } else {
            _MStackedWidget->setCurrentIndex(1);
        }
        return;
    }
    _MStackedWidget->setVisible(v);
    lineFrame->setVisible(v);
    if (_MSelf) {
        _MSelf->setFixedHeight(v ? selfHeight : 102);
        if (QLocale::system().name() == "bo_CN")
            _NomalWidget->setFixedHeight(60 + selfHeight - 184);
        else
            _NomalWidget->setFixedHeight((pairedList.size()>= 7) ? (50 + selfHeight - 160) : (55 + selfHeight - 160));
    }
    setWidgetPosition();
    update();
}



void TrayWidget::setWidgetPosition()
{
    #define MARGIN 8

    //menu->exec();
    int width = this->width();
    int height= this->height();
    qDebug()<<"menu 's  width  height"<<width<<height;

    QDBusInterface iface("org.ukui.panel",
                         "/panel/position",
                         "org.ukui.panel",
                         QDBusConnection::sessionBus());
    if (!iface.isValid())
        return;
    QDBusReply<QVariantList> reply=iface.call("GetPrimaryScreenGeometry");
    //reply获取的参数共5个，分别是 主屏可用区域的起点x坐标，主屏可用区域的起点y坐标，主屏可用区域的宽度，主屏可用区域高度，任务栏位置

    if (!iface.isValid() || !reply.isValid() || reply.value().size()<5) {
        qCritical() << QDBusConnection::sessionBus().lastError().message();
        this->setGeometry(0,0,width,height);
    }

//    qDebug()<<reply.value().at(4).toInt();
    QVariantList position_list=reply.value();

    switch(reply.value().at(4).toInt()){
    case 1:
        //任务栏位于上方
        kdk::WindowManager::setGeometry(this->windowHandle(),
                                        QRect(position_list.at(0).toInt()+position_list.at(2).toInt()-width-MARGIN,
                                              position_list.at(1).toInt()+MARGIN,
                                              width,
                                              height));
        break;
        //任务栏位于左边
    case 2:
        kdk::WindowManager::setGeometry(this->windowHandle(),
                                        QRect(position_list.at(0).toInt()+MARGIN,
                                              position_list.at(1).toInt()+reply.value().at(3).toInt()-height-MARGIN,
                                              width,
                                              height));
        break;
        //任务栏位于右边
    case 3:
        kdk::WindowManager::setGeometry(this->windowHandle(),
                                        QRect(position_list.at(0).toInt()+position_list.at(2).toInt()-width-MARGIN,
                                              position_list.at(1).toInt()+reply.value().at(3).toInt()-height-MARGIN,
                                              width,
                                              height));
        break;
        //任务栏位于下方
    default:
        kdk::WindowManager::setGeometry(this->windowHandle(),
                                        QRect(position_list.at(0).toInt()+position_list.at(2).toInt()-width-MARGIN,
                                              position_list.at(1).toInt()+reply.value().at(3).toInt()-height-MARGIN,
                                              width,
                                              height));
        break;
    }
}

void TrayWidget::GSettingsChanges(const QString &key)
{
    qDebug() << Q_FUNC_INFO << key;
    if(key == "styleName"){
        QPalette palette;
        QPalette pl;
        QPalette _pl;
        getTransparency();
        if(StyleSettings->get("style-name").toString() != "ukui-dark"){
            _pl.setColor(QPalette::WindowText,Qt::black);
            palette.setColor(QPalette::Background,QColor(255,255,255,0));
        }else{
            QColor col(QPalette::Base);
            col.setAlpha(tran);
            _pl.setColor(QPalette::WindowText,Qt::white);
            palette.setColor(QPalette::Background, col);
        }
        this->setPalette(palette);
        _MLabel->setPalette(_pl);
        this->update();
    }
    if (key == "switch") {
        if (_config.gsetting->get("switch").toString() != _SessionDBus->isPowered())
            _MBtn->setChecked(_config.gsetting->get("switch").toBool());
    }
}

void TrayWidget::InitMemberVariables()
{
    _MBtn           = new KSwitchButton(this);
    _MLoad          = new QLabel(this);
    _MStackedWidget = new QStackedWidget(this);
    _MLabel         = new QLabel(this);
    _MMainLayout    = new QVBoxLayout(this);
    _MSettingBtn    = new BluetoothSettingLabel(this);
    _MIconTimer = new QTimer(this);
    _MIconTimer->setInterval(500);
    connect(_MIconTimer,&QTimer::timeout,this,[=]{
        if (iconFlag == 0)
            iconFlag = 7;
        iconFlag--;
        QPixmap pxmp = QIcon::fromTheme("ukui-loading-" + QString::number(iconFlag) + "-symbolic").pixmap(18,18);
        if(StyleSettings->get("style-name").toString() == "ukui-dark")
            pxmp = _config.loadSvg(pxmp, Config::PixmapColor::WHITE);
        _MLoad->setPixmap(pxmp);
        update();
    });

    _MLoad->setVisible(false);
    _MBtn->setChecked(_SessionDBus->isPowered());
    _MBtn->setFocusPolicy(Qt::NoFocus);

    connect(_MSettingBtn, &BluetoothSettingLabel::clickSignal, this, [=]{
        _SessionDBus->openBluetoothSettings();
    });
    connect(_MSettingBtn,&BluetoothSettingLabel::hideFeature,this,[=]{
        _MSelf->hide();
    });
    connect(_MBtn, SIGNAL(stateChanged(bool)), this, SLOT(openBluetoothSlot(bool)));

    QHBoxLayout *topLayout = new QHBoxLayout();
    topLayout->setContentsMargins(24,16,25,12);
    topLayout->setSpacing(0);

    InitErrorWidget();
    InitNomalWidget();

    _MStackedWidget->setFixedSize(420,445);
    _MStackedWidget->addWidget(_NomalWidget);
    if (_Intel)
        _MStackedWidget->addWidget(_ErrorWidget);
    _MStackedWidget->setCurrentIndex(0);

    if (QLocale::system().name() == "bo_CN")
        _MLabel->setFixedSize(60,38);
    else
        _MLabel->setFixedSize(60,25);
    QPalette _pl;
    if(StyleSettings->get("style-name").toString() == "ukui-light" || StyleSettings->get("style-name").toString() == "ukui-default"){
        _pl.setColor(QPalette::WindowText, Qt::black);
    }else{
        _pl.setColor(QPalette::WindowText, Qt::white);
    }
    _MLabel->setPalette(_pl);
    _MLabel->setText(tr("Bluetooth"));

    _MMainLayout->setMargin(0);
    _MMainLayout->setContentsMargins(0,0,0,0);
    _MMainLayout->setSpacing(0);

    topLayout->addWidget(_MLabel);
    topLayout->addStretch(1);
    topLayout->addWidget(_MBtn);
    topLayout->addWidget(_MLoad);

    lineFrame = new KyHLine(this);
    lineFrame2 = new KyHLine(this);

    _MMainLayout->addLayout(topLayout);
    _MMainLayout->addWidget(lineFrame2);
    _MMainLayout->addWidget(_MStackedWidget);
    _MMainLayout->addWidget(lineFrame);
    _MMainLayout->addWidget(_MSettingBtn);
}

void TrayWidget::InitNomalWidget()
{
    _NomalWidget    = new QWidget(_MStackedWidget);
    _PairedWidget   = new QWidget(_NomalWidget);
    _PairedLayout   = new QVBoxLayout(_PairedWidget);
    _ScrollArea     = new QScrollArea(_NomalWidget);
    QVBoxLayout *_ErrorWidgetLayout = new QVBoxLayout(_NomalWidget);
    QVBoxLayout *_ErrorWidgetChildLayout = new QVBoxLayout(_NomalWidget);
    QLabel *_ErrorWidgetTipLabel = new QLabel(_NomalWidget);

    _ErrorWidgetLayout->setAlignment(0);
    _ErrorWidgetLayout->setContentsMargins(8,12,8,0);
    _ErrorWidgetLayout->setSpacing(5);

    _ErrorWidgetChildLayout->setAlignment(0);
    _ErrorWidgetChildLayout->setContentsMargins(16,0,0,0);

    if (QLocale::system().name() == "bo_CN")
        _ErrorWidgetTipLabel->setFixedSize(420,38);
    else
        _ErrorWidgetTipLabel->setFixedSize(420,25);
    _ErrorWidgetTipLabel->setText(tr("My Device"));
    QPalette pl;
    pl.setColor(QPalette::WindowText, QColor("#818181"));
    _ErrorWidgetTipLabel->setPalette(pl);

    _NomalWidget->setFixedWidth(420);
    _PairedWidget->setFixedWidth(420);
    _PairedWidget->setAttribute(Qt::WA_TranslucentBackground);

    //统一滑动模块的样式
    _ScrollArea->setAttribute(Qt::WA_TranslucentBackground);
    _ScrollArea->setProperty("drawScrollBarGroove",false);
    _ScrollArea->verticalScrollBar()->setProperty("drawScrollBarGroove",false);

    _ScrollArea->setFixedWidth(420);
    _ScrollArea->setWidgetResizable(true);
    _ScrollArea->setAlignment(Qt::AlignCenter);
    _ScrollArea->setWidget(_PairedWidget);
    _ScrollArea->setFrameShape(QFrame::NoFrame);
    _ScrollArea->horizontalScrollBar()->hide();
    _ScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    _ScrollArea->setPalette(QColor(Qt::transparent));
    _ScrollArea->setFocusPolicy(Qt::NoFocus);

    _PairedLayout->setAlignment(0);
    _PairedLayout->setContentsMargins(0,0,0,0);
    _PairedLayout->setSpacing(2);

    _ErrorWidgetChildLayout->addWidget(_ErrorWidgetTipLabel);
    _ErrorWidgetLayout->addLayout(_ErrorWidgetChildLayout);
    _ErrorWidgetLayout->addWidget(_ScrollArea);
}

void TrayWidget::InitErrorWidget()
{
    _ErrorWidget       = new QWidget(_MStackedWidget);
    QHBoxLayout* _ErrorWidgeeLayout = new QHBoxLayout(_ErrorWidget);
    QLabel* _ErrorIcon  = new QLabel(_ErrorWidget);

    _ErrorWidget->setFixedSize(446,420);

    _ErrorWidgeeLayout->setAlignment(0);
    _ErrorWidgeeLayout->setContentsMargins(0,0,0,0);
    _ErrorWidgeeLayout->setSpacing(0);

    _ErrorIcon->setPixmap(QPixmap("/usr/share/ukui-bluetooth/no-bluetooth.svg"));

    _ErrorWidgeeLayout->addWidget(_ErrorIcon,1,Qt::AlignCenter);
    if (!_Intel)
        _ErrorIcon->setVisible(false);
}

void TrayWidget::connectUISignalAndSlot()
{
    connect(_SessionDBus,&BluetoothDbus::devRemoveSignal,this,&TrayWidget::removePairedDevUIByAddress);
    connect(_SessionDBus,&BluetoothDbus::adapterAddSignal,this,&TrayWidget::updatePairedDev);
    connect(_SessionDBus,&BluetoothDbus::powerProgressSignal, this, [=](bool inProgress) {
        _MBtn->setVisible(!inProgress);
        _MLoad->setVisible(inProgress);
        if (inProgress && !_MIconTimer->isActive())
            _MIconTimer->start();
        if (!inProgress && _MIconTimer->isActive())
            _MIconTimer->stop();
    });
    connect(_SessionDBus,&BluetoothDbus::powerChangedSignal,this,[=](bool value){
        qDebug() << Q_FUNC_INFO << value <<__LINE__;
        if (!_Intel)
            setWidgetPosition();
        if (value != _MBtn->isChecked())
            _MBtn->setChecked(value);
        emit trayIconStatusChanged(value);
        _SessionDBus->getDefaultAdapterPairedDevices();
        updatePairedDev();
    });
    connect(_SessionDBus,&BluetoothDbus::AdapterChangedSignal,this,[=](QString address){
        Q_UNUSED(address)
        _MBtn->setChecked(_SessionDBus->isPowered());
        updatePairedDev();
    });
}

void TrayWidget::SendMessage(QString name, bool connected)
{
    QString text;
    if (connected) {
        text = QString(tr("The connection with the Bluetooth device “%1” is successful!").arg(name));

    } else {
        text = QString(tr("Bluetooth device “%1” disconnected!").arg(name));
    }
    Config::SendNotifyMessage(text);
}

/************************************************
 * @brief  已配对的设备添加到布局中显示
 * @param  null
 * @return null
*************************************************/
void TrayWidget::layoutAddAllPairedDev()
{
    bool isNull = true;
    int count = 0;
    qDebug() << Q_FUNC_INFO << pairedDevices.size() << __LINE__  << pairedDevices;
    if (!_PairedWidget->findChildren<QDevItem *>().size()) {
        for (auto item : pairedList) {
            _SessionDBus->getDevConnectStatus(item);
            QDevItem *dev = new QDevItem(item, pairedDevices.value(item), _SessionDBus->isConnected(item), _PairedWidget);
            connect(_SessionDBus, &BluetoothDbus::devConnectStatusSignal, dev, [=](QString address, bool connected) {
                qDebug() << " +++ compare " << address << item;
                if (address != item)
                    return;
                if (dev)
                    dev->connectedChangedSlot(connected);
            });
            connect(_SessionDBus, &BluetoothDbus::devLaunchConnectingSignal, dev, [=](QString address) {
               if (address != item)
                   return;
               if (dev)
                   dev->startIconTimer();
            });
            connect(dev, &QDevItem::devConnect, this, [=](bool connectdev){
               if(connectdev)
                  _SessionDBus->devConnect(item);
               else
                   _SessionDBus->devDisconnect(item);
            });
            _PairedLayout->addWidget(dev);
            isNull = false;
            count++;
        }
        _PairedLayout->addStretch();
        if (_Intel)
            return;
        isNull = isNull || !_MBtn->isChecked();
        _MStackedWidget->setVisible(!isNull);
        lineFrame->setVisible(!isNull);
        if (_MSelf) {
            if (QLocale::system().name() == "bo_CN")
                selfHeight = 184 + count * 52;
            else
                selfHeight = 160 + count * 52;
            if (count >= 7)
                selfHeight = 515;
            _MSelf->setFixedHeight((isNull ? 102 : selfHeight));
            if (QLocale::system().name() == "bo_CN")
                _NomalWidget->setFixedHeight(60 + selfHeight - 184);
            else
                _NomalWidget->setFixedHeight((count >= 7) ? (50 + selfHeight - 160) : (55 + selfHeight - 160));
        }
        update();
        setWidgetPosition();
    }
}

void TrayWidget::layoutAddOnePairedDev(QString name, bool paired)
{
    updatePairedDev();
    if (paired)
        SendMessage(name, paired);
}

void TrayWidget::updatePairedDev() {
    pairedDevices = _SessionDBus->getPairedDevices();
    pairedList = _SessionDBus->getPairedDevicesList();
    clearPairedWidget();
    layoutAddAllPairedDev();
}

/************************************************
 * @brief  清空现在显示的所有配对设备UI
 * @param  null
 * @return null
*************************************************/
void TrayWidget::clearPairedWidget()
{
    qDebug() << Q_FUNC_INFO << __LINE__;
    QLayoutItem *child;
    QDevItem *tmp;
    while ((child = _PairedLayout->takeAt(0)) != 0)
    {
        if(child->isEmpty())
            return;
        if(child->widget())
        {
            tmp = qobject_cast<QDevItem*>(child->widget());
            disconnect(tmp, &QDevItem::devConnect, nullptr, nullptr);
            disconnect(_SessionDBus, &BluetoothDbus::devConnectStatusSignal, nullptr, nullptr);
            child->widget()->setParent(NULL);
        }
        delete child;
        delete tmp;
        tmp = nullptr;
        child = nullptr;
    }
}

/************************************************
 * @brief  根据BluezQt::DevicePtr清空现在显示的配对设备UI
 * @param  devPtr 配对设备指针
 * @return null
*************************************************/
void TrayWidget::removePairedDevUIByAddress(QString address)
{
    qDebug() << Q_FUNC_INFO << pairedDevices << __LINE__;
    if (!pairedList.contains(address))
        return;
    pairedList.removeAll(address);
    if (!pairedDevices.contains(address))
        return;
    qDebug() << Q_FUNC_INFO << address << __LINE__;
    QDevItem *item = _PairedWidget->findChild<QDevItem *>(address);
    if (item) {
        if(item->isConnected())
            SendMessage(pairedDevices.value(address).at(0), false);
        _PairedLayout->removeWidget(item);
        item->setParent(NULL);
        item->deleteLater();
        item = nullptr;
    }
    pairedDevices.remove(address);
    updatePairedDev();
}

void TrayWidget::showUI()
{
    if (this->isActiveWindow()) {
        hide();
        return;
    }

    //2209中窗管在hide界面时会刷新属性，需要重新设置无图标属性
    const KWindowInfo info(this->winId(), NET::WMState);
    if (!info.hasState(NET::SkipTaskbar) || !info.hasState(NET::SkipPager))
        KWindowSystem::setState(this->winId(), NET::SkipTaskbar | NET::SkipPager);

    if (!_Intel) {
        int count = pairedList.size();
        if (QLocale::system().name() == "bo_CN")
            selfHeight = 184 + count * 52;
        else
            selfHeight = 160 + count * 52;
        if (count >= 7)
            selfHeight = 515;
        this->setFixedHeight(((_MBtn->isChecked()) && (count != 0) ?  selfHeight : 102));
        if (QLocale::system().name() == "bo_CN")
            _NomalWidget->setFixedHeight(60 + selfHeight - 184);
        else
            _NomalWidget->setFixedHeight((count >= 7) ? (50 + selfHeight - 160) : (55 + selfHeight - 160));
        showNormal();
        raise();
        activateWindow();
        setWidgetPosition();
        return;
    }
    QApplication::desktop()->update();
    QRect availableGeometry = QApplication::screens().at(0)->geometry();
    qDebug() << availableGeometry.x() << availableGeometry.y();
    move((availableGeometry.x() + (availableGeometry.width() - width())/2), (availableGeometry.y() + (availableGeometry.height() - height())/2));
    showNormal();
}

void TrayWidget::kbTabEvent() {
    QList<QDevItem*> l = _PairedWidget->findChildren<QDevItem *>();
    int size = l.size();

    if (!_MBtn->isChecked())
        size = 0;

    if (++pressCnt > 3)
        pressCnt = 1;

    qDebug() << "press Tab"<< pressCnt;

    switch (pressCnt) {
    case 1:
        //预选框唯一处理
        MBtnFocused = false;
        this->update();
        kbUDEvent(true);
        break;
    case 2:
        if (listCnt >= 1)
            l.at(listCnt - 1)->setFocusStyle(false);
        MBtnFocused = false;
        this->update();
        _MSettingBtn->setFocusStyle(true);
        scrollCnt = (size - 7) > 0 ? (size - 7) : 0;
        listCnt = 0;
        break;
    case 3:
        _MSettingBtn->setFocusStyle(false);
        MBtnFocused = true;
        this->update();
        scrollCnt = 0;
        break;
    default:
        return;
    }
}

void TrayWidget::kbEnterEvent() {
    if (pressCnt == 0)
        return;

    QList<QDevItem*> l = _PairedWidget->findChildren<QDevItem *>();

    if(pressCnt == 3 &&
       !_MIconTimer->isActive() &&
       _MBtn->isChecked() == _SessionDBus->isPowered())
    {
        _SessionDBus->setDefaultAdapterPower(!_MBtn->isChecked());
    } else if (pressCnt == 2) {
        _SessionDBus->openBluetoothSettings();
        this->hide();
    }
    else {
        if(listCnt < 1)
            return;
        l.at(listCnt - 1)->pressEnterCallback();
    }
}

void TrayWidget::kbUDEvent(bool opt) {
    if (pressCnt != 1)
        return;
    QList<QDevItem*> l = _PairedWidget->findChildren<QDevItem *>();
    int size = l.size();

    if (opt) {
        if (++listCnt > size) {
            l.at(size - 1)->setFocusStyle(false);
            listCnt = 1;
            scrollCnt = 0;
        }
        qDebug() << "press Down" << listCnt;
    } else {
        if (--listCnt < 1) {
            l.at(0)->setFocusStyle(false);
            listCnt = size;
            scrollCnt = size - 7;
        }
        qDebug() << "press Up" << listCnt;
    }

    if (listCnt >= 2)
        l.at(listCnt - 2)->setFocusStyle(false);
    if (listCnt < size)
        l.at(listCnt)->setFocusStyle(false);
    l.at(listCnt - 1)->setFocusStyle(true);

    //自动翻页
    if(opt && listCnt == 1) {
        _ScrollArea->verticalScrollBar()->setSliderPosition(0);
    }
    if (!opt && listCnt == size) {
        _ScrollArea->verticalScrollBar()->setSliderPosition((size - 7) * 52);
        return;
    }
    if (opt && listCnt > 7) {
        ++scrollCnt;
        qDebug() << "翻页";
        _ScrollArea->verticalScrollBar()->setSliderPosition(52 * (listCnt - 7));
    }
    if (!opt && listCnt <= size - 7) {
        --scrollCnt;
        qDebug() << "翻页";
        _ScrollArea->verticalScrollBar()->setSliderPosition(52 * (listCnt - 7));
    }
}
bool TrayWidget::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::ActivationChange)
    {
        if(QApplication::activeWindow() != this)
        {
            this->hide();
        }
    }
    return QWidget::eventFilter(o,e);
}

void TrayWidget::paintEvent(QPaintEvent *event) {
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::transparent);
    QColor col;
    if(StyleSettings->get("style-name").toString() != "ukui-dark"){
        col = QColor(255,255,255);
    } else{
        col = QColor(35,36,38);
    }
    QPainterPath rectPath;

    if (_Intel)
        rectPath.addRect(this->rect());
    else {
        col.setAlpha(tran);
        rectPath.addRoundedRect(this->rect(),12,12);
    }

    painter.setBrush(col);
    painter.drawPath(rectPath);

    //焦点预选框
    if (!MBtnFocused)
        return;
    QPainter pt(this);
    QColor color = QColor("#818181");
    pt.setPen(color);
    QRect rect;
    rect.setLeft(_MBtn->geometry().left() - 1);
    rect.setTop(_MBtn->geometry().top() - 1);
    rect.setWidth(_MBtn->width() + 2);
    rect.setHeight(_MBtn->height() + 2);
    pt.setRenderHint(QPainter::Antialiasing);
    pt.drawRoundedRect(rect,12,12,Qt::AbsoluteSize);
}

void TrayWidget::keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
    case Qt::Key_Tab:
        kbTabEvent();
        break;
    case Qt::Key_Down:
        kbUDEvent(true);
        break;
    case Qt::Key_Up:
        kbUDEvent(false);
        break;
    case Qt::Key_Enter:
    case Qt::Key_Return:
    case Qt::Key_Space:
        qDebug() << "press Enter";
        kbEnterEvent();
        break;
    case Qt::Key_Escape:
        qDebug() << "press Esc";
        this->hide();
        break;
    default:
        break;
    }
}

void TrayWidget::showEvent(QShowEvent *event) {
    Q_UNUSED(event)
    _ScrollArea->clearFocus();
    _PairedWidget->clearFocus();
}

void TrayWidget::hideEvent(QHideEvent *event) {
    //初始化键盘交互界面，清除操作记录
    Q_UNUSED(event)
    if (pressCnt == 0)
        return;
    QList<QDevItem*> l = _PairedWidget->findChildren<QDevItem *>();
    int size = l.size();

    if (!_MBtn->isChecked())
        size = 0;

    switch (pressCnt) {
    case 1:
        if(listCnt < 1)
            return;
        l.at(listCnt - 1)->setFocusStyle(false);
        listCnt = 0;
        break;
    case 2:
        _MSettingBtn->setFocusStyle(false);
        break;
    case 3:
        MBtnFocused = false;
        this->update();
        break;
    default:
        break;
    }
    pressCnt = 0;
    _ScrollArea->verticalScrollBar()->setSliderPosition(0);
}
