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

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

#include "IHS00401F.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 resource "*.dfm"

TIHS00401 *IHS00401 = NULL;

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

    FParent     = hHandle;
    FStDateTime = sFrom;
    FEdDateTime = sTo;
    FIdList     = sIdList;
    FLinkLevel  = ALinkLevel;
}
//---------------------------------------------------------------------------
__fastcall TIHS00401::~TIHS00401(void)
{
}
//--------------------------------------------------------------------------

void __fastcall TIHS00401::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->lblPrcsTm->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);

    if (FLinkLevel == 2 || FLinkLevel == 3)
    {
        Column05->Visible = false;
        Column06->Visible = false;
        Column07->Visible = false;
        Column08->Visible = false;
        Column10->Visible = false;
        Column11->Visible = false;
    }
}
//---------------------------------------------------------------------------

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

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

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

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

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

    String sQry;
    TADOQuery *pADO = ADOQry;

    if (FLinkLevel == 1)
    {
        sQry = "SELECT A.LINK_ID, A.PRCN_DT, A.TFVL, A.SPED, A.OCPY_RATE, A.TRVL_HH,   \r\n"
               "       TO_DATE(A.PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2,             \r\n"
               "       B.CMMN_CD_KOR_NM CMTR_GRAD_CD,                                  \r\n"
               "       DECODE(A.MISS_YN, 'Y', '결측', 'N', '측정', '-' ) MISS_YN,      \r\n"
               "       A.PRCN_SPED, A.SMTH_SPED,                                       \r\n"
               "       A.ADJS_SPED, A.PTRN_SPED, NVL(C.CMMN_CD_KOR_NM, '-') PRCN_SORC, \r\n"
               "       NVL(D.CMMN_CD_KOR_NM, '-') ADJS_SORC, A.DATA_NUM                \r\n"
               "  FROM TB_LINK_TRAF_HS A,                                              \r\n"
               "       (SELECT CMMN_CD, CMMN_CD_KOR_NM                                 \r\n"
               "          FROM TB_CMMN_CD                                              \r\n"
               "         WHERE CMMN_CLSF_CD = 'LTC'                                    \r\n"
               "       ) B,                                                            \r\n"
               "       (SELECT CMMN_CD, CMMN_CD_KOR_NM                                 \r\n"
               "          FROM TB_CMMN_CD                                              \r\n"
               "         WHERE CMMN_CLSF_CD = 'CST'                                    \r\n"
               "       ) C,                                                            \r\n"
               "       (SELECT CMMN_CD, CMMN_CD_KOR_NM                                 \r\n"
               "          FROM TB_CMMN_CD                                              \r\n"
               "         WHERE CMMN_CLSF_CD = 'MCS'                                    \r\n"
               "       ) D                                                             \r\n"
               " WHERE A.CMTR_GRAD_CD = B.CMMN_CD                                      \r\n"
               "   AND A.PRCN_SORC    = C.CMMN_CD(+)                                   \r\n"
               "   AND A.ADJS_SORC    = D.CMMN_CD(+)                                   \r\n"
               "   AND A.PRCN_DT BETWEEN :p01                                          \r\n"
               "                     AND :p02                                          \r\n"
               "   AND A.LINK_ID = :p03                                                \r\n"
               " ORDER BY A.PRCN_DT, A.LINK_ID                                         \r\n";
    }
    else
    if (FLinkLevel == 2)
    {
        sQry = "SELECT A.IFSC_ID AS LINK_ID, A.PRCN_DT, A.TFVL, A.SPED, A.OCPY_RATE, A.TRVL_HH,   \r\n"
               "       TO_DATE(A.PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2,                        \r\n"
               "       B.CMMN_CD_KOR_NM CMTR_GRAD_CD, A.PTRN_SPED, A.DATA_NUM                     \r\n"
               "  FROM TB_IFSC_TRAF_HS A,                                                         \r\n"
               "       (SELECT CMMN_CD, CMMN_CD_KOR_NM                                            \r\n"
               "          FROM TB_CMMN_CD                                                         \r\n"
               "         WHERE CMMN_CLSF_CD = 'LTC'                                               \r\n"
               "       ) B                                                                        \r\n"
               " WHERE A.CMTR_GRAD_CD = B.CMMN_CD                                                 \r\n"
               "   AND A.PRCN_DT BETWEEN :p01                                                     \r\n"
               "                     AND :p02                                                     \r\n"
               "   AND A.IFSC_ID = :p03                                                           \r\n"
               " ORDER BY A.PRCN_DT, A.IFSC_ID                                                    \r\n";
    }
    else
    if (FLinkLevel == 3)
    {
        sQry = "SELECT A.ROAD_ID AS LINK_ID, A.PRCN_DT, A.TFVL, A.SPED, A.OCPY_RATE, A.TRVL_HH,   \r\n"
               "       TO_DATE(A.PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2,                        \r\n"
               "       B.CMMN_CD_KOR_NM CMTR_GRAD_CD, A.PTRN_SPED, A.DATA_NUM                     \r\n"
               "  FROM TB_ROAD_TRAF_HS A,                                                         \r\n"
               "       (SELECT CMMN_CD, CMMN_CD_KOR_NM                                            \r\n"
               "          FROM TB_CMMN_CD                                                         \r\n"
               "         WHERE CMMN_CLSF_CD = 'LTC'                                               \r\n"
               "       ) B                                                                        \r\n"
               " WHERE A.CMTR_GRAD_CD = B.CMMN_CD                                                 \r\n"
               "   AND A.PRCN_DT BETWEEN :p01                                                     \r\n"
               "                     AND :p02                                                     \r\n"
               "   AND A.ROAD_ID = :p03                                                           \r\n"
               " ORDER BY A.PRCN_DT, A.ROAD_ID                                                    \r\n";
    }
    else return ;

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

        if (FLinkLevel == 1)
        {
            DspHistory();
        }
        else
        if (FLinkLevel == 2)
        {
            DspHistory2();
        }
        else
        if (FLinkLevel == 3)
        {
            DspHistory2();
        }
    }
    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 TIHS00401::DspHistory2()
{
    TADOQuery *pADO = ADOQry;
    TcxGridChartView *TvChart = FRAMEChart1->TvChart;

    try
    {
    	TcxGridChartSeries *pChart1 = NULL;
    	//TcxGridChartSeries *pChart2 = NULL;
    	//TcxGridChartSeries *pChart3 = NULL;
    	//TcxGridChartSeries *pChart4 = NULL;
    	TcxGridChartSeries *pChart5 = 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 = "가공속도";

			//pChart3 = TvChart->CreateSeries();
			//pChart3->DataBinding->ValueType = "Integer";
			//pChart3->DisplayText = "평활화속도";

			//pChart4 = TvChart->CreateSeries();
			//pChart4->DataBinding->ValueType = "Integer";
			//pChart4->DisplayText = "보정속도";

			pChart5 = TvChart->CreateSeries();
			pChart5->DataBinding->ValueType = "Integer";
			pChart5->DisplayText = "패턴속도";

            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][Column13->Index]	= pADO->FieldByName("TFVL")->AsInteger;                        //교통량
                m_pGDC->Values[nRow][Column03->Index]	= pADO->FieldByName("SPED")->AsInteger;                        //속도
                m_pGDC->Values[nRow][Column14->Index]	= pADO->FieldByName("OCPY_RATE")->AsFloat;                     //점유율
                m_pGDC->Values[nRow][Column15->Index]	= pADO->FieldByName("TRVL_HH")->AsInteger;                     //통행시간
                m_pGDC->Values[nRow][Column04->Index]	= pADO->FieldByName("CMTR_GRAD_CD")->AsString;                 //소통등급
                //m_pGDC->Values[nRow][Column05->Index]	= pADO->FieldByName("MISS_YN")->AsString;                      //결측여부
                //m_pGDC->Values[nRow][Column06->Index]	= pADO->FieldByName("PRCN_SPED")->AsInteger;                   //가공속도
                //m_pGDC->Values[nRow][Column07->Index]	= pADO->FieldByName("SMTH_SPED")->AsInteger;                   //평활화속도
                //m_pGDC->Values[nRow][Column08->Index]	= pADO->FieldByName("ADJS_SPED")->AsInteger;                   //보정속도
                m_pGDC->Values[nRow][Column09->Index]	= pADO->FieldByName("PTRN_SPED")->AsInteger;                   //패턴속도
                //m_pGDC->Values[nRow][Column10->Index]	= pADO->FieldByName("PRCN_SORC")->AsString;                    //수집원
                //m_pGDC->Values[nRow][Column11->Index]	= pADO->FieldByName("ADJS_SORC")->AsString;                    //보정소스
                m_pGDC->Values[nRow][Column12->Index]	= pADO->FieldByName("DATA_NUM")->AsInteger;                    //데이터갯수

				pChart1->Values[nRow] = m_pGDC->Values[nRow][Column03->Index];
				//pChart2->Values[nRow] = m_pGDC->Values[nRow][Column06->Index];
				//pChart3->Values[nRow] = m_pGDC->Values[nRow][Column07->Index];
				//pChart4->Values[nRow] = m_pGDC->Values[nRow][Column08->Index];
				pChart5->Values[nRow] = m_pGDC->Values[nRow][Column09->Index];

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

    try
    {
    	TcxGridChartSeries *pChart1 = NULL;
    	TcxGridChartSeries *pChart2 = NULL;
    	TcxGridChartSeries *pChart3 = NULL;
    	TcxGridChartSeries *pChart4 = NULL;
    	TcxGridChartSeries *pChart5 = 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 = "가공속도";

			pChart3 = TvChart->CreateSeries();
			pChart3->DataBinding->ValueType = "Integer";
			pChart3->DisplayText = "평활화속도";

			pChart4 = TvChart->CreateSeries();
			pChart4->DataBinding->ValueType = "Integer";
			pChart4->DisplayText = "보정속도";

			pChart5 = TvChart->CreateSeries();
			pChart5->DataBinding->ValueType = "Integer";
			pChart5->DisplayText = "패턴속도";

            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][Column13->Index]	= pADO->FieldByName("TFVL")->AsInteger;                        //교통량
                m_pGDC->Values[nRow][Column03->Index]	= pADO->FieldByName("SPED")->AsInteger;                        //속도
                m_pGDC->Values[nRow][Column14->Index]	= pADO->FieldByName("OCPY_RATE")->AsFloat;                     //점유율
                m_pGDC->Values[nRow][Column15->Index]	= pADO->FieldByName("TRVL_HH")->AsInteger;                     //통행시간
                m_pGDC->Values[nRow][Column04->Index]	= pADO->FieldByName("CMTR_GRAD_CD")->AsString;                 //소통등급
                m_pGDC->Values[nRow][Column05->Index]	= pADO->FieldByName("MISS_YN")->AsString;                      //결측여부
                m_pGDC->Values[nRow][Column06->Index]	= pADO->FieldByName("PRCN_SPED")->AsInteger;                   //가공속도
                m_pGDC->Values[nRow][Column07->Index]	= pADO->FieldByName("SMTH_SPED")->AsInteger;                   //평활화속도
                m_pGDC->Values[nRow][Column08->Index]	= pADO->FieldByName("ADJS_SPED")->AsInteger;                   //보정속도
                m_pGDC->Values[nRow][Column09->Index]	= pADO->FieldByName("PTRN_SPED")->AsInteger;                   //패턴속도
                m_pGDC->Values[nRow][Column10->Index]	= pADO->FieldByName("PRCN_SORC")->AsString;                    //수집원
                m_pGDC->Values[nRow][Column11->Index]	= pADO->FieldByName("ADJS_SORC")->AsString;                    //보정소스
                m_pGDC->Values[nRow][Column12->Index]	= pADO->FieldByName("DATA_NUM")->AsInteger;                    //데이터갯수

				pChart1->Values[nRow] = m_pGDC->Values[nRow][Column03->Index];
				pChart2->Values[nRow] = m_pGDC->Values[nRow][Column06->Index];
				pChart3->Values[nRow] = m_pGDC->Values[nRow][Column07->Index];
				pChart4->Values[nRow] = m_pGDC->Values[nRow][Column08->Index];
				pChart5->Values[nRow] = m_pGDC->Values[nRow][Column09->Index];

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

void __fastcall TIHS00401::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"가공데이터이력";

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

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

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

