#include "globalinfo.h"

GlobalInfo::GlobalInfo(QObject *parent) : QObject(parent)
{
    _isNoLine = false;
    _config.load();
    packmanger = nullptr;
    _printer = nullptr;
    _serial = nullptr;
}


GlobalInfo * GlobalInfo::this_()
{
    static GlobalInfo glo;
    return  & glo;
}


QString GlobalInfo::packNum()
{
//    auto ret = _config.packId;
    if(pack_num.length() == 4) return  pack_num;
    pack_num = QString::asprintf("%04d",_config.packId);
    if(pack_num.length() > 4)
        pack_num = pack_num.right(4);
    return pack_num;
}

bool GlobalInfo::addCacheInfo(QSharedPointer<ProjectInfo> & info)
{
    auto v = project(info->batch_no);
    if(!v.isNull()) return false;
    _cacheInfo.append(info);
    _project.insert(info->batch_no,info);
    packmanger->syncLocalProjectInfo(_cacheInfo);
}



void GlobalInfo::start(UserInfo & user,bool online)
{
    _users = user;
    _isNoLine = online;
    initInfo();
    _remoteConfig->refConfig();
    if(online){
        _projectmanger->syncLocalList();
    } else {
        _projectmanger->loadServerList(false);
    }
}

void GlobalInfo::initInfo()
{
    if(packmanger != nullptr) return;
    packmanger = new PackInfoManger(this);
    _printer = new PrinterThreadHandle();
    _printer->start();
    _serial = new SerialThreadHandle();
    _serial->start();
    _remoteConfig = new RemotePackConfig(this);
    connect(_remoteConfig,&RemotePackConfig::configUpdate,this,&GlobalInfo::configUpdate);
    connect(_remoteConfig,&RemotePackConfig::dengJIConfigUp,this,&GlobalInfo::dengJIConfigUp);
    _projectmanger = new ProjectInfoManger(packmanger,this);
    connect(_projectmanger,&ProjectInfoManger::inited,this,&GlobalInfo::syncProject);
    connect(_projectmanger,&ProjectInfoManger::synced,this,&GlobalInfo::syncProject);
}

void GlobalInfo::printerBox(QSharedPointer<BoxInfo> info)
{
    if(_printer){
        emit _printer->printerBox(info);
    }
}

void GlobalInfo::printerPack(QSharedPointer<PackInfo> info)
{
    if(_printer){
        emit _printer->printerPack(info);
    }
}


void GlobalInfo::syncProject(ProjectInfoManger * manger, bool )
{
    _cacheInfo = manger->cacheInfo();
    _serverInfo = manger->serverInfo();
    _project.clear();
    for(int i = 0; i < _cacheInfo.size(); ++i){
        auto info = _cacheInfo.at(i);
        _project.insert(info->batch_no,info);
    }

    for(int i = 0; i < _serverInfo.size(); ++i){
        auto info = _serverInfo.at(i);
        _project.insert(info->batch_no,info);
    }
    emit doInited();
}

void GlobalInfo::configUpdate(const DaBaoConfig & config)
{
    _dbConfig = config;
    emit dbConfigUpdated();
}
void GlobalInfo::dengJIConfigUp(const QList<DengJiConfigItem> & dengJis)
{
    _dengJiList = dengJis;
    emit dengJiUped();
}
