#include <QtWidgets/QtWidgets>
#include "QTelSalePolicyInfoInputWidget.h"
#include "QRapidInputWidget.h"
#include "SystemDataQuery.h"
#include "SystemData.h"

QTelSalePolicyInfoInputWidget::QTelSalePolicyInfoInputWidget( QWidget * parent )
	: QWidget( parent )
{
	setupUi( this );

	init();
	initWidget();
	initSignal();
	initData();
}

QTelSalePolicyInfoInputWidget::~QTelSalePolicyInfoInputWidget()
{
}

void QTelSalePolicyInfoInputWidget::init()
{
}

void QTelSalePolicyInfoInputWidget::initWidget()
{
	setLayout( pLayoutMain );

	//单笔录入窗口
	pTabWidget->widget( 0 )->setLayout( pLayoutInputMain );

	pScrollAreaInput->setWidget( pWidgetInput );

	pWidgetInput->setLayout( pLayoutInfoDetail );
	pWidgetInput->setMaximumWidth( 820 );
	pWidgetInput->setMinimumWidth( 820 );

	//批量录入
	QRapidInputWidget * pWidgetRapid = new QRapidInputWidget;

	pScrollAreaRapid->setWidget( pWidgetRapid );

	pTabWidget->widget( 1 )->setLayout( pLayoutRapid );
}

void QTelSalePolicyInfoInputWidget::initSignal()
{
	connect( pEditSalerCode, SIGNAL(editingFinished()), this, SLOT(onQuerySalerName()) );
	connect( pEditSalerCode, SIGNAL(textChanged(const QString &)), this, SLOT(onSalerCodeChanged()) );
	connect( pEditAutoTraderCode, SIGNAL(editingFinished()), this, SLOT(onQueryAutoTraderName()) );
	connect( pEditAutoTraderCode, SIGNAL(textChanged(const QString &)), this, SLOT(onAutoTraderCodeChanged()) );
	connect( pButtonSave, SIGNAL(clicked()), this, SLOT(onSavePolicy()) );
	connect( pButtonResetGift, SIGNAL(clicked()), this, SLOT(onResetGiftsTable()) );
	connect( pButtonReset, SIGNAL(clicked()), this, SLOT(onReset()) );
	connect( pTableGifts, SIGNAL(cellChanged(int,int)), this, SLOT(onGiftTableItemChanged(int, int)) );
}

void QTelSalePolicyInfoInputWidget::initData()
{
	//默认的车商代码
	pEditAutoTraderCode->setText( QString::fromLocal8Bit( pParameters->getParameter( "默认车商代码" ).c_str() ) );

	emit pEditAutoTraderCode->editingFinished();

	//初始化礼品列表
	InitGiftTable();

	pEditQjxPolicySerial->clear();
	pEditBizPolicySerial->clear();
	pEditSalerCode->clear();
	pEditSalerName->clear();
	pEditDeptCode->clear();
	pEditDeptName->clear();
	pEditOfficeCode->clear();
	pEditOfficeName->clear();
	pComboBoxAutotraderCall->setCurrentIndex( 0 );
}

