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

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

#include "TAS00901F.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 "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "cxCalc"
#pragma link "cxTextEdit"
#pragma link "dxmdaset"
#pragma link "dxSkinMcSkin"
#pragma resource "*.dfm"

TTAS00901 *TAS00901 = NULL;

//---------------------------------------------------------------------------
__fastcall TTAS00901::TTAS00901(TComponent* Owner, HWND hHandle,
                                String AStDay, String AEdDay, String AStHour, String AEdHour, String AWeek, String ADir, String AAtrdNm, int ATable, int AQryType, TVdsCtlrManager* AManager)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FParent = hHandle;

    FStDay = AStDay;
    FEdDay = AEdDay;
    FStHour = AStHour;
    FEdHour = AEdHour;
    FWeek = AWeek;
    FDir = ADir;
    FAtrdNm = AAtrdNm;
    FTable = ATable;
    FQryType = AQryType;

    FHourSt = FStHour.ToIntDef(0);
    FHourEd = FEdHour.ToIntDef(0);

    FStatManager = new TStat0090Manager();
    FChartManager = new TStat0090ChartManager();
    MyManager = AManager;
}
//---------------------------------------------------------------------------
__fastcall TTAS00901::~TTAS00901(void)
{
}
//--------------------------------------------------------------------------

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

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<노선별속도분석 정보>";

    LblSearch->Caption = FrmLang->lblQryCond->Caption + FStDay + " ~ " + FEdDay;
}
//---------------------------------------------------------------------------

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

void __fastcall TTAS00901::CommClose()
{
    try
    {
        delete FStatManager;
        FStatManager = NULL;
        delete FChartManager;
        FChartManager = NULL;
    }
    catch(Exception &e)
    {
    }
    CMM_SaveForm(g_sFormsDir, this);
    //TAS00901 = NULL;
}
//---------------------------------------------------------------------------

void __fastcall TTAS00901::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    ChkExpand->Visible = false;
    Application->ProcessMessages();
    CMM_ClearGridTableView(TvList);
    try
    {
        m_pFrmChart->LblOptionName->Caption = "표출구간";
        m_pFrmChart->CbOption->Width = 280;
        m_pFrmChart->CbOption->Properties->OnChange = NULL;
        m_pFrmChart->CbOption->Properties->Items->Clear();
        FOR_STL(TVdsLink*, pObj, MyManager->FLinkLists)
        {
            if (pObj->IsSelected)
            {
                m_pFrmChart->CbOption->Properties->Items->Add("[" + pObj->LINK_ID + "] " + pObj->STR_NAME + " → " + pObj->END_NAME);
            }
        }
        //m_pFrmChart->CbOption->Properties->Items->Add("시간");
        //m_pFrmChart->CbOption->Properties->Items->Add("일자");
        m_pFrmChart->CbOption->ItemIndex = 0;
        m_pFrmChart->PnlOption->Visible = true;

        TvList->BeginUpdate(lsimImmediate);
        SelHistory1();
    }
    __finally
    {
        TvList->EndUpdate();
        ChkExpand->Visible = true;
    }
}
//---------------------------------------------------------------------------

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

String __fastcall TTAS00901::GetDayWeekCode(String ADay)
{
    TDateTime dt;

    System::Word Year  = (System::Word)ADay.SubString( 1, 4).ToIntDef(2018);
    System::Word Month = (System::Word)ADay.SubString( 5, 2).ToIntDef(1);
    System::Word Day   = (System::Word)ADay.SubString( 7, 2).ToIntDef(1);
    dt = EncodeDate(Year, Month, Day);

    System::Word week = DayOfWeek(dt);
    //const days: array[1..7] of string = ('일','월','화','수','목','금','토');
    String sWeek[8] = { "", "DTW7", "DTW1", "DTW2", "DTW3", "DTW4", "DTW5", "DTW6" };

    return sWeek[week];
}
//---------------------------------------------------------------------------

