#include "httpthread.h"
#include "../agVideoProcess/boxdeviceshm.h"
#include "../AGBoxDog/boxshm.h"

HttpThread::HttpThread(QObject *parent) : QObject(parent)
{
    minute = 255;
    minute1 = 255;
    minute2 = 255;
    list<<245<<246<<247<<248<<249<<250;
    keep = false;
    isWaiting = false;
    networkManager = new QNetworkAccessManager(this); //机房系统设备心跳数据
    connect(networkManager,SIGNAL(finished(QNetworkReply *)),this,SLOT(finishedSlot(QNetworkReply *)));
    isWaiting1 = false;
    networkManager1 = new QNetworkAccessManager(this); //机房系统设备状态
    connect(networkManager1,SIGNAL(finished(QNetworkReply *)),this,SLOT(finishedSlot1(QNetworkReply *)));
    isWaiting2 = false;
    networkManager2 = new QNetworkAccessManager(this); //机房系统设备告警数据
    connect(networkManager2,SIGNAL(finished(QNetworkReply *)),this,SLOT(finishedSlot2(QNetworkReply *)));

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&HttpThread::time_out);
    timer->start(5000);

}

void HttpThread::stop()
{
    keep = false;
}

void  HttpThread::finishedSlot(QNetworkReply *reply)
{
    if(reply->error()==QNetworkReply::NoError){
        QString data = QString::fromUtf8(reply->readAll());
        QByteArray ba = data.toLocal8Bit();
        ba = QString::fromLocal8Bit(ba).toUtf8();
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(ba,&parseError);
        printf("attribute data parseError.error %d\n",parseError.error);
        if(parseError.error == QJsonParseError::NoError){
            QString nodeInfo = "";
            QString deviceId = "";
            QString companyCode = "";
            QString deviceType = "";
            QJsonObject obj_doc = doc.object();
            QJsonValue data_value = obj_doc.value("data");
            QJsonObject data_object = data_value.toObject();
            QJsonValue list_value = data_object.value("data");
            if(list_value.isArray()){
                QJsonArray list_array = list_value.toArray();

                QJsonObject list_object0 = list_array.at(0).toObject();
                QString device_code = QString::number(list_object0.value("node_id").toInt());
                printf("attribute data device_code %s\n",device_code.toUtf8().data());
                for(int i=0;i<1024;i++){
                    if(boxDeviceShm->device[i].Enabled == 0x01){
                        if(device_code.compare(QString(boxDeviceShm->device[i].device_code))==0){
                            deviceId = QString(boxDeviceShm->device[i].device_id);
                            companyCode = QString(boxDeviceShm->device[i].company_code);
                            deviceType = QString::number(boxDeviceShm->device[i].device_type);
                            break;
                        }
                    }
                }

                for(int i=0;i<list_array.size();i++){
                    QJsonObject list_object = list_array.at(i).toObject();
                    QString name = list_object.value("name").toString();
                    double value = list_object.value("sdata").toDouble();

                    for(int j=0;j<300;j++){
                        if(name.compare(QString(boxDeviceShm->procuctattrbute[j].attribute_name))==0){
                            nodeInfo.append(QString("\"%1\":%2,").arg(QString(boxDeviceShm->procuctattrbute[j].attribute_code)).arg(value));
                            break;
                        }
                    }

                }
                nodeInfo=nodeInfo.left(nodeInfo.length()-1);
                emit mqttData(QString("{\"device_id\":\"%1\",\"device_code\":\"%2\",\"product_id\":\"%3\",\"timestamp\":%4,\"tags\":{\"conn_type\":\"\",\"type\":\"\"},\"metrics\":{%5},\"device_type\":\"%6-gr\"}")
                              .arg(deviceId).arg(device_code).arg(companyCode).arg(QDateTime::currentDateTime().toTime_t()).arg(nodeInfo).arg(deviceType));
            }

        }else{
            emit dataLog(QString("attribute data QJson Parse  Error  %1").arg(parseError.error));
        }

        emit dataLog(QString("[%1] attribute data QNetworkReply Status %2").arg(QDateTime::fromTime_t(QDateTime::currentDateTime().toTime_t()).toString("yyyy-MM-dd HH:mm:ss")).arg(data));
    }else{
        emit dataLog(QString("[%1] attribute data QNetworkReply Status Err  %2").arg(QDateTime::fromTime_t(QDateTime::currentDateTime().toTime_t()).toString("yyyy-MM-dd HH:mm:ss")).arg(reply->error()));
    }

    isWaiting = false;
    reply->abort();
    reply->deleteLater();
}

