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

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

#include "IDB0070MF.h"
#include "ITSSELDAYF.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"

TIDB0070M *IDB0070M = NULL;

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

    FTitle = Caption;//"휴일정보관리";
}
//---------------------------------------------------------------------------

void __fastcall TIDB0070M::CommClose()
{
    try
    {
        if (ItsHolidayManager)
        {
            delete ItsHolidayManager;
            ItsHolidayManager = NULL;
        }

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

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

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

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

    if (!ItsHolidayManager)
    {
        ItsHolidayManager = new TItsHolidayManager();
    }

    FCodeLHT = ItsCodeManager->FLists.Find("LHT");

    try {
        TcxComboBoxProperties *pcxColumn02 = (TcxComboBoxProperties *)Column02->Properties;
        pcxColumn02->Items->Clear();

        if (FCodeLHT)
        {
            FOR_STL(TItsSubCode*, pSubCode, FCodeLHT->FSubLists)
            {
                pcxColumn02->Items->Add("[" + pSubCode->CMMN_CD + "] " + pSubCode->CMMN_CD_KOR_NM);
                if (FInitCombo == "") FInitCombo = pSubCode->CMMN_CD;
            }
        }
        else
        {
            //pcxColumn02->Items->Add("[LHT0] 공휴일");
            pcxColumn02->Items->Add("[LHT0] Holiday");
        }
        if (FInitCombo == "") FInitCombo = "LHT0";
    } catch(...) {}
}
//---------------------------------------------------------------------------

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

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

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

void __fastcall TIDB0070M::RefreshData()
{
    ItsHolidayManager->LoadFromDb();
    SelListData();
}
//---------------------------------------------------------------------------

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

    try
    {
        TvList->BeginUpdate();

        FOR_STL(TItsHoliday*, pObj, ItsHolidayManager->FLists)
        {
            pObj->EditMode = DB_INIT;   // 미리초기화해준다.(삭제된것)
            pObj->Completed = true;
            if (pObj->DEL_YN == "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 TIDB0070M::BtnCloseClick(TObject *Sender)
{
    Close();    
}
//---------------------------------------------------------------------------

void __fastcall TIDB0070M::BtnExlSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"휴일정보";

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

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

    try
    {
        ITSSELDAY = new TITSSELDAY(this);
        ITSSELDAY->ShowModal();
        if (ITSSELDAY->Selected == false)
        {
            return;
        }

        String sDay = ITSSELDAY->cxDateEdit1->Date.FormatString("YYYYMMDD");
        TItsHoliday *pDb = (TItsHoliday *)ItsHolidayManager->FLists.Find(sDay);
        if (pDb)
        {
            String sErr = FrmLang->lbIdErr->Caption + "[" + sDay + "]";
            Application->MessageBox(sErr.c_str(),//("[" + sDay + "]는 사용할 수 없는 휴일 입니다.").c_str(),
                                    FTitle.c_str(), nMsgType);
            return;
        }

        try
        {
            TvList->BeginUpdate();

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

            pObj->YMD          = sDay;
            pObj->DAY_TYPE_CD  = FInitCombo;
            pObj->LEGL_HLDY_NM = "";
            pObj->RMRK         = "";

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

            ItsHolidayManager->FLists.Push(pObj->YMD, 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;
        }
    }
    __finally
    {
        if (ITSSELDAY) delete ITSSELDAY;
        ITSSELDAY = NULL;
    }
}
//---------------------------------------------------------------------------

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

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

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

void __fastcall TIDB0070M::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 TIDB0070M::ChangeEditMode(bool AEdit)
{
    bool bEditing = AEdit;

    try 
    {
        TvList->BeginUpdate();
        
        Column00->Visible = bEditing;
    
        Column02->Options->Editing = bEditing;
        Column03->Options->Editing = bEditing;
        Column04->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 TIDB0070M::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];
    TItsHoliday *pObj = (TItsHoliday*)nMemPtr;
    if (pObj->Completed == false)
    {
        //신규이거나 삭제인 경우 편집 내용에 따른 변화가 필요없다.
        return;
    }

    String sType = VarToStr(m_pGDC->Values[nRow][Column02->Index]);
    String sName = VarToStr(m_pGDC->Values[nRow][Column03->Index]);
    String sRmrk = VarToStr(m_pGDC->Values[nRow][Column04->Index]);


    TcxGridColumn *pColumn = TvList->Controller->FocusedColumn;
    if      (pColumn == Column02) sType = DisplayValue;
    else if (pColumn == Column03) sName = DisplayValue;
    else if (pColumn == Column04) sRmrk = DisplayValue;

    sType = ITSUtil_GetCode(sType);

    if (pObj->DAY_TYPE_CD  != sType ||  //요일 유형 코드
        pObj->LEGL_HLDY_NM != sName ||  //공휴일 명
        pObj->RMRK         != sRmrk  )  //비고
    {
        m_pGDC->Values[nRow][Column00->Index] = FrmLang->lblModify->Caption;//"수정";
        pObj->EditMode = DB_UPDATE;
    }
    else
    {
        m_pGDC->Values[nRow][Column00->Index] = "-";
        pObj->EditMode = DB_INIT;
    }
}
//---------------------------------------------------------------------------

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

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

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

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

bool __fastcall TIDB0070M::AddObjectItem(TItsHoliday *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->YMD;

        String sLHTName = "[" + pObj->DAY_TYPE_CD + "] ";
        if (FCodeLHT)
        {
            pSubCode = FCodeLHT->FSubLists.Find(pObj->DAY_TYPE_CD);
            if (pSubCode) sLHTName = sLHTName + pSubCode->CMMN_CD_KOR_NM;
        }
        m_pGDC->Values[nRow][Column02->Index] = sLHTName;
        m_pGDC->Values[nRow][Column03->Index] = pObj->LEGL_HLDY_NM;
        m_pGDC->Values[nRow][Column04->Index] = pObj->RMRK;

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

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

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

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

void __fastcall TIDB0070M::SaveData()
{
    bool bSave = false;

    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_LEGL_HLDY_INFR ( \r\n"
                "            YMD         ,       \r\n"
                "            DAY_TYPE_CD ,       \r\n"
                "            LEGL_HLDY_NM,       \r\n"
                "            RMRK       )        \r\n"
                "   VALUES (                     \r\n"
                "           :p01,                \r\n"
                "           :p02,                \r\n"
                "           :p03,                \r\n"
                "           :p04 )               \r\n";

        sQryU = "UPDATE TB_LEGL_HLDY_INFR    \r\n"
                "   SET DAY_TYPE_CD  = :p02, \r\n"
                "       LEGL_HLDY_NM = :p03, \r\n"
                "       RMRK         = :p04  \r\n"
                " WHERE YMD          = :p01  \r\n";

        sQryD = "DELETE TB_LEGL_HLDY_INFR   \r\n"
                " WHERE YMD      = :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(TItsHoliday*, pObj, ItsHolidayManager->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 sDay  = VarToStr(m_pGDC->Values[nRow][Column01->Index]);
                String sType = VarToStr(m_pGDC->Values[nRow][Column02->Index]);
                String sName = VarToStr(m_pGDC->Values[nRow][Column03->Index]);
                String sRmrk = VarToStr(m_pGDC->Values[nRow][Column04->Index]);

                sType = ITSUtil_GetCode(sType);

                //pObj->YMD          = sDay;
                pObj->DAY_TYPE_CD  = sType;
                pObj->LEGL_HLDY_NM = sName;
                pObj->RMRK         = sRmrk;

                nEditMode = pObj->EditMode;
                if (pObj->Completed)
                {
                    if (pObj->EditMode == DB_DELETE)
                    {
                        //delete
                        ITSDb_SQLBind(pADOD, "p01", pObj->YMD);
                        ITSDb_SQLExec(pADOD);
                        pObj->DEL_YN = "Y";
                    }
                    else
                    if (pObj->EditMode == DB_UPDATE)
                    {
                        //update
                        ITSDb_SQLBind(pADOU, "p01", pObj->YMD);
                        ITSDb_SQLBind(pADOU, "p02", pObj->DAY_TYPE_CD);
                        ITSDb_SQLBind(pADOU, "p03", pObj->LEGL_HLDY_NM);
                        ITSDb_SQLBind(pADOU, "p04", pObj->RMRK);
                        ITSDb_SQLExec(pADOU);
                        pObj->DEL_YN = "N";
                    }
                }
                else
                {
                    if (pObj->EditMode == DB_NEW)
                    {
                        //insert
                        ITSDb_SQLBind(pADOI, "p01", pObj->YMD);
                        ITSDb_SQLBind(pADOI, "p02", pObj->DAY_TYPE_CD);
                        ITSDb_SQLBind(pADOI, "p03", pObj->LEGL_HLDY_NM);
                        ITSDb_SQLBind(pADOI, "p04", pObj->RMRK);
                        ITSDb_SQLExec(pADOI);
                        pObj->DEL_YN = "N";
                    }
                }
                pObj->Completed = true;
            }
            bSave = true;
            ITSDb_GetConnection()->CommitTrans();
        }
        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();
    }

    if (bSave)
    {
        Application->ProcessMessages();
        Application->MessageBox(FrmLang->lblDbSave->Caption.c_str(),//L"휴일정보를 저장 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
        POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_04, 0);
    }
}
//---------------------------------------------------------------------------

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

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

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

void __fastcall TIDB0070M::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;
        }
    }
}
//---------------------------------------------------------------------------

