#include "wplanlist.h"
#include "wplanitem.h"

wPlanList::wPlanList(QWidget *parent) : QListWidget(parent)
{
    setAttribute(Qt::WA_DeleteOnClose);
    setFrameShape(QListWidget::NoFrame);
}

void wPlanList::adjustItemNum()
{
    int n = count();
    for(int i=0; i<n; i++) {
        wPlanItem *w = static_cast<wPlanItem*>(itemWidget(item(i)));
        w->setNum(i+1);
    }
}

QJsonArray wPlanList::plansJson()
{
    QJsonArray oRoot;
    int n = count();
    for(int i=0; i<n; i++) {
        wPlanItem *w = static_cast<wPlanItem*>(itemWidget(item(i)));
        oRoot.append(w->planJson());
    }
    return oRoot;
}
//添加时间计划表
void wPlanList::onAddPlan()
{
    QListWidgetItem *item = new QListWidgetItem();
    item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
    wPlanItem *widget = new wPlanItem(item);
    addItem(item);
    setItemWidget(item, widget);
    setCurrentItem(item);
    connect(widget, SIGNAL(sigItemChanged(QListWidgetItem*)), this, SIGNAL(itemChanged(QListWidgetItem*)));
    connect(widget, SIGNAL(sigDelete(QListWidgetItem*)),      this,   SLOT(onDeletePlan(QListWidgetItem*)));
    adjustItemNum();
    emit itemChanged(item);
}

void wPlanList::onRestorePlan(const QJsonArray &jRoot)
{
    clear();
    int n = jRoot.count();
    for(int i=0; i<n; i++) {
        QListWidgetItem *item = new QListWidgetItem();
        item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
        wPlanItem *widget = new wPlanItem(jRoot.at(i).toObject(), item);
        addItem(item);
        setItemWidget(item, widget);
        setCurrentItem(item);
        connect(widget, SIGNAL(sigItemChanged(QListWidgetItem*)), this, SIGNAL(itemChanged(QListWidgetItem*)));
        connect(widget, SIGNAL(sigDelete(QListWidgetItem*)),      this,   SLOT(onDeletePlan(QListWidgetItem*)));
    }
    adjustItemNum();
}

void wPlanList::onDeletePlan(QListWidgetItem *item)
{
    int index = row(item);
    if(index >= 0) {
        removeItemWidget(item);
        delete item;
        emit itemChanged(nullptr);
    }
    adjustItemNum();
}
