//---------------------------------------------------------------------------

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "ITSDbF.h"
#include "AppGlobalF.h"
#include "CDSCodeF.h"
#include "CDSNodeF.h"
#include "CDSLinkF.h"
#include "CDSServiceLinkF.h"
#include "CDSRoadF.h"
#pragma hdrstop

#include "SMS0010MF.h"
#include "ITSSEL2MF.h"
#include "ITSSELAMF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxClasses"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxDropDownEdit"
#pragma link "cxEdit"
#pragma link "cxFilter"
#pragma link "cxGraphics"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "cxTimeEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#pragma link "dxSkinCoffee"
#pragma link "dxSkinDarkRoom"
#pragma link "dxSkinDarkSide"
#pragma link "dxSkinFoggy"
#pragma link "dxSkinGlassOceans"
#pragma link "dxSkiniMaginary"
#pragma link "dxSkinLilian"
#pragma link "dxSkinLiquidSky"
#pragma link "dxSkinLondonLiquidSky"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinMoneyTwins"
#pragma link "dxSkinOffice2007Black"
#pragma link "dxSkinOffice2007Blue"
#pragma link "dxSkinOffice2007Green"
#pragma link "dxSkinOffice2007Pink"
#pragma link "dxSkinOffice2007Silver"
#pragma link "dxSkinOffice2010Black"
#pragma link "dxSkinOffice2010Blue"
#pragma link "dxSkinOffice2010Silver"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "cxCalc"
#pragma link "cxButtonEdit"
#pragma link "cxCheckBox"
#pragma link "cxMemo"
#pragma resource "*.dfm"

TSMS0010M *SMS0010M = NULL;
//---------------------------------------------------------------------------
__fastcall TSMS0010M::TSMS0010M(TComponent* Owner)
    : TForm(Owner)
{
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FTitle = "SMS 문자발송";
}
//---------------------------------------------------------------------------

