#include "modulepostdata.h"

#include "mcu_arm1.h"

mcu_arm1 *ARM_4; //调用串口通信

modulePostData::modulePostData(QObject *parent) : QObject(parent)
{
    //    QString filename = "/home/data/systeminit.ini" ;
    //    QSettings setting(filename,QSettings::IniFormat);
    //    setting.setValue("HTTP/loginpath", "http://120.26.3.63:83/");
    //    QString urlName = setting.value("HTTP/loginpath").toString();

    urlHead = "http://openapi.ie-cloud.com/nj4zddaqe7f6pe24re5ewo9ws46x0aq4/";
    m_pNetWorkManagerAna = new QNetworkAccessManager(this);
    m_pNetWorkManagerAcc = new QNetworkAccessManager(this);
    m_pNetWorkManagerDig = new QNetworkAccessManager(this);
    authentication();
    QTimer::singleShot(900000, this, SLOT(onTimerTimeOutSendData()));
}

//23.8.24   断电数据上传
void modulePostData::powerlost()
{
    postAccData();
    if(isPost)        //判断Acc是否上传成功，失败则直接反馈失败信号
    postAnaData();

    ARM_4->Powerlost_datapost(isPost);

}

void modulePostData::authentication()
{
    QString urlName = urlHead + "auth";

    QUrl url = QUrl(urlName);
    QNetworkRequest request=QNetworkRequest(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("x-ie-access-key","nj4zddaqe7f6pe24re5ewo9ws46x0aq4");
    request.setRawHeader("x-ie-access-token","nj1adww3qbc3b0549ale38ced8dll75f");

    QNetworkAccessManager *pNetWorkManager = new QNetworkAccessManager(this);
    pNetWorkManager->setNetworkAccessible(QNetworkAccessManager::Accessible);
    QNetworkReply* m_pNetworkReply = pNetWorkManager->post(request, "");

    connect(m_pNetworkReply,SIGNAL(finished()),this,SLOT(on_authentication()));
    //m_loop.exec();
}

void modulePostData::postAnaData()
{
    QString anaDate = "";
//    anaDate += SEC.SecWheelVol.toHex();//abc相电流
    anaDate += QString::number(ANA.A_Current,'f',3);
    anaDate += "," + QString::number(ANA.B_Current,'f',3);
    anaDate += "," + QString::number(ANA.C_Current,'f',3);
//    anaDate += "," + SEC.SecFanStartTempeture.toHex();//abc相电压
    anaDate += "," + QString::number(ANA.A_vol,'f',3);
    anaDate += "," + QString::number(ANA.B_vol,'f',3);
    anaDate += "," + QString::number(ANA.C_vol,'f',3);
//    anaDate += "," + SEC.SecWheelFrequency.toHex();//频率
    anaDate += "," + QString::number(ANA.Frequency,'f',2);
//    anaDate += "," + SEC.PhaseAngle.toHex();// abc电压、电流相脚
    anaDate += "," + QString::number(ANA.A_vol_phase);
    anaDate += "," + QString::number(ANA.B_vol_phase);
    anaDate += "," + QString::number(ANA.C_vol_phase);
    anaDate += "," + QString::number(ANA.A_current_phase);
    anaDate += "," + QString::number(ANA.B_current_phase);
    anaDate += "," + QString::number(ANA.C_current_phase);
//    anaDate += "," + SEC.UnstableVandI.toHex();//不平衡电压电流
    anaDate += "," + QString::number(ANA.UnstableI,'f',2);
    anaDate += "," + QString::number(ANA.UnstableV,'f',2);
//    anaDate += "," + SEC.AberrationRate.toHex();//电压电流总畸变率
    anaDate += "," + QString::number(ANA.A_vol_xiebo_jibian);
    anaDate += "," + QString::number(ANA.B_vol_xiebo_jibian);
    anaDate += "," + QString::number(ANA.C_vol_xiebo_jibian);
    anaDate += "," + QString::number(ANA.A_current_xiebo_jibian);
    anaDate += "," + QString::number(ANA.B_current_xiebo_jibian);
    anaDate += "," + QString::number(ANA.C_current_xiebo_jibian);
//    anaDate += "," + SEC.SecWheelATemperature.toHex();//A相温度
//    anaDate += "," + SEC.SecWheelBTemperature.toHex();//B相温度
//    anaDate += "," + SEC.SecWheelCTemperature.toHex();//C相温度
//    anaDate += "," + SEC.SecWheelTTemperature.toHex();//铁芯温度
    anaDate += "," + QString::number(ANA.A_temp,'f',1);
    anaDate += "," + QString::number(ANA.B_temp,'f',1);
    anaDate += "," + QString::number(ANA.C_temp,'f',1);
    anaDate += "," + QString::number(ANA.T_temp,'f',1);
    anaDate += "," + QString::number(ANA.A_vol_K);
    anaDate += "," + QString::number(ANA.B_vol_K);
    anaDate += "," + QString::number(ANA.C_vol_K);
    anaDate += "," + QString::number(ANA.A_current_K);
    anaDate += "," + QString::number(ANA.B_current_K);
    anaDate += "," + QString::number(ANA.C_current_K);
    anaDate += "," + QString::number(ANA.A_vol_top);
    anaDate += "," + QString::number(ANA.B_vol_top);
    anaDate += "," + QString::number(ANA.C_vol_top);
    anaDate += "," + QString::number(ANA.A_current_top);
    anaDate += "," + QString::number(ANA.B_current_top);
    anaDate += "," + QString::number(ANA.C_current_top);

    anaDate += "," + SEC.SecFanStartTemperature.toHex();//风机启动温度
    anaDate += "," + SEC.SecTripTemperature.toHex();//开合跳闸阈值温度
    anaDate += "," + SEC.SecAlarmTemperature.toHex();//报警阈值温度
    anaDate += "," + SEC.SecReturnTemperature.toHex();//迟滞\回差温度值

    anaDate += "," + SEC.wirelessTData_account.toHex();//无线测温
    anaDate += "," + SEC.wirelessTData_adress.toHex();//无线测温
    anaDate += "," + SEC.wirelessTData_data.toHex();//无线测温
    anaDate += "," + SEC.TevTop.toHex();//TEV峰值
    anaDate += "," + SEC.TevFreq.toHex();//TEV频次
    anaDate += "," + SEC.TevLevel.toHex();//TEV噪声水平值
    anaDate += "," + SEC.TevAve.toHex();//TEV均值
    anaDate += "," + SEC.Tevperiodicity.toHex();//TEV周期数
    anaDate += "," + SEC.UltTop.toHex();//超声波峰值
    anaDate += "," + SEC.UltFreq.toHex();//超声波频次
    anaDate += "," + SEC.UltLevel.toHex();//超声波噪声水平值
    anaDate += "," + SEC.UltAve.toHex();//超声波均值
    anaDate += "," + SEC.UltEffective.toHex();//超声波有效值

    anaDate += "," + QString::number(SEC.SIM_quality);//4G信号强度
    anaDate += "," + QString::number(SEC.Wifi_quality);//WIFI信号强度

    auto tp1 = std::chrono::system_clock::now();
    qint64 Secnum = std::chrono::system_clock::to_time_t(tp1);//转换为绝对秒数

    QString postanaurl = urlHead + "dps/rt/ana?ak";
    QUrl url(postanaurl);

    QJsonArray arr;
    QJsonObject object;

    object.insert("id", QJsonValue("289112985"));
    object.insert("flag", QJsonValue("0"));
    object.insert("value", QJsonValue(anaDate));
    object.insert("status", QJsonValue("0"));
    object.insert("proctime", QJsonValue(Secnum));
    object.insert("procms", QJsonValue("0"));
    arr.append(object);
    QJsonDocument document=QJsonDocument(arr);

    QByteArray post_data = document.toJson(QJsonDocument::Compact);
    //qDebug()<<"anapostdata"<<post_data;

    QNetworkRequest request=QNetworkRequest(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("x-ie-access-key","nj4zddaqe7f6pe24re5ewo9ws46x0aq4");
    request.setRawHeader("x-ie-access-token",tokenStr.toLatin1());

    m_pNetWorkManagerAna->setNetworkAccessible(QNetworkAccessManager::Accessible);
    QNetworkReply* m_pNetworkReplyAna = m_pNetWorkManagerAna->post(request, post_data);
    connect(m_pNetworkReplyAna,SIGNAL(finished()),this,SLOT(on_finishedana()));

    //m_loop.exec();
}

void modulePostData::postAccData()
{
    QString accDate = "";

//    accDate += SEC.SecWheelPositiveElectricEnergy.toHex();//正向有功电能
    accDate += QString::number(ACC.P_Power_zong,'f',1);
    accDate += "," + QString::number(ACC.P_Power_jian,'f',1);
    accDate += "," + QString::number(ACC.P_Power_feng,'f',1);
    accDate += "," + QString::number(ACC.P_Power_ping,'f',1);
    accDate += "," + QString::number(ACC.P_Power_gu,'f',1);
//    accDate += "," + SEC.SecWheelPowerFactorCom.toHex();//总功率因素
    accDate += "," + QString::number(ACC.Com_PowerFactor,'f',2);
//    accDate += "," + SEC.SecActivePower.toHex();//abc有功功率
    accDate += "," + QString::number(ACC.A_Active_Power,'f',2);
    accDate += "," + QString::number(ACC.B_Active_Power,'f',2);
    accDate += "," + QString::number(ACC.C_Active_Power,'f',2);
//    accDate += "," + SEC.SecReactivePower.toHex();//abc无功功率
    accDate += "," + QString::number(ACC.A_Reactive_Power,'f',2);
    accDate += "," + QString::number(ACC.B_Reactive_Power,'f',2);
    accDate += "," + QString::number(ACC.C_Reactive_Power,'f',2);
//    accDate += "," + SEC.SecActivePowerCom.toHex();//总有功功率
    accDate += "," + QString::number(ACC.Com_Active_Power,'f',2);
//    accDate += "," + SEC.SecReactivePowerCom.toHex();//总无功功率
    accDate += "," + QString::number(ACC.Com_Reactive_Power,'f',2);
    //三相总视在功率=总有功功率+总无功功率

    auto tp1 = std::chrono::system_clock::now();
    qint64 Secnum = std::chrono::system_clock::to_time_t(tp1);//转换为绝对秒数

    QString postanaurl = urlHead + "dps/rt/acc?ak";
    QUrl url(postanaurl);

    QJsonArray arr;
    QJsonObject object;

    object.insert("id", QJsonValue("288351327"));
    object.insert("flag", QJsonValue("3"));
    object.insert("value", QJsonValue(accDate));
    object.insert("status", QJsonValue("0"));
    object.insert("proctime", QJsonValue(Secnum));
    object.insert("procms", QJsonValue("0"));
    arr.append(object);
    QJsonDocument document=QJsonDocument(arr);

    QByteArray post_data = document.toJson(QJsonDocument::Compact);
    //qDebug()<<"accpostdata"<<post_data;

    QNetworkRequest request=QNetworkRequest(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("x-ie-access-key","nj4zddaqe7f6pe24re5ewo9ws46x0aq4");
    request.setRawHeader("x-ie-access-token",tokenStr.toLatin1());
    m_pNetWorkManagerAcc->setNetworkAccessible(QNetworkAccessManager::Accessible);
    QNetworkReply* m_pNetworkReplyAcc = m_pNetWorkManagerAcc->post(request, post_data);
    connect(m_pNetworkReplyAcc,SIGNAL(finished()),this,SLOT(on_finishedacc()));

    //m_loop.exec();
}

void modulePostData::on_authentication()
{
    qDebug()<<"on_authentication";
    //m_loop.quit();
    QNetworkReply* m_pReply = qobject_cast<QNetworkReply*>(sender());;
    QByteArray replyData = m_pReply->readAll();

    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        qDebug()<< "--trace msg  认证失败，请确认key和token...！"<<m_pReply->errorString();
        //QMessageBox::critical(this, tr("错误"), tr("认证失败，请确认key和token...！"), QMessageBox::Ok, QMessageBox::Ok);
        m_pReply->disconnect();
        m_pReply->deleteLater();
        m_pReply = nullptr;
        return ;
    }
    QJsonObject rootObj = jsonDoc.object();
    int codeStr = rootObj.value("code").toInt();
    if (codeStr == 0)
    {
        //返回代码为200的时候证明请求成功对包含的结构数据进行处理
        QJsonObject data = rootObj.value("data").toObject();
        tokenStr = data.value("accessToken").toString();
        qDebug() << "--trace msg  认证成功，success！";
    }
    else
    {
        //请求失败对对应的处理
        qDebug() << "--trace msg  认证失败，请确认key和token！";
        //QMessageBox::critical(this, tr("错误"), tr("认证失败，请确认key和token！"), QMessageBox::Ok, QMessageBox::Ok);
    }
    m_pReply->disconnect();
    m_pReply->deleteLater();
    m_pReply = nullptr;
}

void modulePostData::on_finishedana()
{
    qDebug()<<"on_postDataanaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    //m_loop.quit();
    QNetworkReply* m_pReplyAna = qobject_cast<QNetworkReply*>(sender());
    QByteArray replyData = m_pReplyAna->readAll();

    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        isPost = false;        //上传表示符号   23.8.24
        qDebug()<< "--trace msg  上传失败...！"<<m_pReplyAna->errorString();
        //QMessageBox::critical(this, tr("错误"), tr("ana上传失败...！"), QMessageBox::Ok, QMessageBox::Ok);
        m_pReplyAna->disconnect();
        m_pReplyAna->deleteLater();
        m_pReplyAna = nullptr;
        return ;
    }

    QJsonObject rootObj = jsonDoc.object();
    int codeStr = rootObj.value("code").toInt();
    if (codeStr == 0)
    {
        //返回代码为200的时候证明请求成功对包含的结构数据进行处理
        isPost = true;        //上传表示符号   23.8.24
        qDebug()<<"successssssssssssssssssssssssssssssssssssssssssssssssssssssana";
    }
    else
    {
        //请求失败对对应的处理
        //写log
        //重新申请token
        //authentication();
        isPost = false;        //上传表示符号   23.8.24
        qDebug()<<"faollllllllllllllllllllllllllllllllllllllllllllllllllllllllana";
    }

    m_pReplyAna->disconnect();
    m_pReplyAna->deleteLater();
    m_pReplyAna = nullptr;
}

void modulePostData::on_finishedacc()
{
    qDebug()<<"on_postDataacccccccccccccccccccccccccccccccccccccc";
    //m_loop.quit();
    QNetworkReply* m_pReplyAcc = qobject_cast<QNetworkReply*>(sender());
    QByteArray replyData = m_pReplyAcc->readAll();

    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        isPost = false;        //上传表示符号   23.8.24
        qDebug()<< "--trace msg  上传失败...！"<<m_pReplyAcc->errorString();
        //QMessageBox::critical(this, tr("错误"), tr("上传失败...acc！"), QMessageBox::Ok, QMessageBox::Ok);
        m_pReplyAcc->disconnect();
        m_pReplyAcc->deleteLater();
        m_pReplyAcc = nullptr;
        return ;
    }

    QJsonObject rootObj = jsonDoc.object();
    int codeStr = rootObj.value("code").toInt();
    if (codeStr == 0)
    {
        //返回代码为200的时候证明请求成功对包含的结构数据进行处理
        isPost = true;        //上传表示符号   23.8.24
        qDebug()<<"successssssssssssssssssssssssssssssssssssssssssssssssssacc";
    }
    else
    {
        //请求失败对对应的处理
        //写log
        //重新申请token
        //authentication();
        isPost = false;        //上传表示符号   23.8.24
        qDebug()<<"faollllllllllllllllllllllllllllllllllllllllllllllllllacc";
    }

    m_pReplyAcc->disconnect();
    m_pReplyAcc->deleteLater();
    m_pReplyAcc = nullptr;
}

