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

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

#include "AVIS0201F.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#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 "cxGridBandedTableView"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "FRAME_ChartF"
#pragma resource "*.dfm"

#define AVRG_OCPY_RATE 0

TAVIS0201 *AVIS0201 = NULL;
//---------------------------------------------------------------------------
__fastcall TAVIS0201::TAVIS0201(TComponent* Owner, HWND hHandle,
                                String ASelId, String AStTime, String AEdTime, int AStatType)
    : TForm(Owner)
{           
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FParent      = hHandle;

    FSelId     = ASelId;
	FStTime    = AStTime;
    FEdTime    = AEdTime;
    FStatType  = AStatType;

    Caption = "AVI-검지기 소통정보 통계";
#if !AVRG_OCPY_RATE
    Column07->Visible = false;
    Column07->VisibleForCustomization = false;
#endif
}
//---------------------------------------------------------------------------
__fastcall TAVIS0201::~TAVIS0201(void)
{
}
//--------------------------------------------------------------------------

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TAVIS0201::FormInit()
{
    ADOQry->Connection = ITSDb_GetConnection();
    m_pGDC = TvList->DataController;

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<AVI-검지기 소통정보 통계>";

    FRAMEChart1->FTitle = "AVI-검지기 소통정보 통계";
    //FRAMEChart1->SetChartLegend("통계시각", "평균 속도(Km)");
    FRAMEChart1->SetChartLegend("통계시각", "");
    FRAMEChart1->ChartValueDisplay(FRAMEChart1->ChkDisplayVal->Checked);
    FRAMEChart1->TvChart->ToolBox->CustomizeButton = true;
    FRAMEChart1->TvChart->Legend->Position = cppDefault;

    LblSearch->Caption = "검색조건: " + FSelId + " " + FStTime + "~" + FEdTime ;
}
//---------------------------------------------------------------------------

