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

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

#include "IDB0140MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCalc"
#pragma link "cxCheckBox"
#pragma link "cxClasses"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxDropDownEdit"
#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 "cxSpinEdit"
#pragma link "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinMcSkin"
#pragma resource "*.dfm"

TIDB0140M *IDB0140M = NULL;

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

    FTitle = Caption;   //"홈페이지 관리자 관리";
    FDbUpdate = false;

    MyWebUserManager = new TWebUserManager();
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::CommClose()
{
    try
    {
        if (MyWebUserManager)
        {
            delete MyWebUserManager;
            MyWebUserManager = NULL;
        }

        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::FormShow(TObject *Sender)
{
    Refresh();
    FormInit();
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::FormInit()
{
    m_pGDC = TvList->DataController;

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<현재 등록된 관리자 정보가 없습니다>";

    InitColumnProperties();
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::InitColumnProperties()
{
    FInitCombo1 = "";
    FInitCombo2 = "";

    //그룹
    TcxComboBoxProperties *pcxColumn13 = (TcxComboBoxProperties *)Column13->Properties;
    pcxColumn13->Items->Clear();
    pcxColumn13->Items->Add("[N] Un Lock");
    pcxColumn13->Items->Add("[Y] Locked");
    FInitCombo2 = "[N] Un Lock";

#if 0
    FInitCombo1 = "";
    FInitCombo2 = "";

    String sQry;
    TADOQuery *pADO = NULL;

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


            sQry = "SELECT GROP_ID, GROP_NM \r\n"
                   "  FROM TB_USERGROP_INFR \r\n"
                   " WHERE DEL_YN = 'N'     \r\n"
                   " ORDER BY GROP_ID       \r\n";
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;
            pADO->Prepared = true;
			pADO->Open();

            //그룹
    		TcxComboBoxProperties *pcxColumn12 = (TcxComboBoxProperties *)Column12->Properties;
            pcxColumn12->Items->Clear();
            for( ; !pADO->Eof; pADO->Next())
            {
                String sCode = pADO->FieldByName("GROP_ID")->AsString;    //코드
                String sName = pADO->FieldByName("GROP_NM")->AsString;    //코드명

    			pcxColumn12->Items->Add("[" + sCode + "] " + sName);
                if (FInitCombo1 == "")
                {
                    FInitCombo1 = "[" + sCode + "] " + sName;
                }
            }

            //시스템
            sQry = "SELECT OPER_SYST_ID, OPER_SYST_NAME \r\n"
                   "  FROM TB_OPERSYST                  \r\n"
                   " ORDER BY OPER_SYST_ID              \r\n";
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;
            pADO->Prepared = true;
			pADO->Open();

            //그룹
    		TcxComboBoxProperties *pcxColumn13 = (TcxComboBoxProperties *)Column13->Properties;
            pcxColumn13->Items->Clear();
            for( ; !pADO->Eof; pADO->Next())
            {
                String sCode = pADO->FieldByName("OPER_SYST_ID")->AsString;    //코드
                String sName = pADO->FieldByName("OPER_SYST_NAME")->AsString;    //코드명

    			pcxColumn13->Items->Add("[" + sCode + "] " + sName);
                if (FInitCombo2 == "")
                {
                    FInitCombo2 = "[" + sCode + "] " + sName;
                }
            }
        }
        catch(EDatabaseError &E)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
        catch(...)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            throw Exception(FrmLang->lblDbErr->Caption);//"알수없는 DB 오류가 발생하였습니다.");
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    BtnSearchClick((TObject*)BtnSearch);
}
//---------------------------------------------------------------------------

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

    RefreshData();
    CxList->SetFocus();
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::RefreshData()
{
    MyWebUserManager->LoadFromDb();
    SelListData();
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::SelListData()
{
    FUpdate = false;
    CMM_ClearGridTableView(TvList);

    try
    {
        TvList->BeginUpdate();

        FOR_STL(TWebUser*, pObj, MyWebUserManager->FLists)
        {
            pObj->EditMode = DB_INIT;   // 미리초기화해준다.(삭제된것)
            pObj->Completed = true;
            if (pObj->DEL_YN == "Y" || pObj->MEM_DEL == "Y") 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();
    }
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::BtnCloseClick(TObject *Sender)
{
    Close();
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= "홈페이지 관리자 정보";

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

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

	String sEmail = InputBox(Label1->Caption, Label2->Caption, Label1->Caption);

    sEmail = sEmail.Trim();
	if (sEmail == Label1->Caption || sEmail == "")
	{
		return;
	}
	if (AnsiString(sEmail).Length() > 50)
	{
        Application->MessageBox(Label3->Caption.c_str(), FTitle.c_str(), nMsgType);
		return;
	}

    FOR_STL(TWebUser*, pDb, MyWebUserManager->FLists)
    {
        if (pDb->EMAIL == sEmail)
        {
            String sErr = FrmLang->lbIdErr->Caption + "[" + sEmail + "]";
            Application->MessageBox(sErr.c_str(),//("[" + sId + "]는 사용할 수 없는 관리자 ID 입니다.").c_str(),
                                    FTitle.c_str(), nMsgType);
            return;
        }
    }

    int nNewId;
    if (!MyWebUserManager->GetNextUserId(nNewId))
    {
        Application->MessageBox(FrmLang->lblMemErr->Caption.c_str(),//L"신규 관리자 정보를 생성할 수 없습니다.[메모리오류]",
                                FTitle.c_str(), nMsgType);
        return;
    }

    String sUserId = String(nNewId);

    try
    {
        TvList->BeginUpdate();

        TWebUser *pObj = new TWebUser();
        if (!pObj)
        {
            Application->MessageBox(FrmLang->lblMemErr->Caption.c_str(),//L"신규 관리자 정보를 생성할 수 없습니다.[메모리오류]",
                                    FTitle.c_str(), nMsgType);
            return;
        }
        //pObj->Clear();

        pObj->USER_ID           = sUserId;
        pObj->EMAIL             = sEmail;
        pObj->PWD               = "";
        pObj->NAME              = "";
        pObj->CONTACTNUM        = "";
        pObj->USERAUTH          = "";
        pObj->QUESTION          = "";
        pObj->ANSWER            = "";
        pObj->RGST_DT           = Now().FormatString("YYYYMMDDHHNNSS");
        pObj->LOGIN_FAIL_COUNT  = "0";
        pObj->IS_ACCOUNT_LOCK   = ITSUtil_GetCode(FInitCombo2);
        pObj->IP_ADDRESS        = "";

        pObj->DEL_YN       = "N";

        pObj->USERAUTH_NM = pObj->USERAUTH;

        if (pObj->IS_ACCOUNT_LOCK == "N")
        {
            pObj->IS_ACCOUNT_LOCK_NM = "[N] Un Lock";
        }
        else
        {
            pObj->IS_ACCOUNT_LOCK_NM = "[Y] Locked";
        }

        pObj->Completed    = false;
        pObj->EditMode     = DB_NEW;
        pObj->MEM_DEL      = "N";

        MyWebUserManager->FLists.Push(pObj->EMAIL, pObj);

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

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

    int nMemPtr = m_pGDC->Values[nIdx][Column99->Index];
    TWebUser *pObj = (TWebUser*)nMemPtr;
    pObj->EditMode = DB_DELETE;
    m_pGDC->Values[nIdx][Column00->Index] = FrmLang->lblDelete->Caption;//"삭제";
}
//---------------------------------------------------------------------------

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

void __fastcall TIDB0140M::BtnEditClick(TObject *Sender)
{
    TListFocus tvFocus(TvList);

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

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

    RefreshData();
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::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;
        Column10->Options->Editing = bEditing;
        Column11->Options->Editing = bEditing;
        Column12->Options->Editing = bEditing;
        Column13->Options->Editing = bEditing;
    }
    __finally
    {
        TvList->EndUpdate();
        if (bEditing)
        {
            BtnEdit->Caption = FrmLang->lblCancel->Caption;//"취소";
            BtnEdit->Hint    = FrmLang->lblCancel->Hint;//데이터 편집 취소";
        }
        else
        {
            BtnEdit->Caption = FrmLang->lblEdit->Caption;//"편집";
            BtnEdit->Hint    = FrmLang->lblEdit->Hint;//데이터 편집";
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::TvListColumnPropertiesValidate(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 = TvList->DataController->Values[nRow][Column99->Index];
    TWebUser *pObj = (TWebUser*)nMemPtr;
    if (pObj->Completed == false)
    {
        //신규이거나 삭제인 경우 편집 내용에 따른 변화가 필요없다.
        return;
    }

    String PWD_TMP      = "";
    String PWD_ORG      = VarToStr(m_pGDC->Values[nRow][Column16->Index]);
    String PWD          = VarToStr(m_pGDC->Values[nRow][Column02->Index]);
    PWD_TMP = PWD_ORG;

    String USERNAME         = VarToStr(m_pGDC->Values[nRow][Column03->Index]);
    String CONTACTNUM       = VarToStr(m_pGDC->Values[nRow][Column04->Index]);
    String USERAUTH         = VarToStr(m_pGDC->Values[nRow][Column12->Index]);
    String QUESTION         = VarToStr(m_pGDC->Values[nRow][Column10->Index]);
    String ANSWER           = VarToStr(m_pGDC->Values[nRow][Column11->Index]);
    String LOGIN_FAIL_COUNT = VarToStr(m_pGDC->Values[nRow][Column05->Index]);
    String IS_ACCOUNT_LOCK  = VarToStr(m_pGDC->Values[nRow][Column13->Index]);
    String IP_ADDRESS       = VarToStr(m_pGDC->Values[nRow][Column06->Index]);

    TcxGridColumn *pColumn = TvList->Controller->FocusedColumn;
    if      (pColumn == Column02)
    {
        PWD = DisplayValue;
        PWD_TMP = GetPassword(PWD);
    }
    else if (pColumn == Column03) USERNAME         = DisplayValue;
    else if (pColumn == Column04) CONTACTNUM       = DisplayValue;
    else if (pColumn == Column12) USERAUTH         = DisplayValue;
    else if (pColumn == Column10) QUESTION         = DisplayValue;
    else if (pColumn == Column11) ANSWER           = DisplayValue;
    else if (pColumn == Column05) LOGIN_FAIL_COUNT = DisplayValue;
    else if (pColumn == Column13) IS_ACCOUNT_LOCK  = DisplayValue;
    else if (pColumn == Column06) IP_ADDRESS       = DisplayValue;

    USERAUTH = ITSUtil_GetCode(USERAUTH);
    IS_ACCOUNT_LOCK = ITSUtil_GetCode(IS_ACCOUNT_LOCK);

    if (PWD_ORG                != PWD_TMP          ||
        pObj->NAME             != USERNAME         ||
        pObj->CONTACTNUM       != CONTACTNUM       ||
        pObj->USERAUTH         != USERAUTH         ||
        pObj->QUESTION         != QUESTION         ||
        pObj->ANSWER           != ANSWER           ||
        pObj->LOGIN_FAIL_COUNT != LOGIN_FAIL_COUNT ||
        pObj->IS_ACCOUNT_LOCK  != IS_ACCOUNT_LOCK  ||
        pObj->IP_ADDRESS       != IP_ADDRESS )
    {
        m_pGDC->Values[nRow][Column00->Index] = FrmLang->lblModify->Caption;//"수정";
        pObj->EditMode = DB_UPDATE;
    }
    else
    {
        TvList->DataController->Values[nRow][Column00->Index] = "-";
        pObj->EditMode = DB_INIT;
    }
}
//---------------------------------------------------------------------------

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

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

void __fastcall TIDB0140M::MnuDeleteCancelClick(TObject *Sender)
{
    //
}
//---------------------------------------------------------------------------

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

bool __fastcall TIDB0140M::AddObjectItem(TWebUser *pObj, String AMode)
{
    int nRow;
    try
    {
        nRow = m_pGDC->AppendRecord();
        pObj->GridIndex = nRow;

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

        m_pGDC->Values[nRow][Column07->Index] = pObj->USER_ID;
        m_pGDC->Values[nRow][Column01->Index] = pObj->EMAIL;
        m_pGDC->Values[nRow][Column02->Index] = "";   //pObj->PASSWORD;
        m_pGDC->Values[nRow][Column16->Index] = pObj->PWD;
        m_pGDC->Values[nRow][Column03->Index] = pObj->NAME;
        m_pGDC->Values[nRow][Column04->Index] = pObj->CONTACTNUM;
        m_pGDC->Values[nRow][Column12->Index] = pObj->USERAUTH;
        m_pGDC->Values[nRow][Column10->Index] = pObj->QUESTION;
        m_pGDC->Values[nRow][Column11->Index] = pObj->ANSWER;
        m_pGDC->Values[nRow][Column05->Index] = pObj->LOGIN_FAIL_COUNT.ToIntDef(0);
        m_pGDC->Values[nRow][Column13->Index] = pObj->IS_ACCOUNT_LOCK_NM;
        m_pGDC->Values[nRow][Column06->Index] = pObj->IP_ADDRESS;

        if (!pObj->RGST_DT.IsEmpty())
        {
            m_pGDC->Values[nRow][Column14->Index] = ITSUtil_StrToTime(pObj->RGST_DT);
        }

        m_pGDC->Values[nRow][Column88->Index] = pObj->DEL_YN;

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

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

bool __fastcall TIDB0140M::IsUpdate()
{
    FOR_STL(TWebUser*, pObj, MyWebUserManager->FLists)
    {
        if (pObj->Completed && pObj->EditMode != DB_INIT)
            return true;

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

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

    if (!FUpdate)
    {
        if (Application->MessageBox(FrmLang->lblEidtConfirm->Caption.c_str(),//L"변경된 정보가 있습니다.\r\n변경된 정보를 저장 하시겠습니까?",
                                    FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;
    }

    TADOQuery *pADOI = NULL;
    TADOQuery *pADOU = NULL;
    TADOQuery *pADOD = NULL;
	String sQryI;
	String sQryU;
	String sQryD;
    int    nEditMode;
    try
    {
    sQryI= "INSERT INTO TB_WEB_USER_INFR (  \r\n"
           "            USER_ID,            \r\n"
           "            EMAIL,              \r\n"
           "            NAME,               \r\n"
           "            PWD,                \r\n"
           "            CONTACTNUM,         \r\n"
           "            USERAUTH,           \r\n"
           "            QUESTION,           \r\n"
           "            ANSWER,             \r\n"
           "            RGST_DT,            \r\n"
           "            LOGIN_FAIL_COUNT,   \r\n"
           "            IS_ACCOUNT_LOCK,    \r\n"
           "            IP_ADDRESS,         \r\n"
           "            DEL_YN              \r\n"
           "   ) VALUES (                   \r\n"
           "           :p01,                \r\n"
           "           :p02,                \r\n"
           "           :p03,                \r\n"
           "           :p04,                \r\n"
           "           :p05,                \r\n"
           "           :p06,                \r\n"
           "           :p07,                \r\n"
           "           :p08,                \r\n"
           "           :p09,                \r\n"
           "           :p10,                \r\n"
           "           :p11,                \r\n"
           "           :p12,                \r\n"
           "           :p13 )               \r\n";

    sQryU= "MERGE INTO TB_WEB_USER_INFR L                           \r\n"
           "USING (SELECT :p01 AS USER_ID,                          \r\n"
           "              :p02 AS EMAIL,                            \r\n"
           "              :p03 AS NAME,                             \r\n"
           "              :p04 AS PWD,                              \r\n"
           "              :p05 AS CONTACTNUM,                       \r\n"
           "              :p06 AS USERAUTH,                         \r\n"
           "              :p07 AS QUESTION,                         \r\n"
           "              :p08 AS ANSWER,                           \r\n"
           "              :p09 AS RGST_DT,                          \r\n"
           "              :p10 AS LOGIN_FAIL_COUNT,                 \r\n"
           "              :p11 AS IS_ACCOUNT_LOCK,                  \r\n"
           "              :p12 AS IP_ADDRESS,                       \r\n"
           "              :p13 AS DEL_YN                            \r\n"
           "         FROM DUAL) M                                   \r\n"
           "        ON (L.USER_ID = M.USER_ID)                      \r\n"
           "WHEN MATCHED THEN                                       \r\n"
           "   UPDATE SET L.EMAIL            = M.EMAIL,             \r\n"
           "              L.NAME             = M.NAME,              \r\n"
           "              L.PWD              = M.PWD,               \r\n"
           "              L.CONTACTNUM       = M.CONTACTNUM,        \r\n"
           "              L.USERAUTH         = M.USERAUTH,          \r\n"
           "              L.QUESTION         = M.QUESTION,          \r\n"
           "              L.ANSWER           = M.ANSWER,            \r\n"
           "              L.RGST_DT          = M.RGST_DT,           \r\n"
           "              L.LOGIN_FAIL_COUNT = M.LOGIN_FAIL_COUNT,  \r\n"
           "              L.IS_ACCOUNT_LOCK  = M.IS_ACCOUNT_LOCK,   \r\n"
           "              L.IP_ADDRESS       = M.IP_ADDRESS,        \r\n"
           "              L.DEL_YN           = M.DEL_YN             \r\n"
           "WHEN NOT MATCHED THEN                                   \r\n"
           "   INSERT (USER_ID,                                     \r\n"
           "           EMAIL,                                       \r\n"
           "           NAME,                                        \r\n"
           "           PWD,                                         \r\n"
           "           CONTACTNUM,                                  \r\n"
           "           USERAUTH,                                    \r\n"
           "           QUESTION,                                    \r\n"
           "           ANSWER,                                      \r\n"
           "           RGST_DT,                                     \r\n"
           "           LOGIN_FAIL_COUNT,                            \r\n"
           "           IS_ACCOUNT_LOCK,                             \r\n"
           "           IP_ADDRESS,                                  \r\n"
           "           DEL_YN )                                     \r\n"
           "   VALUES (M.USER_ID,                                   \r\n"
           "           M.EMAIL,                                     \r\n"
           "           M.NAME,                                      \r\n"
           "           M.PWD,                                       \r\n"
           "           M.CONTACTNUM,                                \r\n"
           "           M.USERAUTH,                                  \r\n"
           "           M.QUESTION,                                  \r\n"
           "           M.ANSWER,                                    \r\n"
           "           M.RGST_DT,                                   \r\n"
           "           M.LOGIN_FAIL_COUNT,                          \r\n"
           "           M.IS_ACCOUNT_LOCK,                           \r\n"
           "           M.IP_ADDRESS,                                \r\n"
           "           M.DEL_YN )                                   \r\n";

        sQryI = sQryU;

        sQryD = "UPDATE TB_WEB_USER_INFR                                \r\n"
                "   SET RGST_DT = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS')  \r\n"
                "       DEL_YN  = 'Y'                                   \r\n"
                " WHERE USER_ID = :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(TWebUser*, pObj, MyWebUserManager->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 PWD_ORG      = VarToStr(m_pGDC->Values[nRow][Column16->Index]);
                String PWD          = VarToStr(m_pGDC->Values[nRow][Column02->Index]);
                if (PWD != "" || PWD != PWD_ORG)
                {
                    PWD = GetPassword(PWD);
                }
                else
                {
                    PWD = PWD_ORG;
                }

                //String USER_ID          = VarToStr(m_pGDC->Values[nRow][Column07->Index]);
                String USERNAME         = VarToStr(m_pGDC->Values[nRow][Column03->Index]);
                String CONTACTNUM       = VarToStr(m_pGDC->Values[nRow][Column04->Index]);
                String USERAUTH         = VarToStr(m_pGDC->Values[nRow][Column12->Index]);
                String QUESTION         = VarToStr(m_pGDC->Values[nRow][Column10->Index]);
                String ANSWER           = VarToStr(m_pGDC->Values[nRow][Column11->Index]);
                String LOGIN_FAIL_COUNT = VarToStr(m_pGDC->Values[nRow][Column05->Index]);
                String IS_ACCOUNT_LOCK  = VarToStr(m_pGDC->Values[nRow][Column13->Index]);
                String IP_ADDRESS       = VarToStr(m_pGDC->Values[nRow][Column06->Index]);
                if (IS_ACCOUNT_LOCK == "")
                    IS_ACCOUNT_LOCK = "N";

                pObj->USERAUTH_NM        = USERAUTH;
                pObj->IS_ACCOUNT_LOCK_NM = IS_ACCOUNT_LOCK;

                USERAUTH = ITSUtil_GetCode(USERAUTH);
                IS_ACCOUNT_LOCK = ITSUtil_GetCode(IS_ACCOUNT_LOCK);

                //pObj->USER_ID          = USER_ID;
                pObj->PWD              = PWD;
                pObj->NAME             = USERNAME;
                pObj->CONTACTNUM       = CONTACTNUM;
                pObj->USERAUTH         = USERAUTH;
                pObj->QUESTION         = QUESTION;
                pObj->ANSWER           = ANSWER;
                pObj->LOGIN_FAIL_COUNT = LOGIN_FAIL_COUNT;
                pObj->IS_ACCOUNT_LOCK  = IS_ACCOUNT_LOCK;
                pObj->IP_ADDRESS       = IP_ADDRESS;

                pObj->RGST_DT          = Now().FormatString("YYYYMMDDHHNNSS");

                nEditMode = pObj->EditMode;
                if (pObj->Completed)
                {
                    if (pObj->EditMode == DB_DELETE)
                    {
                        //delete
                        ITSDb_SQLBind(pADOD, "p01", pObj->USER_ID);
                        ITSDb_SQLExec(pADOD);
                        pObj->DEL_YN  = "Y";
                        pObj->MEM_DEL = "Y";
                    }
                    else
                    if (pObj->EditMode == DB_UPDATE)
                    {

                        pADOU->Parameters->ParamByName("p01")->Value = pObj->USER_ID;
                        pADOU->Parameters->ParamByName("p02")->Value = pObj->EMAIL;
                        pADOU->Parameters->ParamByName("p03")->Value = pObj->NAME;
                        pADOU->Parameters->ParamByName("p04")->Value = pObj->PWD;
                        pADOU->Parameters->ParamByName("p05")->Value = pObj->CONTACTNUM;
                        pADOU->Parameters->ParamByName("p06")->Value = pObj->USERAUTH;
                        pADOU->Parameters->ParamByName("p07")->Value = pObj->QUESTION;
                        pADOU->Parameters->ParamByName("p08")->Value = pObj->ANSWER;
                        pADOU->Parameters->ParamByName("p09")->Value = pObj->RGST_DT;
                        pADOU->Parameters->ParamByName("p10")->Value = pObj->LOGIN_FAIL_COUNT;
                        pADOU->Parameters->ParamByName("p11")->Value = pObj->IS_ACCOUNT_LOCK;
                        pADOU->Parameters->ParamByName("p12")->Value = pObj->IP_ADDRESS;
                        pADOU->Parameters->ParamByName("p13")->Value = pObj->DEL_YN;

                        ITSDb_SQLExec(pADOU);
                        pObj->DEL_YN  = "N";
                        pObj->MEM_DEL = "N";
                    }
                }
                else
                {
                    if (pObj->EditMode == DB_NEW)
                    {
                        pADOI->Parameters->ParamByName("p01")->Value = pObj->USER_ID;
                        pADOI->Parameters->ParamByName("p02")->Value = pObj->EMAIL;
                        pADOI->Parameters->ParamByName("p03")->Value = pObj->NAME;
                        pADOI->Parameters->ParamByName("p04")->Value = pObj->PWD;
                        pADOI->Parameters->ParamByName("p05")->Value = pObj->CONTACTNUM;
                        pADOI->Parameters->ParamByName("p06")->Value = pObj->USERAUTH;
                        pADOI->Parameters->ParamByName("p07")->Value = pObj->QUESTION;
                        pADOI->Parameters->ParamByName("p08")->Value = pObj->ANSWER;
                        pADOI->Parameters->ParamByName("p09")->Value = pObj->RGST_DT;
                        pADOI->Parameters->ParamByName("p10")->Value = pObj->LOGIN_FAIL_COUNT;
                        pADOI->Parameters->ParamByName("p11")->Value = pObj->IS_ACCOUNT_LOCK;
                        pADOI->Parameters->ParamByName("p12")->Value = pObj->IP_ADDRESS;
                        pADOI->Parameters->ParamByName("p13")->Value = pObj->DEL_YN;

                        ITSDb_SQLExec(pADOI);
                        pObj->DEL_YN  = "N";
                        pObj->MEM_DEL = "N";
                    }
                }
                pObj->Completed = true;
            }
            ITSDb_GetConnection()->CommitTrans();
            Application->MessageBox(FrmLang->lblDbSave->Caption.c_str(),//L"관리자정보를 저장 하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
            FDbUpdate = true;
        }
        catch(EDatabaseError &E)
        {
            ITSDb_GetConnection()->RollbackTrans();
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            if (nEditMode == DB_DELETE)
                DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQryD);
            else
            if (nEditMode == DB_UPDATE)
                DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQryU);
            else
            if (nEditMode == DB_NEW)
                DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQryI);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            ITSDb_GetConnection()->RollbackTrans();
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            if (nEditMode == DB_DELETE)
                DBERRORMSG(Caption, String(e.ClassName()), e.Message, sQryD);
            else
            if (nEditMode == DB_UPDATE)
                DBERRORMSG(Caption, String(e.ClassName()), e.Message, sQryU);
            else
            if (nEditMode == DB_NEW)
                DBERRORMSG(Caption, String(e.ClassName()), e.Message, sQryI);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADOI)
        {
            pADOI->Close();
            delete pADOI;
        }
        if (pADOU)
        {
            pADOU->Close();
            delete pADOU;
        }
        if (pADOD)
        {
            pADOD->Close();
            delete pADOD;
        }
        TvList->EndUpdate();
    }
}
//---------------------------------------------------------------------------

String __fastcall TIDB0140M::GetPassword(String APswd)
{
    int    nRes;
    String sEncPswd = "";
    String sQry;

#if 1
#if 0
    sQry = "SELECT SCP.HASH_B64('71', :p01) AS PWD FROM DUAL \r\n";
#else
    sQry = "SELECT :p01 AS PWD FROM DUAL \r\n";
#endif

    TADOQuery *pADO = NULL;
    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
            pADO->Connection = ITSDb_GetConnection();
            pADO->Close();
            pADO->SQL->Text = sQry;
            pADO->Parameters->ParamByName("p01")->Value = APswd;
            pADO->Prepared = true;
            pADO->Open();
            if (!pADO->Eof)
            {
                pADO->First();
                sEncPswd = pADO->FieldByName("PWD")->AsString;
            }
            pADO->Close();
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName())+E.Message);
        }
        catch (Exception &exception)
        {
            throw Exception(String(exception.ClassName())+exception.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
#else
    sEncPswd = String(ITSSHA256_Encrpyt(AnsiString(APswd)));
#endif

    return sEncPswd;
}
//---------------------------------------------------------------------------

void __fastcall TIDB0140M::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    SaveData();
}
//---------------------------------------------------------------------------

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

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

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

