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

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

#include "DSRH0701F.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCalc"
#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 "cxSplitter"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma resource "*.dfm"

TDSRH0701 *DSRH0701 = NULL;

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

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

    Caption = "DSRC-RSE OBU 수집 통계";
}
//---------------------------------------------------------------------------
__fastcall TDSRH0701::~TDSRH0701(void)
{
}
//--------------------------------------------------------------------------

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

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<DSRC-RSE OBU 수집 통계 정보>";

    cxSplitter1->Visible = false;
    PnlChart->Visible = false;
#if 0
    FRAMEChart1->FTitle = "DSRC-RSE OBU 수집 통계";
    FRAMEChart1->SetChartLegend("수집시각", "개수");
    FRAMEChart1->ChartValueDisplay(FRAMEChart1->ChkDisplayVal->Checked);
    FRAMEChart1->TvChart->ToolBox->CustomizeButton = true;
    FRAMEChart1->TvChart->Legend->Position = cppDefault;
    FRAMEChart1->TvChart->DiagramStackedBar->Enabled = true;
    FRAMEChart1->TvChart->DiagramStackedColumn->Enabled = true;
    FRAMEChart1->TvChart->DiagramStackedColumn->Active = true;
#endif
    LblSearch->Caption = "검색조건: " + FStDateTime.SubString(1, 10) + " ~ " + FEdDateTime.SubString(1, 10);
}
//---------------------------------------------------------------------------

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

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

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

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

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

    String     sQry;
    String     sTable;
    TADOQuery *pADO = ADOQry;

    switch(FSTAT)
    {
    case 0: sTable = "TB_RSE_OBU_CLCT_HH_STAT";
        break;
    case 1: sTable = "TB_RSE_OBU_CLCT_DD_STAT";
        break;
    default: return;
    }

    sQry = "SELECT M.ID, M.RSE_ID, M.ISTL_LCTN_NM, H.STAT_DT AS COLL_DT,            \r\n"
           "       TO_DATE(H.STAT_DT, 'YYYYMMDDHH24MISS') AS COLL_DT2,              \r\n"
           "       H.STAT_DT, H.DAY_TYPE_CD, H.CLCT_NUM,                            \r\n"
           "       C.DAY_TYPE_CDNM                                                  \r\n"
           "  FROM TB_RSE_MSTR M,                                                   \r\n"
           "       " + sTable + " H,                                                \r\n"
           "       (SELECT CMMN_CD AS DAY_TYPE_CD, CMMN_CD_KOR_NM AS DAY_TYPE_CDNM  \r\n"
           "          FROM TB_CMMN_CD                                               \r\n"
           "         WHERE CMMN_CLSF_CD = 'DTW') C                                  \r\n"
           " WHERE M.ID IN (" + FIdList + ")                                        \r\n"
           "   AND M.ID = H.ID                                                      \r\n"
           "   AND H.STAT_DT BETWEEN :p01 AND :p02                                  \r\n"
           "   AND H.DAY_TYPE_CD = C.DAY_TYPE_CD                                    \r\n"
           " ORDER BY M.ID, H.STAT_DT                                               \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 TDSRH0701::DspHistory()
{
    TADOQuery *pADO = ADOQry;
    TcxGridChartView *TvChart = FRAMEChart1->TvChart;

    try
    {
#if 0
    	TcxGridChartSeries *pChart1 = NULL;
    	TcxGridChartSeries *pChart2 = NULL;
    	TcxGridChartSeries *pChart3 = NULL;
    	TcxGridChartSeries *pChart4 = NULL;
    	TcxGridChartSeries *pChart5 = NULL;
    	TcxGridChartSeries *pChart6 = NULL;

        TvChart->ClearSeries();
        FRAMEChart1->ChartValueDisplay(FRAMEChart1->ChkDisplayVal->Checked);
#endif

        CMM_ClearGridTableView(TvList);

        int nRow = 0;
        int nDataCnt = 0;
        try {
            TvList->BeginUpdate();
            nDataCnt = pADO->RecordCount;
            m_pGDC->RecordCount = nDataCnt;
#if 0
            TvChart->BeginUpdate();
            TvChart->DataController->RecordCount = nDataCnt;

			pChart1 = TvChart->CreateSeries();
			pChart1->DataBinding->ValueType = "Integer";
			pChart1->DisplayText = "원활";

			pChart2 = TvChart->CreateSeries();
			pChart2->DataBinding->ValueType = "Integer";
			pChart2->DisplayText = "지체";

			pChart3 = TvChart->CreateSeries();
			pChart3->DataBinding->ValueType = "Integer";
			pChart3->DisplayText = "정체";

			pChart4 = TvChart->CreateSeries();
			pChart4->DataBinding->ValueType = "Integer";
			pChart4->DisplayText = "정보없음";
#endif

            String sTimeFormat = STR_DATE;
            if (FSTAT == 0) sTimeFormat = STR_DATEHOUR;

            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                m_pGDC->Values[nRow][Column01->Index] = pADO->FieldByName("ID")->AsString;
                m_pGDC->Values[nRow][Column02->Index] = pADO->FieldByName("RSE_ID")->AsString;
                m_pGDC->Values[nRow][Column03->Index] = pADO->FieldByName("ISTL_LCTN_NM")->AsString;
                String sDbDate = pADO->FieldByName("COLL_DT")->AsString;
                m_pGDC->Values[nRow][Column04->Index] = ITSUtil_FormatStr(sDbDate, sTimeFormat);
                m_pGDC->Values[nRow][Column05->Index] = pADO->FieldByName("DAY_TYPE_CDNM")->AsString;
                m_pGDC->Values[nRow][Column06->Index] = pADO->FieldByName("CLCT_NUM")->AsInteger;

#if 0
				pChart1->Values[nRow] = m_pGDC->Values[nRow][Column04->Index];
				pChart2->Values[nRow] = m_pGDC->Values[nRow][Column05->Index];
				pChart3->Values[nRow] = m_pGDC->Values[nRow][Column06->Index];
				pChart4->Values[nRow] = m_pGDC->Values[nRow][Column07->Index];

				TvChart->Categories->Values[nRow] = pADO->FieldByName("STAT_DT")->AsString.SubString(1,12);
#endif
            }
        }
        __finally
        {
            if (pADO)
            {
                pADO->Close();
            }

#if 0
    		TvChart->EndUpdate();
#endif
            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 TDSRH0701::OnMessage(TMessage &Msg)
{
    switch (Msg.Msg)
    {
    case WM_PARAM_DATABASE:
        if (WP_DB_SELECT_OK == Msg.WParam)
        {
            //ShowMessage("Select Ok");
        }
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TDSRH0701::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle = "DSRC-RSE OBU 수집통계";

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

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

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

