// ColumnSetupDlg.cpp : implementation file
//

#include "stdafx.h"
#include "resource.h"
#include "ColumnSetupDlg.h"
#include "SimplDlg.h"
#include "ReportDict.h"
#include "LevelPropDlg.h"
#include "GSSetupDlg.h"
#include <AplGuiEx.h>


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CColumnSetupDlg dialog


CColumnSetupDlg::CColumnSetupDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CColumnSetupDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CColumnSetupDlg)
	//}}AFX_DATA_INIT
	m_section = NULL;		
	m_GroupCol = NULL;
	m_ReportMgr = NULL;
	m_dlg_mode = APL_DLG_MODE_CREATE;
	m_bDelTitleCol = false;
	m_sTitleColName.Empty();
}


void CColumnSetupDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CColumnSetupDlg)
	DDX_Control(pDX, IDC_STATIC_IMAGE, m_ImageCtrl);
	DDX_Control(pDX, IDC_PROP_COL, m_prop_col_btn);
	DDX_Control(pDX, IDC_DEL_COL, m_del_col_btn);
	DDX_Control(pDX, IDC_ADD_COL, m_add_col_btn);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_MOVE_UP, m_up);
	DDX_Control(pDX, IDC_MOVE_DOWN, m_down);
	DDX_Control(pDX, IDC_LEVEL_TABLE, m_level_ctrl);
	DDX_Control(pDX, IDC_COLUMN_TABLE, m_column_ctrl);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CColumnSetupDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CColumnSetupDlg)
	ON_NOTIFY(NM_RCLICK, IDC_COLUMN_TABLE, OnRclickColumnTable)
	ON_NOTIFY(NM_RCLICK, IDC_LEVEL_TABLE, OnRclickLevelTable)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LEVEL_TABLE, OnItemchangedLevelTable)
	ON_BN_CLICKED(IDC_MOVE_UP, OnMoveUp)
	ON_BN_CLICKED(IDC_MOVE_DOWN, OnMoveDown)
	ON_NOTIFY(NM_DBLCLK, IDC_COLUMN_TABLE, OnDblclkColumnTable)
	ON_NOTIFY(LVN_ITEMCHANGING, IDC_LEVEL_TABLE, OnItemchangingLevelTable)
	ON_NOTIFY(LVN_KEYDOWN, IDC_COLUMN_TABLE, OnKeydownColumnTable)
	ON_BN_CLICKED(IDC_GROUPS, OnGroups)
	ON_BN_CLICKED(IDC_ADD_COL, OnAddCol)
	ON_BN_CLICKED(IDC_DEL_COL, OnDelCol)
	ON_BN_CLICKED(IDC_PROP_COL, OnPropCol)
	ON_NOTIFY(NM_DBLCLK, IDC_LEVEL_TABLE, OnDblclkLevelTable)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CColumnSetupDlg message handlers