void QTelSalePolicyInfoInputWidget::InitGiftTable()
{
	//设置标志位
	m_initing = true;

	giftsList.clear();

	try
	{
		//queryTelsalePolicyGifts( giftsList );
	}
	catch ( runtime_error & error )
	{
		QMessageBox::critical( this, QString::fromLocal8Bit( "获取礼品列表出错！" ), error.what() );

		return;
	}

	pTableGifts->clearContents();
	pTableGifts->setColumnWidth( 0, 200 );
	pTableGifts->setRowCount( giftsList.size() + 2 );

	vector<TelSalePolicyGift>::iterator iter = giftsList.begin();

	for ( unsigned int rowIndex = 0; iter != giftsList.end(); rowIndex++ )
	{
		QTableWidgetItem * pItem = new QTableWidgetItem();

		pItem->setCheckState( Qt::Unchecked );
		pItem->setFlags( Qt::ItemIsUserCheckable | Qt::ItemIsEnabled );
		pItem->setText( QString::fromLocal8Bit( iter->GiftName().c_str() ) );
		pItem->setTextAlignment( Qt::AlignLeft | Qt::AlignVCenter );

		pTableGifts->setItem( rowIndex, 0, pItem );

		pItem = new QTableWidgetItem();

		pItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsEditable );
		pItem->setText( QString::fromLocal8Bit( iter->GiftDefaultPrice().c_str() ) );
		pItem->setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );

		pTableGifts->setItem( rowIndex, 1, pItem );

		++iter;
	}

	//其他
	QTableWidgetItem * pItemOther      = new QTableWidgetItem();
	QTableWidgetItem * pItemOtherPrice = new QTableWidgetItem();

	pItemOther->setText( QString::fromLocal8Bit( "其他" ) );
	pItemOther->setCheckState( Qt::Unchecked );
	pItemOther->setFlags( Qt::ItemIsUserCheckable | Qt::ItemIsEnabled );
	pItemOther->setTextAlignment( Qt::AlignLeft | Qt::AlignVCenter );

	pItemOtherPrice->setText( "0" );
	pItemOtherPrice->setFlags( Qt::ItemIsEnabled | Qt::ItemIsEditable );
	pItemOtherPrice->setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );

	pTableGifts->setItem( giftsList.size(), 0, pItemOther );
	pTableGifts->setItem( giftsList.size(), 1, pItemOtherPrice );

	//礼品总价值
	QTableWidgetItem * pItemTotalPrice       = new QTableWidgetItem();
	QTableWidgetItem * pItemTotalPriceAmount = new QTableWidgetItem();

	pItemTotalPrice->setText( QString::fromLocal8Bit( "礼品总价值" ) );
	pItemTotalPrice->setTextColor( Qt::red );
	pItemTotalPrice->setFlags( Qt::ItemIsEnabled );
	pItemTotalPrice->setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );

	pItemTotalPriceAmount->setText( QString::fromLocal8Bit( "0 元" ) );
	pItemTotalPriceAmount->setTextColor( Qt::red );
	pItemTotalPriceAmount->setFlags( Qt::ItemIsEnabled );
	pItemTotalPriceAmount->setTextAlignment( Qt::AlignHCenter | Qt::AlignVCenter );

	pTableGifts->setItem( giftsList.size() + 1, 0, pItemTotalPrice );
	pTableGifts->setItem( giftsList.size() + 1, 1, pItemTotalPriceAmount );

	pTableGifts->resizeColumnsToContents();

	m_initing = false;
}

void QTelSalePolicyInfoInputWidget::readGiftTable( vector<TelSalePolicyGift> & giftList )
{
	int rowCount = pTableGifts->rowCount();

	for ( int rowIndex = 0; rowIndex < rowCount; rowIndex++ )
	{
		QTableWidgetItem * pItemName  = pTableGifts->item( rowIndex, 0 );
		QTableWidgetItem * pItemPrice = pTableGifts->item( rowIndex, 1 );

		if ( pItemName->checkState() == Qt::Unchecked )
		{
			continue;
		}

		TelSalePolicyGift gift( rowIndex,
		                        string( pItemName->text().toLocal8Bit().data() ),
		                        string( pItemPrice->text().toLocal8Bit().data() ) );

		giftList.push_back( gift );
	}
}

void QTelSalePolicyInfoInputWidget::onSalerCodeChanged()
{
	pEditSalerName->clear();
	pEditDeptName->clear();
	pEditDeptCode->clear();
	pEditOfficeName->clear();
	pEditOfficeCode->clear();

	salerCode.clear();
	salerName.clear();
	salerDeptCode.clear();
	salerDeptName.clear();
}

