#include "TelSalePolicyManager.h"
#include <string>
#include <sstream>
#include <exception>
#include <stdlib.h>


using namespace std; 
using namespace StringCodeConverter;

#ifndef _UNICODE
#define _UNICODE
#endif

const char g_cszConnectStringIDS6[] = 
    "DRIVER={};"
    "PROTOCOL=onsoctcp;"
    "SERVICE=16191;"
    "SERVER=xmcx1;"
    "HOST=10.39.0.91;"
    "DATABASE=ids6;"
    "DB_LOCALE=en_US.819;";

const static char g_szUserNameIDS6[] = "ccx99";
const static char g_szPasswordIDS6[] = "c91IT09";

const static char g_cszConnstringYwgl[] =
    "DRIVER={};"
    "PROTOCOL=onsoctcp;"
    "SERVICE=16192;"
    "SERVER=xmcx2;"
    "HOST=10.39.0.92;"
    "DATABASE=ywgl_xm;"
    "DB_LOCALE=en_US.819;";

const static char g_cszUserNameYwgl[] = "ccx99";
const static char g_cszPasswordYwgl[] = "c92IT09";

CTelSalePolicyManager::CTelSalePolicyManager(void)
{
}


CTelSalePolicyManager::~CTelSalePolicyManager(void)
{
}

void CTelSalePolicyManager::Query( SPolicyQuery &policy, std::vector<SPolicyRecord> &vPolicy )
{
	SAConnection conn;
	SACommand command;


	//生成查询字符串
	string strCommand;

	strCommand.reserve( 1024 );
	strCommand.append( "select bdh, zhjywy, to_char(czrq, '%Y年%m月%d日') from w_dxbd_i where 1=1 and czrq >='" );

	strCommand += policy.strStartDate;
	strCommand += "' and czrq <= '";
	strCommand += policy.strEndDate;
	strCommand += "'";

	if ( policy.strPolicySerial.empty() == false )
	{
		strCommand += " and bdh = '";
		strCommand += policy.strPolicySerial;
		strCommand += "'";
	}

	if ( policy.strSalerCode.empty() == false )
	{
		strCommand += " and zhjywy = '";
		strCommand += policy.strSalerCode;
		strCommand += "'";
	}

	if ( policy.strPlateSerial.empty() == false )
	{
		strCommand += " and chph = '";
		strCommand += policy.strPlateSerial;
		strCommand += "'";
	}

	if ( policy.strFrameSerial.empty() == false )
	{
		strCommand += " and chjh = '";
		strCommand += policy.strFrameSerial;
		strCommand += "'";
	}

	if ( policy.strEngineSerial.empty() == false )
	{
		strCommand += " and fdjh = '";
		strCommand += policy.strEngineSerial;
		strCommand += "'";
	}

	command.setConnection( &conn );
	command.setCommandText( strCommand.c_str() );

	try
	{
		conn.Connect(
			g_cszConnstringYwgl,
			g_cszUserNameYwgl,
			g_cszPasswordYwgl,
			SA_Informix_Client );

		command.Execute();
	}
	catch ( SAException &error )
	{
		string strError = error.ErrText();

		throw strError;
	}

	while ( command.FetchNext() == true )
	{
		SPolicyRecord policyQuery;

		SAString strCol = command.Field( 1 ).asString();
		strCol.TrimRight();

		policyQuery.strPolicySerial = strCol;

		strCol = command.Field( 2 ).asString();
		strCol.TrimRight();
		policyQuery.strSalerCode = strCol;
		
		strCol = (SAString)command.Field( 3 ).asString();
		strCol.TrimRight();
		policyQuery.strOperatorDate = strCol;

		vPolicy.push_back( policyQuery );
	}

	conn.Disconnect();
}

string QueryOperatorName( string strOperatorCode )
{
	SAConnection conn;
	SACommand command;

	string strCommand( "select rymc from rydm where rydm='" );
	string strResult;

	strCommand += strOperatorCode;
	strCommand += "'";

	command.setConnection( &conn );
	command.setCommandText( strCommand.c_str() );

	try
	{
		conn.Connect(
			"DRIVER={};"
			"PROTOCOL=onsoctcp;"	// protocol in lower case
			"SERVICE=7777;"
			"SERVER=xmtb1;"
			"HOST=10.39.0.80;"
			"DATABASE=datacenter;",
			"ccxuser",
			"ccx99",
			SA_Informix_Client );

		command.Execute();
	}
	catch ( SAException &error )
	{
		SAString strError = error.ErrText();
	}

	if ( command.FetchNext() == true )
	{
		SAString sastrResult = command.Field("rymc").asString();
		sastrResult.TrimRight();

		strResult = (const char *)sastrResult;
	}

	conn.Disconnect();

	return strResult;
}

