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

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

#include "AVIH0801F.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 resource "*.dfm"

TAVIH0801 *AVIH0801 = NULL;

//---------------------------------------------------------------------------
__fastcall TAVIH0801::TAVIH0801(TComponent* Owner, HWND hHandle, String sFrom, String sTo, String sIdList)
    : TForm(Owner)
{           
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

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

    Caption = "AVI-지점 수집 이력";
}
//---------------------------------------------------------------------------
__fastcall TAVIH0801::~TAVIH0801(void)
{
}
//--------------------------------------------------------------------------

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

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<AVI-지점 수집 이력>";
	//TvList->ViewInfo->GroupByBoxViewInfo->Text = "그룹핑할 필드의 헤더를 이곳으로 드래그 하세요";
    LblSearch->Caption = "검색조건: " + FStDateTime.SubString(1, 12) + " ~ " + FEdDateTime.SubString(1, 12);
}
//---------------------------------------------------------------------------

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

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

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

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

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

    String sQry;
    TADOQuery *pADO = ADOQry;

    sQry = "SELECT DT.AVI_CTLR_MNGM_NMBR, AVI.AVI_LCTN_NM, DT.AVI_DTCT_NMBR, DT.ISTL_LANE, \r\n"
           "       R.OCRR_DT, R.TFVL, R.AVRG_OCPY_RATE, R.SPED                             \r\n"
           "  FROM TB_AVI_DTCT_RAW_CLCT R, TB_AVI_DTCT_MSTR DT, TB_AVI_CTLR AVI            \r\n"
           " WHERE R.OCRR_DT BETWEEN :p01 AND :p02                                         \r\n"
           "   AND AVI.AVI_CTLR_MNGM_NMBR = DT.AVI_CTLR_MNGM_NMBR                          \r\n"
           "   AND DT.AVI_DTCT_NMBR IN(" + FIdList + ")                                    \r\n"
           "   AND DT.AVI_DTCT_NMBR = R.AVI_DTCT_NMBR                                      \r\n"
           " ORDER BY DT.AVI_CTLR_MNGM_NMBR ASC, R.OCRR_DT, DT.ISTL_LANE                   \r\n";

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FStDateTime);
        ITSDb_SQLBind(pADO, "p02", FEdDateTime);
        ITSDb_SQLOpen(pADO);

        DspHistory();
    }
    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 TAVIH0801::DspHistory()
{
    TADOQuery *pADO = ADOQry;

    try
    {
        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][Column09->Index] = pADO->FieldByName("AVI_LCTN_NM")->AsString;
                m_pGDC->Values[nRow][Column01->Index] = pADO->FieldByName("AVI_DTCT_NMBR")->AsString;
                m_pGDC->Values[nRow][Column02->Index] = pADO->FieldByName("ISTL_LANE")->AsString;
                String sDbDate = pADO->FieldByName("OCRR_DT")->AsString;
                m_pGDC->Values[nRow][Column03->Index] = ITSUtil_FormatStr(sDbDate, STR_DATETIME);

                m_pGDC->Values[nRow][Column04->Index] = pADO->FieldByName("TFVL")->AsString;
                //m_pGDC->Values[nRow][Column05->Index] = pADO->FieldByName("AVRG_OCPY_RATE")->AsString;
                m_pGDC->Values[nRow][Column06->Index] = pADO->FieldByName("SPED")->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 TAVIH0801::OnMessage(TMessage &Msg)
{
    switch (Msg.Msg)
    {
    case WM_PARAM_DATABASE:
        if (WP_DB_SELECT_OK == Msg.WParam)
        {
            //ShowMessage("Select Ok");
        }
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TAVIH0801::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle = "AVI-지점 수집 이력";

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

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

void __fastcall TAVIH0801::FormDestroy(TObject *Sender)
{
    CommClose();
}
//---------------------------------------------------------------------------

