/****************************************************************************
 * @source      :
 * @description :
 ****************************************************************************
 * DATE         AUTHOR    DESCRIPTION
 * --------------------------------------------------------------------------
 * 2011/12/24   정승호    최초작성
 *
 ****************************************************************************/
//---------------------------------------------------------------------------

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "AppGlobalF.h"
#include "CDSCodeF.h"
#include "CDSFacilityF.h"
#pragma hdrstop

#include "IFM0060MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCalendar"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxDropDownEdit"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#pragma link "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxTextEdit"
#pragma link "cxTimeEdit"
#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 "cxRadioGroup"
#pragma link "cxClasses"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxDBData"
#pragma link "cxFilter"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridDBTableView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxStyles"
#pragma link "cxCheckBox"
#pragma link "FRAME_FlashMapF"
#pragma link "FRAME_ParkingListF"
#pragma resource "*.dfm"

TIFM0060M *IFM0060M = NULL;
//---------------------------------------------------------------------------

void TIFM0060M_FlashCall(TObject *ASender, const WideString request)
{
    try
    {
        if (!IFM0060M) return;
        IFM0060M->ShockwaveFlash1FlashCall1(ASender, request);
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

__fastcall TIFM0060M::TIFM0060M(TComponent* Owner)
    : TForm(Owner)
{
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FUpdate= false;
    FTitle = "주차장 관리";

    MapStart = false;

    FRAMEGisMap1->FlashCallbackFunc = TIFM0060M_FlashCall;
    FRAMEGisMap1->DrawMode = 1; //구간정보표출

    FRAMEGisMap1->ImgPan->Visible = true;
    FRAMEGisMap1->ImgZoomIn->Visible = true;
    FRAMEGisMap1->ImgZoomOut->Visible = true;
    FRAMEGisMap1->ImgSel->Visible = true;
    FRAMEGisMap1->ImgStnd->Visible = true;
    FRAMEGisMap1->ImgRefresh->Visible = true;

    FRAMEGisMap1->LbDef->Caption = "(선택메뉴를 클릭하여 위치를 선택합니다.)";
    FRAMEGisMap1->LbDef->Hint = FRAMEGisMap1->LbDef->Caption;
    FRAMEGisMap1->LbDef->Visible = true;

    FRAMEParkingList1->PnlTop->Visible = false;
    FRAMEParkingList1->PnlBottom->Visible = false;
    FRAMEParkingList1->ColumnSel->Visible = false;
    FRAMEParkingList1->Column02->Visible = false;

    m_pGDC = FRAMEParkingList1->TvList->DataController;
}
//---------------------------------------------------------------------------

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

/*
 * Form을 보여줄때 호출되는 event 메서드이다.
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TIFM0060M::FormShow(TObject *Sender)
{
    Refresh();

    CbTypeCd->Properties->Items->Clear();
    TItsCode *FCodeRMF  = ItsCodeManager->FLists.Find("RMF");
    if (FCodeRMF)
    {
		FOR_STL(TItsSubCode *, pSubCode, FCodeRMF->FSubLists)
		{
			if (pSubCode->USE_YN == "N") continue;
			CbTypeCd->Properties->Items->Add(" [" + pSubCode->CMMN_CD + "] " + pSubCode->CMMN_CD_KOR_NM);
		}
    }
	CbTypeCd->ItemIndex = 0;

    FormInit();
    ChangeEditMode(1);
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TIFM0060M::FormInit()
{
    EdId->Text          = "";
    EdMngmNmbr->Text    = "";
    EdName->Text        = "";
    SeParkingCnt->Value = 0;
    EdPhone->Text       = "";
    SePosX->Value       = 0;
    SePosY->Value       = 0;
    EdLoc->Text         = "";
    EdAddr->Text        = "";
    EdEName->Text       = "";
    EdELoc->Text        = "";
    EdEAddr->Text       = "";

    FNewDb = false;
}
//---------------------------------------------------------------------------

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

    FRAMEGisMap1->LinkLevel = 1;
    FRAMEGisMap1->LoadGisMap();

    FRAMEParkingList1->UpdateList();
}
//---------------------------------------------------------------------------

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

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

void __fastcall TIFM0060M::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    if (FUpdate)
    {
        POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_14, 0);
    }

    FRAMEParkingList1->OnCloseQuery(CanClose);
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::DisplayInfo(TItsParking* AObj)
{
    FormInit();

    if (!AObj) return;

    EdId->Text          = AObj->PARKINGID;
    EdMngmNmbr->Text    = AObj->PARKINGID;
    EdName->Text        = AObj->PARKINGNAME;
    SeParkingCnt->Value = AObj->PARKINGCNT.ToIntDef(0);
    EdPhone->Text       = AObj->PHONE;
    SePosX->Value       = StrToFloatDef(AObj->COORDX, 0);
    SePosY->Value       = StrToFloatDef(AObj->COORDY, 0);
    EdLoc->Text         = AObj->LOCATION;
    EdAddr->Text        = AObj->ADDRESS;
    EdEName->Text       = AObj->PARKINGENAME;
    EdELoc->Text        = AObj->ELOCATION;
    EdEAddr->Text       = AObj->EADDRESS;

    //CMM_SetComboBoxItem(CbTypeCd, AObj->CTLR_TYPE_CD);
    //CbValidYn->Text    = AObj->VALD_YN;

    FRAMEGisMap1->SelectObjectByPos(SePosX->Value, SePosY->Value, true);

    ChangeEditMode(3);
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::UpdateParkingIcon()
{
    if (!MapStart) return;

    TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "RemoveFacility", FAC_PARK);

    TItsFacility *pFacility;
    try
    {
        //if (ChkViewIcon->Checked)
        {
            String sObjList = "";

            try
            {
                ItsParkingManager->FLists.Lock();
                FOR_STL(TItsParking*, pObj, ItsParkingManager->FLists)
                {
                    if (pObj->DEL_YN != "N") continue;

                    String sLoc = TCommFlash::ReplaceName(pObj->PARKINGNAME);
                    sObjList += (pObj->PARKINGID + "," + "0," + sLoc + "," + pObj->COORDX + "," + pObj->COORDY + "," + pObj->PARKINGID + "|");
                }
            }
            __finally
            {
                ItsParkingManager->FLists.UnLock();

                if (sObjList != "")
                {
                    sObjList = sObjList.SubString(1, sObjList.Length()-1);
                    TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "AddFacility", FAC_PARK + "|" + sObjList);
                }
            }
        }
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::FRAMEParkingList1TvListCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift, bool &AHandled)
{
	if (!ACellViewInfo) return;
	int nRow = FRAMEParkingList1->TvList->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    int nMemPtr = FRAMEParkingList1->TvList->DataController->Values[nRow][FRAMEParkingList1->Column99->Index];
    TItsParking* pObj = (TItsParking*)nMemPtr;
    DisplayInfo(pObj);
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::ChkViewIconClick(TObject *Sender)
{
    if (!MapStart) return;

    String sShowIcon = ChkViewIcon->Checked ? "1" : "0";
    String sShowName = ChkViewName->Checked ? "1" : "0";
    TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "ShowFacility", "PARK|" + sShowIcon + "|" + sShowName);
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::BtnEditClick(TObject *Sender)
{
    if (BtnEdit->Caption == "편집")
    {
        ChangeEditMode(0);
        FNewDb = false;
    }
    else
    {
        String sId = EdId->Text;
        ChangeEditMode(1);

        TItsParking *pObj = ItsParkingManager->FLists.Find(sId);
        if (pObj)
        {
            CMM_SetGridRow(FRAMEParkingList1->CxList, FRAMEParkingList1->TvList, sId, FRAMEParkingList1->Column01->Index);
            DisplayInfo(pObj);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::ChangeEditMode(int AEdit)
{
    bool bEnabled = false;
    switch(AEdit)
    {
    case 0: //편집버튼클릭
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = false;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = true;

            BtnEdit->Caption = "취소";
            BtnEdit->Hint    = "데이터 편집 취소";
        }
        break;
    case 1: //편집[취소]버튼클릭
        {
            FormInit(); //화면을 모두 지운다.
            BtnEdit->Enabled = false;
            BtnInsert->Enabled = true;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = false;

            BtnEdit->Caption = "편집";
            BtnEdit->Hint    = "데이터 편집";
            bEnabled = true;
        }
        break;
    case 2: //추가
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = false;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = true;

            BtnEdit->Caption = "취소";
            BtnEdit->Hint    = "데이터 편집 취소";
        }
        break;
    case 3: //수정모드
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = true;
            BtnDelete->Enabled = true;
            BtnSave->Enabled = false;

            BtnEdit->Caption = "편집";
            BtnEdit->Hint    = "데이터 편집";
            bEnabled = true;
        }
        break;
    }

    if (AEdit == 0 || AEdit == 2)
    {
        FRAMEParkingList1->CxList->Enabled = false;
    }
    else
    {
        FRAMEParkingList1->CxList->Enabled = true;
    }

    EdId->Properties->ReadOnly = bEnabled;
    EdMngmNmbr->Properties->ReadOnly = bEnabled;
    EdName->Properties->ReadOnly = bEnabled;
    SeParkingCnt->Properties->ReadOnly = bEnabled;
    EdPhone->Properties->ReadOnly = bEnabled;
    SePosX->Properties->ReadOnly = bEnabled;
    SePosY->Properties->ReadOnly = bEnabled;
    EdLoc->Properties->ReadOnly = bEnabled;
    EdAddr->Properties->ReadOnly = bEnabled;

    EdEName->Properties->ReadOnly = bEnabled;
    EdELoc->Properties->ReadOnly = bEnabled;
    EdEAddr->Properties->ReadOnly = bEnabled;
}
//---------------------------------------------------------------------------


void __fastcall TIFM0060M::BtnInsertClick(TObject *Sender)
{
    FormInit();

    //신규아이디를 얻어와서 화면을 초기화한다.
    String sId;

#if 0
    if (!ItsParkingManager->GetNextParkingId(sId))
    {
        Application->MessageBox(L"새로운 주차장ID를 생성하지 못하였습니다.\r\n프로그램 종료후에 다시 시도해 보세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
#else
	sId = InputBox("주차장ID", "신규 주차장ID를 입력하세요(10Byte).", "주차장ID" );

    sId = sId.Trim();
	if (sId == "주차장ID" || sId == "")
	{
		return;
	}
	if (AnsiString(sId).Length() > 10)
	{
        Application->MessageBox(L"주차장ID는  10Byte를 초과할 수 없습니다.", FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    TItsParking *pDb = (TItsParking *)ItsParkingManager->FLists.Find(sId);
    if (pDb)
    {
        Application->MessageBox(("[" + sId + "]는 사용할 수 없는 주차장ID 입니다.").c_str(), FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
#endif

    EdId->Text = sId;
    EdMngmNmbr->Text = sId;
    ChangeEditMode(2);
    FNewDb = true;
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::BtnDeleteClick(TObject *Sender)
{
    if (!MapStart) return;

    int nIdx = m_pGDC->FocusedRecordIndex;
    if (nIdx < 0) return;

    String sId = EdId->Text;

    if (sId.IsEmpty())
    {
        Application->MessageBox(L"삭제할 주차장정보를 목록에서 선택하세요.\r\n목록에서 더블클릭하여 선택합니다.", FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
    String sMsg;
    sMsg = "ID: " + sId;
    sMsg+= "\r\n선택하신 주차장 정보를 삭제하시겠습니까?";

    if (Application->MessageBox(sMsg.c_str(), FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

	TItsParking *pObj = ItsParkingManager->FLists.Find(sId);
	if (pObj)
	{
		if (ItsParkingManager->DeleteParking(pObj))
		{
            pObj->DEL_YN = "Y";
            FRAMEParkingList1->UpdateList();
		}

#if 0
		TItsFacility *pFacility = ItsFacilityManager->FLists.Find(sId);
        if (pFacility)
        {
            FUpdate = true;
        }
#else
        FUpdate = true;
#endif
        Application->MessageBox(L"주차장 정보삭제\r\n주차장 정보를 삭제 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FormInit();
        ChangeEditMode(1);

        TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "DeleteFacility", FAC_PARK + "|" + sId);
	}
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::BtnSaveClick(TObject *Sender)
{
	if (EdId->Text.IsEmpty()         ||
        EdName->Text.Trim().IsEmpty()||
        SePosX->Value == 0           ||
        SePosY->Value == 0           )
        //CbTypeCd->Text.IsEmpty()  )
	{
        Application->MessageBox(L"★항목은 필수 입력 항목입니다.\r\n모두 입력후 진행해 주세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    String sId = EdId->Text;

    TItsParking *pObj;
    if (FNewDb)
        pObj = new TItsParking();
    else
        pObj = ItsParkingManager->FLists.Find(sId);

    if (pObj)
    {
        pObj->PARKINGID    = sId;
        pObj->PARKINGNAME  = EdName->Text.Trim();
        pObj->PARKINGCNT   = VarToStr(SeParkingCnt->Value);
        pObj->COORDX       = VarToStr(SePosX->Value);
        pObj->COORDY       = VarToStr(SePosY->Value);
        pObj->PHONE        = EdPhone->Text.Trim();
        pObj->LOCATION     = EdLoc->Text.Trim();
        pObj->ADDRESS      = EdAddr->Text.Trim();
        pObj->PARKINGENAME = EdEName->Text.Trim();
        pObj->ELOCATION    = EdELoc->Text.Trim();
        pObj->EADDRESS     = EdEAddr->Text.Trim();
        pObj->PISFLAG      = "";
        pObj->DISTRICTID   = "";

        pObj->DEL_YN       = "N";

        bool bResult;
        if (FNewDb)
        {
            bResult = ItsParkingManager->InsertParking(pObj);
            if (bResult)
            {
                ItsParkingManager->FLists.Push(sId, pObj);
            }
		}
        else
		{
            bResult = ItsParkingManager->UpdateParking(pObj);
		}

        if (bResult)
        {
            Application->MessageBox(L"주차장 정보저장\r\n주차장 정보를 저장 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

            FUpdate = true;

            FRAMEParkingList1->UpdateList();
            UpdateParkingIcon();
            CMM_SetGridRow(FRAMEParkingList1->CxList, FRAMEParkingList1->TvList, sId, FRAMEParkingList1->Column01->Index);
            DisplayInfo(pObj);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TIFM0060M::ShockwaveFlash1FlashCall1(TObject *ASender, const WideString request)
{
    try
    {
        String sTemp;
        String sFunc;
        String sArgs;

        sTemp = request;

        int nFuncStrIdx = sTemp.Pos("\"");
        int nFuncEndIdx = sTemp.Pos("\" returntype");
        int nArgsStrIdx = sTemp.Pos("string>");
        int nArgsEndIdx = sTemp.Pos("</string");

        sFunc = sTemp.SubString(nFuncStrIdx + 1, nFuncEndIdx - (nFuncStrIdx + 1));
        sArgs = sTemp.SubString(nArgsStrIdx + 7, nArgsEndIdx - (nArgsStrIdx + 7));

        if (sFunc == "OnMapStart")
        {
            String sShowIcon = ChkViewIcon->Checked ? "1" : "0";
            String sShowName = ChkViewName->Checked ? "1" : "0";
            MapStart = true;
            TCommFlash::CallFunc(FRAMEGisMap1->ShockwaveFlash1, "ShowFacility", "PARK|" + sShowIcon + "|" + sShowName);
        }
        else
        if (sFunc == "OnDrawTrafLink")
        {
            static bool bFirst = true;
            if (bFirst)
            {
                UpdateParkingIcon();
                bFirst = true;
            }
        }
        else
        if (sFunc == "OnMousePos")
        {
            if (FRAMEGisMap1->ModeSelect)
            {
                TStringList *pStringList = new TStringList;
                pStringList->CommaText = sArgs;
                String sMapX = pStringList->Strings[0]; //lat
                String sMapY = pStringList->Strings[1]; //lng
                delete pStringList;
                try {
                    SePosX->Value = sMapX.ToDouble();
                    SePosY->Value = sMapY.ToDouble();
                } catch(...) {}
            }
        }
        else
        if (sFunc == "OnSelLink")
        {
            if (FRAMEGisMap1->ModeSelect)
            {
                TStringList *pStringList = new TStringList;
                pStringList->CommaText = sArgs;

                String sLevl = pStringList->Strings[0]; //링크레벨
                String sId   = pStringList->Strings[1]; //링크아이디
                String sZoom = pStringList->Strings[2]; //줌레벨
                String sPosX = pStringList->Strings[3]; //x
                String sPosY = pStringList->Strings[4]; //y
                String sMapX = pStringList->Strings[5]; //lat
                String sMapY = pStringList->Strings[6]; //lng

                delete pStringList;

                try {
                    SePosX->Value = sMapX.ToDouble();
                    SePosY->Value = sMapY.ToDouble();
                } catch(...) {}
            }
        }
        else
        if (sFunc == "OnClickFacility")
        {
            TStringList *pStringList = new TStringList;
            pStringList->CommaText = sArgs;

            String sType = pStringList->Strings[0]; //유형
            String sId   = pStringList->Strings[1]; //아이디
            String sName = pStringList->Strings[2]; //아이디

            delete pStringList;
        }
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

