#include "OrmModelBase.h"

#include<QDebug>

OrmModelBase::OrmModelBase(QObject* parent)
	: qx::IxModel(parent)
	, multiSelect(false)
{
}

OrmModelBase::~OrmModelBase()
{
}

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

Qt::ItemFlags OrmModelBase::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 | Qt::ItemIsEditable;
}

/**
* 字段值格式化显示
*/
QVariant OrmModelBase::data(const QModelIndex& index, int role) const
{
	int row = index.row();
	int col = index.column();
	if (role == Qt::CheckStateRole && col == 0 && multiSelect)
	{
		if (checkStateMap.contains(row))
			return checkStateMap[row] == Qt::Checked ? Qt::Checked : Qt::Unchecked;
		return Qt::Unchecked;
	}
	else if (role == Qt::TextAlignmentRole)
	{
		return Qt::AlignCenter;
	}
	else if (role == Qt::DisplayRole || role == Qt::EditRole)
	{
		QVariantMap dict = getDataMember(index.column())->getPropertyBag("dict").toMap();
		if (dict.size() > 0)
		{
			return dict[qx::IxModel::data(index, role).toString()];
		}
	}
	return qx::IxModel::data(index, role);
}


void OrmModelBase::limit(qx::QxSqlQuery & query, int pageIndex)
{
	query.limit(pageSize - 1, pageIndex*pageSize + 1); 
}

void OrmModelBase::count(const qx::QxSqlQuery  &query)
{
	totalCount = this->qxCount(query); 
}

