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

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

#include "VMSM210MF.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 "cxSplitter"
#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 "FRAME_VmsIfscListF"
#pragma link "FRAME_VmsListF"
#pragma link "cxDropDownEdit"
#pragma resource "*.dfm"

TVMSM210M *VMSM210M = NULL;
//---------------------------------------------------------------------------

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

    FUpdate= false;
    FTitle = Caption;//"VMS 정보제공구간 설정";

    ColLink8->Visible = false;
    ColLink9->Visible = false;
    Panel7->Visible = false;

    //FRAMEVmsList1->Column02->Visible = false;
    FRAMEVmsList1->PnlTop->Visible = false;
    FRAMEVmsList1->PnlBottom->Visible = false;
    FRAMEVmsList1->ColumnSel->Visible = false;

    FRAMEVmsIfscList1->PnlTop->Visible = false;
    FRAMEVmsIfscList1->PnlBottom->Visible = false;
    FRAMEVmsIfscList1->ColumnSel->Visible = false;
    FRAMEVmsIfscList1->TvList->OptionsSelection->MultiSelect = true;
    FRAMEVmsIfscList1->TvList->OptionsSelection->CellSelect = false;

    m_pGDC = FRAMEVmsList1->TvList->DataController;

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

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

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

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

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TVMSM210M::FormInit()
{
	EdNmbr->Text = "";
	EdId->Text = "";

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

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

    FRAMEVmsList1->UpdateList();
    FRAMEVmsIfscList1->UpdateList();
}
//---------------------------------------------------------------------------

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

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

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

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

void __fastcall TVMSM210M::DisplayInfo(TVmsCtlr* AObj)
{
    FormInit();

    if (!AObj) return;

	EdNmbr->Text  = String(AObj->VMS_CTLR_NMBR);
	EdId->Text = AObj->VMS_CTLR_ID;

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

        int ii = 0;
        FOR_STL(TVmsIfscRltn *, pObj, AObj->FIfscRltn)
        {
            nRow = pGDC->AppendRecord();
            pGDC->Values[nRow][ColLink1->Index] = String(ii+1);
            pGDC->Values[nRow][ColLink2->Index] = String(pObj->VMS_IFSC_ID);
            TVmsIfsc *pIfsc = VmsIfscManager->FLists.Find(pObj->VMS_IFSC_ID);
            if (pIfsc)
            {
                pGDC->Values[nRow][ColLink3->Index] = pIfsc->VMS_IFSC_NM;
                pGDC->Values[nRow][ColLink7->Index] = pIfsc->AXIS_YN;
            }
            else
            {
                pGDC->Values[nRow][ColLink3->Index] = "-???-";
                pGDC->Values[nRow][ColLink7->Index] = "N";
            }
            pGDC->Values[nRow][ColLink8->Index] = pObj->CNGS_CNFM_YN;
            pGDC->Values[nRow][ColLink9->Index] = String(pObj->CNGS_CNFM_SPED);

            ii++;
        }
    }
    __finally
    {
        TvLink->EndUpdate();
    }

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

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

        TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sId);
        if (pObj)
        {
            CMM_SetGridRow(FRAMEVmsList1->CxList, FRAMEVmsList1->TvList, sId, FRAMEVmsList1->Column01->Index);
            DisplayInfo(pObj);
        }
    }
}
//---------------------------------------------------------------------------

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

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

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

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

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

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

    //PnlEdit->Enabled = EditMode;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM210M::BtnSaveClick(TObject *Sender)
{
    String sNmbr = EdNmbr->Text;
    String sId   = EdId->Text;
    int    nNmbr = sNmbr.ToInt();

    TVmsCtlr *pVms;
    pVms = VmsCtlrManager->FLists.Find(sNmbr);
    if (!pVms) return;

    int nOrgCnt = pVms->FIfscRltn.Size();
    int nSrcCnt = TvLink->DataController->RecordCount;
    if (nOrgCnt == 0 && nSrcCnt == 0)
    {
        Application->MessageBox(lblText1->Caption.c_str(),//L"VMS정보제공구간 설정\r\n저장할 데이터가 없습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    if (Application->MessageBox(lblText2->Caption.c_str(),//L"VMS정보제공구간 설정\r\nVMS정보제공구간 설정 정보를 저장하시겠습니까?",
                                FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

    bool bResult = false;
    try
    {
        pVms->FIfscRltn.RemoveAll();

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

                TVmsIfscRltn *pObj = new TVmsIfscRltn();
                if (pObj)
                {
                    pObj->VMS_CTLR_NMBR  = pVms->VMS_CTLR_NMBR;
                    pObj->VMS_IFSC_ID    = sIfscId.ToInt();
                    pObj->CNGS_CNFM_YN   = VarToStr(TvLink->DataController->Values[ii][ColLink8->Index]);
                    pObj->CNGS_CNFM_SPED = VarToStr(TvLink->DataController->Values[ii][ColLink9->Index]).ToIntDef(5);

                    pObj->DSPL_PRRT = nPrrt++;
                    pVms->FIfscRltn.Push(pObj->DSPL_PRRT, pObj);
                }
            }
        }
        __finally
        {
            TvLink->EndUpdate();
        }
        bResult = VmsCtlrManager->SaveIfscRltn(pVms);
    }
    catch(Exception &e)
    {
        throw Exception(String(e.ClassName()) + e.Message);
    }

    if (bResult)
    {
        Application->MessageBox(lblText3->Caption.c_str(),//L"VMS정보제공구간 설정\r\nVMS정보제공구간 설정 정보를 저장 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FUpdate = true;

        CMM_SetGridRow(FRAMEVmsList1->CxList, FRAMEVmsList1->TvList, sId, FRAMEVmsList1->Column01->Index);
        DisplayInfo(pVms);

        POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_14, 0);
    }
}
//---------------------------------------------------------------------------

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

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

