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

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

#include "FRAME_FacilityFailF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCalc"
#pragma link "cxCalendar"
#pragma link "cxCheckBox"
#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 "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#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 "cxDropDownEdit"
#pragma link "cxEditRepositoryItems"
#pragma resource "*.dfm"

extern LOGININFO *g_pLOGIN;

//---------------------------------------------------------------------------
__fastcall TFRAMEFacilityFail::TFRAMEFacilityFail(TComponent* Owner)
    : TFrame(Owner)
{
    ITSSkin_Load((TForm*)this);

    FTitle = "시설물 장애내역 관리";
    m_pGDC = TvList->DataController;
    TvList->OptionsView->NoDataToDisplayInfoText = "<시설물 장애내역 정보가 없습니다>";

    FFacility = NULL;
    FUpdate   = false;
    FKeySeq   = -1;

    //TcxDateEditProperties *pcxColumn02 = (TcxDateEditProperties*)Column02->Properties;
    //pcxColumn02->DisplayFormat = "yyyy-MM-dd HH:mm:ss";

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

    pcxEqpm = (TcxComboBoxProperties *)Column03->Properties;
    pcxOccr = (TcxComboBoxProperties *)Column10->Properties;
    pcxFail = (TcxComboBoxProperties *)Column11->Properties;


    FDefFFA = "";
    FCodeFFA = ItsCodeManager->FLists.Find("FFA");

#if 0
    TcxComboBoxProperties *pcxComboBox08 = (TcxComboBoxProperties *)Column08->Properties;
    pcxComboBox08->Items->Clear();
    if (FCodeFFA)
    {
		FOR_STL(TItsSubCode *, pSubCode, FCodeFFA->FSubLists)
		{
			pcxComboBox08->Items->Add("[" + pSubCode->CMMN_CD + "] " + pSubCode->CMMN_CD_KOR_NM);
            if (FDefFFA == "") FDefFFA = "[" + pSubCode->CMMN_CD + "] " + pSubCode->CMMN_CD_KOR_NM;
		}
    }
    else
    {
        pcxComboBox08->Items->Add("[FFA05] 기타");
        FDefFFA = "[FFA05] 기타";
    }
#endif

    if (!ItsFacilityFailManager)
    {
        ItsFacilityFailManager = new TItsFacilityFailManager();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::UpdateCheck()
{
    if (FFacility)
    {
        if (BtnEdit->Down)
        {
            FUpdate = false;
            BtnEdit->Down = false;
            BtnEdit->Click();
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::UpdateList(TItsFacility *AFacility)
{
    FUpdate = false;

    FFacility = AFacility;

    LblFacility->Caption = "---";
    CMM_ClearGridTableView(TvList);

    if (!FFacility) return;
    LblFacility->Caption = "[" + FFacility->FCLT_ID + "] " + FFacility->FCLT_LCTN;

    FDefEqpm = "";
    FDefEqpmName = "";
    pcxEqpm->Items->Clear();
    FOR_STL(TFacilityEqpmType *, pCode, FCode->FLists)
    {
        if (FFacility->FCLT_TYPE != pCode->FCLT_TYPE) continue;

        pcxEqpm->Items->Add("[" + pCode->EQPM_TYPE_CD + "] " + pCode->EQPM_TYPE_CD_NM);
        if (FDefEqpm == "")
        {
            FDefEqpm = pCode->EQPM_TYPE_CD;
            FDefEqpmName = "[" + pCode->EQPM_TYPE_CD + "] " + pCode->EQPM_TYPE_CD_NM;
        }
    }

    try
    {
        TvList->BeginUpdate();

        ItsFacilityFailManager->SelDbFail(AFacility);
        FOR_STL(TItsFacilityFail*, pObj, ItsFacilityFailManager->FSelLists)
        {
            pObj->EditMode = DB_INIT;   //미리 초기화시켜야함
            pObj->Completed = true;
            if (pObj->DEL_YN == "Y") continue;

            //if (pObj->FCLT_ID != FFacility->FCLT_ID) continue;

            AddObjectItem(pObj, "-");
        }
    }
    __finally
    {
        LblRecords->Caption = "("+FormatFloat("##,##0", m_pGDC->FilteredRecordCount) +"/"+FormatFloat("##,##0", m_pGDC->RecordCount) + ")";
        TvList->EndUpdate();
        TvList->DataController->GotoFirst();
        TvList->DataController->FocusedRecordIndex = 0;
        //CxList->SetFocus();
    }
}
//---------------------------------------------------------------------------

bool __fastcall TFRAMEFacilityFail::AddObjectItem(TItsFacilityFail *pObj, String AMode)
{
    TItsSubCode *pSubCode;
    int nRow;
    try
    {
        TFacilityEqpmType *pEqpmCd;

        nRow = m_pGDC->AppendRecord();
        pObj->GridIndex = nRow;

        m_pGDC->Values[nRow][Column00->Index] = AMode;

        m_pGDC->Values[nRow][Column01->Index] = pObj->FAIL_HS_SEQ;    //"장애이력일련번호";
        m_pGDC->Values[nRow][Column02->Index] = pObj->FCLT_ID;        //"장비ID";

        String sEqpm = "[" + pObj->EQPM_TYPE_CD + "] ";
        pEqpmCd = FCode->FLists.Find(pObj->EQPM_TYPE_CD);
        if (pEqpmCd) sEqpm = sEqpm + pEqpmCd->EQPM_TYPE_CD_NM;
        else         sEqpm = pcxEqpm->Items->Strings[0];

        m_pGDC->Values[nRow][Column03->Index] = sEqpm;      //장비유형

        if (!pObj->OCRR_DT.IsEmpty())
        m_pGDC->Values[nRow][Column04->Index] = ITSUtil_StrToDateTime(pObj->OCRR_DT);        //"발생일시";

        m_pGDC->Values[nRow][Column05->Index] = pObj->RCPR_NM;        //"접수자명";

        if (!pObj->ADTN_DT.IsEmpty())
        m_pGDC->Values[nRow][Column06->Index] = ITSUtil_StrToDateTime(pObj->ADTN_DT);        //"추가일시";

        m_pGDC->Values[nRow][Column07->Index] = pObj->ADTN_NM;        //"추가자명";
        m_pGDC->Values[nRow][Column08->Index] = pObj->CHNG_NM;        //"변경자명";

        if (!pObj->CHNG_DT.IsEmpty())
        m_pGDC->Values[nRow][Column09->Index] = ITSUtil_StrToDateTime(pObj->CHNG_DT);        //"변경일시";

        // 장애 발생 코드
        String sOccrCd  = "";
        String sOccrDef = "";
        String sOccr    = "";
        //pcxOccr->Items->Clear();
        if (pEqpmCd)
        {
            FOR_STL(TFacilityFailOccr *, pOccr, pEqpmCd->FLists)
            {
                String sCode = "[" + pOccr->FAIL_OCRR_CD + "] " + pOccr->FAIL_OCRR_CD_NM;
                //pcxOccr->Items->Add(sCode);
                if (sOccrDef == "")
                {
                    sOccrCd  = pOccr->FAIL_OCRR_CD;
                    sOccrDef = sCode;
                }
                if (pObj->FAIL_OCRR_CD == pOccr->FAIL_OCRR_CD)
                {
                    sOccr = sCode;
                    break;
                }
            }
        }
        if (sOccr == "") sOccr = sOccrDef;
        m_pGDC->Values[nRow][Column10->Index] = sOccr;      //"장애 유형";

        // 장애 유형
        String sFailCd  = "";
        String sFailDef = "";
        String sFail    = "";
        //pcxFail->Items->Clear();
        String sFailOccrCd = pObj->FAIL_OCRR_CD;
        if (sFailOccrCd == "")
        {
            sFailOccrCd = sOccrCd;
        }
        if (pEqpmCd)
        {
            TFacilityFailOccr *pOccr = pEqpmCd->FLists.Find(sFailOccrCd);
            if (pOccr)
            {
                FOR_STL(TFacilityFailCode *, pFail, pOccr->FLists)
                {
                    String sCode = "[" + pFail->FAIL_CD + "] " + pFail->FAIL_CD_NM;
                    //pcxFail->Items->Add(sCode);
                    if (sFailDef == "")
                    {
                        sFailCd  = pFail->FAIL_CD;
                        sFailDef = sCode;
                    }
                    if (pObj->FAIL_TYPE == pFail->FAIL_CD)
                    {
                        sFail = sCode;
                        break;
                    }
                }
            }
        }
        if (sFail == "") sFail = sFailDef;
        m_pGDC->Values[nRow][Column11->Index] = sFail;      //"장애 상세 유형";

        m_pGDC->Values[nRow][Column12->Index] = pObj->ETC_FAIL_CONT; //"기타 장애 내용";

        m_pGDC->Values[nRow][Column99->Index] = (int)pObj;

        return true;
    }
    catch(...)
    {
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::TvListDataControllerFilterChanged(TObject *Sender)
{
    LblRecords->Caption = "("+FormatFloat("##,##0", m_pGDC->FilteredRecordCount) +"/"+FormatFloat("##,##0", m_pGDC->RecordCount) + ")";
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= "시설물장애내역";

    CMM_ExportToExcelFile(sTitle, pGrid, pView, (TForm*)this);
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::BtnEditClick(TObject *Sender)
{
    if (!FFacility)
    {
        Application->MessageBox(L"시설물 정보를 먼저 선택하세요.", FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
    }

    TListFocus tvFocus(TvList);

    if (BtnEdit->Caption == "취소")
    {
        CxList->SetFocus();
        Application->ProcessMessages();
        SaveData();
    }

    ITSSkin_ButtonClick(BtnSearch, BtnEdit, BtnInsert, BtnDelete, BtnApply);
    ChangeEditMode(BtnEdit->Down);

    //ItsFacilityFailManager->LoadFromDb();
    UpdateList(FFacility);
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::ChangeEditMode(bool AEdit)
{
    bool bEditing = AEdit;

    try
    {
        TvList->BeginUpdate();

        Column00->Visible = bEditing;

        Column03->Options->Editing = bEditing;
        Column04->Options->Editing = bEditing;
        Column05->Options->Editing = bEditing;
        Column06->Options->Editing = bEditing;
        Column07->Options->Editing = bEditing;
        Column08->Options->Editing = bEditing;
        Column09->Options->Editing = bEditing;
        Column10->Options->Editing = bEditing;
        Column11->Options->Editing = bEditing;
        Column12->Options->Editing = bEditing;
    }
    __finally
    {
        TvList->EndUpdate();
        if (bEditing)
        {
            BtnEdit->Caption = "취소";
            BtnEdit->Hint    = "데이터 편집 취소";
        }
        else
        {
            BtnEdit->Caption = "편집";
            BtnEdit->Hint    = "데이터 편집";
        }
    }
}
//---------------------------------------------------------------------------

bool __fastcall TFRAMEFacilityFail::GetNewId(String &ANewId)
{
    String sQry;
    TADOQuery *pADO = NULL;
    String sNowDate = Now().FormatString("YYYYMM");

#if 0
    if (FKeySeq > 0)
    {
        String sTmpKey;
        sTmpKey.printf(L"%s%04d", sNowDate.c_str(), FKeySeq++);
        ANewId = sTmpKey;
        return true;
    }
#endif


#if 1
    sQry = "SELECT TO_CHAR(SYSDATE, 'YYYYMM') ||                                        \r\n"
           "       LPAD(NVL(MAX(SUBSTR(FAIL_HS_SEQ, -4)), '0000') + 1, 4, '0') AS NEWID \r\n"
           "  FROM TB_FCLT_FAIL_HS                                                      \r\n"
           " WHERE SUBSTR(FAIL_HS_SEQ, 1, 6) = TO_CHAR(SYSDATE, 'YYYYMM')               \r\n";
#else
    sQry = "SELECT TO_NUMBER(LPAD(NVL(MAX(SUBSTR(FAIL_HS_SEQ, -4)), '0000') + 1, 4, '0')) AS NEWID \r\n"
           "  FROM TB_FCLT_FAIL_HS                                                                 \r\n"
           " WHERE SUBSTR(FAIL_HS_SEQ, 1, 6) = :p01                                                \r\n";
#endif

    ANewId = "";
    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;
#if 0
            pADO->Parameters->ParamByName("p01")->Value = sNowDate;
#endif
			pADO->Open();

#if 1
            ANewId = pADO->FieldByName("NEWID")->AsString;
#else
            int nKeySeq = pADO->FieldByName("NEWID")->AsInteger;
            String sTmpKey;
            FKeySeq = nKeySeq;
            sTmpKey.printf(L"%s%04d", sNowDate.c_str(), FKeySeq++);
            ANewId = sTmpKey;
#endif
            return true;
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
        catch(...)
        {
            throw Exception("알수없는 DB 오류가 발생하였습니다.");
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::BtnInsertClick(TObject *Sender)
{
    int nMsgType = MB_OK|MB_ICONERROR|MB_APPLMODAL;

    if (!FFacility)
    {
        Application->MessageBox(L"시설물 정보를 먼저 선택하세요.", FTitle.c_str(), nMsgType);
		return;
    }

    String sNewId = "";
    GetNewId(sNewId);
    if (sNewId == "")
    {
	    sNewId = InputBox("장애일련번호", "새로운 일련번호를 입력하세요.\r\n입력후에는 수정이 불가능 합니다.", "최대10자리" );
        sNewId = sNewId.Trim();
        if (sNewId == "최대10자리" || sNewId == "")
        {
            return;
        }
        if (AnsiString(sNewId).Length() > 10)
        {
            Application->MessageBox(L"장애일련번호는  10Byte를 초과할 수 없습니다.", FTitle.c_str(), nMsgType);
            return;
        }

        TItsFacilityFail *pDb = (TItsFacilityFail *)ItsFacilityFailManager->FSelLists.Find(sNewId);
        if (pDb)
        {
            Application->MessageBox(("[" + sNewId + "]는 사용할 수 없는 장애일련번호 입니다.").c_str(), FTitle.c_str(), nMsgType);
            return;
        }
	}

    try
    {
        TvList->BeginUpdate();

        TItsFacilityFail *pObj = new TItsFacilityFail();
        pObj->Clear();

        pObj->FAIL_HS_SEQ   = sNewId;                               // 장애 이력 일련번호
        pObj->FCLT_ID       = FFacility->FCLT_ID;                   // 시설물 ID
        pObj->EQPM_TYPE_CD  = FDefEqpm;                             // 장비 유형 코드
        pObj->OCRR_DT       = Now().FormatString("yyyymmddhhnnss"); // 발생 일시
        pObj->RCPR_NM       = g_pLOGIN->sUserId;                    // 접수자 명
        pObj->ADTN_DT       = Now().FormatString("yyyymmddhhnnss"); // 추가 일시
        pObj->ADTN_NM       = g_pLOGIN->sUserId;                    // 추가자 명
        pObj->CHNG_NM       = g_pLOGIN->sUserId;                    // 변경자 명
        pObj->CHNG_DT       = Now().FormatString("yyyymmddhhnnss"); // 변경 일시
        pObj->FAIL_OCRR_CD  = "";                                   // 장애 발생 코드
        pObj->FAIL_TYPE     = "";                                   // 장애 유형
        pObj->ETC_FAIL_CONT = "";                                   // 기타 장애 내용

        pObj->ActionCnt   = 0;

        ItsFacilityFailManager->FSelLists.Push(pObj->FAIL_HS_SEQ, pObj);

        pObj->Completed = false;
        pObj->EditMode = DB_NEW;

        AddObjectItem(pObj, "신규");
    }
    __finally
    {
        LblRecords->Caption = "("+FormatFloat("##,##0", m_pGDC->FilteredRecordCount) +"/"+FormatFloat("##,##0", m_pGDC->RecordCount) + ")";
        TvList->EndUpdate();
        TvList->DataController->GotoFirst();
        TvList->DataController->FocusedRecordIndex = 0;
    }
}
//---------------------------------------------------------------------------

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

    int nMemPtr = m_pGDC->Values[nIdx][Column99->Index];
    TItsFacilityFail *pObj = (TItsFacilityFail*)nMemPtr;
    if (pObj->ActionCnt > 0)
    {
        Application->MessageBox(L"장애 조치내역이 있는 내역 정보는 삭제할 수 없습니다.\r\n장애 조치내역을 삭제한 후에 작업하세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
    }
    m_pGDC->Values[nIdx][Column00->Index] = "삭제";
    pObj->EditMode = DB_DELETE;
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::BtnApplyClick(TObject *Sender)
{
    FUpdate = true;
    BtnEdit->Down = false;
    BtnEdit->Click();
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::ChkAutoWidthPropertiesChange(TObject *Sender)
{
    try
    {
        TvList->BeginUpdate();
		TvList->OptionsView->ColumnAutoWidth = ChkAutoWidth->Checked;
        BtnBestFit->Visible = !ChkAutoWidth->Checked;
	}
	__finally
	{
        TvList->EndUpdate();
	}
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::BtnBestFitClick(TObject *Sender)
{
    try
    {
        TvList->BeginUpdate();
		TvList->ApplyBestFit(NULL, false, false);
	}
	__finally
	{
        TvList->EndUpdate();
	}
}
//---------------------------------------------------------------------------


bool __fastcall TFRAMEFacilityFail::IsUpdate()
{
    FOR_STL(TItsFacilityFail*, pObj, ItsFacilityFailManager->FSelLists)
    {
        if (pObj->Completed && pObj->EditMode != DB_INIT)
            return true;

        if (!pObj->Completed && pObj->EditMode == DB_NEW)
            return true;
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::SaveData()
{
    if (!IsUpdate()) return;

    if (!FUpdate)
    {
        if (Application->MessageBox(L"변경된 정보가 있습니다.\r\n변경된 정보를 저장 하시겠습니까?",
                                    FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES)
        {
            FOR_STL(TItsFacilityFail*, pObj, ItsFacilityFailManager->FLists)
            {
                if (pObj->EditMode == DB_NEW)
                    ItsFacilityFailManager->FLists.Remove(pObj->FAIL_HS_SEQ);
            }
            return;
        }
    }

    TADOQuery *pADOI  = NULL;
    TADOQuery *pADOU  = NULL;
    TADOQuery *pADOD1 = NULL;
    TADOQuery *pADOD2 = NULL;
	String sQryI;
	String sQryU;
	String sQryD1;
	String sQryD2;
    try
    {
        sQryI = "INSERT INTO TB_FCLT_FAIL_HS (FAIL_HS_SEQ, FCLT_ID, EQPM_TYPE_CD,     \r\n"
                "                             OCRR_DT, RCPR_NM, ADTN_DT, ADTN_NM,     \r\n"
                "                             CHNG_NM, CHNG_DT,                       \r\n"
                "                             FAIL_OCRR_CD, FAIL_TYPE, ETC_FAIL_CONT) \r\n"
                "                      VALUES(:p01, :p02, :p03,                       \r\n"
                "                             :p04, :p05, :p06, :p07,                 \r\n"
                "                             :p08, :p09,                             \r\n"
                "                             :p10, :p11, :p12)                       \r\n";

        sQryU = "UPDATE TB_FCLT_FAIL_HS        \r\n"
                "   SET FCLT_ID       = :p02,  \r\n"
                "       EQPM_TYPE_CD  = :p03,  \r\n"
                "       OCRR_DT       = :p04,  \r\n"
                "       RCPR_NM       = :p05,  \r\n"
                "       ADTN_DT       = :p06,  \r\n"
                "       ADTN_NM       = :p07,  \r\n"
                "       CHNG_NM       = :p08,  \r\n"
                "       CHNG_DT       = :p09,  \r\n"
                "       FAIL_OCRR_CD  = :p10,  \r\n"
                "       FAIL_TYPE     = :p11,  \r\n"
                "       ETC_FAIL_CONT = :p12   \r\n"
                " WHERE FAIL_HS_SEQ   = :p01   \r\n";

        sQryD1 = "DELETE TB_FCLT_FAIL_RPAR_HS  \r\n"
                 " WHERE FAIL_HS_SEQ = :p01    \r\n";

        sQryD2 = "DELETE TB_FCLT_FAIL_HS       \r\n"
                 " WHERE FAIL_HS_SEQ = :p01    \r\n";

        int nRow;
        TvList->BeginUpdate();
        try
        {
            pADOI = new TADOQuery(NULL);
			pADOI->Close();
            pADOI->Connection = ITSDb_GetConnection();

            pADOU = new TADOQuery(NULL);
			pADOU->Close();
            pADOU->Connection = ITSDb_GetConnection();

            pADOD1 = new TADOQuery(NULL);
			pADOD1->Close();
            pADOD1->Connection = ITSDb_GetConnection();

            pADOD2 = new TADOQuery(NULL);
			pADOD2->Close();
            pADOD2->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADOI,  sQryI);
            ITSDb_SQLText(pADOU,  sQryU);
            ITSDb_SQLText(pADOD1, sQryD1);
            ITSDb_SQLText(pADOD2, sQryD2);

            ITSDb_GetConnection()->BeginTrans();

            FOR_STL(TItsFacilityFail*, pObj, ItsFacilityFailManager->FSelLists)
            {
                if (pObj->GridIndex < 0) continue;

                if (pObj->Completed && pObj->EditMode == DB_INIT)
                    continue;

                if (!pObj->Completed && pObj->EditMode != DB_NEW)
                    continue;

                nRow = pObj->GridIndex;

                String FAIL_HS_SEQ   = pObj->FAIL_HS_SEQ;   // 장애 이력 일련번호
                String FCLT_ID       = pObj->FCLT_ID;       // 시설물 ID
                String EQPM_TYPE_CD  = pObj->EQPM_TYPE_CD;  // 장비 유형 코드
                String OCRR_DT       = pObj->OCRR_DT;       // 발생 일시
                String RCPR_NM       = pObj->RCPR_NM;       // 접수자 명
                String ADTN_DT       = pObj->ADTN_DT;       // 추가 일시
                String ADTN_NM       = pObj->ADTN_NM;       // 추가자 명
                String CHNG_NM       = pObj->CHNG_NM;       // 변경자 명
                String CHNG_DT       = pObj->CHNG_DT;       // 변경 일시
                String FAIL_OCRR_CD  = pObj->FAIL_OCRR_CD;  // 장애 발생 코드
                String FAIL_TYPE     = pObj->FAIL_TYPE;     // 장애 유형
                String ETC_FAIL_CONT = pObj->ETC_FAIL_CONT; // 기타 장애 내용

                EQPM_TYPE_CD  = VarToStr(m_pGDC->Values[nRow][Column03->Index]);     // 장비 유형 코드
                OCRR_DT       = "";                                                  // 발생 일시
                RCPR_NM       = VarToStr(m_pGDC->Values[nRow][Column05->Index]);     // 접수자 명
                ADTN_DT       = "";                                                  // 추가 일시
                ADTN_NM       = VarToStr(m_pGDC->Values[nRow][Column07->Index]);     // 추가자 명
                CHNG_NM       = VarToStr(m_pGDC->Values[nRow][Column08->Index]);     // 변경자 명
                CHNG_DT       = "";                                                  // 변경 일시
                FAIL_OCRR_CD  = VarToStr(m_pGDC->Values[nRow][Column10->Index]);     // 장애 발생 코드
                FAIL_TYPE     = VarToStr(m_pGDC->Values[nRow][Column11->Index]);     // 장애 유형
                ETC_FAIL_CONT = VarToStr(m_pGDC->Values[nRow][Column12->Index]);     // 기타 장애 내용

                if (!VarIsNull(m_pGDC->Values[nRow][Column04->Index]))
                {
                    TDateTime dtTmp = m_pGDC->Values[nRow][Column04->Index];
                    OCRR_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
                }
                if (!VarIsNull(m_pGDC->Values[nRow][Column06->Index]))
                {
                    TDateTime dtTmp = m_pGDC->Values[nRow][Column06->Index];
                    ADTN_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
                }
                if (!VarIsNull(m_pGDC->Values[nRow][Column09->Index]))
                {
                    TDateTime dtTmp = m_pGDC->Values[nRow][Column09->Index];
                    CHNG_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
                }

                //String CHNG_DT   = Now().FormatString("yyyymmddhhnnss");

                EQPM_TYPE_CD = ITSUtil_GetCode(EQPM_TYPE_CD);
                FAIL_OCRR_CD = ITSUtil_GetCode(FAIL_OCRR_CD);
                FAIL_TYPE    = ITSUtil_GetCode(FAIL_TYPE);

                pObj->EQPM_TYPE_CD  = EQPM_TYPE_CD;  // 장비 유형 코드
                pObj->OCRR_DT       = OCRR_DT;       // 발생 일시
                pObj->RCPR_NM       = RCPR_NM;       // 접수자 명
                pObj->ADTN_DT       = ADTN_DT;       // 추가 일시
                pObj->ADTN_NM       = ADTN_NM;       // 추가자 명
                pObj->CHNG_NM       = CHNG_NM;       // 변경자 명
                pObj->CHNG_DT       = CHNG_DT;       // 변경 일시
                pObj->FAIL_OCRR_CD  = FAIL_OCRR_CD;  // 장애 발생 코드
                pObj->FAIL_TYPE     = FAIL_TYPE;     // 장애 유형
                pObj->ETC_FAIL_CONT = ETC_FAIL_CONT; // 기타 장애 내용

                if (pObj->Completed)
                {
                    if (pObj->EditMode == DB_DELETE)
                    {
                        //delete
                        ITSDb_SQLBind(pADOD1, "p01", pObj->FAIL_HS_SEQ);
                        ITSDb_SQLExec(pADOD1);

                        ITSDb_SQLBind(pADOD2, "p01", pObj->FAIL_HS_SEQ);
                        ITSDb_SQLExec(pADOD2);
                        pObj->DEL_YN = "Y";
                    }
                    else
                    if (pObj->EditMode == DB_UPDATE)
                    {
                        //update
                        ITSDb_SQLBind(pADOU, "p01", pObj->FAIL_HS_SEQ);
                        ITSDb_SQLBind(pADOU, "p02", pObj->FCLT_ID);
                        ITSDb_SQLBind(pADOU, "p03", pObj->EQPM_TYPE_CD);
                        ITSDb_SQLBind(pADOU, "p04", pObj->OCRR_DT);
                        ITSDb_SQLBind(pADOU, "p05", pObj->RCPR_NM);
                        ITSDb_SQLBind(pADOU, "p06", pObj->ADTN_DT);
                        ITSDb_SQLBind(pADOU, "p07", pObj->ADTN_NM);
                        ITSDb_SQLBind(pADOU, "p08", pObj->CHNG_NM);
                        ITSDb_SQLBind(pADOU, "p09", pObj->CHNG_DT);
                        ITSDb_SQLBind(pADOU, "p10", pObj->FAIL_OCRR_CD);
                        ITSDb_SQLBind(pADOU, "p11", pObj->FAIL_TYPE);
                        ITSDb_SQLBind(pADOU, "p12", pObj->ETC_FAIL_CONT);

                        ITSDb_SQLExec(pADOU);
                    }
                }
                else
                {
                    if (pObj->EditMode == DB_NEW)
                    {
                        //insert
                        ITSDb_SQLBind(pADOI, "p01", pObj->FAIL_HS_SEQ);
                        ITSDb_SQLBind(pADOI, "p02", pObj->FCLT_ID);
                        ITSDb_SQLBind(pADOI, "p03", pObj->EQPM_TYPE_CD);
                        ITSDb_SQLBind(pADOI, "p04", pObj->OCRR_DT);
                        ITSDb_SQLBind(pADOI, "p05", pObj->RCPR_NM);
                        ITSDb_SQLBind(pADOI, "p06", pObj->ADTN_DT);
                        ITSDb_SQLBind(pADOI, "p07", pObj->ADTN_NM);
                        ITSDb_SQLBind(pADOI, "p08", pObj->CHNG_NM);
                        ITSDb_SQLBind(pADOI, "p09", pObj->CHNG_DT);
                        ITSDb_SQLBind(pADOI, "p10", pObj->FAIL_OCRR_CD);
                        ITSDb_SQLBind(pADOI, "p11", pObj->FAIL_TYPE);
                        ITSDb_SQLBind(pADOI, "p12", pObj->ETC_FAIL_CONT);

                        ITSDb_SQLExec(pADOI);
                    }
                }
                pObj->Completed = true;
            }
            ITSDb_GetConnection()->CommitTrans();
            Application->MessageBox(L"시설물 장애 내역 정보를 저장 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        }
        catch(EDatabaseError &E)
        {
            ITSDb_GetConnection()->RollbackTrans();
            ShowMessage(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            ITSDb_GetConnection()->RollbackTrans();
            ShowMessage(String(exception.ClassName()) + exception.Message);
        }
        catch(...)
        {
            ITSDb_GetConnection()->RollbackTrans();
            ShowMessage("데이터 작업 중에 알수없는 DB 오류가 발생하였습니다.");
        }
    }
    __finally
    {
        if (pADOI)
        {
            pADOI->Close();
            delete pADOI;
        }
        if (pADOU)
        {
            pADOU->Close();
            delete pADOU;
        }
        if (pADOD1)
        {
            pADOD1->Close();
            delete pADOD1;
        }
        if (pADOD2)
        {
            pADOD2->Close();
            delete pADOD2;
        }
        TvList->EndUpdate();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::ColumnPropertiesValidate(TObject *Sender, Variant &DisplayValue, TCaption &ErrorText,
          bool &Error)
{
    if (TvList->Controller->FocusedRow->IsFilterRow) return;

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

    int nMemPtr = m_pGDC->Values[nRow][Column99->Index];
    TItsFacilityFail *pObj = (TItsFacilityFail*)nMemPtr;
    if (pObj->Completed == false)
    {
        //신규이거나 삭제인 경우 편집 내용에 따른 변화가 필요없다.
        return;
    }

    //String FAIL_HS_SEQ   = VarToStr(m_pGDC->Values[nRow][Column01->Index]);     // 장애 이력 일련번호
    //String FCLT_ID       = VarToStr(m_pGDC->Values[nRow][Column02->Index]);     // 시설물 ID
    String EQPM_TYPE_CD  = VarToStr(m_pGDC->Values[nRow][Column03->Index]);     // 장비 유형 코드
    String OCRR_DT       = "";                                                  // 발생 일시
    String RCPR_NM       = VarToStr(m_pGDC->Values[nRow][Column05->Index]);     // 접수자 명
    String ADTN_DT       = "";                                                  // 추가 일시
    String ADTN_NM       = VarToStr(m_pGDC->Values[nRow][Column07->Index]);     // 추가자 명
    String CHNG_NM       = VarToStr(m_pGDC->Values[nRow][Column08->Index]);     // 변경자 명
    String CHNG_DT       = "";                                                  // 변경 일시
    String FAIL_OCRR_CD  = VarToStr(m_pGDC->Values[nRow][Column10->Index]);     // 장애 발생 코드
    String FAIL_TYPE     = VarToStr(m_pGDC->Values[nRow][Column11->Index]);     // 장애 유형
    String ETC_FAIL_CONT = VarToStr(m_pGDC->Values[nRow][Column12->Index]);     // 기타 장애 내용

    if (!VarIsNull(m_pGDC->Values[nRow][Column04->Index]))
    {
        TDateTime dtTmp = m_pGDC->Values[nRow][Column04->Index];
        OCRR_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    if (!VarIsNull(m_pGDC->Values[nRow][Column06->Index]))
    {
        TDateTime dtTmp = m_pGDC->Values[nRow][Column06->Index];
        ADTN_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    if (!VarIsNull(m_pGDC->Values[nRow][Column09->Index]))
    {
        TDateTime dtTmp = m_pGDC->Values[nRow][Column09->Index];
        CHNG_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }

    TcxGridColumn *pColumn = TvList->Controller->FocusedColumn;

    if      (pColumn == Column03) EQPM_TYPE_CD = DisplayValue;
    else if (pColumn == Column04)
    {
        TDateTime dtTmp = DisplayValue;
        OCRR_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    else if (pColumn == Column05) RCPR_NM = DisplayValue;
    else if (pColumn == Column06)
    {
        TDateTime dtTmp = DisplayValue;
        ADTN_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    else if (pColumn == Column07) ADTN_NM = DisplayValue;
    else if (pColumn == Column08) CHNG_NM = DisplayValue;
    else if (pColumn == Column09)
    {
        TDateTime dtTmp = DisplayValue;
        CHNG_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    else if (pColumn == Column10) FAIL_OCRR_CD  = DisplayValue;
    else if (pColumn == Column11) FAIL_TYPE     = DisplayValue;
    else if (pColumn == Column12) ETC_FAIL_CONT = DisplayValue;

    EQPM_TYPE_CD = ITSUtil_GetCode(EQPM_TYPE_CD);
    FAIL_OCRR_CD = ITSUtil_GetCode(FAIL_OCRR_CD);
    FAIL_TYPE    = ITSUtil_GetCode(FAIL_TYPE);


    if (EQPM_TYPE_CD  != pObj->EQPM_TYPE_CD  ||  // 장비 유형 코드
        OCRR_DT       != pObj->OCRR_DT       ||  // 발생 일시
        RCPR_NM       != pObj->RCPR_NM       ||  // 접수자 명
        ADTN_DT       != pObj->ADTN_DT       ||  // 추가 일시
        ADTN_NM       != pObj->ADTN_NM       ||  // 추가자 명
        CHNG_NM       != pObj->CHNG_NM       ||  // 변경자 명
        CHNG_DT       != pObj->CHNG_DT       ||  // 변경 일시
        FAIL_OCRR_CD  != pObj->FAIL_OCRR_CD  ||  // 장애 발생 코드
        FAIL_TYPE     != pObj->FAIL_TYPE     ||  // 장애 유형
        ETC_FAIL_CONT != pObj->ETC_FAIL_CONT  )  // 기타 장애 내용
    {
        m_pGDC->Values[nRow][Column00->Index] = "수정";
        pObj->EditMode = DB_UPDATE;
    }
    else
    {
        m_pGDC->Values[nRow][Column00->Index] = "-";
        pObj->EditMode = DB_INIT;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::TvListCustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    if (AViewInfo)
    {
        String sType = AViewInfo->GridRecord->DisplayTexts[Column00->Index];
        if (sType == "수정")
        {
            ACanvas->Brush->Color = clOlive;
        }
        else if (sType == "삭제")
        {
            ACanvas->Brush->Color = clRed;
        }
        else if (sType == "신규")
        {
            ACanvas->Brush->Color = clLime;
            if (AViewInfo->Focused) ACanvas->Font->Color = clBlack;
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::TvListKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
{
	if (Key == VK_DELETE)
	{
		if (BtnDelete->Enabled) BtnDeleteClick(Sender);
	}
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::OnCloseQuery(bool &CanClose)
{
    SaveData();
    try {
        if (FCode) delete FCode;
        FCode = NULL;
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::Column10GetPropertiesForEdit(TcxCustomGridTableItem *Sender,
          TcxCustomGridRecord *ARecord, TcxCustomEditProperties *&AProperties)
{
    try
    {
        TcxEditRepositoryComboBoxItem *cxEditRepository = cxEditRepositoryFailOccr;
        TcxGridColumn                 *pColumn          = Column10;

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

        TcxGridDataController *pGDC = (TcxGridDataController *)TvList->DataController;
        int nRow = pGDC->FocusedRecordIndex;
        if (nRow < 0) return;

        int nMemPtr = pGDC->Values[nRow][Column99->Index];
        TItsFacilityFail *pObj = (TItsFacilityFail*)nMemPtr;
        if (!pObj) return;

        //장비유형
        String sEqpmTypeCd = VarToStr(pGDC->Values[nRow][Column03->Index]);
        sEqpmTypeCd = ITSUtil_GetCode(sEqpmTypeCd);

        TFacilityEqpmType *pEqpmCd = FCode->FLists.Find(sEqpmTypeCd);
        if (!pEqpmCd) return;

        //장애 발생 코드
		FOR_STL(TFacilityFailOccr *, pOccr, pEqpmCd->FLists)
		{
            String sCode = "[" + pOccr->FAIL_OCRR_CD + "] " + pOccr->FAIL_OCRR_CD_NM;
            ((TcxComboBoxProperties*)pColumn->Properties)->Items->Add(sCode);
            cxEditRepository->Properties->Items->Add(sCode);
        }
        ((TcxComboBoxProperties*)pColumn->Properties)->Items->Assign(cxEditRepository->Properties->Items);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::Column11GetPropertiesForEdit(TcxCustomGridTableItem *Sender,
          TcxCustomGridRecord *ARecord, TcxCustomEditProperties *&AProperties)
{
    try
    {
        TcxEditRepositoryComboBoxItem *cxEditRepository = cxEditRepositoryFailType;
        TcxGridColumn                 *pColumn          = Column11;

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

        TcxGridDataController *pGDC = (TcxGridDataController *)TvList->DataController;
        int nRow = pGDC->FocusedRecordIndex;
        if (nRow < 0) return;

        int nMemPtr = pGDC->Values[nRow][Column99->Index];
        TItsFacilityFail *pObj = (TItsFacilityFail*)nMemPtr;
        if (!pObj) return;

        //장비유형
        String sEqpmTypeCd = VarToStr(pGDC->Values[nRow][Column03->Index]);
        sEqpmTypeCd = ITSUtil_GetCode(sEqpmTypeCd);

        //장애 발생 코드
        String sFailOccrCd = VarToStr(pGDC->Values[nRow][Column10->Index]);
        sFailOccrCd = ITSUtil_GetCode(sFailOccrCd);

        //장비유형 목록 검색
        TFacilityEqpmType *pEqpmCd = FCode->FLists.Find(sEqpmTypeCd);
        if (!pEqpmCd) return;

        //장애 발생 코드 목록 검색
        TFacilityFailOccr *pOccr = pEqpmCd->FLists.Find(sFailOccrCd);
        if (!pOccr) return;

        //장애 유형
		FOR_STL(TFacilityFailCode *, pFail, pOccr->FLists)
		{
            String sCode = "[" + pFail->FAIL_CD + "] " + pFail->FAIL_CD_NM;
            ((TcxComboBoxProperties*)pColumn->Properties)->Items->Add(sCode);
            cxEditRepository->Properties->Items->Add(sCode);
        }
        ((TcxComboBoxProperties*)pColumn->Properties)->Items->Assign(cxEditRepository->Properties->Items);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::Column10PropertiesChange(TObject *Sender)
{
    try
    {
        TcxGridDataController *pGDC = (TcxGridDataController *)TvList->DataController;
        int nRow = pGDC->FocusedRecordIndex;
        if (nRow < 0) return;

        int nMemPtr = pGDC->Values[nRow][Column99->Index];
        TItsFacilityFail *pObj = (TItsFacilityFail*)nMemPtr;
        if (!pObj) return;

        //장비유형
        String sEqpmTypeCd = VarToStr(pGDC->Values[nRow][Column03->Index]);
        sEqpmTypeCd = ITSUtil_GetCode(sEqpmTypeCd);

        //장애 발생 코드
        String sFailOccrCd = VarToStr(pGDC->Values[nRow][Column10->Index]);
        sFailOccrCd = ITSUtil_GetCode(sFailOccrCd);

        //장비유형 목록 검색
        TFacilityEqpmType *pEqpmCd = FCode->FLists.Find(sEqpmTypeCd);
        if (!pEqpmCd) return;

        //장애 발생 코드 목록 검색
        TFacilityFailOccr *pOccr = pEqpmCd->FLists.Find(sFailOccrCd);
        if (!pOccr) return;

        //장애 유형
        String sFailType = "";
		FOR_STL(TFacilityFailCode *, pFail, pOccr->FLists)
		{
            if (sFailType == "")
            {
                sFailType = "[" + pFail->FAIL_CD + "] " + pFail->FAIL_CD_NM;
                break;
            }
        }
        pGDC->Values[nRow][Column11->Index] = sFailType;
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFRAMEFacilityFail::SetDefaultCodeValue()
{
    try
    {
        TcxGridDataController *pGDC = (TcxGridDataController *)TvList->DataController;
        int nRow = pGDC->FocusedRecordIndex;
        if (nRow < 0) return;

        int nMemPtr = pGDC->Values[nRow][Column99->Index];
        TItsFacilityFail *pObj = (TItsFacilityFail*)nMemPtr;
        if (!pObj) return;

        //장비유형
        String sEqpmTypeCd = VarToStr(pGDC->Values[nRow][Column03->Index]);
        sEqpmTypeCd = ITSUtil_GetCode(sEqpmTypeCd);

        //장애 발생 코드
        String sFailOccrCd = VarToStr(pGDC->Values[nRow][Column10->Index]);
        sFailOccrCd = ITSUtil_GetCode(sFailOccrCd);

        //장비유형 목록 검색
        TFacilityEqpmType *pEqpmCd = FCode->FLists.Find(sEqpmTypeCd);
        if (!pEqpmCd) return;

        //장애 발생 코드 목록 검색
        TFacilityFailOccr *pOccr = pEqpmCd->FLists.Find(sFailOccrCd);
        if (!pOccr) return;

        //장애 유형
        String sFailType = "";
		FOR_STL(TFacilityFailCode *, pFail, pOccr->FLists)
		{
            if (sFailType == "")
            {
                sFailType = "[" + pFail->FAIL_CD + "] " + pFail->FAIL_CD_NM;
                break;
            }
        }
        pGDC->Values[nRow][Column11->Index] = sFailType;
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

