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

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

#include "IDB0130MF.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 "cxStyles"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinMcSkin"
#pragma resource "*.dfm"

TIDB0130M *IDB0130M = NULL;

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

    FTitle = Caption;//"운영자그룹 메뉴관리";
    FDbUpdate = false;
}
//---------------------------------------------------------------------------

void __fastcall TIDB0130M::CommClose()
{
    try
    {
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

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

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<현재 등록된 운영자그룹 메뉴 정보가 없습니다>";

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

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

    try
    {
        try
        {
            //메뉴권한
    		TcxComboBoxProperties *pcxColumn12 = (TcxComboBoxProperties *)Column12->Properties;
            pcxColumn12->Items->Clear();
            FInitCombo1 = lblY->Caption;//"[Y] 권한있음";
            pcxColumn12->Items->Add(lblY->Caption);//"[Y] 권한있음");
            pcxColumn12->Items->Add(lblN->Caption);//"[N] 권한없음");
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
        catch(...)
        {
            throw Exception(FrmLang->lblDbErr->Caption);//"알수없는 DB 오류가 발생하였습니다.");
        }
    }
    __finally
    {
    }
}
//---------------------------------------------------------------------------

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

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

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

void __fastcall TIDB0130M::RefreshData()
{
    SelListData();
}
//---------------------------------------------------------------------------

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

    String sQry;
    TADOQuery *pADO = NULL;
    try
    {
        TvList->BeginUpdate();

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


#if 0
            sQry = "SELECT X.GROP_ID, X.GROP_NM, X.OPERSYST_MENU_ID, X.ATHR_YN,        \r\n"
                   "       Y.GROP_MENU_NAME, Y.MENU_NAME                               \r\n"
                   "  FROM (SELECT A.GROP_ID, B.GROP_NM, A.OPERSYST_MENU_ID, A.ATHR_YN \r\n"
                   "          FROM TB_USER_GROP_MENU_ATHR A,                           \r\n"
//                   "               TB_USER_GROP_INFR      B                            \r\n"
                   "               TB_USERGROP_INFR      B                            \r\n"
                   "         WHERE A.GROP_ID = B.GROP_ID                               \r\n"
                   "           AND B.DEL_YN = 'N' ) X,                                 \r\n"
                   "       (SELECT B.GROP_MENU_NAME, A.OPERSYST_MENU_ID, A.MENU_NAME   \r\n"
                   "          FROM TB_OPERSYST_MENU A,                                 \r\n"
                   "               (SELECT OPERSYST_MENU_ID AS OPER_SYST_ID,           \r\n"
                   "                       MENU_NAME AS GROP_MENU_NAME                 \r\n"
                   "                  FROM TB_OPERSYST_MENU                            \r\n"
                   "                 WHERE MENU_LEVL = 1                               \r\n"
                   "                   AND DEL_YN = 'N') B                             \r\n"
                   "         WHERE A.OPER_SYST_ID = B.OPER_SYST_ID                     \r\n"
                   "           AND A.MENU_LEVL = 2                                     \r\n"
                   "           AND A.DEL_YN = 'N' ) Y                                  \r\n"
                   " WHERE X.OPERSYST_MENU_ID = Y.OPERSYST_MENU_ID                     \r\n"
                   " ORDER BY X.GROP_ID, Y.GROP_MENU_NAME, Y.MENU_NAME                 \r\n";
#else
            sQry = "SELECT X.GROP_ID, X.GROP_NM, Y.OPERSYST_MENU_ID,                             \r\n"
                   "       NVL((SELECT ATHR_YN                                                   \r\n"
                   "              FROM TB_GROP_MENU_ATHR                                         \r\n"
                   "             WHERE GROP_ID = X.GROP_ID                                       \r\n"
                   "               AND OPERSYST_MENU_ID = Y.OPERSYST_MENU_ID), 'Y') AS ATHR_YN,  \r\n"
                   "       Y.GROP_MENU_NAME, Y.MENU_NAME                                         \r\n"
//                   "  FROM TB_USER_GROP_INFR X,                                                  \r\n"
                   "  FROM TB_USERGROP_INFR X,                                                   \r\n"
                   "       (SELECT B.GROP_MENU_NAME, A.OPERSYST_MENU_ID, A.MENU_NAME             \r\n"
                   "          FROM TB_OPERSYST_MENU A,                                           \r\n"
                   "               (SELECT OPERSYST_MENU_ID AS OPER_SYST_ID,                     \r\n"
                   "                       MENU_NAME AS GROP_MENU_NAME                           \r\n"
                   "                  FROM TB_OPERSYST_MENU                                      \r\n"
                   "                 WHERE MENU_LEVL = 1                                         \r\n"
                   "                   AND DEL_YN = 'N') B                                       \r\n"
                   "         WHERE A.OPER_SYST_ID = B.OPER_SYST_ID                               \r\n"
                   "           AND A.MENU_LEVL = 2                                               \r\n"
                   "           AND A.DEL_YN = 'N' ) Y                                            \r\n";
#endif

			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;
            pADO->Prepared = true;
			pADO->Open();

            int nRow;

            for( ; !pADO->Eof; pADO->Next())
            {
                nRow = m_pGDC->AppendRecord();

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

                m_pGDC->Values[nRow][Column01->Index] = pADO->FieldByName("GROP_ID")->AsString;
                m_pGDC->Values[nRow][Column02->Index] = pADO->FieldByName("GROP_NM")->AsString;
                m_pGDC->Values[nRow][Column03->Index] = pADO->FieldByName("GROP_MENU_NAME")->AsString;
                m_pGDC->Values[nRow][Column04->Index] = pADO->FieldByName("OPERSYST_MENU_ID")->AsString;
                m_pGDC->Values[nRow][Column05->Index] = pADO->FieldByName("MENU_NAME")->AsString;
                m_pGDC->Values[nRow][Column14->Index] = pADO->FieldByName("ATHR_YN")->AsString;

                String sATHR_YN = pADO->FieldByName("ATHR_YN")->AsString;    //권한
                if (sATHR_YN == "Y")
                    m_pGDC->Values[nRow][Column12->Index] = lblY->Caption;//"[Y] 권한있음";
                else
                    m_pGDC->Values[nRow][Column12->Index] = lblN->Caption;//"[N] 권한없음";
            }
        }
    catch(EDatabaseError &E)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQry);
        throw Exception(String(E.ClassName()) + E.Message);
    }
    catch(Exception &e)
    {
        ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
        DBERRORMSG(Caption, String(e.ClassName()), e.Message, sQry);
        throw Exception(String(e.ClassName()) + e.Message);
    }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }

        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 TIDB0130M::BtnCloseClick(TObject *Sender)
{
    Close();
}
//---------------------------------------------------------------------------

