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

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

#include "IAN00701F.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#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 "dxSkinCaramel"
#pragma link "dxSkinCoffee"
#pragma link "dxSkinDarkRoom"
#pragma link "dxSkinDarkSide"
#pragma link "dxSkinFoggy"
#pragma link "dxSkinGlassOceans"
#pragma link "dxSkiniMaginary"
#pragma link "dxSkinLilian"
#pragma link "dxSkinLiquidSky"
#pragma link "dxSkinLondonLiquidSky"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinMoneyTwins"
#pragma link "dxSkinOffice2007Black"
#pragma link "dxSkinOffice2007Blue"
#pragma link "dxSkinOffice2007Green"
#pragma link "dxSkinOffice2007Pink"
#pragma link "dxSkinOffice2007Silver"
#pragma link "dxSkinOffice2010Black"
#pragma link "dxSkinOffice2010Blue"
#pragma link "dxSkinOffice2010Silver"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "FRAME_ChartF"
#pragma resource "*.dfm"

TIAN00701 *IAN00701 = NULL;

//---------------------------------------------------------------------------
__fastcall TIAN00701::TIAN00701(TComponent* Owner, HWND hHandle, String sFrom, String sTo, String sIdList)
    : TForm(Owner)
{           
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

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

    Caption = "반복정체구간 분석(기상)";
}
//---------------------------------------------------------------------------
__fastcall TIAN00701::~TIAN00701(void)
{
}
//--------------------------------------------------------------------------

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

    TvList->OptionsView->NoDataToDisplayInfoText = "<반복정체구간(기상) 분석 정보>";

    FRAMEChart1->FTitle = "반복정체구간(기상) 분석";
    FRAMEChart1->SetChartLegend("수집시각", "개수");
    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 = "검색조건: " + FStDateTime.SubString(1, 12) + " ~ " + FEdDateTime.SubString(1, 12);
}
//---------------------------------------------------------------------------

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

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

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

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

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

    String sQry;
    TADOQuery *pADO = ADOQry;

    int nLevel = StrToInt(FIdList);
    switch(nLevel)
    {
      case 1:
      sQry = "SELECT PRCN_DT, TO_DATE(PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2,            \r\n"
             "       (SELECT COUNT(1) CNT FROM TB_LINK WHERE DEL_YN = 'N') Total,          \r\n"
             "       (LINK_LIGT_NUM + LINK_DELY_NUM + LINK_CNGS_NUM) GenerateCount,        \r\n"
             "       LINK_LIGT_NUM G1,                                                     \r\n"
             "       LINK_DELY_NUM G2,                                                     \r\n"
             "       LINK_CNGS_NUM G3,                                                     \r\n"
             "       (SELECT COUNT(1) CNT FROM TB_LINK  WHERE DEL_YN = 'N')                \r\n"
             "       - LINK_LIGT_NUM - LINK_DELY_NUM - LINK_CNGS_NUM NoneDataCount         \r\n"
             "  FROM TB_TRFC_PRCN_STAT                                                     \r\n"
             " WHERE PRCN_DT BETWEEN :p01 AND :p02                                         \r\n"
             " ORDER BY PRCN_DT                                                            \r\n";
        break;
      case 2:
      sQry = "SELECT PRCN_DT PRCN_DT, TO_DATE(PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2,    \r\n"
             "       (SELECT COUNT(1) CNT FROM TB_IFSC  WHERE DEL_YN = 'N') Total,         \r\n"
             "       (IFSC_LIGT_NUM + IFSC_DELY_NUM + IFSC_CNGS_NUM) GenerateCount,        \r\n"
             "       IFSC_LIGT_NUM G1,                                                     \r\n"
             "       IFSC_DELY_NUM G2,                                                     \r\n"
             "       IFSC_CNGS_NUM G3,                                                     \r\n"
             "       (SELECT COUNT(1) CNT FROM TB_IFSC WHERE DEL_YN = 'N')                 \r\n"
             "       - IFSC_LIGT_NUM - IFSC_DELY_NUM - IFSC_CNGS_NUM NoneDataCount         \r\n"
             "  FROM TB_TRFC_PRCN_STAT                                                     \r\n"
             " WHERE PRCN_DT BETWEEN :p01 AND :p02                                         \r\n"
             " ORDER BY PRCN_DT                                                            \r\n";
        break;
      case 3:
      sQry = "SELECT PRCN_DT, TO_DATE(PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2,            \r\n"
             "       (SELECT COUNT(1) CNT FROM TB_ROAD WHERE DEL_YN = 'N') Total,          \r\n"
             "       (ROAD_LIGT_NUM + ROAD_DELY_NUM + ROAD_CNGS_NUM) GenerateCount,        \r\n"
             "       ROAD_LIGT_NUM G1,                                                     \r\n"
             "       ROAD_DELY_NUM G2,                                                     \r\n"
             "       ROAD_CNGS_NUM G3,                                                     \r\n"
             "       (SELECT COUNT(1) CNT FROM TB_ROAD WHERE DEL_YN = 'N')                 \r\n"
             "       - ROAD_LIGT_NUM - ROAD_DELY_NUM - ROAD_CNGS_NUM NoneDataCount         \r\n"
             "  FROM TB_TRFC_PRCN_STAT                                                     \r\n"
             " WHERE PRCN_DT BETWEEN :p01 AND :p02                                         \r\n"
             " ORDER BY PRCN_DT                                                            \r\n";
        break;
      case 4:
      sQry = "SELECT PRCN_DT, TO_DATE(PRCN_DT, 'YYYYMMDDHH24MISS') AS PRCN_DT2,                 \r\n"
             "       (SELECT COUNT(1) CNT FROM TB_VMS_IFSC) Total,                              \r\n"
             "       (VMS_IFSC_LIGT_NUM + VMS_IFSC_DELY_NUM + VMS_IFSC_CNGS_NUM) GenerateCount, \r\n"
             "       VMS_IFSC_LIGT_NUM G1,                                                      \r\n"
             "       VMS_IFSC_DELY_NUM G2,                                                      \r\n"
             "       VMS_IFSC_CNGS_NUM G3,                                                      \r\n"
             "       (SELECT COUNT(1) CNT FROM TB_VMS_IFSC) - VMS_IFSC_LIGT_NUM                 \r\n"
             "       - VMS_IFSC_DELY_NUM - VMS_IFSC_CNGS_NUM NoneDataCount                      \r\n"
             "  FROM TB_TRFC_PRCN_STAT                                                          \r\n"
             " WHERE PRCN_DT BETWEEN :p01 AND :p02                                              \r\n"
             " ORDER BY PRCN_DT                                                                 \r\n";
        break;
    default: return;
    }

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

    try
    {
    	TcxGridChartSeries *pChart1 = NULL;
    	TcxGridChartSeries *pChart2 = NULL;
    	TcxGridChartSeries *pChart3 = NULL;
    	TcxGridChartSeries *pChart4 = 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 = "정보없음";

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

                m_pGDC->Values[nRow][Column02->Index] = pADO->FieldByName("Total")->AsInteger;
                m_pGDC->Values[nRow][Column03->Index] = pADO->FieldByName("GenerateCount")->AsInteger;
                m_pGDC->Values[nRow][Column04->Index] = pADO->FieldByName("G1")->AsInteger;
                m_pGDC->Values[nRow][Column05->Index] = pADO->FieldByName("G2")->AsInteger;
                m_pGDC->Values[nRow][Column06->Index] = pADO->FieldByName("G3")->AsInteger;
                m_pGDC->Values[nRow][Column07->Index] = pADO->FieldByName("NoneDataCount")->AsInteger;

				pChart1->Values[nRow] = m_pGDC->Values[nRow][Column04->Index];
				pChart2->Values[nRow] = m_pGDC->Values[nRow][Column05->Index];
				pChart3->Values[nRow] = m_pGDC->Values[nRow][Column06->Index];
				pChart4->Values[nRow] = m_pGDC->Values[nRow][Column07->Index];

				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) + " 건";

            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("알수없는 오류가 발생하였습니다.");
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TIAN00701::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle = "반복정체구간 분석(기상)";

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

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

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

