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

HttpThread::HttpThread(QObject *parent) : QObject(parent)
{
    minute = 255;
    minute1 = 255;
    hour = 25;
    roomList.clear();
    keep = false;
    isWaiting = false;
    networkManager = new QNetworkAccessManager(this); //3-12层房间设备列表心跳数据
    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(1000);

}

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){
            QJsonArray list_array = doc.array();
            QString device_code = "";
            QString nodeInfo = "";
            double wd=0.00,sd=0.00,pm2_5=0.00,co2=0.00;
            int voc= 0;
            int fan_status = 0;
            int ts = (QDateTime::fromString(QDateTime::currentDateTime().toString("yyyy-MM-dd HH")+":00:00","yyyy-MM-dd HH:mm:ss")).toTime_t();
            int count = 0;
            for(int i=0;i<list_array.size();i++){
                QJsonObject list_object = list_array.at(i).toObject();
                device_code = list_object.value("roomNo").toString();
                QString attribute_name = list_object.value("name").toString();
                //printf("222  list_object.value(eventTime).toString() %s, eventTime %s \n",list_object.value("eventTime").toString().toUtf8().data(),eventTime.toUtf8().data());
                if(attribute_name.compare("新风系统-室内温度")==0){
                    wd = list_object.value("value").toDouble();
                    int tmpValue = list_object.value("value").toInt();
                    if(tmpValue == 0){
                        count++;
                    }
                    nodeInfo.append(QString("\"wd\":%1,").arg(wd));
                }
                if(attribute_name.compare("新风系统-室内湿度")==0){
                    sd = list_object.value("value").toDouble();
                    int tmpValue = list_object.value("value").toInt();
                    if(tmpValue == 0){
                        count++;
                    }
                    nodeInfo.append(QString("\"sd\":%1,").arg(sd));
                }
                if(attribute_name.compare("新风系统-室内PM2.5")==0){
                    pm2_5 = list_object.value("value").toDouble();
                    int tmpValue = list_object.value("value").toInt();
                    if(tmpValue == 0){
                        count++;
                    }
                    nodeInfo.append(QString("\"pm2_5\":%1,").arg(pm2_5));
                }
                if(attribute_name.compare("新风系统-室内CO2")==0){
                    co2 = list_object.value("value").toDouble();
                    int tmpValue = list_object.value("value").toInt();
                    if((tmpValue == 0)||(tmpValue == 244)){
                        count++;
                    }
                    nodeInfo.append(QString("\"co2\":%1,").arg(co2));
                }
                if(attribute_name.compare("新风系统-室内VOC等级")==0){
                    voc = list_object.value("value").toInt();
                    if(voc == 0){
                        count++;
                    }
                    nodeInfo.append(QString("\"voc\":%1,").arg(voc));
                }
                if(attribute_name.contains("排气扇")){
                    fan_status = list_object.value("value").toInt();
                    nodeInfo.append(QString("\"fan_status\":%1,").arg(fan_status));

                }

            }
            nodeInfo = nodeInfo.left(nodeInfo.length()-1);

            if(count < 5){
                for(int i=0;i<1024;i++){
                    if(agBoxShm->device[i].Enabled == 0x01){
                        if(device_code.compare(QString(agBoxShm->device[i].device_code))==0){
                            emit mqttData(QString("{\"device_id\":\"%1\",\"device_code\":\"%2\",\"product_id\":\"%3\",\"timestamp\":%4,\"tags\":{\"conn_type\":\"\",\"type\":\"\"},\"metrics\":{%5},\"device_type\":\"%6-xf\"}")
                                                                              .arg(QString(agBoxShm->device[i].device_id)).arg(device_code).arg(QString(agBoxShm->device[i].product_code)).arg(ts).arg(nodeInfo).arg(agBoxShm->device[i].device_type));
                            break;
                        }
                    }
                }
            }


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

        emit dataLog(QString("[%1] http room 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] http room QNetworkReply Status Err  %2").arg(QDateTime::fromTime_t(QDateTime::currentDateTime().toTime_t()).toString("yyyy-MM-dd HH:mm:ss")).arg(reply->error()));
    }

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

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

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("showapi_res_body");

            QJsonObject data_object = data_value.toObject();
            QJsonValue list_value = data_object.value("now");
            QJsonObject list_object = list_value.toObject();
            double wd = list_object.value("temperature").toString().toDouble();
            QString sdStr = list_object.value("sd").toString();
            double sd = sdStr.left(sdStr.length()-1).toDouble();

            QJsonValue aqi_detail = list_object.value("aqiDetail");
            QJsonObject detail_object = aqi_detail.toObject();
            double pm2_5 = detail_object.value("pm2_5").toString().toDouble();
            QString qual = detail_object.value("quality").toString();

            int quality = 0;
            if(qual.compare("优质")==0){
                quality = 1;
            }else if(qual.compare("良好")==0){
                quality = 2;
            }else if(qual.compare("轻度污染")==0){
                quality = 3;
            }else if(qual.compare("中度污染")==0){
                quality = 4;
            }else if(qual.compare("重度污染")==0){
                quality = 5;
            }else if(qual.compare("严重污染")==0){
                quality = 6;
            }

            emit mqttData(QString("{\"device_id\":\"%1\",\"device_code\":\"%2\",\"product_id\":\"%3\",\"timestamp\":%4,\"tags\":{\"conn_type\":\"\",\"type\":\"\"},\"metrics\":{\"wd\":%5,\"sd\":%6,\"pm2_5\":%7,\"quality\":%8},\"device_type\":\"%9-xf\"}")
                          .arg(QString("weather0001")).arg(QString("weather0001")).arg(QString("511_XFFJ")).arg(QDateTime::fromString(QDateTime::currentDateTime().toString("yyyy-MM-dd HH")+":00:00","yyyy-MM-dd HH:mm:ss").toTime_t()).arg(wd).arg(sd).arg(pm2_5).arg(quality).arg(511));


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

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

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

    if(hour != QDateTime::currentDateTime().time().hour()){
        hour = QDateTime::currentDateTime().time().hour();
        for(int i=0;i<1024;i++){
            if(QString("http").compare(QString(agBoxShm->device[i].device_gateway))==0){
                roomList.append(QString(agBoxShm->device[i].device_code));
            }
        }

        //每小时获取一次阿里天气数据
        if(!isWaiting1){
            isWaiting1 = true;
            QNetworkRequest *req = new QNetworkRequest();
            QString url = QString("https://weather01.market.alicloudapi.com/area-to-weather?area=历城区");
            req->setUrl(QUrl(url));
            req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
            req->setRawHeader("Accept","*/*");
            req->setRawHeader("Connection","keep-alive");
            req->setRawHeader("Cache-Control"," no-cache");
            req->setRawHeader("Authorization","APPCODE 0f2b7fce6e104ba8835358b7b59b4fb6");
            QNetworkReply *reply = networkManager1->get(*req);
            QReplayTimeout *pTimeout = new QReplayTimeout(reply,10000);
            connect(pTimeout, SIGNAL(net_timeout()),this,SLOT(reply_timeout1()));

        }

    }


    if(!isWaiting && roomList.length() > 0){  //每小时获取3-12层每个房间设备列表心跳数据一次
        isWaiting = true;
        QString roomNo = roomList.first();
        QNetworkRequest *req = new QNetworkRequest();
        QString url = QString("http://www.limark.net:81/api/hotel/control/device/list.do?hotelCode=ff80808179c6599a0179c65caf9a0001&roomNo=%1").arg(roomNo);
        req->setUrl(QUrl(url));
        req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
        req->setRawHeader("Accept","*/*");
        req->setRawHeader("Connection","keep-alive");
        req->setRawHeader("Cache-Control"," no-cache");
        req->setRawHeader("api-key","ff1930560ed8405382d49c6991861e75");
        QNetworkReply *reply = networkManager->get(*req);
        QReplayTimeout *pTimeout = new QReplayTimeout(reply,10000);
        connect(pTimeout, SIGNAL(net_timeout()),this,SLOT(reply_timeout()));

    }

}









