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

#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 "IAN00101F.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "FRAME_ChartF"
#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 "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "cxLabel"
#pragma link "dxSkinMcSkin"
#pragma resource "*.dfm"

TIAN00101 *IAN00101 = NULL;

//---------------------------------------------------------------------------
__fastcall TIAN00101::TIAN00101(TComponent* Owner, HWND hHandle, String sFrom, String sTo, String sIdList)
    : TForm(Owner)
{           
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

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

    FColumn[ 0] = Column03;
    FColumn[ 1] = Column04;
    FColumn[ 2] = Column05;
    FColumn[ 3] = Column06;
    FColumn[ 4] = Column07;
    FColumn[ 5] = Column08;
    FColumn[ 6] = Column09;
    FColumn[ 7] = Column10;
    FColumn[ 8] = Column11;
    FColumn[ 9] = Column12;
    FColumn[10] = Column13;
    FColumn[11] = Column14;
    FColumn[12] = Column15;
    FColumn[13] = Column16;
    FColumn[14] = Column17;

    int ii = 0;
    for (ii = 0; ii < MAX_COLSYS; ii++)
    {
        FChart[ii] = NULL;
    }

    ii = 0;
    FOR_STL(TItsColSys*, pObj, ItsColSysManager->FLists)
    {
        if (pObj->USE_YN == "N") continue;
        FColumn[ii]->Caption = pObj->CLCT_SYST_NM;
        FColumn[ii]->Visible = true;
        ii++;
        if (ii >= MAX_COLSYS) break;
    }
}
//---------------------------------------------------------------------------
__fastcall TIAN00101::~TIAN00101(void)
{
}
//--------------------------------------------------------------------------

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

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<교통정보수집결과분석 정보>";
	//TvList->ViewInfo->GroupByBoxViewInfo->Text = "그룹핑할 필드의 헤더를 이곳으로 드래그 하세요";

    FRAMEChart1->FTitle = Caption;//"교통정보수집결과분석";
    FRAMEChart1->SetChartLegend(FrmLang->lblColTm->Caption, FrmLang->lblCnt->Caption);//""수집시각", "개수");
    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;
    LblSearch->Caption = FrmLang->lblQryCond->Caption + FStDateTime.SubString(1, 12) + " ~ " + FEdDateTime.SubString(1, 12);
}
//---------------------------------------------------------------------------

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

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

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

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

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

    String sQry;
    TADOQuery *pADO = ADOQry;


#if 0
    sQry = "SELECT PRCN_DT, TO_DATE(PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2,        \r\n"
           "       SUM(OPER01) AS OPER01, SUM(UTIS01) AS UTIS01,                     \r\n"
           "       SUM(UTIS02) AS UTIS02, SUM(UTIS26) AS UTIS26                      \r\n"
           "  FROM (SELECT PRCN_DT,                                                  \r\n"
           "               DECODE(CLCT_SYST_CD, 'OPER01', CLCT_NUM, 0) AS OPER01,    \r\n"
           "               DECODE(CLCT_SYST_CD, 'UTIS01', CLCT_NUM, 0) AS UTIS01,    \r\n"
           "               DECODE(CLCT_SYST_CD, 'UTIS02', CLCT_NUM, 0) AS UTIS02,    \r\n"
           "               DECODE(CLCT_SYST_CD, 'UTIS26', CLCT_NUM, 0) AS UTIS26     \r\n"
           "          FROM TB_CLCT_SYST_STTS_HS                                      \r\n"
           "         WHERE PRCN_DT BETWEEN :p01                                      \r\n"
           "                           AND :p02                                      \r\n"
           "           AND CLCT_SYST_CD IN ('OPER01', 'UTIS01', 'UTIS02', 'UTIS26')  \r\n"
           "       )                                                                 \r\n"
           " GROUP BY PRCN_DT                                                        \r\n"
           " ORDER BY PRCN_DT                                                        \r\n";
#endif
    int ii = 0;
    String sTemp;
    String sFetch = "";
    String sSubFetch = "";
    ii = 0;
    FOR_STL(TItsColSys*, pObj, ItsColSysManager->FLists)
    {
        if (pObj->USE_YN == "N") continue;
        sTemp = ", SUM(" + pObj->CLCT_SYST_CD + ") AS " + pObj->CLCT_SYST_CD + " \r\n";
        sFetch += sTemp;

        sTemp = ", DECODE(CLCT_SYST_CD, '" + pObj->CLCT_SYST_CD + "', CLCT_NUM, 0) AS " + pObj->CLCT_SYST_CD + " \r\n";
        sSubFetch += sTemp;

        ii++;
        if (ii >= MAX_COLSYS) break;
    }

    sQry = "SELECT PRCN_DT, TO_DATE(PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2        \r\n";
    sQry+= sFetch;
    sQry+= "  FROM (SELECT PRCN_DT                                                  \r\n";
    sQry+= sSubFetch;
    sQry+= "          FROM TB_CLCT_SYST_STTS_HS                                     \r\n"
           "         WHERE PRCN_DT BETWEEN :p01                                     \r\n"
           "                           AND :p02                                     \r\n"
           "       )                                                                \r\n"
           " GROUP BY PRCN_DT                                                       \r\n"
           " ORDER BY PRCN_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 TIAN00101::DspHistory()
{
    TADOQuery *pADO = ADOQry;
    TcxGridChartView *TvChart = FRAMEChart1->TvChart;

    try
    {
        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;


            int ii = 0;
            FOR_STL(TItsColSys*, pObj, ItsColSysManager->FLists)
            {
                FChart[ii] = TvChart->CreateSeries();
                FChart[ii]->DataBinding->ValueType = "Integer";
                FChart[ii]->DisplayText = pObj->CLCT_SYST_NM;
                ii++;
                if (ii >= MAX_COLSYS) break;
            }

            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                String sDbDate = pADO->FieldByName("PRCN_DT")->AsString;
                m_pGDC->Values[nRow][Column01->Index] = APP_FormatStr(sDbDate, STR_DATETIME);  //가공시각

                int nTotal = 0;
                int nValue = 0;

                ii = 0;
                FOR_STL(TItsColSys*, pObj, ItsColSysManager->FLists)
                {
                    nValue = pADO->FieldByName(pObj->CLCT_SYST_CD)->AsInteger;
                    m_pGDC->Values[nRow][FColumn[ii]->Index] = nValue;
    				FChart[ii]->Values[nRow] = nValue;
                    nTotal += nValue;

                    ii++;
                    if (ii >= MAX_COLSYS) break;
                }
                m_pGDC->Values[nRow][Column02->Index] = nTotal;

				TvChart->Categories->Values[nRow] = pADO->FieldByName("PRCN_DT")->AsString.SubString(1,12);
            }
        }
        __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)
    {
            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 TIAN00101::OnMessage(TMessage &Msg)
{
    switch (Msg.Msg)
    {
    case WM_PARAM_DATABASE:
        if (WP_DB_SELECT_OK == Msg.WParam)
        {
            //ShowMessage("Select Ok");
        }
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TIAN00101::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"교통정보수집결과분석";

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

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

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

