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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "FrmResourceF.h"
#include "ITSDbF.h"
#include "AppGlobalF.h"
#include "ITSLangTransF.h"
#pragma hdrstop

#include "FRAME_FailHndlF.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCalc"
#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 "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma resource "*.dfm"
//TFRAMEFailHndl *FRAMEFailHndl;
//---------------------------------------------------------------------------
__fastcall TFRAMEFailHndl::TFRAMEFailHndl(TComponent* Owner)
    : TFrame(Owner)
{
    ITSSkin_Load((TForm*)this);

    FCode = new TFacilityCodeManager();
    //FCode->LoadHndlTypeDb();

    TvList1->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<장애 장비 유형 정보가 없습니다>";

    m_pGDC1 = TvList1->DataController;

    EdId1->Enabled = false;

    FormClear1();
    SelListData1();
    ChangeButtonType1(1);

    //BtnSearchClick((TObject*)BtnSearch);
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::FormClear1()
{
    m_enJob1 = enJobNone;

    EdId1->Clear();
    EdKName1->Clear();
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::ChangeButtonType1(int nBtnType)
{
    if (nBtnType == 1)
    {
        BtnSave1->Visible = false;
        BtnCancel1->Visible = false;

        BtnInsert1->Visible = true;
        //if (TvList1->ViewData->RecordCount > 0)
        if (TvList1->ViewData->RecordCount >= 0)
        {
            BtnEdit1->Visible = true;
            BtnDelete1->Visible = true;
        }
        else
        {
            BtnEdit1->Visible = false;
            BtnDelete1->Visible = false;
        }

        BtnSearch->Enabled = true;
        CxList1->Enabled = true;
        cxGroupBox1->Enabled = false;
    }
    else
    {
        BtnSave1->Visible = true;
        BtnCancel1->Visible = true;

        BtnInsert1->Visible = false;
        BtnEdit1->Visible = false;
        BtnDelete1->Visible = false;

        BtnSearch->Enabled = false;
        CxList1->Enabled = false;
        cxGroupBox1->Enabled = true;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::SelListData1()
{
    FCode->LoadHndlTypeDb();

    CMM_ClearGridTableView(TvList1);

    int nRow = 0;
    try
    {
        TvList1->BeginUpdate();

        FOR_STL(TFacilityHndlType *, pCode, FCode->FHndlLists)
        {
            nRow = m_pGDC1->AppendRecord();

            m_pGDC1->Values[nRow][MColumn01->Index] = "-";
            m_pGDC1->Values[nRow][MColumn02->Index] = pCode->FAIL_HNDL_CD;
            m_pGDC1->Values[nRow][MColumn03->Index] = pCode->FAIL_HNDL_CD_NM;

            m_pGDC1->Values[nRow][MColumn98->Index] = (int)pCode;
        }
    }
    __finally
    {
        TvList1->EndUpdate();
        TvList1->DataController->GotoFirst();
        TvList1->DataController->FocusedRecordIndex = 0;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::OnCloseQuery(bool &CanClose)
{
    //SaveData();

    try {
        if (FCode) delete FCode;
        FCode = NULL;
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::DisplayListData1()
{
    int ii;

    FormClear1();

    if (TvList1->ViewData->RecordCount <= 0) return;
    int nIndex = m_pGDC1->FocusedRecordIndex;
    if (nIndex < 0) return;

    int nMemPtr = m_pGDC1->Values[nIndex][MColumn98->Index];
    if (nMemPtr == 0) return;

    TFacilityHndlType *pCode = (TFacilityHndlType *)nMemPtr;

    try
    {
        EdId1->Text    = pCode->FAIL_HNDL_CD;
        EdKName1->Text = pCode->FAIL_HNDL_CD_NM;
    }
    catch(Exception &e)
    {
        Application->MessageBox((e.Message + " - " +__FILE__+ " - " +__LINE__).c_str(), Caption.c_str(), MB_OK);
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::TvList1FocusedRecordChanged(TcxCustomGridTableView *Sender,
          TcxCustomGridRecord *APrevFocusedRecord, TcxCustomGridRecord *AFocusedRecord,
          bool ANewItemRecordFocusingChanged)
{
    DisplayListData1();
    //SelListData2();
    //ChangeButtonType2(1);
}
//---------------------------------------------------------------------------
void __fastcall TFRAMEFailHndl::BtnCancel1Click(TObject *Sender)
{
    TcxButton *pBtn = (TcxButton*)Sender;
    if (pBtn->Tag == 0)
    {
        ChangeButtonType1(1);
        m_enJob1 = enJobNone;
        DisplayListData1();
    }
}
//---------------------------------------------------------------------------
void __fastcall TFRAMEFailHndl::BtnInsert1Click(TObject *Sender)
{
    String sErrMsg = "";
    String sId     = "";

    TcxButton *pBtn = (TcxButton*)Sender;
    if (pBtn->Tag == 0)
    {
        sId = InputBox("장애 처리 코드", "새로운 장애 처리 코드를 입력하세요.\r\n입력후에는 수정이 불가능합니다.", "최대7자리");
        sId.Trim();
        if (sId.IsEmpty() || AnsiString(sId).Length() > 5 || sId == "최대7자리")
        {
            Application->MessageBox(L"7자리를 초과하였거나 값이 없습니다.", L"장애 처리 코드 추가 오류", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        	return;
        }

        TFacilityHndlType *pCode = FCode->FHndlLists.Find(sId);
        if (pCode)
        {
            sErrMsg = "[" + sId + "] 코드는 이미 사용 중인 코드입니다.\r\n다른 코드를 입력하세요.";
            Application->MessageBox(sErrMsg.c_str(), L"장애 처리 코드 추가 오류", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        	return;
        }

        ChangeButtonType1(2);
        FormClear1();
        EdId1->Text = sId;
        m_enJob1 = enJobSave;
    }
}
//---------------------------------------------------------------------------
void __fastcall TFRAMEFailHndl::BtnEdit1Click(TObject *Sender)
{
    TcxButton *pBtn = (TcxButton*)Sender;
    if (pBtn->Tag == 0)
    {
        ChangeButtonType1(2);
        m_enJob1 = enJobEdit;
    }
}
//---------------------------------------------------------------------------
void __fastcall TFRAMEFailHndl::BtnDelete1Click(TObject *Sender)
{
    TcxButton *pBtn = (TcxButton*)Sender;
    if (pBtn->Tag == 0)
    {
        DeleteData1();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::DeleteData1()
{
    TADOQuery *pADO = NULL;
	String sQry;
    String sMsgString;

    if (TvList1->ViewData->RecordCount <= 0) return;
    if (TvList1->DataController->FocusedRecordIndex < 0) return;
    if (!FCode)
    {
        return;
    }
    sMsgString = "장애 처리 코드 정보를 삭제 하시겠습니까?" ;
    if (Application->MessageBox(sMsgString.c_str(), L"코드 정보 삭제", MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

    String sCode = EdId1->Text;

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_GetConnection()->BeginTrans();
            // 코드 삭제
        	sQry = "DELETE FROM TB_FAIL_HNDL_TYPE  \r\n"
                   " WHERE FAIL_HNDL_CD = :p01     \r\n";

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLBind(pADO, "p01", sCode);
            ITSDb_SQLExec(pADO);

            ITSDb_SQLExec(pADO);
            ITSDb_GetConnection()->CommitTrans();

            ItsCodeManager->FLists.Remove(sCode);
            Application->MessageBox(L"장애 처리 코드 정보를 삭제하였습니다.", L"코드 정보 삭제", MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
        catch(EDatabaseError &E)
        {
            ITSDb_GetConnection()->RollbackTrans();
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORMSG(Caption, String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

    BtnSearchClick(NULL);
}
//---------------------------------------------------------------------------

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

    FormClear1();

    RefreshData();
    CxList1->SetFocus();

    ChangeButtonType1(1);
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::RefreshData()
{
    SelListData1();
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFailHndl::BtnSave1Click(TObject *Sender)
{
    bool   bMemDel = true;
    String sMsgTitle, sMsgString;

    TcxButton *pBtn = (TcxButton*)Sender;

    if (pBtn->Tag == 0)
    {
        TFacilityHndlType *pCode = new TFacilityHndlType();

        try
        {
            pCode->FAIL_HNDL_CD    = EdId1->Text.Trim();
            pCode->FAIL_HNDL_CD_NM = EdKName1->Text.Trim();

            if (m_enJob1 == enJobSave) sMsgTitle  = "장애 처리 코드 정보 등록";
                                       sMsgTitle  = "장애 처리 코드 정보 수정";

            if (MergeMainCode(pCode))
            {
                if (m_enJob1 == enJobSave)
                {
    				FCode->FHndlLists.Push(pCode->FAIL_HNDL_CD, pCode);
                    pCode->Completed = true;
                    bMemDel = false;
                }
                else
                {
#if 0
                    FCode->FMSG_TYPE_CD       = EdMsgCd->Text.Trim();
                    FCode->FCMMN_CLSF_KOR_NM  = EdKName1->Text.Trim();
                    FCode->FCMMN_CLSF_ENGL_NM = EdEName1->Text.Trim();
                    FCode->FUSE_SYST_CD       = EdSysCd->Text.Trim();
                    FCode->FRMRK              = EdRemark1->Text.Trim();
                    FCode->FUSE_YN            = (CbUseYn1->ItemIndex == 0) ? "Y" : "N";
#endif
                }
                RefreshData();
                CMM_SetGridFocusRow(CxList1, TvList1, pCode->FAIL_HNDL_CD, MColumn02->Index);
                DisplayListData1();
                ChangeButtonType1(1);
                Application->MessageBox(String(sMsgTitle + " 하였습니다.").c_str(), sMsgTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
            }
        }
        __finally
        {
            if (bMemDel)
            {
                if (pCode) delete pCode;
            }
        }
    }
}
//---------------------------------------------------------------------------

bool __fastcall TFRAMEFailHndl::MergeMainCode(TFacilityHndlType *ACode)
{
    bool   bResult = false;
    String sQry;
    TADOQuery *pADO = NULL;

	sQry = "MERGE INTO TB_FAIL_HNDL_TYPE L                        \r\n"
           "USING (SELECT :p01 AS FAIL_HNDL_CD,                   \r\n"
           "              :p02 AS FAIL_HNDL_CD_NM                 \r\n"
           "         FROM DUAL                                    \r\n"
           "      ) M                                             \r\n"
           "ON (L.FAIL_HNDL_CD = M.FAIL_HNDL_CD)                  \r\n"
           "WHEN MATCHED THEN                                     \r\n"
           "    UPDATE SET L.FAIL_HNDL_CD_NM = M.FAIL_HNDL_CD_NM  \r\n"
           "WHEN NOT MATCHED THEN                                 \r\n"
           "    INSERT (L.FAIL_HNDL_CD,                           \r\n"
           "            L.FAIL_HNDL_CD_NM)                        \r\n"
           "    VALUES (M.FAIL_HNDL_CD,                           \r\n"
           "            M.FAIL_HNDL_CD_NM)                        \r\n";
    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADO, sQry);

            ITSDb_SQLBind(pADO, "p01", ACode->FAIL_HNDL_CD);
            ITSDb_SQLBind(pADO, "p02", ACode->FAIL_HNDL_CD_NM);

            ITSDb_GetConnection()->BeginTrans();
            ITSDb_SQLExec(pADO);
            ITSDb_GetConnection()->CommitTrans();

            bResult = true;
        }
        catch(EDatabaseError &E)
        {
            ITSDb_GetConnection()->RollbackTrans();
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORMSG(Caption, String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }

    return bResult;
}
//---------------------------------------------------------------------------

