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

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

#include "VDSS0101F.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 "cxGridBandedTableView"
#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 "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "cxSpinEdit"
#pragma link "dxSkinMcSkin"
#pragma resource "*.dfm"

TVDSS0101 *VDSS0101 = NULL;

//---------------------------------------------------------------------------
__fastcall TVDSS0101::TVDSS0101(TComponent* Owner, HWND hHandle,
                                String ASelId, String AStTime, String AEdTime, int AStatType)
    : TForm(Owner)
{           
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FParent      = hHandle;

    FSelId     = ASelId;
	FStTime    = AStTime;
    FEdTime    = AEdTime;
    FStatType  = AStatType;

#if 0
    Column05->FooterAlignmentHorz = taRightJustify;
    Column06->FooterAlignmentHorz = taRightJustify;
    Column07->FooterAlignmentHorz = taRightJustify;
#endif
}
//---------------------------------------------------------------------------
__fastcall TVDSS0101::~TVDSS0101(void)
{
}
//--------------------------------------------------------------------------

void __fastcall TVDSS0101::FormInit()
{
    ADOQry->Connection = ITSDb_GetConnection();
    m_pGDC = TvList->DataController;

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<VDS-검지기 소통정보 통계>";

    FRAMEChart1->FTitle = Caption;//"VDS-검지기 소통정보 통계";
    //FRAMEChart1->SetChartLegend(FrmLang->lblStatTm->Caption, FrmLang->lblSpd->Caption);//"통계시각", "평균 속도(Km)");
    FRAMEChart1->SetChartLegend(FrmLang->lblStatTm->Caption, "");//"통계시각", "");
    FRAMEChart1->ChartValueDisplay(FRAMEChart1->ChkDisplayVal->Checked);
    FRAMEChart1->TvChart->ToolBox->CustomizeButton = true;
    FRAMEChart1->TvChart->Legend->Position = cppDefault;

    //LblSearch->Caption = "검색조건: " + FSelId + " " + FStTime + "~" + FEdTime ;
    LblSearch->Caption = FrmLang->lblQryCond->Caption + FStTime + "~" + FEdTime ;
}
//---------------------------------------------------------------------------

void __fastcall TVDSS0101::FormShow(TObject *Sender)
{
    FormInit();
    Refresh();
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TVDSS0101::CommClose()
{
    CMM_SaveForm(g_sFormsDir, this);
    //VDSS0101 = NULL;
}
//---------------------------------------------------------------------------

void __fastcall TVDSS0101::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false; 
    Application->ProcessMessages();
    SelHistory();
}
//---------------------------------------------------------------------------

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

