#include "sessiondbusregister.h"
#include <QMap>
#include <QSet>
#include <QDateTime>

#include "tmpdevclear.h"
#include "globalsize.h"

#define TIMER_TIMEOUT   (2*1000)

extern bool global_systemSleepFlag;
extern qint64 global_InitBluetoothTime;
extern Daemon * global_daemon;


QString global_active_connection_dev = "";
bool global_activeconn_switch = true;
static QTimer * static_active_timer = nullptr;
static QSet<QString> static_black_activeconn_dev;

bool global_DefaultAdapterPower = true;

//当蓝牙power有关闭到开启，需要回连
bool global_need_reconnect = false;

static bool isScan = false;
SessionDbusRegister * global_sess = nullptr;
static QMap<QString, DelayStruct *> static_delays;
static QMap<QString,qint64> devConnectAgainMap;

//检测bluez重启参数
//bluez重启(停止然后启动)后，关闭适配器蓝牙，移除蓝牙适配器，新增蓝牙适配器
static int static_bluezreboot_power = -1;

//仅适合单线程模式
int cancelEmitDevStatus(QString addr)
{
    DelayStruct * p = static_delays.value(addr, nullptr);
    if(nullptr != p)
    {
        p->close();
        //从qmap删除
        static_delays.remove(addr);
    }
    return 0;
}

DelayStruct::DelayStruct(BluezQt::DevicePtr dev, QObject *parent /*= nullptr*/):QObject(parent)
{
    m_dev = dev;
    m_TimerID = this->startTimer(TIMER_TIMEOUT);
}

DelayStruct::~DelayStruct()
{
    qDebug() << Q_FUNC_INFO << __LINE__;
    m_dev = nullptr;
}

void  DelayStruct::close(void)
{
    qDebug() << Q_FUNC_INFO << __LINE__;
    this->killTimer(m_TimerID);
    this->deleteLater();
}

void DelayStruct::timerEvent( QTimerEvent *event)
{
    qDebug() << Q_FUNC_INFO << __LINE__;
    if(nullptr != m_dev && nullptr != global_sess)
    {
        qDebug() << Q_FUNC_INFO << __LINE__ << m_dev->address() << m_dev->isConnected();
        emit global_sess->devConnectStatusSignal(m_dev->address(), m_dev->isConnected());
        if (m_dev->isConnected() && m_dev->isPaired()) {
            Config::writeKeyFile(m_dev->address(),m_dev->name(),m_dev->type());
        }
    }
    //从qmap删除
    if(nullptr != m_dev)
    {
        static_delays.remove(m_dev->address());
    }

    this->close();
}


static void init_static_sess(SessionDbusRegister * p)
{
    global_sess = p;
}

void addDelay(BluezQt::DevicePtr dev)
{
    if(nullptr != dev)
    {
        //非手机、电脑没有必要延迟发送设备状态
        if(dev->type() != BluezQt::Device::Phone && dev->type() != BluezQt::Device::Computer)
        {
            qDebug() << Q_FUNC_INFO << __LINE__ << dev->address() << dev->isConnected();
            emit global_sess->devConnectStatusSignal(dev->address(), dev->isConnected());
            if (dev->isConnected() && dev->isPaired()) {
                Config::writeKeyFile(dev->address(), dev->name(), dev->type());
            }
        }
        else
        {
            QString key = dev->address();
            //未找到
            if(static_delays.find(key) == static_delays.end())
            {
                DelayStruct * p = new DelayStruct(dev);
                static_delays[key] = p;
            }
        }
    }
}

static bool existDelay(QString key)
{
    return (static_delays.find(key) != static_delays.end());
}

////////////////////////////////////////////SessionDbusRegister////////////////////////////////////
////////////////////////////////////////////SessionDbusRegister////////////////////////////////////


static inline bool isAvailableAddress(QString addr) {
    if (addr.isEmpty() || addr.isNull())
        return false;

    return true;
}

SessionDbusRegister::SessionDbusRegister(QObject *parent) : QObject(parent)
{
    qInfo() << Q_FUNC_INFO ;
    init_static_sess(this);
    if (InterfaceAlreadyExists()) {
        QDBusConnection sessionDbus = QDBusConnection::sessionBus();
        if (!sessionDbus.registerService("com.ukui.bluetooth")) {
            qCritical() << "QDbus register service failed reason:" << sessionDbus.lastError();
        }

        if (!sessionDbus.registerObject("/com/ukui/bluetooth", "com.ukui.bluetooth", this, QDBusConnection::ExportAllSlots|QDBusConnection::ExportAllSignals)){
            qCritical() << "QDbus register object failed reason:" << sessionDbus.lastError();
        }
    }
    //控制面板文件发送设备和状态信号改变的记录监听
    QDBusConnection::sessionBus().connect("com.ukui.bluetooth",
                                         "/com/ukui/bluetooth",
                                         "com.ukui.bluetooth",
                                         "statusChanged",
                                         this,
                                         SLOT(dealStatusChanged(QString, QString,QString)));
}

SessionDbusRegister::~SessionDbusRegister()
{

}

bool SessionDbusRegister::InterfaceAlreadyExists()
{
    QDBusConnection conn = QDBusConnection::sessionBus();
    if (!conn.isConnected())
        return 0;

    QDBusReply<QString> reply = conn.interface()->call("GetNameOwner", "com.ukui.bluetooth");
    return reply.value() == "";
}