BOOL CColumnSetupDlg::OnInitDialog() 
{
	CaplResizableDialog::OnInitDialog();

	if(m_dlg_mode==APL_DLG_MODE_SELECT)
	{
		SetWindowText(APL_T("Выбор..."));
	}
	else
	{
		HICON hIcon = aplGetStdIco16(APL_STD_SECTION_PROP);
		SetIcon(hIcon, FALSE);
		::DestroyIcon(hIcon);
	}
	if(m_section==NULL && m_GroupCol==NULL)
	{
		EndDialog(0);
		return FALSE;
	}


	AddAnchor(IDC_STATIC_LEVEL,TOP_LEFT);
	AddAnchor(IDC_STATIC_COLUMN,TOP_LEFT,TOP_RIGHT);

	AddAnchor(IDC_COLUMN_TABLE,TOP_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_LEVEL_TABLE,TOP_LEFT,BOTTOM_LEFT);
	AddAnchor(IDC_MOVE_UP,TOP_RIGHT);
	AddAnchor(IDC_MOVE_DOWN,TOP_RIGHT);
	AddAnchor(IDOK,BOTTOM_RIGHT);
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	AddAnchor(IDC_GROUPS,BOTTOM_LEFT);

	AddAnchor(IDC_ADD_COL, TOP_RIGHT);
	AddAnchor(IDC_DEL_COL, TOP_RIGHT);
	AddAnchor(IDC_PROP_COL, TOP_RIGHT);

	m_add_col_btn.SetWindowText(_T(""));
	m_add_col_btn.SetIcon(aplGetStdIco16(APL_STD_ADD_COLUMN));
	m_del_col_btn.SetWindowText(_T(""));
	m_del_col_btn.SetIcon(aplGetStdIco16(APL_STD_DELETE));
	m_prop_col_btn.SetWindowText(_T(""));
	m_prop_col_btn.SetIcon(aplGetStdIco16(APL_STD_PROPERTIES));

	m_up.SetIcon(aplGetStdIco16(APL_STD_TOP));
	m_down.SetIcon(aplGetStdIco16(APL_STD_BOTTOM));

	m_ok_btn.SetIcon(aplGetStdIco16(APL_STD_OK));
	m_ok_btn.SetFlat(FALSE);
	m_cancel_btn.SetIcon(aplGetStdIco16(APL_STD_CANCEL));
	m_cancel_btn.SetFlat(FALSE);

	m_level_ctrl.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT);
	m_level_ctrl.InsertColumn(0,APL_T("Уровень"),LVCFMT_LEFT,150);
	m_column_ctrl.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT);
	m_column_ctrl.ModifyStyle(LVS_SINGLESEL, 0);
	m_column_ctrl.InsertColumn(0,APL_T("Позиция"),LVCFMT_LEFT,60);
	m_column_ctrl.InsertColumn(1,APL_T("Наименование"),LVCFMT_LEFT,190);
	m_column_ctrl.InsertColumn(2,APL_T("Ширина"),LVCFMT_LEFT,60);
	m_column_ctrl.InsertColumn(3,APL_T("Поле источника данных"),LVCFMT_LEFT,100);

	if(m_section==NULL || m_dlg_mode==APL_DLG_MODE_SELECT)
	{
		GetDlgItem(IDC_GROUPS)->ShowWindow(SW_HIDE);
	}

	int cnt = 0;
	if(m_section)
	{
		cnt = m_section->m_levels.GetSize();
		m_ReportMgr = m_section->m_ReportMgr;
		pLArray = &m_section->m_levels;
		if(m_section->m_title_column)
			m_sTitleColName = m_section->m_title_column->m_name;
	}
	else if(m_dlg_mode==APL_DLG_MODE_CREATE_GROUP)
	{
		cnt = m_GroupCol->m_row.GetSize();
		m_ReportMgr = m_GroupCol->m_ReportMgr;
		pLArray = &m_GroupCol->m_row;
	}
	else if(m_dlg_mode==APL_DLG_MODE_CREATE_LR_GROUP)
	{
		cnt = m_GroupCol->m_last_row.GetSize();
		m_ReportMgr = m_GroupCol->m_ReportMgr;
		pLArray = &m_GroupCol->m_last_row;
	}
	else if(m_dlg_mode==APL_DLG_MODE_CREATE_ONE_GROUP)
	{
		cnt = m_GroupCol->m_one_row.GetSize();
		m_ReportMgr = m_GroupCol->m_ReportMgr;
		pLArray = &m_GroupCol->m_one_row;
	}
	else
	{
		ASSERT(0);
		EndDialog(0);
	}
	m_levels = NULL;
	if(m_dlg_mode!=APL_DLG_MODE_SELECT)
	{
		m_levels = new CSectionLevelArray;
		*m_levels = (*pLArray);
		for(int i=0;i<cnt;i++)
		{
			CSectionLevel* level = m_levels->GetAt(i);
			m_level_ctrl.InsertItem(i,level->m_name);
			m_level_ctrl.SetItemData(i,(DWORD)level);
		}
	}
	else
	{
		m_levels = pLArray;
		for(int i=0;i<cnt;i++)
		{
			CSectionLevel* old = pLArray->GetAt(i);
			m_level_ctrl.InsertItem(i,old->m_name);
			m_level_ctrl.SetItemData(i,(DWORD)old);
		}
	}
	SelectString(&m_level_ctrl,0);
	ShowData(m_levels->GetAt(0));
	SelectString(&m_column_ctrl,0);
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CColumnSetupDlg::OnRclickColumnTable(NMHDR* pNMHDR, LRESULT* pResult) 
{
	if(m_dlg_mode==APL_DLG_MODE_SELECT) return;
	NMLISTVIEW* pLV = (NMLISTVIEW*)pNMHDR;
	CPoint pt = pLV->ptAction;
	CMenu menu;
	CMenu *pPopup;
	menu.LoadMenu(IDR_CONTEXT_MENU);
	pPopup = menu.GetSubMenu(3);
	m_column_ctrl.ClientToScreen(&pt);
	int c_ind = m_column_ctrl.GetNextItem(-1,LVIS_SELECTED);
	int ind = m_level_ctrl.GetNextItem(-1,LVIS_SELECTED);
	pPopup->ModifyMenu(ID_COPY,MF_BYCOMMAND, ID_COPY, APL_T("Копировать..."));
	if(c_ind<0 || ind<0)
	{
		pPopup->EnableMenuItem(ID_PROPERTY,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_DELETE,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_COPY,MF_BYCOMMAND|MF_GRAYED);
	}
	if(ind<0)
	{
		pPopup->EnableMenuItem(ID_ADD,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_COPY,MF_BYCOMMAND|MF_GRAYED);
	}
	BOOL res = pPopup->TrackPopupMenu(TPM_RIGHTBUTTON|TPM_LEFTALIGN|TPM_RETURNCMD,pt.x,pt.y,&m_column_ctrl);
	switch(res) 
	{
	case ID_ADD : 
		AddColumn();
		break;
	case ID_DELETE : 
		OnDelCol();
		break;
	case ID_PROPERTY:
		ColumnProp();
		break;
	case ID_COPY:
		CopyColumn(c_ind);
		break;
	}
	*pResult = 0;
}

