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

#include <vcl.h>
#include <winsock2.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "AppGlobalF.h"
#include "CenterCommF.h"
#include "CDSFacilityF.h"
#include "ITSLangTransF.h"
#pragma hdrstop

#include "PIS0030MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#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 "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxStyles"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma resource "*.dfm"

TPIS0030M *PIS0030M = NULL;

//---------------------------------------------------------------------------
__fastcall TPIS0030M::TPIS0030M(TComponent* Owner)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FTitle = "주차장 제어";
    FReqSeq = 0;
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::CommClose()
{
    try
    {
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TPIS0030M::FormInit()
{
    LoadParkServerInfo();
    RefreshData();
}
//---------------------------------------------------------------------------

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

void __fastcall TPIS0030M::BtnCloseClick(TObject *Sender)
{
    Close();
}
//---------------------------------------------------------------------------

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

void __fastcall TPIS0030M::BtnControlClick(TObject *Sender)
{
#ifdef USE_PARKxx
    if (CTLR_MNGM_NMBR->Text == "")
    {
        Application->MessageBox(L"주차장을 선택하지 않았습니다.", FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        CxList->SetFocus();
        return;
    }

    if (COMM_STATE->Text != "정상")
	{
        Application->MessageBox(L"통신상태가 정상이 아닌 주차장으로는 주차면수 초기화명령을 전송할 수 없습니다.", FTitle.c_str(), MB_OK|MB_ICONWARNING|MB_APPLMODAL);
		return;
	}

    if (Application->MessageBox(L"주차장 주차면수 초기화 명령 확인\r\n선택한 주차장에 대하여 주차면수 초기화 명령을 전송하시겠습니까??",
                                FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;


    AnsiString sIpAddress = FIpAddress;
    int nPort = FPort;

    AnsiString sId;
    P_INIT_PARKING *pInfo;
    P_REQ_INIT_PARKING data;
    memset((char*) & data, 0x00, sizeof(P_REQ_INIT_PARKING));

    int ADataLen;

    data.Count = 1;
    pInfo = &data.Info[0];

    sId = CTLR_MNGM_NMBR->Text;
    sprintf(pInfo->Id, "%.*s", P_PARKING_ID_SIZE, sId.c_str()); // Id

    //pInfo->Total    = (DWORD)StrToIntDef(Edit1->Text.Trim(), 0);    // 총 주차여유 면수	        주차장 전체 여유 면수	    4	N
    pInfo->General  = (DWORD)StrToIntDef(Edit2->Text.Trim(), 0);    // 일반 주차여유 면수	    일반 차량 주차 여유 면수	4	N
    pInfo->Disabled = (DWORD)StrToIntDef(Edit3->Text.Trim(), 0);    // 장애인 주차여유 면수	    장애인 차량 주차 여유 면수	4	N
    pInfo->Small    = (DWORD)StrToIntDef(Edit4->Text.Trim(), 0);    // 경차 주차여유 면수	    경차 주차 여유 면수	        4	N
    pInfo->Woman    = (DWORD)StrToIntDef(Edit5->Text.Trim(), 0);    // 여성전용 주차여유 면수	여성전용 주차여유 면수	    4	N
    pInfo->Electric = (DWORD)StrToIntDef(Edit6->Text.Trim(), 0);    // 전기차 주차여유 면수	    전기차 전용 주차여유 면수	4	N
    pInfo->Total = pInfo->General  +
                   pInfo->Disabled +
                   pInfo->Small    +
                   pInfo->Woman    +
                   pInfo->Electric;
#if 0
    pInfo->Total = 200; // 총 주차여유 면수	        주차장 전체 여유 면수	    4	N
    pInfo->General = 0; // 일반 주차여유 면수	    일반 차량 주차 여유 면수	4	N
    pInfo->Disabled = 14; // 장애인 주차여유 면수	    장애인 차량 주차 여유 면수	4	N
    pInfo->Small = 10; // 경차 주차여유 면수	    경차 주차 여유 면수	        4	N
    pInfo->Woman = 22; // 여성전용 주차여유 면수	여성전용 주차여유 면수	    4	N
    pInfo->Electric = 12; // 전기차 주차여유 면수	    전기차 전용 주차여유 면수	4	N
#endif

    ADataLen = 1 + (data.Count*sizeof(P_INIT_PARKING));

    P_INT_PACKET PKT;
    memset((char*) & PKT, 0x00, sizeof(P_INT_HEADER_SIZE));

    PKT.head.SendId = P_INT_ID_MAIN_OPER; /* 송신 시스템 ID */
    PKT.head.RecvId = P_INT_ID_PARK_SERVER; /* 수신 시스템 ID */
    PKT.head.TotalFrame = 1; /* 전체 프레임 갯수 */
    PKT.head.CurrentFrame = 1; /* 현재 프레임 번호 */
    PKT.head.Reserved = 0x00; /* Reserved */
    PKT.head.OPCode = INT_OP_PROC_EVENT; // INT_OP_COMM_COMMON;     /* 명령어 */
    PKT.head.Length = htonl(ADataLen + 2); /* 데이터의 길이 */

    PKT.data.Data[0] = INT_OP_PARKING_INIT;
    PKT.data.Data[1] = 0X00;

#if 0
    memcpy(&PKT.data.Data[2], (char*) & data, ADataLen);
    int result = CenterSendMessageB(sIpAddress, nPort, (char*) & PKT, P_INT_HEADER_SIZE + ADataLen + 2);

    Application->MessageBox(L"주차면수 초기화 제어명령을 전송 하였습니다.", FTitle.c_str(), MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
#endif
#endif
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::OnMainFormMessage(TMessage &Msg)
{
#if 0
    IPCUDPMESSAGESTRUCT *pMsg; // 메시지 구조체
    IPCUDPDATASTRUCT *pPkt; // 내부 통신 패킷 구조체
    UNION_INT_DATA *pData; // 내부 통신 데이터부 구조체

    pMsg = (IPCUDPMESSAGESTRUCT*)Msg.LParam;
    pPkt = &pMsg->Frame;
    pData = &pPkt->Data.unData;

    switch(Msg.WParam)
    {
    case INT_OP_RSE_CONTROL_RES: /* 0xC1, RSE 제어정보 응답 */
    {
            INT_RSE_CONTROL_RES *pRseCtl;
            pRseCtl = (INT_RSE_CONTROL_RES*)pData;

            String sResId = String(pRseCtl->Head.RseId);
            String sResSeq = String(pRseCtl->Head.Seq);
            int nResult = pRseCtl->Data.ResType;
            try {
                TvResult->BeginUpdate();

                int nRowCnt = TvResult->ViewData->RecordCount;

                for (int ii = 0; ii < nRowCnt; ii++)
                {
                    TcxCustomGridRow* ARow = FRAMEDsrcList1->TvList->ViewData->Rows[ii];
                    if (((bool)ARow->Values[FRAMEDsrcList1->ColumnSel->Index]))
                    {
                        String sId = VarToStr(ARow->Values[ColResult1->Index]);
                        String sSeq = VarToStr(ARow->Values[ColResult2->Index]);
                        if (sResId == sId && sResSeq == sSeq) {
                            String sResult = "Unknown";
                            if (nResult == (int)INT_RSE_RESPONSE_SUCC)
                                sResult = "성공";
                            else if (nResult == (int)INT_RSE_RESPONSE_NACK)
                                sResult = "실패";
                            else if (nResult == (int)INT_RSE_RESPONSE_NONE)
                                sResult = "응답없음";

                            ARow->Values[ColResult4->Index] = sResult;
                            break;
                        }
                    }
                }
            }
            __finally
            {
                TvResult->EndUpdate();
            }
        }
        break;
    default:
        break;
    } /* end switch */
#endif
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::LoadParkServerInfo()
{
    FIpAddress = "192.168.0.3";
    FPort = 4701;

    String sSvrID = "PARK01";
    String sIniFile = ChangeFileExt(ExtractFileName(Application->ExeName), ".ini");
    ReadConfigInfo(sIniFile, "APPLICATION", "PARKINGSERVERID", sSvrID);
    if (sSvrID == "")
    {
        sSvrID = "PARK01";
    }

    // 검색조건에 의한 링크 데이터 조회
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "SELECT A.*                          \r\n"
           "  FROM TB_UNIT_SYST A               \r\n"
           " WHERE A.SYST_ID = '" + sSvrID + "' \r\n";

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
            pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
            pADO->SQL->Clear();
            pADO->SQL->Text = sQry;

            pADO->Open();
            for( ; !pADO->Eof; pADO->Next())
            {
                FIpAddress = pADO->FieldByName("SYST_IP_1")->AsString;
                FPort = pADO->FieldByName("PRGM_PORT")->AsString.ToIntDef(4701);
            }
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
        catch(...)
        {
            throw Exception(FrmLang->lblDbErr->Caption);//"[주차서버정보조회] 알수없는 DB 오류가 발생하였습니다.");
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::RefreshData()
{
    // 검색조건에 의한 링크 데이터 조회
    String sQry;
    TADOQuery *pADO = NULL;

    ClearForm();

    sQry = "SELECT A.PRLT_CTLR_ID, A.PRLT_NM, B.*       \r\n"
           "  FROM TB_PRLT_CTLR    A,                   \r\n"
           "       TB_PRLT_RT_INFR B                    \r\n"
           " WHERE A.REAL_DATA_YN   = 'Y'               \r\n"
           "   AND A.PRLT_CTLR_NMBR = B.PRLT_CTLR_NMBR  \r\n"
           " ORDER BY A.PRLT_CTLR_NMBR, B.FLOR_NMBR     \r\n";

    CMM_ClearGridTableView(TvList);

    try
    {
        int nRow;
        TvList->BeginUpdate();
        try
        {
            int nORD;

            pADO = new TADOQuery(NULL);
            pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
            pADO->SQL->Clear();
            pADO->SQL->Text = sQry;

            pADO->Open();
            for( ; !pADO->Eof; pADO->Next())
            {
                //실시간주차정보제공 하는 주차장만 제어가능
                String REAL_DATA_YN = pADO->FieldByName("REAL_DATA_YN")->AsString;
                if (REAL_DATA_YN != "Y") continue;

                nRow = TvList->DataController->AppendRecord();
                String PRLT_CTLR_ID = pADO->FieldByName("PRLT_CTLR_ID")->AsString;
                TvList->DataController->Values[nRow][Col11->Index] = PRLT_CTLR_ID;
                TvList->DataController->Values[nRow][Col12->Index] = pADO->FieldByName("PRLT_NM")->AsString;

                TvList->DataController->Values[nRow][Col00->Index] = pADO->FieldByName("FLOR_NMBR")->AsString;
                //TvList->DataController->Values[nRow][Col01->Index] = pADO->FieldByName("FLORNM")->AsString;
                //TvList->DataController->Values[nRow][Col02->Index] = pADO->FieldByName("UPDT_DT")->AsString;
                TvList->DataController->Values[nRow][Col02->Index] = ITSUtil_StrToDateTime(pADO->FieldByName("UPDT_DT")->AsString).FormatString(STR_DATETIME);
                TvList->DataController->Values[nRow][Col03->Index] = pADO->FieldByName("GNRL_RMND_PRZN_NUM")->AsString;
                TvList->DataController->Values[nRow][Col04->Index] = pADO->FieldByName("LGVH_RMND_PRZN_NUM")->AsString;
                TvList->DataController->Values[nRow][Col05->Index] = pADO->FieldByName("HVVH_RMND_PRZN_NUM")->AsString;
                TvList->DataController->Values[nRow][Col06->Index] = pADO->FieldByName("EMVH_RMND_PRZN_NUM")->AsString;
                TvList->DataController->Values[nRow][Col07->Index] = pADO->FieldByName("HNDC_RMND_PRZN_NUM")->AsString;
                TvList->DataController->Values[nRow][Col08->Index] = pADO->FieldByName("WMON_RMND_PRZN_NUM")->AsString;
                TvList->DataController->Values[nRow][Col09->Index] = pADO->FieldByName("ELVH_RMND_PRZN_NUM")->AsString;
                TvList->DataController->Values[nRow][Col10->Index] = pADO->FieldByName("ETC_RMND_PRZN_NUM")->AsString;

                TItsFacility *pObj = ItsFacilityManager->FLists.Find(PRLT_CTLR_ID);
                if (pObj)
                {
                    if (pObj->FComm == state_error)
                        TvList->DataController->Values[nRow][Col13->Index] = "장애";
                    else
                        TvList->DataController->Values[nRow][Col13->Index] = "정상";
                }
                else
                {
                    TvList->DataController->Values[nRow][Col10->Index] = FrmLang->lblUnknown->Caption;//"알수없음";
                }
            }
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
        catch(...)
        {
            throw Exception(FrmLang->lblDbErr->Caption);//"[주차현황조회] 알수없는 DB 오류가 발생하였습니다.");
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        TvList->EndUpdate();
        //cxGroupBox3->Caption = "▶ 주차정보";// (최종가공시각: " + FRAMETrafficLinkList1->FLastAnsTime + ")";
    }
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::Edit1KeyPress(TObject *Sender, wchar_t &Key)
{
    if (Key > '9' || Key < '0')
    {
        if (Key != VK_BACK && Key != VK_TAB && Key != VK_DELETE)
            Key = 0;
    }
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::BtnSearchClick(TObject *Sender)
{
    Application->ProcessMessages();
    TSqlCursor sqlCrs((TControl*)BtnSearch);

    RefreshData();
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::Col13CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas,
          TcxGridTableDataCellViewInfo *AViewInfo, bool &ADone)
{
	if (AViewInfo->Value == "정상")
    {
	    ACanvas->Canvas->Brush->Color = clWhite;
	    ACanvas->Canvas->Font->Color  = clBlack;
	}
    else
    {
	    ACanvas->Canvas->Brush->Color = clRed;
	    ACanvas->Canvas->Font->Color  = clWhite;
	}
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::TvListCellClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift,
          bool &AHandled)
{
    DisplayInfo();
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::TvListFocusedRecordChanged(TcxCustomGridTableView *Sender,
          TcxCustomGridRecord *APrevFocusedRecord, TcxCustomGridRecord *AFocusedRecord,
          bool ANewItemRecordFocusingChanged)
{
    DisplayInfo();
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::DisplayInfo()
{
    ClearForm();

    if (TvList->ViewData->RecordCount <= 0) return;
    int nIndex = TvList->DataController->FocusedRecordIndex;
    if (nIndex < 0) return;

    CTLR_MNGM_NMBR->Text = VarToStr(TvList->DataController->Values[nIndex][Col11->Index]);
    CTLR_MNGM_NM->Text = VarToStr(TvList->DataController->Values[nIndex][Col12->Index]);
    COMM_STATE->Text = VarToStr(TvList->DataController->Values[nIndex][Col10->Index]);

#if 0
    int GNRL_RMND_PRZN_NUM = pObj->GENERAL;     //	N	NUMBER(3)	Y	0		일반 잔여 주차구역 개수
    int LGVH_RMND_PRZN_NUM = pObj->SMALL;       //	N	NUMBER(3)	Y	0		경차 잔여 주차구역 개수
    int HVVH_RMND_PRZN_NUM = 0;                 //	N	NUMBER(3)	Y	0		대형 잔여 주차구역 개수
    int EMVH_RMND_PRZN_NUM = 0;                 //	N	NUMBER(3)	Y	0		긴급차량 잔여 주차구역 개수
    int HNDC_RMND_PRZN_NUM = pObj->DISABLED;    //	N	NUMBER(3)	Y	0		장애인 잔여 주차구역 개수
    int WMON_RMND_PRZN_NUM = pObj->WOMAN;       //	N	NUMBER(3)	Y	0		여성전용 잔여 주차구역 개수
    int ETC_RMND_PRZN_NUM  = pObj->ELECTRIC;    //	N	NUMBER(3)	Y	0		기타 잔여 주차구역 개수
#endif

    Edit1->Text = "0";//VarToStr(TvList->DataController->Values[nIndex][Col09->Index]);
    Edit2->Text = VarToStr(TvList->DataController->Values[nIndex][Col03->Index]);
    Edit3->Text = VarToStr(TvList->DataController->Values[nIndex][Col07->Index]);
    Edit4->Text = VarToStr(TvList->DataController->Values[nIndex][Col04->Index]);
    Edit5->Text = VarToStr(TvList->DataController->Values[nIndex][Col08->Index]);
    Edit6->Text = VarToStr(TvList->DataController->Values[nIndex][Col09->Index]);

    if (COMM_STATE->Text == "정상")
        BtnControl->Enabled = true;
    else
        BtnControl->Enabled = false;
}
//---------------------------------------------------------------------------

void __fastcall TPIS0030M::ClearForm()
{
    CTLR_MNGM_NMBR->Text = "";
    CTLR_MNGM_NM->Text = "";
    COMM_STATE->Text = "-";

#if 0
    Edit1// 총 주차여유 면수	        주차장 전체 여유 면수	    4	N
    Edit2// 일반 주차여유 면수	    일반 차량 주차 여유 면수	4	N
    Edit3// 장애인 주차여유 면수	    장애인 차량 주차 여유 면수	4	N
    Edit4// 경차 주차여유 면수	    경차 주차 여유 면수	        4	N
    Edit5// 여성전용 주차여유 면수	여성전용 주차여유 면수	    4	N
    Edit6// 전기차 주차여유 면수	    전기차 전용 주차여유 면수	4	N
#endif
    Edit1->Text = "0";
    Edit2->Text = "0";
    Edit3->Text = "0";
    Edit4->Text = "0";
    Edit5->Text = "0";
    Edit6->Text = "0";

    BtnControl->Enabled = false;
}
//---------------------------------------------------------------------------