void SessionDbusRegister::AudioDevConnectFunc(BluezQt::DevicePtr dev)
{
    qDebug () << Q_FUNC_INFO  << "START" << __LINE__;

    if (dev)
    {
        if (dev.data()->type() == BluezQt::Device::AudioVideo ||
            dev.data()->type() == BluezQt::Device::Headphones ||
            dev.data()->type() == BluezQt::Device::Headset    ) {

            BluezQt::AdapterPtr MDevAdapter = dev.data()->adapter();

            for (auto tmpdev : MDevAdapter.data()->devices()) {
                //id 相同，跳过，避免出现配对后发送断开连接请求
                if (tmpdev->address() == dev->address())
                    continue;

                qDebug () << Q_FUNC_INFO  << "=======================" << tmpdev.data()->name() << __LINE__;
                if (tmpdev.data()->isConnected() && tmpdev.data()->isPaired()) {
                    if (tmpdev.data()->type() == BluezQt::Device::AudioVideo ||
                        tmpdev.data()->type() == BluezQt::Device::Headphones ||
                        tmpdev.data()->type() == BluezQt::Device::Headset    ) {

                        qDebug () << Q_FUNC_INFO  << "==================disconn=====" << tmpdev.data()->name() << __LINE__;
                        BluezQt::PendingCall *pending = tmpdev.data()->disconnectFromDevice();
                        qDebug () << Q_FUNC_INFO  << "=======================" << __LINE__;
                        connect(pending,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *call){
                            qDebug () << Q_FUNC_INFO  << "=================conn======" << dev.data()->name() << call << __LINE__;

                            if (!call->error()) {
                                BluezQt::PendingCall *call = dev.data()->connectToDevice();
                                GlobalSize::refBlueDevActive(dev->address());
                                connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
                                    qDebug () << Q_FUNC_INFO << callReturn->error() << "   " << callReturn->errorText() << __LINE__;
                                    GlobalSize::unrefBlueDevActive(dev->address());
                                    if (callReturn->error()) {
                                    	emit devOperateErrorSignal(dev.data()->address(),
                                                                   callReturn->error(),
                                                                   callReturn->errorText());
                                    }
                                    else
                                    {
                                        //主动连接成功后，发送连接成功信号
                                        addDelay(dev);
                                    }

                                    //主动连接全部完成后，启动扫描
                                    if(GlobalSize::BlueDevActiveSize() == 0)
                                    {
                                         qDebug () << Q_FUNC_INFO  << ::isScan << "===================startDiscovery====" << ::isScan << __LINE__;
                                        if (::isScan) {
                                            BluezQt::PendingCall * start_call = Daemon::_DefualtAdapter.data()->startDiscovery();
                                            connect(start_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
                                                qDebug () << Q_FUNC_INFO << callReturn->error() << "   " << callReturn->errorText() << __LINE__;
                                            });
                                        }
                                    }

                                });
                            }
                        });
                        //如果有正在连接的音频设备，做完以上流程后，直接退出函数体
                        //因为流程解决定了只有一个音频设备连接，而不需要判断后面是否有音频设备连接；提高代码执行效率
                        return;
                    }
                }
            }
            //当没有任何音频设备连接，最后再连接目标设备
            BluezQt::PendingCall *call = dev.data()->connectToDevice();
            GlobalSize::refBlueDevActive(dev->address());
            connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
                qDebug () << Q_FUNC_INFO << callReturn->error() << "   " << callReturn->errorText() << __LINE__;
                GlobalSize::unrefBlueDevActive(dev->address());
                if (callReturn->error()) {
                    emit devOperateErrorSignal(dev.data()->address(),
                                               callReturn->error(),
                                               callReturn->errorText());
                }
                else
                {
                    //主动连接成功后，发送连接成功信号
                    addDelay(dev);
                }

                //不存在主动连接
                if(GlobalSize::BlueDevActiveSize() == 0)
                {
                    qDebug () << Q_FUNC_INFO  << ::isScan << "===================startDiscovery====" << ::isScan << __LINE__;
                    if (::isScan) {
                        if(!Daemon::_DefualtAdapter.data()->isDiscovering())
                            Daemon::_DefualtAdapter.data()->startDiscovery();
                    }
                }

            });
        }
        //Dt-test phone只连接媒体音频
        else if(dev.data()->type() == BluezQt::Device::Phone)
        {
            qDebug () << Q_FUNC_INFO <<
                         dev.data()->name() <<
                         dev.data()->address() <<
                         dev.data()->type() << __LINE__;

            if ( Environment::HUAWEI != envPC )
            {
                //只连接 UUID: Audio Source (0000110a-0000-1000-8000-00805f9b34fb) 提高连接的成功率
                BluezQt::PendingCall *call = dev.data()->connectProfile("0000110a-0000-1000-8000-00805f9b34fb");
                GlobalSize::refBlueDevActive(dev->address());
                connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
                    qDebug () << Q_FUNC_INFO << callReturn->error() << "   " << callReturn->errorText() << __LINE__;
                    GlobalSize::unrefBlueDevActive(dev->address());
                    if (callReturn->error()) {
                        emit devOperateErrorSignal(dev.data()->address(),
                                                   callReturn->error(),
                                                   callReturn->errorText());
                    }
                    else
                    {
                        //主动连接成功后，发送连接成功信号
                        addDelay(dev);
                    }

                    //不存在主动连接
                    if(GlobalSize::BlueDevActiveSize() == 0)
                    {
                        qDebug () << Q_FUNC_INFO  << ::isScan << "===================startDiscovery====" << ::isScan << __LINE__;
                        if (::isScan) {
                            if(!Daemon::_DefualtAdapter.data()->isDiscovering())
                                Daemon::_DefualtAdapter.data()->startDiscovery();
                        }
                    }

                });
            }
            else
            {
                qDebug () << Q_FUNC_INFO << "Environment::HUAWEI"<< envPC;
                //主动连接全部完成后，启动扫描
                if(GlobalSize::BlueDevActiveSize() == 0)
                {
                     qDebug () << Q_FUNC_INFO  << ::isScan << "===================startDiscovery====" << ::isScan << __LINE__;
                    if (::isScan) {
                        BluezQt::PendingCall * start_call = Daemon::_DefualtAdapter.data()->startDiscovery();
                        connect(start_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
                            qDebug () << Q_FUNC_INFO << callReturn->error() << "   " << callReturn->errorText() << __LINE__;
                        });
                    }
                }
            }

        }
        else
        {

            qDebug () << Q_FUNC_INFO << dev.data()->type() << __LINE__;

            BluezQt::PendingCall *call = dev.data()->connectToDevice();
            GlobalSize::refBlueDevActive(dev->address());
            connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
                qDebug () << Q_FUNC_INFO << callReturn->error() << "   " << callReturn->errorText() << __LINE__;
                GlobalSize::unrefBlueDevActive(dev->address());
                if (callReturn->error()) {
                    emit devOperateErrorSignal(dev.data()->address(),
                                               callReturn->error(),
                                               callReturn->errorText());
                }
                else
                {
                    //主动连接成功后，发送连接成功信号
                    addDelay(dev);
                }

                if(GlobalSize::BlueDevActiveSize() == 0)
                {
                     qDebug () << Q_FUNC_INFO  << ::isScan << "===================startDiscovery====" << ::isScan << __LINE__;
                    if (::isScan) {
                        if (!Daemon::_DefualtAdapter.data()->isDiscovering())
                        {
                            BluezQt::PendingCall * start_call =  Daemon::_DefualtAdapter.data()->startDiscovery();
                            connect(start_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
                                qDebug () << Q_FUNC_INFO << callReturn->error() << "   " << callReturn->errorText() << __LINE__;
                            });
                        }
                    }
                }
            });
        }
    }

    qDebug () << Q_FUNC_INFO  << "END" << __LINE__;
}

bool SessionDbusRegister::registerClient(QString, int, QString)
{
    qInfo() << Q_FUNC_INFO <<__LINE__;
    return true;
}


bool SessionDbusRegister::unregisterClient(QString)
{
    qInfo() << Q_FUNC_INFO <<__LINE__;

    return true;
}


bool SessionDbusRegister::getBluetoothBlock()
{
    if (Daemon::_BluezManager)
        return Daemon::_BluezManager->isBluetoothBlocked();
}

QString SessionDbusRegister::getDefaultAdapterAddress()
{
    if (!Daemon::_DefualtAdapter.isNull())
        return Daemon::_DefualtAdapter.data()->address();
    else
        return "";
}

bool SessionDbusRegister::getDefaultAdapterPower()
{
    qInfo() << Q_FUNC_INFO ;
    if (!Daemon::_DefualtAdapter.isNull())
        return Daemon::_DefualtAdapter.data()->isPowered();
    else
        return false;
}

void SessionDbusRegister::setDefaultAdapterPower(bool v)
{
    qInfo() << Q_FUNC_INFO << "setDefaultAdapterPower" << v << __LINE__;
    Config::gsetting->set(GSETTING_STR_BLUETOOTH_POWER_SWTICH,QVariant(v));
    global_DefaultAdapterPower = v;

    if (!Daemon::_DefualtAdapter.isNull()) {

#ifdef EXISTS_KYSDK_DIAGNOSTICS
        QString action = Daemon::_DefualtAdapter->address() + "+";
        if (v)
            action.append("true");
        else
            action.append("false");

        Daemon::sendWriteInData("PowerSwitch",action);
#endif

        if(v)
        {
            if(!Daemon::_DefualtAdapter->isPowered())
            {
                global_need_reconnect = true;
            }
        }

        if (!v)
        {
           emit powerProgress(true);
           //遇到长城机器在关闭蓝牙时不停止扫描动作，会造成下次开启后，扫描无法拉起的问题，增加关闭蓝牙时先停止蓝牙适配器扫描的动作
           if (Daemon::_DefualtAdapter->isDiscovering())
           {
               BluezQt::PendingCall * stop_call = Daemon::_DefualtAdapter.data()->stopDiscovery();
               connect(stop_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn)
               {
                   qDebug() << Q_FUNC_INFO << "stopDiscovery:" << callReturn->error() << callReturn->errorText() << __LINE__;
                   qDebug() << Q_FUNC_INFO << "setDefaultAdapterPower" << v << __LINE__;
                   BluezQt::PendingCall * power_call = Daemon::_DefualtAdapter.data()->setPowered(v);
                   connect(power_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn) {
                       emit powerProgress(false);
                   });
               });
               stop_call->waitForFinished();
           }
           else
           {
               BluezQt::PendingCall * power_call = Daemon::_DefualtAdapter.data()->setPowered(v);
               connect(power_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn) {
                   emit powerProgress(false);
               });
           }
       }
       else
       {
           emit powerProgress(true);
           if (Daemon::_BluezManager && Daemon::_BluezManager->isBluetoothBlocked())
               Daemon::_BluezManager->setBluetoothBlocked(false);

           qDebug() << Q_FUNC_INFO << "setDefaultAdapterPower" << v << __LINE__;
           BluezQt::PendingCall * power_call = Daemon::_DefualtAdapter.data()->setPowered(v);
           connect(power_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn) {
               emit powerProgress(false);
           });

           huawei_scan_interval_flag = true;
           QTimer::singleShot(2500,this,[=]{
               huawei_scan_interval_flag = false;
               qDebug() << Q_FUNC_INFO << huawei_scan_interval_flag << __LINE__;
           });
       }
    }
}