void CColumnSetupDlg::OnRclickLevelTable(NMHDR* pNMHDR, LRESULT* pResult) 
{
	if(m_dlg_mode==APL_DLG_MODE_SELECT) return;
	NMLISTVIEW* pLV = (NMLISTVIEW*)pNMHDR;
	CPoint pt = pLV->ptAction;
	CMenu menu;
	CMenu *pPopup;
	menu.LoadMenu(IDR_CONTEXT_MENU);
	pPopup = menu.GetSubMenu(4);
	m_level_ctrl.ClientToScreen(&pt);
	int ind = m_level_ctrl.GetNextItem(-1,LVIS_SELECTED);
	if(ind<0)
	{
		pPopup->EnableMenuItem(ID_PROPERTY,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_DELETE,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_LEVEL_COPY,MF_BYCOMMAND|MF_GRAYED);
		pPopup->EnableMenuItem(ID_CLONE,MF_BYCOMMAND|MF_GRAYED);
	}
	COleDataObject pDataObject;
	if(pDataObject.AttachClipboard())
	{
		UINT cf_hinst=RegisterClipboardFormat(APL_LEVEL_CLIPBOARD_DATA);
		if(!pDataObject.IsDataAvailable(cf_hinst))
			pPopup->EnableMenuItem(ID_LEVEL_PASTE, MF_BYCOMMAND|MF_GRAYED);
	}
	else
		pPopup->EnableMenuItem(ID_LEVEL_PASTE, MF_BYCOMMAND|MF_GRAYED);
	BOOL res = pPopup->TrackPopupMenu(TPM_RIGHTBUTTON|TPM_LEFTALIGN|TPM_RETURNCMD,pt.x,pt.y,&m_column_ctrl);
	switch(res) 
	{
	case ID_ADD : 
		{
			CLevelPropDlg dlg(m_ReportMgr);
			dlg.m_pLevels = m_levels;
			if(dlg.DoModal()==IDOK)
			{
				ind = m_level_ctrl.InsertItem(m_level_ctrl.GetItemCount(), dlg.m_pLevel->m_name);
				m_level_ctrl.SetItemData(ind,(DWORD)dlg.m_pLevel);
				SelectString(&m_level_ctrl, ind);
			}
		}
		break;
	case ID_DELETE : 
		{
			CString txt;
			m_column_ctrl.GetItemText(ind,1);
			CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(ind);
			ASSERT(level);
			m_levels->RemoveAt(m_levels->Find(level));
			m_level_ctrl.DeleteItem(ind);
			SelectString(&m_level_ctrl,ind-1);
		}
		break;
	case ID_PROPERTY:
		LevelProp(ind);
		break;
	case ID_CLONE:
		CopyLevel(ind);
		break;
	case ID_LEVEL_COPY:
		CopyLevelToMem(ind);
		break;
	case ID_LEVEL_PASTE:
		PasteLevel();
		break;
	}
	*pResult = 0;
}

void CColumnSetupDlg::OnOK() 
{
	if(m_dlg_mode!=APL_DLG_MODE_SELECT)
	{
		OnItemchangingLevelTable(NULL,NULL);
		pLArray->RemoveAll();
		for(int i=0;i<m_levels->GetSize();i++)
			pLArray->Add(m_levels->GetAt(i));
		m_levels->Clear();
		if(m_bDelTitleCol && m_section)
			m_section->m_title_column = NULL;
		else if(m_section)
		{
			//Определяем нашу колонку.
			bool bFind = false;
			for(int i=0; i<pLArray->GetSize(); i++)
			{
				CSectionLevel* level = pLArray->GetAt(i);
				for(int j=0; j<level->m_columns.GetSize(); j++)
				{
					if(level->m_columns.GetAt(j)->m_name==m_sTitleColName)
					{
						m_section->m_title_column = level->m_columns.GetAt(j);
						bFind = true;
						break;
					}
				}
				if(bFind)
					break;
			}
			if(!bFind)
				m_section->m_title_column = NULL;
		}
		delete m_levels;
	}
	else
	{
		int ind = m_column_ctrl.GetNextItem(-1,LVIS_SELECTED);
		if(ind<0)
			m_select=NULL;
		else
			m_select = (CColumn*)m_column_ctrl.GetItemData(ind);
	}

	CaplResizableDialog::OnOK();
}

void CColumnSetupDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	if(m_levels!=pLArray)
	{
		m_levels->RemoveAll();
		delete m_levels;
	}
	
	CaplResizableDialog::OnCancel();
}

