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

#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 "IDB0060MF.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 "cxGridBandedTableView"
#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"

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

    FTitle = Caption;//"소통등급관리";
}
//---------------------------------------------------------------------------

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

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

void __fastcall TIDB0060M::FormInit()
{
    m_pGDC = TvList->DataController;
    FCodeLTC = ItsCodeManager->FLists.Find("LTC");

    TvList->OptionsView->NoDataToDisplayInfoText = FrmLang->lblNoInfo->Caption;//"<소통등급 정보가 없습니다>";

    TcxComboBoxProperties *pcxComboBoxProperties = (TcxComboBoxProperties *)Column13->Properties;
    pcxComboBoxProperties->Items->Add("Y");
    pcxComboBoxProperties->Items->Add("N");
}
//---------------------------------------------------------------------------

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

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

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

void __fastcall TIDB0060M::RefreshData()
{
    // 검색조건에 의한 링크 데이터 조회
    SelListData();
    ChkExpandClick(ChkExpand);
    //TvList->ApplyBestFit(NULL, false, false);
}
//---------------------------------------------------------------------------

void __fastcall TIDB0060M::SelListData()
{
#if 0
101.고속국도
102.도시고속국도
103.일반국도
104.특별·광역시도
105.국가지원지방도
106.지방도
107.시·군도
--108.기타

SRT1	단속류
SRT2	연속류
SRT3	시군도
SRT4	국도
SRT5	도시고속도로
SRT6	고속도로
#endif

    FUpdate = false;

    TItsSubCode *pSubCode;

    CMM_ClearGridTableView(TvList);

    int nTrfClr;
    int nRow = 0;
    try
    {
        TvList->BeginUpdate();

        FOR_STL(TItsTrafficGrade *, pGrade, ItsTrafficGradeManager->FLists)
        {
            FOR_STL(TItsTrafficSubGrade *, pSubGrade, pGrade->FSubLists)
            {
                nRow = m_pGDC->AppendRecord();

                m_pGDC->Values[nRow][Column01->Index] = lbl3Step->Caption;//"3단계 소통등급";
                m_pGDC->Values[nRow][Column02->Index] = "3";

                //도로등급
                m_pGDC->Values[nRow][Column03->Index] = "[" + pGrade->SECT_GRAD_CD + "] " + pGrade->SECT_GRAD_NM;
                m_pGDC->Values[nRow][Column04->Index] = pGrade->SECT_GRAD_CD;

                //소통등급
                String sLTC = "[" + pSubGrade->CMTR_GRAD_CD +"] ";
                if (FCodeLTC)
                {
                    pSubCode = FCodeLTC->FSubLists.Find(pSubGrade->CMTR_GRAD_CD);
                    if (pSubCode) sLTC = sLTC + pSubCode->CMMN_CD_KOR_NM;
                }
                m_pGDC->Values[nRow][Column05->Index] = sLTC;
                m_pGDC->Values[nRow][Column06->Index] = pSubGrade->CMTR_GRAD_CD;

                //nTrfClr = StrToInt();

                m_pGDC->Values[nRow][Column07->Index] = pSubGrade->LWST_TRVL_SPED;
                m_pGDC->Values[nRow][Column08->Index] = pSubGrade->LWST_TRVL_SPED;

                m_pGDC->Values[nRow][Column09->Index] = pSubGrade->HGHS_TRVL_SPED;
                m_pGDC->Values[nRow][Column10->Index] = pSubGrade->HGHS_TRVL_SPED;

                if      (pSubGrade->CMTR_GRAD_CD == "LTC1") nTrfClr = clLime;//65280;
                else if (pSubGrade->CMTR_GRAD_CD == "LTC2") nTrfClr = clYellow;//65535;
                else if (pSubGrade->CMTR_GRAD_CD == "LTC3") nTrfClr = clRed;//255;
                else                                        nTrfClr = clSilver;

                m_pGDC->Values[nRow][Column11->Index] = nTrfClr;
                m_pGDC->Values[nRow][Column12->Index] = nTrfClr;

                m_pGDC->Values[nRow][Column13->Index] = pSubGrade->CNGS_GRAD_YN;
                m_pGDC->Values[nRow][Column14->Index] = pSubGrade->CNGS_GRAD_YN;

                m_pGDC->Values[nRow][Column88->Index] = 0;
                m_pGDC->Values[nRow][Column98->Index] = (int)pGrade;
                m_pGDC->Values[nRow][Column99->Index] = (int)pSubGrade;
            }
        }
    }
    __finally
    {
        TvList->EndUpdate();
        TvList->DataController->GotoFirst();
        TvList->DataController->FocusedRecordIndex = 0;
    }
}
//---------------------------------------------------------------------------

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