void HttpThread::reply_timeout()
{
    printf("[%s] attribute data reply_timeout\n",QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toUtf8().data());
    isWaiting = false;
}

void  HttpThread::finishedSlot1(QNetworkReply *reply)
{
    if(reply->error()==QNetworkReply::NoError){
        QString data = QString::fromUtf8(reply->readAll());
        QByteArray ba = data.toLocal8Bit();
        ba = QString::fromLocal8Bit(ba).toUtf8();
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(ba,&parseError);
        printf("status parseError.error %d\n",parseError.error);
        if(parseError.error == QJsonParseError::NoError){
            QJsonObject obj_doc = doc.object();
            QJsonValue data_value = obj_doc.value("data");

            QJsonObject data_object = data_value.toObject();
            QJsonValue list_value = data_object.value("data");
            if(list_value.isArray()){
                QJsonArray list_array = list_value.toArray();
                for(int i=0;i<list_array.size();i++){
                    QJsonObject list_object = list_array.at(i).toObject();
                    QString device_code = QString::number(list_object.value("id").toInt());
                    QJsonValue status_value = list_object.value("data");
                    QJsonObject status_object = status_value.toObject();
                    QString status = status_object.value("iot_node_status").toString();

                    int deviceStatus = 0;
                    if(status.compare("在线")==0){
                        deviceStatus = 1;
                    }else{
                        deviceStatus = 0;
                    }
                    for(int i=0;i<1024;i++){
                        if(boxDeviceShm->device[i].Enabled == 0x01){
                            if(device_code.compare(QString(boxDeviceShm->device[i].device_code))==0){
                                emit mqttData(QString("{\"device_id\":\"%1\",\"device_code\":\"%2\",\"product_id\":\"%3\",\"timestamp\":%4,\"tags\":{\"conn_type\":\"\",\"type\":\"\"},\"metrics\":{\"device_status\":%5},\"device_type\":\"%6-gr\"}")
                                              .arg(QString(boxDeviceShm->device[i].device_id)).arg(device_code).arg(QString(boxDeviceShm->device[i].company_code)).arg(QDateTime::currentDateTime().toTime_t()).arg(deviceStatus).arg(boxDeviceShm->device[i].device_type));
                                break;
                            }
                        }
                    }


                }
            }


        }else{
            emit dataLog(QString("status QJson Parse  Error  %1").arg(parseError.error));
        }

        emit dataLog(QString("[%1] status QNetworkReply Status %2").arg(QDateTime::fromTime_t(QDateTime::currentDateTime().toTime_t()).toString("yyyy-MM-dd HH:mm:ss")).arg(data));
    }else{
        emit dataLog(QString("[%1] status QNetworkReply Status Err  %2").arg(QDateTime::fromTime_t(QDateTime::currentDateTime().toTime_t()).toString("yyyy-MM-dd HH:mm:ss")).arg(reply->error()));
    }

    isWaiting1 = false;
    reply->abort();
    reply->deleteLater();
}

void HttpThread::reply_timeout1()
{
    printf("[%s] status reply_timeout\n",QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toUtf8().data());
    isWaiting1 = false;
}

