#include "dataprocess.h"

Q_GLOBAL_STATIC(DataProcess, dataProcess)

DataProcess::DataProcess()
{
#ifdef hasUploadInterface
    qDebug()<<"DataProcess is run";
    QString path = QDir::homePath() + "/sidebarUploadMessage/";
    QPluginLoader pluginLoder("/usr/lib/libupload-plugin-interface.so");
    QObject *plugin = pluginLoder.instance();
    if (plugin) {
        m_initState = true;
        m_sendDataInterface = qobject_cast<UploadPluginInterface *>(plugin);
        m_sendDataInterface->initInterface(getpid(),"ukui-sidebar", "sidebarData", path);
    } else {
        m_initState = false;
    }
#else
    qDebug() << "The dependency on data upload of buried points does not exist, and subsequent operations will not be performed";
#endif
}

DataProcess::~DataProcess()
{
#ifdef hasUploadInterface
    if (m_sendDataInterface != nullptr) {
        delete  m_sendDataInterface;
        m_sendDataInterface = nullptr;
    }
#endif
}

DataProcess *DataProcess::getInstance()
{
    return dataProcess();
}

void DataProcess::sendData(const pointDataStruct &data)
{
#ifdef hasUploadInterface
    //检测是否有so文件
    if (m_initState) {
        // 时区需要为东八区 时区需要为东八区 时区需要为东八区
        QString tempDateTimeStr;
        QDateTime tempDateTime = QDateTime::currentDateTime().toTimeZone(QTimeZone(8*3600));
        tempDateTimeStr= tempDateTime.toString("yyyy-MM-dd HH:mm:ss.zzz");

        int curNum = 1;
        QStringList applist = QStringList();
        QString keyValue = data.module + data.function;

        if (m_functionCount.keys().contains(keyValue)) {
            curNum = m_functionCount.value(keyValue);
            curNum ++;
        }

        m_functionCount.insert(keyValue, curNum);

        if (!data.otherFunction.isEmpty()) {
            if (m_applist.keys().contains(keyValue)) {
                applist = m_applist.value(keyValue);
            }

            applist.append(data.otherFunction.at(0));
            m_applist.insert(keyValue, applist);
        }
        m_functionCount.insert(keyValue, curNum);

        // 将需要发送的信息以json格式保存
        QJsonObject jsonObj;
        QJsonArray otherFunction = QJsonArray::fromStringList(data.otherFunction);
        jsonObj.insert("module", QJsonValue(data.module));
        jsonObj.insert("function", QJsonValue(data.function));
        jsonObj.insert("functionNum", QJsonValue(QString::number(curNum)));
        jsonObj.insert("otherFunction", otherFunction);
        jsonObj.insert("errorLevel", QJsonValue(data.errorLevel));
        jsonObj.insert("errorOutput", QJsonValue(data.errorOutput));
        jsonObj.insert("createTimeStamp", tempDateTimeStr);

        //  将数据转化为QString
        QString informationData(QJsonDocument(jsonObj).toJson(QJsonDocument::Compact));
//        qDebug()<<"调试打印数据:"<<jsonObj;
        m_sendDataInterface->uploadMessage(informationData);
    } else {
        qWarning()<<"no burial point .So file, embedded point mechanism exception";
    }
#endif
}
