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

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

#include "TAS00801F.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 "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxmdaset"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma resource "*.dfm"

TTAS00801 *TAS00801 = NULL;

//---------------------------------------------------------------------------
__fastcall TTAS00801::TTAS00801(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;

    FColumn[ 0] = Column03;
    FColumn[ 1] = Column04;
    FColumn[ 2] = Column05;
    FColumn[ 3] = Column06;
    FColumn[ 4] = Column07;
    FColumn[ 5] = Column08;
    FColumn[ 6] = Column09;
    FColumn[ 7] = Column10;
    FColumn[ 8] = Column11;
    FColumn[ 9] = Column12;
    FColumn[10] = Column13;
    FColumn[11] = Column14;
    FColumn[12] = Column15;
    FColumn[13] = Column16;
    FColumn[14] = Column17;

    int ii = 0;
    for (ii = 0; ii < MAX_COLSYS; ii++)
    {
        FChart[ii] = NULL;
    }

    ii = 0;
    FOR_STL(TItsColSys*, pObj, ItsColSysManager->FLists)
    {
        if (pObj->USE_YN == "N") continue;
        FColumn[ii]->Caption = pObj->CLCT_SYST_NM;
        FColumn[ii]->Visible = true;
        ii++;
        if (ii >= MAX_COLSYS) break;
    }

    FStatManager = new TStat0080Manager();
    FChartManager = new TStat0080ChartManager();
    MyManager = AManager;
}
//---------------------------------------------------------------------------
__fastcall TTAS00801::~TTAS00801(void)
{
}
//--------------------------------------------------------------------------

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

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

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

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

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

void __fastcall TTAS00801::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 TTAS00801::ChkExpandClick(TObject *Sender)
{
    CMM_ExpandCollapseChk(TvList, ChkExpand->Checked);
}
//---------------------------------------------------------------------------

String __fastcall TTAS00801::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 TTAS00801::SelHistory1()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery *pADO = ADOQry;

    int ii = 0;
    String sTemp;

#if 0
    String sFetch = "";
    ii = 0;
    FOR_STL(TItsColSys*, pObj, ItsColSysManager->FLists)
    {
        if (pObj->USE_YN == "N") continue;

        sTemp = ", MAX(DECODE(A.CLCT_SYST_CD, '" + pObj->CLCT_SYST_CD + "', A.SPED, 0)) " + pObj->CLCT_SYST_CD + " \r\n";
        sFetch += sTemp;

        ii++;
        if (ii >= MAX_COLSYS) break;
    }
#endif

    String sWhere = "";
    if (FAtrdNm.IsEmpty())
    {
        sWhere = "";
    }
    else
    {
        sWhere = " AND A.LINK_ID IN (" + FAtrdNm + ")";
    }

    String sTmp;

    sTmp = "SELECT A.*, SUBSTR(A.PRCN_DT, 9, 4) AS PRCN_DT2                \r\n";
    sTmp+= "  FROM TB_LINK_TRAF_CLCT_HS A                                  \r\n"
           " WHERE A.PRCN_DT BETWEEN :p01                                  \r\n"
           "                     AND :p02                                  \r\n"
           + sWhere;

    sQry = "SELECT A.ROAD_NAME, B.NODE_NAME AS F_NAME, C.NODE_NAME AS T_NAME,   \r\n";
    sQry+= "       D.*                                                          \r\n";
    sQry+= "  FROM TB_LINK A, TB_NODE B, TB_NODE C,                             \r\n";
    sQry+= "       (                                                            \r\n";
    sQry+= sTmp;
    sQry+= "       ) D                                                          \r\n";
    sQry+= " WHERE A.LINK_ID   = D.LINK_ID                                      \r\n";
    sQry+= "   AND A.F_NODE_ID = B.NODE_ID                                      \r\n";
    sQry+= "   AND A.T_NODE_ID = C.NODE_ID                                      \r\n";
    sQry+= " ORDER BY A.LINK_ID, PRCN_DT                                        \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 TTAS00801::DspHistory()
{
    m_pGDC = TvList->DataController;

    try
    {
        int nRow = 0;
        int nDataCnt = 0;
        int ii = 0;
        try
        {
            int nValue = 0;
            while(!dxMemData1->Eof)
            {
                nRow = m_pGDC->AppendRecord();

                String LINK_ID = dxMemData1->Fields->FieldByName("LINK_ID")->AsString;
                String STAT_HM = dxMemData1->Fields->FieldByName("PRCN_DT2")->AsString;
                String sDbDate = dxMemData1->Fields->FieldByName("PRCN_DT")->AsString;

                m_pGDC->Values[nRow][Column01->Index] = ITSUtil_FormatStr(sDbDate, STR_DATETIME);
                m_pGDC->Values[nRow][Column02->Index] = LINK_ID;
                m_pGDC->Values[nRow][ColRoad->Index]  = dxMemData1->Fields->FieldByName("ROAD_NAME")->AsString;
                m_pGDC->Values[nRow][ColFName->Index] = dxMemData1->Fields->FieldByName("F_NAME")->AsString;
                m_pGDC->Values[nRow][ColTName->Index] = dxMemData1->Fields->FieldByName("T_NAME")->AsString;

                TStat0080 *pStat = FStatManager->FLists.Find(LINK_ID);
                if (!pStat)
                {
                    pStat = new TStat0080();
                    pStat->LINK_ID = LINK_ID;
                    FStatManager->FLists.Push(pStat->LINK_ID, pStat);
                }
                TTraf0080 *pTraf = pStat->FLists.Find(STAT_HM);
                if (!pTraf)
                {
                    pTraf = new TTraf0080();
                    pTraf->STAT_HM = STAT_HM;
                    pStat->FLists.Push(pTraf->STAT_HM, pTraf);
                }

                ii = 0;
                FOR_STL(TItsColSys*, pObj, ItsColSysManager->FLists)
                {
                    nValue = dxMemData1->Fields->FieldByName(pObj->CLCT_SYST_CD)->AsInteger;
                    m_pGDC->Values[nRow][FColumn[ii]->Index] = nValue;

                    TTrafSped *pSped = new TTrafSped();
                    pSped->CLCT_SYST_CD = pObj->CLCT_SYST_CD;
                    pSped->SPED = nValue;
                    pTraf->FLists.Push(pSped->CLCT_SYST_CD, pSped);
                    ii++;
                    if (ii >= MAX_COLSYS) break;
                }
                dxMemData1->Next();
            }
        }
        __finally
        {
            dxMemData1->Close();

            //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 TTAS00801::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(), "시간", "속도");

    TStat0080 *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(TItsColSys*, pObj, ItsColSysManager->FLists)
        {
            if (pObj->USE_YN == "N") continue;

            clSrsColor = GetDefaultColor(kk++);
            if (clSrsColor == clWhite) clSrsColor = GetDefaultColor(++kk);
            if (clSrsColor == clYellow) clSrsColor = GetDefaultColor(++kk);

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

            FOR_STL(TTraf0080*, pTraf, pStat->FLists)
            {
                TTrafSped *pSped = pTraf->FLists.Find(pObj->CLCT_SYST_CD);
                if (!pSped) continue;

                //if (pSped->SPED > 0)
                {
                    pSeries->AddY(pSped->SPED, pTraf->STAT_HM);
                }
            }
        }


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

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

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

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

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

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