void CColumnSetupDlg::ShowData(CSectionLevel* level)
{
	m_column_ctrl.DeleteAllItems();
	if(level==0) return;
	CString str;
	int cnt = level->m_columns.GetSize();
	for(int i=0;i<cnt;i++)
	{
		str.Format(_T("%d"),m_column_ctrl.GetItemCount()+1);
		int ind = m_column_ctrl.InsertItem(i,str);
		m_column_ctrl.SetItemText(ind,1,level->m_columns.GetAt(i)->m_name);
		double d = level->m_columns.GetAt(i)->m_width; d=d/10;
		str.Format(_T("%.1f"),d);
		m_column_ctrl.SetItemText(ind,2,str);
		if(level->m_columns.GetAt(i)->m_show_flag==APL_COLUMN_SHOW_LEVEL_NAME)
			m_column_ctrl.SetItemText(ind,3,APL_T("Уровень"));
		else if(level->m_columns.GetAt(i)->m_show_flag==APL_COLUMN_SHOW_ROW_NUM)
			m_column_ctrl.SetItemText(ind,3,APL_T("Порядковый номер"));
		else if(level->m_columns.GetAt(i)->m_ds_column)
		{
			CHeaderColumn* col = level->m_columns.GetAt(i)->m_ds_column;
			if(col)
				m_column_ctrl.SetItemText(ind,3,col->GetName());
		}
		m_column_ctrl.SetItemData(ind,DWORD(level->m_columns.GetAt(i)));
	}
}

void CColumnSetupDlg::OnItemchangedLevelTable(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
	int ind = m_level_ctrl.GetNextItem(-1,LVIS_SELECTED);
	if(ind>-1) ShowData((CSectionLevel*)m_level_ctrl.GetItemData(ind));
	else
		ShowData(NULL);
	*pResult = 0;
}

void CColumnSetupDlg::RefreshColumns()
{
	int cnt = m_column_ctrl.GetItemCount();
	for(int i=0;i<cnt;i++)
	{
		CColumn* col = (CColumn*)m_column_ctrl.GetItemData(i);
		col->m_ind = i+1;
		CString str;
		str.Format(_T("%d"),i+1);
		m_column_ctrl.SetItemText(i,0,str);
	}
}

void CColumnSetupDlg::OnMoveUp() 
{
	int ind = m_column_ctrl.GetNextItem(-1,LVIS_SELECTED);
	if(ind<=0) return;
	CString txt2 = m_column_ctrl.GetItemText(ind,1);
	CString txt3 = m_column_ctrl.GetItemText(ind,2);
	CColumn* col1 = (CColumn*)m_column_ctrl.GetItemData(ind);
	CColumn* col2 = (CColumn*)m_column_ctrl.GetItemData(ind-1);
	col1->m_ind--;
	col2->m_ind++;
	m_column_ctrl.DeleteItem(ind);
	CString txt1;
	txt1.Format(_T("%d"),col1->m_ind);
	int i = m_column_ctrl.InsertItem(ind-1,txt1);
	m_column_ctrl.SetItemText(i,1,txt2);
	m_column_ctrl.SetItemText(i,2,txt3);
	txt1.Format(_T("%d"),col2->m_ind);
	m_column_ctrl.SetItemText(ind-1,0,txt1);
	txt1 = _T("");
	if(col1->m_ds_column!=0)
		txt1 = col1->m_ds_column->m_name;
	if(col1->m_show_flag==APL_COLUMN_SHOW_LEVEL_NAME)
		txt1 = APL_T("Уровень");
	else if(col1->m_show_flag==APL_COLUMN_SHOW_ROW_NUM)
		txt1 = APL_T("Порядковый номер");
	m_column_ctrl.SetItemText(i,3,txt1);
	m_column_ctrl.SetItemData(i,DWORD(col1));
	RefreshColumns();
	SelectString(&m_column_ctrl,ind-1);
}

void CColumnSetupDlg::OnMoveDown() 
{
	int l_ind = m_level_ctrl.GetNextItem(-1,LVIS_SELECTED);
	if(l_ind<0) return;
	CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(l_ind);
	if(level==0) return;
	int ind = m_column_ctrl.GetNextItem(-1,LVIS_SELECTED);
	int cnt = m_column_ctrl.GetItemCount();
	if(ind>=cnt-1 || ind<0) return;
	CString txt2 = m_column_ctrl.GetItemText(ind,1);
	CString txt3 = m_column_ctrl.GetItemText(ind,2);
	CColumn* col1 = (CColumn*)m_column_ctrl.GetItemData(ind);
	CColumn* col2 = (CColumn*)m_column_ctrl.GetItemData(ind+1);
	col1->m_ind++;
	col2->m_ind--;
	m_column_ctrl.DeleteItem(ind);
	CString txt1;
	txt1.Format(_T("%d"),col1->m_ind);
	int i = m_column_ctrl.InsertItem(ind+1,txt1);
	m_column_ctrl.SetItemText(i,1,txt2);
	m_column_ctrl.SetItemText(i,2,txt3);
	txt1.Format(_T("%d"),col2->m_ind);
	m_column_ctrl.SetItemText(ind,0,txt1);
	txt1 = _T("");
	if(col1->m_ds_column!=0)
		txt1 = col1->m_ds_column->m_name;
	if(col1->m_show_flag==APL_COLUMN_SHOW_LEVEL_NAME)
		txt1 = APL_T("Уровень");
	else if(col1->m_show_flag==APL_COLUMN_SHOW_ROW_NUM)
		txt1 = APL_T("Порядковый номер");
	m_column_ctrl.SetItemText(i,3,txt1);
	m_column_ctrl.SetItemData(i,DWORD(col1));
	RefreshColumns();
	SelectString(&m_column_ctrl,ind+1);
}


