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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "ITSDbF.h"
#include "AppGlobalF.h"
#include "WindowMsgF.h"
#include "CDSAviF.h"
#pragma hdrstop

#include "AVIH0401F.h"
#include "AVIH040MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCheckBox"
#pragma link "cxClasses"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#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 "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxStyles"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxmdaset"
#pragma resource "*.dfm"

#define USE_MEMDATA 1

TAVIH0401 *AVIH0401 = NULL;
//---------------------------------------------------------------------------
__fastcall TAVIH0401::TAVIH0401(TComponent* Owner, HWND hHandle, String sFrom, String sTo, String sIdList, bool AAllSel, String ACarNo)
    : TForm(Owner)
{           
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FParent     = hHandle;
    FStDateTime = sFrom;
    FEdDateTime = sTo;
    FIdList     = sIdList;

    FAllSel     = AAllSel;
    FCarNo      = ACarNo;

    Caption = "AVI-제어기 차량통과 이력";
}
//---------------------------------------------------------------------------

__fastcall TAVIH0401::~TAVIH0401(void)
{
}
//--------------------------------------------------------------------------

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TAVIH0401::FormInit()
{
    ADOQry->Connection = ITSDb_GetConnection();
    m_pGDC = TvList->DataController;

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<AVI-제어기 차량통과 이력 정보>";
	//TvList->ViewInfo->GroupByBoxViewInfo->Text = "그룹핑할 필드의 헤더를 이곳으로 드래그 하세요";
#if 0
    LblSearch->Caption = "검색조건: " + FStDateTime.SubString(1, 10) + " ~ " + FEdDateTime.SubString(1, 10);
#else
    LblSearch->Caption = "검색조건: " + FStDateTime.SubString(1, 12) + " ~ " + FEdDateTime.SubString(1, 12);
#endif
}
//---------------------------------------------------------------------------

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

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