/*
 * 닫기버튼 이나 x버튼 클릭시 공통으로 처리하는 로직이들어간다..
 * Form과 DataModule class를 delete시킨다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TSMS0010M::CommClose()
{
    try
    {
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TSMS0010M::FormInit()
{
    memoSMS->Lines->Clear();
}
//---------------------------------------------------------------------------

/*
 * Form을 보여줄때 호출되는 event 메서드이다.
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TSMS0010M::FormShow(TObject *Sender)
{
    Refresh();
    FormInit();
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

/*
 * Form이 Show되고 난 후 최초 1회 수행되는 타이머 이벤트
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TSMS0010M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    BtnSearchClick((TObject*)BtnSearch);
}
//---------------------------------------------------------------------------

/*
 * Search 버튼 클릭 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TSMS0010M::BtnSearchClick(TObject *Sender)
{
    RefreshData();
}
//---------------------------------------------------------------------------

/*
 * Refresh Data Event Function
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TSMS0010M::RefreshData()
{
    SelSmsUserList();
}
//---------------------------------------------------------------------------

void __fastcall TSMS0010M::SelSmsUserList()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery         *pADO    = ADOQry;
    TcxGridTableView  *pTvList = TvList1;
    TcxDataController *pGDC    = pTvList->DataController;


    CMM_ClearGridTableView(pTvList);

    sQry = "SELECT A.SMS_USER_ID,    \r\n"
           "       A.SMS_USER_NM,    \r\n"
           "       A.SMS_USER_TEL,   \r\n"
           "       A.SMS_USER_EXPL,  \r\n"
           "       A.SMS_RPLY_TEL,   \r\n"
           "       A.RGST_DT         \r\n"
           "  FROM TB_SMS_USER A     \r\n"
           " ORDER BY A.SMS_USER_ID  \r\n";

    try
    {
        pADO->Connection = ITSDb_GetConnection();
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLOpen(pADO);

        int nRow = 0;
        try
        {
            pTvList->BeginUpdate();

            pGDC->RecordCount = pADO->RecordCount;

            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                pGDC->Values[nRow][ColumnSel->Index] = true;
                pGDC->Values[nRow][AColumn02->Index] = pADO->FieldByName("SMS_USER_ID")->AsString;
                pGDC->Values[nRow][AColumn03->Index] = pADO->FieldByName("SMS_USER_NM")->AsString;
                pGDC->Values[nRow][AColumn04->Index] = pADO->FieldByName("SMS_USER_TEL")->AsString;
                pGDC->Values[nRow][AColumn05->Index] = pADO->FieldByName("SMS_RPLY_TEL")->AsString;
                pGDC->Values[nRow][AColumn06->Index] = pADO->FieldByName("SMS_USER_EXPL")->AsString;
                //pGDC->Values[nRow][AColumn07->Index] = ITSUtil_StrToTime(pADO->FieldByName("RGST_DT")->AsString);
            }
        }
        __finally
        {
            if (pADO)
            {
                pADO->Close();
            }

            pTvList->EndUpdate();
            //LblRecords->Caption = FormatFloat("##,##0", pGDC->RecordCount) + " 건";
        }
    }
    catch(EDatabaseError &E)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(...)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        throw Exception("알수없는 오류가 발생하였습니다.");
    }
}
//---------------------------------------------------------------------------

/*
 * Close 버튼 클릭 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TSMS0010M::BtnCloseClick(TObject *Sender)
{
    Close();    
}
//---------------------------------------------------------------------------

void __fastcall TSMS0010M::FormClose(TObject *Sender, TCloseAction &Action)
{
    CommClose();
    SMS0010M = NULL;
    Action = caFree;    
}
//---------------------------------------------------------------------------

bool __fastcall TSMS0010M::CheckField()
{
    String sMsg = memoSMS->Lines->Text.Trim();

	if (sMsg == "")
    {
        Application->MessageBox(L"SMS 발송문자를 확인 하세요.", Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return false;
    }
    int nSelCount = CMM_GetCheckCount(TvList1, ColumnSel->Index);
    if (nSelCount == 0)
    {
        Application->MessageBox(L"SMS 발송대상자가 선택되지 않았습니다.\r\nSMS 발송대상자을 체크하여 선택하십시요.",
                                Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    return true;
}
//---------------------------------------------------------------------------

bool __fastcall TSMS0010M::GetMsgNewId(int &ANewId)
{
    String sQry;
    TADOQuery *pADO = NULL;

    ANewId = 0;

    sQry = "SELECT NVL(MAX(SMS_SEQ), 0) + 1 AS NEWID \r\n"
           "  FROM TB_SMS_SEND_PNST                  \r\n";

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;
			pADO->Open();

            ANewId = pADO->FieldByName("NEWID")->AsInteger;

            return true;
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
        catch(...)
        {
            throw Exception("알수없는 DB 오류가 발생하였습니다.");
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TSMS0010M::SaveSmsSendMsg(TADOConnection *ADbCon/*=NULL*/, bool ALocal/*=true*/)
{
    if (!ADbCon) ADbCon = ITSDb_GetConnection();

    TADOQuery *pADO = NULL;
	String sQry;

    String sSendMsg = memoSMS->Lines->Text.Trim();
    int    nNewId = 0;

    try
    {
        if (ALocal)
        {
            if (!GetMsgNewId(nNewId))
            {
                return;
            }
        }

        if (ALocal)
        {
            sQry = "INSERT INTO TB_SMS_SEND_PNST(SMS_SEQ,                              \r\n"
                   "                             SEND_TEL,                             \r\n"
                   "                             RPLY_TEL,                             \r\n"
                   "                             SEND_MSG,                             \r\n"
                   "                             SMS_CRTN_DT)                          \r\n"
                   "                      VALUES(:p01,                                 \r\n"
                   "                             :p02,                                 \r\n"
                   "                             :p03,                                 \r\n"
                   "                             :p04,                                 \r\n"
                   "                             TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS')) \r\n";
        }
        else
        {
            sQry = "INSERT INTO EM_TRAN(TRAN_PR,             \r\n"
                   "                    TRAN_PHONE,          \r\n"
                   "                    TRAN_CALLBACK,       \r\n"
                   "                    TRAN_STATUS,         \r\n"
                   "                    TRAN_DATE,           \r\n"
                   "                    TRAN_MSG,            \r\n"
                   "                    TRAN_TYPE)           \r\n"
                   "             VALUES(EM_TRAN_PR.NEXTVAL,  \r\n"
                   "                    :p02,                \r\n"
                   "                    :p03,                \r\n"
                   "                    '1',                 \r\n"
                   "                    SYSDATE,             \r\n"
                   "                    :p04,                \r\n"
                   "                    4 )                  \r\n";
        }

        TvList1->BeginUpdate();
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ADbCon;

            ITSDb_SQLText(pADO, sQry);

            ADbCon->BeginTrans();

            int nRowCnt = TvList1->ViewData->RecordCount;
            for (int ii = 0; ii < nRowCnt; ii++)
            {
                TcxCustomGridRow* ARow = TvList1->ViewData->Rows[ii];
                if (((bool)ARow->Values[ColumnSel->Index]))
                {
                    String sCallTel = ARow->Values[AColumn04->Index];
                    String sBackTel = ARow->Values[AColumn05->Index];

                    if (ALocal)
                    {
                        ITSDb_SQLBind(pADO, "p01", String(nNewId++));
                    }
                    ITSDb_SQLBind(pADO, "p02", sCallTel);
                    ITSDb_SQLBind(pADO, "p03", sBackTel);
                    ITSDb_SQLBind(pADO, "p04", sSendMsg);

                    ITSDb_SQLExec(pADO);
                }
            }
            ADbCon->CommitTrans();
            Application->MessageBox(L"선택하신 SMS 발송대상자에게 SMS 메시지 전송을 정상적으로 요청하였습니다.",
                                    Caption.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
        catch(EDatabaseError &E)
        {
            ADbCon->RollbackTrans();
            ShowMessage(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            ADbCon->RollbackTrans();
            ShowMessage(String(exception.ClassName()) + exception.Message);
        }
        catch(...)
        {
            ADbCon->RollbackTrans();
            ShowMessage("데이터 작업 중에 알수없는 DB 오류가 발생하였습니다.");
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        TvList1->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TSMS0010M::BtnOperatorInputClick(TObject *Sender)
{
    if (!CheckField()) return;

    if (Application->MessageBox(L"SMS 메시지를 전송 하시겠습니까?", L"SMS 메시지 전송", MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

    bool bRemote = false;

    TADOConnection *pConnection = NULL;
    String          sDbConnString;

    if (bRemote)
    {

#if 0
        sDbConnString  = "";
        sDbConnString += "Provider=" + g_AppCfg.smsdb.sProvider;
        sDbConnString += ";Password=" + g_AppCfg.smsdb.sPassword;
        sDbConnString += ";Persist Security Info=True";
        sDbConnString += ";User ID=" + g_AppCfg.smsdb.sUserName;
        sDbConnString += ";Data Source=" + g_AppCfg.smsdb.sServerName;
#endif
    }

    try
    {
        if (bRemote)
        {
            pConnection = new TADOConnection(NULL);
            if (!DbConnect(pConnection, sDbConnString))
            {
                Application->MessageBox(L"SMS 데이터베이스와 연결에 실패하였습니다.",
                                        L"SMS 데이터베이스 연결 실패", MB_OK|MB_ICONERROR|MB_APPLMODAL);
                return;
            }
            SaveSmsSendMsg(pConnection, false);
        }
        else
        {
            SaveSmsSendMsg();
        }
    }
    __finally
    {
        if (bRemote)
        {
            DbClose(pConnection);
            delete pConnection;
            pConnection = NULL;
        }
    }
}
//---------------------------------------------------------------------------

bool __fastcall TSMS0010M::DbConnect(TADOConnection *AConnection, String AConnString)
{
    if (!AConnection) return false;

	try
    {
        AConnection->ConnectionString = AConnString;
        AConnection->KeepConnection   = true;
        AConnection->LoginPrompt      = false;
        AConnection->Open();
    }
    catch(EDatabaseError &E)
    {
        ShowMessage(E.Message);
        return false;
    }
	catch (Exception &e)
	{
        ShowMessage(e.Message);
        return false;
	}
    catch (...)
    {
        ShowMessage("데이터베이스 연결실패-알수없는 오류");
        return false;
    }

    return true;
}
//---------------------------------------------------------------------------

void __fastcall TSMS0010M::DbClose(TADOConnection *AConnection)
{
    if (!AConnection) return;

    if (AConnection->Connected)
    {
        AConnection->Close();
    }
}
//---------------------------------------------------------------------------

void __fastcall TSMS0010M::TvList1MouseMove(TObject *Sender, TShiftState Shift, int X,
          int Y)
{
    try
    {
        TcxGridSite *ASite = (TcxGridSite *)Sender;

        //Screen->Cursor = crDefault;

        //TcxCustomGridHitTest *AHitTest = tvSel->GetHitTest(X, Y);
        TcxCustomGridHitTest *AHitTest = dynamic_cast<TcxGridRecordHitTest*>(ASite->ViewInfo->GetHitTest(X, Y));
        if (dynamic_cast<TcxGridRecordHitTest*>(ASite->ViewInfo->GetHitTest(X, Y)))
        {
            int ARow = ((TcxGridRecordCellHitTest*)AHitTest)->GridRecord->Index;
            if (((TcxGridRecordCellHitTest*)AHitTest)->Item == NULL) return;
            int ACol = ((TcxGridRecordCellHitTest*)AHitTest)->Item->Index;
            if (ACol == ColumnSel->Index &&
                ARow < ASite->GridView->DataController->RecordCount-1)
            {
                Screen->Cursor = crHandPoint;
            }
        }
        else
        {
            Screen->Cursor = crDefault;
        }
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TSMS0010M::BtnAllSelectClick(TObject *Sender)
{
    TcxButton *pBtn = (TcxButton*)Sender;
    CMM_CheckAllListItem(TvList1, ColumnSel->Index, pBtn->Tag);
}
//---------------------------------------------------------------------------

void __fastcall TSMS0010M::BtnCnfmCancelClick(TObject *Sender)
{
    memoSMS->Lines->Clear();
}
//---------------------------------------------------------------------------

