// SelectClassifierItemDlg.cpp : implementation file
//

#include "stdafx.h"
#include "SelectClassifierItemDlg.h"
#include "ClassifierTreeFrame.h"
#include "ClassifierTableFrame.h"
#include "ClassifierTreeView.h"
#include "ClassifierTableItemsView.h"

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

//#define HIDECTRL(id) {CWnd *wnd=GetDlgItem(id); if(0!=wnd) wnd->ShowWindow(SW_HIDE);}
#define SHOWHIDECTRL(id,val) {CWnd *wnd=GetDlgItem(id); if(0!=wnd) wnd->EnableWindow(val);}

#define InsertSelectAttr(name_attr,attr_insert) \
	pos=m_combo_find_attr.AddString(name_attr);\
	m_combo_find_attr.SetItemData(pos,(DWORD_PTR)attr_insert);\
	if(m_combo_find_attr.GetCount()==1){m_combo_find_attr.SetCurSel(pos);}

#define InsertSelectEntt(name_entt,entt) \
if(0==pSysEntity || pSysEntity==entt)\
{pos=m_combo_find_object.AddString(name_entt); m_combo_find_object.SetItemData(pos,(long)entt);\
	if(e_prev_find_entt == entt){m_combo_find_object.SetCurSel(pos);}\
}


/////////////////////////////////////////////////////////////////////////////
// CSelectClassifierItemDlg dialog


CSelectClassifierItemDlg::CSelectClassifierItemDlg(CaplAPI* api, UINT mode, CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CSelectClassifierItemDlg::IDD, pParent)
{
	ASSERT(api);
	m_api = api;
	m_SelectedItem = NULL;
	m_Mode = mode;
	m_sTitle =  APL_T("Выбор объекта");
	m_pFrame = NULL;
	m_pTableView=NULL;
	m_SelectedSystem = NULL;
	m_ToolTipCtrl = NULL;
	m_extItems4Add=0;
	m_filter = NULL;
	m_first_filter_feel = true;
	//{{AFX_DATA_INIT(CSelectClassifierItemDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
}
CSelectClassifierItemDlg::~CSelectClassifierItemDlg()
{
	if(m_ToolTipCtrl!=0) delete m_ToolTipCtrl;
	m_ToolTipCtrl = 0;
}

void CSelectClassifierItemDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSelectClassifierItemDlg)
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDOK, m_ok_btn);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_FIND_STR, m_find_str_ctrl);
	DDX_Control(pDX, IDC_COMBO_OBJECT_ATTR, m_combo_find_attr);
	DDX_Control(pDX, IDC_COMBO_OBJECT_TYPE, m_combo_find_object);
	DDX_Control(pDX, IDC_COMBO_RELATION, m_combo_find_relation);
	DDX_Control(pDX, ID_FIND, m_FindBtn);
	DDX_Control(pDX, ID_ADD, m_add_btn);
	DDX_Control(pDX, IDC_STATIC_SELECTED_COUNT, m_st_selected_count);
}


BEGIN_MESSAGE_MAP(CSelectClassifierItemDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CSelectClassifierItemDlg)
	ON_WM_CREATE()
	//}}AFX_MSG_MAP
	ON_CBN_SELCHANGE(IDC_COMBO_OBJECT_TYPE, &CSelectClassifierItemDlg::OnCbnSelchangeComboObjectType)
	ON_BN_CLICKED(ID_FIND, &CSelectClassifierItemDlg::OnBnClickedFind)
	ON_BN_CLICKED(ID_ADD, &CSelectClassifierItemDlg::OnBnClickedAdd)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSelectClassifierItemDlg message handlers

