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

#include <vcl.h>
#include "AppGlobalF.h"
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "ITSDbF.h"
#include "ITSLogF.h"
#include "ITSLangTransF.h"
#include "CDSCrossF.h"
#pragma hdrstop

#include "FrmCrsTrafVolStaSubF.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 "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#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 "cxLabel"
#pragma link "cxGridBandedTableView"
#pragma link "cxSpinEdit"
#pragma link "FRAME_ChartF"
#pragma link "cxDropDownEdit"
#pragma link "cxMaskEdit"
#pragma resource "*.dfm"

//TFrmCrsTrafVolStaSub *FrmCrsTrafVolStaSub = NULL;

//---------------------------------------------------------------------------
__fastcall TFrmCrsTrafVolStaSub::TFrmCrsTrafVolStaSub(TComponent* Owner, HWND hHandle, String sFrom, String sTo, String sCrossId, String sCamId, int nStatType, bool isLane, TCross *pObj)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    //CMM_LoadForm(g_sFormsDir, this);

    FParent     = hHandle;
    FStDateTime = sFrom;
    FEdDateTime = sTo;
    FCrossId    = sCrossId;
    FCamId      = sCamId;
    FStatType   = nStatType;
    FLane       = isLane;
    FCrossObj   = pObj;
    FCrossNm    = FCrossObj->IXR_NM;
    FCamNm      = "";

    if (FLane)
    {
        //차선별 이력일 경우 차트를 그리지 않는다
        PnlChart->Visible = false;
        spltChart->Visible = false;
    }
    else
    {
        FRAMEChart1->LblOptionName->Caption = "교차로";
        FRAMEChart1->LblOptionName->Visible = true;
        FRAMEChart1->CbOption->Visible = true;
    }
    FRAMEChart1->LblOptionName->Visible = false;
    FRAMEChart1->CbOption->Visible = false;
}
//---------------------------------------------------------------------------

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

    TvList->OptionsView->NoDataToDisplayInfoText = Caption + ":  " + lblText1->Caption;//조회결과가 없습니다.";

    FRAMEChart1->FTitle = Caption;//"시설물 통신단절통계";
    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;
    //FRAMEChart1->TvChart->DiagramColumn->Active = true;

    if (!FLane) FillChartOptions();

    LblSearch->Caption = lblText2->Caption + FStDateTime.SubString(1, 12) + " ~ " + FEdDateTime.SubString(1, 12);
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::FillChartOptions()
{
#if 0
    FRAMEChart1->CbOption->Properties->OnChange = NULL;
    FRAMEChart1->CbOption->Properties->Items->Clear();

    TCross* pCross = CrossManager->FLists.Find(FCrossId);
    if (pCross)
    {
        if (FCamNm == "*ALL*")
        {
            FOR_STL(TCrossCam*, pCam, pCross->FLists)
            {
                FRAMEChart1->CbOption->Properties->Items->Add("[" + pCam->CMRA_ID + "] " + pCam->CMRA_NM);
            }
        }
        else
        {
            String sCamId = StringReplace(FCamId, "'", "", TReplaceFlags() << rfReplaceAll);
            FRAMEChart1->CbOption->Properties->Items->Add("[" + sCamId + "] " + FCamNm);
        }
    }

    FRAMEChart1->CbOption->ItemIndex = 0;

    FRAMEChart1->CbOption->Properties->OnChange = CbOptionPropertiesChange;
#endif
}
//---------------------------------------------------------------------------

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

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

