#include "InteractiveHttp.h"
//#include "InteractiveData.h"

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

QString InteractiveHttp::strToken;

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

}


bool InteractiveHttp::httpRequestGet(const QString &url, const QByteArray &inData, QByteArray &outData)
{
    QNetworkAccessManager* pHttpMgr = new QNetworkAccessManager();
    QString strUrl = url;
    if(false == inData.isNull())
    {
        strUrl = strUrl + "?" + inData;
    }
    // 设置头信息
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(strUrl));
    requestInfo.setRawHeader("Authorization", InteractiveHttp::strToken.toUtf8());

    // 发送 post 请求
    QNetworkReply* reply = pHttpMgr->get(requestInfo);

    // 添加超时处理，1ms 超时
    QEventLoop eventLoop;
    connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));

    // 比如设置 1ms 内完成请求，否则就认为是超时
    QTimer::singleShot(HTTP_REQUEST_TIMEOUT_TIME, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    QByteArray array;
    if(reply->isFinished()){
        if (reply->error() == QNetworkReply::NoError) {
            // 正常结束，读取响应数据
            QByteArray result = reply->readAll();
            QString strResult = QString::fromUtf8(result);
            reply->deleteLater();
            outData = strResult.toUtf8();
            return true;
        }
        else {
            // 请求失败
            QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

            outData = QString("{\"code\":" + statusCode.toString() + ",\"result\":\"" + reply->errorString() + "\"}").toUtf8();
            reply->deleteLater();
            return false;
        }
    }
    else {
        // 请求超时
        disconnect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
        reply->abort();

    }

    reply->deleteLater();

    outData =  "{\"code\":400,\"result\":\"failure\"}";
    return false;
}

bool InteractiveHttp::httpRequestPostJson(const QString &url, const QByteArray &inData, QByteArray &outData)
{
    // 获取当前日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString timetamp_str = currentDateTime.toString("yyyy-MM-ddTHH:mm:ssZ");

    QNetworkAccessManager* pHttpMgr = new QNetworkAccessManager();
    QString strUrl = url;
    // 设置头信息
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(strUrl));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    requestInfo.setRawHeader("Module", "Android_Material");
    requestInfo.setRawHeader("Authorization", InteractiveHttp::strToken.toUtf8());

    // 发送 post 请求
    QNetworkReply* reply = pHttpMgr->post(requestInfo, inData);

    // 添加超时处理，1ms 超时
    QEventLoop eventLoop;
    connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));

    // 比如设置 1ms 内完成请求，否则就认为是超时
    QTimer::singleShot(HTTP_REQUEST_TIMEOUT_TIME, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    if(reply->isFinished()){
        if (reply->error() == QNetworkReply::NoError) {
            // 正常结束，读取响应数据
            QByteArray result = reply->readAll();
            outData = result;
            reply->deleteLater();
            return true;
        }
        else {
            // 请求失败
            QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

            // qDebug() << "http post failed, error code = " << statusCode.toString() << " error info: " << reply->errorString();
            outData = QString("{\"code\":" + statusCode.toString() + ",\"result\":\"" + reply->errorString() + "\"}").toUtf8();
            reply->deleteLater();
            return false;
        }
    }
    else {
        // 请求超时
        disconnect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
        reply->abort();
    }

    reply->deleteLater();

    outData = "{\"code\":400,\"result\":\"failure\"}";
    return false;
}

bool InteractiveHttp::httpRequestPostFormdata(const QString &url, QList<QHttpPart> &inData, QByteArray &outData)
{
    // 获取当前日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString timetamp_str = currentDateTime.toString("yyyy-MM-ddTHH:mm:ssZ");

    QNetworkAccessManager* pHttpMgr = new QNetworkAccessManager();
    QString strUrl = url;

    // 创建multipart表单
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    for (int i = 0; i < inData.size(); ++i)
    {
        multiPart->append(inData.at(i));
    }


    // 设置头信息
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + multiPart->boundary());
    requestInfo.setRawHeader("Module", "Android_Material");
    requestInfo.setRawHeader("Authorization", InteractiveHttp::strToken.toUtf8());

    // 发送 post 请求
    QNetworkReply* reply = pHttpMgr->post(requestInfo, multiPart);
    multiPart->setParent(reply); // reply删除时会自动删除multiPart

    // 添加超时处理，1ms 超时
    QEventLoop eventLoop;
    connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));

    // 比如设置 1ms 内完成请求，否则就认为是超时
    QTimer::singleShot(HTTP_REQUEST_TIMEOUT_TIME, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    if(reply->isFinished()){
        if (reply->error() == QNetworkReply::NoError) {
            // 正常结束，读取响应数据
            QByteArray result = reply->readAll();
            outData = result;
            reply->deleteLater();
            return true;
        }
        else {
            // 请求失败
            QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
            // qDebug() << "http post failed, error code = " << statusCode.toString() << " error info: " << reply->errorString();
            outData = QString("{\"code\":" + statusCode.toString() + ",\"result\":\"" + reply->errorString() + "\"}").toUtf8();
            reply->deleteLater();
            return false;
        }
    }
    else {
        // 请求超时
        disconnect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
        reply->abort();
    }

    reply->deleteLater();

    outData = "{\"code\":400,\"result\":\"failure\"}";
    return false;
}

// 获取异常类型字典值
QByteArray InteractiveHttp::http_get_exception_type()
{
    QString strUrl = "http://" + Config()->httpHost + "/system/dict/data/type/material_exception";
    QByteArray inData;
    QByteArray outData;

    httpRequestGet(strUrl, inData, outData);

    return outData;
}

// 获取严重等级字典值
QByteArray InteractiveHttp::http_get_severity_level()
{
    QString strUrl = "http://" + Config()->httpHost + "/system/dict/data/type/severity_level";
    QByteArray inData;
    QByteArray outData;

    httpRequestGet(strUrl, inData, outData);

    return outData;
}

// 获取用户信息
QByteArray InteractiveHttp::http_get_getInfo()
{
    // 访问http服务
    QString strUrl = "http://" + Config()->httpHost + Config()->getInfo_url;
    QByteArray inData;
    QByteArray outData;

    httpRequestGet(strUrl, inData, outData);

    return outData;
}

// 用于临时存储服务器请求响应的函数
// TempWriteData("C:/Users/HP/Desktop/Temp/0.txt", outData);
void InteractiveHttp::TempWriteData(const QString &path, const QByteArray &data)
{
    QFile file(path);
    if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        file.write(data);
        file.close();
    }
}
