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

#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 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";

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

    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] 기타";
    }

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

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;

    try
    {
        TvList->BeginUpdate();

        FOR_STL(TItsFacilityFail*, pObj, ItsFacilityFailManager->FLists)
        {
            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
    {
        nRow = m_pGDC->AppendRecord();
        pObj->GridIndex = nRow;

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

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

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

        m_pGDC->Values[nRow][Column03->Index] = pObj->RCPR_NM;        //"접수자명";
        m_pGDC->Values[nRow][Column04->Index] = pObj->ADTN_NM;        //"추가자명";

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

        m_pGDC->Values[nRow][Column06->Index] = pObj->CHNG_NM;        //"변경자명";

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

        String sFFA = "[" + pObj->FAIL_TYPE + "] ";
        if (FCodeFFA)
        {
            pSubCode = FCodeFFA->FSubLists.Find(pObj->FAIL_TYPE);
            if (pSubCode) sFFA = sFFA + pSubCode->CMMN_CD_KOR_NM;
        }

        m_pGDC->Values[nRow][Column08->Index] = sFFA;      //"장애 유형";


        m_pGDC->Values[nRow][Column09->Index] = pObj->FAIL_CONT;      //"장애 내용";
        m_pGDC->Values[nRow][Column10->Index] = pObj->FCLT_ID;        //"시설물 ID";

        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;

        Column02->Options->Editing = 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;
    }
    __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");

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

#if 0
    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;
            pADO->Parameters->ParamByName("p01")->Value = sNowDate;
			pADO->Open();

#if 0
            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() > 30)
        {
            Application->MessageBox(L"장애일련번호는  10Byte를 초과할 수 없습니다.", FTitle.c_str(), nMsgType);
            return;
        }

        TItsFacilityFail *pDb = (TItsFacilityFail *)ItsFacilityFailManager->FLists.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->OCRR_DT     = Now().FormatString("yyyymmddhhnnss");   //"발생일시";
        pObj->RCPR_NM     = g_pLOGIN->sUserId;                      //"접수자명";
        pObj->ADTN_NM     = g_pLOGIN->sUserId;                      //"추가자명";
        pObj->ADTN_DT     = Now().FormatString("yyyymmddhhnnss");   //"추가일시";
        pObj->CHNG_NM     = g_pLOGIN->sUserId;                      //"변경자명";
        pObj->CHNG_DT     = Now().FormatString("yyyymmddhhnnss");   //"변경일시";
        pObj->FCLT_ID     = FFacility->FCLT_ID;                     //"시설물 ID";
        pObj->ActionCnt   = 0;

        ItsFacilityFailManager->FLists.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->FLists)
    {
        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 *pADOD = NULL;
	String sQryI;
	String sQryU;
	String sQryD;
    try
    {
        sQryI = "INSERT INTO TB_FCLT_FAIL_HS (FAIL_HS_SEQ, OCRR_DT, RCPR_NM,        \r\n"
                "                             ADTN_NM, ADTN_DT, CHNG_NM,            \r\n"
                "                             CHNG_DT,                              \r\n"
                "                             FAIL_TYPE, FAIL_CONT, FCLT_ID)        \r\n"
                "                      VALUES(:p01, :p02, :p03,                     \r\n"
                "                             :p04, :p05, :p06,                     \r\n"
                "                             TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), \r\n"
                "                             :p08, :p09, :p10)                     \r\n";

        sQryU = "UPDATE TB_FCLT_FAIL_HS                                   \r\n"
                "   SET OCRR_DT   = :p02,                                 \r\n"
                "       RCPR_NM   = :p03,                                 \r\n"
                "       ADTN_NM   = :p04,                                 \r\n"
                "       ADTN_DT   = :p05,                                 \r\n"
                "       CHNG_NM   = :p06,                                 \r\n"
                "       CHNG_DT   = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'), \r\n"
                "       FAIL_TYPE = :p08,                                 \r\n"
                "       FAIL_CONT = :p09,                                 \r\n"
                "       FCLT_ID   = :p10                                  \r\n"
                " WHERE FAIL_HS_SEQ = :p01                                \r\n";

        sQryD = "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();

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

            ITSDb_SQLText(pADOI, sQryI);
            ITSDb_SQLText(pADOU, sQryU);
            ITSDb_SQLText(pADOD, sQryD);

            ITSDb_GetConnection()->BeginTrans();

            FOR_STL(TItsFacilityFail*, pObj, ItsFacilityFailManager->FLists)
            {
                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 OCRR_DT = ""; //"발생일시";
                String ADTN_DT = ""; //"추가일시";
                //String CHNG_DT = ""; //"변경일시";

                if (!VarIsNull(m_pGDC->Values[nRow][Column02->Index]))
                {
                    TDateTime dtTmp = m_pGDC->Values[nRow][Column02->Index];
                    OCRR_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
                }
                if (!VarIsNull(m_pGDC->Values[nRow][Column05->Index]))
                {
                    TDateTime dtTmp = m_pGDC->Values[nRow][Column05->Index];
                    ADTN_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
                }
                //if (!VarIsNull(m_pGDC->Values[nRow][Column07->Index]))
                //{
                //    TDateTime dtTmp = m_pGDC->Values[nRow][Column07->Index];
                //    CHNG_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
                //}

                String RCPR_NM   = VarToStr(m_pGDC->Values[nRow][Column03->Index]); //"접수자명";
                String ADTN_NM   = VarToStr(m_pGDC->Values[nRow][Column04->Index]); //"추가자명";
                String CHNG_NM   = VarToStr(m_pGDC->Values[nRow][Column06->Index]); //"변경자명";
                String FAIL_TYPE = VarToStr(m_pGDC->Values[nRow][Column08->Index]); //"장애 유형";
                FAIL_TYPE = ITSUtil_GetCode(FAIL_TYPE);
                String FAIL_CONT = VarToStr(m_pGDC->Values[nRow][Column09->Index]); //"장애 내용";

                pObj->OCRR_DT   = OCRR_DT;   //"발생일시";
                pObj->RCPR_NM   = RCPR_NM;   //"접수자명";
                pObj->ADTN_NM   = ADTN_NM;   //"추가자명";
                pObj->ADTN_DT   = ADTN_DT;   //"추가일시";
                pObj->CHNG_NM   = CHNG_NM;   //"변경자명";
                //pObj->CHNG_DT   = CHNG_DT;   //"변경일시";
                pObj->FAIL_TYPE = FAIL_TYPE; //"장애 유형";
                pObj->FAIL_CONT = FAIL_CONT; //"장애 내용";

                if (pObj->Completed)
                {
                    if (pObj->EditMode == DB_DELETE)
                    {
                        //delete
                        ITSDb_SQLBind(pADOD, "p01", pObj->FAIL_HS_SEQ);
                        ITSDb_SQLExec(pADOD);
                        pObj->DEL_YN = "Y";
                    }
                    else
                    if (pObj->EditMode == DB_UPDATE)
                    {
                        //update
                        ITSDb_SQLBind(pADOU, "p01", pObj->FAIL_HS_SEQ);
                        ITSDb_SQLBind(pADOU, "p02", pObj->OCRR_DT);
                        ITSDb_SQLBind(pADOU, "p03", pObj->RCPR_NM);
                        ITSDb_SQLBind(pADOU, "p04", pObj->ADTN_NM);
                        ITSDb_SQLBind(pADOU, "p05", pObj->ADTN_DT);
                        ITSDb_SQLBind(pADOU, "p06", pObj->CHNG_NM);
                        //ITSDb_SQLBind(pADOU, "p07", pObj->CHNG_DT);
                        ITSDb_SQLBind(pADOU, "p08", pObj->FAIL_TYPE);
                        ITSDb_SQLBind(pADOU, "p09", pObj->FAIL_CONT);
                        ITSDb_SQLBind(pADOU, "p10", pObj->FCLT_ID);

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

                        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 (pADOD)
        {
            pADOD->Close();
            delete pADOD;
        }
        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 OCRR_DT = ""; //"발생일시";
    String ADTN_DT = ""; //"추가일시";
    //String CHNG_DT = ""; //"변경일시";

    if (!VarIsNull(m_pGDC->Values[nRow][Column02->Index]))
    {
        TDateTime dtTmp = m_pGDC->Values[nRow][Column02->Index];
        OCRR_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    if (!VarIsNull(m_pGDC->Values[nRow][Column05->Index]))
    {
        TDateTime dtTmp = m_pGDC->Values[nRow][Column05->Index];
        ADTN_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    //if (!VarIsNull(m_pGDC->Values[nRow][Column07->Index]))
    //{
    //    TDateTime dtTmp = m_pGDC->Values[nRow][Column07->Index];
    //    CHNG_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    //}

    String RCPR_NM   = VarToStr(m_pGDC->Values[nRow][Column03->Index]); //"접수자명";
    String ADTN_NM   = VarToStr(m_pGDC->Values[nRow][Column04->Index]); //"추가자명";
    String CHNG_NM   = VarToStr(m_pGDC->Values[nRow][Column06->Index]); //"변경자명";
    String FAIL_TYPE = VarToStr(m_pGDC->Values[nRow][Column08->Index]); //"장애 유형";

    FAIL_TYPE = ITSUtil_GetCode(FAIL_TYPE);

    String FAIL_CONT = VarToStr(m_pGDC->Values[nRow][Column09->Index]); //"장애 내용";


    TcxGridColumn *pColumn = TvList->Controller->FocusedColumn;
    if (pColumn == Column02)
    {
        TDateTime dtTmp = DisplayValue;
        OCRR_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    else
    if (pColumn == Column05)
    {
        TDateTime dtTmp = DisplayValue;
        ADTN_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    }
    //else
    //if (pColumn == Column07)
    //{
    //    TDateTime dtTmp = DisplayValue;
    //    CHNG_DT = dtTmp.FormatString("YYYYMMDDHHNNSS");
    //}
    else if (pColumn == Column03) RCPR_NM   = DisplayValue;
    else if (pColumn == Column04) ADTN_NM   = DisplayValue;
    else if (pColumn == Column06) CHNG_NM   = DisplayValue;
    else if (pColumn == Column08) FAIL_TYPE = DisplayValue;
    else if (pColumn == Column09) FAIL_CONT = DisplayValue;

    if (pObj->OCRR_DT   != OCRR_DT   || //"발생일시";
        pObj->RCPR_NM   != RCPR_NM   || //"접수자명";
        pObj->ADTN_NM   != ADTN_NM   || //"추가자명";
        pObj->ADTN_DT   != ADTN_DT   || //"추가일시";
        pObj->CHNG_NM   != CHNG_NM   || //"변경자명";
        //pObj->CHNG_DT   != CHNG_DT   || //"변경일시";
        pObj->FAIL_TYPE != FAIL_TYPE || //"장애 유형";
        pObj->FAIL_CONT != 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();
}
//---------------------------------------------------------------------------

