#include "cmwauthorityuser.h"
#include "ui_cmwauthorityuser.h"
#include <QMessageBox>

CMWAuthorityUser::CMWAuthorityUser(QWidget *parent)
	: QWidget(parent)
{
	ui = new Ui::CMWAuthorityUser();
	ui->setupUi(this);

	//init();

	QStringList headerList;
	headerList << "id" << "loginName" << "description" << "pwd" << "disable" << "removed";
	ui->tableUser->setColumnCount(headerList.size());
	ui->tableUser->setHorizontalHeaderLabels(headerList);

	// 设置选择模式为整行选择
	ui->tableUser->setSelectionBehavior(QAbstractItemView::SelectRows);

	// 设置选择模式为单个选择（如果需要多行选择，可以使用 QAbstractItemView::MultiSelection）
	ui->tableUser->setSelectionMode(QAbstractItemView::SingleSelection);
	headerList.clear();
	headerList << "name" << "description" << "Level" << "id";
	ui->tableRole->setColumnCount(headerList.size());
	ui->tableRole->setHorizontalHeaderLabels(headerList);
	ui->tableRole->hideColumn(3);
	//m_AuthorityManager->Init();
	//FreshUser();
	//FreshRole();

	connect(ui->tableUser, &QTableWidget::currentCellChanged, this, &CMWAuthorityUser::user_currentCellChanged);

}
CMWAuthorityUser::~CMWAuthorityUser()
{
	delete ui;
}

int CMWAuthorityUser::init()
{
	if (QSqlDatabase::contains("qt_sql_default_connection"))
	{
		m_db = QSqlDatabase::database("qt_sql_default_connection");
	}
	else
	{
		m_db = QSqlDatabase::addDatabase("QSQLITE");


		QString dataPath = CMakePath::make_data_path("permission.db");
		m_db.setDatabaseName(dataPath);
	}

	QString info;
	if (!m_db.open())
	{
		info = "error: failed to connect sqlite3 database." + m_db.lastError().text();

		return -1;
	}
	else
	{
		info = "success to connect sqlite3 database.";
		m_ModelUser = new QSqlTableModel(this, m_db);
		//m_ModelUser.database() = m_db;
		m_ModelUser->setTable("users");
		return 0;
	}
}

void CMWAuthorityUser::FreshUser()
{
	/*QSqlQuery query;
	query.prepare("select * from user");
	m_ModelUser->select();

	ui->tableUser->clearContents();
	int rowCount = m_ModelUser->rowCount();
	int colCount = m_ModelUser->columnCount();
	ui->tableUser->setRowCount(rowCount);

	for (int i = 0; i < m_ModelUser->rowCount(); ++i)
	{
		for (int j = 0; j < m_ModelUser->columnCount(); ++j)
		{
			QVariant data = m_ModelUser->data(m_ModelUser->index(i, j));
			QTableWidgetItem* item = new QTableWidgetItem(data.toString());
			ui->tableUser->setItem(i, j, item);
		}
	}*/
	auto mapUsers = m_AuthorityManager->GetUsers(true);
	ui->tableUser->setRowCount(mapUsers.size());
	ui->tableUser->clearContents();
	int iRow = 0;
	for each (auto pair in mapUsers)
	{
		User& user = pair.second;
		QTableWidgetItem* item = new QTableWidgetItem(QString::number(user.ID));
		ui->tableUser->setItem(iRow, 0, item);
		item->setData(1000, user.ID);
		item = new QTableWidgetItem(user.LoginName.c_str());
		ui->tableUser->setItem(iRow, 1, item);

		item = new QTableWidgetItem(user.DisplayName.c_str());
		ui->tableUser->setItem(iRow, 2, item);

		item = new QTableWidgetItem(user.Password.c_str());
		ui->tableUser->setItem(iRow, 3, item);

		item = new QTableWidgetItem();
		ui->tableUser->setItem(iRow, 4, item);
		item->setCheckState(user.Disabled ? Qt::Checked : Qt::Unchecked);

		item = new QTableWidgetItem();
		ui->tableUser->setItem(iRow, 5, item);
		item->setCheckState(user.Removed ? Qt::Checked : Qt::Unchecked);

		iRow++;
	}
}

void CMWAuthorityUser::FreshRole()
{
	ui->tableRole->clearContents();
	auto mapRoles = m_AuthorityManager->GetRoles();
	ui->tableRole->setRowCount(mapRoles.size());
	int iRow = 0;
	for each (auto pair in mapRoles)
	{
		Role& role = pair.second;
		QTableWidgetItem* item;
		item = new QTableWidgetItem(role.Name.c_str());
		ui->tableRole->setItem(iRow, 0, item);
		item->setData(1000, role.ID);
		item->setCheckState(Qt::Unchecked);

		item = new QTableWidgetItem(role.Description.c_str());
		ui->tableRole->setItem(iRow, 1, item);

		item = new QTableWidgetItem(QString::number(role.Level));
		ui->tableRole->setItem(iRow, 2, item);

		item = new QTableWidgetItem(QString::number(role.ID));
		ui->tableRole->setItem(iRow, 3, item);

		iRow++;
	}
}