bool SessionDbusRegister::getDefaultAdapterScanStatus()
{
    if (!Daemon::_DefualtAdapter.isNull()) {
        return Daemon::_DefualtAdapter.data()->isDiscovering();
    }
    return false;
}

bool SessionDbusRegister::getDefaultAdapterDiscoverable()
{
    if (!Daemon::_DefualtAdapter.isNull()) {
        return Daemon::_DefualtAdapter.data()->isDiscoverable();
    }
    return false;
}

QString SessionDbusRegister::getAdapterNameByAddr(QString addr)
{
    qDebug() << Q_FUNC_INFO << addr << __LINE__;
    if (addr.isEmpty() || addr.isNull() || !Daemon::_BluezManager)
    {
        qDebug() << Q_FUNC_INFO << "addr isEmpty or isNull / Daemon::_BluezManager isNull" << __LINE__;
        return "";
    }
    BluezQt::AdapterPtr adapter = Daemon::_BluezManager->adapterForAddress(addr);
    if (adapter.isNull())
    {
        qDebug() << Q_FUNC_INFO << "from Daemon::_BluezManager find this adapter!!!" << __LINE__;
        return "";
    }
    return adapter.data()->name();
}

void SessionDbusRegister::setDefaultAdapterScanOn(bool scanon)
{
    qDebug () << Q_FUNC_INFO  << scanon << __LINE__;
    if (!Daemon::_DefualtAdapter.isNull()) {
//        BluezQt::PendingCall *call = nullptr;
        ::isScan = scanon;
        if (GlobalSize::BlueDevActiveSize() == 0)
        {
            if (scanon)
            {
                if (Environment::HUAWEI == envPC && huawei_scan_interval_flag)
                {
                    if (scanOnTimer == nullptr)
                    {
                        scanOnCount = 0;
                        scanOnTimer = new QTimer();
                        scanOnTimer->disconnect();
                        connect(scanOnTimer,&QTimer::timeout,this,[=]
                        {
                            qDebug () << Q_FUNC_INFO  << "scanOnCount:" << scanOnCount << __LINE__;
                            qDebug () << Q_FUNC_INFO  << "!Daemon::_DefualtAdapter.isNull():" << !Daemon::_DefualtAdapter.isNull() << __LINE__;
                            if (!Daemon::_DefualtAdapter.isNull())
                                    qDebug () << Q_FUNC_INFO  << "Daemon::_DefualtAdapter->isPowered():" << Daemon::_DefualtAdapter->isPowered() << __LINE__;
                            if (!Daemon::_DefualtAdapter.isNull() && Daemon::_DefualtAdapter->isPowered())
                            {
                                if (scanOnCount%2 == 0)
                                {
                                    if (Daemon::_DefualtAdapter.data()->isDiscovering())
                                        Daemon::_DefualtAdapter.data()->stopDiscovery();
                                }
                                else
                                {
                                    if (!Daemon::_DefualtAdapter.data()->isDiscovering())
                                        Daemon::_DefualtAdapter.data()->startDiscovery();
                                }
                                scanOnCount++;
                                if (scanOnCount > 3)
                                {
                                    if (!Daemon::_DefualtAdapter.data()->isDiscovering())
                                        Daemon::_DefualtAdapter.data()->startDiscovery();
                                    scanOnCount = 0;
                                    scanOnTimer->stop();
                                    scanOnTimer->disconnect();
                                    scanOnTimer->deleteLater();
                                    scanOnTimer = nullptr;
                                    qDebug () << Q_FUNC_INFO  << ((scanOnTimer==nullptr)?"111":"222") << __LINE__;

                                }
                            }
                            else
                            {
                                scanOnTimer->stop();
                                scanOnTimer->disconnect();
                                scanOnTimer->deleteLater();
                                scanOnTimer = nullptr;
                                qDebug () << Q_FUNC_INFO  << ((scanOnTimer==nullptr)?"333":"444") << __LINE__;

                            }
                        });
                        scanOnTimer->start(2000);
                    }
                }

                if (!Daemon::_DefualtAdapter.data()->isDiscovering())
                {
                    BluezQt::PendingCall * scanOn_call = Daemon::_DefualtAdapter.data()->startDiscovery();
                    connect(scanOn_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn) {
                        qDebug() << Q_FUNC_INFO  << "startDiscovery finished:" <<  callReturn->error() << callReturn->errorText() << __LINE__;

                    });
                }
            }
            else
            {
                if (Daemon::_DefualtAdapter.data()->isDiscovering())
                {
                    BluezQt::PendingCall * scanOff_call = Daemon::_DefualtAdapter.data()->stopDiscovery();
                    connect(scanOff_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn) {
                        qDebug() << Q_FUNC_INFO  << "stopDiscovery finished:" <<  callReturn->error() << callReturn->errorText() << __LINE__;

                    });
                }

            }
        }
    }
    else
    {
        qWarning() << Q_FUNC_INFO  << "default adapter is null!" << __LINE__;
    }
}

void SessionDbusRegister::setDefaultAdapter(QString addr)
{
    qInfo() << Q_FUNC_INFO << addr;
    if (addr.isEmpty() || addr.isNull() || !Daemon::_BluezManager)
        return;

    BluezQt::AdapterPtr adapter = Daemon::_BluezManager->adapterForAddress(addr);
    if (!adapter.isNull())
    {
        if(adapter->address() != Daemon::_DefualtAdapter->address())
        {
            BluezQt::PendingCall *pending = Daemon::_DefualtAdapter->setDiscoverable(false);
            pending->waitForFinished();

            pending = Daemon::_DefualtAdapter->stopDiscovery();
            pending->waitForFinished();

            TmpDevClear::getInstant()->fini();

            for (auto device : Daemon::_DefualtAdapter->devices())
            {
                if(device->isPaired())
                    continue;

                Daemon::_DefualtAdapter->removeDevice(device);
            }

            Daemon::_DefualtAdapter->disconnect(this);
            Daemon::_DefualtAdapter = adapter;
        }
        Config::gsetting->set(GSETTING_STR_ADAPTER_ADDRESS,QVariant::fromValue(addr));
        global_daemon->launchDefaultBluetooth();
        emit this->defaultAdapterChanged(addr);
    }
}

void SessionDbusRegister::setDefaultAdapterDiscoverable(bool value)
{
    if (!Daemon::_DefualtAdapter.isNull()) {

#ifdef EXISTS_KYSDK_DIAGNOSTICS
        QString action = Daemon::_DefualtAdapter->address() + "+";

        if (value)
            action.append("true");
        else
            action.append("false");

        Daemon::sendWriteInData("DiscoverableSwitch",action);
#endif

        qInfo() << Q_FUNC_INFO << Daemon::_DefualtAdapter.data()->discoverableTimeout() << ", value: " << value;
        if (value) {
            Daemon::_DefualtAdapter.data()->setDiscoverableTimeout(0);
        }

        Daemon::_DefualtAdapter.data()->setDiscoverable(value);
        Config::gsetting->set(GSETTING_STR_BLUETOOTH_DISCOVERABLE_SWTICH,QVariant(value));
    }
}

