#include "modelitemlistmodel.h"

ModelItemListModel* ModelItemListModel::m_ptr = nullptr;

ModelItemListModel::ModelItemListModel(QObject *parent)
    : QAbstractListModel{parent}
{

}

ModelItemListModel::~ModelItemListModel()
{
    if(m_ptr != nullptr){
        delete m_ptr;
    }
}

ModelItemListModel *ModelItemListModel::getInstance()
{
    if(m_ptr == nullptr){
        m_ptr = new ModelItemListModel;
    }

    return m_ptr;
}

void ModelItemListModel::setItems(const QList<ModelItem *> &items)
{
    beginResetModel();
    qDeleteAll(m_items); // 删除所有 ModelItem*
    m_items.clear();     // 清空列表
    
    m_items = items;
    endResetModel();
}

int ModelItemListModel::rowCount(const QModelIndex &) const
{
    return m_items.count();
}

QVariant ModelItemListModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() >= m_items.size())
        return QVariant();

    ModelItem* item = m_items[index.row()];
    switch (role) {
    case NameRole:
        return item->m_modelName;
    case DescriptionRole:
        return item->m_description;
    case IsCheckedRole:
        return item->m_isChecked;
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> ModelItemListModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[NameRole] = "modelName";
    roles[DescriptionRole] = "description";
    roles[IsCheckedRole] = "isChecked";
    return roles;
}
