#include "workobject.h"
#include <QThread>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument>
#include "preDefine.h"

WorkObject::WorkObject(QObject *parent) : QObject(parent)
{
    _stopflag = false;
    _stoped = false;
}

WorkObject::~WorkObject()
{
    emit workclose();

    if(this->thread() != QThread::currentThread())
    {
       this->thread()->wait(20);
    }
}

void WorkObject::moveToThread(QThread *thread, bool with_thread_start)
{
    if(with_thread_start)
    {
        connect(thread, &QThread::started, this, &WorkObject::workstart);
        connect(this, &WorkObject::workclose, thread, &QThread::quit);
    }

    QObject::moveToThread(thread);
}

bool WorkObject::S_Request(const QJsonObject &requestJson, QJsonObject &recvJson, QString url, QString &error, QByteArray contentype)
{
    QNetworkAccessManager m_networkManger;

    if(QNetworkAccessManager::Accessible != m_networkManger.networkAccessible())
    {
        m_networkManger.setNetworkAccessible(QNetworkAccessManager::Accessible);
    }

    QNetworkRequest networkRequest;
    networkRequest.setUrl(url);
    networkRequest.setRawHeader("Content-Type",contentype);

    QByteArray sendArray = QJsonDocument(requestJson).toJson(QJsonDocument::Compact);
    QEventLoop eventLoop;
    QNetworkReply *reply = m_networkManger.post(networkRequest , sendArray);
    connect(&m_networkManger, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)), &eventLoop, SLOT(quit()));
    connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &eventLoop, SLOT(quit()));
    connect(this, &WorkObject::quit, &eventLoop,&QEventLoop::quit);
    // 加用定时器防止网络出现异常长时间不返回导致的阻塞
    QTimer::singleShot(JSON_LOGIN_TIMEOUT, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

   if(reply->error() != QNetworkReply::NoError)
   {
       error = reply->errorString();
       return false;
   }

   QByteArray recvArray = reply->readAll();
   if(recvArray.size() == 0)
   {
       error = "nothing recved";
       return false;
   }
   recvJson = QJsonDocument::fromJson(recvArray).object();
   qDebug() << recvJson;
   reply->deleteLater();

   return true;
}

void WorkObject::workstart()
{
    _stoped = true;
}