void SessionDbusRegister::setBluetoothBlock(bool)
{

}

void SessionDbusRegister::setDefaultAdapterName(QString bluetoothName)
{
    if (Daemon::_DefualtAdapter.isNull())
        return;
    Daemon::_DefualtAdapter.data()->setName(bluetoothName);

}

void SessionDbusRegister::clearNonViableDevice(QStringList devAddrList)
{
    qDebug() << Q_FUNC_INFO << devAddrList <<__LINE__;
    if (Daemon::_DefualtAdapter.isNull())
        return;

    for (auto devAddr : devAddrList)
    {
        BluezQt::DevicePtr dev = Daemon::_DefualtAdapter.data()->deviceForAddress(devAddr);
        if (!dev.isNull())
        {
            qDebug() << Q_FUNC_INFO << dev->name() << dev->address() <<__LINE__;
            Daemon::_DefualtAdapter.data()->removeDevice(dev);
        }
        else
        {
            qDebug() << Q_FUNC_INFO << "_DefualtAdapter not find :" << devAddr <<__LINE__;
        }
    }
}

void SessionDbusRegister::devPair(const QString addr)
{
    if (!isAvailableAddress(addr))
        return;

    BluezQt::DevicePtr devPtr = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
    if (!devPtr)
        return;

    BluezQt::PendingCall *call = devPtr.data()->pair();
    connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
        if (callReturn->error()) {
            emit devOperateErrorSignal(devPtr.data()->address(),
                                       callReturn->error(),
                                       callReturn->errorText());
        }
    });
}

void SessionDbusRegister::devConnect(const QString addr)
{
    qInfo() << Q_FUNC_INFO << __LINE__ << ", dev addr: "<< addr;
    if (!isAvailableAddress(addr))
        return;

    BluezQt::DevicePtr devPtr = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
    if (!devPtr)
        return;

#ifdef EXISTS_KYSDK_DIAGNOSTICS
        QString action = Daemon::_DefualtAdapter->address() + "+" + devPtr.data()->address();
        Daemon::sendWriteInData("DeviceConnect",action);
#endif

    if (Daemon::_DefualtAdapter.data()->isDiscovering()) {
        ::isScan = true;
        BluezQt::PendingCall * stop_call = Daemon::_DefualtAdapter.data()->stopDiscovery();
        connect(stop_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn)
        {
            qDebug() << Q_FUNC_INFO << "stopDiscovery:" << callReturn->error() << callReturn->errorText() << __LINE__;
        });
        stop_call->waitForFinished();
    }

    //其他程序连接蓝牙设备时同步状态
    emit devLaunchConnecting(devPtr.data()->address());

    if (devPtr.data()->isPaired()) {
        AudioDevConnectFunc(devPtr);
    } else {
        BluezQt::PendingCall *call = devPtr.data()->pair();
        //设置可信任设备后，适配器会相应来自设备的回连。当前验证鼠标和键盘是如此。
        devPtr.data()->setTrusted(true);

        //更新临时设备时间戳，防止配对过程中移除设备
        TmpDevClear::getInstant()->updateTime(devPtr->address());

        GlobalSize::refBlueDevActive(devPtr->address());
        connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
            GlobalSize::unrefBlueDevActive(devPtr->address());
            if (callReturn->error()) {
                emit devOperateErrorSignal(devPtr.data()->address(),
                                           callReturn->error(),
                                           callReturn->errorText());
                //主动连接全部完成后，启动扫描
                if(GlobalSize::BlueDevActiveSize() == 0)
                {
                    qDebug () << Q_FUNC_INFO  << ::isScan << "===================startDiscovery====" << ::isScan << __LINE__;
                    if (::isScan) {
                        BluezQt::PendingCall * start_call = Daemon::_DefualtAdapter.data()->startDiscovery();
                        connect(start_call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
                            qDebug () << Q_FUNC_INFO << callReturn->error() << "   " << callReturn->errorText() << __LINE__;
                        });
                    }
                }
            } else
                AudioDevConnectFunc(devPtr);
        });
    }
}

void SessionDbusRegister::devDisconnect(const QString addr)
{
    if (!isAvailableAddress(addr))
        return;

    BluezQt::DevicePtr devPtr = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
    if (!devPtr)
        return;

#ifdef EXISTS_KYSDK_DIAGNOSTICS
        QString action = Daemon::_DefualtAdapter->address() + "+" + devPtr.data()->address();
        Daemon::sendWriteInData("DeviceDisconnect",action);
#endif

    BluezQt::PendingCall *call = devPtr.data()->disconnectFromDevice();
    connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
        if (callReturn->error()) {
            emit devOperateErrorSignal(devPtr.data()->address(),
                                       callReturn->error(),
                                       callReturn->errorText());
        }
    });
}

void SessionDbusRegister::devRemove(const QString addr)
{
    if (!isAvailableAddress(addr))
        return;

    BluezQt::DevicePtr devPtr = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
    if (!devPtr)
        return;

    BluezQt::PendingCall *call = Daemon::_DefualtAdapter.data()->removeDevice(devPtr);
    connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
        if (callReturn->error()) {
            emit devOperateErrorSignal(devPtr.data()->address(),
                                       callReturn->error(),
                                       callReturn->errorText());
        } else {
            Config::removeKey(addr);
        }
    });
}

void SessionDbusRegister::devTrust(const QString addr,const bool trust)
{
    if (!isAvailableAddress(addr))
        return;

    BluezQt::DevicePtr devPtr = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
    if (!devPtr)
        return;

    BluezQt::PendingCall *call = devPtr.data()->setTrusted(trust);
    connect(call,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *callReturn){
        if (callReturn->error()) {
            emit devOperateErrorSignal(devPtr.data()->address(),
                                       callReturn->error(),
                                       callReturn->errorText());
        }
    });
}

bool SessionDbusRegister::getDevPairStatus(const QString addr)
{
    if (addr.isEmpty() || addr.isNull())
        return false;

    if (!Daemon::_DefualtAdapter.isNull()) {
        BluezQt::DevicePtr dev = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
        if (!dev.isNull())
            return dev.data()->isPaired();
        else
            return false;
    } else {
        return false;
    }
}

bool SessionDbusRegister::getDevConnectStatus(const QString addr)
{
    if (addr.isEmpty() || addr.isNull())
        return false;

    if (!Daemon::_DefualtAdapter.isNull()) {
        BluezQt::DevicePtr dev = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
        if (!dev.isNull())
            return dev.data()->isConnected();
        else
            return false;
    } else {
        return false;
    }
}

QString SessionDbusRegister::getDevType(const QString addr)
{
    if (addr.isEmpty() || addr.isNull())
        return "";

    if (!Daemon::_DefualtAdapter.isNull()) {
        BluezQt::DevicePtr dev = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
        if (!dev.isNull())
        {
            if (Environment::HUAWEI == envPC && dev.data()->type() == BluezQt::Device::AudioVideo)
                return BluezQt::Device::typeToString(BluezQt::Device::Headphones);
            else
                return BluezQt::Device::typeToString(dev.data()->type());
        }
        else
            return "";
    } else {
        return "";
    }
}

void SessionDbusRegister::clearAllUnPairedDevicelist()
{
    if (!Daemon::_DefualtAdapter.isNull()) {
        for (auto dev : Daemon::_DefualtAdapter.data()->devices()) {
            if (!dev.data()->isPaired()) {
                Daemon::_DefualtAdapter.data()->removeDevice(dev);
            }
        }
    }
}

