//#include <occi.h>
//#include <QTextCodec>
#include <QtWidgets/QMessageBox>
#include "QLoginWidget.h"
#include "SystemData.h"
#include "SystemDataQuery.h"

QLoginWidget::QLoginWidget( QWidget * parent )
	: QDialog( parent )
{
	ui.setupUi( this );

	init();
}

QLoginWidget::~QLoginWidget()
{
}

void QLoginWidget::init()
{
	initWidget();
	initSignal();

	doesLoginSuccess = false;
}

void QLoginWidget::initWidget()
{
	setLayout( ui.pLayoutMain );
}

void QLoginWidget::initSignal()
{
	connect( ui.pButtonLogin, SIGNAL(clicked()), this, SLOT(login()) );
	connect( ui.pButtonCancel, SIGNAL(clicked()), this, SLOT(cancel()) );
	connect( ui.pEditUserCode, SIGNAL(editingFinished()), this, SLOT(getUserName()) );
}

void QLoginWidget::onLogin()
{
	string strPassword( static_cast<char *>(ui.pEditPassword->text().toLocal8Bit().data()) );

	if ( strPassword == userPassword )
	{
		doesLoginSuccess = true;

		//保存用户名和密码
		setUserCode( userCode );
		setUserName( userName );

		close();
	}
	else
	{
		QMessageBox::warning( this, QString::fromLocal8Bit( "错误" ), QString::fromLocal8Bit( "密码错误！" ) );
	}
}

void QLoginWidget::onCancel()
{
	doesLoginSuccess = false;

	close();
}

void QLoginWidget::onQueryUserInfo()
{
	userCode = ui.pEditUserCode->text().toLocal8Bit().data();

	try
	{
		//根据用户填入的工号，查询名称和密码
		query_user_info( userCode,
		               userName,
		               userPassword );

		ui.pEditUserName->setText( QString::fromLocal8Bit( userName.c_str() ) );
	}
	catch ( runtime_error & error )
	{
		QMessageBox::critical( this,
		                       QString::fromLocal8Bit( "查询用户信息出错" ),
		                       QString::fromLocal8Bit( error.what() ) );
	}
}