void CColumnSetupDlg::SelectString(CListCtrl *ctrl, int row)
{
	if(ctrl==NULL) return;
	if(!::IsWindow(ctrl->m_hWnd)) return;
	int cnt = ctrl->GetItemCount();
	if(row<0 || row>=cnt) return;
	while(ctrl->GetNextItem(-1, LVIS_SELECTED)>-1)
		ctrl->SetItemState(ctrl->GetNextItem(-1, LVIS_SELECTED), 0, LVIS_SELECTED|LVIS_FOCUSED);

	ctrl->SetItemState(row,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED);
}

void CColumnSetupDlg::OnDblclkColumnTable(NMHDR* pNMHDR, LRESULT* pResult) 
{
	if(m_dlg_mode==APL_DLG_MODE_SELECT)
	{
		OnOK();
		return;
	}
	ColumnProp();
	*pResult = 0;
}

void CColumnSetupDlg::OnItemchangingLevelTable(NMHDR* pNMHDR, LRESULT* pResult) 
{
	int ind = m_level_ctrl.GetNextItem(-1,LVIS_SELECTED);
	if(ind>-1)
	{
		//Сохранение в нужной последовательности.
		CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(ind);
		if(level==0) return;
		for(int i=0; i<m_column_ctrl.GetItemCount();i++)
		{
			CColumn* col = (CColumn*)m_column_ctrl.GetItemData(i);
			level->m_columns.Move(col,i);
		}
	}
}

void CColumnSetupDlg::AddColumn()
{
	CopyColumn();
}

void CColumnSetupDlg::ColumnProp()
{
	int c_ind = m_column_ctrl.GetNextItem(-1,LVIS_SELECTED|LVIS_FOCUSED);
	int ind = m_level_ctrl.GetNextItem(-1,LVIS_SELECTED);
	if(ind<0 || c_ind<0) return;
	CColumn* col = (CColumn*)m_column_ctrl.GetItemData(c_ind);
	CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(ind);
	int t_ind;
	ASSERT(col);
	ASSERT(level);
	CSimplDlg dlg;
	int res; 
	do 
	{
		if(m_dlg_mode!=APL_DLG_MODE_CREATE_LR_GROUP && m_dlg_mode!=APL_DLG_MODE_CREATE_GROUP && m_dlg_mode!=APL_DLG_MODE_CREATE_ONE_GROUP)
			dlg.m_show = APL_FULL_MODE;
		else
			dlg.m_show = APL_FULL_EX_MODE;
		dlg.m_title = APL_T("Свойства поля");
		dlg.m_width = col->m_width;
		dlg.m_text = col->m_name;
		dlg.m_ReportMgr = m_ReportMgr;
		dlg.m_ds_column = col->m_ds_column;
		dlg.m_show_flag = col->m_show_flag;
		dlg.m_align = col->m_align;
		dlg.m_bShowasDate = col->m_params&APL_COLUMN_SHOWASDATE;
		dlg.m_bShowAsTime = col->m_params&APL_COLUMN_SHOWASTIME;
		dlg.m_SpacePara = col->m_SpacePara;
		dlg.m_line_width = float(col->m_border)/10;
		dlg.m_ColumnType = col->m_ColumnType;
		dlg.m_iStrCount = col->m_RowsCount;
		dlg.m_sConditions = col->m_sCondition;
		dlg.m_bNotShowZero = (col->m_params&APL_COLUMN_NOT_SHOW_ZERO)!=0?TRUE:FALSE;
		dlg.m_bShowTopLine = (col->m_params&APL_COLUMN_SHOW_TOP_LINE)!=0?TRUE:FALSE;
		if(col->m_ColumnType==aplSTRCONST)
			dlg.m_column_text = col->m_TextCnst;
		if(col->m_fit_to_rect!=0)
			dlg.m_fit_to_rect = TRUE;
		else
			dlg.m_fit_to_rect = FALSE;
		if(m_dlg_mode==APL_DLG_MODE_CREATE_GROUP || m_dlg_mode==APL_DLG_MODE_CREATE_LR_GROUP
			 || m_dlg_mode==APL_DLG_MODE_CREATE_ONE_GROUP)
			dlg.m_IsGroup = TRUE;
		res = dlg.DoModal();
		if(res==IDOK)
		{
			t_ind = level->m_columns.Find(dlg.m_text);
			if(t_ind>-1 && level->m_columns.GetAt(t_ind)!=col)
			{
				AfxMessageBox(APL_T("Имя уровня не уникально!"));
				continue;
			}
		}
		break;
	} while(true);
	if(res==IDOK)
	{
		col->m_params = 0;
		col->m_align = dlg.m_align;
		if(dlg.m_bShowasDate)
			col->m_params |= APL_COLUMN_SHOWASDATE;
		if(dlg.m_bShowAsTime)
			col->m_params |= APL_COLUMN_SHOWASTIME;
		if(dlg.m_bNotShowZero)
			col->m_params|=APL_COLUMN_NOT_SHOW_ZERO;
		if(dlg.m_bShowTopLine)
			col->m_params|=APL_COLUMN_SHOW_TOP_LINE;
		col->m_SpacePara = dlg.m_SpacePara;
		col->m_border = int(dlg.m_line_width*10);
		col->m_name = dlg.m_text;
		col->m_width = int(dlg.m_width*10);
		col->m_show_flag = dlg.m_show_flag;
		col->m_ds_column = dlg.m_ds_column;
		col->m_fit_to_rect = dlg.m_fit_to_rect;
		col->m_ColumnType = dlg.m_ColumnType;
		col->m_RowsCount = dlg.m_iStrCount;
		col->m_sCondition = dlg.m_sConditions;
		if(dlg.m_ColumnType==aplSTRCONST)
			col->m_TextCnst = dlg.m_column_text;
		else
			col->m_TextCnst.Empty();
		m_column_ctrl.SetItemText(c_ind,1,col->m_name);
		CString width;
		double d = col->m_width; d=d/10;
		width.Format(_T("%.1f"),d);
		m_column_ctrl.SetItemText(c_ind,2,width);
		m_column_ctrl.SetItemText(c_ind,3,_T(""));
		if(col->m_show_flag==APL_COLUMN_SHOW_LEVEL_NAME)
			m_column_ctrl.SetItemText(c_ind, 3, APL_T("Уровень"));
		else if(col->m_show_flag==APL_COLUMN_SHOW_ROW_NUM)
			m_column_ctrl.SetItemText(c_ind, 3, APL_T("Порядковый номер"));
		else if(col->m_ds_column)
				m_column_ctrl.SetItemText(c_ind,3,col->m_ds_column->GetName());

		SelectString(&m_column_ctrl,c_ind);
	}
}