qint64 SessionDbusRegister::getDevBattery(const QString addr)
{
    if (addr.isEmpty() || addr.isNull())
        return -1;

#ifdef BATTERY
    if (!Daemon::_DefualtAdapter.isNull()) {
        BluezQt::DevicePtr dev = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
        if (!dev.isNull()) {
            if (dev.data()->battery().isNull())
                return -1;
            return dev.data()->battery().data()->percentage();
        }
    }
#endif
    return -1;
}

QString SessionDbusRegister::getDevName(const QString addr)
{
    qDebug() << Q_FUNC_INFO << "Get device name address:" << addr<< __LINE__;
    if (addr.isEmpty() || addr.isNull() || Daemon::_DefualtAdapter.isNull())
    {
        qDebug() << Q_FUNC_INFO << "addr isEmpty or isNull / _DefualtAdapter isNull" << __LINE__;
        return "";
    }
    BluezQt::DevicePtr devpter = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
    if (devpter.isNull())
    {
        qDebug() << Q_FUNC_INFO << "devpter isNull" << __LINE__;

        return "";
    }
    return devpter.data()->name();
}

QStringList SessionDbusRegister::getDefaultAdapterPairedDevAddress()
{
    qDebug() << Q_FUNC_INFO << __LINE__;

    QStringList pairDev;
    pairDev.clear();
    if (!Daemon::_DefualtAdapter.isNull()) {
        for (auto item : Daemon::_DefualtAdapter.data()->devices()) {
            if(item.data()->isPaired()) {
                pairDev.append(item.data()->address());
            }
        }
    }
    return pairDev;
}

QStringList SessionDbusRegister::getDefaultAdapterTrustedDevAddress()
{
    qDebug() << Q_FUNC_INFO << __LINE__;

    QStringList TrusteDev;
    TrusteDev.clear();
    if (!Daemon::_DefualtAdapter.isNull()) {
        for (auto item : Daemon::_DefualtAdapter.data()->devices()) {
            if(item.data()->isTrusted()) {
                TrusteDev.append(item.data()->address());
            }
        }
    }
    return TrusteDev;
}

QStringList SessionDbusRegister::getDefaultAdapterCacheDevAddress()
{
    qDebug() << Q_FUNC_INFO << __LINE__;

    QStringList CacheDevList;
    CacheDevList.clear();
    if (!Daemon::_DefualtAdapter.isNull()) {
        for (auto item : Daemon::_DefualtAdapter.data()->devices()) {
            CacheDevList.append(item.data()->address());
        }
    }
    return CacheDevList;
}

QStringList SessionDbusRegister::getAdapterDevAddressList()
{
    qDebug() << Q_FUNC_INFO << __LINE__;

    QStringList AdapterList;
    AdapterList.clear();
    if (Daemon::_BluezManager) {
        for (auto item : Daemon::_BluezManager->adapters()) {
            AdapterList.append(item.data()->address());
        }
    }
    return AdapterList;
}

void SessionDbusRegister::sendFiles(QString addr,QString filename)
{
    qDebug() << Q_FUNC_INFO << __LINE__;

    if (filename.isEmpty() || filename.isNull())
        return;

    emit sendFile(addr,filename);
}

void SessionDbusRegister::exit()
{
    qApp->exit(0);
}

void SessionDbusRegister::sendNotifyMessage(QString message)
{
    qDebug() << Q_FUNC_INFO << __LINE__;

    if (message.isEmpty() || message.isNull())
        return;

    Config::SendNotifyMessage(message);
}

void SessionDbusRegister::openBluetoothSettings()
{

#ifdef EXISTS_KYSDK_DIAGNOSTICS
        QString action = "1";
        Daemon::sendWriteInData("openBluetoothSettings",action);
#endif

    Config::OpenBluetoothSettings();
}