void CMWAuthorityUser::FreshRoleState()
{
	std::map<int, int> mapUserRole = m_AuthorityManager->GetRolesByUser(m_iSelUserId);
	for (int i = 0; i < ui->tableRole->rowCount(); i++)
	{
		QTableWidgetItem* item = ui->tableRole->item(i, 0);
		int roleId = item->data(1000).toInt();
		if (mapUserRole.find(roleId) == mapUserRole.end())
		{
			item->setCheckState(Qt::Unchecked);
		}
		else
		{
			item->setCheckState(Qt::Checked);
		}
	}
}

void CMWAuthorityUser::FreshSelectedUser()
{
	if (m_iSelUserId <= 0)
	{
		ui->tableUser->setCurrentItem(nullptr);
	}
	else
	{
		for (int i = 0; i < ui->tableUser->rowCount(); i++)
		{
			if (m_iSelUserId == ui->tableUser->item(i, 0)->data(1000).toInt())
			{
				ui->tableUser->setCurrentItem(ui->tableUser->item(i, 0));
			}
		}
	}

	ui->tableUser->setFocus();
}

void CMWAuthorityUser::user_itemChanged(QTableWidgetItem *item)
{
	int i = 0;
}

void CMWAuthorityUser::user_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
{
	if (m_iLastUserSelRow != currentRow)
	{
		if (currentRow == -1)
		{
			m_iSelUserId = -1;
		}
		else
		{
			m_iSelUserId = ui->tableUser->item(currentRow, 0)->text().toInt();
		}
		
		FreshRoleState();
	}
}

void CMWAuthorityUser::SetAuthorityManager(IAuthorityManager* instance)
{
	IAuthoritySupport::SetAuthorityManager(instance);

	m_AuthorityManager = static_cast<CSqliteAuthorityManager*>(instance);
}

void CMWAuthorityUser::FreshAuthority()
{
	ui->btnRefresh->click();
}

void CMWAuthorityUser::on_btnRefresh_clicked()
{
	FreshUser();
	FreshRole();
	FreshRoleState();

	FreshSelectedUser();
}

void CMWAuthorityUser::on_btnDel_clicked()
{
	if (false == m_AuthorityManager->DeleteUser(m_iSelUserId))
	{
		QMessageBox::information(this, QString("error"), "failed");
	} 
	else
	{
		m_iSelUserId = -1;
		FreshUser();
		FreshSelectedUser();
	}
}

void CMWAuthorityUser::on_btnAdd_clicked()
{
	QString error = "";
	User user;
	user.LoginName = ui->txtUserName->text().toStdString();
	user.Password = ui->txtUserPassword->text().toStdString();
	user.DisplayName = ui->txtDisplayName->text().toStdString();
	if (false == m_AuthorityManager->AddUser(user))
	{
		QMessageBox::information(this, QString("error"), "failed");
		return;
	}
	

	FreshUser();
	FreshSelectedUser();
}

void CMWAuthorityUser::on_btnModify_clicked()
{
	QString error = "";
	User user;
	user.LoginName = ui->txtUserName->text().toStdString();
	user.Password = ui->txtUserPassword->text().toStdString();
	user.DisplayName = ui->txtDisplayName->text().toStdString();
	bool bChangePwd = ui->chkModifyPwd->isChecked();
	if (false == m_AuthorityManager->MotifyUser(user, bChangePwd))
	{
		QMessageBox::information(this, QString("xx"), "failed");
		return;
	}

	FreshUser();
	FreshSelectedUser();
}

void CMWAuthorityUser::on_btnDisable_clicked()
{
	m_AuthorityManager->EnableUser(m_iSelUserId, false);
}

void CMWAuthorityUser::on_btnModifyRole_clicked()
{
	if (m_iSelUserId <= 0)return;

	std::vector<int> roleIdList;
	for (int iRow = 0; iRow < ui->tableRole->rowCount(); iRow++)
	{
		QTableWidgetItem* item = ui->tableRole->item(iRow, 0);
		if(!item)continue;

		if (item->checkState() == Qt::Checked)
		{
			roleIdList.push_back(item->data(1000).toInt());
		}
	}
	m_AuthorityManager->UpdateUserRoles(m_iSelUserId, roleIdList);

	FreshSelectedUser();
}

void CMWAuthorityUser::SetControlPermission(QWidget* object, const PermissionInfo& permissionInfo)
{
	//m_mapObjectsPermission[object] = permissionInfo;
}

void CMWAuthorityUser::InitAuthority()
{
}

