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

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

#include "TAS00501F.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 resource "*.dfm"

TTAS00501 *TAS00501 = NULL;

//---------------------------------------------------------------------------
__fastcall TTAS00501::TTAS00501(TComponent* Owner, HWND hHandle,
                                String AAtrdId, String AAtrdNm, String AAtrdId1, String AAtrdNm1, String AQryDay)
    : TForm(Owner)
{           
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FParent  = hHandle;

    FAtrdId  = AAtrdId;    //IFSC_ID
    FAtrdNm  = AAtrdNm;    //IFSC_NM
    FAtrdId1 = AAtrdId1;   //IFSC_ID
    FAtrdNm1 = AAtrdNm1;   //IFSC_NM
	FQryDay  = AQryDay;    //특수일

    FTrfManager = new TDetourTrfManager();

    SetQueryDay(FQryDay);
}
//---------------------------------------------------------------------------
__fastcall TTAS00501::~TTAS00501(void)
{
}
//--------------------------------------------------------------------------

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

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<우회도로분석 정보>";

    LblSearch->Caption = FrmLang->lblQryCond->Caption + FAtrdId + "/" + FAtrdId1 + " [" + FQryDay + "]";
}
//---------------------------------------------------------------------------

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

void __fastcall TTAS00501::CommClose()
{
    try
    {
        delete FTrfManager;
        FTrfManager = NULL;
    }
    catch(Exception &e)
    {
    }
    CMM_SaveForm(g_sFormsDir, this);
    //TAS00501 = NULL;
}
//---------------------------------------------------------------------------

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

    Application->ProcessMessages();

    SelHistory1();
    SelHistory2();

    DspHistory();
}
//---------------------------------------------------------------------------

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

String __fastcall TTAS00501::GetDayWeek(TDateTime ADay)
{
    System::Word week = DayOfWeek(ADay);
    //const days: array[1..7] of string = ('일','월','화','수','목','금','토');
    String sWeek[8] = { "", "일", "월", "화", "수", "목", "금", "토" };

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


void __fastcall TTAS00501::SetQueryDay(String ADay)
{
    TDateTime dt, dtTemp;

    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);

    int nInc = -3;
    for (int ii = 0; ii < MAX_QRY_TERM; ii++)
    {
        FQryDayList[ii] = IncDay(dt, nInc++);

        TDetourTrf *pTrf = new TDetourTrf();
        pTrf->dtQry = FQryDayList[ii];
        pTrf->sQryDay = FQryDayList[ii].FormatString("YYYYMMDD");
        pTrf->IFSC_ID = FAtrdId;
        FTrfManager->FLists.Push(pTrf->sQryDay, pTrf);

        TvList->Bands->Items[ii+1]->Caption = FQryDayList[ii].FormatString("YYYY-MM-DD") + GetDayWeek(FQryDayList[ii]);
    }
}
//---------------------------------------------------------------------------

void __fastcall TTAS00501::SelHistory1()
{
#if 0
#endif
}
//---------------------------------------------------------------------------

void __fastcall TTAS00501::SelHistory2()
{
    TSqlCursor sqlCrs;

    String sQry;
    TADOQuery *pADO = ADOQry;

    sQry =
    "SELECT A.IFSC_ID, A.STAT_DT,                                                   \r\n"
    "       SUBSTR(A.STAT_DT, 1,8) AS STAT_DD, SUBSTR(A.STAT_DT, 9,2) AS STAT_HH,   \r\n"
    "       A.SPED, A.TRVL_HH,                                                      \r\n"
    "       NVL(B.CMTR_GRAD_CD, 'LTC0') AS GRAD                                     \r\n"
    "  FROM TB_IFSC_HH_STAT   A,                                                    \r\n"
    "       TB_SECT_GRAD_STUP B,                                                    \r\n"
    "       TB_IFSC           C                                                     \r\n"
    " WHERE A.STAT_DT BETWEEN :p01 AND :p02                                         \r\n"
    "   AND A.IFSC_ID      IN (:p03, :p04)                                          \r\n"
    "   AND A.IFSC_ID      = C.IFSC_ID                                              \r\n"
    "   AND B.SECT_GRAD_CD = C.SECT_GRAD_CD                                         \r\n"
    "   AND (A.SPED >= B.LWST_TRVL_SPED AND A.SPED <= B.HGHS_TRVL_SPED)             \r\n";

    try
    {
        ITSDb_SQLText(pADO, sQry);
        ITSDb_SQLBind(pADO, "p01", FQryDayList[             0].FormatString("YYYYMMDD") + "000000");
        ITSDb_SQLBind(pADO, "p02", FQryDayList[MAX_QRY_TERM-1].FormatString("YYYYMMDD") + "235959");
        ITSDb_SQLBind(pADO, "p03", FAtrdId);    //IFSC_ID
        ITSDb_SQLBind(pADO, "p04", FAtrdId1);   //IFSC_ID

        ITSDb_SQLOpen(pADO);

        int nIdx, nIfsc;
        TDetourTrf *pTrf;

        for( ; !pADO->Eof; pADO->Next())
        {
            pTrf = FTrfManager->FLists.Find(pADO->FieldByName("STAT_DD")->AsString);
            if (pTrf == NULL) continue;

            nIdx = pADO->FieldByName("STAT_HH")->AsInteger;

            if (pADO->FieldByName("IFSC_ID")->AsString == FAtrdId)
                nIfsc = 0;
            else
                nIfsc = 1;

            pTrf->INFO[nIfsc][nIdx].SPED = pADO->FieldByName("SPED")->AsString.ToIntDef(0);
            pTrf->INFO[nIfsc][nIdx].GRAD = pADO->FieldByName("GRAD")->AsString;
        }

        pADO->Close();
    }
    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 &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);
    }
}
//---------------------------------------------------------------------------