void QueryOperatorInfo( const string & cstrOperatorCode,
                        string & strOperatorName,
                        string & strDeptCode,
                        string & strDeptName )
{
    SAConnection connection;
    SACommand    command;

    string strCommand = "select a.staff_name, "
                        "       a.department_code,"
                        "       b.department_name "
                        "from rydm_t a, bm_t b  "
                        "where a.department_code = b.department_code "
                        "and   a.staff_code = '";

    strCommand.append( cstrOperatorCode );
    strCommand.append( "'" );

    try
    {
        connection.Connect( g_cszConnectStringIDS6,
                            g_szUserNameIDS6,
                            g_szPasswordIDS6,
                            SA_Informix_Client );

        command.setConnection( &connection );
        command.setCommandText( strCommand.c_str() );

        command.Execute();

        if ( command.FetchNext() == true )
        {
            strOperatorName = (const char *)( command.Field( "staff_name").asString() );
            strDeptCode = (const char *)( command.Field( "department_code").asString() );
            strDeptName = (const char *)( command.Field( "department_name").asString() );
        }

        connection.Disconnect();
    }
    catch ( SAException & sqlError )
    {
        runtime_error error( sqlError.ErrText() );

        throw error;
    }
}

void CTelSalePolicyManager::SavePolicy( const SPolicyRecord & policy,
                                        const vector<TelSalePolicyGift> giftList )
{
	if ( policy.strPolicySerial.empty() == true )
	{
		throw invalid_argument( "保单号为空!" );
	}

	if ( policy.strSalerCode.empty() == true )
	{
		throw invalid_argument( "保单号为空！" );
	}

	ostringstream ostrCommand;
    string strAutotraderCall;

    //车店联呼
    if ( policy.bIsAutotraderCall == true )
    {
        strAutotraderCall = "1";
    }
    else
    {
        strAutotraderCall = "0";
    }

	ostrCommand << "insert into w_dxbd_i ( khjl, khjllx, bdh, zhjywy, zhjywymc, zhjywybm, zhjywybmm, czydm, czrq , chdlh, khmc, chph, chjh, fdjh ) "
				   "values(  0, 0, "
				<< "'" << policy.strPolicySerial << "', "
				<< "'" << policy.strSalerCode << "', "
                << "'" << policy.strSalerName << "', "
                << "'" << policy.strSalerDeptCode << "', "
                << "'" << policy.strSalerDeptName << "', "
				<< "'" << policy.strOperatorCode << "', "
				<< "'" << policy.strOperatorDate << "', "
                << "'" << strAutotraderCall << "'";

	if ( policy.strCustomerName.empty() == false )
	{
		ostrCommand << ", '" << policy.strCustomerName << "'";
	}
	else
	{
		ostrCommand << ", NULL";
	}

	if ( policy.strPlateSerial.empty() == false )
	{
		ostrCommand << ", '" << policy.strPlateSerial << "'";
	}
	else
	{
		ostrCommand << ", NULL";
	}

	if ( policy.strFrameSerial.empty() == false )
	{
		ostrCommand << ", '" << policy.strFrameSerial << "'";
	}
	else
	{
		ostrCommand << ", NULL";
	}

	if ( policy.strEngineSerial.empty() == false )
	{
		ostrCommand << ", '" << policy.strEngineSerial << "'";
	}
	else
	{
		ostrCommand << ", NULL";
	}

	ostrCommand << " )";

	string strCommand = ostrCommand.str();

	SAConnection conn;
	SACommand command;

	command.setConnection( &conn );
	command.setCommandText( strCommand.c_str() );

	try
	{
        conn.Connect(
            g_cszConnstringYwgl,
            g_cszUserNameYwgl,
            g_cszPasswordYwgl,
            SA_Informix_Client );
        //conn.setAutoCommit( SA_AutoCommitOff ); //导致锁表

        //保存保单
		command.Execute();

        //保存礼品列表,先删除旧数据
        command.setCommandText( "delete w_dxbd_gift_i where bdh = :1 " );
        command.Param( 1 ).setAsString() = policy.strPolicySerial.c_str();
        command.Execute();

        command.setCommandText( "insert into w_dxbd_gift_i ( bdh, gift_name, gift_price ) values ( :1, :2, :3 )" );

        for ( vector<TelSalePolicyGift>::const_iterator iter = giftList.begin(); iter != giftList.end(); ++iter )
        {
            command.Param( 1 ).setAsString() = policy.strPolicySerial.c_str();
            command.Param( 2 ).setAsString() = iter->GiftName().c_str();
            command.Param( 3 ).setAsString() = iter->GiftDefaultPrice().c_str();

            command.Execute();
        }

        conn.Commit();
	}
	catch ( SAException &error )
	{
		conn.Rollback();
        conn.Disconnect();

		throw runtime_error( error.ErrText() );
	}

	conn.Disconnect();
}