void SessionDbusRegister::connectSignal()
{
    qInfo() << Q_FUNC_INFO ;
    if (nullptr == Daemon::_BluezManager)
    {
        qWarning() << Q_FUNC_INFO << "btManaher is null!" ;
        return;
    }

    if (nullptr == Daemon::_DefualtAdapter)
    {
        qWarning() << Q_FUNC_INFO << "_DefualtAdapter is null!" ;
        return;
    }

    Daemon::_DefualtAdapter->disconnect(this);

    TmpDevClear* test = TmpDevClear::getInstant();
    test->init();

    //初始化，蓝牙状态开启，需要打开扫描
    if(global_activeconn_switch && global_DefaultAdapterPower && Daemon::_DefualtAdapter->isPowered())
    {
        this->setDefaultAdapterScanOn(true);
    }

    connect(Daemon::_DefualtAdapter.data(),&BluezQt::Adapter::adapterRemoved,this,[=](BluezQt::AdapterPtr adapter){
        qInfo() << Q_FUNC_INFO << "adapterRemoved" << ", adaptersize : " << Daemon::_BluezManager->adapters().size() << __LINE__;
    });

    connect(Daemon::_DefualtAdapter.data(),&BluezQt::Adapter::nameChanged,this,[=](const QString &name)
    {
        qDebug() << Q_FUNC_INFO << "nameChanged" << name << __LINE__;
        emit defaultAdapterNameChanged(name);
    });

    connect(Daemon::_DefualtAdapter.data(),&BluezQt::Adapter::deviceRemoved,this,[=](BluezQt::DevicePtr devPtr){
        qDebug() << Q_FUNC_INFO << "deviceRemoved" << devPtr->address() << devPtr->type() <<__LINE__;
        emit devRemoveSignal(devPtr.data()->address());

        if (devPtr.data()->isPaired() && !::global_systemSleepFlag)
            Config::removeKey(devPtr.data()->address());
    });

    connect(Daemon::_DefualtAdapter.data(),&BluezQt::Adapter::poweredChanged,this,[=](bool powered){
        qInfo() << Q_FUNC_INFO << "poweredChanged" << powered <<__LINE__;

        //初始化蓝牙功能5s内，若出现设置蓝牙的状态和bluez返回的状态不一致，则重新设置
        //无需发送蓝牙适配器状态
        if(abs(QDateTime::currentMSecsSinceEpoch() - global_InitBluetoothTime) <= 5000
                && global_DefaultAdapterPower != powered)
        {
            qWarning() << Q_FUNC_INFO << "error bluetooth status, reset bluetooth status : " << global_DefaultAdapterPower;
            BluezQt::PendingCall *pending = Daemon::_DefualtAdapter->setPowered(global_DefaultAdapterPower);
            connect(pending,&BluezQt::PendingCall::finished,this,[=](BluezQt::PendingCall *call)
            {
                qInfo() << Q_FUNC_INFO << "power: error: " << call->error() << ", errorText: " <<call->errorText();
            });
            pending->waitForFinished();
        }
        else
        {
            //发送蓝牙适配器状态
            qInfo() << Q_FUNC_INFO << "send defaultAdapterPowerChanged: " << powered <<__LINE__;
            emit defaultAdapterPowerChanged(powered);

            //蓝牙适配器从关闭到开启，设置Discoverble
            if(powered)
            {
                global_daemon->setDefaultDiscoverble();
            }

            if(powered && global_need_reconnect)
            {
                global_need_reconnect = false;
                Daemon::reconnectFunc();
            }

            //主动发现 且 蓝牙开启
            if(global_activeconn_switch && global_DefaultAdapterPower && powered)
            {
                this->setDefaultAdapterScanOn(true);
            }
        }
    });

    connect(Daemon::_DefualtAdapter.data(),&BluezQt::Adapter::discoveringChanged,this,[=](bool status){
        qDebug() << Q_FUNC_INFO << "discoveringChanged" << status << __LINE__;
        emit defaultScanStatusChanged(status);
    });

    connect(Daemon::_DefualtAdapter.data(),&BluezQt::Adapter::discoverableChanged,this,[=](bool discoverable){
        qDebug() << Q_FUNC_INFO << "discoverableChanged" << discoverable << __LINE__;

        //这里是否需要增加intel机型判断，intel默认可被发状态为开启
        //无需保存状态
        //Config::gsetting->set(GSETTING_STR_BLUETOOTH_DISCOVERABLE_SWTICH,QVariant(discoverable));

        emit defaultDiscoverableChanged(discoverable);
    });

    connect(Daemon::_DefualtAdapter.data(),&BluezQt::Adapter::deviceAdded,this,[=](BluezQt::DevicePtr devPtr){
        //qInfo() << Q_FUNC_INFO << "deviceAdded:" << devPtr->address() << devPtr->rssi()  <<  ";line = "<< __LINE__ ;



        //设备类型正常，才发送信号
        if(devPtr->type() != BluezQt::Device::Type::Uncategorized)
        {
            if (!deviceMacAddressChanged(devPtr))
            {
                if (Environment::HUAWEI == envPC && devPtr->type() == BluezQt::Device::AudioVideo)
                    emit deviceScanResult(devPtr.data()->address(),
                                          devPtr.data()->name(),
                                          BluezQt::Device::typeToString(BluezQt::Device::Headphones),
                                          devPtr.data()->uuids().contains("00001105-0000-1000-8000-00805f9b34fb",Qt::CaseInsensitive),
                                          devPtr.data()->rssi()
                                          );
                else
                    emit deviceScanResult(devPtr.data()->address(),
                                          devPtr.data()->name(),
                                          BluezQt::Device::typeToString(devPtr.data()->type()),
                                          (devPtr.data()->type() == BluezQt::Device::Computer ?
                                               true :
                                               devPtr.data()->uuids().contains("00001105-0000-1000-8000-00805f9b34fb",Qt::CaseInsensitive)),
                                          devPtr.data()->rssi()
                                          );
            }
            //添加mac前3位和名称一致的判断，过滤掉扫描列表中mac地址会变化的设备
            //clearDeviceScanList(devPtr);

            //主动连接
            this->deal_active_connection(devPtr);
        }


        //清空信号,防止重复连接
        devPtr->disconnect(this);

        connect(devPtr.data(),&BluezQt::Device::connectedChanged,this,[=](bool v){
            qDebug() << Q_FUNC_INFO << "connectedChanged" << devPtr.data()->address() <<
                        v << devPtr.data()->isPaired() << devPtr->isConnected()<< devPtr.data()->type();

            //增加设备连接成功后在1秒内有连接失败的流程中，增加再次连接的操作
            if (devPtr.data()->isPaired())
            {
                deviceConnectAgain(devPtr,v);
            }
            //发送信号
            //主动连接，不发送信号
            //非主动连接情况下
            if(!GlobalSize::IsBlueDevActive(devPtr->address()))
            {
                //条件: 蓝牙适配器：配对、连接， 且蓝牙设备主动连接
                if(devPtr->isPaired() && v)
                {
                    addDelay(devPtr);
                }
                //未配对，且为连接状态， 不发送
                else if(!devPtr->isPaired() && v)
                {
                    ;
                }
                else
                {
                    if(existDelay(devPtr->address()))
                    {
                        qDebug() << Q_FUNC_INFO << __LINE__ << "existDelay " << devPtr->address();
                    }
                    else
                    {
                        qDebug() << Q_FUNC_INFO<< __LINE__ << "emit " << devPtr->address() << v;
                        emit devConnectStatusSignal(devPtr->address(),v);

                        if (v && devPtr->isPaired()) {
                            Config::writeKeyFile(devPtr->address(),devPtr->name(),devPtr->type());
                        }
                    }
                }
            }
        });

        connect(devPtr.data(),&BluezQt::Device::rssiChanged,this,[=](qint16 rssi){
            qDebug() << Q_FUNC_INFO <<devPtr.data()->address() << "rssi" << rssi;
            this->deal_active_connection(devPtr);
            emit devRssiChangedSignal(devPtr.data()->address(), rssi);

        });

        connect(devPtr.data(),&BluezQt::Device::pairedChanged,this,[=](bool v){
            qDebug() << Q_FUNC_INFO << "pairedChanged" << devPtr.data()->address() << v;
            emit devPairSignal(devPtr.data()->address(),v);

            //匹配成功 且 非主动连接情况下 且 蓝牙设备状态 连接
            if(v && !GlobalSize::IsBlueDevActive(devPtr->address()) && devPtr->isConnected())
            {
                addDelay(devPtr);
            }
        });

        connect(devPtr.data(),&BluezQt::Device::typeChanged,this,[=](BluezQt::Device::Type type){
            qDebug() << Q_FUNC_INFO << "typeChanged" << devPtr.data()->address();

            //设备类型正常，才发送信号
            if(devPtr->type() != BluezQt::Device::Type::Uncategorized)
            {
                if (Environment::HUAWEI == envPC && devPtr->type() == BluezQt::Device::AudioVideo)
                    emit deviceScanResult(devPtr.data()->address(),
                                          devPtr.data()->name(),
                                          BluezQt::Device::typeToString(BluezQt::Device::Headphones),
                                          devPtr.data()->uuids().contains("00001105-0000-1000-8000-00805f9b34fb",Qt::CaseInsensitive),
                                          devPtr.data()->rssi());
                else
                    emit deviceScanResult(devPtr.data()->address(),
                                          devPtr.data()->name(),
                                          BluezQt::Device::typeToString(devPtr.data()->type()),
                                          (devPtr.data()->type() == BluezQt::Device::Computer ?
                                               true :
                                               devPtr.data()->uuids().contains("00001105-0000-1000-8000-00805f9b34fb",Qt::CaseInsensitive)),
                                          devPtr.data()->rssi()
                                          );

                QTimer::singleShot(500, this, [=]
                {
                    emit devTypeChangedSignal(devPtr->address(),BluezQt::Device::typeToString(devPtr->type()));
                });
            }
            //无蓝牙设备类型，删除设备
            else
            {
                emit devRemoveSignal(devPtr->address());
            }

        });

        connect(devPtr.data(),&BluezQt::Device::nameChanged,this,[=](const QString &name){
            qDebug() << Q_FUNC_INFO << "nameChanged" << devPtr.data()->address();
            emit devNameChangedSignal(devPtr.data()->address(),name);
        });

#ifdef BATTERY
        connect(devPtr.data(),&BluezQt::Device::batteryChanged,this,[=](BluezQt::BatteryPtr battery){
            if(nullptr != battery){
                qDebug() << Q_FUNC_INFO << "batteryChanged" << battery.data()->percentage();
                emit devBatteryChangedSignal(devPtr.data()->address(), QString::number(battery.data()->percentage()));
            }
            else{
                qDebug() << Q_FUNC_INFO << "batteryChanged null " << devPtr.data()->address();
            }

        });
#endif

    });

    foreach (auto dev, Daemon::_DefualtAdapter.data()->devices()) {
        //清空信号，防止重复连接
        dev->disconnect(this);

        connect(dev.data(),&BluezQt::Device::connectedChanged,this,[=](bool v){
            qDebug() << Q_FUNC_INFO  << "connectedChanged" << dev.data()->address() <<
                        v << dev.data()->isPaired() <<  dev->isConnected() << dev->type();

            //增加设备连接成功后在1秒内有连接失败的流程中，增加再次连接的操作
            if (dev.data()->isPaired())
            {
                deviceConnectAgain(dev,v);
            }
            //主动连接，在连接完成发送连接信号
            //非主动连接情况下，发送信号
            if(!GlobalSize::IsBlueDevActive(dev->address()))
            {
                //已匹配设备，且改变为连接状态，延时发送，暂时定义2s
                if(dev->isPaired() && v)
                {
                    addDelay(dev);
                }
                //未匹配，且为连接状态， 不发送
                else if(!dev->isPaired() && v)
                {
                    ;
                }
                else
                {
                    if(existDelay(dev->address()))
                    {
                        qDebug() << Q_FUNC_INFO << __LINE__ << "existDelay " << dev->address();
                    }
                    else
                    {
                        qDebug() << Q_FUNC_INFO<< __LINE__ << "emit " << dev->address() << v;
                        emit devConnectStatusSignal(dev.data()->address(),v);

                        if (v && dev.data()->isPaired()) {
                            Config::writeKeyFile(dev.data()->address(),dev.data()->name(),dev.data()->type());
                        }
                    }
                }
            }
        });

        connect(dev.data(),&BluezQt::Device::pairedChanged,this,[=](bool v){
            qDebug() << Q_FUNC_INFO << "pairedChanged" << dev.data()->address();
            emit devPairSignal(dev.data()->address(),v);

            //匹配成功 且 非主动连接情况下 且 蓝牙设备状态 连接
            if(v && !GlobalSize::IsBlueDevActive(dev->address()) && dev->isConnected())
            {
                addDelay(dev);
            }
        });


        connect(dev.data(),&BluezQt::Device::typeChanged,this,[=](BluezQt::Device::Type type){
            qDebug() << Q_FUNC_INFO << "typeChanged" << dev.data()->address();
            //设备类型正常，才发送信号
            if(dev->type() != BluezQt::Device::Type::Uncategorized)
            {
                if (Environment::HUAWEI == envPC && dev->type() == BluezQt::Device::AudioVideo)
                    emit deviceScanResult(dev.data()->address(),
                                          dev.data()->name(),
                                          BluezQt::Device::typeToString(BluezQt::Device::Headphones),
                                          dev.data()->uuids().contains("00001105-0000-1000-8000-00805f9b34fb",Qt::CaseInsensitive),
                                          dev.data()->rssi());
                else
                    emit deviceScanResult(dev.data()->address(),
                                          dev.data()->name(),
                                          BluezQt::Device::typeToString(dev.data()->type()),
                                          (dev.data()->type() == BluezQt::Device::Computer ?
                                               true :
                                               dev.data()->uuids().contains("00001105-0000-1000-8000-00805f9b34fb",Qt::CaseInsensitive)),
                                          dev.data()->rssi());

                QTimer::singleShot(500, this, [=]
                {
                    emit devTypeChangedSignal(dev->address(),BluezQt::Device::typeToString(dev->type()));
                });

            }
            //无蓝牙设备类型，删除设备
            else
            {
                emit devRemoveSignal(dev->address());
            }
        });

        connect(dev.data(),&BluezQt::Device::nameChanged,this,[=](const QString &name){
            qDebug() << Q_FUNC_INFO << "nameChanged" << dev.data()->address();
            emit devNameChangedSignal(dev.data()->address(),name);
        });
#ifdef BATTERY
        connect(dev.data(),&BluezQt::Device::batteryChanged,this,[=](BluezQt::BatteryPtr battery){
            if(nullptr != battery){
                qDebug() << Q_FUNC_INFO << "batteryChanged" << battery.data()->percentage();
                emit devBatteryChangedSignal(dev.data()->address(), QString::number(battery.data()->percentage()));
            }
            else{
                qDebug() << Q_FUNC_INFO << "batteryChanged null " << dev.data()->address();
            }
            });
#endif
        connect(dev.data(),&BluezQt::Device::rssiChanged,this,[=](qint16 rssi){
            qDebug() << Q_FUNC_INFO <<dev.data()->address() << "rssi" << rssi;
            emit devRssiChangedSignal(dev.data()->address(), rssi);
        });
    }
}


