#include "bstatusForm.h"
#include "ui_bstatusForm.h"
#include "Control/flowControl.h"
#include "bstatusItem.h"

BStatusForm::BStatusForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::BStatusForm)
{
    ui->setupUi(this);

    connect(&FlowControl::GetInstance(), &FlowControl::initChannelsData, this, &BStatusForm::onInitChannelsData);
    connect(&FlowControl::GetInstance(), &FlowControl::setStoreOperatingStatusFinsh, this, &BStatusForm::onSetStoreOperatingStatusFinsh);
    connect(&FlowControl::GetInstance(), &FlowControl::setStoreStatusChanged, this, &BStatusForm::onStoreStatusChanged);

    setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    this->setModal(true);
}

BStatusForm::~BStatusForm()
{
    delete ui;
}

void BStatusForm::onInitChannelsData(QStringList list)
{
    foreach(BStatusItem* item, m_items)
    {
        delete item;
    }
    m_items.clear();

    foreach(QString channelInfo, list)
    {
        BStatusItem *item = new BStatusItem(this);
        connect(item, &BStatusItem::setStoreOperatingStatus, &FlowControl::GetInstance(), &FlowControl::onSetStoreOperatingStatus);
        item->InitData(channelInfo);
        m_items.append(item);
        ui->verticalLayout->insertWidget(0, item);
    }
    if(this->parentWidget()->isVisible())
    {
        this->show();
    }
}

void BStatusForm::onSetStoreOperatingStatusFinsh(QString channel)
{
    foreach (auto value,m_items ) {
        if(channel.compare(value->getChannelCode()))
        {
            value->onSetStoreOperatingStatusFinsh();
        }
    }
}

void BStatusForm::onStoreStatusChanged(QJsonArray array)
{
    QString channelCode;
    foreach(QJsonValue v,array)
    {
        QJsonObject object=v.toObject();
        channelCode=object["channelCode"].toString();
        foreach (auto value,m_items ) {
            if(channelCode.compare(value->getChannelCode()))
            {
                value->onSetStoreOperatingStatusFinsh(object["state"].toInt());
            }
        }
    }
    show();
}

void BStatusForm::on_btsBtnClose_clicked()
{
    hide();
}