/*
 * 최초 1회 수행되는 타이머 이벤트
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TAVIH0401::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false; 
    Application->ProcessMessages();

    CMM_ClearGridTableView(TvList);
    Application->ProcessMessages();

#if USE_MEMDATA
    try
    {
        TvList->BeginUpdate(lsimImmediate);
#endif
        SelHistory();
#if USE_MEMDATA
    }
    __finally
    {
        TvList->EndUpdate();
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TAVIH0401::ChkExpandClick(TObject *Sender)
{
    CMM_ExpandCollapseChk(TvList, ChkExpand->Checked);
}
//---------------------------------------------------------------------------

/*
 * Refresh Data Event Function
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TAVIH0401::SelHistory()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery *pADO = ADOQry;

    sQry = "SELECT A.AVI_CTLR_MNGM_NMBR,                                                                \r\n"
           "       TO_CHAR(TO_DATE(A.CRTN_DT, 'YYYYMMDDHH24MISS'), 'YYYY-MM-DD HH24:MI:SS') AS CRTN_DT, \r\n"
           "       A.WHOL_VHCL_NMBR, A.VHCL_NMBR, A.LANE_NMBR,                                          \r\n"
           "       DECODE(A.LANE_DRCT, 'ACD0', '상행',                                                  \r\n"
           "                           'ACD1', '하행', '') AS LANE_DRCT,                                \r\n"
           "       DECODE(A.VHCL_KIND_CD, '1', '승용차',                                                \r\n"
           "                              '2', '버스',                                                  \r\n"
           "                              '3', '트럭',                                                  \r\n"
           "                              '4', '합',                                                    \r\n"
           "                              '5', '특장', '') AS VHCL_KIND_CD                              \r\n"
           "  FROM TB_AVI_PASS_VHCL A                                                                   \r\n"
           " WHERE 1 = 1                                                                                \r\n"
           "   AND A.CRTN_DT BETWEEN :p01 AND :p02                                                      \r\n";
if (FCarNo != "")
{
    sQry+= "   AND A.WHOL_VHCL_NMBR LIKE '%' || :p03 || '%'                                             \r\n";
}
else
{
    if (FAllSel == false)
    {
    sQry+= "   AND A.AVI_CTLR_MNGM_NMBR IN(" + FIdList + ")                                             \r\n";
    }
}
#if 0
    sQry+= " ORDER BY A.AVI_CTLR_MNGM_NMBR ASC, A.WHOL_VHCL_NMBR, A.CRTN_DT DESC                        \r\n";
#endif


    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FStDateTime);
        ITSDb_SQLBind(pADO, "p02", FEdDateTime);
if (FCarNo != "")
{
        ITSDb_SQLBind(pADO, "p03", FCarNo);
}
        ITSDb_SQLOpen(pADO);

#if USE_MEMDATA
        dxMemData1->DisableControls();
        dxMemData1->Close();
        dxMemData1->CreateFieldsFromDataSet(pADO);
        dxMemData1->LoadFromDataSet(pADO);
        dxMemData1->Open();
        dxMemData1->First();
        dxMemData1->EnableControls();
        pADO->Close();

        DspHistoryMemData();
#else
        DspHistory();
#endif
    }
    catch(EDatabaseError &E)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQry);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &exception)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(exception.ClassName()), exception.Message, sQry);
        throw Exception(String(exception.ClassName()) + exception.Message);
    }
}
//---------------------------------------------------------------------------

void __fastcall TAVIH0401::SelHistory2()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery *pADO = ADOQry;

    sQry = "SELECT A.AVI_CTLR_MNGM_NMBR, B.AVI_ID, B.AVI_LCTN_NM, A.CRTN_DT,      \r\n"
           "       A.WHOL_VHCL_NMBR, A.VHCL_NMBR, A.LANE_NMBR,                    \r\n"
           "       DECODE(A.LANE_DRCT, 'ACD0', '상행',                            \r\n"
           "                           'ACD1', '하행', '') AS LANE_DRCT,          \r\n"
           "       DECODE(A.VHCL_KIND_CD, '1', '승용차',                          \r\n"
           "                              '2', '버스',                            \r\n"
           "                              '3', '트럭',                            \r\n"
           "                              '4', '합',                              \r\n"
           "                              '5', '특장', '') AS VHCL_KIND_CD        \r\n"
           "  FROM TB_AVI_PASS_VHCL A, TB_AVI_CTLR B                              \r\n"
           " WHERE 1 = 1                                                          \r\n"
           "   AND A.AVI_CTLR_MNGM_NMBR = B.AVI_CTLR_MNGM_NMBR                    \r\n";
if (FCarNo != "")
{
    sQry+= "   AND A.WHOL_VHCL_NMBR LIKE '%' || :p03 || '%'                       \r\n";
}
else
{
    if (FAllSel == false)
    {
    sQry+= "   AND B.AVI_CTLR_MNGM_NMBR IN(" + FIdList + ")                       \r\n";
    }
}
    sQry+= "   AND A.CRTN_DT BETWEEN :p01 AND :p02                                \r\n";
#if 0
    sQry+= " ORDER BY A.AVI_CTLR_MNGM_NMBR ASC, A.WHOL_VHCL_NMBR, A.CRTN_DT DESC  \r\n";
#endif

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FStDateTime);
        ITSDb_SQLBind(pADO, "p02", FEdDateTime);
if (FCarNo != "")
{
        ITSDb_SQLBind(pADO, "p03", FCarNo);
}
        ITSDb_SQLOpen(pADO);

#if USE_MEMDATA
        dxMemData1->DisableControls();
        dxMemData1->Close();
        dxMemData1->CreateFieldsFromDataSet(pADO);
        dxMemData1->LoadFromDataSet(pADO);
        dxMemData1->Open();
        dxMemData1->First();
        dxMemData1->EnableControls();
        pADO->Close();

        DspHistoryMemData();
#else
        DspHistory();
#endif
    }
    catch(EDatabaseError &E)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQry);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &exception)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(exception.ClassName()), exception.Message, sQry);
        throw Exception(String(exception.ClassName()) + exception.Message);
    }
}
//---------------------------------------------------------------------------

void __fastcall TAVIH0401::SelHistoryBackup()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery *pADO = ADOQry;

    sQry = "SELECT A.AVI_CTLR_MNGM_NMBR, B.AVI_ID, B.AVI_LCTN_NM, A.CRTN_DT,                                                     \r\n"
           "       WHOL_VHCL_NMBR, CRTN_DT, VHCL_NMBR, LANE_NMBR,                                                                \r\n"
#if 0
		   "       (SELECT CMMN_CD_KOR_NM FROM TB_CMMN_CD WHERE CMMN_CD = A.LANE_DRCT    AND CMMN_CLSF_CD = 'APV') LANE_DRCT,    \r\n"
		   "       (SELECT CMMN_CD_KOR_NM FROM TB_CMMN_CD WHERE CMMN_CD = A.VHCL_KIND_CD AND CMMN_CLSF_CD = 'VTC') VHCL_KIND_CD  \r\n"
#else
		   "       (SELECT CMMN_CD_KOR_NM FROM TB_CMMN_CD WHERE CMMN_CD = A.LANE_DRCT    AND CMMN_CLSF_CD = 'ACD') LANE_DRCT,    \r\n"
		   "       (SELECT CMMN_CD_KOR_NM FROM TB_CMMN_CD WHERE CMMN_CD = A.VHCL_KIND_CD AND CMMN_CLSF_CD = 'VTC') VHCL_KIND_CD  \r\n"
#endif
           "  FROM TB_AVI_PASS_VHCL A, TB_AVI_CTLR B                                                                             \r\n"
           " WHERE A.CRTN_DT BETWEEN :p01 AND :p02                                                                               \r\n"
           "   AND A.AVI_CTLR_MNGM_NMBR = B.AVI_CTLR_MNGM_NMBR                                                                   \r\n";
if (FCarNo != "")
{
    sQry+= "   AND A.WHOL_VHCL_NMBR LIKE '%' || :p03 || '%'  \r\n";
}
else
{
    if (FAllSel == false)
    {
    sQry+= "   AND B.AVI_CTLR_MNGM_NMBR IN(" + FIdList + ")                                                                      \r\n";
    }
}
    sQry+= " ORDER BY A.AVI_CTLR_MNGM_NMBR ASC, A.WHOL_VHCL_NMBR, A.CRTN_DT DESC                                                 \r\n";

#if 0
    sQry = "SELECT AVI_CTLR_MNGM_NMBR, WHOL_VHCL_NMBR, CRTN_DT, VHCL_NMBR, LANE_NMBR, \r\n"
           "       LANE_DRCT, VHCL_KIND_CD                                            \r\n"
           "  FROM TB_AVI_PASS_VHCL                                                   \r\n"
           " WHERE CRTN_DT BETWEEN :p01 AND :p02                                      \r\n"
           "   AND AVI_CTLR_MNGM_NMBR IN(" + FIdList + ")                             \r\n"
           " ORDER BY AVI_CTLR_MNGM_NMBR, WHOL_VHCL_NMBR, CRTN_DT                     \r\n";
#endif

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FStDateTime);
        ITSDb_SQLBind(pADO, "p02", FEdDateTime);
if (FCarNo != "")
{
        ITSDb_SQLBind(pADO, "p03", FCarNo);
}
        ITSDb_SQLOpen(pADO);

#if USE_MEMDATA
        dxMemData1->DisableControls();
        dxMemData1->Close();
        dxMemData1->CreateFieldsFromDataSet(pADO);
        dxMemData1->LoadFromDataSet(pADO);
        dxMemData1->Open();
        dxMemData1->First();
        dxMemData1->EnableControls();
        pADO->Close();

        DspHistoryMemData();
#else
        DspHistory();
#endif
    }
    catch(EDatabaseError &E)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQry);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &exception)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(exception.ClassName()), exception.Message, sQry);
        throw Exception(String(exception.ClassName()) + exception.Message);
    }
}
//---------------------------------------------------------------------------

void __fastcall TAVIH0401::DspHistory()
{
    TADOQuery *pADO = ADOQry;

    try
    {
    	TcxGridChartSeries *pChart = NULL;

        CMM_ClearGridTableView(TvList);

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

            nDataCnt = pADO->RecordCount;
            m_pGDC->RecordCount = nDataCnt;

            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                m_pGDC->Values[nRow][Column00->Index] = pADO->FieldByName("AVI_CTLR_MNGM_NMBR")->AsString;
                m_pGDC->Values[nRow][Column11->Index] = pADO->FieldByName("AVI_ID")->AsString;
                m_pGDC->Values[nRow][Column09->Index] = pADO->FieldByName("AVI_LCTN_NM")->AsString;

                m_pGDC->Values[nRow][Column01->Index] = pADO->FieldByName("WHOL_VHCL_NMBR")->AsString;
                m_pGDC->Values[nRow][Column02->Index] = ITSUtil_StrToDateTime(pADO->FieldByName("CRTN_DT")->AsString).FormatString(STR_DATETIME);   //TODO
                m_pGDC->Values[nRow][Column03->Index] = pADO->FieldByName("VHCL_NMBR")->AsString;
                m_pGDC->Values[nRow][Column04->Index] = pADO->FieldByName("LANE_NMBR")->AsString;
                m_pGDC->Values[nRow][Column05->Index] = pADO->FieldByName("LANE_DRCT")->AsString;
                m_pGDC->Values[nRow][Column06->Index] = pADO->FieldByName("VHCL_KIND_CD")->AsString;
            }
        }
        __finally
        {
            if (pADO)
            {
                pADO->Close();
            }

            TvList->EndUpdate();
            //CxList->SetFocus();
            LblRecords->Caption = FormatFloat("##,##0", m_pGDC->RecordCount) + " 건";

            String sEnd = "데이터 " + LblRecords->Caption + " 이 조회 되었습니다.";
            Application->MessageBox(sEnd.c_str(), L"데이터 조회 완료", MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
    }
    catch(EDatabaseError &E)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(...)
    {
        throw Exception(FrmLang->lblDbErr->Caption);//"알수없는 오류가 발생하였습니다.");
    }
}
//---------------------------------------------------------------------------
void __fastcall TAVIH0401::DspHistoryMemData()
{
    TAVIH040M *FRM = (TAVIH040M*)this->Owner;
    try
    {
    	TcxGridChartSeries *pChart = NULL;

        //CMM_ClearGridTableView(TvList);

        int nRow = 0;
        int nDataCnt = 0;
        try {

            while(!dxMemData1->Eof)
            {
                String AVI_CTLR_MNGM_NMBR = dxMemData1->Fields->FieldByName("AVI_CTLR_MNGM_NMBR")->AsString;
                TItsAvi *pObj = FRM->FRAMEAviList1->MyItsAviManager->FLists.Find(AVI_CTLR_MNGM_NMBR);
                if (!pObj)
                {
                    dxMemData1->Next();
                    continue;
                }
                nRow = m_pGDC->AppendRecord();

                m_pGDC->Values[nRow][Column00->Index] = AVI_CTLR_MNGM_NMBR;//dxMemData1->Fields->FieldByName("AVI_CTLR_MNGM_NMBR")->AsString;
                m_pGDC->Values[nRow][Column11->Index] = pObj->AVI_ID;// dxMemData1->Fields->FieldByName("AVI_ID")->AsString;
                m_pGDC->Values[nRow][Column09->Index] = pObj->AVI_LCTN_NM; //dxMemData1->Fields->FieldByName("AVI_LCTN_NM")->AsString;

                m_pGDC->Values[nRow][Column01->Index] = dxMemData1->Fields->FieldByName("WHOL_VHCL_NMBR")->AsString;
                //m_pGDC->Values[nRow][Column02->Index] = ITSUtil_StrToDateTime(dxMemData1->Fields->FieldByName("CRTN_DT")->AsString).FormatString(STR_DATETIME);   //TODO
                m_pGDC->Values[nRow][Column02->Index] = dxMemData1->Fields->FieldByName("CRTN_DT")->AsString;   //TODO
                m_pGDC->Values[nRow][Column03->Index] = dxMemData1->Fields->FieldByName("VHCL_NMBR")->AsString;
                m_pGDC->Values[nRow][Column04->Index] = dxMemData1->Fields->FieldByName("LANE_NMBR")->AsString;
                m_pGDC->Values[nRow][Column05->Index] = dxMemData1->Fields->FieldByName("LANE_DRCT")->AsString;
                m_pGDC->Values[nRow][Column06->Index] = dxMemData1->Fields->FieldByName("VHCL_KIND_CD")->AsString;

                dxMemData1->Next();
            }
        }
        __finally
        {
            dxMemData1->Close();

            LblRecords->Caption = FormatFloat("##,##0", m_pGDC->RecordCount) + " 건";

            String sEnd = "데이터 " + LblRecords->Caption + " 이 조회 되었습니다.";
            Application->MessageBox(sEnd.c_str(), L"데이터 조회 완료", MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
    }
    catch(EDatabaseError &E)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(...)
    {
        throw Exception(FrmLang->lblDbErr->Caption);//"알수없는 오류가 발생하였습니다.");
    }
}
//---------------------------------------------------------------------------

void __fastcall TAVIH0401::OnMessage(TMessage &Msg)
{
    switch (Msg.Msg)
    {
    case WM_PARAM_DATABASE:
        if (WP_DB_SELECT_OK == Msg.WParam)
        {
            //ShowMessage("Select Ok");
        }
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TAVIH0401::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle = "AVI-제어기 차량통과이력";

    CMM_ExportToExcelFile(sTitle, pGrid, pView, this);
}
//---------------------------------------------------------------------------

void __fastcall TAVIH0401::FormClose(TObject *Sender, TCloseAction &Action)
{
    POST_MSG(FParent, WM_SUBFORM_CLOSE, 0, 0);
    CommClose();
    //AVIH0401 = NULL;
}
//---------------------------------------------------------------------------