/*
 * form을 보여줄때 호출되는 event 메서드이다.
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TAVIS0201::FormShow(TObject *Sender)
{
    FormInit();
    Refresh();
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

/*
 * 닫기버튼 이나 x버튼 클릭시 공통으로 처리하는 로직이들어간다..
 * Form과 DataModule class를 delete시킨다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TAVIS0201::CommClose()
{
    CMM_SaveForm(g_sFormsDir, this);
    //AVIS0201 = NULL;
}
//---------------------------------------------------------------------------

/*
 * 최초 1회 수행되는 타이머 이벤트
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TAVIS0201::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false; 
    Application->ProcessMessages();
    SelHistory();
}
//---------------------------------------------------------------------------

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

/*
 * Refresh Data Event Function
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TAVIS0201::SelHistory()
{
    TSqlCursor sqlCrs;

    String sTemp;
    String sQry;
    TADOQuery *pADO = ADOQry;

    String sDateFormat;
    FDateFormat = STR_DATETIME;
    switch(FStatType)
    {
    case 0: //15분 통계
    case 1: //시간 통계(1시간)
        FDateFormat = STR_HHNN;
        FStTime = FStTime + "0000";
        FEdTime = FEdTime + "5959";
        sDateFormat = "SUBSTR(STAT_DT, 1, 12) DATES, TO_DATE(SUBSTR(STAT_DT, 1, 12), 'YYYY-MM-DD HH24:MI') AS DATENM, ";
        break;
    case 2: //일 통계(1일)
        FDateFormat = STR_DATEHOUR;
        FStTime = FStTime + "000000";
        FEdTime = FEdTime + "235959";
        sDateFormat = "SUBSTR(STAT_DT, 1, 10) DATES, TO_DATE(SUBSTR(STAT_DT, 1, 10), 'YYYY-MM-DD HH24') AS DATENM, ";
        break;
    case 3: //월 통계(1개월)
        FDateFormat = STR_DATE;
        sTemp.printf(L"%02d", ITSUtil_GetMonthLastDay(AnsiString(FStTime).c_str()));
        FStTime = FStTime + "01000000";
        FEdTime = FEdTime + sTemp + "235959";
        sDateFormat = "SUBSTR(STAT_DT, 1,  8) DATES, TO_DATE(SUBSTR(STAT_DT, 1,  8), 'YYYY-MM-DD') AS DATENM, ";
        break;
    default: return;
    }

    String sStatTable;
    switch(FStatType)
    {
    case 0:  sStatTable = "TB_AVI_DTCT_15M_STAT"; break;
    case 1:  sStatTable = "TB_AVI_DTCT_HH_STAT";  break;
    case 2:  sStatTable = "TB_AVI_DTCT_DD_STAT";  break;
    case 3:  sStatTable = "TB_AVI_DTCT_MN_STAT";  break;
    }
    sQry = "SELECT B.AVI_DTCT_NMBR ID, A.DATENM, A.DATES,      \r\n"
           "       B.ISTL_LANE,                                \r\n"
           "       A.TFVL, A.AVRG_SPED, A.AVRG_OCPY_RATE       \r\n"
           "  FROM (SELECT AVI_DTCT_NMBR AS DTCT_NMBR,         \r\n"
           "               " + sDateFormat + "                 \r\n"
           "               TFVL, AVRG_SPED, AVRG_OCPY_RATE     \r\n"
           "          FROM " + sStatTable + " A                \r\n"
           "         WHERE AVI_DTCT_NMBR = :p01                \r\n"
           "           AND STAT_DT BETWEEN :p02 AND :p03       \r\n"
           "       ) A,                                        \r\n"
           "       TB_AVI_DTCT_MSTR B                          \r\n"
           " WHERE B.DEL_YN    = 'N'                           \r\n"
           "   AND A.DTCT_NMBR = B.AVI_DTCT_NMBR               \r\n"
           " ORDER BY DATES                                    \r\n";

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FSelId);
        ITSDb_SQLBind(pADO, "p02", FStTime);
        ITSDb_SQLBind(pADO, "p03", FEdTime);

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

    try
    {
    	TcxGridChartSeries *pChart1 = NULL;
    	TcxGridChartSeries *pChart2 = 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 = "평균 속도(km/h)";

            int nVol, nSpd;
            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                m_pGDC->Values[nRow][Column01->Index] = pADO->FieldByName("ID")->AsString;              //ID
                m_pGDC->Values[nRow][Column02->Index] = pADO->FieldByName("ISTL_LANE")->AsString;       //차선
                String sDbDate = pADO->FieldByName("DATES")->AsString;
                m_pGDC->Values[nRow][Column04->Index] = ITSUtil_FormatStr(sDbDate, FDateFormat);          //통계시각

                nVol = pADO->FieldByName("TFVL")->AsInteger;
                nSpd = pADO->FieldByName("AVRG_SPED")->AsInteger;

                m_pGDC->Values[nRow][Column05->Index] = String(nVol);      //교통량
                m_pGDC->Values[nRow][Column06->Index] = String(nSpd);      //평균 속도
#if USE_AVRG_OCPY_RATE
                m_pGDC->Values[nRow][Column07->Index] = FormatFloat("##0.#0", pADO->FieldByName("AVRG_OCPY_RATE")->AsFloat);   //평균 점유율
#endif

				pChart1->Values[nRow] = nVol;
				pChart2->Values[nRow] = nSpd;

				TvChart->Categories->Values[nRow] = m_pGDC->Values[nRow][Column04->Index];
            }
        }
        __finally
        {
            if (pADO)
            {
                pADO->Close();
            }

    		TvChart->EndUpdate();
            TvList->EndUpdate();
            //CxList->SetFocus();
            LblRecords->Caption = FormatFloat("##,##0", m_pGDC->RecordCount) + " 건";

            String sEnd = "데이터 " + LblRecords->Caption + " 이 조회 되었습니다.";
            Application->MessageBox(sEnd.c_str(), L"데이터 조회 완료", MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
    }
    catch(EDatabaseError &E)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(...)
    {
        throw Exception(FrmLang->lblDbErr->Caption);//"알수없는 오류가 발생하였습니다.");
    }
}
//---------------------------------------------------------------------------

void __fastcall TAVIS0201::OnMessage(TMessage &Msg)
{
    switch (Msg.Msg)
    {
    case WM_PARAM_DATABASE:
        if (WP_DB_SELECT_OK == Msg.WParam)
        {
            //ShowMessage("Select Ok");
        }
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TAVIS0201::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle = "VDS-검지기 소통정보통계";

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

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

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