void __fastcall TVMSM210M::UpdateIfscRltnSeq()
{
    try {
        TvLink->BeginUpdate();
        for (int ii = 0; ii < TvLink->DataController->RecordCount; ii++)
        {
            TvLink->DataController->Values[ii][ColLink1->Index] = String(ii+1);
        }
    }
    __finally
    {
        TvLink->EndUpdate();
    }
}
//---------------------------------------------------------------------------

bool __fastcall TVMSM210M::FindIfscRltnInfo(String AIfscId)
{
    try {
        TvLink->BeginUpdate();
        for (int ii = 0; ii < TvLink->DataController->RecordCount; ii++)
        {
            String sIfscId = VarToStr(TvLink->DataController->Values[ii][ColLink2->Index]);
            if (sIfscId == AIfscId) return true;
        }
    }
    __finally
    {
        TvLink->EndUpdate();
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM210M::BtnListAddClick(TObject *Sender)
{
    TcxGridTableView *pSrcList = FRAMEVmsIfscList1->TvList;
    TcxGridTableView *pDstList = TvLink;
    int nSelRows = pSrcList->Controller->SelectedRowCount;
    if (nSelRows <= 0)
    {
        return;
    }

    try
    {
        TcxGridDataController *pGDC = pDstList->DataController;
        try
        {
            for (int ii = 0; ii < nSelRows; ii++)
            {
                int nSelIdx = pSrcList->Controller->SelectedRows[ii]->RecordIndex;

                String sIfscId = VarToStr(pSrcList->DataController->Values[nSelIdx][FRAMEVmsIfscList1->Column01->Index]);
                String sIfscNm = VarToStr(pSrcList->DataController->Values[nSelIdx][FRAMEVmsIfscList1->Column02->Index]);

                if (FindIfscRltnInfo(sIfscId)) continue;

                int nRow = pGDC->AppendRecord();

                pGDC->Values[nRow][ColLink2->Index] = sIfscId;
                pGDC->Values[nRow][ColLink3->Index] = sIfscNm;

                String sAxisYn = VarToStr(pSrcList->DataController->Values[nSelIdx][FRAMEVmsIfscList1->Column05->Index]);
                pGDC->Values[nRow][ColLink7->Index] = sAxisYn;
                pGDC->Values[nRow][ColLink8->Index] = (sAxisYn == "Y") ? "N" : "Y";
                pGDC->Values[nRow][ColLink9->Index] = "5";
            }
        }
        catch(...)
        {
        }
    }
    __finally
    {
        UpdateIfscRltnSeq();
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM210M::BtnListDeleteClick(TObject *Sender)
{
    TcxGridTableView *pSrcList = TvLink;
    int nFocused = pSrcList->Controller->FocusedRecordIndex;

    int nSelRows = pSrcList->Controller->SelectedRowCount;
    if (nSelRows <= 0)
    {
        return;
    }

    try
    {
        TcxGridDataController *pGDC = pSrcList->DataController;
        pSrcList->BeginUpdate();
        try
        {
            pSrcList->Controller->DeleteSelection();

            int nDataCnt = pSrcList->DataController->RecordCount;
            if (nDataCnt <= nFocused)
                nFocused = nDataCnt - 1;

            pSrcList->Controller->ClearSelection();
            if (nFocused >= 0)
            {
                pSrcList->Controller->FocusedRowIndex = nFocused;
                pSrcList->ViewData->Records[nFocused]->Focused = true;
                pSrcList->ViewData->Records[nFocused]->Selected = true;
            }
            //CxLink->SetFocus();
        }
        catch(...)
        {
        }
    }
    __finally
    {
        pSrcList->EndUpdate();
        UpdateIfscRltnSeq();
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM210M::FRAMEVmsList1TvListFocusedRecordChanged(TcxCustomGridTableView *Sender,
          TcxCustomGridRecord *APrevFocusedRecord, TcxCustomGridRecord *AFocusedRecord,
          bool ANewItemRecordFocusingChanged)
{
	if (!AFocusedRecord) return;
	int nRow = FRAMEVmsList1->TvList->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

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

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

void __fastcall TVMSM210M::BtnSaveCngsSpdClick(TObject *Sender)
{
    String sMsg;
    sMsg = "";
    sMsg+= "\r\n제공구간 정체폼 정체판정 속도정보를 전체 제공구간에 동일하게 적용 하시겠습니까?";//lblText10->Caption;//"제공구간 속도정보를 전체 제공구간에 동일하게 적용 하시겠습니까?";

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

    if (EdCngsSpd->Text.Trim() == "" || EdCngsSpd->Text.Trim() == "0")
    {
        Application->MessageBox(L"속도정보가 정확하지 않습니다.\r\n속도정보를 확인하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }

    int CngsSpd = EdCngsSpd->Text.ToIntDef(0);
    try
    {
        if (VmsCtlrManager->UpdateIfscCngsSpeedInfo(CngsSpd))
        {
            FUpdate = true;

            FOR_STL(TVmsCtlr*, pTmpObj, VmsCtlrManager->FLists)
            {
                FOR_STL(TVmsIfscRltn *, pLink, pTmpObj->FIfscRltn)
                {
                    pLink->CNGS_CNFM_SPED = CngsSpd;
                }
            }

            TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(EdNmbr->Text);
            if (pObj)
            {
                DisplayInfo(pObj);
            }

            Application->MessageBox(L"제공구간 정체폼 정체판정 속도정보저장\r\n제공구간 정체폼 정체판정 속도 정보를 전체 제공구간에 적용 하였습니다.",//lblText11->Caption.c_str(),//L"제공구간 속도정보저장\r\n제공구간 속도 정보를 전체 제공구간에 적용 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
    }
    __finally
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM210M::ColLink7CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    int nRecordIdx = AViewInfo->GridRecord->RecordIndex;
    if (nRecordIdx < 0)
    {
        return;
    }

    try
    {
        int nItemIdx = AViewInfo->Item->Index;
    	if (VarIsNull(AViewInfo->GridRecord->DisplayTexts[nItemIdx])) return;

        String sData = AViewInfo->GridRecord->DisplayTexts[nItemIdx];
        if (sData == "Y")
        {
            ACanvas->Canvas->Brush->Color = clLime;
        }
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM210M::ColLink8CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    int nRecordIdx = AViewInfo->GridRecord->RecordIndex;
    if (nRecordIdx < 0)
    {
        return;
    }

    try
    {
        int nItemIdx = AViewInfo->Item->Index;
    	if (VarIsNull(AViewInfo->GridRecord->DisplayTexts[nItemIdx])) return;

        String sData = AViewInfo->GridRecord->DisplayTexts[nItemIdx];
        if (sData == "Y")
        {
            ACanvas->Canvas->Brush->Color = clLime;
        }
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

