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

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

#include "IST0030MF.h"
#include "IST00301F.h"
#include "IST00302F.h"
#include "IST00303F.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "FRAME_LinkListF"
#pragma link "FRAME_RoadListF"
#pragma link "cxButtons"
#pragma link "cxCalendar"
#pragma link "cxCheckBox"
#pragma link "cxClasses"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxDropDownEdit"
#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 "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "FRAME_IfscListF"
#pragma link "dxSkinMcSkin"
#pragma resource "*.dfm"

TIST0030M *IST0030M = NULL;
//---------------------------------------------------------------------------
__fastcall TIST0030M::TIST0030M(TComponent* Owner)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    FTitle = Caption;//"소통정보 통계";

    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    ColumnSel->Options->Filtering = false;

    m_pFormList = new TList();
    TsList01->TabVisible = false;

    FRAMELinkList1->PnlTop->Visible = false;
    FRAMELinkList1->PnlBottom->Visible = false;

    FRAMEIfscList1->PnlTop->Visible = false;
    FRAMEIfscList1->PnlBottom->Visible = false;

    FRAMERoadList1->PnlTop->Visible = false;
    FRAMERoadList1->PnlBottom->Visible = false;

    cxPageControl1->ActivePageIndex = 0;
    cxPageControl2->ActivePageIndex = 0;
    PnlQry->Height = 190;
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::CommClose()
{
    try
    {
        for (int idx = m_pFormList->Count-1; idx >= 0; idx--)
        {
            m_pFormList->Delete(idx);
        }
        delete m_pFormList;

        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TIST0030M::FormInit()
{
	CbStatType->ItemIndex = 0;

	TDateTime dtStart = Now()-1;
	TDateTime dtEnd = Now();

    DtStDate->Date = dtStart;
    DtEdDate->Date = dtEnd;

    DtStTime->Date = dtStart;
    DtEdTime->Date = dtEnd;
    //DtStTime->Time = StrToDateTime("00:00");
    //DtEdTime->Time = StrToDateTime("23:59");

    //시간대 검색
	CbStatType1->ItemIndex = 0;
    dtStrDate1->DateTime = Now()-1;
    dtEndDate1->DateTime = Now();//-1;
    CbStrTm1->ItemIndex = 7;
    CbEndTm1->ItemIndex = 7;

    //지정시각 검색
    CbStrTm2->ItemIndex = 7;
    CbEndTm2->ItemIndex = 7;
    InitQryList();
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::InitQryList()
{
    CMM_ClearGridTableView(TvList);

    int nRow = 0;
    try
    {
        TcxDataController *pGDC = TvList->DataController;;
        TvList->BeginUpdate();

        for (int ii = 0; ii < MAX_QRY_LIST; ii++)
        {
            nRow = pGDC->AppendRecord();

            pGDC->Values[nRow][ColumnSel->Index] = false;                 //선택
            pGDC->Values[nRow][Column00->Index]  = "-";                   //편집
            pGDC->Values[nRow][Column01->Index]  = (Now() - (MAX_QRY_LIST-ii)).FormatString("yyyy-MM-dd");
            pGDC->Values[nRow][Column02->Index]  = "07";
            pGDC->Values[nRow][Column03->Index]  = "07";
        }
    }
    __finally
    {
        TvList->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;

    FRAMELinkList1->UpdateList();
    FRAMEIfscList1->UpdateList();
    FRAMERoadList1->UpdateList();
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::RefreshData()
{
    // 검색조건에 의한 링크 데이터 조회
    try
    {
        //SelListData();
	}
	__finally
	{
	}
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::BtnSearchClick(TObject *Sender)
{
    Application->ProcessMessages();
    TSqlCursor sqlCrs((TControl*)BtnSearch);

    TcxGrid          *pCxList = NULL;
    TcxGridTableView *pTvList = NULL;
    int               nIdCol  = -1;

    if (cxPageControl1->Properties->ActivePage->PageIndex == 0)
    {
        pCxList = FRAMELinkList1->CxList;
        pTvList = FRAMELinkList1->TvList;
        nIdCol  = FRAMELinkList1->Column01->Index;
        FLinkLevel = 0;
    }
    else
    if (cxPageControl1->Properties->ActivePage->PageIndex == 1)
    {
        pCxList = FRAMEIfscList1->CxList;
        pTvList = FRAMEIfscList1->TvList;
        nIdCol  = FRAMEIfscList1->Column01->Index;
        FLinkLevel = 1;
    }
    else
    if (cxPageControl1->Properties->ActivePage->PageIndex == 2)
    {
        pCxList = FRAMERoadList1->CxList;
        pTvList = FRAMERoadList1->TvList;
        nIdCol  = FRAMERoadList1->Column01->Index;
        FLinkLevel = 2;
    }
    if (!pTvList) return;

    TcxDataController *pGDC = pTvList->DataController;
	int nIndex = pGDC->FocusedRecordIndex;
	if( nIndex < 0 )
    {
        Application->MessageBox(FrmLang->lblSelErr->Caption.c_str(),//L"링크를 먼저 선택 하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = pCxList;
		return;
    }

    FLinkId = VarToStr(pGDC->Values[nIndex][nIdCol]);

    String sStTime, sEdTime, sTemp;
    switch(CbStatType->ItemIndex)
    {
    case 0: //15분 통계
    case 1: //시간 통계(1시간)
        sStTime = DtStDate->Date.FormatString("yyyyMMdd") + DtStTime->Time.FormatString("hh");
        sEdTime = DtEdDate->Date.FormatString("yyyyMMdd") + DtEdTime->Time.FormatString("hh");
        FStTime = sStTime + "0000";
        FEdTime = sEdTime + "5959";
        break;
    case 2: //일 통계(1일)
        sStTime = DtStDate->Date.FormatString("yyyyMMdd");
        sEdTime = DtEdDate->Date.FormatString("yyyyMMdd");
        FStTime = sStTime + "000000";
        FEdTime = sEdTime + "235959";
        break;
    case 3: //월 통계(1개월)
        sStTime = DtStDate->Date.FormatString("yyyyMM");
        sEdTime = DtEdDate->Date.FormatString("yyyyMM");
        sTemp.printf(L"%02d", ITSUtil_GetMonthLastDay(AnsiString(sEdTime).c_str()));
        FStTime = sStTime + "01000000";
        FEdTime = sEdTime + sTemp + "235959";
        break;
    case 4: //년 통계(1년)
        sStTime = DtStDate->Date.FormatString("yyyy");
        sEdTime = DtEdDate->Date.FormatString("yyyy");
        FStTime = sStTime + "0101000000";
        FEdTime = sEdTime + "1231235959";
        break;
    default:
        return;
    }

    if (sStTime > sEdTime)
    {
        Application->MessageBox(FrmLang->lblQryDtErr->Caption.c_str(),//L"검색 시작시각이 검색 종료시각 보다 큽니다.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = DtStDate;
        return;
    }

    FStatType = CbStatType->ItemIndex;

    String sTitle;
	sTitle.printf(L"%s - %s(%s~%s) %s ", cxPageControl1->Properties->ActivePage->Caption.c_str(),
                                         CbStatType->Text.c_str(),
                                         sStTime.c_str(),
                                         sEdTime.c_str(),
                                         FLinkId.c_str());

    try
    {
        Application->ProcessMessages();
        LockWindowUpdate(Handle);

        TcxTabSheet *pSheet = CMM_AddTabSheet(PgTab, sTitle);
        if (!pSheet) return;



        IST00301 = new TIST00301(this, Handle, FLinkId, sStTime, sEdTime, FLinkLevel, FStatType);
        IST00301->Parent = pSheet;
        IST00301->Show();
        PgTab->ActivePage = pSheet;
        pSheet = PgTab->ActivePage;
        m_pFormList->Add(IST00301);
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::BtnCloseClick(TObject *Sender)
{
    Close();    
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::OnSubFormClose(TMessage Msg)
{
    int nActiveIdx = PgTab->ActivePageIndex;
    if (nActiveIdx <= 0) return;

    LockWindowUpdate(Handle);

    TcxTabSheet *pSheet = PgTab->ActivePage;
    if (pSheet)
    {
        delete pSheet;
    }
    nActiveIdx--;   // 첫번째 탭은 화면에 숨겨져 있다.
    m_pFormList->Delete(nActiveIdx);

    LockWindowUpdate(0);
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::PgTabDblClick(TObject *Sender)
{
    TPoint APoint;
    APoint = PgTab->MouseDownPos;
    if (PgTab->IndexOfTabAt(APoint.x, APoint.y) != -1)
        POST_MSG(Handle, WM_SUBFORM_CLOSE, 0, 0);
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::FormClose(TObject *Sender, TCloseAction &Action)
{
    CommClose();
    IST0030M = NULL;
    Action = caFree;    
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::CbStatTypePropertiesChange(TObject *Sender)
{
    switch(CbStatType->ItemIndex)
    {
    case 0: //15분 통계
    case 1: //시간 통계(1시간)
        DtStDate->Format = "  yyyy년 MM월 dd일";
        DtEdDate->Format = "  yyyy년 MM월 dd일";
        DtStTime->Visible = true;
        DtEdTime->Visible = true;
        break;
    case 2: //일 통계(1일)
        DtStDate->Format = "  yyyy년 MM월 dd일";
        DtEdDate->Format = "  yyyy년 MM월 dd일";
        DtStTime->Visible = false;
        DtEdTime->Visible = false;
        break;
    case 3: //월 통계(1개월)
        DtStDate->Format = "     yyyy년 MM월";
        DtEdDate->Format = "     yyyy년 MM월";
        DtStTime->Visible = false;
        DtEdTime->Visible = false;
        break;
    case 4: //년 통계(1년)
        DtStDate->Format = "         yyyy년";
        DtEdDate->Format = "         yyyy년";
        DtStTime->Visible = false;
        DtEdTime->Visible = false;
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::cxPageControl2PageChanging(TObject *Sender, TcxTabSheet *NewPage,
          bool &AllowChange)
{
    switch(NewPage->PageIndex)
    {
    case 0 :
        PnlQry->Height = 190;
        break;
    case 1 :
        PnlQry->Height = 220;
        break;
    case 2 :
        PnlQry->Height = 300;
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::BtnSearch1Click(TObject *Sender)
{
    Application->ProcessMessages();
    TSqlCursor sqlCrs((TControl*)BtnSearch);

    TcxGrid          *pCxList = NULL;
    TcxGridTableView *pTvList = NULL;
    int               nIdCol  = -1;

    if (cxPageControl1->Properties->ActivePage->PageIndex == 0)
    {
        pCxList = FRAMELinkList1->CxList;
        pTvList = FRAMELinkList1->TvList;
        nIdCol  = FRAMELinkList1->Column01->Index;
        FLinkLevel = 0;
    }
    else
    if (cxPageControl1->Properties->ActivePage->PageIndex == 1)
    {
        pCxList = FRAMEIfscList1->CxList;
        pTvList = FRAMEIfscList1->TvList;
        nIdCol  = FRAMEIfscList1->Column01->Index;
        FLinkLevel = 1;
    }
    else
    if (cxPageControl1->Properties->ActivePage->PageIndex == 2)
    {
        pCxList = FRAMERoadList1->CxList;
        pTvList = FRAMERoadList1->TvList;
        nIdCol  = FRAMERoadList1->Column01->Index;
        FLinkLevel = 2;
    }
    if (!pTvList) return;

    TcxDataController *pGDC = pTvList->DataController;
	int nIndex = pGDC->FocusedRecordIndex;
	if( nIndex < 0 )
    {
        Application->MessageBox(FrmLang->lblSelErr->Caption.c_str(),//L"링크를 먼저 선택 하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = pCxList;
		return;
    }

    FLinkId = VarToStr(pGDC->Values[nIndex][nIdCol]);

    String sStTime, sEdTime, sTemp;
    switch(CbStatType->ItemIndex)
    {
    case 0: //15분 통계
    case 1: //시간 통계(1시간)
        sStTime = dtStrDate1->DateTime.FormatString("yyyyMMdd");
        sEdTime = dtEndDate1->DateTime.FormatString("yyyyMMdd");
        FStTime = sStTime + "000000";
        FEdTime = sEdTime + "235959";
        break;
    default:
        return;
    }

    if (sStTime > sEdTime)
    {
        Application->MessageBox(FrmLang->lblQryDtErr->Caption.c_str(),//L"검색 시작일이 검색 종료일 보다 큽니다.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = dtStrDate1;
        return;
    }

    if (CbStrTm1->ItemIndex > CbEndTm1->ItemIndex)
    {
        Application->MessageBox(FrmLang->lblQryHourErr->Caption.c_str(),//L"시간대 시작시각이 시간대 종료시각 보다 큽니다.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = CbStrTm1;
        return;
    }

    FStTerm.printf(L"%02d0000", CbStrTm1->ItemIndex);
    FEdTerm.printf(L"%02d5959", CbEndTm1->ItemIndex);

    FStatType = CbStatType1->ItemIndex;

    String sTitle;
	sTitle.printf(L"%s - %s(%s~%s) %s ", cxPageControl1->Properties->ActivePage->Caption.c_str(),
                                         CbStatType1->Text.c_str(),
                                         sStTime.c_str(),
                                         sEdTime.c_str(),
                                         FLinkId.c_str());

    try
    {
        Application->ProcessMessages();
        LockWindowUpdate(Handle);

        TcxTabSheet *pSheet = CMM_AddTabSheet(PgTab, sTitle);
        if (!pSheet) return;



        IST00302 = new TIST00302(this, Handle, FLinkId, FStTime, FEdTime, FLinkLevel, FStatType, FStTerm, FEdTerm);
        IST00302->Parent = pSheet;
        IST00302->Show();
        PgTab->ActivePage = pSheet;
        pSheet = PgTab->ActivePage;
        m_pFormList->Add(IST00302);
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::BtnSearch2Click(TObject *Sender)
{
    Application->ProcessMessages();
    TSqlCursor sqlCrs((TControl*)BtnSearch);

    TcxGrid          *pCxList = NULL;
    TcxGridTableView *pTvList = NULL;
    int               nIdCol  = -1;

    if (cxPageControl1->Properties->ActivePage->PageIndex == 0)
    {
        pCxList = FRAMELinkList1->CxList;
        pTvList = FRAMELinkList1->TvList;
        nIdCol  = FRAMELinkList1->Column01->Index;
        FLinkLevel = 0;
    }
    else
    if (cxPageControl1->Properties->ActivePage->PageIndex == 1)
    {
        pCxList = FRAMEIfscList1->CxList;
        pTvList = FRAMEIfscList1->TvList;
        nIdCol  = FRAMEIfscList1->Column01->Index;
        FLinkLevel = 1;
    }
    else
    if (cxPageControl1->Properties->ActivePage->PageIndex == 2)
    {
        pCxList = FRAMERoadList1->CxList;
        pTvList = FRAMERoadList1->TvList;
        nIdCol  = FRAMERoadList1->Column01->Index;
        FLinkLevel = 2;
    }
    if (!pTvList) return;

    TcxDataController *pGDC = pTvList->DataController;
	int nIndex = pGDC->FocusedRecordIndex;
	if( nIndex < 0 )
    {
        Application->MessageBox(FrmLang->lblSelErr->Caption.c_str(),//L"링크를 먼저 선택 하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = pCxList;
		return;
    }

    FLinkId = VarToStr(pGDC->Values[nIndex][nIdCol]);

    int nSelects = CMM_GetCheckCount(TvList, ColumnSel->Index);
    if (0 == nSelects)
    {
        Application->MessageBox(FrmLang->lblSelNoDate->Caption.c_str(),//L"검색 지정일을 선택하지 않았습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = CxList;
        return;
    }

    bool bDateCheck = true;
    int nRowCnt = TvList->ViewData->RecordCount;
    for (int ii = 0; ii < nRowCnt; ii++)
    {
        TcxCustomGridRow* ARow = TvList->ViewData->Rows[ii];
        if (((bool)ARow->Values[ColumnSel->Index]))
        {
            try
            {
                if (VarIsNull(ARow->Values[Column01->Index]))
                {
                    bDateCheck = false;
                    break;
                }
                String sSelDay = ARow->Values[Column01->Index];
                sSelDay = StringReplace(sSelDay, DateSeparator, "", TReplaceFlags() << rfReplaceAll);
                if (sSelDay.Length() != 8)
                {
                    bDateCheck = false;
                    break;
                }
            }
            catch(Exception &e)
            {
            }
        }
    }
    if (!bDateCheck)
    {
        Application->MessageBox(FrmLang->lblSelDtErr->Caption.c_str(),//L"검색 지정일의 일자가 올바르지 않았습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = CxList;
        return;
    }

    if (CbStrTm2->ItemIndex > CbEndTm2->ItemIndex)
    {
        Application->MessageBox(FrmLang->lblSelHourOver->Caption.c_str(),//L"시간대 시작시각이 시간대 종료시각 보다 큽니다.",
                                FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        ActiveControl = CbStrTm1;
        return;
    }

    FStTerm.printf(L"%02d0000", CbStrTm2->ItemIndex);
    FEdTerm.printf(L"%02d5959", CbEndTm2->ItemIndex);

    FStatType = CbStatType2->ItemIndex;

    String sTitle;
	sTitle.printf(L"%s - %s %s ", cxPageControl1->Properties->ActivePage->Caption.c_str(),
                                  CbStatType2->Text.c_str(),
                                  FLinkId.c_str());

    try
    {
        Application->ProcessMessages();
        LockWindowUpdate(Handle);

        TcxTabSheet *pSheet = CMM_AddTabSheet(PgTab, sTitle);
        if (!pSheet) return;



        IST00303 = new TIST00303(this, Handle, FLinkId, FStTime, FEdTime, FLinkLevel, FStatType, FStTerm, FEdTerm);

        IST00303->FSelDayCnt = 0;
        int nRowCnt = TvList->ViewData->RecordCount;
        for (int ii = 0; ii < nRowCnt; ii++)
        {
            TcxCustomGridRow* ARow = TvList->ViewData->Rows[ii];
            if (((bool)ARow->Values[ColumnSel->Index]))
            {
                try
                {
                    TDateTime dt = VarToDateTime(ARow->Values[Column01->Index]);
                    String sSelDay = dt.FormatString("yyyyMMdd");
                    IST00303->FSelDay[IST00303->FSelDayCnt++] = sSelDay;
                }
                catch(Exception &e)
                {
                }
            }
        }

        IST00303->Parent = pSheet;
        IST00303->Show();
        PgTab->ActivePage = pSheet;
        pSheet = PgTab->ActivePage;
        m_pFormList->Add(IST00302);
    }
    __finally
    {
        LockWindowUpdate(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TIST0030M::PgTabCanCloseEx(TObject *Sender, int ATabIndex, bool &ACanClose)
{
    int nActiveIdx = ATabIndex;
    if (nActiveIdx <= 0) return;

    nActiveIdx--;   // 첫번째 탭은 화면에 숨겨져 있다.
    m_pFormList->Delete(nActiveIdx);
}
//---------------------------------------------------------------------------

