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


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

}

bool FMNetWork::HttpPost(QString url, QByteArray &outdata, const QByteArray &indata, QString content, QString accept, QString  &error, int timeout)
{
    QString path;
    ToolS::GetPath(path);

    QString host = QSettings(path + "\\" + USERCONFIG_NAME, QSettings::IniFormat).value(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=");


    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() << outdata.data();

    return true;
}
