#include "NewHttpService.h"

NewHttpService::NewHttpService() {
}

NewHttpService::~NewHttpService() {
}

vides_data::response* NewHttpService::httpPostDeviceStatus(vides_data::requestDeviceStatus & deviceStatus) {
    httpUrl.append("/api/v1.0/device/ping");

    QJsonObject json;
    json.insert("sn",deviceStatus.sSn);
    json.insert("type",deviceStatus.type);
    json.insert("status",deviceStatus.status);
    QJsonDocument jsonDoc;
    jsonDoc.setObject(json);
    QByteArray bytearr= jsonDoc.toJson(QJsonDocument::Compact);

    vides_data::response *resp=new vides_data::response();
    QNetworkRequest request;
    request.setUrl(QUrl(httpUrl));
    request.setRawHeader(vides_data::HEADER_TYPE_KAY, vides_data::HEADER_TYPE_VALUE);
    if(m_httpClient.post(request,bytearr)){
        QByteArray && byte=m_httpClient.text().toUtf8();
        QJsonDocument docujson= QJsonDocument::fromJson(byte.data());
        QJsonObject maps= docujson.object();
        QVariantMap map =std::move(maps.toVariantMap());
        resp->code=map["code"].toInt();
        resp->msg=map["msg"].toString();
    }else{
        qDebug()<<m_httpClient.errorCode();
        resp->code=2;
        resp->msg=OPERATION_FAILED;
    }
    return resp;
}

vides_data::response *NewHttpService::httpFindCameras(QString &serialNumber,std::list<vides_data::responseDeviceStatus*>&datas) {
    httpUrl.append("/api/v1.0/device/all");
    vides_data::response *resp=new vides_data::response();
    QUrlQuery query;
    query.addQueryItem("sn",serialNumber);
    QNetworkRequest request;
    QUrl url(httpUrl);
    url.setQuery(query);
    request.setUrl(url);
    request.setRawHeader(vides_data::HEADER_TYPE_KAY, vides_data::HEADER_TYPE_VALUE);

    if(m_httpClient.get(request)){
        QByteArray && byte=m_httpClient.text().toUtf8();
        QJsonDocument docujson= QJsonDocument::fromJson(byte.data());
        QJsonObject maps= docujson.object();
        QVariantMap map =std::move(maps.toVariantMap());
        resp->code=map["code"].toInt();

        QJsonArray dataArray = map["data"].toJsonArray();  // 将"data"字段转换为QJsonArray

        for (const QJsonValue& value : dataArray) {
            vides_data::responseDeviceStatus *res=new  vides_data::responseDeviceStatus();
            QJsonObject dataObject = value.toObject();  // 将数组中的每个元素转换为QJsonObject
            // 从每个对象中获取所需的数据并进行处理
            QString sn = dataObject["sn"].toString();
            res->sSn=dataObject["sn"].toString();
            res->type=dataObject["type"].toInt();
            res->merchant_id= dataObject["merchant_id"].toInt();
            datas.push_back(res);
        }
        resp->msg=map["msg"].toString();
    }else{
        qDebug()<<m_httpClient.errorCode();
        resp->code=2;
        resp->msg=OPERATION_FAILED;
    }
    return resp;
}
