#include <iostream>
#include "QLoginDialog.h"
#include "../../system/system_util.h"
#include "../../data/Datastructure/UserInfo/UserInfo.h"
#include "../../data/query/query_user.h"
#include "../../data/AppParameters/AppParameters.h"
#include <QMessageBox>

using namespace std;

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

	init();
}

QLoginDialog::~QLoginDialog()
{
}

void QLoginDialog::init()
{
	initData();
	initWidgets();
	initSignal();
}

void QLoginDialog::initData()
{
	returnCode = EXIT;

	systemUserName = QString::fromStdWString( getUserName() );
}

void QLoginDialog::initSignal()
{
	connect( ui.pButtonOK, SIGNAL( clicked() ), this, SLOT( onOK() ));
	connect( ui.pButtonExit, SIGNAL( clicked() ), this, SLOT( onExit() ));
}

void QLoginDialog::initWidgets()
{
	setLayout( ui.pLayoutMain );

	ui.pEditSystemUserName->setText( systemUserName );

	try
	{
		queryStaffInfo( systemUserName );
	}
	catch ( runtime_error & error )
	{
		//如果出现异常，就不让用户继续登录
		QMessageBox::critical( nullptr,
		                       "错误，请联系管理员!",
		                       QString::fromLocal8Bit( error.what() ) );

		ui.pButtonOK->setEnabled( false );
	}
}

void QLoginDialog::onOK()
{
	returnCode = OK;

	this->close();
}

void QLoginDialog::onExit()
{
	returnCode = EXIT;

	this->close();
}

void QLoginDialog::queryStaffInfo( const QString & systemUserName )
{
	string userName = "car_dealer";
	string password = "cpic123456";
	string tnsName  = "xmcx1";

	string staffP13 = systemUserName.toLocal8Bit();

	UserInfo && info = queryUserInfo( userName,
	                                  password,
	                                  tnsName,
	                                  staffP13 );

	pStaffInfo = new UserInfo( info );
}