void __fastcall TTAS00901::SelHistory1()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery *pADO = ADOQry;

    int ii = 0;
    String sTemp;


    String sWhere = "";
    if (FAtrdNm.IsEmpty())
    {
        sWhere = "";
    }
    else
    {
        sWhere = "         WHERE LINK_ID IN (" + FAtrdNm + ")  \r\n";
    }

    String sTmp;

    sQry = "SELECT /*+ INDEX(A PK_VDS_DTCT_HH) */                                                       \r\n"
           "       B.LINK_ID, SUBSTR(A.STAT_DT, 1, 8) AS STAT_DD, SUBSTR(A.STAT_DT, 9, 2) AS STAT_HH,   \r\n"
           "       SUM(A.TFVL) AS TFVL                                                                  \r\n"
           "  FROM TB_VDS_DTCT_HH_STAT A,                                                               \r\n"
           "       (SELECT LINK_ID, VDS_DTCT_NMBR                                                       \r\n"
           "          FROM TB_VDS_DTCT_RLTN_LINK                                                        \r\n"
           +  sWhere +
           "       ) B                                                                                  \r\n"
           " WHERE A.STAT_DT BETWEEN :p01 AND :p02                                                      \r\n"
           "   AND A.VDS_DTCT_NMBR = B.VDS_DTCT_NMBR                                                    \r\n"
           " GROUP BY B.LINK_ID, SUBSTR(A.STAT_DT, 1, 8), SUBSTR(A.STAT_DT, 9, 2)                       \r\n";

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FStDay);
        ITSDb_SQLBind(pADO, "p02", FEdDay);
        ITSDb_SQLOpen(pADO);

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

        DspHistory();
        m_pFrmChart->CbOption->Properties->OnChange = CbOptionPropertiesChange;
        DrawChart("");
    }
    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 TTAS00901::DspHistory()
{
    m_pGDC = TvList->DataController;

    try
    {
        try
        {
            while(!dxMemData1->Eof)
            {
                String LINK_ID = dxMemData1->Fields->FieldByName("LINK_ID")->AsString;
                String STAT_DD = dxMemData1->Fields->FieldByName("STAT_DD")->AsString;
                int    STAT_HH = dxMemData1->Fields->FieldByName("STAT_HH")->AsInteger;

                TStat0090 *pStat = FStatManager->FLists.Find(LINK_ID);
                if (!pStat)
                {
                    pStat = new TStat0090();
                    pStat->LINK_ID = LINK_ID;
                    FStatManager->FLists.Push(pStat->LINK_ID, pStat);
                }
                TTraf0090 *pTraf = pStat->FLists.Find(STAT_DD);
                if (!pTraf)
                {
                    pTraf = new TTraf0090();
                    pTraf->STAT_DD = STAT_DD;
                    pStat->FLists.Push(pTraf->STAT_DD, pTraf);
                }
                pTraf->TFVL[STAT_HH] = dxMemData1->Fields->FieldByName("TFVL")->AsInteger;

                dxMemData1->Next();
            }
        }
        __finally
        {
            dxMemData1->Close();
        }
    }
    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);
    }

    try
    {
        FOR_STL(TStat0090*, pStat, FStatManager->FLists)
        {
            FOR_STL(TTraf0090*, pTraf, pStat->FLists)
            {
                for (int ii = FHourSt; ii <= FHourEd; ii++)
                {
                    pTraf->SUM_TFVL += pTraf->TFVL[ii];
                }
            }
        }
        int nRow = 0;
        int nDataCnt = 0;
        int ii = 0;
        try
        {
            int nIdxSped = 0;
            FOR_STL(TStat0090*, pStat, FStatManager->FLists)
            {
                TVdsLink *pObj = MyManager->FLinkLists.Find(pStat->LINK_ID);
                if (!pObj) continue;

                FOR_STL(TTraf0090*, pTraf, pStat->FLists)
                {
                    nRow = m_pGDC->AppendRecord();

                    m_pGDC->Values[nRow][Col01->Index] = pStat->LINK_ID;
                    m_pGDC->Values[nRow][Col02->Index] = pObj->STR_NAME;
                    m_pGDC->Values[nRow][Col03->Index] = pObj->END_NAME;
                    m_pGDC->Values[nRow][Col04->Index] = APP_FormatStr(pTraf->STAT_DD, STR_DATE);

                    nIdxSped = ColSped->Index;
                    m_pGDC->Values[nRow][ColSum->Index] = pTraf->SUM_TFVL;
                    for (ii = FHourSt; ii <= FHourEd; ii++)
                    {
                        m_pGDC->Values[nRow][nIdxSped+ii] = pTraf->TFVL[ii];
                    }
                }
            }
        }
        __finally
        {
            //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(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 TTAS00901::DrawChart(String ATitle)
{
    m_pFrmChart->Clear();

    int             ii, jj, kk;
    SeriesType      SrsType;
    TColor          clSrsColor;
    TChartSeries    *pSeries;

    TCursor cOldCursor= Screen->Cursor;
    Screen->Cursor = crHourGlass;

    String LINK_ID = APP_GetCode(m_pFrmChart->CbOption);
    m_pFrmChart->SetChartInfo(m_pFrmChart->CbOption->Text.Trim(), "시간", "교통량");

    TStat0090 *pStat = FStatManager->FLists.Find(LINK_ID);
    if (!pStat)
    {
        return;
    }

    SrsType = (SeriesType)m_pFrmChart->CbChartKind->ItemIndex;
    m_pFrmChart->BeginDraw("", "", "");
    m_pFrmChart->LstLegend->Items->BeginUpdate();

    ii = jj = kk = 0;

    try
    {
        FOR_STL(TTraf0090*, pTraf, pStat->FLists)
        {
            clSrsColor = GetDefaultColor(kk++);
            if (clSrsColor == clWhite) clSrsColor = GetDefaultColor(++kk);
            if (clSrsColor == clYellow) clSrsColor = GetDefaultColor(++kk);

            pSeries = m_pFrmChart->AddSeriesItem(pTraf->STAT_DD, SrsType, clSrsColor, true);
            if (!pSeries) continue;

            for (ii = FHourSt; ii <= FHourEd; ii++)
            {
                String sAxisX;
                sAxisX.printf(L"%02d시", ii);
                //if (pTraf->TFVL[ii] > 0)
                {
                    pSeries->AddY(pTraf->TFVL[ii], sAxisX);
                }
            }
        }

        m_pFrmChart->DbChart->LeftAxis->Minimum = 0;
        m_pFrmChart->DbChart->LeftAxis->Maximum = m_pFrmChart->GetActiveMaxY() + 10;
        if (m_pFrmChart->DbChart->LeftAxis->Minimum >= m_pFrmChart->DbChart->LeftAxis->Maximum)
        {
            m_pFrmChart->DbChart->LeftAxis->Maximum = m_pFrmChart->DbChart->LeftAxis->Minimum + 1;
        }
    }
    __finally
    {
        m_pFrmChart->DbChart->Refresh();
        m_pFrmChart->LstLegend->Items->EndUpdate();
        m_pFrmChart->EndDraw();
        Screen->Cursor = cOldCursor;
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TTAS00901::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"노선별속도분석";

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

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

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

void __fastcall TTAS00901::FormCreate(TObject *Sender)
{
    m_pFrmChart = new TPlugInChart(this);
    m_pFrmChart->Parent = PnlChart;
    m_pFrmChart->SetChartInfo("", "시간", "속도");
    m_pFrmChart->Show();
}
//---------------------------------------------------------------------------
void __fastcall TTAS00901::CbOptionPropertiesChange(TObject *Sender)
{
    TcxComboBox *pCombo = (TcxComboBox*)Sender;
    DrawChart("");
    m_pFrmChart->SetFocus();
}
//---------------------------------------------------------------------------

