#include "fmnetwork.h"
#include <QTimer>
#include <QSettings>
#include <QEventLoop>
#include <QSslSocket>
#include <QSslConfiguration>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QFutureWatcher>
#include <QJsonDocument>
#include "tools.h"
#include "fmglobal.h"
#include "QsLog.h"
#include "fmtool.h"
#include "fmp_settings.h"
#include <QtConcurrent>
#include <QLibrary>

FMNetWork::FMNetWork(QObject *parent) : QObject(parent)
{
}

bool FMNetWork::HttpPost(QString url, QByteArray &outdata, const QByteArray &indata, QString content, QString accept, QString  &error, int timeout)
{
    FMPSettings setting;
    QString host = setting.GetValue(VALUE_HOST, "").toString();
    QEventLoop loop;
    QTimer timer;

    QSslConfiguration config = QSslConfiguration::defaultConfiguration();
    config.setPeerVerifyMode(QSslSocket::VerifyNone);

    QNetworkAccessManager manger;
    QNetworkRequest request(url);

    request.setSslConfiguration(config);
    request.setRawHeader("Content-Type", content.toUtf8());
    request.setRawHeader("Accept", accept.toUtf8());
    request.setRawHeader("Host", host.toUtf8());
    request.setRawHeader("Authorization", "Basic dXBzLWNsaWVudDo2VGk4TjBXNzRyb1A=");

    QLOG_INFO() << "HttpPost url: " << url << " content: " << content << " accept: " << accept << " timeout: " << timeout;

    QNetworkReply* reply = manger.post(request, indata);

    connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
    connect(&manger, &QNetworkAccessManager::finished, &loop, &QEventLoop::quit);
    connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), &loop, &QEventLoop::quit);
    timer.start(timeout*1000);

    loop.exec();
    reply->deleteLater();

    if(reply->error() != QNetworkReply::NoError) {
        QLOG_ERROR() << reply->errorString();
        error = QString::fromLocal8Bit("网络异常");
        return false;
    }

    outdata = reply->readAll();

    if(outdata.isEmpty()) {
        error = QString::fromLocal8Bit("返回数据为空");
        return false;
    }

    QLOG_INFO() << "HttpPost response: " << outdata.data();
    return true;

}