void SessionDbusRegister::deal_active_connection(BluezQt::DevicePtr devPtr)
{
    if(global_activeconn_switch && nullptr != devPtr)
    {
        int v = devPtr->rssi();
        //qInfo() << devPtr->address() << devPtr->type() << v;
        if(devPtr->type() != BluezQt::Device::Type::Headphones && devPtr->type() != BluezQt::Device::Type::Headset
           && devPtr->type() != BluezQt::Device::Type::AudioVideo)
        {
            qDebug() << Q_FUNC_INFO <<  devPtr->address() << devPtr->type();
            return;
        }
        if( static_black_activeconn_dev.find(devPtr->address()) != static_black_activeconn_dev.end())
        {
            qInfo() << "black list in" << devPtr->address() << " rssi: " << devPtr->rssi();
            return;
        }

        if( devPtr->isPaired())
            return;
        if(!global_active_connection_dev.isEmpty())
            return;

        int timeout = 15;

        //耳机且未配对设备，且未处于发起主动连接过程中，进行主动连接流程
        //信号强 0dBm ~ -50dBm
        //信号中 -50dBm ~ -70dBm
        if(abs(v) <= 60)
        {
            global_active_connection_dev = devPtr->address();
            emit ActiveConnection(devPtr->address(), devPtr->name(),
                    BluezQt::Device::typeToString(devPtr->type()), v, timeout);

            if(nullptr == static_active_timer)
            {
                static_active_timer = new QTimer(this);
            }
            else
            {
                static_active_timer->disconnect();
            }
            connect(static_active_timer, &QTimer::timeout, this, [=](void)
            {
                global_active_connection_dev = "";
                qInfo() << Q_FUNC_INFO << "active connection timeout";
                static_active_timer->stop();
            });
            static_active_timer->start(timeout * 1000);

            qInfo() << Q_FUNC_INFO <<  "start active conection" << devPtr->address()
                    <<" rssi: "<< devPtr->rssi() << " timeout:" << timeout
                    <<" type: " << BluezQt::Device::typeToString(devPtr->type())
                    <<" name: " << devPtr->name();
        }
        else
        {
            qInfo() << Q_FUNC_INFO <<  "not start active conection" << devPtr->address()
                     << " rssi: "<< devPtr->rssi() << " timeout:" << timeout
                     <<" type: "<< BluezQt::Device::typeToString(devPtr->type())
                     <<" name: " << devPtr->name();
        }

    }
}

void SessionDbusRegister::activeConnectionReply(QString dev, bool v)
{
    qInfo() << Q_FUNC_INFO << dev << v;
    if(nullptr != static_active_timer)
    {
        static_active_timer->stop();
    }
    if(dev == global_active_connection_dev)
    {
        if(v)
        {
            devConnect(dev);
        }
        else
        {
            static_black_activeconn_dev.insert(global_active_connection_dev);
        }
        global_active_connection_dev = "";
    }
    else
    {
        global_active_connection_dev = "";
    }
}


//针对已配对的音频设备，发起连后设备立马断开的设备再发起一次连接操作
void SessionDbusRegister::deviceConnectAgain(BluezQt::DevicePtr devPtr, bool connectChangedValue)
{
    qDebug () << Q_FUNC_INFO << __LINE__;
    if (devPtr.isNull())
    {
        qDebug () << Q_FUNC_INFO << "device is nullptr!!!" << __LINE__;
        return;
    }

    //只针对音频设备进行再次连接
    if (BluezQt::Device::AudioVideo == devPtr.data()->type() ||
        BluezQt::Device::Headset    == devPtr.data()->type() ||
        BluezQt::Device::Headphones == devPtr.data()->type()
            )
    {
        if(connectChangedValue)
        {
            if(devConnectAgainMap.contains(devPtr->address()))
            {
                devConnectAgainMap[devPtr->address()] = QDateTime::currentMSecsSinceEpoch();
            }
            else
            {
                devConnectAgainMap.insert(devPtr->address(),QDateTime::currentMSecsSinceEpoch());
            }
        }
        else
        {
            if (devConnectAgainMap.contains(devPtr->address()))
            {
                qint64 timeDiff = QDateTime::currentMSecsSinceEpoch() - devConnectAgainMap.value(devPtr->address());
                if (timeDiff < 1000)//时间差在1s以内则再次发发起连接
                {
                    //非主动连接情况下，发起主动连接前，上报状态，预防重连失败后，控制面板/托盘还处于连接状态
                    if(!GlobalSize::IsBlueDevActive(devPtr->address()))
                    {
                        addDelay(devPtr);
                    }

                    AudioDevConnectFunc(devPtr);
                    //devConnect(devPtr->address());
                }
                devConnectAgainMap.remove(devPtr->address());
            }
        }
    }

}