void modulePostData::on_finisheddig()
{
    qDebug()<<"on_postDatadigggggggggggggggggggggggggggggggggggggggggggg";
    //m_loop.quit();

    QNetworkReply* m_pReplyDig = qobject_cast<QNetworkReply*>(sender());

    QByteArray replyData = m_pReplyDig->readAll();

    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(replyData, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        isPost = false;        //上传表示符号   23.8.24
        qDebug()<< "--trace msg  上传失败...！"<<m_pReplyDig->errorString();
        //QMessageBox::critical(this, tr("错误"), tr("上传失败...dig！"), QMessageBox::Ok, QMessageBox::Ok);
        m_pReplyDig->disconnect();
        m_pReplyDig->deleteLater();
        m_pReplyDig = nullptr;

        return ;
    }

    QJsonObject rootObj = jsonDoc.object();
    int codeStr = rootObj.value("code").toInt();
    if (codeStr == 0)
    {
        //返回代码为200的时候证明请求成功对包含的结构数据进行处理
        isPost = true;        //上传表示符号   23.8.24
        qDebug()<<"successssssssssssssssssssssssssssssssssssssssssssssssdig";
    }
    else
    {
        //请求失败对对应的处理
        //写log
        //重新申请token
        //authentication();
        isPost = false;        //上传表示符号   23.8.24
        qDebug()<<"faollllllllllllllllllllllllllllllllllllllllllllldig";
    }

    m_pReplyDig->disconnect();
    m_pReplyDig->deleteLater();
    m_pReplyDig = nullptr;
}
void modulePostData::onTimerTimeOutSendData()
{
    postAnaData();
    postAccData();
    QTimer::singleShot(900000, this, SLOT(onTimerTimeOutSendData()));
}

