#include "billSocket.h"

#include <QtNetwork/QNetworkReply>
#include<QNetworkProxy>
#include "DTools/configManger.h"
#include "preDefine.h"
#include <QEventLoop>
#include <QTimer>
#include <QDebug>
#include "QsLog.h"

BillSocket::BillSocket(QObject *parent)
    : QObject(parent)
{
//    QNetworkProxy proxy;
//    proxy.setType (QNetworkProxy::HttpProxy);
//    proxy.setHostName (ConfigManger::GetInstance().getproxyIp());
//    proxy.setPort (ConfigManger::GetInstance().getproxyProt());
//    proxy.setHostName ("192.168.1.187");
//    proxy.setPort (8083);
//    QLOG_INFO()<<proxy.hostName()<<proxy.port();
//    if(!proxy.hostName().isEmpty())
//    {
//        m_networkManger.setProxy(proxy);
//    }
    m_current_url = 0;
    m_errorNum = 0;
    m_networkRequest.setUrl(ConfigManger::GetInstance().GetServerUrl());
    m_networkRequest.setRawHeader("Content-Type","text/json");
}

BillSocket::~BillSocket()
{

}

bool BillSocket::Request(const QJsonObject &requestJson, QJsonObject &recvJson, QString &error)
{
    if(QNetworkAccessManager::Accessible != m_networkManger.networkAccessible())
    {
        m_networkManger.setNetworkAccessible(QNetworkAccessManager::Accessible);
    }
    if(m_errorNum >= 5)
    {
        if(m_current_url==0)
        {
            m_alternateUrl = ConfigManger::GetInstance().GetServerUrl1();
            m_current_url = 1;
        }else
        {
            m_alternateUrl = ConfigManger::GetInstance().GetServerUrl();
            m_current_url = 0;
        }
        m_networkRequest.setUrl(m_alternateUrl);
        QLOG_INFO() << QString("change url to [%1]").arg(m_alternateUrl.toString());

        m_errorNum = 0;
    }

    QByteArray sendArray = QJsonDocument(requestJson).toJson(QJsonDocument::Compact);
    QEventLoop eventLoop;
    QNetworkReply *reply = m_networkManger.post(m_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()));
    // 加用定时器防止网络出现异常长时间不返回导致的阻塞
    QTimer::singleShot(VALUE_NETTIMEOUT, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

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

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

   return true;
}
