#include "fmnetwork.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QEventLoop>
#include <QTimer>
#include <QDebug>

FMNetwork::FMNetwork(QObject *parent) :
    QObject(parent),
    _nam(new QNetworkAccessManager),
    _req(new QNetworkRequest)
{

}

FMNetwork::~FMNetwork()
{
    delete _nam;
    delete _req;
}

bool FMNetwork::post(const QString &url, const QByteArray *reqData, QByteArray *rspData)
{
    qDebug() << "Post Url: " << url;
    qDebug() << "Post Data: " << *reqData;

    _req->setUrl(url);

    // 设置请求头
    _req->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    _req->setHeader(QNetworkRequest::ContentLengthHeader, reqData->length());

    auto reply = _nam->post(*_req, *reqData);

    // 使用定时器处理超时
    QEventLoop loop;
    connect(_nam, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
    QTimer timer;
    timer.setSingleShot(true);
    connect(&timer, SIGNAL(timeout()),&loop,SLOT(quit()));
    timer.start(1000 * 30);
    loop.exec();

    if(timer.isActive())
    {
        timer.stop();
        if (reply->error() == QNetworkReply::NoError) {
            *rspData = reply->readAll();
            qDebug() << tr("Recv data: ") << QString::fromUtf8(*rspData);
        } else {
            _errorString = reply->errorString();
            qDebug() << tr("Network error: %1").arg(_errorString);
            return false;
        }
    }else{
        _errorString = "Time out";
        qDebug() << tr("Network error: %1").arg(_errorString);
        return false;
    }
    return true;
}
