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

#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 "IHS00301F.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"

TIHS00301 *IHS00301 = NULL;

//---------------------------------------------------------------------------
__fastcall TIHS00301::TIHS00301(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 TIHS00301::~TIHS00301(void)
{
}
//--------------------------------------------------------------------------

void __fastcall TIHS00301::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->lblSpd->Caption);//""수집시각", "속도(km/h)");
    FRAMEChart1->ChartValueDisplay(FRAMEChart1->ChkDisplayVal->Checked);
    FRAMEChart1->TvChart->ToolBox->CustomizeButton = true;
    FRAMEChart1->TvChart->Legend->Position = cppDefault;

    LblSearch->Caption = FrmLang->lblQryCond->Caption + "[" + FIdList + "] " + FStDateTime.SubString(1, 12) + " ~ " + FEdDateTime.SubString(1, 12);
}
//---------------------------------------------------------------------------

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

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

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

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

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

    String sQry;
    TADOQuery *pADO = ADOQry;

#if 1
    int ii = 0;
    String sTemp;
    String sFetch = "";
    ii = 0;
    FOR_STL(TItsColSys*, pObj, ItsColSysManager->FLists)
    {
        if (pObj->USE_YN == "N") continue;

        sTemp = ", MAX(DECODE(A.CLCT_SYST_CD, '" + pObj->CLCT_SYST_CD + "', A.SPED, 0)) " + pObj->CLCT_SYST_CD + " \r\n";
        sFetch += sTemp;

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

    sQry = "SELECT A.LINK_ID, A.PRCN_DT, TO_DATE(A.PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2 \r\n";
    sQry+= sFetch;
    sQry+= "  FROM TB_LINK_TRAF_CLCT_HS A                                                   \r\n"
           " WHERE A.PRCN_DT BETWEEN :p01                                                   \r\n"
           "                     AND :p02                                                   \r\n"
           "   AND A.LINK_ID = :p03                                                         \r\n"
           " GROUP BY A.LINK_ID, A.PRCN_DT                                                  \r\n"
           " ORDER BY A.LINK_ID, A.PRCN_DT                                                  \r\n";
#else
    sQry = "SELECT A.*, TO_DATE(A.PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2  \r\n"
           "  FROM TB_LINK_TRAF_CLCT_HS A                                   \r\n"
           " WHERE A.PRCN_DT BETWEEN :p01                                   \r\n"
           "                     AND :p02                                   \r\n"
           "   AND A.LINK_ID = :p03                                         \r\n"
           " ORDER BY A.LINK_ID, A.PRCN_DT                                  \r\n";
#endif

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FStDateTime);
        ITSDb_SQLBind(pADO, "p02", FEdDateTime);
        ITSDb_SQLBind(pADO, "p03", FIdList);
        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 TIHS00301::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;
            }

            int nValue = 0;
            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                String sDbDate = pADO->FieldByName("PRCN_DT")->AsString;
                m_pGDC->Values[nRow][Column01->Index] = APP_FormatStr(sDbDate, STR_DATETIME);
                m_pGDC->Values[nRow][Column02->Index] = pADO->FieldByName("LINK_ID")->AsString;

                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;

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

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

            TvChart->ToolBox->CustomizeButton = true;
            TvChart->Legend->Position = cppDefault;
    		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 TIHS00301::OnMessage(TMessage &Msg)
{
    switch (Msg.Msg)
    {
    case WM_PARAM_DATABASE:
        if (WP_DB_SELECT_OK == Msg.WParam)
        {
            //ShowMessage("Select Ok");
        }
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TIHS00301::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"수집데이터이력조회";

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

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

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