void  HttpThread::finishedSlot2(QNetworkReply *reply)
{
    if(reply->error()==QNetworkReply::NoError){
        QString data = QString::fromUtf8(reply->readAll());
        QByteArray ba = data.toLocal8Bit();
        ba = QString::fromLocal8Bit(ba).toUtf8();
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(ba,&parseError);
        printf("alarm parseError.error %d\n",parseError.error);
        if(parseError.error == QJsonParseError::NoError){
            QJsonObject obj_doc = doc.object();
            QJsonValue data_value = obj_doc.value("data");
            QJsonObject data_object = data_value.toObject();
            QJsonValue list_value = data_object.value("data");
            if(list_value.isArray()){
                emit appendSql(QString("delete from alarm_gr where alarm_time >= '%1' and alarm_time <= '%2';").arg(startTime).arg(endTime));
                QJsonArray list_array = list_value.toArray();
                for(int i=0;i<list_array.size();i++){
                    QJsonObject list_object = list_array.at(i).toObject();
                    QString device_name = list_object.value("node_name").toString();
                    QString device_code = "";
                    if(device_name.compare("温湿度监控")==0){
                        device_code = QString("245");
                    }else if(device_name.compare("数据采集主机")==0){
                        device_code = QString("246");
                    }else if(device_name.compare("市电监测")==0){
                        device_code = QString("247");
                    }else if(device_name.compare("UPS监测")==0){
                        device_code = QString("248");
                    }else if(device_name.compare("黑盾精密空调1")==0){
                        device_code = QString("249");
                    }else if(device_name.compare("黑盾精密空调2")==0){
                        device_code = QString("250");
                    }

                    QJsonValue alarm_value = list_object.value("data");
                    QJsonObject alarm_object = alarm_value.toObject();
                    QString alarmLevel = alarm_object.value("iot_trigger_alarm_level").toString();
                    QString handling_status = alarm_object.value("iot_trigger_alarm_level").toString();
                    int handlingStatus = 0;
                    if(handling_status.compare("未处理")==0){
                        handlingStatus = 0;
                    }else{
                        handlingStatus = 1;
                    }
                    QString alarmDesc = list_object.value("description").toString();
                    QString alarmTime = list_object.value("atimestr").toString();
                    double alarmValue = list_object.value("sdata").toDouble();
                    for(int i=0;i<1024;i++){
                        if(boxDeviceShm->device[i].Enabled == 0x01){
                            if(device_code.compare(QString(boxDeviceShm->device[i].device_code))==0){
                                emit appendSql(QString::fromLocal8Bit("insert into alarm_gr(device_id, device_code, device_name, alarm_type, alarm_desc, alarm_time, alarm_value, handling_status) values('%1','%2','%3','%4','%5','%6',%7,%8);")
                                              .arg(QString(boxDeviceShm->device[i].device_id)).arg(device_code).arg(device_name).arg(alarmLevel).arg(alarmDesc).arg(alarmTime).arg(alarmValue).arg(handlingStatus));
                                break;
                            }
                        }
                    }


                }
            }


        }else{
            emit dataLog(QString("alarm QJson Parse  Error  %1").arg(parseError.error));
        }

        emit dataLog(QString("[%1] alarm QNetworkReply Status %2").arg(QDateTime::fromTime_t(QDateTime::currentDateTime().toTime_t()).toString("yyyy-MM-dd HH:mm:ss")).arg(data));
    }else{
        emit dataLog(QString("[%1] alarm QNetworkReply Status Err  %2").arg(QDateTime::fromTime_t(QDateTime::currentDateTime().toTime_t()).toString("yyyy-MM-dd HH:mm:ss")).arg(reply->error()));
    }

    isWaiting2 = false;
    reply->abort();
    reply->deleteLater();
}

void HttpThread::reply_timeout2()
{
    printf("[%s] alarm reply_timeout\n",QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toUtf8().data());
    isWaiting2 = false;
}

