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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "AppGlobalF.h"
#include "CDSCodeF.h"
#include "CDSFacilityF.h"
#include "CDSNodeF.h"
#include "CDSLinkF.h"
#include "ITSLangTransF.h"
#include "ITSMapF.h"
#include "CDSLayerF.h"
#include "ITS_OPLibF.h"
#pragma hdrstop

#include "VDSM200MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "FRAME_VdsDtctListF"
#pragma link "FRAME_VdsListF"
#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 "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 "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "FRAME_OpenMapF"
#pragma link "cxCalc"
#pragma link "dxSkinMcSkin"
#pragma resource "*.dfm"

TVDSM200M *VDSM200M = NULL;
//---------------------------------------------------------------------------
void TVDSM200M_MapCallback(TObject *ASender, const String AFunc, const String AArgs, const bool AFirst)
{
    try
    {
        if (!VDSM200M) return;
        VDSM200M->OpenMapCallback(ASender, AFunc, AArgs, AFirst);
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

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

    FUpdate= false;
    FTitle = Caption;//"VDS-검지기 관리";

    m_pGDC = FRAMEVdsDtctList1->TvList->DataController;

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

    FRAMEVdsList1->Column04->Visible = false;
    FRAMEVdsList1->Column05->Visible = false;
    FRAMEVdsList1->Column07->Visible = false;
    FRAMEVdsList1->Column08->Visible = false;
    FRAMEVdsList1->Column11->Visible = false;

    FRAMEVdsDtctList1->PnlTop->Visible = false;
    FRAMEVdsDtctList1->PnlBottom->Visible = false;
    FRAMEVdsDtctList1->ColumnSel->Visible = false;
    FRAMEVdsDtctList1->Column09->Visible = true;//검지차로

    FLayerIdx = LyrTp_Vds;
    FRAMEOpenMap1->LayerIdx = FLayerIdx;
    FRAMEOpenMap1->MapCallbackFunc = TVDSM200M_MapCallback;

    TvLink->OptionsView->NoDataToDisplayInfoText  = FrmLang->lblNoInfo->Caption;//"<VDS 검지기 링크구성정보>";

    EditMode = false;
}
//---------------------------------------------------------------------------

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

void __fastcall TVDSM200M::FormShow(TObject *Sender)
{
    Refresh();

    FRAMEOpenMap1->OpenMap();

    CbCTLR_MNGM_NMBR->Properties->Items->Clear();

    VdsCtlrManager->FLists.Lock();
    try
    {
        FOR_STL(TVdsCtlr*, pObj, VdsCtlrManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;

            String sId = String(pObj->VDS_CTLR_NMBR);  //관리번호
            String sNm = pObj->VDS_NM;            //위치
            CbCTLR_MNGM_NMBR->Properties->Items->Add("[" + sId + "] " + sNm);
        }
    }
    __finally
    {
        VdsCtlrManager->FLists.UnLock();
    }
    CbCTLR_MNGM_NMBR->ItemIndex = -1;

    APP_FillCode(CbType, "DTT");
    APP_FillCode(Cb_DTCT_DIR, "VCD");

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

void __fastcall TVDSM200M::FormInit()
{
    //제공구간목록이 초기화되기전에 이전정보를 지도에서 지워준다.
    if (FRAMEOpenMap1->MapStart)
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        try
        {
            int nSeq = 1;
            for (int ii = 0; ii < pGDC->RecordCount; ii++)
            {
                String sLinkId = pGDC->Values[ii][ColLink2->Index];

                sJs.printf(L"updateEditLink('%s', 0)", sLinkId.c_str());
                FRAMEOpenMap1->ExecScript(sJs);
            }
        }
        catch(...)
        {
        }
    }

    EdVdsCtrl->Text         = "";
	EdNmbr->Text = "";
    EdDtctId->Text = "";
	EdDtctNm->Text = "";

	CbType->ItemIndex = 0;
    Cb_DTCT_DIR->ItemIndex = 0;

    Se_DETECT_LANE->Value = 1;
    Se_ISTL_LANE->Value = 1;
    Se_MIN_TFVL->Value = 0;
    Se_MAX_TFVL->Value = 150;
    Se_MIN_OCPY_RATE->Value = 0.0;
    Se_MAX_OCPY_RATE->Value = 100.0;
    Se_MIN_SPED->Value = 0;
    Se_MAX_SPED->Value = 150;

    Cb_USE_YN->ItemIndex = 1;

    CMM_ClearGridTableView(TvLink);
    FNewDb = false;
}
//---------------------------------------------------------------------------

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

    FRAMEVdsList1->UpdateList();
    VdsCtlrManager->LoadFromDtctLinkDb();
    UpdateList();
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::UpdateList()
{
    FRAMEVdsDtctList1->UpdateList();
}
//---------------------------------------------------------------------------

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

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

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

    FRAMEVdsList1->OnCloseQuery(CanClose);
    FRAMEVdsDtctList1->OnCloseQuery(CanClose);
    FRAMEOpenMap1->OnCloseQuery(CanClose);
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::DisplayInfo(TVdsDtct* AObj)
{
    FormInit();

    if (!AObj) return;

    EdVdsCtrl->Text = String(AObj->VDS_CTLR_NMBR);
	EdNmbr->Text    = AObj->VDS_DTCT_NMBR;
    EdDtctId->Text  = AObj->VDS_DTCT_ID;
	EdDtctNm->Text  = AObj->VDS_DTCT_NM;

    CMM_SetComboBoxItem(CbCTLR_MNGM_NMBR, String(AObj->VDS_CTLR_NMBR));
    CMM_SetComboBoxItem(CbVDS_CMRA_NO,    String(AObj->VDS_CMRA_NO));
	APP_SetCode(CbType, AObj->DTCT_TYPE);
	APP_SetCode(Cb_DTCT_DIR, AObj->DTCT_DIR);

    Se_DETECT_LANE->Value   = AObj->DETECT_LANE;
    Se_ISTL_LANE->Value     = AObj->ISTL_LANE;
    Se_MIN_TFVL->Value      = AObj->MIN_TFVL;
    Se_MAX_TFVL->Value      = AObj->MAX_TFVL;
    Se_MIN_OCPY_RATE->Value = AObj->MIN_OCPY_RATE;
    Se_MAX_OCPY_RATE->Value = AObj->MAX_OCPY_RATE;
    Se_MIN_SPED->Value      = AObj->MIN_SPED;
    Se_MAX_SPED->Value      = AObj->MAX_SPED;

    Cb_USE_YN->Text = AObj->USE_YN;//(AObj->VDS_CTLR_NMBR);

    ChangeEditMode(3);

    DisplayLink(AObj);
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::DisplayLink(TVdsDtct* AObj)
{
    if (!AObj) return;

    CMM_ClearGridTableView(TvLink);

    String sLinkIds = "";
    try
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        TvLink->BeginUpdate();

        FOR_STL(TVdsDtctLink *, pObj, AObj->FLinks)
        {
            String LINK_ID = pObj->LINK_ID;
            nRow = pGDC->AppendRecord();
            pGDC->Values[nRow][ColLink2->Index] = LINK_ID;

            TItsLink *pLink = ItsLinkManager->FLists.Find(LINK_ID);
            if (pLink)
            {
                TItsNode *pNode;
                pGDC->Values[nRow][ColLink3->Index] = pLink->F_NODE_ID;
                pGDC->Values[nRow][ColLink5->Index] = pLink->T_NODE_ID;
                pNode = ItsNodeManager->FLists.Find(pLink->F_NODE_ID);
                if (pNode)
                {
                    pGDC->Values[nRow][ColLink4->Index] = pNode->NODE_NAME;
                }
                pNode = ItsNodeManager->FLists.Find(pLink->T_NODE_ID);
                if (pNode)
                {
                    pGDC->Values[nRow][ColLink6->Index] = pNode->NODE_NAME;
                }
                if (sLinkIds == "") sLinkIds = LINK_ID;
                else                sLinkIds = sLinkIds+","+LINK_ID;
            }
        }
    }
    __finally
    {
        TvLink->EndUpdate();
    }

    RefreshLink();

    if (sLinkIds != "")
    {
        sJs.printf(L"extentLayerObject(%d, '%s')", LyrTp_Traffic, sLinkIds.c_str());
        FRAMEOpenMap1->ExecScript(sJs);
    }
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::UpdateIcon()
{
    if (!FRAMEOpenMap1->MapStart) return;

    sJs.printf(L"removeLayerObject(%d)", FLayerIdx);
    FRAMEOpenMap1->ExecScript(sJs);

    String arrObj = "";
    String sTemp;

    VdsCtlrManager->FLists.Lock();
    try
    {
        FOR_STL(TVdsCtlr*, pObj, VdsCtlrManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;

            if (arrObj != "") arrObj += "|";

            sTemp.printf(L"%s,%s,%s,%.6f,%.6f,0,0,0,0", pObj->VDS_CTLR_NMBR.c_str(), pObj->VDS_CTLR_ID.c_str(), pObj->VDS_NM.c_str(), pObj->X_CRDN, pObj->Y_CRDN);
            arrObj += sTemp;
        }
    }
    __finally
    {
        VdsCtlrManager->FLists.UnLock();
        if (arrObj != "")
        {
            sJs.printf(L"addFacility(%d, '%s')", FLayerIdx, arrObj.c_str());
            FRAMEOpenMap1->ExecScript(sJs);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::BtnEditClick(TObject *Sender)
{
    if (BtnEdit->Caption == FrmLang->lblEdit->Caption)//"편집")
    {
        ChangeEditMode(0);
        FNewDb = false;
    }
    else
    {
        String sVdsCtrlId = EdVdsCtrl->Text;
        String sDtctId = EdNmbr->Text;

        ChangeEditMode(1);

        TVdsCtlr *pVds = VdsCtlrManager->FLists.Find(sVdsCtrlId);
        if (pVds)
        {
            TVdsDtct *pObj = pVds->FDtcts.Find(sDtctId);
            if (pObj)
            {
                CMM_SetGridRow(FRAMEVdsDtctList1->CxList, FRAMEVdsDtctList1->TvList, sDtctId, FRAMEVdsDtctList1->Column02->Index);
                DisplayInfo(pObj);
            }
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::ChangeEditMode(int AEdit)
{
    bool bGisEdit = true;
    bool bEnabled = false;

    switch(AEdit)
    {
    case 0: //편집버튼클릭
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = false;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = true;

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

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

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

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

    if (AEdit == 0 || AEdit == 2)
    {
        FRAMEVdsDtctList1->CxList->Enabled = false;
    }
    else
    {
        FRAMEVdsDtctList1->CxList->Enabled = true;
    }
    CbCTLR_MNGM_NMBR->Properties->ReadOnly = bEnabled;
    PnlEdit->Enabled = EditMode;
}
//---------------------------------------------------------------------------


void __fastcall TVDSM200M::BtnInsertClick(TObject *Sender)
{
    FormInit();
    //신규아이디를 얻어와서 화면을 초기화한다.
    String sId;
    int nNmbr, nId;

#if 1
    if (!VdsCtlrManager->GetNextVdsDtctId(nNmbr, nId))
    {
        Application->MessageBox(lblText1->Caption.c_str(),//L"새로운 검지기 번호를 생성하지 못하였습니다.\r\n프로그램 종료후에 다시 시도해 보세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
    sId = String(nNmbr);
#else
	sId = InputBox("검지기 번호", "신규 검지기 번호를 입력하세요(10Byte).", "검지기 번호" );

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

    VdsCtlrManager->FLists.Lock();
    try
    {
        FOR_STL(TVdsCtlr*, pObj, VdsCtlrManager->FLists)
        {
            TVdsDtct *pDb = pObj->FSubLists.Find(sId);
            if (pDb)
            {
                String sErr = FrmLang->lbIdErr->Caption + "[" + sId + "]";
                Application->MessageBox(sErr.c_str(),//("[" + sId + "]는 사용할 수 없는 검지기 번호 입니다.").c_str(),
                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
                return;
            }
        }
    }
    __finally
    {
        VdsCtlrManager->FLists.UnLock();
    }
#endif

    EdVdsCtrl->Text = "";
    EdNmbr->Text    = sId;

    ChangeEditMode(2);
    FNewDb = true;
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::BtnDeleteClick(TObject *Sender)
{
    int nIdx = m_pGDC->FocusedRecordIndex;
    if (nIdx < 0) return;

    String sId = EdNmbr->Text;

    if (sId.IsEmpty())
    {
        Application->MessageBox(lblText2->Caption.c_str(),//L"삭제할 검지기를 목록에서 선택하세요.\r\n목록에서 더블클릭하여 선택합니다.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    String sMsg;
    sMsg = lblText3->Caption + ": " + sId;//"검지기번호: " + sId;
    sMsg+= "\r\n" + lblText4->Caption;//"선택하신 검지기 정보를 삭제하시겠습니까?";

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

    TVdsDtct *pObj = NULL;
    try
    {
        VdsCtlrManager->FLists.Lock();
        FOR_STL(TVdsCtlr*, pVds, VdsCtlrManager->FLists)
        {
            pObj = pVds->FDtcts.Find(sId);
            if (pObj)
            {
                break;
            }
        }
    }
    __finally
    {
        VdsCtlrManager->FLists.UnLock();
    }

	if (pObj)
	{
		if (VdsCtlrManager->DeleteVdsDtct(pObj))
		{
            pObj->DEL_YN = "Y";
            UpdateList();
		}

        Application->MessageBox(lblText5->Caption.c_str(),//L"검지기 정보삭제\r\n검지기 정보를 삭제 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FUpdate = true;

        FormInit();
        ChangeEditMode(1);
	}
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::BtnSaveClick(TObject *Sender)
{
    TVdsCtlr *pVds;
    TVdsDtct *pObj;

    String sId     = EdNmbr->Text;
    String sCtrlId = ITSUtil_GetCode(CbCTLR_MNGM_NMBR->Text);   // 제어기 관리 번호
    String sCmraNo = ITSUtil_GetCode(CbVDS_CMRA_NO->Text);      // 카메라 번호

    pVds = VdsCtlrManager->FLists.Find(sCtrlId);

    if (!pVds                              ||
        EdDtctId->Text.Trim().IsEmpty()    ||
//        EdVdsCtrl->Text.Trim().IsEmpty()   ||
        EdNmbr->Text.Trim().IsEmpty()      ||
        EdDtctNm->Text.Trim().IsEmpty()    ||
        CbCTLR_MNGM_NMBR->ItemIndex < 0    ||
        CbVDS_CMRA_NO->ItemIndex    < 0    )
	{
        Application->MessageBox(FrmLang->lblCnfm->Caption.c_str(),//L"★항목은 필수 입력 항목입니다.\r\n모두 입력후 진행해 주세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    if (!FNewDb)
    {
        //수정모드일때 컨트롤러가 다르다면 신규로 처리한다.
        if (EdVdsCtrl->Text != sCtrlId)
        {
            TVdsCtlr *pTmpVds = VdsCtlrManager->FLists.Find(EdVdsCtrl->Text);
            if (pTmpVds)
            {
                pTmpVds->FDtcts.Remove(sId);
            }
            FNewDb = true;
        }
    }

    if (FNewDb)
        pObj = new TVdsDtct();
    else
        pObj = pVds->FDtcts.Find(sId);

    if (pObj)
    {
        pObj->VDS_DTCT_NMBR = sId;
        pObj->VDS_DTCT_ID   = EdDtctId->Text.Trim();
        pObj->VDS_DTCT_NM   = EdDtctNm->Text.Trim();
        pObj->VDS_CTLR_NMBR = sCtrlId.ToIntDef(0);
        pObj->VDS_CMRA_NO   = sCmraNo.ToIntDef(0);
        pObj->DTCT_TYPE     = APP_GetCode(CbType);
        pObj->DTCT_DIR      = APP_GetCode(Cb_DTCT_DIR);
        pObj->DETECT_LANE   = Se_DETECT_LANE->Value;
        pObj->ISTL_LANE     = Se_ISTL_LANE->Value;
        pObj->SPED_CLCT_YN  = Chk_SPED_CLCT_YN->Checked ? "Y" : "N";
        pObj->TFVL_CLCT_YN  = Chk_TFVL_CLCT_YN->Checked ? "Y" : "N";
        pObj->OCPY_CLCT_YN  = Chk_OCPY_CLCT_YN->Checked ? "Y" : "N";
        pObj->MAX_TFVL      = Se_MAX_TFVL->Value;
        pObj->MIN_TFVL      = Se_MIN_TFVL->Value;
        pObj->MAX_OCPY_RATE = Se_MAX_OCPY_RATE->Value;
        pObj->MIN_OCPY_RATE = Se_MIN_OCPY_RATE->Value;
        pObj->MAX_SPED      = Se_MAX_SPED->Value;
        pObj->MIN_SPED      = Se_MIN_SPED->Value;
        pObj->USE_YN        = Cb_USE_YN->Text.Trim();
        pObj->DEL_YN        = "N";
        pObj->MEM_DEL       = "N";

        pObj->FLinks.RemoveAll();

        try {
            TvLink->BeginUpdate();
            for (int ii = 0; ii < TvLink->DataController->RecordCount; ii++)
            {
                String sLinkId = TvLink->DataController->Values[ii][ColLink2->Index];

				TVdsDtctLink *pObjLnk = new TVdsDtctLink();

                pObjLnk->VDS_CTLR_NMBR = pObj->VDS_CTLR_NMBR;
                pObjLnk->VDS_DTCT_NMBR = pObj->VDS_DTCT_NMBR;
                pObjLnk->LINK_ID       = sLinkId;

				pObj->FLinks.Push(pObjLnk->LINK_ID, pObjLnk);

                pObjLnk->MEM_DEL   = "N";
            }
        }
        __finally
        {
            TvLink->EndUpdate();
        }

        bool bResult;
        bResult = VdsCtlrManager->SaveVdsDtct(pObj);

        if (bResult)
        {
            Application->MessageBox(FrmLang->lblDbSave->Caption.c_str(),//L"VDS-검지기 정보저장\r\nVDS-검지기 정보를 저장 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

            if (FNewDb)
            {
                pVds->FDtcts.Push(pObj->VDS_DTCT_NMBR, pObj);
            }

            FUpdate = true;

            UpdateList();
            CMM_SetGridRow(FRAMEVdsDtctList1->CxList, FRAMEVdsDtctList1->TvList, sId, FRAMEVdsDtctList1->Column02->Index);

            int nRow = FRAMEVdsDtctList1->TvList->DataController->FocusedRecordIndex;
            if( nRow <= -1 )
                return;

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

void __fastcall TVDSM200M::RefreshLink()
{
    if (!FRAMEOpenMap1->MapStart) return;

    try
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        TvLink->BeginUpdate();
        try
        {
            int nSeq = 1;
            for (int ii = 0; ii < pGDC->RecordCount; ii++)
            {
                pGDC->Values[ii][ColSeq->Index] = nSeq;
                String sLinkId = pGDC->Values[ii][ColLink2->Index];

                sJs.printf(L"updateEditLink('%s', %d)", sLinkId.c_str(), nSeq);
                FRAMEOpenMap1->ExecScript(sJs);
                if (nSeq++ > ITSMAP_MAX_DISPCOLOR) nSeq = 1;
            }
        }
        catch(...)
        {
        }
    }
    __finally
    {
        TvLink->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::BtnLinkDelClick(TObject *Sender)
{
    int nSelRows = TvLink->Controller->SelectedRowCount;
    if (nSelRows <= 0)
    {
        Application->MessageBox(lblText13->Caption.c_str(),//L"삭제를 원하는 구간을 목록에서 선택하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
    for (int ii = 0; ii < nSelRows; ii++)
    {
        int nSelIdx = TvLink->Controller->SelectedRows[ii]->RecordIndex;

        String sLinkId = TvLink->DataController->Values[nSelIdx][ColLink2->Index];
        sJs.printf(L"updateEditLink('%s', 0)", sLinkId.c_str());
        FRAMEOpenMap1->ExecScript(sJs);
    }
    TvLink->Controller->DeleteSelection();

    RefreshLink();
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::BtnLinkAddClick(TObject *Sender)
{
    if (EdLinkId->Text.IsEmpty()) return;

    String sNewId = EdLinkId->Text;
    bool bFound = false;
    try
    {
        int nRow;
        TcxDataController *pGDC = TvLink->DataController;
        TvLink->BeginUpdate();

        for (int ii = 0; ii < pGDC->RecordCount; ii++)
        {
            String sLinkId = pGDC->Values[ii][ColLink2->Index];
            if (sNewId == sLinkId)
            {
                bFound = true;
                break;
            }
        }
        if (bFound)
        {
            Application->MessageBox(cxLabel10->Caption.c_str(), //L"이미 등록되어 있는 링크구간 입니다.\r\n링크 구간은 중복해서 등록 할 수 없습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
            return;
        }

        nRow = pGDC->AppendRecord();
        pGDC->Values[nRow][ColLink2->Index] = sNewId;
        TItsLink *pLink = ItsLinkManager->FLists.Find(sNewId);
        if (pLink)
        {
            TItsNode *pNode;
            pGDC->Values[nRow][ColLink3->Index] = pLink->F_NODE_ID;
            pGDC->Values[nRow][ColLink5->Index] = pLink->T_NODE_ID;
            pNode = ItsNodeManager->FLists.Find(pLink->F_NODE_ID);
            if (pNode)
            {
                pGDC->Values[nRow][ColLink4->Index] = pNode->NODE_NAME;
            }
            pNode = ItsNodeManager->FLists.Find(pLink->T_NODE_ID);
            if (pNode)
            {
                pGDC->Values[nRow][ColLink6->Index] = pNode->NODE_NAME;
            }
        }
    }
    __finally
    {
        TvLink->EndUpdate();
    }

    RefreshLink();
}
//---------------------------------------------------------------------------
void __fastcall TVDSM200M::TvLinkCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift, bool &AHandled)
{
    if (!FRAMEOpenMap1->MapStart) return;

	if (!ACellViewInfo) return;
	int nRow = TvLink->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    String sLinkId = TvLink->DataController->Values[nRow][ColLink2->Index];
    sJs.printf(L"extentLayerObject(%d, '%s')", LyrTp_Traffic, sLinkId.c_str());
    FRAMEOpenMap1->ExecScript(sJs);
}
//---------------------------------------------------------------------------

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

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

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

    int nMemPtr = FRAMEVdsList1->TvList->DataController->Values[nRow][FRAMEVdsList1->Column99->Index];
    TVdsCtlr* pObj = (TVdsCtlr*)nMemPtr;
    try {
        sJs.printf(L"selectLayerObject(%d, '%s', %d)", FLayerIdx, pObj->VDS_CTLR_NMBR.c_str(), FRAMEOpenMap1->MapZoom);
        FRAMEOpenMap1->ExecScript(sJs);
    } catch(...) { }
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::UpdateEditLink()
{
    if (!FRAMEOpenMap1->MapStart) return;

    TItsNode* pNode;
    String    STRT_NM;
    String    END_NM;

    try
    {
        ItsLinkManager->FLists.Lock();
        try
        {
            FOR_STL(TItsLink*, pLink, ItsLinkManager->FLists)
            {
                if (pLink->DEL_YN == "Y")   continue;

#if 0
                pVrtx = pLink->Vrtxs.Find(nZoom);
                if (!pVrtx) continue;

                pNode = ItsNodeManager->FLists.Find(pLink->F_NODE_ID);
                if (pNode) STRT_NM = pNode->NODE_NAME; else STRT_NM = " ";
                pNode = ItsNodeManager->FLists.Find(pLink->T_NODE_ID);
                if (pNode) END_NM = pNode->NODE_NAME; else END_NM = " ";

                sJs.printf(L"addEditLink('%s', '%s', '%s', '%s', '%s', '%s')",
                    pLink->LINK_ID.c_str(),
                    pLink->ROAD_NAME.c_str(),
                    STRT_NM.c_str(),
                    END_NM.c_str(),
                    pVrtx->X_CRDN_ARR.c_str(),
                    pVrtx->Y_CRDN_ARR.c_str());

                FRAMEOpenMap1->ExecScript(sJs);
#else
                if (pLink->IsVertex)
                {
                    pNode = ItsNodeManager->FLists.Find(pLink->F_NODE_ID);
                    if (pNode) STRT_NM = pNode->NODE_NAME; else STRT_NM = " ";
                    pNode = ItsNodeManager->FLists.Find(pLink->T_NODE_ID);
                    if (pNode) END_NM = pNode->NODE_NAME; else END_NM = " ";

                    sJs.printf(L"addEditLink('%s', '%s', '%s', '%s', '%s', '%s')",
                        pLink->LINK_ID.c_str(),
                        pLink->ROAD_NAME.c_str(),
                        STRT_NM.c_str(),
                        END_NM.c_str(),
                        pLink->X_CRDN_ARR.c_str(),
                        pLink->Y_CRDN_ARR.c_str());

                    FRAMEOpenMap1->ExecScript(sJs);
                }
#endif
            }
        }
        __finally
        {
            ItsLinkManager->FLists.UnLock();
        }
        FRAMEOpenMap1->ExecScript("makeEditLinkLayer()");
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::OpenMapCallback(TObject *ASender, const String AFunc, const String AArgs, const bool AFirst)
{
    try
    {
        if (AFirst)
        {
            //지도를 편집모드로 변경
            sJs.printf(L"setEditMode(%d, 1)", FLayerIdx);
            FRAMEOpenMap1->ExecScript(sJs);

            //편집레이어 생성
            FRAMEOpenMap1->ExecScript("initEditLayer()");

            //배경링크레이어 생성
            UpdateEditLink();

            //시설물아이콘 등록
            UpdateIcon();
            sJs.printf(L"extentLayer(%d)", FLayerIdx);
            FRAMEOpenMap1->ExecScript(sJs);
            return;
        }

        if (AFunc.Pos("onlinkclick"))
        {
            TStringList *pStringList = new TStringList;
            pStringList->CommaText = AArgs;

            try
            {
                String sLyrType = pStringList->Strings[0];
                String sLinkId  = pStringList->Strings[1];
                if (EditMode)
                {
                    EdLinkId->Text = sLinkId;
                }
            }
            catch(Exception &e)
            {
            }
            delete pStringList;
        }
    }
    catch(Exception &exception)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::ChkViewIconClick(TObject *Sender)
{
    if (!FRAMEOpenMap1->MapStart) return;
    sJs.printf(L"showLayerText(%d, %d)", FLayerIdx, (ChkViewIcon->Checked) ? 1: 0);
    FRAMEOpenMap1->ExecScript(sJs);
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::ColSeqCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
	if (AViewInfo->GridRecord->RecordIndex < 0)
		return;
	if (VarIsNull(AViewInfo->Value))
		return;

	try
	{
		int nIdx = AViewInfo->Value;
		if (nIdx < 0)
			return;

		ACanvas->Brush->Color = ITSMap_GetDisplayColor(nIdx);
		ACanvas->Font->Color  = ACanvas->Brush->Color;
	}
	catch(...)
	{
	}
}
//---------------------------------------------------------------------------

void __fastcall TVDSM200M::CbCTLR_MNGM_NMBRPropertiesChange(TObject *Sender)
{
    CbVDS_CMRA_NO->Properties->Items->Clear();

    String sId     = EdNmbr->Text;
    String sCtrlId = ITSUtil_GetCode(CbCTLR_MNGM_NMBR->Text);   // 제어기 관리 번호

    TVdsCtlr *pVds;
    pVds = VdsCtlrManager->FLists.Find(sCtrlId);
    if (!pVds) return;
    FOR_STL(TVdsCmra*, pCmra, pVds->FCmras)
    {
        String sId = String(pCmra->VDS_CMRA_NO);
        String sNm = pCmra->VDS_CMRA_NM;
        CbVDS_CMRA_NO->Properties->Items->Add("[" + sId + "] " + sNm);
    }
    CbVDS_CMRA_NO->ItemIndex = 0;
}
//---------------------------------------------------------------------------