void CColumnSetupDlg::OnKeydownColumnTable(NMHDR* pNMHDR, LRESULT* pResult) 
{
	LV_KEYDOWN* pLVKeyDow = (LV_KEYDOWN*)pNMHDR;
	// TODO: Add your control notification handler code here
	if(pLVKeyDow->wVKey==VK_INSERT)
		AddColumn();
	
	*pResult = 0;
}

void CColumnSetupDlg::OnGroups() 
{
	CGSSetupDlg dlg;
	dlg.m_section = m_section;
	dlg.DoModal();
}

void CColumnSetupDlg::OnAddCol() 
{
	AddColumn();	
}

void CColumnSetupDlg::OnDelCol() 
{
	int c_ind = m_column_ctrl.GetNextItem(-1,LVIS_SELECTED);
	int ind = m_level_ctrl.GetNextItem(-1,LVIS_SELECTED);
	if(c_ind<0 || ind<0)  return;
	
	CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(ind);
	ASSERT(level);
	
	while((c_ind = m_column_ctrl.GetNextItem(-1,LVIS_SELECTED))>-1)
	{
		CString txt = m_column_ctrl.GetItemText(c_ind,1);
		int nInd = level->m_columns.Find(txt);
		CColumn* col = level->m_columns.GetAt(nInd);
		if(col)
		{
			if(m_section)
			{
				if(m_section->m_title_column)
					if(m_section->m_title_column->m_name==col->m_name)
						m_bDelTitleCol = true;
			}
			level->m_columns.RemoveAt(nInd);
			m_column_ctrl.DeleteItem(c_ind);
			int i;
			CString buf;
			for(i=c_ind; i<m_column_ctrl.GetItemCount(); i++)
			{
				buf = m_column_ctrl.GetItemText(i, 0);
				ind = _atoi(buf)-1;
				buf.Format(_T("%i"), ind);
				m_column_ctrl.SetItemText(i, 0, buf);
			}
		}
	}
	if(m_column_ctrl.GetItemCount()>c_ind)
		m_column_ctrl.SetItemState(c_ind, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
	else if(c_ind>0)
		m_column_ctrl.SetItemState(--c_ind, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED);
}

void CColumnSetupDlg::OnPropCol() 
{
	ColumnProp();
}

void CColumnSetupDlg::OnDblclkLevelTable(NMHDR* pNMHDR, LRESULT* pResult) 
{
	LevelProp();
}

void CColumnSetupDlg::LevelProp(int ind)
{
	if(ind<0)
		ind = m_level_ctrl.GetNextItem(-1, LVIS_SELECTED);
	if(ind<0)
		return;

	CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(ind);
	ASSERT(level);
	CLevelPropDlg dlg(m_ReportMgr);
	dlg.m_pLevels = m_levels;
	dlg.m_pLevel = level;
	if(dlg.DoModal()==IDOK)
	{
		m_level_ctrl.SetItemText(ind,0,dlg.m_pLevel->m_name);
		SelectString(&m_level_ctrl, ind);
	}
}

void CColumnSetupDlg::CopyColumn(int ind)
{
	int Ind = m_level_ctrl.GetNextItem(-1,LVIS_SELECTED);
	if(Ind<0) return;
	CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(Ind);
	CColumn* col_base = NULL;
	if(ind>-1)
		col_base = (CColumn*)m_column_ctrl.GetItemData(ind);
	ASSERT(level);
	CSimplDlg dlg;
	if(m_dlg_mode!=APL_DLG_MODE_CREATE_LR_GROUP && m_dlg_mode!=APL_DLG_MODE_CREATE_GROUP
		 && m_dlg_mode!=APL_DLG_MODE_CREATE_ONE_GROUP)
		dlg.m_show = APL_FULL_MODE;
	else
		dlg.m_show = APL_FULL_EX_MODE;
	dlg.m_title = APL_T("Поле");
	dlg.m_ReportMgr = m_ReportMgr;
	if(col_base)
	{
		dlg.m_align = col_base->m_align;
		dlg.m_SpacePara = col_base->m_SpacePara;
		dlg.m_show_flag = col_base->m_show_flag;
		dlg.m_width = col_base->m_width;
		dlg.m_bShowasDate = col_base->m_params&APL_COLUMN_SHOWASDATE;
		dlg.m_bShowAsTime = col_base->m_params&APL_COLUMN_SHOWASTIME;
		dlg.m_line_width = float(col_base->m_border)/10;
		dlg.m_fit_to_rect = col_base->m_fit_to_rect;
		dlg.m_ColumnType = col_base->m_ColumnType;
		dlg.m_iStrCount = col_base->m_RowsCount;
		if(col_base->m_ColumnType==aplSTRCONST)
			dlg.m_column_text = col_base->m_TextCnst;
		dlg.m_bNotShowZero = col_base->m_params&APL_COLUMN_NOT_SHOW_ZERO;
	}
	else
	{
		dlg.m_fit_to_rect = FALSE;
		dlg.m_show_flag = 0;
		dlg.m_width = 500;
	}
	if(m_dlg_mode==APL_DLG_MODE_CREATE_GROUP || m_dlg_mode==APL_DLG_MODE_CREATE_ONE_GROUP || m_dlg_mode ==APL_DLG_MODE_CREATE_LR_GROUP)
		dlg.m_IsGroup = TRUE;
	do
	{
		if(dlg.DoModal()!=IDOK) return;
		int tmp_ind = level->m_columns.Find(dlg.m_text);
		if(tmp_ind<0)
			break;
		AfxMessageBox(APL_T("Имя не уникально!"));
		dlg.m_width = dlg.m_width*10;
	}while(true);

	CString str;
	double d;
	CColumn* col = new CColumn(m_ReportMgr);
	col->m_params = 0;
	col->m_show_flag = dlg.m_show_flag;
	col->m_name = dlg.m_text;
	col->m_width = int(dlg.m_width*10);
	col->m_ds_column = dlg.m_ds_column;
	col->m_align = dlg.m_align;
	if(dlg.m_bShowasDate)
		col->m_params |=APL_COLUMN_SHOWASDATE;
	if(dlg.m_bShowAsTime)
		col->m_params |=APL_COLUMN_SHOWASTIME;
	if(dlg.m_bNotShowZero)
		col->m_params |=APL_COLUMN_NOT_SHOW_ZERO;
	if(dlg.m_bShowTopLine)
		col->m_params|=APL_COLUMN_SHOW_TOP_LINE;
	col->m_border = int(dlg.m_line_width*10);
	col->m_fit_to_rect = dlg.m_fit_to_rect;
	col->m_ColumnType = dlg.m_ColumnType;
	col->m_RowsCount = dlg.m_iStrCount; 
	col->m_SpacePara = dlg.m_SpacePara;
	if(dlg.m_ColumnType==aplSTRCONST)
		col->m_TextCnst = dlg.m_column_text;
	else
		col->m_TextCnst.Empty();
	level->m_columns.Add(col);
	
	ind = m_column_ctrl.GetItemCount();
	col->m_ind= ind+1;
	str.Format(_T("%d"),col->m_ind);
	ind = m_column_ctrl.InsertItem(ind,str);
	m_column_ctrl.SetItemText(ind,1,col->m_name);
	d = col->m_width; d=d/10;
	str.Format(_T("%.1f"),d);
	m_column_ctrl.SetItemText(ind,2,str);
	if(col->m_show_flag==APL_COLUMN_SHOW_LEVEL_NAME)
		m_column_ctrl.SetItemText(ind, 3, APL_T("Уровень"));
	else if(col->m_show_flag==APL_COLUMN_SHOW_ROW_NUM)
			m_column_ctrl.SetItemText(ind, 3, APL_T("Порядковый номер"));
	else if(col->m_ds_column)
		m_column_ctrl.SetItemText(ind,3,col->m_ds_column->GetName());
	m_column_ctrl.SetItemData(ind,(DWORD)col);
	SelectString(&m_column_ctrl,ind);
}


void CColumnSetupDlg::CopyLevel(int ind)
{
	if(ind<0) return;
	CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(ind);
	if(level==NULL) return;
	//Копирование уровня
	CLevelPropDlg dlg(m_ReportMgr);
	dlg.m_pLevels = m_levels;
	dlg.m_pLevelPrototipe = level;
	if(dlg.DoModal()==IDOK)
	{
		int ind_L = m_level_ctrl.InsertItem(m_level_ctrl.GetItemCount(),dlg.m_pLevel->m_name);
		m_level_ctrl.SetItemData(ind_L, (DWORD)dlg.m_pLevel);
		for(int i=0; i<level->m_columns.GetSize(); i++)
		{
			CColumn* col = new CColumn(m_ReportMgr);
			col->m_align = level->m_columns.GetAt(i)->m_align;
			col->m_params = level->m_columns.GetAt(i)->m_params;
			col->m_border = level->m_columns.GetAt(i)->m_border;
			col->m_ds_column = level->m_columns.GetAt(i)->m_ds_column;
			col->m_fit_to_rect = level->m_columns.GetAt(i)->m_fit_to_rect;
			col->m_show_flag = level->m_columns.GetAt(i)->m_show_flag;
			col->m_name = level->m_columns.GetAt(i)->m_name;
			col->m_width = level->m_columns.GetAt(i)->m_width;
			col->m_ind= level->m_columns.GetAt(i)->m_ind;
			dlg.m_pLevel->m_columns.Add(col);
		}
		SelectString(&m_level_ctrl, ind_L);
	}
}

bool CColumnSetupDlg::CopyLevelToMem(int ind)
{
	if(ind<0) return false;
	CSectionLevel* level = (CSectionLevel*)m_level_ctrl.GetItemData(ind);
	if(level==NULL) return false;

	UINT cf_hinst=RegisterClipboardFormat(APL_LEVEL_CLIPBOARD_DATA);
	if(cf_hinst==0)
	{
		AfxMessageBox(APL_T("Не удалось зарегистрировать формат буфера обмена (APL_LEVEL_CLIPBOARD_DATA)\nКопирование в буфер обмена не удалось!"), MB_ICONSTOP|MB_OK);
		return NULL;
	}
	int size = level->GetMemSize(true);
	int MemInd=0;
	COleDataSource*	pSource = new COleDataSource();
	if(pSource==NULL)
	{
		AfxMessageBox(APL_T("Копирование в буфер обмена не удалось!"), MB_ICONSTOP|MB_OK);
	}
	HGLOBAL hMem=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT, size);
	if (!hMem) return NULL;
	BYTE *phItem=(BYTE*)GlobalLock(hMem);
	level->CopyToMem(phItem, MemInd, true);
	pSource->CacheGlobalData(cf_hinst, hMem);
	pSource->SetClipboard();

	return true;
}

