#include "HttpUpdateNodeApproval.h"

#include <QJsonDocument>
#include <QJsonObject>

#include "../usr/config.h"
#include "../interactive/InteractiveData.h"

HttpUpdateNodeApproval::HttpUpdateNodeApproval(QObject *parent)
    : QThread(parent)
{

}

void HttpUpdateNodeApproval::run()
{
    httpRequestUpdateNodeApproval();
}

void HttpUpdateNodeApproval::httpRequestUpdateNodeApproval()
{
    QJsonObject jsonRoot;
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qint64 timestampSeconds = currentDateTime.toMSecsSinceEpoch();

    QString url = Config()->updateNodeApprovalUrl;
    jsonRoot.insert("nodeId", this->m_nodeId);
    jsonRoot.insert("approvalStatus", this->m_approvalStatus);
    jsonRoot.insert("formData", this->m_formData);

    QJsonDocument jsonDoc(jsonRoot);
    QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);
    qDebug() << "json=" << QString::fromUtf8(jsonData);

    emit signalPostRequestData(timestampSeconds, url, jsonData, NULL, GetInteractiveData()->m_token);
}

void HttpUpdateNodeApproval::slotHttpResponseUpdateNodeApproval(QByteArray data)
{
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        emit signalUpdateNodeApprovalReturnStat(-3, "提交失败");
        return;
    }
    if(jsonDoc.isNull() || jsonDoc.isEmpty()) {
        emit signalUpdateNodeApprovalReturnStat(-3, "提交失败");
        return;
    }

    QJsonObject rootObj = jsonDoc.object();
    if(rootObj.contains("code"))
    {
        int codeValue = rootObj.value("code").toInt();
        if (codeValue == 408) {
            emit signalUpdateNodeApprovalReturnStat(408, "处理超时，请稍后重试。");
            return;
        }
        if(codeValue == 200 || codeValue == 0) {
            QString msg = "提交成功";
            if (rootObj.contains("msg")) {
                if (!rootObj.value("msg").toString().isEmpty()) {
                    msg = rootObj.value("msg").toString();
                }
            }
            emit signalUpdateNodeApprovalReturnStat(0, msg);
        }
        else {
            QString msg = "提交表单失败";
            if (rootObj.contains("msg")) {
                msg = rootObj.value("msg").toString();
            }
            emit signalUpdateNodeApprovalReturnStat(-3, msg);
        }
    }
}