void __fastcall TVDSS0101::SelHistory()
{
    TSqlCursor sqlCrs;

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

    String sDateFormat;
    FDateFormat = STR_DATETIME;
    switch(FStatType)
    {
    case 0: //15분 통계
    case 1: //시간 통계(1시간)
        FDateFormat = STR_HHNN;
        FStTime = FStTime + "0000";
        FEdTime = FEdTime + "5959";
        sDateFormat = "SUBSTR(STAT_DT, 1, 12) DATES, TO_DATE(SUBSTR(STAT_DT, 1, 12), 'YYYY-MM-DD HH24:MI') AS DATENM, ";
        break;
    case 2: //일 통계(1일)
        FDateFormat = STR_DATE;
        FStTime = FStTime + "000000";
        FEdTime = FEdTime + "235959";
        //sDateFormat = "SUBSTR(STAT_DT, 1, 10) DATES, TO_DATE(SUBSTR(STAT_DT, 1, 10), 'YYYY-MM-DD HH24') AS DATENM, ";
        sDateFormat = "SUBSTR(STAT_DT, 1, 8) DATES, TO_DATE(SUBSTR(STAT_DT, 1, 8), 'YYYY-MM-DD') AS DATENM, ";
        break;
    case 3: //월 통계(1개월)
        FDateFormat = STR_MM;
        sTemp.printf(L"%02d", ITSUtil_GetMonthLastDay(AnsiString(FStTime).c_str()));
        //FStTime = FStTime + "01000000";
        FStTime = FStTime + "00000000";
        FEdTime = FEdTime + sTemp + "235959";
        //sDateFormat = "SUBSTR(STAT_DT, 1,  8) DATES, TO_DATE(SUBSTR(STAT_DT, 1,  8), 'YYYY-MM-DD') AS DATENM, ";
        sDateFormat = "SUBSTR(STAT_DT, 1,  6) DATES, TO_DATE(SUBSTR(STAT_DT, 1,  6), 'YYYY-MM') AS DATENM, ";
        break;
    default: return;
    }

    String sStatTable;
    switch(FStatType)
    {
    case 0:  sStatTable = "TB_VDS_DTCT_15M_STAT"; break;
    case 1:  sStatTable = "TB_VDS_DTCT_HH_STAT";  break;
    case 2:  sStatTable = "TB_VDS_DTCT_DD_STAT";  break;
    case 3:  sStatTable = "TB_VDS_DTCT_MN_STAT";  break;
    }
//    sQry = "SELECT C.VDS_CTLR_NMBR, C.VDS_NM, A.VDS_DTCT_NMBR ID, A.DATENM, A.DATES,    \r\n"
    sQry = "SELECT C.VDS_CTLR_NMBR, A.VDS_DTCT_NMBR ID, A.DATENM, A.DATES,              \r\n"
           "       DECODE(C.VDS_TYPE_CD, 'C', B.VDS_DTCT_NM, C.VDS_NM) AS VDS_NM,       \r\n"
           "       B.ISTL_LANE, B.VDS_DTCT_NM,                                          \r\n"
           "       B.DTCT_TYPE,                                                         \r\n"
           "       (SELECT CMMN_CD_KOR_NM                                               \r\n"
           "          FROM TB_CMMN_CD                                                   \r\n"
           "         WHERE CMMN_CLSF_CD = 'DTT'                                         \r\n"
           "           AND CMMN_CD      = B.DTCT_TYPE) AS DTCT_TYPE_NM,                 \r\n"
           "       B.DTCT_DIR,                                                          \r\n"
           "       (SELECT CMMN_CD_KOR_NM                                               \r\n"
           "          FROM TB_CMMN_CD                                                   \r\n"
           "         WHERE CMMN_CLSF_CD = 'VCD'                                         \r\n"
           "           AND CMMN_CD      = B.DTCT_DIR) AS DTCT_DIR_NM,                   \r\n"
           "       A.TFVL, A.AVRG_SPED, A.AVRG_OCPY_RATE, A.AVRG_HDWY, A.AVRG_LNGT      \r\n"
           "  FROM (SELECT VDS_DTCT_NMBR,                                               \r\n"
           "               " + sDateFormat + "                                          \r\n"
           "               TFVL, AVRG_SPED, AVRG_OCPY_RATE, AVRG_HDWY, AVRG_LNGT        \r\n"
           "          FROM " + sStatTable + " A                                         \r\n"
           "         WHERE VDS_DTCT_NMBR IN(" + FSelId + ")                             \r\n"
           "           AND STAT_DT BETWEEN :p02 AND :p03                                \r\n"
           "       ) A,                                                                 \r\n"
           "       TB_VDS_DTCT B,                                                       \r\n"
           "       TB_VDS_CTLR C                                                        \r\n"
           " WHERE B.DEL_YN = 'N'                                                       \r\n"
           "   AND A.VDS_DTCT_NMBR = B.VDS_DTCT_NMBR                                    \r\n"
           "   AND B.VDS_CTLR_NMBR = C.VDS_CTLR_NMBR                                    \r\n"
           " ORDER BY DATES                                                             \r\n";

    try
    {
        ITSDb_SQLText(pADO, sQry);
#if 0
        ITSDb_SQLBind(pADO, "p01", FSelId);
#endif
        ITSDb_SQLBind(pADO, "p02", FStTime);
        ITSDb_SQLBind(pADO, "p03", FEdTime);

        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 TVDSS0101::DspHistory()
{
    TADOQuery *pADO = ADOQry;
    TcxGridChartView *TvChart = FRAMEChart1->TvChart;

    try
    {
    	TcxGridChartSeries *pChart1 = NULL;
    	TcxGridChartSeries *pChart2 = NULL;

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

        CMM_ClearGridTableView(TvList);

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

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

			pChart1 = TvChart->CreateSeries();
			pChart1->DataBinding->ValueType = "Integer";
			pChart1->DisplayText = "교통량(대)";

			pChart2 = TvChart->CreateSeries();
			pChart2->DataBinding->ValueType = "Integer";
			pChart2->DisplayText = "평균 속도(km/h)";

            int nVol, nSpd;
            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                m_pGDC->Values[nRow][Column01->Index] = pADO->FieldByName("ID")->AsString;              //ID
                m_pGDC->Values[nRow][Column02->Index] = pADO->FieldByName("ISTL_LANE")->AsString;       //차선
                //m_pGDC->Values[nRow][Column03->Index] = pADO->FieldByName("VDS_DTCT_NM")->AsString;      //교통량
                String sDbDate = pADO->FieldByName("DATES")->AsString;
                m_pGDC->Values[nRow][Column04->Index] = APP_FormatStr(sDbDate, FDateFormat);          //통계시각

                nVol = pADO->FieldByName("TFVL")->AsInteger;
                nSpd = pADO->FieldByName("AVRG_SPED")->AsInteger;

                m_pGDC->Values[nRow][Column05->Index] = nVol;      //교통량
                m_pGDC->Values[nRow][Column06->Index] = nSpd;      //평균 속도
                m_pGDC->Values[nRow][Column07->Index] = pADO->FieldByName("AVRG_OCPY_RATE")->AsFloat;   //평균 점유율
                //m_pGDC->Values[nRow][Column08->Index] = pADO->FieldByName("AVRG_HDWY")->AsString;      //평균 차두시간
                //m_pGDC->Values[nRow][Column09->Index] = pADO->FieldByName("AVRG_LNGT")->AsString;      //평균 길이
#if 0
                m_pGDC->Values[nRow][Column07->Index] = FormatFloat("##0.#0", pADO->FieldByName("AVRG_OCPY_RATE")->AsFloat);   //평균 점유율
                m_pGDC->Values[nRow][Column08->Index] = pADO->FieldByName("AVRG_HDWY")->AsInteger;      //평균 차두시간
                m_pGDC->Values[nRow][Column09->Index] = pADO->FieldByName("AVRG_LNGT")->AsInteger;      //평균 길이
#endif

                m_pGDC->Values[nRow][Column10->Index] = pADO->FieldByName("VDS_CTLR_NMBR")->AsString+"."+pADO->FieldByName("VDS_NM")->AsString;

				pChart1->Values[nRow] = nVol;
				pChart2->Values[nRow] = nSpd;

				TvChart->Categories->Values[nRow] = m_pGDC->Values[nRow][Column04->Index];
            }
        }
        __finally
        {
            if (pADO)
            {
                pADO->Close();
            }

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

            String sEnd = FrmLang->lblQrySel->Caption + " [" + LblRecords->Caption + "]";//"데이터 " + LblRecords->Caption + " 이 조회 되었습니다.";
            Application->MessageBox(sEnd.c_str(),
                                    FrmLang->lblQryEnd->Caption.c_str(),//L"데이터 조회 완료",
                                    MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
    }
    catch(EDatabaseError &E)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(E.ClassName()), E.Message, pADO->SQL->Text);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &e)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(e.ClassName()), e.Message, pADO->SQL->Text);
        throw Exception(String(e.ClassName()) + e.Message);
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TVDSS0101::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"VDS-검지기 소통정보통계";

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

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

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

void __fastcall TVDSS0101::TvListTcxGridDataControllerTcxDataSummaryDefaultGroupSummaryItems6GetText(TcxDataSummaryItem *Sender,
          const Variant &AValue, bool AIsFooter, UnicodeString &AText)
{
    AText = "소계";
}
//---------------------------------------------------------------------------

void __fastcall TVDSS0101::TvListTcxGridDataControllerTcxDataSummaryFooterSummaryItems3GetText(TcxDataSummaryItem *Sender,
          const Variant &AValue, bool AIsFooter, UnicodeString &AText)
{
    AText = "합계";
}
//---------------------------------------------------------------------------

