#include "refundControl.h"
#include "QsLog.h"
#include <QJsonObject>
#include <QJsonDocument>
#include "DTools/dataManger.h"

RefundControl &RefundControl::GetInstance()
{
    static RefundControl rc;
    return rc;
}

void RefundControl::SetListenPort(int port)
{
    m_port = port;
}

RefundControl::~RefundControl()
{
    m_bContinue = false;
    m_mutex.lock();
    QLOG_INFO() << __FUNCTION__ << m_bContinue;
}

// 同步模式
void RefundControl::run()
{
    m_mutex.lock();
    m_procOrderSocket = new BillSocket(this);
    m_tcpServer = new QTcpServer(this);

    if(!m_tcpServer->listen(QHostAddress::LocalHost, m_port))
    {
        QLOG_WARN() << QString("tcp server listen failed on port[%1]").arg(m_port);
        return;
    }else
    {
        QLOG_INFO() << QString("tcp server listened on port[%1]").arg(m_port);
    }

    m_bContinue = true;

    QByteArray recvData;
    QString replyData;
    QJsonParseError jsonError;
    QJsonDocument jsonDoc;
    while(m_bContinue)
    {
        //QLOG_INFO() << "waiting new connection....";
        if(!m_tcpServer->waitForNewConnection(1000))
        {
            continue;
        }
        QLOG_INFO() << "onNewConnecion.....";

        QString error;
        QString orderId, reason; int version, reqtype;
        m_tcpSocket = m_tcpServer->nextPendingConnection();
        if(!m_tcpSocket->waitForReadyRead())
        {
            QLOG_INFO() << "read failed";
            m_tcpSocket->close();
            continue;
        }
        recvData = m_tcpSocket->readAll();
        QLOG_INFO() << QString("recv data.[%1]").arg(QString::fromLocal8Bit(recvData));

        jsonDoc = QJsonDocument::fromJson(QString::fromLocal8Bit(recvData).toUtf8(), &jsonError);
        if(jsonError.error == QJsonParseError::NoError)
        {
            QJsonObject jsonObject = jsonDoc.object();
            version = jsonObject["ver"].toInt();
            reqtype = jsonObject["reqtype"].toInt();
            orderId = jsonObject["order_id"].toString();
            reason = jsonObject["reason"].toString();;
            if(version == 1)
            {
                if(reqtype == 17)
                {
                    QString httpError;
                    bool httpResult;
                    QJsonObject httpSendJson;
                    QJsonObject httpRecvJson;

                    httpSendJson = DataManger::GetInstance().GetRefundOrderData(reason,orderId);
                    QLOG_INFO() << QString("[---refund order---]. [requestData:%1]")
                                   .arg(QString(QJsonDocument(httpSendJson).toJson(QJsonDocument::Compact).replace("\"","")));
                    httpResult = m_procOrderSocket->Request(httpSendJson, httpRecvJson, httpError);
                    QLOG_INFO() << QString("refund order finsh. [result:%1][msg:%2][recvData:%3]")
                                   .arg(httpResult).arg(httpError)
                                   .arg(QString(QJsonDocument(httpRecvJson).toJson(QJsonDocument::Compact).replace("\"","")));
                    if(httpResult)
                    {
                        if(100 == httpRecvJson["statusCode"].toInt() || 104 == httpRecvJson["statusCode"].toInt())
                        {
                            replyData = QString("{\"ver\":1, \"order_id\":\"%1\", \"statusCode\":100, \"msg\":\"\"}").arg(orderId);
                            m_tcpSocket->write(replyData.toUtf8());
                            m_tcpSocket->waitForBytesWritten(5000);
                            m_tcpSocket->close();
                            continue;
                        }else
                        {
                            error = QString(httpRecvJson["msg"].toString());
                        }
                    }else
                    {
                        error = httpError;
                    }
                }else
                {
                    error = QString("undefine reqtype [%1]").arg(reqtype);
                }
            }else
            {
                error = QString("wrong version, current[%1] right[1]").arg(version);
            }
        }else
        {
            error = "invalid data";
        }

        // 发生错误
        replyData = QString("{\"ver\":1, \"order_id\":\"%1\", \"statusCode\":101, \"msg\":\"%2\"}").arg(orderId).arg(error);
        m_tcpSocket->write(replyData.toLocal8Bit());
        m_tcpSocket->waitForBytesWritten(5000);
        m_tcpSocket->close();
        continue;
    }
    m_tcpServer->close();
    m_tcpServer->deleteLater();

    m_mutex.unlock();
    QLOG_INFO() << "refundControl exit.";
}