void HttpThread::time_out()
{
    agBoxShm->processStatus[4].t_time=QDateTime::currentDateTime().toTime_t();

    if(QDateTime::currentDateTime().time().minute()!=minute){//每分钟执行一次，同步设备属性数据
        minute = QDateTime::currentDateTime().time().minute();

        if(!isWaiting){
            for(int i=0;i<list.size();i++){
                isWaiting = true;
                QNetworkRequest *req = new QNetworkRequest();
                req->setUrl(QUrl("http://172.17.200.209:8080/service/page/sensor.json?paged=1&pageSize=30"));
                req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
                req->setRawHeader("USER-KEY","426aad8a150a4d85a8fa7221085edca3");
                QString postdata = QString("{\"node_id\": %1}").arg(list.at(i));
                req->setRawHeader("Content_Length",QString("%1").arg(postdata.length()).toUtf8());
                QNetworkReply *reply = networkManager->post(*req,postdata.toUtf8());
                QReplayTimeout *pTimeout = new QReplayTimeout(reply,10000);
                connect(pTimeout, SIGNAL(net_timeout()),this,SLOT(reply_timeout()));

            }

        }
    }

    if(QDateTime::currentDateTime().time().minute()!=minute1){//每半个小时执行一次，同步设备状态
      minute1 = QDateTime::currentDateTime().time().minute();
      if(!isWaiting1 && ((minute1==00)||(minute1==30))){
          isWaiting1 = true;
          QNetworkRequest *req = new QNetworkRequest();
          req->setUrl(QUrl("http://172.17.200.209:8080/service/page/node.json?paged=1"));
          req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
          req->setRawHeader("USER-KEY","426aad8a150a4d85a8fa7221085edca3");
          QString postdata = QString("{\"scene_id\": 31}");
          req->setRawHeader("Content_Length",QString("%1").arg(postdata.length()).toUtf8());
          QNetworkReply *reply = networkManager1->post(*req,postdata.toUtf8());
          QReplayTimeout *pTimeout = new QReplayTimeout(reply,10000);
          connect(pTimeout, SIGNAL(net_timeout()),this,SLOT(reply_timeout1()));

      }
  }

    if(QDateTime::currentDateTime().time().minute()!=minute2){//每分钟执行一次，统计从现在算起之前10分钟时间内的机房告警记录（插入之前先执行删除这个时间端数据的命令）
        minute2 = QDateTime::currentDateTime().time().minute();
        QString tempTime1 = QDateTime::currentDateTime().addSecs(-600).toString("yyyy-MM-dd HH:mm");
        QString tempTime2 = QDateTime::currentDateTime().addSecs(-60).toString("yyyy-MM-dd HH:mm");
        startTime = QString("%1:00").arg(tempTime1);
        endTime = QString("%1:59").arg(tempTime2);

        printf("startTime: %s, endTime %s\n",startTime.toUtf8().data(),endTime.toUtf8().data());

        if(!isWaiting2){
            isWaiting2 = true;
            QNetworkRequest *req = new QNetworkRequest();
            req->setUrl(QUrl("http://172.17.200.209:8080/service/page/alarm.json?paged=1&pageSize=50"));
            req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
            req->setRawHeader("USER-KEY","426aad8a150a4d85a8fa7221085edca3");
            QString postdata = QString("{\"start_time\": \"%1\",\"end_time\": \"%2\"}").arg(startTime).arg(endTime);
            emit dataLog(QString(" events QNetworkReply event [%1]").arg(postdata));
            req->setRawHeader("Content_Length",QString("%1").arg(postdata.length()).toUtf8());
            QNetworkReply *reply = networkManager2->post(*req,postdata.toUtf8());
            QReplayTimeout *pTimeout = new QReplayTimeout(reply,10000);
            connect(pTimeout, SIGNAL(net_timeout()),this,SLOT(reply_timeout2()));

        }
    }

}