void __fastcall TIDB0130M::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"운영자그룹 메뉴";

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

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

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

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

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

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

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

    try
    {
        TvList->BeginUpdate();

        Column00->Visible = bEditing;

        Column12->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 TIDB0130M::TvListColumnPropertiesValidate(TObject *Sender, Variant &DisplayValue, TCaption &ErrorText, bool &Error)

{
    if (TvList->Controller->FocusedRow->IsFilterRow) return;

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

    String ATHR_YN_ORG = VarToStr(m_pGDC->Values[nRow][Column14->Index]);
    String ATHR_YN     = VarToStr(m_pGDC->Values[nRow][Column12->Index]);

    TcxGridColumn *pColumn = TvList->Controller->FocusedColumn;
    if (pColumn == Column12) ATHR_YN = DisplayValue;

    ATHR_YN = ITSUtil_GetCode(ATHR_YN);

    if (ATHR_YN_ORG != ATHR_YN )
    {
        m_pGDC->Values[nRow][Column00->Index] = FrmLang->lblModify->Caption;//"수정";
    }
    else
    {
        TvList->DataController->Values[nRow][Column00->Index] = "-";
    }
}
//---------------------------------------------------------------------------

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

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

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

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

bool __fastcall TIDB0130M::IsUpdate()
{
    try
    {
        TcxGridDataController *pGDC = TvList->DataController;
        TvList->BeginUpdate();
        for(int ii = 0; ii < pGDC->RecordCount; ii++)
        {
            String sEdit = VarToStr(pGDC->Values[ii][Column00->Index]);
            if (sEdit != "-") return true;
        }
	}
	__finally
	{
        TvList->EndUpdate();
	}

    return false;
}
//---------------------------------------------------------------------------

void __fastcall TIDB0130M::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 *pADOU = NULL;
	String sQryU;
    try
    {
        sQryU= "MERGE INTO TB_GROP_MENU_ATHR L                                         \r\n"
               "USING (SELECT :p01 AS GROP_ID,                                         \r\n"
               "              :p02 AS OPERSYST_MENU_ID,                                \r\n"
               "              :p03 AS ATHR_YN                                          \r\n"
               "         FROM DUAL                                                     \r\n"
               "      ) M                                                              \r\n"
               "ON (L.GROP_ID = M.GROP_ID AND L.OPERSYST_MENU_ID = M.OPERSYST_MENU_ID) \r\n"
               "WHEN MATCHED THEN                                                      \r\n"
               "    UPDATE SET L.ATHR_YN = M.ATHR_YN                                   \r\n"
               "WHEN NOT MATCHED THEN                                                  \r\n"
               "    INSERT (L.GROP_ID, L.OPERSYST_MENU_ID, L.ATHR_YN)                  \r\n"
               "    VALUES (M.GROP_ID, M.OPERSYST_MENU_ID, M.ATHR_YN)                  \r\n";

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

            ITSDb_SQLText(pADOU, sQryU);

            ITSDb_GetConnection()->BeginTrans();

            try
            {
                TcxGridDataController *pGDC = TvList->DataController;
                for(int ii = 0; ii < pGDC->RecordCount; ii++)
                {
                    String sEdit = VarToStr(pGDC->Values[ii][Column00->Index]);
                    if (sEdit == "-") continue;

                    String GROP_ID          = VarToStr(pGDC->Values[ii][Column01->Index]);
                    String OPERSYST_MENU_ID = VarToStr(pGDC->Values[ii][Column04->Index]);
                    String ATHR_YN          = VarToStr(pGDC->Values[ii][Column12->Index]);
                    ATHR_YN = ITSUtil_GetCode(ATHR_YN);

                    ITSDb_SQLBind(pADOU, "p01", GROP_ID);
                    ITSDb_SQLBind(pADOU, "p02", OPERSYST_MENU_ID);
                    ITSDb_SQLBind(pADOU, "p03", ATHR_YN);
#if 0
                    ITSDb_SQLBind(pADOU, "p04", g_pLOGIN->sUserId);
#endif
                    ITSDb_SQLExec(pADOU);

                    pGDC->Values[ii][Column14->Index] = ATHR_YN;
                }
            }
            catch(...)
            {
            }

            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);
            DBERRORMSG(Caption, String(E.ClassName()), E.Message, sQryU);
            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);
            DBERRORMSG(Caption, String(e.ClassName()), e.Message, sQryU);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADOU)
        {
            pADOU->Close();
            delete pADOU;
        }
        TvList->EndUpdate();
    }
}
//---------------------------------------------------------------------------

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

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

void __fastcall TIDB0130M::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;
        }
        else
        {
            String sAuth = AViewInfo->GridRecord->DisplayTexts[Column12->Index];
            if (sAuth.Pos("N"))
            {
                ACanvas->Brush->Color = clPurple;
            }
        }
    }
}
//---------------------------------------------------------------------------