void __fastcall TIDB0060M::BtnSaveClick(TObject *Sender)
{
    TcxGrid          *pGrid = CxList;
    TcxGridTableView *pView = TvList;
    String            sTitle= Caption;//"소통등급";

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

void __fastcall TIDB0060M::Column11CustomDrawCell(TcxCustomGridTableView *Sender, TcxCanvas *ACanvas, TcxGridTableDataCellViewInfo *AViewInfo,
          bool &ADone)
{
    try
    {
        //ACanvas->Canvas->Brush->Color = m_pColor[0]->Color;
        int iIndex = AViewInfo->Item->Index;

        String val  = (String)AViewInfo->GridRecord->DisplayTexts[iIndex];

        ACanvas->Canvas->Font->Color  = (TColor)StrToInt(val.c_str());
        ACanvas->Canvas->Brush->Color = (TColor)StrToInt(val.c_str());
    }
    catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TIDB0060M::ChkExpandClick(TObject *Sender)
{
    CMM_ExpandCollapseChk(TvList, ChkExpand->Checked);
}
//---------------------------------------------------------------------------

void __fastcall TIDB0060M::ColValSpdPropertiesChange(TObject *Sender)
{
    if (((TcxSpinEdit*)Sender)->Value < 0)
        ((TcxSpinEdit*)Sender)->Value = 0;
    else if(((TcxSpinEdit*)Sender)->Value > ((TcxSpinEdit*)Sender)->Properties->MaxValue &&
        ((TcxSpinEdit*)Sender)->Properties->MaxValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MaxValue;
}
//---------------------------------------------------------------------------

void __fastcall TIDB0060M::TvListCellClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo, TMouseButton AButton,
          TShiftState AShift, bool &AHandled)
{
#if 0
    if (ACellViewInfo->Item->Index == Column11->Index)
	{
		if (ColorDialog->Execute())
		{
			//m_pColor[0]->Color = ColorDialog->Color;
			//m_pGDC->Values[m_pGDC->FocusedRow->Index-1][Column11->Index] = ColorDialog->Color;
			m_pGDC->Values[m_pGDC->GetFocusedRecordIndex()][Column11->Index] = ColorDialog->Color;
		}
	}
#endif
}
//---------------------------------------------------------------------------

void __fastcall TIDB0060M::TvListMouseMove(TObject *Sender, TShiftState Shift, int X, int Y)
{
    try
    {
        if (!BtnEdit->Down) return;

        TcxGridSite *ASite = (TcxGridSite *)Sender;

        //Screen->Cursor = crDefault;

        //TcxCustomGridHitTest *AHitTest = tvSel->GetHitTest(X, Y);
        TcxCustomGridHitTest *AHitTest = dynamic_cast<TcxGridRecordHitTest*>(ASite->ViewInfo->GetHitTest(X, Y));
        if (dynamic_cast<TcxGridRecordHitTest*>(ASite->ViewInfo->GetHitTest(X, Y)))
        {
            int ARow = ((TcxGridRecordCellHitTest*)AHitTest)->GridRecord->Index;
            if (((TcxGridRecordCellHitTest*)AHitTest)->Item == NULL) return;
            int ACol = ((TcxGridRecordCellHitTest*)AHitTest)->Item->Index;

#if 0
            if (ACol == Column11->Index &&
                ARow < ASite->GridView->DataController->RecordCount-1)
            {
                Screen->Cursor = crHandPoint;
            }
            else
#endif
            if (ACol == Column07->Index &&
                ARow < ASite->GridView->DataController->RecordCount-1)
            {
                Screen->Cursor = crIBeam;
            }
            else
            if (ACol == Column09->Index &&
                ARow < ASite->GridView->DataController->RecordCount-1)
            {
                Screen->Cursor = crIBeam;
            }
            else
            if (ACol == Column13->Index &&
                ARow < ASite->GridView->DataController->RecordCount-1)
            {
                Screen->Cursor = crHandPoint;
            }
        }
        else
        {
            Screen->Cursor = crDefault;
        }
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

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

    try
    {
        TvList->BeginUpdate();

        Column00->Visible = bEditing;

        Column07->Options->Editing = bEditing;
        Column09->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;//데이터 편집";
            Screen->Cursor = crDefault;
        }
    }
}
//---------------------------------------------------------------------------

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

bool __fastcall TIDB0060M::IsUpdate()
{
    int nMemPtr;
    int nMinSpd, nMaxSpd;
    String sGradYn;
    TItsTrafficSubGrade *pSubGrade;

    int nUpdateCnt = 0;
	int nRows = m_pGDC->RecordCount;
    try
    {
        for (int ii = 0; ii < nRows; ii++)
        {
            m_pGDC->Values[ii][Column88->Index] = 0;

            nMemPtr = m_pGDC->Values[ii][Column99->Index];
            pSubGrade = (TItsTrafficSubGrade *)nMemPtr;

            nMinSpd = m_pGDC->Values[ii][Column07->Index];
            nMaxSpd = m_pGDC->Values[ii][Column09->Index];
            sGradYn = m_pGDC->Values[ii][Column13->Index];

            if (nMinSpd != pSubGrade->LWST_TRVL_SPED ||
                nMaxSpd != pSubGrade->HGHS_TRVL_SPED ||
                sGradYn != pSubGrade->CNGS_GRAD_YN)
            {
                m_pGDC->Values[ii][Column88->Index] = 1;
                nUpdateCnt++;
            }
        }
    }
    catch(...)
    {
    }

    if (nUpdateCnt == 0)
    {
        return false;
    }
    return true;
}
//---------------------------------------------------------------------------

void __fastcall TIDB0060M::RollbackListData()
{
    int nStateVal;
    int nMinSpd, nMaxSpd, nColor;
    try
    {
        try
        {
            int nRows = m_pGDC->RecordCount;
            TvList->BeginUpdate();

            for (int ii = 0; ii < nRows; ii++)
            {
                nStateVal = m_pGDC->Values[ii][Column88->Index];
                if (nStateVal == 0) continue;

                nMinSpd = m_pGDC->Values[ii][Column08->Index];
                nMaxSpd = m_pGDC->Values[ii][Column10->Index];
                nColor  = m_pGDC->Values[ii][Column12->Index];

                m_pGDC->Values[ii][Column88->Index] = 0;

                m_pGDC->Values[ii][Column07->Index] = nMinSpd;
                m_pGDC->Values[ii][Column09->Index] = nMaxSpd;
                m_pGDC->Values[ii][Column11->Index] = nColor;
            }
        }
        catch (Exception &exception)
        {
			throw Exception(String(exception.ClassName()) + exception.Message);
        }
	}
	__finally
	{
		TvList->EndUpdate();
	}
}
//---------------------------------------------------------------------------

void __fastcall TIDB0060M::SaveData()
{
	this->Update();

    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)
        {
            RollbackListData();
            return;
        }
    }

	int nStateVal;
    int                  nMemPtr;
    TItsTrafficGrade    *pGrade;
    TItsTrafficSubGrade *pSubGrade;

    int nMinSpd, nMaxSpd;
    String sGradYn;

    bool bSave = false;
    int nUpdateCnt = 0;
	int nRows = m_pGDC->RecordCount;
    TADOQuery *pADO = NULL;
    String sQry;
    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            TvList->BeginUpdate();

			ITSDb_GetConnection()->BeginTrans();
			{
//                sQry = "UPDATE TB_SECT_GRAD_STUP      \r\n"
                sQry = "UPDATE TB_CMTR_GRAD_CLSF      \r\n"
                       "   SET LWST_TRVL_SPED = :p01, \r\n"
                       "       HGHS_TRVL_SPED = :p02, \r\n"
                       "       CNGS_GRAD_YN   = :p03  \r\n"
                       " WHERE SECT_GRAD_CD = :p04    \r\n"
                       "   AND CMTR_GRAD_CD = :p05    \r\n";

                ITSDb_SQLText(pADO, sQry);

                for (int ii = 0; ii < nRows; ii++)
				{
                    TSqlCursor sqlCrs;

                    nStateVal = m_pGDC->Values[ii][Column88->Index];
                    if (nStateVal == 0) continue;

                    nMemPtr = m_pGDC->Values[ii][Column98->Index];
                    pGrade = (TItsTrafficGrade *)nMemPtr;

                    nMemPtr = m_pGDC->Values[ii][Column99->Index];
                    pSubGrade = (TItsTrafficSubGrade *)nMemPtr;

                    nMinSpd = m_pGDC->Values[ii][Column07->Index];
                    nMaxSpd = m_pGDC->Values[ii][Column09->Index];
                    sGradYn = m_pGDC->Values[ii][Column13->Index];

                    ITSDb_SQLBind(pADO, "p01", nMinSpd);
                    ITSDb_SQLBind(pADO, "p02", nMaxSpd);
                    ITSDb_SQLBind(pADO, "p03", sGradYn);
                    ITSDb_SQLBind(pADO, "p04", pGrade->SECT_GRAD_CD);
                    ITSDb_SQLBind(pADO, "p05", pSubGrade->CMTR_GRAD_CD);

					ITSDb_SQLExec(pADO);

                    m_pGDC->Values[ii][Column88->Index] = 0;

                    pSubGrade->LWST_TRVL_SPED = nMinSpd;
                    pSubGrade->HGHS_TRVL_SPED = nMaxSpd;
                    pSubGrade->CNGS_GRAD_YN   = sGradYn;

                    m_pGDC->Values[ii][Column08->Index] = nMinSpd;
                    m_pGDC->Values[ii][Column10->Index] = nMaxSpd;
                    m_pGDC->Values[ii][Column14->Index] = pSubGrade->CNGS_GRAD_YN;
                }
				ITSDb_GetConnection()->CommitTrans();
                bSave = 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, sQry);
            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, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
	}
	__finally
	{
		TvList->EndUpdate();
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        if (bSave)
        {
            Application->ProcessMessages();
            Application->MessageBox(FrmLang->lblDbSave->Caption.c_str(),//L"변경된 소통등급 정보를 저장하였습니다.",
                                    FTitle.c_str(), MB_OK|MB_ICONQUESTION|MB_APPLMODAL);
            RefreshData();  //소통정보 변경을 알리기 위해 먼저 다시 읽어 놓는다.
            POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_01, 0);
            Sleep(500);
            POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_06, 0); //가공서버로 보내는 메시지
        }
	}
}
//---------------------------------------------------------------------------


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