void QTelSalePolicyInfoInputWidget::onQuerySalerName()
{
	salerCode = pEditSalerCode->text().trimmed().toUpper().toLocal8Bit().data();

	query_staff_info( salerCode,
	                salerName,
	                salerDeptCode,
	                salerDeptName,
	                salerOfficeCode,
	                salerOfficeName );

	pEditSalerName->setText( QString::fromLocal8Bit( salerName.c_str() ) );
	pEditOfficeCode->setText( QString::fromLocal8Bit( salerOfficeCode.c_str() ) );
	pEditOfficeName->setText( QString::fromLocal8Bit( salerOfficeName.c_str() ) );
	pEditDeptCode->setText( QString::fromLocal8Bit( salerDeptCode.c_str() ) );
	pEditDeptName->setText( QString::fromLocal8Bit( salerDeptName.c_str() ) );
}

void QTelSalePolicyInfoInputWidget::onSavePolicy()
{
	string strJqxPolicySerial = pEditQjxPolicySerial->text().trimmed().toLocal8Bit().data();
	string strBizPolicySerial = pEditBizPolicySerial->text().trimmed().toLocal8Bit().data();

	int iAutotraderCallIndex = pComboBoxAutotraderCall->currentIndex();

	vector<TelSalePolicyGift> giftsList; //用户选择的礼品清单

	//触发信号
	emit pEditSalerCode->editingFinished();
	emit pEditAutoTraderCode->editingFinished();

	if ( strJqxPolicySerial.empty() && strBizPolicySerial.empty() )
	{
		QMessageBox::critical( this,
		                       QString::fromLocal8Bit( "必须输入保单号" ),
		                       QString::fromLocal8Bit( "交强险、商业险保单号皆为空，\n必须输入一个保单号！" ),
		                       QMessageBox::Yes );

		return;
	}

	if ( salerName.empty() == true )
	{
		QMessageBox::critical( this,
		                       QString::fromLocal8Bit( "必须输入经办人代码" ),
		                       QString::fromLocal8Bit( "经办人代码不正确！" ),
		                       QMessageBox::Yes );

		return;
	}

	if ( iAutotraderCallIndex == 0 )
	{
		QMessageBox::critical( this,
		                       QString::fromLocal8Bit( "输入错误" ),
		                       QString::fromLocal8Bit( "未选择是否车店联呼！" ),
		                       QMessageBox::Yes );

		return;
	}

	if ( pEditAutoTraderName->text().isEmpty() )
	{
		QMessageBox::critical( this,
		                       QString::fromLocal8Bit( "输入错误" ),
		                       QString::fromLocal8Bit( "车商代码错误！" ),
		                       QMessageBox::Yes );

		return;
	}

	if ( pGroupBoxGift->isChecked() == true )
	{
		readGiftTable( giftsList );

		if ( giftsList.size() == 0 )
		{
			QMessageBox::critical( this,
			                       QString::fromLocal8Bit( "输入错误" ),
			                       QString::fromLocal8Bit( "未选择礼品！" ),
			                       QMessageBox::Yes );

			return;
		}
	}

	SPolicyRecord policy; //保单信息

	policy.strSalerCode       = salerCode;
	policy.strSalerName       = salerName;
	policy.strSalerDeptCode   = salerDeptCode;
	policy.strSalerDeptName   = salerDeptName;
	policy.strSalerOfficeCode = salerOfficeCode;
	policy.strSalerOfficeName = salerOfficeName;
	policy.strOperatorCode    = getUserCode();
	policy.strCustomerName    = pEditCustomerName->text().trimmed().toLocal8Bit().data();
	policy.strPlateSerial     = pEditPlateSerial->text().trimmed().toLocal8Bit().data();
	policy.strFrameSerial     = pEditFrameSerial->text().trimmed().toLocal8Bit().data();
	policy.strEngineSerial    = pEditEngineSerial->text().trimmed().toLocal8Bit().data();
	policy.strOperatorDate    = QDate::currentDate()
	                            .toString( QString::fromLocal8Bit( "MM/dd/yyyy" ) ).toLocal8Bit().data();

	if ( iAutotraderCallIndex == 2 )
	{
		policy.bIsAutotraderCall = true;
	}
	else
	{
		policy.bIsAutotraderCall = false;
	}

	//车商代码
	if ( autoTraderName.empty() == false )
	{
		policy.strAutoTraderCode = autoTraderCode;
		policy.strAutoTraderName = autoTraderName;
	}

	if ( strJqxPolicySerial.empty() == false )
	{
		//处理交强险保单
		policy.strPolicySerial = strJqxPolicySerial;

		try
		{
			SaveTelSalePolicyInfo( policy, giftsList );

			QMessageBox::information( this,
			                          QString::fromLocal8Bit( "保存成功!" ),
			                          QString::fromLocal8Bit( "交强险保单保存成功!" ),
			                          QMessageBox::Yes );
		}
		catch ( runtime_error & error )
		{
			QMessageBox::critical( this,
			                       QString::fromLocal8Bit( "保存交强险保单失败！" ),
			                       QString::fromLocal8Bit( error.what() ),
			                       QMessageBox::Yes );
		}
	}

	if ( strBizPolicySerial.empty() == false )
	{
		//处理交强险保单
		policy.strPolicySerial = strBizPolicySerial;

		try
		{
			SaveTelSalePolicyInfo( policy, giftsList );

			QMessageBox::information( this,
			                          QString::fromLocal8Bit( "保存成功!" ),
			                          QString::fromLocal8Bit( "商业险保单保存成功!" ),
			                          QMessageBox::Yes );
		}
		catch ( runtime_error & error )
		{
			QMessageBox::critical( this,
			                       QString::fromLocal8Bit( "保存商业险保单失败！" ),
			                       QString::fromLocal8Bit( error.what() ),
			                       QMessageBox::Yes );
		}
	}
}

