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

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

#include "DSRH0101F.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 "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma resource "*.dfm"

TDSRH0101 *DSRH0101 = NULL;

//---------------------------------------------------------------------------
__fastcall TDSRH0101::TDSRH0101(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 = "DSRC-RSE 상태 이력";
}
//---------------------------------------------------------------------------

__fastcall TDSRH0101::~TDSRH0101(void)
{
}
//--------------------------------------------------------------------------

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

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<DSRC-RSE 상태 이력 정보>";
	//TvList->ViewInfo->GroupByBoxViewInfo->Text = "그룹핑할 필드의 헤더를 이곳으로 드래그 하세요";
    LblSearch->Caption = "검색조건: " + FStDateTime.SubString(1, 12) + " ~ " + FEdDateTime.SubString(1, 12);
}
//---------------------------------------------------------------------------

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

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

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

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

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

    String sQry;
    TADOQuery *pADO = ADOQry;

#if 1
    sQry = "SELECT A.ID, B.RSE_ID, B.ISTL_LCTN_NM,                          \r\n"
           "       A.CLCT_DT, A.CNTL_DEVC_STTS, A.CMNC_STTS, A.ATN_1_STTS,  \r\n"
           "       A.ATN_2_STTS, A.ATN_3_STTS, A.ATN_4_STTS, A.ATN_1_MTNS   \r\n"
           "  FROM TB_RSE_STTS_HS A, TB_RSE_MSTR B                          \r\n"
           " WHERE A.CLCT_DT BETWEEN :p01 AND :p02                          \r\n"
           "   AND A.ID = B.ID                                              \r\n"
           "   AND B.ID IN(" + FIdList + ")                                 \r\n"
           " ORDER BY A.ID, A.CLCT_DT                                       \r\n";
           //" ORDER BY TO_NUMBER(ID), CLCT_DT                            \r\n";
#else
    sQry = "SELECT ID, CLCT_DT, CNTL_DEVC_STTS, CMNC_STTS, ATN_1_STTS,  \r\n"
           "       ATN_2_STTS, ATN_3_STTS, ATN_4_STTS, ATN_1_MTNS       \r\n"
           "  FROM TB_RSE_STTS_HS                                       \r\n"
           " WHERE CLCT_DT BETWEEN :p01 AND :p02                        \r\n"
           "   AND ID IN(" + FIdList + ")                               \r\n"
           " ORDER BY ID, CLCT_DT                                       \r\n";
           //" ORDER BY TO_NUMBER(ID), CLCT_DT                            \r\n";
#endif

    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 TDSRH0101::DspHistory()
{
    TADOQuery *pADO = ADOQry;

    try
    {
    	TcxGridChartSeries *pChart = NULL;

        CMM_ClearGridTableView(TvList);

        int nRow = 0;
        int nDataCnt = 0;
        try {
            TvList->BeginUpdate();

            nDataCnt = pADO->RecordCount;
            m_pGDC->RecordCount = nDataCnt;

            for( ; !pADO->Eof; pADO->Next(), nRow++)
            {
                m_pGDC->Values[nRow][Column00->Index] = pADO->FieldByName("ID")->AsString;
                m_pGDC->Values[nRow][Column11->Index] = pADO->FieldByName("RSE_ID")->AsString;
                m_pGDC->Values[nRow][Column12->Index] = pADO->FieldByName("ISTL_LCTN_NM")->AsString;
                String sDbDate = pADO->FieldByName("CLCT_DT")->AsString;
                m_pGDC->Values[nRow][Column01->Index] = ITSUtil_FormatStr(sDbDate, STR_DATETIME);

                String sDevcStts = pADO->FieldByName("CNTL_DEVC_STTS")->AsString;
                String sCmncStts = pADO->FieldByName("CMNC_STTS")->AsString;
                String sAtn1Stts = pADO->FieldByName("ATN_1_STTS")->AsString;
#if 0
                String sAtn2Stts = pADO->FieldByName("ATN_2_STTS")->AsString;
                String sAtn3Stts = pADO->FieldByName("ATN_3_STTS")->AsString;
                String sAtn4Stts = pADO->FieldByName("ATN_4_STTS")->AsString;
#endif
                String sAtn1Mtns = pADO->FieldByName("ATN_1_MTNS")->AsString;

                if      (sDevcStts == "0") sDevcStts = "정상";
                else if (sDevcStts == "1") sDevcStts = "문열림";
                else if (sDevcStts == "2") sDevcStts = "팬동작";
                else if (sDevcStts == "3") sDevcStts = "내부온도 이상";
                else if (sDevcStts == "4") sDevcStts = "정보 없음";

                m_pGDC->Values[nRow][Column02->Index] = sDevcStts;

                if      (sCmncStts == "0") sCmncStts = "정상";
                else if (sCmncStts == "1") sCmncStts = "장애";
                else if (sCmncStts == "2") sCmncStts = "정보 없음";

                m_pGDC->Values[nRow][Column03->Index] = sCmncStts;

                if      (sAtn1Stts == "0") sAtn1Stts = "정상";
                else if (sAtn1Stts == "1") sAtn1Stts = "장애";
                else if (sAtn1Stts == "2") sAtn1Stts = "정보 없음";

                m_pGDC->Values[nRow][Column04->Index] = sAtn1Stts;

                if      (sAtn1Mtns == "0") sAtn1Mtns = "송출종료";
                else if (sAtn1Mtns == "1") sAtn1Mtns = "송출개시";
                else if (sAtn1Mtns == "2") sAtn1Mtns = "유지보수 근무개시";
                else if (sAtn1Mtns == "3") sAtn1Mtns = "정보 없음";

                m_pGDC->Values[nRow][Column05->Index] = sAtn1Mtns;

#if 0
                if      (sAtn2Stts == "0") sAtn2Stts = "정상";
                else if (sAtn2Stts == "1") sAtn2Stts = "장애";
                else if (sAtn2Stts == "2") sAtn2Stts = "정보 없음";

                if      (sAtn3Stts == "0") sAtn3Stts = "정상";
                else if (sAtn3Stts == "1") sAtn3Stts = "장애";
                else if (sAtn3Stts == "2") sAtn3Stts = "정보 없음";

                if      (sAtn4Stts == "0") sAtn4Stts = "정상";
                else if (sAtn4Stts == "1") sAtn4Stts = "장애";
                else if (sAtn4Stts == "2") sAtn4Stts = "정보 없음";

                m_pGDC->Values[nRow][Column06->Index] = sAtn2Stts;
                m_pGDC->Values[nRow][Column07->Index] = sAtn3Stts;
                m_pGDC->Values[nRow][Column08->Index] = sAtn4Stts;
#endif
            }
        }
        __finally
        {
            if (pADO)
            {
                pADO->Close();
            }

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

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

void __fastcall TDSRH0101::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle = "DSRC-RSE 상태이력";

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

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

void __fastcall TDSRH0101::Column02CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
	if( AViewInfo )
	{
		if(AViewInfo->Text == "정상")
		{
			ACanvas->Canvas->Font->Color = clTeal;
		}
		else if(AViewInfo->Text == "장애")
		{
			ACanvas->Canvas->Font->Color = clFuchsia;
		}
		else
		{
			ACanvas->Canvas->Font->Color = clGray;
		}
	}
}
//---------------------------------------------------------------------------