bool SessionDbusRegister::deviceMacAddressContrast(QString newMacAddress , QString oldMacAddress,int compareLength)
{
    //判断mac前三位是否一致
    QString newStr = newMacAddress.left(compareLength);
    QString oldStr = oldMacAddress.left(compareLength);
    if (newStr == oldStr)
        return true;
    else
        return false;
}

bool SessionDbusRegister::deviceMacAddressChanged(BluezQt::DevicePtr devPtr)
{
    //qDebug() << Q_FUNC_INFO << __LINE__;
    //华为机型不做该功能处理
    if(Environment::HUAWEI == envPC)
        return false;

    if (devPtr.isNull())
    {
        qDebug() << Q_FUNC_INFO << "devPtr isNull !!!" << __LINE__;
        return false;
    }

    foreach (auto dev, Daemon::_DefualtAdapter.data()->devices())
    {
        //现象部分设备在多次开启配对后，会产生设备名称相同但mac地址接近的另一个外的设备
        //已配对的设置中，
        if( nullptr != dev &&
            dev.data()->isPaired() &&
            !dev.data()->isConnected() &&
            (devPtr.data()->name() == dev.data()->name()) &&
            (devPtr.data()->address() != dev.data()->address()) &&
             deviceMacAddressContrast(devPtr.data()->address(),dev.data()->address(),15)
                )
        {
            qDebug() << Q_FUNC_INFO  << devPtr.data()->name() << devPtr.data()->name() ;
            qDebug() << Q_FUNC_INFO  << dev.data()->name() << dev.data()->name() ;

            emit devMacAddressChangedSignal(dev.data()->address(),devPtr.data()->address());

            QTimer::singleShot(3000,this,[=]{
                Daemon::_DefualtAdapter.data()->removeDevice(dev);
                qDebug() << Q_FUNC_INFO << __LINE__;
            });
            return true;
        }
    }
    return false;
}

void SessionDbusRegister::clearDeviceScanList(BluezQt::DevicePtr devPtr)
{
    qDebug() << Q_FUNC_INFO << __LINE__;

    if (devPtr.isNull())
    {
        return;
    }

    foreach (auto dev, Daemon::_DefualtAdapter.data()->devices())
    {
        if( nullptr != dev &&
            !dev.data()->isPaired() &&
            !dev.data()->isConnected() &&
            (devPtr.data()->name() == dev.data()->name()) &&
            (devPtr.data()->address() != dev.data()->address()) &&
             deviceMacAddressContrast(devPtr.data()->address(),dev.data()->address(),8)
                )
        {
            qDebug() << Q_FUNC_INFO  << devPtr.data()->name() << devPtr.data()->name() ;
            qDebug() << Q_FUNC_INFO  << dev.data()->name() << dev.data()->name() ;
            //删除老的设备
            Daemon::_DefualtAdapter.data()->removeDevice(dev);
            break;
        }
    }
}

void SessionDbusRegister::sendContinueRecieveFilesSignal()
{
    qDebug() << Q_FUNC_INFO;
    emit continueRecieveFilesSignal();
}

void SessionDbusRegister::sendReplyFileReceivingSignal(bool v)
{
    qDebug() << "SessionDbusRegister::sendReplyFileReceivingSignal";
    emit replyFileReceivingSignal(v);
}

void SessionDbusRegister::sendCloseSession()
{
    qDebug() << "SessionDbusRegister::sendCloseSession";
    emit closeSessionSignal();
}


void SessionDbusRegister::sendReplyRequestConfirmation(bool v)
{
    qDebug() << "SessionDbusRegister::sendReplyRequestConfirmation";
    emit replyRequestConfirmation(v);
}

void SessionDbusRegister::setSendTransferFileMesg(QStringList files)
{
    qDebug() << "SessionDbusRegister::setSendTransferFileMesg";

#ifdef EXISTS_KYSDK_DIAGNOSTICS
        QString action = "1";
        Daemon::sendWriteInData("DesktopSendFile",action);
#endif

    emit sendTransferFilesMesg(files);
}

void SessionDbusRegister::setSendTransferDeviceMesg(QString address)
{
    qDebug() << "SessionDbusRegister::setSendTransferDeviceMesg";

#ifdef EXISTS_KYSDK_DIAGNOSTICS
        QString action = "1";
        Daemon::sendWriteInData("UkccSendFile",action);
#endif

    emit sendTransferDeviceMesg(address);
}

void SessionDbusRegister::setclearOldSession() {
    qDebug() << "SessionDbusRegister::clearOldSession";
    emit clearOldSession();
}

void SessionDbusRegister::continueSendFiles(QString filename) {
    emit continueSendFilesSignal(filename);
}

void SessionDbusRegister::cancelFileReceiving() {
    qDebug() << "SessionDbusRegister::cancelFileReceiving";
    emit cancelFileReceivingSignal();
}

void SessionDbusRegister::showTrayWidgetUI() {
    qDebug() << "SessionDbusRegister::showTrayWidgetUI";
    emit showTrayWidgetUISignal();
}

bool SessionDbusRegister::getDevSupportFileSend(const QString addr)
{
    if (addr.isEmpty() || addr.isNull())
        return false;

    if (!Daemon::_DefualtAdapter.isNull()) {
        BluezQt::DevicePtr dev = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
        if (!dev.isNull())
        {
            if (BluezQt::Device::Phone != dev.data()->type() && BluezQt::Device::Computer != dev.data()->type())
                return false;
            if (BluezQt::Device::Computer == dev.data()->type())
                return true;
            return dev.data()->uuids().contains("00001105-0000-1000-8000-00805f9b34fb",Qt::CaseInsensitive);
        }
    }
    return false;
}

qint16 SessionDbusRegister::getDevRssi(const QString addr)
{
    if (addr.isEmpty() || addr.isNull())
        return 0;

    if (!Daemon::_DefualtAdapter.isNull()) {
        BluezQt::DevicePtr dev = Daemon::_DefualtAdapter.data()->deviceForAddress(addr);
        if (!dev.isNull())
        {
            return dev.data()->rssi();
        }
    }
    return 0;
}


//服务记录当前文件传输状态
void SessionDbusRegister::dealStatusChanged(QString status, QString dev, QString path) {
    qDebug() << Q_FUNC_INFO << dev << sessionList <<status << path <<"+++++++++++++++++++++++++++++++++++";
    if (path == QString("") && status != "Error") {
        tmpDevCord = dev;
        return;
    }
    tmpDevCord = QString("");
    if (sessionList.keys().contains(dev))
    {
        if (!sessionList.value(dev).contains(path)) {
            QMap<QString,QString> temp = sessionList.value(dev);
            temp.remove(path);
            temp.insert(path, status);
            sessionList.remove(dev);
            sessionList.insert(dev, temp);
            return;
        }
        if (status == "Error" || status == "Complete") {
            QMap<QString,QString> temp = sessionList.value(dev);
            temp.remove(path);
            sessionList.remove(dev);
            if (temp.size() != 0)
                sessionList.insert(dev,temp);
            return;
        }
        QMap<QString,QString> temp = sessionList.value(dev);
        temp.remove(path);
        temp.insert(path,status);
        sessionList.remove(dev);
        sessionList.insert(dev, temp);
        return;
    }
    if (status == "Error")
        return;
    QMap<QString,QString> temp;
    temp.insert(path, status);
    sessionList.insert(dev, temp);
    qDebug() << Q_FUNC_INFO << __LINE__ << sessionList;
}

//服务返回记录的文件传输状态
bool SessionDbusRegister::getTransferDevAndStatus(QString dev) {
    qDebug() << Q_FUNC_INFO << sessionList << sessionList.keys().contains(dev);
    //特殊判断间隙操作Queued
    if (!tmpDevCord.isEmpty())
        return tmpDevCord == dev;
    if (sessionList.size() == 0)
        return true;
    return sessionList.keys().contains(dev);
}
