#include "DataListModel.h"


DataListModel::DataListModel(QObject *parent)
    : QAbstractListModel(parent), m_nextRole(Qt::UserRole + 1)
{
    // 初始化一些默认角色
}

int DataListModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_data.size();
}

QVariant DataListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_data.size())
    {
        return QVariant();
    }

    const QVariantMap &entry = m_data.at(index.row());
    QString roleName = m_roles.value(role);

    return entry.value(roleName);
}

QHash<int, QByteArray> DataListModel::roleNames() const
{
    return m_roles;
}

bool DataListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || index.row() >= m_data.size())
    {
        return false;
    }

    QString roleName = m_roles.value(role);
    if (roleName.isEmpty())
    {
        return false;
    }

    m_data[index.row()][roleName] = value;
    emit dataChanged(index, index, {role});
    return true;
}

Qt::ItemFlags DataListModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
    {
        return Qt::NoItemFlags;
    }

    return Qt::ItemIsEditable | QAbstractListModel::flags(index);
}

void DataListModel::append(const QVariantMap &entry)
{
    beginInsertRows(QModelIndex(), m_data.size(), m_data.size());
    m_data.append(entry);
    endInsertRows();
}

void DataListModel::insert(int index, const QVariantMap &entry)
{
    if (index < 0 || index > m_data.size())
    {
        return;
    }

    beginInsertRows(QModelIndex(), index, index);
    m_data.insert(index, entry);
    endInsertRows();
}

void DataListModel::remove(int index)
{
    if (index < 0 || index >= m_data.size())
    {
        return;
    }

    beginRemoveRows(QModelIndex(), index, index);
    m_data.remove(index);
    endRemoveRows();
}

void DataListModel::clear()
{
    beginResetModel();
    m_data.clear();
    endResetModel();
}

void DataListModel::setProperty(int index, const QString &property, const QVariant &value)
{
    if (index < 0 || index >= m_data.size())
    {
        return;
    }

    // 如果属性不存在，自动添加角色
    if (!m_roles.key(property.toUtf8())) {
        addRole(property);
    }

    m_data[index][property] = value;
    QModelIndex modelIndex = createIndex(index, 0);
    int role = m_roles.key(property.toUtf8());
    emit dataChanged(modelIndex, modelIndex, {role});
}

QVariantMap DataListModel::get(int index) const
{
    if (index < 0 || index >= m_data.size())
    {
        return QVariantMap();
    }

    return m_data.at(index);
}

int DataListModel::count() const
{
    return m_data.size();
}

void DataListModel::addRole(const QString &roleName)
{
    if (m_roles.values().contains(roleName.toUtf8()))
    {
        return;
    }

    m_roles[m_nextRole++] = roleName.toUtf8();
    // emit roleNamesChanged();
}