void CTelSalePolicyManager::LoadFromExcelFile( const char *pcszFilePath, vector< SPolicyRecord > *pvPolicy )
{
	if ( pvPolicy == NULL )
	{
		return;
	}

	wchar_t pwszFilePath[1024];

	mbs2unicode( pcszFilePath, pwszFilePath );
	
	IBookT<wchar_t> *pBookPolicy = xlCreateXMLBookW();

	if ( pBookPolicy == NULL )
	{
		return;
	}

	if ( !(pBookPolicy->load( pwszFilePath )) )
	{
		const char *pcszError = pBookPolicy->errorMessage();

		pBookPolicy->release();
	}

	ISheetT<wchar_t> *pSheet = pBookPolicy->getSheet( 0 );

	if ( pSheet == NULL )
	{
		pBookPolicy->release();
		return;
	}

	int iStartRow = pSheet->firstRow();
	int iEndROw = pSheet->lastRow();

	for ( iStartRow++; iStartRow <= iEndROw; iStartRow++ )
	{
		SPolicyRecord policy;

		policy.strPolicySerial = getCellString( pSheet, iStartRow, 0 );

		if ( policy.strPolicySerial.empty() == true )
		{
			iStartRow++;
			continue;
		}

		policy.strSalerCode = getCellString( pSheet, iStartRow, 1 );
		policy.strCustomerName = getCellString( pSheet, iStartRow, 2 );
		policy.strPlateSerial = getCellString( pSheet, iStartRow, 3 );
		policy.strFrameSerial = getCellString( pSheet, iStartRow, 4 );
		policy.strEngineSerial = getCellString( pSheet, iStartRow, 5 );

		pvPolicy->push_back( policy );
	}

	pBookPolicy->release();
}

void CTelSalePolicyManager::SavePolicyGift( const string & strPolicyNo, const vector<TelSalePolicyGift> & giftsList )
{
    if ( strPolicyNo.empty() )
    {
        throw invalid_argument( "strPolicyNo" );
    }

    if ( giftsList.empty() )
    {
        throw invalid_argument( "礼品列表为空！" );
    }

    SAConnection conn;
    SACommand command;

    command.setConnection( &conn );
    command.setCommandText( "insert into w_dxbd_gift_i ( bdh, gift_name, gift_price ) values ( :1, :2, :3 )" );

    try
    {
        conn.Connect( g_cszConnstringYwgl,
                      g_cszUserNameYwgl,
                      g_cszPasswordYwgl,
                      SA_Informix_Client );

        for ( vector<TelSalePolicyGift>::const_iterator iter = giftsList.begin(); iter != giftsList.end(); ++iter )
        {
            command.Param( 1 ).setAsString() = strPolicyNo.c_str();
            command.Param( 2 ).setAsString() = iter->GiftName().c_str();
            command.Param( 3 ).setAsString() = iter->GiftDefaultPrice().c_str();

            command.Execute();
        }
    }
    catch ( SAException &error )
    {
        throw runtime_error( error.ErrText() );
    }

    conn.Disconnect();
}


string getCellString( ISheetT<wchar_t> *pSheet, int iRowIndex, int iColIndex )
{
	if ( pSheet == NULL )
	{
		return NULL;
	}

	string strCell;
	int iCellValue;
	const char *pcszBuffer = NULL;
	char pszNumber[100];

	CellType celltype = pSheet->cellType( iRowIndex, iColIndex );

	switch ( celltype )
	{
	case CELLTYPE_STRING:
		//字符串
		strCell = unicode2mbs( pSheet->readStr( iRowIndex, iColIndex ) );
		break;

	case CELLTYPE_NUMBER:
		//数字
		iCellValue = pSheet->readNum( iRowIndex, iColIndex );

		sprintf( pszNumber,"%d", iCellValue );
		strCell = pszNumber;

		break;
	}

	

	return strCell;
}

void queryTelsalePolicyGifts( vector<TelSalePolicyGift> &giftList )
{
    SAConnection connection;
    SACommand command;

    string strSQL = "select id, trim(name), default_price from w_dx_gifts";

    command.setConnection( &connection );
    command.setCommandText( strSQL.c_str() );

    try
    {
        connection.Connect(
            g_cszConnstringYwgl,
            g_cszUserNameYwgl,
            g_cszPasswordYwgl,
            SA_Informix_Client );

        command.Execute();
    }
    catch ( SAException &error )
    {
        throw runtime_error( error.ErrText() );
    }

    while ( command.FetchNext() )
    {
        TelSalePolicyGift gift;

        gift.Id( command.Field(1).asLong() );
        gift.GiftName( (const char *)(command.Field(2).asString()) );
        gift.GiftDefaultPrice( (const char *)(command.Field(3).asString()) );

        giftList.push_back( gift );
    }

    connection.Disconnect();
}
