#include "rollback.h"
#include "fmglobal.h"
#include <QSqlQuery>
#include <QEventLoop>
#include <QJsonDocument>
#include <QTimer>
#include <QSettings>
#include <QJsonObject>
#include "tools.h"
#include "QsLog.h"
#include "cretopt.h"
#include "fmnetwork.h"
#include <QtConcurrent>

RollBack::RollBack(QObject *parent) : QThread(parent)
{
    QString path;
    ToolS::GetPath(path);

    qDebug() << "++++++++++++++++++++++++++++" << path;

    _db = new FMPDataBase(path + DB_ORDER, QString("rollback"));
    _spr.release(10);
}

RollBack::~RollBack()
{
    requestInterruption();
    wait();

    if(_db != NULL)
    {
        delete _db;
        _db = NULL;
    }

}

void RollBack::RollWiteQuery(QSqlQuery &query)
{
    while(query.next())
    {
        QString parnetid = query.value(0).toString();
        QString content = query.value(1).toString();

        QJsonDocument jsonDocument = QJsonDocument::fromJson(content.toUtf8());

        if( jsonDocument.isNull() )
        {
            QLOG_ERROR() << "content not json:" << content;
            _db->dlt(DB_TABLE_NAME, QString("%1='%2'").arg(SQL_KEY_ORDERID).arg(parnetid));
        }

        QJsonObject json = jsonDocument.object();

        json.insert(JSON_KEY_REQTYPE, 3);

        if(!CretOperate::GetSign(json))
        {
            QLOG_ERROR() << "get sign error";
            continue;
        }

        QLOG_INFO() << json;

        QByteArray data = QJsonDocument(json).toJson(QJsonDocument::Compact);

        _spr.acquire();

        QtConcurrent::run( [this, parnetid, data]()
        {
            QByteArray array;

            QString path;
            QString error;
            ToolS::GetPath(path);

            qDebug() << "*****************************" << path;

            QString url = QSettings(path + "\\" + USERCONFIG_NAME, QSettings::IniFormat).value(VALUE_URL).toString();

            if(FMNetWork::HttpPost(url, array, data, "application/json;charset=utf-8","application/json", error, 25))
            {
                QString path;
                ToolS::GetPath(path);
                FMPDataBase db(path + "\\" + DB_ORDER, QString("curr") + QString::number((int)QThread::currentThreadId()));
                db.dlt(DB_TABLE_NAME, QString("%1='%2'").arg(SQL_KEY_ORDERID).arg(parnetid));
            }

            QLOG_WARN() << QThread::currentThreadId() << ":" << array;

            this->_spr.release();
        });
    }
}

void RollBack::run()
{
    while(!isInterruptionRequested())
    {
        QString path;

        ToolS::GetPath(path);

        qDebug() << "======================" << path;

        int timeout = QSettings(path + "\\" + USERCONFIG_NAME, QSettings::IniFormat).value(VALUE_TIMEOUT).toInt();

        if(timeout == 0)
            timeout = 30;

        do
        {
            QSqlQuery query;

            if(!_db->find(DB_TABLE_NAME, query))
                break;

            RollWiteQuery(query);

        }while(0);

        QEventLoop loop;
        QTimer timer;
        connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
        timer.start(timeout*1000);

        loop.exec();
    }
}
