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

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

#include "BDS0010MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxSplitter"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "FRAME_BlackBoxListF"
#pragma resource "*.dfm"

TBDS0010M *BDS0010M = NULL;
//---------------------------------------------------------------------------

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

    FUpdate= false;
    FTitle = "블랙박스 단말기 관리";

    FRAMEBlackBoxList1->TvList->FilterRow->Visible = false;
    FRAMEBlackBoxList1->PnlTop->Visible = false;
    FRAMEBlackBoxList1->PnlBottom->Visible = false;
    FRAMEBlackBoxList1->ColumnSel->Visible = false;

    //FRAMEBlackBoxList1->Column13->Visible = true;

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

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

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

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

/*
 * form 초기화
 *
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TBDS0010M::FormInit()
{
    EdId->Text          = "";
    BDS_MNGM_NMBR->Text = "";
    OPNC_NMBR->Text     = "";
    MDM_NMBR->Text      = "";
    USIM_NMBR->Text     = "";
    VHCL_NMBR->Text     = "";
    OWNR_NM->Text       = "";
    PRCT_NM->Text       = "";

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

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

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

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

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

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

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

void __fastcall TBDS0010M::DisplayInfo(TBlackBox* AObj)
{
    FormInit();

    if (!AObj) return;

    EdId->Text          = AObj->BDS_MNGM_NMBR;
    BDS_MNGM_NMBR->Text = AObj->BDS_MNGM_NMBR;
    OPNC_NMBR->Text     = AObj->OPNC_NMBR;
    MDM_NMBR->Text      = AObj->MDM_NMBR;
    USIM_NMBR->Text     = AObj->USIM_NMBR;
    VHCL_NMBR->Text     = AObj->VHCL_NMBR;
    OWNR_NM->Text       = AObj->OWNR_NM;
    PRCT_NM->Text       = AObj->PRCT_NM;

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

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

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

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

        TBlackBox *pObj = BlackBoxManager->FLists.Find(sId.ToIntDef(0));
        if (pObj)
        {
            CMM_SetGridRow(FRAMEBlackBoxList1->CxList, FRAMEBlackBoxList1->TvList, sId, FRAMEBlackBoxList1->Column01->Index);
            DisplayInfo(pObj);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TBDS0010M::ChangeEditMode(int AEdit)
{
    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;//데이터 편집 취소";
        }
        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;
        }
        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;//데이터 편집 취소";
        }
        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;
        }
        break;
    }

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


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

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

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

    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;
	}
    try
    {
        int nId = sId.ToInt();
    }
    catch(Exception &e)
    {
        Application->MessageBox(L"관리번호는 숫자이어야 합니다.", FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
    }

    TBlackBox *pDb = (TBlackBox *)BlackBoxManager->FLists.Find(sId.ToIntDef(0));
    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;
    }
#endif

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

void __fastcall TBDS0010M::BtnDeleteClick(TObject *Sender)
{
    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;

	TBlackBox *pObj = BlackBoxManager->FLists.Find(sId.ToIntDef(0));
	if (pObj)
	{
        //pObj->DEL_USER_ID = g_pLOGIN->sUserId;                      //변경자 명
        //pObj->DEL_DT      = Now().FormatString("yyyymmddhhnnss");   //변경 일시
		if (BlackBoxManager->DeleteBlackBox(pObj))
		{
            pObj->MEM_DEL = "Y";
            FRAMEBlackBoxList1->UpdateList();
		}

#if 0
		TItsFacility *pFacility = ItsFacilityManager->FLists.Find(sId);
        if (pFacility)
        {
            FUpdate = true;
        }
#endif
        FUpdate = true;

        Application->MessageBox(L"블랙박스 단말기 정보삭제\r\n블랙박스 단말기 정보를 삭제 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

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

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

    String sId = EdId->Text;

    TBlackBox *pObj;
    if (FNewDb)
        pObj = new TBlackBox();
    else
        pObj = BlackBoxManager->FLists.Find(sId.ToIntDef(0));

    if (pObj)
    {
        pObj->BDS_MNGM_NMBR = sId.ToIntDef(0);
        pObj->OPNC_NMBR     = OPNC_NMBR->Text.Trim();
        pObj->MDM_NMBR      = MDM_NMBR->Text.Trim();
        pObj->USIM_NMBR     = USIM_NMBR->Text.Trim();
        pObj->VHCL_NMBR     = VHCL_NMBR->Text.Trim();
        pObj->OWNR_NM       = OWNR_NM->Text.Trim();
        pObj->PRCT_NM       = PRCT_NM->Text.Trim();

        pObj->MEM_DEL       = "N";

        bool bResult;
        if (FNewDb)
        {
            //pObj->ADTN_USER_ID = g_pLOGIN->sUserId;                      //변경자 명
            //pObj->ADTN_DT      = Now().FormatString("yyyymmddhhnnss");   //변경 일시
            bResult = BlackBoxManager->InsertBlackBox(pObj);
            if (bResult)
            {
                BlackBoxManager->FLists.Push(sId.ToIntDef(0), pObj);
            }
		}
        else
		{
            //pObj->CHNG_USER_ID = g_pLOGIN->sUserId;                      //변경자 명
            //pObj->CHNG_DT      = Now().FormatString("yyyymmddhhnnss");   //변경 일시
            bResult = BlackBoxManager->UpdateBlackBox(pObj);
		}

        if (bResult)
        {
            Application->MessageBox(FrmLang->lblDbSave->Caption.c_str(),//L"블랙박스 단말기 정보저장\r\n블랙박스 단말기 정보를 저장 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

            FUpdate = true;

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

