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

HttpThread::HttpThread(QObject *parent) : QObject(parent)
{
    minute = 255;
    minute1 = 255;
    hour = 25;
    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 *)));

    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("event 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()){
                emit appendSql(QString("delete from event_eg where event_time >= '%1' and event_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_code = list_object.value("doorIndexCode").toString();
                    QString doorName = list_object.value("doorName").toString();
                    QString personName = list_object.value("personName").toString();
                    QString cardNo = list_object.value("cardNo").toString();
                    QString orgName = list_object.value("orgName").toString();
                    int eventType = list_object.value("eventType").toInt();
                    int inAndOutType = list_object.value("inAndOutType").toInt();
                    QString eventTime = list_object.value("eventTime").toString();
                    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 event_eg (id, device_id, device_code, device_name, install_address, person_name, card_no, org_name, event_type, in_out_type, event_time) values(null,'%1','%2','%3','%4','%5','%6','%7',%8,%9,'%10');")
                                              .arg(QString(boxDeviceShm->device[i].device_id)).arg(device_code).arg(doorName).arg("").arg(personName).arg(cardNo).arg(orgName).arg(eventType).arg(inAndOutType).arg(eventTime));
                                break;
                            }
                        }
                    }


                }
            }


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

        emit dataLog(QString("[%1] event 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] event 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] event 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("authDoorList");
            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("doorIndexCode").toString();
                    int doorState = list_object.value("doorState").toInt();
                    int deviceStatus = 0;
                    if(doorState==3){
                        deviceStatus = 0;
                    }else{
                        deviceStatus = 1;
                    }
                    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,\"door_status\":%6},\"device_type\":\"%7-eg\"}")
                                              .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(doorState).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::time_out()
{
    agBoxShm->processStatus[2].t_time=QDateTime::currentDateTime().toTime_t();

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

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

        if(!isWaiting){
            isWaiting = true;
            QNetworkRequest *req = new QNetworkRequest();
            req->setUrl(QUrl("https://172.17.200.250:443/artemis/api/acs/v1/door/events"));
            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","zocGT3eKtbbUyljDBPf4yoQPoFdN97+Mg4fCc9Ki4jE=");
            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("{\"startTime\": \"%1\",\"endTime\": \"%2\",\"pageNo\": 1,\"pageSize\": 500}").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 = 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("https://172.17.200.250:443/artemis/api/acs/v1/door/states"));
          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","FZRWBzzvzp8mDxFSpLHGdtNaot1PfNvpMbCaoT+dDLw=");
          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("{}");
          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()));

      }
  }

}