int CSelectClassifierItemDlg::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if(CaplResizableDialog::OnCreate(lpCreateStruct) == -1)
		return -1;

	// Создаём фрейм, указывая в качестве родительского окна наш диалог (this)
	CRect rect;
	GetClientRect(&rect);

    m_pFrame = new CBaseFrame(m_Mode);
    m_pFrame->Create(NULL, NULL, WS_VISIBLE|WS_CHILD,rect, this);

	CClassifierTreeView *pTreeView=(CClassifierTreeView*)((CFrameWnd*)(m_pFrame->m_wndVSplitter.GetPane(0, 0)))->GetActiveView();
	if(pTreeView) pTreeView->m_api = m_api;

	if(m_pFrame->m_wndHSplitter.GetColumnCount()>1)
	{
		m_pTableView = ((CClassifierTableItemsView*)((CFrameWnd*)(m_pFrame->m_wndHSplitter.GetPane(0, 1)))->GetActiveView());
		if(m_pTableView)
		{
			m_pTableView->m_api = m_api;
			m_pTableView->m_Mode = m_Mode;
			m_pTableView->m_filter = m_filter;
		}
	}

	if(pTreeView)
	{
		pTreeView->m_BaseSystems.Append(m_BaseClassifierSystems);
		pTreeView->m_pTableView = m_pTableView;
		pTreeView->m_pClassifDlg = this;
		if(m_pFrame->m_wndVSplitter.GetRowCount()>1)
		{
			pTreeView->m_pPictureView = (CPictureView*)m_pFrame->m_wndVSplitter.GetPane(1, 0);
		}

		((CClassifierTreeFrame*)(m_pFrame->m_wndVSplitter.GetPane(0, 0)))->SetMode(m_Mode);
	}

	if(m_pFrame->m_wndHSplitter.GetColumnCount()>1)
	{
		((CClassifierTableFrame*)(m_pFrame->m_wndHSplitter.GetPane(0, 1)))->SetMode(m_Mode);
		if(m_pTableView) m_pTableView->SendMessage(WM_INITIALUPDATE);
	}
	
	if(pTreeView) pTreeView->SendMessage(WM_INITIALUPDATE);

	return 0;
}

