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

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

#include "IFM0000MF.h"
#include "FrmMainF.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 "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 "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#pragma link "dxSkinCoffee"
#pragma link "dxSkinDarkRoom"
#pragma link "dxSkinDarkSide"
#pragma link "dxSkinFoggy"
#pragma link "dxSkinGlassOceans"
#pragma link "dxSkiniMaginary"
#pragma link "dxSkinLilian"
#pragma link "dxSkinLiquidSky"
#pragma link "dxSkinLondonLiquidSky"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinMoneyTwins"
#pragma link "dxSkinOffice2007Black"
#pragma link "dxSkinOffice2007Blue"
#pragma link "dxSkinOffice2007Green"
#pragma link "dxSkinOffice2007Pink"
#pragma link "dxSkinOffice2007Silver"
#pragma link "dxSkinOffice2010Black"
#pragma link "dxSkinOffice2010Blue"
#pragma link "dxSkinOffice2010Silver"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "cxGroupBox"
#pragma resource "*.dfm"

TIFM0000M *IFM0000M = NULL;
extern LOGININFO *g_pLOGIN;

//---------------------------------------------------------------------------
__fastcall TIFM0000M::TIFM0000M(TComponent* Owner)
    : TForm(Owner)
{
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FTitle = "시설물상태 현황";

    FFacilityType = "";
}
//---------------------------------------------------------------------------

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

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

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TIFM0000M::FormInit()
{
    TvList->OptionsView->NoDataToDisplayInfoText = "<시설물 상태>";
}
//---------------------------------------------------------------------------