void modulePostData::onPostDigData()
{
    QString digDate = "";
    digDate += DIG.policeDataDig.toHex();//超声波、tev
//    digDate += QString::number(DIG.alarm_Pop_ult);
//    digDate += QString::number(DIG.alarm_Tev);
    digDate += "," + DIG.McuState.toHex();//0x05
//    digDate += QString::number(DIG.alarm_Tev);

    digDate += "," + DIG.McuConnectState.toHex();//0x19
    digDate += "," + DIG.McuAlarmState.toHex();//0x15
    digDate += "," + DIG.wirelessTData_State.toHex();//0x18
    digDate += "," + QString::number(DIG.alarm_rxy);//热像仪掉线
    digDate += "," + DIG.rxy_img1;//热像仪1图片
    digDate += "," + DIG.rxy_img2;//热像仪2图片

    auto tp1 = std::chrono::system_clock::now();
    qint64 Secnum = std::chrono::system_clock::to_time_t(tp1);//转换为绝对秒数

    QString postanaurl = urlHead + "dps/rt/dig?ak";
    QUrl url(postanaurl);

    QJsonArray arr;
    QJsonObject object;

    object.insert("id", QJsonValue("288494437"));
    object.insert("flag", QJsonValue("0"));
    object.insert("value", QJsonValue(digDate));
    object.insert("status", QJsonValue("0"));
    object.insert("proctime", QJsonValue(Secnum));
    object.insert("procms", QJsonValue("0"));
    arr.append(object);
    QJsonDocument document=QJsonDocument(arr);

    QByteArray post_data = document.toJson(QJsonDocument::Compact);
    //qDebug()<<"digpostdata"<<post_data;

    QNetworkRequest request=QNetworkRequest(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("x-ie-access-key","nj4zddaqe7f6pe24re5ewo9ws46x0aq4");
    request.setRawHeader("x-ie-access-token",tokenStr.toLatin1());
    m_pNetWorkManagerDig->setNetworkAccessible(QNetworkAccessManager::Accessible);
    QNetworkReply* m_pNetworkReplyDig = m_pNetWorkManagerDig->post(request, post_data);

    connect(m_pNetworkReplyDig,SIGNAL(finished()),this,SLOT(on_finisheddig()));

    //m_loop.exec();
}