void __fastcall TFrmCrsTrafVolStaSub::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;

    if (FLane)
    {
        switch(FStatType)
        {
        case 0: Sel15M_Lane(); break; //15분
        case 1: Sel60M_Lane(); break; //1시간
        }
    }
    else
    {
        switch(FStatType)
        {
        case 0: Sel15M(); break; //15분
        case 1: Sel60M(); break; //1시간
        }
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TFrmCrsTrafVolStaSub::Sel05M()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::Sel05M_Lane()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::Sel15M()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery *pADO = ADOQry;

    sQry = "SELECT A.IXR_ID AS ixrId, A.IXR_NM AS ixrNm,                                                        \r\n"
           "       TO_CHAR(B.CLCT_DT, 'YYYYMMDDHH24MISS') AS statDt,                                            \r\n"
           "       TO_CHAR(B.CLCT_DT, 'YYYY-MM-DD HH24:MI') AS dspDt,                                           \r\n"
           "       NVL(B.SRVC_LVL, 0) AS srvcLvl,                                                               \r\n"
           "       NVL(B.DELY_HH, 0) AS delyHh,                                                                 \r\n"
           "       NVL(B.TFVL, 0) AS tfvl                                                                       \r\n"
           "  FROM TB_SC_IXR_MNGM A, TB_SC_IXR_15MM_STAT B                                                      \r\n"
           " WHERE 1=1                                                                                          \r\n"
           "   AND A.IXR_ID = :p01                                                                              \r\n"
           //"   AND A.IXR_ID IN (" + FCrossId + ")                                                               \r\n"
           "   AND A.IXR_ID = B.IXR_ID                                                                          \r\n"
           "   AND B.CLCT_DT BETWEEN TO_DATE(:p02, 'YYYYMMDDHH24MISS') AND TO_DATE(:p03, 'YYYYMMDDHH24MISS')    \r\n"
           " ORDER BY A.IXR_ID, B.CLCT_DT                                                                       \r\n";

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FCrossId);
        ITSDb_SQLBind(pADO, "p02", FStDateTime);
        ITSDb_SQLBind(pADO, "p03", FEdDateTime);
        ITSDb_SQLOpen(pADO);
    }
    catch(EDatabaseError &E)
    {
        DBERRORMSG("TFrmCrsTrafVolStaSub::Sel15M", String(E.ClassName()), E.Message, sQry);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &e)
    {
        DBERRORMSG("TFrmCrsTrafVolStaSub::Sel15M", String(e.ClassName()), e.Message, sQry);
        throw Exception(String(e.ClassName()) + e.Message);
    }
    SelHistory();
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::Sel15M_Lane()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::Sel30M()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::Sel30M_Lane()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::Sel60M()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery *pADO = ADOQry;

    sQry = "SELECT A.IXR_ID AS ixrId, A.IXR_NM AS ixrNm,                                                        \r\n"
           "       TO_CHAR(B.CLCT_DT, 'YYYYMMDDHH24MISS') AS statDt,                                            \r\n"
           "       TO_CHAR(B.CLCT_DT, 'YYYY-MM-DD HH24') AS dspDt,                                              \r\n"
           "       NVL(B.SRVC_LVL, 0) AS srvcLvl,                                                               \r\n"
           "       NVL(B.DELY_HH, 0) AS delyHh,                                                                 \r\n"
           "       NVL(B.TFVL, 0) AS tfvl                                                                       \r\n"
           "  FROM TB_SC_IXR_MNGM A, TB_SC_IXR_HH_STAT B                                                        \r\n"
           " WHERE 1=1                                                                                          \r\n"
           "   AND A.IXR_ID = :p01                                                                              \r\n"
           //"   AND A.IXR_ID IN (" + FCrossId + ")                                                               \r\n"
           "   AND A.IXR_ID = B.IXR_ID                                                                          \r\n"
           "   AND B.CLCT_DT BETWEEN TO_DATE(:p02, 'YYYYMMDDHH24MISS') AND TO_DATE(:p03, 'YYYYMMDDHH24MISS')    \r\n"
           " ORDER BY A.IXR_ID, B.CLCT_DT                                                                       \r\n";

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FCrossId);
        ITSDb_SQLBind(pADO, "p02", FStDateTime);
        ITSDb_SQLBind(pADO, "p03", FEdDateTime);
        ITSDb_SQLOpen(pADO);
    }
    catch(EDatabaseError &E)
    {
        DBERRORMSG("TFrmCrsTrafVolStaSub::Sel60M", String(E.ClassName()), E.Message, sQry);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &e)
    {
        DBERRORMSG("TFrmCrsTrafVolStaSub::Sel60M", String(e.ClassName()), e.Message, sQry);
        throw Exception(String(e.ClassName()) + e.Message);
    }
    SelHistory();
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::Sel60M_Lane()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::SelDay()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::SelDay_Lane()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::SelMonth()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::SelMonth_Lane()
{
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::SelHistory()
{
    DspHistory();
}
//---------------------------------------------------------------------------

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

    try
    {
        CMM_ClearGridTableView(TvList);

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

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

            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                m_pGDC->Values[nRow][Col01->Index] = nRow+1;
                m_pGDC->Values[nRow][Col02->Index] = "["+pADO->FieldByName("ixrId")->AsString+"] " + pADO->FieldByName("ixrNm")->AsString;
                m_pGDC->Values[nRow][Col04->Index] = pADO->FieldByName("dspDt")->AsString;
                m_pGDC->Values[nRow][Col05->Index] = pADO->FieldByName("srvcLvl")->AsInteger;
                m_pGDC->Values[nRow][Col06->Index] = pADO->FieldByName("tfvl")->AsInteger;
                m_pGDC->Values[nRow][Col07->Index] = pADO->FieldByName("srvcLvl")->AsString;
            }
        }
        __finally
        {
            if (pADO)
            {
                pADO->Close();
            }

            TvList->EndUpdate();
            if (!FLane)
            {
                DspChart();
            }
            LblRecords->Caption = FormatFloat("##,##0", m_pGDC->RecordCount) + lblCnt->Caption;//" 건";

            String sEnd = "데이터 " + LblRecords->Caption + " 이 조회 되었습니다.";
            Application->MessageBox(sEnd.c_str(), L"데이터 조회 완료", MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
    }
    catch(EDatabaseError &E)
    {
        DBERRORMSG("TFrmCrsTrafVolStaSub::DspHistory", String(E.ClassName()), E.Message, pADO->SQL->Text);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &e)
    {
        DBERRORMSG("TFrmCrsTrafVolStaSub::DspHistory", String(e.ClassName()), e.Message, pADO->SQL->Text);
        throw Exception(String(e.ClassName()) + e.Message);
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::DspChart()
{
    FRAMEChart1->ChartValueDisplay(FRAMEChart1->ChkDisplayVal->Checked);
    TcxGridChartView *TvChart = FRAMEChart1->TvChart;

    try
    {
        TvChart->ClearSeries();
        TvChart->DataController->RecordCount = 0;

        TcxGridChartSeries *pChart1 = NULL;

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

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

            int nRowCnt = TvList->DataController->RecordCount;
            for (int ii = 0; ii < nRowCnt; ii++)
            {
                nRow = TvChart->DataController->AppendRecord();

                pChart1->Values[nRow] = TvList->DataController->Values[ii][Col06->Index];

				String sCltTm = TvList->DataController->Values[ii][Col04->Index];
                TvChart->Categories->Values[nRow] = sCltTm;//sCltTm.SubString(12, 5);
            }
        }
        __finally
        {
    		TvChart->EndUpdate();
            TvList->EndUpdate();
        }
    }
    catch(EDatabaseError &E)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &e)
    {
        throw Exception(String(e.ClassName()) + e.Message);
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;

    CMM_ExportToExcelFile(sTitle, pGrid, pView, this);
    //CMM_ExportToExcelFile(String pTitle, TcxGrid *pGrid, TcxGridTableView *pView, TForm *pOwner, bool bExpand=true, bool bSaveAll=true, bool bUseNativeFormat=true);
}
//---------------------------------------------------------------------------

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

void __fastcall TFrmCrsTrafVolStaSub::FormDestroy(TObject *Sender)
{
    //
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::CbOptionPropertiesChange(TObject *Sender)
{
    //TcxComboBox *pCombo = (TcxComboBox*)Sender;
    DspChart();
    FRAMEChart1->EdFocus->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::Col06CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    TColor tColor = ACanvas->Brush->Color;
    TColor tFont  = clBlack;

    try
    {
        if (!VarIsNull(AViewInfo->Value))
        {
            int value = AViewInfo->Value;
            if (value == 0)
            {
                tColor = clSilver;
            }
            else
            {
                tColor = clLime;
            }
        }
        else
        {
            tColor = clSilver;
        }

        //if (tColor == clSilver) tFont = tColor;
        ACanvas->Font->Color = tFont;
        ACanvas->SetBrushColor(tColor);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmCrsTrafVolStaSub::BtnBestFitClick(TObject *Sender)
{
    try
    {
        TvList->BeginUpdate();
		TvList->ApplyBestFit(NULL, false, false);
	}
	__finally
	{
        TvList->EndUpdate();
	}
}
//---------------------------------------------------------------------------