bool CColumnSetupDlg::PasteLevel()
{
	COleDataObject pDataObject;
	if(!pDataObject.AttachClipboard()) return false;
	UINT cf_hinst=RegisterClipboardFormat(APL_LEVEL_CLIPBOARD_DATA);
	if(pDataObject.IsDataAvailable(cf_hinst))
	{

		HGLOBAL hGlob=pDataObject.GetGlobalData(cf_hinst);
		if(hGlob==0)
		{
			AfxMessageBox(APL_T("Ошибка чтения информации из буфера обмена."));
			return false;
		}
		BYTE *phItem=(BYTE*)GlobalLock(hGlob);
		int MemInd = 0;
		if(phItem==0)
		{
			AfxMessageBox(APL_T("Ошибка чтения информации из буфера обмена."));
			return false;
		}
		
		//Проверяем уникальность имени уровня
		//Если уровень не уникален, то попросту не вставляем его
		CString level_name;
		int *pInt = NULL;
		int tmp_ind = MemInd+3*sizeof(int), name_length;
		int i;
		pInt = (int*)&phItem[tmp_ind];
		name_length = *pInt;
		tmp_ind+=sizeof(int);
		for(i=0; i<name_length; i++)
			level_name+=phItem[tmp_ind+i];
		//Непосредственно проверка уникальность
		for(i=0; i<m_levels->GetSize(); i++)
		{
			if(m_levels->GetAt(i)->m_name.CompareNoCase(level_name)==0)
			{
				AfxMessageBox(APL_T("Уровень с таким наименованием уже присутствует. Копирование невозможно!"), MB_OK|MB_ICONSTOP);
				return false;
			}
		}
		CSectionLevel* level = new CSectionLevel(m_ReportMgr);
		if(level->LoadDataFromMem(phItem, MemInd))
		{
			m_levels->Add(level);
			int ind = m_level_ctrl.InsertItem(m_level_ctrl.GetItemCount(),level->m_name);
			m_level_ctrl.SetItemData(ind,(DWORD)level);
			SelectString(&m_level_ctrl,ind);
			pDataObject.Release();

			return true;
		}
		else
			delete level;
	}

	return false;
}