void __fastcall TTAS00501::DspHistory()
{
    m_pGDC = TvList->DataController;

    try
    {
        CMM_ClearGridTableView(TvList);

        int nRow1 = 0;
        int nDataCnt = 0;
        int ii;

        try
        {
            TvList->BeginUpdate(lsimImmediate);

            nDataCnt = FTrfManager->FLists.Size();

            String sCaption;
            int nIdxSped, nIdxGrad;
            int nGap;
            for (ii = 0; ii < DAY_HOUR; ii++)
            {
                nRow1 = m_pGDC->AppendRecord();

                sCaption.printf(L"%02d", ii);
                m_pGDC->Values[nRow1][Col03->Index] = sCaption;

                nIdxSped = ColSped->Index;
                nIdxGrad = ColGrad->Index;
                FOR_STL(TDetourTrf*, pObj, FTrfManager->FLists)
                {
                    m_pGDC->Values[nRow1][nIdxSped++] = pObj->INFO[0][ii].SPED;
                    m_pGDC->Values[nRow1][nIdxSped++] = pObj->INFO[1][ii].SPED;
                    nGap = pObj->INFO[0][ii].SPED - pObj->INFO[1][ii].SPED;
                    if (nGap < 0)
                    {
                        sCaption.printf(L"▼ %3d", nGap*-1);
                    }
                    else if (nGap > 0)
                    {
                        sCaption.printf(L"▲ %3d", nGap);
                    }
                    else
                    {
                        sCaption = "0";
                    }
                    m_pGDC->Values[nRow1][nIdxSped++] = sCaption;

                    m_pGDC->Values[nRow1][nIdxGrad++] = pObj->INFO[0][ii].GRAD;
                    m_pGDC->Values[nRow1][nIdxGrad++] = pObj->INFO[1][ii].GRAD;
                    m_pGDC->Values[nRow1][nIdxGrad++] = pObj->INFO[0][ii].GRAD;
                }
            }
        }
        __finally
        {
            TvList->EndUpdate();
            //CxList->SetFocus();

            //DrawChart(FAtrdNm + " [" + FQryDay + "]");

            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)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &e)
    {
        throw Exception(String(e.ClassName()) + e.Message);
    }
}
//---------------------------------------------------------------------------

void __fastcall TTAS00501::DrawChart(String ATitle)
{
    TcxGridBandedTableView *pView = NULL;
    String                  sAxisX, sAxisY;
    int   nAxisY1, nAxisY2, nStColIdx, nEdColIdx, nTotColIdx;

    nEdColIdx = 0;
    nTotColIdx = -1;

    pView   = TvList;
    nAxisY1 = Col03->Index;         //특수일
    nAxisY2 = Col04->Index;         //구분(화면보이지 않음)
    nEdColIdx = TvListColumn29->Index;  // 23시
    nStColIdx = ColSped->Index;         // 00시

    /*
    *  Chart draw
    */
    try
    {
        m_pFrmChart->Clear();
        if (pView->DataController->RecordCount == 0)
        {
            return;
        }

        m_pFrmChart->BeginDraw("", "", "");
        m_pFrmChart->DrawChart5_1((TcxGridTableView *)pView, nAxisY1, nAxisY2, nStColIdx, nEdColIdx, nTotColIdx);
        m_pFrmChart->EndDraw();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TTAS00501::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"우회도로분석";

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

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

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

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

void __fastcall TTAS00501::ColSpedCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
    TColor tColor = ACanvas->Brush->Color;
    TColor tFont  = clBlack;

    try
    {
        if (!VarIsNull(AViewInfo->Value))
        {
            String sSpd = AViewInfo->Value;
            if (sSpd == NULL || sSpd.IsEmpty() || sSpd == "0" || sSpd == "-")
            {
                tColor = clSilver;
            }
            else
            {
                String sGrad = AViewInfo->GridRecord->DisplayTexts[AViewInfo->Item->Index+24];
                if      (sGrad == "LTC1") tColor = clLime;
                else if (sGrad == "LTC2") tColor = clYellow;
                else if (sGrad == "LTC3") tColor = clRed;
                else                      tColor = clSilver;
            }
        }
        else
        {
            tColor = clSilver;
        }

        if (tColor == clSilver) tFont = tColor;
        ACanvas->Font->Color = tFont;
        ACanvas->SetBrushColor(tColor);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TTAS00501::TvListDiffCustomDrawCell(TcxCustomGridTableView *Sender,
          TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    TColor tColor = ACanvas->Brush->Color;
    TColor tFont  = clBlack;

    try
    {
        if (!VarIsNull(AViewInfo->Value))
        {
            String sTmp = AViewInfo->Value;
            int sVal = sTmp.ToIntDef(99999);
            if (sVal != 99999)
            {
                if (sVal > 2)
                {
                    tColor = clRed;
                }
                else
                if (sVal < -2)
                {
                    tColor = clFuchsia;
                }
                else
                {
                    tColor = clLime;
                }
            }
        }

        ACanvas->Font->Color = tFont;
        ACanvas->SetBrushColor(tColor);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