/*
 * Form이 Show되고 난 후 최초 1회 수행되는 타이머 이벤트
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TIFM0000M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    RefreshData();
}
//---------------------------------------------------------------------------

/*
 * Search 버튼 클릭 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TIFM0000M::BtnSearchClick(TObject *Sender)
{
    BtnSearch->Enabled = false;
    // 시설물상태정보
    FrmMain->FPollStatus01.Reset();
    //RefreshData();
}
//---------------------------------------------------------------------------

/*
 * Refresh Data Event Function
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TIFM0000M::RefreshData()
{
    UpdateFacility();
    UpdateFacilityStatusTotal();
    UpdateFacilityStatus();

    BtnSearch->Enabled = true;
}
//---------------------------------------------------------------------------

/*
 * Close 버튼 클릭 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TIFM0000M::BtnCloseClick(TObject *Sender)
{
    Close();    
}
//---------------------------------------------------------------------------

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

void __fastcall TIFM0000M::UpdateFacility()
{
    try
    {
        TItsSubCode *pSubCode;
        try
        {
            ItsFacilityManager->FLists.Lock();

            TFacilityStatus *pStatus;
            ItsFacilityManager->FListStatus.RemoveAll();

            FOR_STL(TItsFacility*, pFacility, ItsFacilityManager->FLists)
            {
                pFacility->StatusGridIndex = -1;
                if (pFacility->DEL_YN == "Y") continue;

                String sComm = "정상";
                if (pFacility->FComm == state_normal) sComm = "정상";
                else
                if (pFacility->FComm == state_error ) sComm = "통신이상";
                else
                if (pFacility->FComm == state_module) sComm = "함체문열림";
                else                                  sComm = "알수없음";

                pStatus = ItsFacilityManager->FListStatus.Find(pFacility->FCLT_TYPE);
                if (!pStatus)
                {
                    pStatus = new TFacilityStatus();
                    pStatus->Type   = pFacility->FCLT_TYPE;
                    pStatus->Total  = 0;
                    pStatus->Normal = 0;
                    pStatus->Error  = 0;
                    pStatus->Collect= 0;

                    ItsFacilityManager->FListStatus.Push(pFacility->FCLT_TYPE, pStatus);
                }
                pStatus->Total++;   /* 전체 갯수를 증가 시킴 */
                if (pFacility->FComm == state_error)
                {
                    pStatus->Error++;
                }
                else
                if (pFacility->FComm == state_module)
                {
                    pStatus->Module++;
                }
                if (pFacility->FCollError)
                {
                    pStatus->Collect++;
                }
                try
                {
                    String sValue = pFacility->FCBoxTmpr;
                    int nValue = 0;
                    if (TryStrToInt(sValue, nValue))
                    {
                        if (nValue > g_AppCfg.Temp.AlarmValue)
                        {
                            sComm = "함체온도";
                        }
                    }
                } catch(...) {}

            }
        }
        __finally
        {
            ItsFacilityManager->FLists.UnLock();
        }
    }
    __finally
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::UpdateFacilityStatusTotal()
{
    int nRow = 0;
    try
    {
        CMM_ClearGridTableView(TvStatus);

        TcxDataController *pGDC = TvStatus->DataController;
        TvStatus->BeginUpdate();

        try
        {
            FOR_STL(TFacilityStatus*, pStatus, ItsFacilityManager->FListStatus)
            {
                nRow = pGDC->AppendRecord();

                pGDC->Values[nRow][ColType->Index]   = pStatus->Type;

                if (FFacilityType == "") FFacilityType = pStatus->Type;

                String sName = "";
                if (pStatus->Type == FAC_CCTV) sName = " CCTV제어기";
                else
                if (pStatus->Type == FAC_VMS)  sName = " VMS제어기";
                else
                if (pStatus->Type == FAC_VDS)  sName = " VDS제어기";
                else
                if (pStatus->Type == FAC_PVMS) sName = " PIS표출기";
                else
                if (pStatus->Type == FAC_PVDS) sName = " PIS수집기";
                else
                if (pStatus->Type == FAC_BIT)  sName = " 정류소안내기";
                else
                if (pStatus->Type == FAC_SIG)  sName = " 신호제어기";

                pGDC->Values[nRow][ColName->Index]   = sName;

                pGDC->Values[nRow][ColTotal->Index]  = pStatus->Total;
                pGDC->Values[nRow][ColNormal->Index] = pStatus->Total - pStatus->Error;
                pGDC->Values[nRow][ColFail->Index]   = pStatus->Error;
                if (pStatus->Type == "VDS" || pStatus->Type == "AVI")
                    pGDC->Values[nRow][ColModule->Index] = pStatus->Collect;//Module;
                else
                    pGDC->Values[nRow][ColModule->Index] = "-";
            }
        }
        catch(Exception &exception)
        {
        }
    }
    __finally
    {
        TvStatus->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::UpdateFacilityStatus()
{
    String sName;
    if (FFacilityType == FAC_CCTV) sName = "▶ CCTV제어기 상태";
    else
    if (FFacilityType == FAC_VMS)  sName = "▶ VMS제어기 상태";
    else
    if (FFacilityType == FAC_VDS)  sName = "▶ VDS제어기 상태";
    else
    if (FFacilityType == FAC_PVMS) sName = "▶ PIS표출기 상태";
    else
    if (FFacilityType == FAC_PVDS) sName = "▶ PIS수집기 상태";
    else
    if (FFacilityType == FAC_BIT)  sName = "▶ 정류소안내기 상태";
    else
    if (FFacilityType == FAC_SIG)  sName = "▶ 신호제어기 상태";
    else sName = "▶ 시설물현황";

    grpBox->Caption = sName;

    CMM_ClearGridTableView(TvList);

    Col02->Visible = false;
    Col03->Visible = false;
    Col04->Visible = false;
    Col05->Visible = false;
    Col06->Visible = false;
    Col07->Visible = false;
    Col08->Visible = false;
    Col09->Visible = false;
    Col10->Visible = false;

    if (FFacilityType == FAC_CCTV ||
        FFacilityType == FAC_VMS  ||
        FFacilityType == FAC_VDS  ||
        FFacilityType == FAC_AVI )
    {
        Col02->Visible = true;  //함체온도
        Col03->Visible = true;  //함체문
    }
    else
    if (FFacilityType == FAC_DSRC ||
        FFacilityType == FAC_SIG  ||
        FFacilityType == FAC_PVMS )
    {
        Col03->Visible = true;  //함체문
    }
    else
    if (FFacilityType == FAC_PVDS )
    {
        Col04->Visible = true;  //제어기상태
    }

    if (FFacilityType == FAC_PVMS )
    {
        Col05->Visible = true;  //전원
        Col06->Visible = true;  //모듈
        Col07->Visible = true;  //FAN
        Col08->Visible = true;  //히터
    }


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

        TItsSubCode *pSubCode;
        try
        {
            ItsFacilityManager->FLists.Lock();

            TFacilityStatus *pStatus;
            ItsFacilityManager->FListStatus.RemoveAll();

            //통신이상인 것들을 먼저 표출한다.
            FOR_STL(TItsFacility*, pFacility, ItsFacilityManager->FLists)
            {
                pFacility->StatusGridIndex = -1;
                if (pFacility->DEL_YN == "Y") continue;
                if (pFacility->FCLT_TYPE != FFacilityType) continue;
                if (pFacility->FComm != state_error ) continue;

                nRow = m_pGDC->AppendRecord();

                m_pGDC->Values[nRow][ColId->Index] = pFacility->FCLT_ID;
                m_pGDC->Values[nRow][ColNm->Index] = pFacility->FCLT_LCTN;
                m_pGDC->Values[nRow][Col00->Index] = ITSUtil_FormatStr(pFacility->Sts00, STR_DATETIME);


                m_pGDC->Values[nRow][Col01->Index] = "이상";

                m_pGDC->Values[nRow][Col02->Index] = "-";
                m_pGDC->Values[nRow][Col03->Index] = "-";
                m_pGDC->Values[nRow][Col04->Index] = "-";
                m_pGDC->Values[nRow][Col05->Index] = "-";
                m_pGDC->Values[nRow][Col06->Index] = "-";
                m_pGDC->Values[nRow][Col07->Index] = "-";
                m_pGDC->Values[nRow][Col08->Index] = "-";
                m_pGDC->Values[nRow][Col09->Index] = "-";
                m_pGDC->Values[nRow][Col10->Index] = "-";
            }

            //통신이상이 아닌것들을 표출한다.
            FOR_STL(TItsFacility*, pFacility, ItsFacilityManager->FLists)
            {
                pFacility->StatusGridIndex = -1;
                if (pFacility->DEL_YN == "Y") continue;
                if (pFacility->FCLT_TYPE != FFacilityType) continue;
                if (pFacility->FComm == state_error ) continue;

                nRow = m_pGDC->AppendRecord();

                m_pGDC->Values[nRow][ColId->Index] = pFacility->FCLT_ID;
                m_pGDC->Values[nRow][ColNm->Index] = pFacility->FCLT_LCTN;
                m_pGDC->Values[nRow][Col00->Index] = ITSUtil_FormatStr(pFacility->Sts00, STR_DATETIME);

                m_pGDC->Values[nRow][Col01->Index] = "정상";

                m_pGDC->Values[nRow][Col02->Index] = pFacility->FCBoxTmpr;  //함체온도

                m_pGDC->Values[nRow][Col03->Index] = pFacility->FDoor == "0" ? "닫힘" : "열림";

                m_pGDC->Values[nRow][Col04->Index] = pFacility->Sts01 == "0" ? "정상" : "오류";     //제어기상태
                m_pGDC->Values[nRow][Col05->Index] = pFacility->Sts02 == "0" ? "정상" : "오류";     //전원
                m_pGDC->Values[nRow][Col06->Index] = pFacility->Sts03 == "0" ? "정상" : "오류";     //모듈
                m_pGDC->Values[nRow][Col07->Index] = pFacility->Sts04 == "0" ? "가동" : "중지";     //FAN
                m_pGDC->Values[nRow][Col08->Index] = pFacility->Sts05 == "0" ? "가동" : "중지";     //히터
                m_pGDC->Values[nRow][Col09->Index] = "-";
                m_pGDC->Values[nRow][Col10->Index] = "-";
            }
        }
        __finally
        {
            ItsFacilityManager->FLists.UnLock();
        }
    }
    __finally
    {
        TvList->EndUpdate();
        TvList->DataController->GotoFirst();
        TvList->DataController->FocusedRecordIndex = 0;
    }
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::ColNameCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
    if (AViewInfo->GridRecord->RecordIndex < 0) return;
    ACanvas->Font->Style = TFontStyles() << fsBold;
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::ColTotalCustomDrawCell(TcxCustomGridTableView *Sender,
          TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    // 전체
    if (AViewInfo->GridRecord->RecordIndex < 0) return;
    ACanvas->Font->Style = TFontStyles() << fsBold;
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::ColNormalCustomDrawCell(TcxCustomGridTableView *Sender,
          TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    // 정상
    if (AViewInfo->GridRecord->RecordIndex < 0) return;
    ACanvas->Font->Style = TFontStyles() << fsBold;
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::ColFailCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
    // 이상
    if (AViewInfo->GridRecord->RecordIndex < 0) return;
    ACanvas->Font->Style = TFontStyles() << fsBold;
	if (!VarIsNull(AViewInfo->GridRecord->DisplayTexts[ColFail->Index]))
    {
        String sErr = AViewInfo->GridRecord->DisplayTexts[ColFail->Index];
        if (sErr != "0")
        {
            ACanvas->Font->Color = clRed;
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::TvStatusFocusedRecordChanged(TcxCustomGridTableView *Sender,
          TcxCustomGridRecord *APrevFocusedRecord, TcxCustomGridRecord *AFocusedRecord,
          bool ANewItemRecordFocusingChanged)
{
    int nIndex = TvStatus->DataController->FocusedRecordIndex;
    if (nIndex < 0) return;

    String sFacilityType = VarToStr(TvStatus->DataController->Values[nIndex][ColType->Index]);
    FFacilityType = sFacilityType;

    UpdateFacilityStatus();
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::Col04CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
    if (AViewInfo->GridRecord->RecordIndex < 0) return;
    ACanvas->Font->Style = TFontStyles() << fsBold;

	if (AViewInfo)
	{
        String sInfo = AViewInfo->Text.Trim();

		if (sInfo == "이상" ||
            sInfo == "오류" ||
            sInfo == "장애" ||
            sInfo == "열림" )
		{
			ACanvas->Canvas->Font->Color = clRed;
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::ColIdCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
    if (AViewInfo->GridRecord->RecordIndex < 0) return;
    ACanvas->Font->Style = TFontStyles() << fsBold;

	if (!VarIsNull(AViewInfo->GridRecord->DisplayTexts[Col01->Index]))
    {
        String sErr = AViewInfo->GridRecord->DisplayTexts[Col01->Index].Trim();
        if (sErr != "정상")
        {
            ACanvas->Font->Color = clRed;
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::ColNmCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
    if (AViewInfo->GridRecord->RecordIndex < 0) return;
    ACanvas->Font->Style = TFontStyles() << fsBold;
}
//---------------------------------------------------------------------------

void __fastcall TIFM0000M::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxStatus;
    TcxGridTableView *pView = TvStatus;
    String            sTitle= "시설물현황";

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

void __fastcall TIFM0000M::cxButton1Click(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= grpBox->Caption;
    sTitle = StringReplace(sTitle, "▶ ", "", TReplaceFlags() << rfReplaceAll);

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