BOOL CSelectClassifierItemDlg::OnInitDialog() 
{
	CaplResizableDialog::OnInitDialog();
	if(m_api==NULL)
	{
		EndDialog(0);
		return FALSE;
	}

	// предотвращаем потерю модальности после диалога с бочками из aplSocketTransport
	CORRECT_LOOSE_MODAL_ON_CLASS(&(m_api->m_data));

	//EnableToolTips(TRUE);
	if(m_ToolTipCtrl == 0) m_ToolTipCtrl = new CToolTipCtrl();

	if (m_ToolTipCtrl != 0) 
	{
		m_ToolTipCtrl->Create(this, TTS_ALWAYSTIP);
		m_ToolTipCtrl->AddTool(&m_cancel_btn,APL_T("Отмена"));
		m_ToolTipCtrl->AddTool(&m_FindBtn,APL_T("Найти объекты"));
		m_ToolTipCtrl->SendMessage(TTM_SETMAXTIPWIDTH, 0, SHRT_MAX);
		m_ToolTipCtrl->SendMessage(TTM_SETDELAYTIME, TTDT_AUTOPOP, SHRT_MAX);
		m_ToolTipCtrl->SendMessage(TTM_SETDELAYTIME, TTDT_INITIAL, 200);
		m_ToolTipCtrl->SendMessage(TTM_SETDELAYTIME, TTDT_RESHOW, 200);
		m_ToolTipCtrl->Activate(TRUE);
	} 

	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	m_ok_btn.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_ok_btn.SetFlat(FALSE);

	m_add_btn.SetIcon(GetAplStdIco16(APLSTDICO_PLUS));
	m_add_btn.SetFlat(FALSE);

	if(0!=m_extItems4Add)
	{
		m_add_btn.ShowWindow(SW_SHOW);
		m_st_selected_count.ShowWindow(SW_SHOW);
		m_st_selected_count.SetWindowText(_T(""));
	}

	m_FindBtn.SetIcon(GetAplTableIco(APL_TABLE_FIND));
	m_FindBtn.SetFlat(FALSE);

	SetWindowText(m_sTitle);
	CClassifierTreeView *tv=((CClassifierTreeView*)((CFrameWnd*)(m_pFrame->m_wndVSplitter.GetPane(0, 0)))->GetActiveView());
	if(tv)
	{
		tv->st_sTitle=m_sTitle;
		tv->RestoreSelectedClassifierItem();
	}


	bool bSelectMode=false;
	if(m_Mode&(APL_SELECT_CLASSIFIER_ITEM|APL_SELECT_CLASSIFIER_LEVEL|APL_SELECT_CLASSIFIER_SYSTEM)) bSelectMode=true;


	CRect rect;
	if(m_Mode==APL_CLASSIFIER_EXE_EDITOR)
	{
		GetClientRect(rect);
		m_cancel_btn.ShowWindow(SW_HIDE);
		m_ok_btn.ShowWindow(SW_HIDE);
	}
	else if(m_Mode&APL_CLASSIFIER_EDITOR || bSelectMode )
	{
		GetDlgItem(IDC_STATIC_FRAME)->GetWindowRect(&rect);
		ScreenToClient(&rect);
		if(m_Mode&APL_CLASSIFIER_EDITOR && !bSelectMode)
		{
			m_cancel_btn.SetWindowText( APL_T("Закрыть"));
			m_ok_btn.ShowWindow(SW_HIDE);
		}
	}
	GetDlgItem(IDC_STATIC_FRAME)->ShowWindow(SW_HIDE);
	m_pFrame->MoveWindow(rect);


	AddAnchor(m_pFrame->m_hWnd, TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDOK, BOTTOM_RIGHT);
	AddAnchor(IDCANCEL, BOTTOM_RIGHT);

	// положение кнопок поиска
	AddAnchor(IDC_STATIC_FIND, BOTTOM_LEFT);
	AddAnchor(IDC_COMBO_OBJECT_TYPE, BOTTOM_LEFT);
	AddAnchor(IDC_STATIC_ATTR, BOTTOM_LEFT);
	AddAnchor(IDC_COMBO_OBJECT_ATTR, BOTTOM_LEFT);
	AddAnchor(IDC_COMBO_RELATION, BOTTOM_LEFT);
	AddAnchor(IDC_FIND_STR, BOTTOM_LEFT, BOTTOM_RIGHT);
	AddAnchor(ID_FIND, BOTTOM_RIGHT);
	AddAnchor(ID_ADD, BOTTOM_RIGHT);
	AddAnchor(IDC_STATIC_SELECTED_COUNT, BOTTOM_RIGHT);

	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0

	if(0==m_SelectedSystem)
	{
		if(m_BaseClassifierSystems.Size==1)
		{
			CheckFillFindButtons(m_BaseClassifierSystems[0]);
		}
		else
		{
			CheckFillFindButtons(NULL);
		}
	}

	RECT w_rect;
	UINT size = sizeof(RECT)+1;
	BYTE *pBytes = NULL;
	if(0!=app) app->GetProfileBinary(_T("Settings"), _T("WindowPosition"), &pBytes, &size);
	if(pBytes)
	{
		memcpy(&w_rect, pBytes, sizeof(RECT));
		if(pBytes[sizeof(RECT)]==1)
		{
			ShowWindow(SW_MAXIMIZE);
		}
		else
		{
			MoveWindow(&w_rect,TRUE);
		}
		delete pBytes;
	}

	if(m_pFrame->m_wndVSplitter.GetRowCount()>1)
	{
		int vpos = 200;
		if(0!=app) vpos=app->GetProfileInt(_T("Settings"), _T("VSplitterPos"), 200);
		if(vpos>30) m_pFrame->m_wndVSplitter.SetRowInfo(0, vpos, 0);
		m_pFrame->m_wndVSplitter.RecalcLayout();
	}

	if(m_pFrame->m_wndHSplitter.GetColumnCount()>0)
	{
		int hpos = 300;
		if(0!=app) hpos=app->GetProfileInt(_T("Settings"), _T("HSplitterPos"), 300);
		if(hpos>30)m_pFrame->m_wndHSplitter.SetColumnInfo(0, hpos, 0);
		m_pFrame->m_wndHSplitter.RecalcLayout();
	}

	//Скрываем кнопки фильтра
	if(0==m_pTableView)
	{
		CWnd *w;
		w=GetDlgItem(IDC_STATIC_FIND); if(0!=w) w->ShowWindow(SW_HIDE);
		w=GetDlgItem(IDC_COMBO_OBJECT_TYPE); if(0!=w) w->ShowWindow(SW_HIDE);
		w=GetDlgItem(IDC_STATIC_ATTR); if(0!=w) w->ShowWindow(SW_HIDE);
		w=GetDlgItem(IDC_COMBO_OBJECT_ATTR); if(0!=w) w->ShowWindow(SW_HIDE);
		w=GetDlgItem(IDC_COMBO_RELATION); if(0!=w) w->ShowWindow(SW_HIDE);
		w=GetDlgItem(IDC_FIND_STR); if(0!=w) w->ShowWindow(SW_HIDE);
		w=GetDlgItem(ID_FIND); if(0!=w) w->ShowWindow(SW_HIDE);
	}

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CSelectClassifierItemDlg::CheckFillFindButtons(CaplInstance *item)
{
	BOOL bOkEnabled=FALSE;
	//Определяем наличие кнопок поиска
	bool bUseFind=false;
	CaplEntity *pSysEntity = NULL;
	if(item != 0) // item - этто в дереве или в спраочнике
	{
		if(m_api->m_data.IsKindOf(item,m_api->m_classifier_mgr.e_apl_classifier_level))
		{
			if(m_Mode&APL_SELECT_CLASSIFIER_LEVEL) bOkEnabled=TRUE;
			m_api->m_data.GetAttr(item,m_api->m_classifier_mgr.a_apl_classifier_level_system,m_SelectedSystem);
		}
		else if(m_api->m_data.IsKindOf(item,m_api->m_classifier_mgr.e_apl_classifier_system))
		{
			if(m_Mode&APL_SELECT_CLASSIFIER_SYSTEM) bOkEnabled=TRUE;
			m_SelectedSystem = item;
		}

	}
	if(m_SelectedSystem != 0)
	{
		bool bCanStoreObject;
		m_api->m_data.GetAttr(m_SelectedSystem,m_api->m_classifier_mgr.a_apl_classifier_system_can_store_object,bCanStoreObject);
		if(bCanStoreObject)
		{
			bool bHasTypeCtlr = false;
			m_api->m_data.GetAttr(m_SelectedSystem, m_api->m_classifier_mgr.a_apl_classifier_system_is_type_control, bHasTypeCtlr);
			if(bHasTypeCtlr)
			{
				CString sEntity;
				m_api->m_data.GetAttr(m_SelectedSystem, m_api->m_classifier_mgr.a_apl_classifier_system_stored_entity, sEntity);
				if(!sEntity.IsEmpty())
				{
					pSysEntity = m_api->m_data.GetEntityBN(sEntity);
				}
			}
			bUseFind=true;
		}
	}

	if(m_Mode&(APL_SELECT_CLASSIFIER_LEVEL|APL_SELECT_CLASSIFIER_SYSTEM)) m_ok_btn.EnableWindow(bOkEnabled); 
	

	if(bUseFind)
	{
		int pos;
		CaplEntity *e_prev_find_entt = 0;

		SHOWHIDECTRL(IDC_STATIC_FIND,true);
		SHOWHIDECTRL(IDC_COMBO_OBJECT_TYPE,true);
		SHOWHIDECTRL(IDC_STATIC_ATTR,true);
		SHOWHIDECTRL(IDC_COMBO_OBJECT_ATTR,true);
		SHOWHIDECTRL(IDC_COMBO_RELATION,true);
		SHOWHIDECTRL(IDC_FIND_STR,true);

	
		pos = m_combo_find_object.GetCurSel();
		if(pos != -1) e_prev_find_entt = (CaplEntity *)m_combo_find_object.GetItemData(pos);

		for (int i = m_combo_find_object.GetCount() - 1; i >= 0; i--)
		{
			m_combo_find_object.DeleteString(i);
		}

		if(NULL != m_filter)
		{
			if(m_filter->search_entity_name == _T(""))m_filter->search_entity_name = m_filter->search_entity->name;
			InsertSelectEntt(m_filter->search_entity_name,m_filter->search_entity);
		}
		else
		{
			InsertSelectEntt(APL_T("Версию изделия"),m_api->m_prd_mgr.e_apl_pdf);
			InsertSelectEntt(APL_T("Документ"),m_api->m_doc_mgr.e_doc);
			InsertSelectEntt(APL_T("Организацию (рабочую группу)"),m_api->m_appr_mgr.e_org);
// 	 		if(0==pSysEntity || pSysEntity==m_api->m_prd_mgr.e_apl_pdf)
// 	 		{i=m_combo_find_object.AddString(APL_T("Версию изделия")); m_combo_find_object.SetItemData(i,(long)m_api->m_prd_mgr.e_apl_pdf);}
		}

		if(m_combo_find_object.GetCount()==1 || NULL != m_filter)
		{
			m_combo_find_object.SetCurSel(0);
			OnCbnSelchangeComboObjectType();
		}
	}
	else
	{
		SHOWHIDECTRL(IDC_STATIC_FIND,false);
		SHOWHIDECTRL(IDC_COMBO_OBJECT_TYPE,false);
		SHOWHIDECTRL(IDC_STATIC_ATTR,false);
		SHOWHIDECTRL(IDC_COMBO_OBJECT_ATTR,false);
		SHOWHIDECTRL(IDC_COMBO_RELATION,true);
		SHOWHIDECTRL(IDC_FIND_STR,false);
		SHOWHIDECTRL(ID_FIND,false);
	}
}

void CSelectClassifierItemDlg::OnOK() 
{
	if(m_Mode&(APL_SELECT_CLASSIFIER_LEVEL|APL_SELECT_CLASSIFIER_SYSTEM))
	{
		CClassifierTreeView *tv=((CClassifierTreeView*)((CFrameWnd*)(m_pFrame->m_wndVSplitter.GetPane(0, 0)))->GetActiveView());
		if(tv)
		{
			CaplInstance *selinst=tv->GetSelectedInstance();
			if(0!=selinst)
			{
				if(m_Mode&APL_SELECT_CLASSIFIER_SYSTEM && m_api->m_data.IsKindOf(selinst, m_api->m_classifier_mgr.e_apl_classifier_system)) m_SelectedItem=selinst;
				if(m_Mode&APL_SELECT_CLASSIFIER_LEVEL && m_api->m_data.IsKindOf(selinst, m_api->m_classifier_mgr.e_apl_classifier_level)) m_SelectedItem=selinst;
			}
		}
	}
	else if(m_pTableView!=NULL)
	{
		int cur = m_pTableView->m_ListCtrl.GetNextItem(-1, LVIS_SELECTED);
		if(cur<0 && m_Mode&APL_SELECT_CLASSIFIER_ITEM)
			return;
		else if(cur>-1)
		{
			int ind = (int)m_pTableView->m_ListCtrl.GetItemData(cur);
			if(ind<0) return;
			SItemColumnData* pItem = m_pTableView->m_Items.GetAt(ind);
			if(pItem)
			{
				m_SelectedItem =pItem->m_inst;
				m_pTableView->CopyToClipboard();
			}
			else
				return;
		}
	}
	
	CaplResizableDialog::OnOK();
}

void CSelectClassifierItemDlg::InsertRelation(CaplQLQuery::aplQLLogRelation relation, CaplQLQuery::aplQLLogRelation default_relation)
{
	int pos = m_combo_find_relation.AddString(CaplQLQuery::LogOp2String(relation));
	m_combo_find_relation.SetItemData(pos,(DWORD)relation);
	if(relation == default_relation || pos == 0)
	{
		m_combo_find_relation.SetCurSel(pos);
	}
}

void CSelectClassifierItemDlg::OnCbnSelchangeComboObjectType()
{
	// TODO: Add your control notification handler code here
	int i,pos,prev_select_attr=0;

	SHOWHIDECTRL(ID_FIND,false);

	i=m_combo_find_object.GetCurSel();
	if(i<0) return;
	void *type=	m_combo_find_object.GetItemDataPtr(i);
	if(0==type) return;

	if(!m_first_filter_feel)prev_select_attr = m_combo_find_attr.GetCurSel();
	m_combo_find_attr.ResetContent();

	CaplQLQuery::aplQLLogRelation	default_relation = CaplQLQuery::aplLIKE;

	CaplEntity* filter_type = 0;
	if(0 != m_filter)filter_type = m_filter->search_entity;

	if(type == filter_type)
	{
		CaplAttr* attr;
		CString name_attr;
		for(i=0;i<m_filter->selection_array.GetSize();i++)
		{
			attr = m_filter->selection_array.GetAt(i);
			if(0 == attr ) continue;
			if(attr->type != aplSTRING) continue;

			if(m_filter->selection_array_names.GetSize() > i) name_attr = m_filter->selection_array_names[i];
			else name_attr = attr->name;

			pos=m_combo_find_attr.AddString(name_attr);
			m_combo_find_attr.SetItemData(pos,(DWORD_PTR)attr);

			if(m_first_filter_feel && m_filter->default_selection == attr)
			{
				m_combo_find_attr.SetCurSel(pos);
			}
		}
		if(m_first_filter_feel)
		{
			if(_T("") != m_filter->default_value) m_find_str_ctrl.SetWindowText(m_filter->default_value);
			default_relation = m_filter->default_relation;
		}
		else
		{
			m_combo_find_attr.SetCurSel(prev_select_attr);
		}
	}
	else if(type==m_api->m_prd_mgr.e_apl_pdf)
	{
		InsertSelectAttr(APL_T("Обозначение изделия"),m_api->m_prd_mgr.a_prd_id);
		InsertSelectAttr(APL_T("Наименование изделия"),m_api->m_prd_mgr.a_prd_name);
		InsertSelectAttr(APL_T("Код изделия"),m_api->m_prd_mgr.a_prd_code);
		InsertSelectAttr(APL_T("Обозначение версии"),m_api->m_prd_mgr.a_pdf_id);
		InsertSelectAttr(APL_T("Код версии"),m_api->m_prd_mgr.a_pdf_code);
		InsertSelectAttr(APL_T("Код 1 версии"),m_api->m_prd_mgr.a_pdf_code1);
		InsertSelectAttr(APL_T("Код 2 версии"),m_api->m_prd_mgr.a_pdf_code2);

// 		i=m_combo_find_attr.AddString(APL_T("Обозначение изделия"));
// 			m_combo_find_attr.SetItemData(i,(DWORD_PTR)m_api->m_prd_mgr.a_prd_id);
// 			if(a_prev_find_attr == m_api->m_prd_mgr.a_prd_id)m_combo_find_attr.SetCurSel(i);
// 		i=m_combo_find_attr.AddString(APL_T("Наименование изделия"));
// 			m_combo_find_attr.SetItemData(i,(DWORD_PTR)m_api->m_prd_mgr.a_prd_name);
// 		i=m_combo_find_attr.AddString(APL_T("Обозначение версии"));
// 			m_combo_find_attr.SetItemData(i,(DWORD_PTR)m_api->m_prd_mgr.a_pdf_id);
	}
	else if(type==m_api->m_doc_mgr.e_doc)
	{
		InsertSelectAttr(APL_T("Обозначение"),m_api->m_doc_mgr.a_doc_id);
		InsertSelectAttr(APL_T("Наименование"),m_api->m_doc_mgr.a_doc_name);

// 		i=m_combo_find_attr.AddString(APL_T("Обозначение"));
// 			m_combo_find_attr.SetItemData(i,(DWORD_PTR)m_api->m_doc_mgr.a_doc_id);
// 		i=m_combo_find_attr.AddString(APL_T("Наименование"));
// 			m_combo_find_attr.SetItemData(i,(DWORD_PTR)m_api->m_doc_mgr.a_doc_name);
	}
	else if(type==m_api->m_appr_mgr.e_org)
	{
		InsertSelectAttr(APL_T("Обозначение"),m_api->m_appr_mgr.a_org_id);
		InsertSelectAttr(APL_T("Наименование"),m_api->m_appr_mgr.a_org_name);
		InsertSelectAttr(APL_T("ИНН"),m_api->m_appr_mgr.a_org_inn);

// 		i=m_combo_find_attr.AddString(APL_T("Обозначение"));
// 			m_combo_find_attr.SetItemData(i,(DWORD_PTR)m_api->m_appr_mgr.a_org_id);
// 		i=m_combo_find_attr.AddString(APL_T("Наименование"));
// 			m_combo_find_attr.SetItemData(i,(DWORD_PTR)m_api->m_appr_mgr.a_org_name);
	}


	// заполняем комбобокс отношений. Пока заполняем вручную для всех один набор - для строковых атрибутов,
	// на будущее для каждого типа может появиться свой набор
	if(m_first_filter_feel)
	{
		for (int i = m_combo_find_relation.GetCount() - 1; i >= 0; i--)
		{
			m_combo_find_relation.DeleteString(i);
		}
		InsertRelation(CaplQLQuery::aplEQUAL,default_relation);
		InsertRelation(CaplQLQuery::aplLIKE,default_relation);
		InsertRelation(CaplQLQuery::aplLIKELEFT,default_relation);
		InsertRelation(CaplQLQuery::aplLIKERIGHT,default_relation);
		InsertRelation(CaplQLQuery::aplNOTEQUAL,default_relation);
		InsertRelation(CaplQLQuery::aplNOTLIKE,default_relation);
		InsertRelation(CaplQLQuery::aplNOTLIKELEFT,default_relation);
		InsertRelation(CaplQLQuery::aplNOTLIKERIGHT,default_relation);
	}

	m_first_filter_feel = false;

	SHOWHIDECTRL(ID_FIND,true);

}

void CSelectClassifierItemDlg::OnBnClickedFind()
{
	int i=m_combo_find_object.GetCurSel();
	if(i<0){AfxMessageBox(APL_T("Не выбран тип объекта!")); m_combo_find_object.SetFocus(); return;}
	CaplEntity *type= (CaplEntity*)m_combo_find_object.GetItemDataPtr(i);
	if(0==type){AfxMessageBox(APL_T("Не выбран тип объекта")); m_combo_find_object.SetFocus();return;}

	CString query,subquery,text,buf;
	m_find_str_ctrl.GetWindowText(text);
	if(text==APL_T(""))
	{
		if(IDYES!=AfxMessageBox(APL_T("Не задана строка для поиска.\n\n Показать все содержимое справочника?"),MB_ICONWARNING|MB_YESNO))
		{ m_find_str_ctrl.SetFocus();return;}
		if(IDYES!=AfxMessageBox(APL_T("Операция может занять длительное время!\n\n Вы действительно хотите продолжить?"),MB_ICONWARNING|MB_YESNO))return;
	}
	else
	{
		i=m_combo_find_attr.GetCurSel();
		if(i<0){AfxMessageBox(APL_T("Не выбран атрибут!")); m_combo_find_attr.SetFocus(); return;}
		CaplAttr *attr =(CaplAttr*)m_combo_find_attr.GetItemDataPtr(i);
		if(0==attr){AfxMessageBox(APL_T("Не выбран атрибут")); m_combo_find_attr.SetFocus();return;}

		bool bUnknownAttr=false;
		CaplEntity* filter_type = 0;
		if(0 != m_filter)filter_type = m_filter->search_entity;

		if(type == filter_type)
		{
			subquery=filter_type->name + _T(".");
			subquery+=attr->name;
		}
		else if(type==m_api->m_prd_mgr.e_apl_pdf)
		{
			subquery=_T("apl_product_definition_formation.");
			if(attr==m_api->m_prd_mgr.a_prd_id)subquery+=_T("of_product->product.id");
			else if(attr==m_api->m_prd_mgr.a_prd_name)subquery+=_T("of_product->product.name");
			else if(attr==m_api->m_prd_mgr.a_prd_code)subquery+=_T("of_product->product.code");
			else if(attr==m_api->m_prd_mgr.a_pdf_id)subquery+=_T("id");
			else if(attr==m_api->m_prd_mgr.a_pdf_code)subquery+=_T("code");
			else if(attr==m_api->m_prd_mgr.a_pdf_code1)subquery+=_T("code1");
			else if(attr==m_api->m_prd_mgr.a_pdf_code2)subquery+=_T("code2");
			else bUnknownAttr=true;
		}
		else if(type==m_api->m_doc_mgr.e_doc)
		{
			subquery=_T("apl_document.");
			if(attr==m_api->m_doc_mgr.a_doc_id)subquery+=_T("id");
			else if(attr==m_api->m_doc_mgr.a_doc_name)subquery+=_T("name");
			else bUnknownAttr=true;

		}
		else if(type==m_api->m_appr_mgr.e_org)
		{
			subquery=_T("organization.");
			if(attr==m_api->m_appr_mgr.a_org_id)subquery+=_T("id");
			else if(attr==m_api->m_appr_mgr.a_org_name)subquery+=_T("name");
			else if(attr==m_api->m_appr_mgr.a_org_inn)subquery+=_T("inn");
			else bUnknownAttr=true;
		}
		else bUnknownAttr=true;
		
		if(bUnknownAttr)
		{AfxMessageBox(APL_T("Неизвестный атрибут")); return;}
	}

	i=m_combo_find_relation.GetCurSel();
	if(i<0){AfxMessageBox(APL_T("Не выбрано отношение!")); m_combo_find_relation.SetFocus(); return;}
	
	CaplQLQuery::aplQLLogRelation relation = (CaplQLQuery::aplQLLogRelation)m_combo_find_relation.GetItemData(i);

	if(m_SelectedSystem != 0)
	{
		// Ищем в справочнике
		/*SELECT
			Ext
			FROM
			Ext {apl_classifier_association(.system=#19276 
			AND.item->apl_product_definition_formation.of_product->product.id LIKE '') }
		END_SELECT*/

		if(text!=_T(""))
		{
			int pos1 =0 ,pos2;
			query.Format(_T("SELECT Ext.item  FROM Ext{apl_classifier_association(.system=#%i "),m_SelectedSystem->GetId());
			do{
				pos2 = text.Find(_T("&"),pos1);
				if(pos2 == -1)
				{
					buf = text.Mid(pos1);
				}
				else
				{
					buf = text.Mid(pos1,pos2-pos1);
				}
				query += _T(" AND .item->") + subquery + CaplQLQuery::LogOp2String(relation,false) + _T(" '") + buf + _T("' ");
				pos1 = pos2 + 1;
			}while(pos2 != -1);
			query += _T(") } END_SELECT");
		}
		else
		{
			query.Format(_T("SELECT Ext.item  FROM Ext{apl_classifier_association.system=#%i} END_SELECT"),m_SelectedSystem->GetId());
		}
	}
	else
	{
		// Ищем везде
		if(subquery==_T("")) 
		{
			if(type==m_api->m_prd_mgr.e_apl_pdf)subquery=_T("apl_product_definition_formation.id");
			else if(type==m_api->m_doc_mgr.e_doc) subquery=_T("apl_document.id");
			else if(type==m_api->m_appr_mgr.e_org) subquery=_T("organization.id");
		}
			
		query.Format(_T("SELECT Ext_  FROM Ext_{ %s  LIKE '%s' } END_SELECT"),LPCTSTR(subquery),LPCTSTR(text));
	}
	aplExtent ext;
	if(!m_api->m_data.NET_QueryEditParse(query))
		{AfxMessageBox(APL_T("Ошибка разбора запроса")); return;}

	if(!m_api->m_data.NET_QueryExecute(ext,  APL_T("Поиск...")))
		{AfxMessageBox(APL_T("Ошибка при поиске")); return;}

	if(ext.GetSize()<1) {AfxMessageBox(APL_T("Ничего не найдено")); return;}

	if(ext.GetSize() > 100)
	{
		buf.Format(APL_T("Найдено %i. Показать?"),ext.GetSize());
		if(IDYES!=AfxMessageBox(buf,MB_YESNO|MB_ICONQUESTION)) return;
	}


	if(m_pTableView!=NULL)
	{
		m_api->LoadExtentInfo(ext);
		m_pTableView->m_ext_fom_find=ext;
		m_pTableView->UpdateTable((CaplInstance *)-1);

		// не понял, зачем сбрасывать выделение в дереве. Ведь ищется среди объектов конкретного справочника.
// 		CClassifierTreeView *tv=((CClassifierTreeView*)((CFrameWnd*)(m_pFrame->m_wndVSplitter.GetPane(0, 0)))->GetActiveView());
// 		if(0!=tv)
// 		{
// 			tv->GetTreeCtrl().SelectItem(0);
// 			tv->GetTreeCtrl().SelectDropTarget(0);
// 		}
	}
}


BOOL CSelectClassifierItemDlg::PreTranslateMessage(MSG* pMsg) 
{
	if (m_ToolTipCtrl != 0)
	{
		switch(pMsg->message) {
		case WM_LBUTTONDOWN:    
		case WM_MOUSEMOVE:
		case WM_LBUTTONUP:    
		case WM_RBUTTONDOWN:
		case WM_MBUTTONDOWN:    
		case WM_RBUTTONUP:
		case WM_MBUTTONUP:
			m_ToolTipCtrl->RelayEvent(pMsg);
			break;
		}
	}

	return CaplResizableDialog::PreTranslateMessage(pMsg);
}
void CSelectClassifierItemDlg::OnBnClickedAdd()
{
	if(0==m_extItems4Add) return;
	if(m_pTableView==NULL)return;

	int cur = m_pTableView->m_ListCtrl.GetNextItem(-1, LVIS_SELECTED);
	if(cur<0 && m_Mode&APL_SELECT_CLASSIFIER_ITEM)	return;
	int ind = (int)m_pTableView->m_ListCtrl.GetItemData(cur);
	if(ind<0) return;
	SItemColumnData* pItem = m_pTableView->m_Items.GetAt(ind);
	if(0==pItem) return;
	m_extItems4Add->Add(pItem->m_inst);

	CString buf;
	buf.Format(APL_T("Элементов в буфере: %i"),m_extItems4Add->GetSize());
	m_st_selected_count.SetWindowText(buf);
}

BOOL CSelectClassifierItemDlg::DestroyWindow()
{
	// TODO: Add your specialized code here and/or call the base class

	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0

	int tmp;
	int vpos;
	int hpos;

	int size = sizeof(RECT);
	BYTE zoomed = IsZoomed()?1:0;
	BYTE *pBytes = new BYTE[size+1];
	if(IsZoomed())
		ShowWindow(SW_NORMAL);
	RECT w_rect;
	GetWindowRect(&w_rect);
	memcpy(pBytes, &w_rect, size);
	pBytes[size] = zoomed;
	if(0!=app) app->WriteProfileBinary(_T("Settings"), _T("WindowPosition"), pBytes, sizeof(RECT)+1);

	delete pBytes;


	if(m_pFrame->m_wndHSplitter.GetColumnCount()>1)
	{
		m_pFrame->m_wndHSplitter.GetColumnInfo(0, hpos, tmp);
		if(hpos>30 && 0!=app)	app->WriteProfileInt(_T("Settings"), _T("HSplitterPos"), hpos);
	}

	if(m_pFrame->m_wndVSplitter.GetRowCount()>1)
	{
		m_pFrame->m_wndVSplitter.GetRowInfo(0, vpos, tmp);
		if(vpos>30 && 0!=app)	app->WriteProfileInt(_T("Settings"), _T("VSplitterPos"), vpos);
	}

	return CaplResizableDialog::DestroyWindow();
}


void CSelectClassifierItemDlg::OnCancel()
{
	if(0!=m_extItems4Add)
	{
		if(m_extItems4Add->GetSize()>0)
		{
			CString buf;
			buf.Format(_T("Элементов в буфере %i ! Отменить выбор ?"),m_extItems4Add->GetSize());
			if(IDYES!=AfxMessageBox(buf,MB_ICONWARNING|MB_YESNO|MB_DEFBUTTON2)) return;
		}
	}
	CaplResizableDialog::OnCancel();
}
