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

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

#include "IHS00601F.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 "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxmdaset"
#pragma resource "*.dfm"

TIHS00601 *IHS00601 = NULL;

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

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

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

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

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

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

void __fastcall TIHS00601::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false; 
    ChkExpand->Visible = false;
    Application->ProcessMessages();
    CMM_ClearGridTableView(TvList);
    try
    {
        TvList->BeginUpdate(lsimImmediate);
        SelHistory();
    }
    __finally
    {
        TvList->EndUpdate();
        ChkExpand->Visible = true;
    }
}
//---------------------------------------------------------------------------

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

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

    String sQry;
    TADOQuery *pADO = ADOQry;

    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;
    }

    String sWhere = "";
    if (FIdList.IsEmpty())
    {
        sWhere = "";
    }
    else
    {
        sWhere = " AND " + FIdList;
    }

    String sTmp;

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

    sQry = "SELECT A.ROAD_NAME, B.NODE_NAME AS F_NAME, C.NODE_NAME AS T_NAME,   \r\n";
    sQry+= "       D.*                                                          \r\n";
    sQry+= "  FROM TB_LINK A, TB_NODE B, TB_NODE C,                             \r\n";
    sQry+= "       (                                                            \r\n";
    sQry+= sTmp;
    sQry+= "       ) D                                                          \r\n";
    sQry+= " WHERE A.LINK_ID   = D.LINK_ID                                      \r\n";
    sQry+= "   AND A.F_NODE_ID = B.NODE_ID                                      \r\n";
    sQry+= "   AND A.T_NODE_ID = C.NODE_ID                                      \r\n";

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FStDateTime);
        ITSDb_SQLBind(pADO, "p02", FEdDateTime);
        //ITSDb_SQLBind(pADO, "p03", FIdList);
        ITSDb_SQLOpen(pADO);

        dxMemData1->DisableControls();
        dxMemData1->Close();
        dxMemData1->CreateFieldsFromDataSet(pADO);
        dxMemData1->LoadFromDataSet(pADO);
        dxMemData1->Open();
        dxMemData1->First();
        dxMemData1->EnableControls();
        pADO->Close();


        DspHistoryMem();
    }
    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 TIHS00601::DspHistory()
{
    TADOQuery *pADO = ADOQry;
    try
    {
        CMM_ClearGridTableView(TvList);

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

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

            int nValue = 0;
            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                String sDbDate = pADO->FieldByName("PRCN_DT")->AsString;
                m_pGDC->Values[nRow][Column01->Index] = ITSUtil_FormatStr(sDbDate, STR_DATETIME);
                m_pGDC->Values[nRow][Column02->Index] = pADO->FieldByName("LINK_ID")->AsString;
                m_pGDC->Values[nRow][ColRoad->Index]  = pADO->FieldByName("ROAD_NAME")->AsString;
                m_pGDC->Values[nRow][ColFName->Index] = pADO->FieldByName("F_NAME")->AsString;
                m_pGDC->Values[nRow][ColTName->Index] = pADO->FieldByName("T_NAME")->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;

                    ii++;
                    if (ii >= MAX_COLSYS) break;
                }
            }
        }
        __finally
        {
            if (pADO)
            {
                pADO->Close();
            }

            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 TIHS00601::DspHistoryMem()
{
    try
    {
        int nRow = 0;
        int nDataCnt = 0;
        int ii = 0;
        try
        {
            int nValue = 0;
            while(!dxMemData1->Eof)
            {
                nRow = m_pGDC->AppendRecord();

                String sDbDate = dxMemData1->Fields->FieldByName("PRCN_DT")->AsString;
                m_pGDC->Values[nRow][Column01->Index] = ITSUtil_FormatStr(sDbDate, STR_DATETIME);
                m_pGDC->Values[nRow][Column02->Index] = dxMemData1->Fields->FieldByName("LINK_ID")->AsString;
                m_pGDC->Values[nRow][ColRoad->Index]  = dxMemData1->Fields->FieldByName("ROAD_NAME")->AsString;
                m_pGDC->Values[nRow][ColFName->Index] = dxMemData1->Fields->FieldByName("F_NAME")->AsString;
                m_pGDC->Values[nRow][ColTName->Index] = dxMemData1->Fields->FieldByName("T_NAME")->AsString;

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

                    ii++;
                    if (ii >= MAX_COLSYS) break;
                }
                dxMemData1->Next();
            }
        }
        __finally
        {
            dxMemData1->Close();

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

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

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

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

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

