#include "ModelBase.h"

#include<QDebug>
#include <QSqlField>

ModelBase::ModelBase(QObject *parent)
	: QSqlQueryModel(parent)
	, totalCount(0)
	, multiSelect(false)
{
	for (size_t i = 0; i < fields.length(); i++)
	{
		QPair<QString, QString> pari = fields.at(i);
		setHeaderData(i, Qt::Horizontal, pari.first);
	}
}

ModelBase::~ModelBase()
{
}

void ModelBase::setQuery(const QSqlQuery &query)
{
	QSqlQueryModel::setQuery(query);
	//checkStateMap.clear();

	// 移除分页带来的rowno字段
	if (record().count() > 0)
	{
		int columnIndex = columnCount() - 1;
		QString columnName = record(0).fieldName(columnIndex).toLower();
		if (columnName == "rowno");
		removeColumn(columnIndex);
	}
}

bool ModelBase::setData(const QModelIndex &index, const QVariant &value, int role)
{
	if (!index.isValid())
		return false;
	if (multiSelect && role == Qt::CheckStateRole && index.column() == 0)
	{	
		Qt::CheckState cs = value == Qt::Checked ? Qt::Checked : Qt::Unchecked;
		checkStateMap[index.row()] = cs;
		emit checkStateChanged(cs, record(index.row()));
	}

	return true;
}

Qt::ItemFlags ModelBase::flags(const QModelIndex &index) const
{
	if (!index.isValid())
		return 0;

	if (index.column() == 0)
		return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;

	return  Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

/**
* 输出表头显示
*/
QVariant ModelBase::headerData(int section, Qt::Orientation orientation, int role) const
{
	if ((role == Qt::DisplayRole || role == Qt::CheckStateRole) && orientation == Qt::Horizontal)
	{
		if (section < fields.count())
		{
			return fields.at(section).second;
		}
	}
	return QVariant();
}

/**
* 字段值格式化显示
*/
QVariant ModelBase::data(const QModelIndex &index, int role) const
{
	int row = index.row();
	int col = index.column();

	if (multiSelect && role == Qt::CheckStateRole && col == 0)
	{
		if (checkStateMap.contains(row))
			return checkStateMap[row] == Qt::Checked ? Qt::Checked : Qt::Unchecked;
		return Qt::Unchecked;
	}

	return QSqlQueryModel::data(index, role);
}