#include "packinfoseed2server.h"
#include <QTimer>
#include <QJsonDocument>
#include "globalinfo.h"

PackInfoSeed2Server::PackInfoSeed2Server(PackInfoManger * manger, QObject *parent, bool autoSync) : QObject(parent),
    _manger(manger),_autoSync(autoSync)
{
    connect(&_requst,&HttpRequest::result,this,&PackInfoSeed2Server::result);
    _netErrorCount = 0;
    _oneSyncError = 0;
    log = PQ::PQLogManger::this_()->getLog("PackInfoSeed2Server");
}

void PackInfoSeed2Server::send(QSharedPointer<PackInfo> & info)
{
    if(_manger == nullptr) return;
    _queue.append(info);
    QTimer::singleShot(20,this,&PackInfoSeed2Server::doSend);
}


void PackInfoSeed2Server::doSend()
{
    if(_current.isNull()){
        if(_queue.isEmpty()) {
            emit syncEnd();
            return;
        }
        _current = _queue.first();
        //docs： http://doc.vanlai.net:3001/web/#/1?page_id=64
//        if(_current->autoRuku == true){
//            QString url = GlobalInfo::this_()->config()->baseUrl+"/v1/product/directly/into";
//            _requst.setUserToken(QString::number(GlobalInfo::this_()->user().accountId),GlobalInfo::this_()->user().acessToken);
//            _requst.post(url,_current->toObject());
//            return;
//        }
        QString url = GlobalInfo::this_()->config()->baseUrl+"/v2/product/pending";
        _requst.setUserToken(QString::number(GlobalInfo::this_()->user().accountId),GlobalInfo::this_()->user().acessToken);
        _requst.post(url,_current->toObject());
    }
}

void PackInfoSeed2Server::sendList(QList<QSharedPointer<PackInfo>> & infos)
{
    if(_manger == nullptr) return;
    _queue.append(infos);
    QTimer::singleShot(20,this,&PackInfoSeed2Server::doSend);
}

void PackInfoSeed2Server::result(int code, const QJsonObject & body)
{
    qDebug()<<body;
    if(code != 200 || body.isEmpty()){
        _current.clear();
        QTimer::singleShot(500,this,&PackInfoSeed2Server::doSend);
        _netErrorCount ++;
        return;
    }
    auto error = body.value("code").toInt();
    auto message = body.value("message").toString();
    if(error == 200 || message.indexOf("已存在") >= 0){ // TODO： fix error
        _queue.dequeue();
        _manger->setPackInfoSync(_current->codeSingle(),_current->time(),_autoSync);

//        int product_id = body.value("data").toObject().value("product_id").toInt();

        _current.clear();
        QTimer::singleShot(20,this,&PackInfoSeed2Server::doSend);
        _netErrorCount = 0;
        _oneSyncError = 0;

    }else {
        _oneSyncError ++;
        if(_oneSyncError > 3){
            pqWarning(log) << "sync error,and to skip: data : \n" << QJsonDocument(_current->toObject()).toJson() <<
                              "\n error: \n " <<  QJsonDocument(body).toJson();
            _oneSyncError = 0;
            _queue.dequeue();
        }
        _current.clear();
        QTimer::singleShot(20,this,&PackInfoSeed2Server::doSend);
    }
}