void QTelSalePolicyInfoInputWidget::onResetGiftsTable()
{
	InitGiftTable();
}

void QTelSalePolicyInfoInputWidget::onGiftTableItemChanged( int row, int column )
{
	if ( m_initing == true )
	{
		return;
	}

	int                rowCount   = pTableGifts->rowCount() - 1;
	QTableWidgetItem * pItem      = NULL;
	QTableWidgetItem * pItemPrice = NULL;
	bool               isSuccess  = false;
	double             giftPrice  = 0.0l;

	if ( column == 1 && row != rowCount )
	{
		pItem      = pTableGifts->item( row, 0 );
		pItemPrice = pTableGifts->item( row, column );

		pItemPrice->text().toDouble( &isSuccess );

		if ( isSuccess == false )
		{
			QMessageBox::critical( this,
			                       QString::fromLocal8Bit( "输入错误！" ),
			                       pItem->text() + QString::fromLocal8Bit( "价格有误！" ) );

			pItemPrice->setText( "0" );
		}
	}

	for ( int rowIndex = 0; rowIndex < rowCount; rowIndex++ )
	{
		pItem      = pTableGifts->item( rowIndex, 0 );
		pItemPrice = pTableGifts->item( rowIndex, 1 );

		if ( pItem->checkState() == Qt::Unchecked )
		{
			continue;
		}

		giftPrice += pItemPrice->text().toDouble( &isSuccess );

		if ( isSuccess == false )
		{
			QMessageBox::critical( this,
			                       QString::fromLocal8Bit( "输入错误！" ),
			                       pItem->text() + QString::fromLocal8Bit( "价格有误！" ) );

			pItemPrice->setText( "0" );
		}
	}

	pTableGifts->item( pTableGifts->rowCount() - 1, 1 )->setText( QString::fromLocal8Bit( "%1 元" ).arg( giftPrice ) );
	pTableGifts->resizeColumnsToContents();
}

void QTelSalePolicyInfoInputWidget::onAutoTraderCodeChanged()
{
	pEditAutoTraderName->clear();

	autoTraderName.clear();
}

void QTelSalePolicyInfoInputWidget::onQueryAutoTraderName()
{
	autoTraderCode = pEditAutoTraderCode->text().trimmed().toUpper().toLocal8Bit().data();

	query_auto_trader_info( autoTraderCode, autoTraderName );

	pEditAutoTraderName->setText( QString::fromLocal8Bit( autoTraderName.c_str() ) );
}

void QTelSalePolicyInfoInputWidget::onReset()
{
	initData();
}
