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

HttpThread::HttpThread(QObject *parent) : QObject(parent)
{
    minute = 255;
    hour = 25;
    keep = false;
    isWaiting = false;
    networkManager = new QNetworkAccessManager(this);
    connect(networkManager,SIGNAL(finished(QNetworkReply *)),this,SLOT(finishedSlot(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("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("list");
            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 = list_object.value("indexCode").toString();
                    int device_status = list_object.value("online").toInt();
                    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-vd\"}")
                                              .arg(QString(boxDeviceShm->device[i].device_id)).arg(device_code).arg(QString(boxDeviceShm->device[i].company_code)).arg(QDateTime::currentDateTime().toTime_t()).arg(device_status).arg(boxDeviceShm->device[i].device_type));
                                break;
                            }
                        }
                    }


                }
            }


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

        emit dataLog(QString("[%1] 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] 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] reply_timeout\n",QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss").toUtf8().data());
    isWaiting = false;
}

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

//    if(((QDateTime::currentDateTime().time().minute())%5==0) && (QDateTime::currentDateTime().time().minute()!=minute)){//每5分钟执行一次
      if(QDateTime::currentDateTime().time().minute()!=minute){//每半小时执行一次
        minute = QDateTime::currentDateTime().time().minute();
        if(!isWaiting && ((minute==00)||(minute==30))){
            isWaiting = true;
            QNetworkRequest *req = new QNetworkRequest();
            req->setUrl(QUrl("https://172.17.200.250:443/artemis/api/nms/v1/online/camera/get"));
            req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
            req->setRawHeader("Accept","*/*");
            req->setRawHeader("Connection","keep-alive");
            req->setRawHeader("Cache-Control"," no-cache");
            req->setRawHeader("X-Ca-Key","27997984");
            req->setRawHeader("X-Ca-Signature","a9kzGHD938rFhCfWVlGB6eO0bZ0SQbhzSwXlT+FMh+Q=");
            req->setRawHeader("X-Ca-Signature-Headers","x-ca-key");
            config = req->sslConfiguration();
            config.setPeerVerifyMode(QSslSocket::VerifyNone);
            config.setProtocol(QSsl::TlsV1_0OrLater);
            req->setSslConfiguration(config);
            QString postdata = QString("{\"pageNo\": 1,\"pageSize\": 500}");
            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()));

        }
    }

}









