#include "projectinfomanger.h"
#include <QTimer>
#include "globalinfo.h"
#include <QSet>
#include <pqQtlib/utils/pqfileutils.h>
#include <QJsonDocument>

ProjectInfoManger::ProjectInfoManger(PackInfoManger *manger, QObject *parent) : QObject(parent),_manger(manger)
{
    connect(&_requst,&HttpRequest::result,this,&ProjectInfoManger::result);
    _nowJob = 0;
    _status = IDIL;
}

bool ProjectInfoManger::loadServerList(bool local)
{
    if(_status != IDIL) return false;
    _serverInfo.clear();
    _cacheInfo.clear();
    if(local){
        auto dt = PQ::CacheFile::readFile("ProjectInfoList.cache");
        auto ary = QJsonDocument::fromJson(dt).array();
        hanldeServerList(ary,false);
        return true;
    }
    _oneSyncError = 0;
    _netErrorCount = 0;
    _nowJob = 1;
    QTimer::singleShot(0,this,&ProjectInfoManger::doSendLoad);
    return true;
}

bool ProjectInfoManger::syncLocalList()
{
    if(_status != IDIL) return false;
    auto  info =  _manger->getLocalProjectInfo();
    _serverInfo.clear();
    _cacheInfo.clear();
    _pushQueue.clear();
     _nowJob = 2;
    for(int i = 0; i < info.size(); ++i){
        _pushQueue.append(info.at(i));
    }
//    qDebug()<<"pushQueue.size"<<_pushQueue.size();
    QTimer::singleShot(0,this,&ProjectInfoManger::doSendCreate);
    return true;
}

void ProjectInfoManger::setStatus()
{
    _status = IDIL;
}

void ProjectInfoManger::doSendLoad()
{
    _status = Load_Server_List;
    // docs: http://doc.vanlai.net:3001/web/#/1?page_id=60
    QString url = GlobalInfo::this_()->config()->baseUrl+"/v2/goods/list?page=0&limit=10000&status=ON";
    _requst.setUserToken(QString::number(GlobalInfo::this_()->user().accountId),GlobalInfo::this_()->user().acessToken);
    _requst.get(url);
}

void ProjectInfoManger::addNewProject(QSharedPointer<ProjectInfo> pro)
{
    _pushQueue.append(pro);
    QTimer::singleShot(20,this,&ProjectInfoManger::doSendCreate);
}

void ProjectInfoManger::doSendCreate()
{
    if(!_pushQueue.isEmpty()){
        _status = Sync_Local_List;
        QSharedPointer<ProjectInfo> info = _pushQueue.first();
        // test:  调用新建批号的接口
        // docs: http://doc.vanlai.net:3001/web/#/1?page_id=59

        QString url = GlobalInfo::this_()->config()->baseUrl+"/v2/goods/add";
        _requst.setUserToken(QString::number(GlobalInfo::this_()->user().accountId),GlobalInfo::this_()->user().acessToken);
        _requst.post(url,info->toObject());
    } else {
        _status = IDIL;
        QTimer::singleShot(0,this,&ProjectInfoManger::doSendLoad);
    }
}

void ProjectInfoManger::handleList()
{
    QSet<QString> remoted;
    for(int i = 0; i < _serverInfo.size(); ++i){
        remoted.insert(_serverInfo.at(i)->batch_no);
    }
    _cacheInfo.clear();
    auto list = _manger->getLocalProjectInfo();
    for(int i = 0; i < list.size(); ++i){
        auto info = list.at(i);
        if(!remoted.contains(info->batch_no)){
            _cacheInfo.append(info);
        }
    }
    _manger->syncLocalProjectInfo(_cacheInfo);
    if(_nowJob == 1)
        emit inited(this,true);
    else
        emit synced(this,true);
}

void ProjectInfoManger::result(int code, const QJsonObject & body)
{
    switch (_status) {
    case Load_Server_List:
        handleGetList(code,body);
        break;
    case Sync_Local_List:
        handlSync(code,body);
        break;
    default:
        break;
    }
}


void ProjectInfoManger::handlSync(int code, const QJsonObject & body)
{
    if(code != 200){
        _netErrorCount ++;
        if(_netErrorCount > 3) {
            emit synced(this,false);
        } else {
            QTimer::singleShot(500,this,&ProjectInfoManger::syncLocalList);
        }
        return;
    }
//    auto error = body.value("code").toInt();
//    if(error == 200){
        emit sync();

        _pushQueue.dequeue();
        QTimer::singleShot(50,this,&ProjectInfoManger::syncLocalList);
//    } else {
//        _pushQueue.dequeue();
//        QTimer::singleShot(50,this,&ProjectInfoManger::syncLocalList);
//    }
}

void ProjectInfoManger::handleGetList(int code, const QJsonObject & body)
{
    if(code != 200){
        _netErrorCount ++;
        if(_netErrorCount > 3) {
            auto dt = PQ::CacheFile::readFile("ProjectInfoList.cache");
            auto ary = QJsonDocument::fromJson(dt).array();
            hanldeServerList(ary,false);
        } else {
            QTimer::singleShot(500,this,&ProjectInfoManger::syncLocalList);
        }
        return;
    }
    auto error = body.value("code").toInt();
    if(error == 200){
        _oneSyncError = 0;
        auto ary = body.value("data").toArray();
        hanldeServerList(ary);
    } else {
        _oneSyncError ++;
        if(_oneSyncError > 3) {
            auto dt = PQ::CacheFile::readFile("ProjectInfoList.cache");
            auto ary = QJsonDocument::fromJson(dt).array();
            hanldeServerList(ary,false);
        } else {
            QTimer::singleShot(50,this,&ProjectInfoManger::syncLocalList);
        }
    }
}

void ProjectInfoManger::hanldeServerList(QJsonArray & ary,bool inServer)
{
    if(inServer){
        auto dt = QJsonDocument(ary).toJson();
        PQ::CacheFile::writeFile("ProjectInfoList.cache",dt);
    }

    //TEST:  解析返回的到 _serverInfo
    // docs: http://doc.vanlai.net:3001/web/#/1?page_id=60
    for(int i = 0;i<ary.size();i++){
        _serverInfo.append(ProjectInfo::fromObject(ary.at(i).toObject()));
    }
    handleList();
}
