// SelectInstDlg.cpp : implementation file
//

#include "stdafx.h"
#include "resource.h"
#include "SelectInstDlg.h"
#include <aplNetStepData.h>
#include "apl_api.h"
#include "icons_defines.h"

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

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
aplObjVertonInfo CSelectInstDlg::m_ItemVertionInfo= {aplNo, -1, NULL, NULL, NULL};
void CSelectInstDlg::SetObjVertionInfo(aplObjVersionType type, int ico, 
					CaplAttr* id, CaplAttr* base, CaplAttr* obj, CaplAttr* active)
{
	m_ItemVertionInfo._type= type;
	m_ItemVertionInfo._ico= ico;
	m_ItemVertionInfo._VerIdAttr= id;
	m_ItemVertionInfo._VerBaseAttr= base;
	m_ItemVertionInfo._VerObjAttr= obj;
	m_ItemVertionInfo._ObjActiveVerAttr= active;
}
void CSelectInstDlg::ClearObjVertionInfo()
{
	m_ItemVertionInfo._type= aplNo;
	m_ItemVertionInfo._ico= -1;
	m_ItemVertionInfo._VerIdAttr= NULL;
	m_ItemVertionInfo._VerBaseAttr= NULL;
	m_ItemVertionInfo._VerObjAttr= NULL;
	m_ItemVertionInfo._ObjActiveVerAttr= NULL;	
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////
// CSelectInstDlg dialog
HTREEITEM InsertFictiveItem(CTreeCtrl *tree,HTREEITEM  item)
{
	if(tree==0)return 0;
	HTREEITEM newitem=tree->InsertItem(_T(""),0,0,item);
	tree->SetItemData(newitem,0);
	return newitem;
}

void CSelectInstDlg::RemoveItemsFromTree(HTREEITEM item, CaplOldSelInstItem *parent, bool bSaveItems)
{
	if (m_tree.ItemHasChildren(item))
	{
	   HTREEITEM hChildItem = m_tree.GetChildItem(item);

	   CArray <HTREEITEM,HTREEITEM> treeitems;
	   while (hChildItem != NULL)
	   {
			treeitems.Add(hChildItem);
			hChildItem = m_tree.GetNextSiblingItem(hChildItem);//, TVGN_NEXT);
	   }
	   int i;
	   for(i=0;i<treeitems.GetSize();i++)
	   {
			hChildItem	=treeitems[i];
			CItemData *dta=(CItemData*)m_tree.GetItemData(hChildItem);
			CaplOldSelInstItem *oitem=0;
			if(dta!=0)
			{
				if(m_old_items!=0 && bSaveItems)
				{
					oitem = new CaplOldSelInstItem(parent,dta->inst);
					if(dta->inst==0)
					{
						int a,b;
						m_tree.GetItemImage(hChildItem,a,b);
						if(a==ICON_FOLDERS)oitem->m_inst=(CaplInstance*)-2;
						else if(a==ICON_PERS_FOLDER)oitem->m_inst=(CaplInstance*)-4;
						else if(a==ICON_CATEGORIES)oitem->m_inst=(CaplInstance*)-3;
						else if(a==ICON_CLASSIFIER_SYSTEM)oitem->m_inst=(CaplInstance*)-5;
						else if(a==ICON_QUERYES)oitem->m_inst=(CaplInstance*)-6;
					}
					m_old_items->Add(oitem);
				}
			}
			RemoveItemsFromTree(hChildItem, oitem,bSaveItems);
			m_tree.DeleteItem(hChildItem);
			if(dta!=0)	delete dta;
	   }
   	   // for(i=0;i<treeitems.GetSize();i++) m_tree.DeleteItem(treeitems[i]);
//		item
	}
}

int CALLBACK CSelectInstDlg::CompareHtreeItem(LPARAM lParam1, LPARAM lParam2,LPARAM lParamSort)
{
	if(lParam1==0) return 0;
	if(lParam2==0) return 0;
	CTreeCtrl* tree = (CTreeCtrl*) lParamSort;
	if(tree==0)return 0;

	HTREEITEM item1=((CItemData*)lParam1)->item;
	HTREEITEM item2=((CItemData*)lParam2)->item;
	int img1,img2,img0;
	tree->GetItemImage(item1,img1,img0);
	tree->GetItemImage(item2,img2,img0);
	if(img1<img2) return -1;
	if(img1>img2) return  1;

	// Изменено 27.09.2023 для нормальной сортировки проектов по просьбе Созвездия
	if((img1>=ICON_DOC_INDEX && img1<ICON_CHARACT_INDEX) ||
		(img1>=ICON_PRODUCT_INDEX && img1<ICON_CONTINUE_INDEX+2))  // тут изделия и проекты
		return aplCompareNumericStr(tree->GetItemText(item1),tree->GetItemText(item2));

	return (tree->GetItemText(item1)).Compare(tree->GetItemText(item2));
} 

CSelectInstDlg::CSelectInstDlg(CWnd* pParent /*=NULL*/)
	: CResizableDialog(CSelectInstDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSelectInstDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	m_folders_item=0;
	m_categories_item=0;
	m_classifier_item=0;
	m_query_item= 0;
	m_api=0;
	m_mode=0;
	m_sel_inst=0;
	m_cur_inst=0;
	m_sel_doc= 0;
	m_NoExpand=false;
	m_base_items=0;

	m_bShPrd= true;
	m_bShPdf= true;
	m_bShDoc= true;
	m_bShDocVer= true;
	m_bShAct= true;
	m_show_ass_doc=true;
}


void CSelectInstDlg::DoDataExchange(CDataExchange* pDX)
{
	CResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSelectInstDlg)
	DDX_Control(pDX, IDC_SHOW_INSTS, m_inst_show_btn);
	DDX_Control(pDX, IDC_VIEW_DOCUMENT, m_viewDocBtn);
	DDX_Control(pDX, IDC_FIND_BUTTON, m_findBtn);
	DDX_Control(pDX, IDC_SHOW_VERS, m_showVerBtn);
	DDX_Control(pDX, IDC_SHOW_PRDS, m_showPrdBtn);
	DDX_Control(pDX, IDC_SHOW_CHAR, m_showCharBtn);
	DDX_Control(pDX, IDC_SHOW_DOCS, m_showDocsBtn);
	DDX_Control(pDX, IDC_SHOW_ACTS, m_showActsBtn);
	DDX_Control(pDX, IDC_CREATE_FOLDER, m_create_folder_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDC_OBJ_TREE, m_tree);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CSelectInstDlg, CResizableDialog)
	//{{AFX_MSG_MAP(CSelectInstDlg)
	ON_NOTIFY(TVN_ITEMEXPANDING, IDC_OBJ_TREE, OnItemexpandingObjTree)
	ON_WM_DESTROY()
	ON_NOTIFY(TVN_SELCHANGED, IDC_OBJ_TREE, OnSelchangedObjTree)
	ON_BN_CLICKED(IDC_CREATE_FOLDER, OnCreateFolder)
	ON_BN_CLICKED(IDC_SHOW_PRDS, OnShowPrds)
	ON_BN_CLICKED(IDC_SHOW_PDFS, OnShowChrs)
	ON_BN_CLICKED(IDC_SHOW_DOCS, OnShowDocs)
	ON_BN_CLICKED(IDC_SHOW_VERS, OnShowVers)
	ON_BN_CLICKED(IDC_SHOW_ACTS, OnShowActs)
	ON_BN_CLICKED(IDC_FIND_BUTTON, OnFindButton)
	ON_BN_CLICKED(IDC_VIEW_DOCUMENT, OnViewDocument)
	ON_BN_CLICKED(IDC_SHOW_INSTS, OnShowInsts)
	ON_NOTIFY(NM_DBLCLK, IDC_OBJ_TREE, OnDblclkObjTree)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSelectInstDlg message handlers
void CSelectInstDlg::OnDestroy() 
{
	RemoveItemsFromTree(0,0,true);
	CResizableDialog::OnDestroy();
		
	
	//немного кривовато, но пока работает (фокус возвращается)
	CWnd* prWnd= GetParent();
	if(prWnd)prWnd->BringWindowToTop();
}
void CSelectInstDlg::InitExpand(HTREEITEM item)
{
	if(item==0) return;
	m_tree.Expand(item,TVE_EXPAND);
	CItemData *dta=(CItemData*)m_tree.GetItemData(item);
	if(dta==0) return;
	if(dta->fictive!=0) m_tree.DeleteItem(dta->fictive);
	dta->fictive=0;
}
//******************************************************************************
BOOL CSelectInstDlg::OnInitDialog() 
{
	CResizableDialog::OnInitDialog();
	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   
	if(m_title!=_T("")) SetWindowText(m_title);
	
	m_tree.SetImageList(aplGetInstImageList(),TVSIL_NORMAL);//   TVSIL_STATE);
	m_icons.Create(IDR_ICONS,16,1,RGB(192,192,192));

	AddAnchor(IDC_OBJ_TREE,TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_CREATE_FOLDER,BOTTOM_LEFT);
	AddAnchor(IDC_VIEW_DOCUMENT, BOTTOM_LEFT);
	AddAnchor(IDOK,BOTTOM_RIGHT);
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	AddAnchor(IDC_FIND_BUTTON, TOP_RIGHT);
		
	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_create_folder_btn.SetIcon(m_icons.ExtractIcon(0));
	m_create_folder_btn.SetFlat(FALSE);	
	m_viewDocBtn.SetIcon(GetAplTableIco(APL_TABLE_VIEW));
	m_viewDocBtn.SetFlat(FALSE);

	m_btnImglst.Create(IDR_SELECT_INSTANCE, 20, 20, RGB(255, 0, 255));
	int i;
		
	m_findBtn.SetIcon(m_btnImglst.ExtractIcon(13));
	m_findBtn.SetTooltipText(APL_T("Найти объект в базе данных"));
	m_findBtn.SetFlat(FALSE);

	m_showPrdBtn.SetIcon(m_btnImglst.ExtractIcon(0));
	m_showPrdBtn.SetTooltipText(APL_T("Показать изделия"));
	m_showPrdBtn.SetFlat(FALSE);
	
	m_showCharBtn.SetIcon(m_btnImglst.ExtractIcon(10));
	m_showCharBtn.SetTooltipText(APL_T("Показать характеристики"));
	m_showCharBtn.SetFlat(FALSE);
	
	m_showDocsBtn.SetIcon(m_btnImglst.ExtractIcon(4));
	m_showDocsBtn.SetTooltipText(APL_T("Показать документы"));
	m_showDocsBtn.SetFlat(FALSE);
	
	m_showVerBtn.SetIcon(m_btnImglst.ExtractIcon(6));
	m_showVerBtn.SetTooltipText(APL_T("Показать версии"));
	m_showVerBtn.SetFlat(FALSE);
	
	m_showActsBtn.SetIcon(m_btnImglst.ExtractIcon(8));	
	m_showActsBtn.SetTooltipText(APL_T("Показать действия"));
	m_showActsBtn.SetFlat(FALSE);

	m_ok_btn.EnableWindow(FALSE);
	m_create_folder_btn.EnableWindow(FALSE);
	m_viewDocBtn.EnableWindow(FALSE);

	m_inst_show_btn.SetIcon(m_btnImglst.ExtractIcon(14));
	m_inst_show_btn.SetTooltipText( APL_T("Показать экземпляры и партии"));
	m_inst_show_btn.SetFlat(FALSE);
	m_inst_show_btn.EnableWindow(FALSE);

	aplExtent ext;
	CString buf;

//	apidata.SetAutoDownloadMode(true);

	bool bShowTop=true;

	if(m_base_items!=0)
	{
		if(m_base_items->Size>0) bShowTop=false;
	}

	if(bShowTop)
	{
		if((m_mode&APL_MODE_SELECT_PERSORG)>0 || 
			(m_mode&APL_MODE_SELECT_PERSON)>0 ||
			(m_mode&APL_MODE_SELECT_ORG)>0 )
		{
			m_perorg_item= m_tree.InsertItem( APL_T("Орг. структура"), ICON_ORGANIZATION, ICON_ORGANIZATION);
			CItemData *dta=new CItemData(0, m_perorg_item, InsertFictiveItem(&m_tree, m_perorg_item));
			m_tree.SetItemData(m_perorg_item, (DWORD)dta);

			FillPersonOrgTree(m_perorg_item);
		} 
		
		m_pers_folders_item=m_tree.InsertItem( APL_T("Личные папки"),ICON_PERS_FOLDER, ICON_PERS_FOLDER);
		CItemData *dta=new CItemData(0,m_pers_folders_item,InsertFictiveItem(&m_tree,m_pers_folders_item));
		m_tree.SetItemData(m_pers_folders_item,(DWORD)dta);

		m_folders_item=m_tree.InsertItem( APL_T("Папки"),ICON_FOLDERS, ICON_FOLDERS);
		dta=new CItemData(0,m_folders_item,InsertFictiveItem(&m_tree,m_folders_item));
		m_tree.SetItemData(m_folders_item,(DWORD)dta);

		/*
		m_categories_item=m_tree.InsertItem( APL_T("Категории"),ICON_CATEGORIES, ICON_CATEGORIES);
		CItemData *dta1=new CItemData(0,m_categories_item,InsertFictiveItem(&m_tree,m_categories_item));
		m_tree.SetItemData(m_categories_item,(DWORD)dta1);
		*/

		m_classifier_item= m_tree.InsertItem( APL_T("Справочники"), ICON_CLASSIFIER_SYSTEM, ICON_CLASSIFIER_SYSTEM);
		dta=new CItemData(0, m_classifier_item, InsertFictiveItem(&m_tree, m_classifier_item));
		m_tree.SetItemData(m_classifier_item, (DWORD)dta);
		

		m_query_item= m_tree.InsertItem( APL_T("Поиск в БД"), ICON_QUERYES, ICON_QUERYES);
		dta= new CItemData(0, m_query_item, InsertFictiveItem(&m_tree, m_query_item));
		m_tree.SetItemData(m_query_item, (DWORD)dta);

	}
	else
	{
		for(i=0;i<m_base_items->GetSize();i++)
		{
			if((*m_base_items)[i]==0) continue;
			if((*m_base_items)[i]->GetAccessmode()>aplRO) continue;

			if(apidata.IsKindOf((*m_base_items)[i],m_api->m_categ_mgr.e_categ))
			{
///				apidata.GetAttr((*m_base_items)[i],m_api->m_categ_mgr.a_categ_name,buf);
				m_api->GetItemName(m_base_items->GetAt(i),buf);
				int ico = m_api->GetInstIco((*m_base_items)[i]);
				HTREEITEM item=m_tree.InsertItem(buf,ico, ico,0);
				CItemData *dta1=new CItemData((*m_base_items)[i],item,InsertFictiveItem(&m_tree,item));
				m_tree.SetItemData(item,(DWORD)dta1);
				
				InitExpand(item);
			}
			else if(apidata.IsKindOf((*m_base_items)[i],m_api->m_prd_mgr.e_prd))
			{
				InsertPrdInTree(0, (*m_base_items)[i]);
			}
			else if(apidata.IsKindOf((*m_base_items)[i],m_api->m_prd_mgr.e_pdf))
			{
				InsertPdfInTree(0, (*m_base_items)[i]);
			}
			else if(apidata.IsKindOf((*m_base_items)[i],m_api->m_doc_mgr.e_doc))
			{
				InsertDocInTree(0, (*m_base_items)[i]);
			}
			else if(apidata.IsKindOf((*m_base_items)[i],m_api->m_bp_mgr.e_bp))
			{
				InsertActionInTree(0, (*m_base_items)[i]); //-V595
			}
		}
	}

	m_NoExpand=true;
	if(m_old_items!=0)
	{
		CaplOldSelInstItem *olditem;
		for(i=0;i<m_old_items->GetSize();i++)
		{
			olditem=m_old_items->GetAt(i);
			if(olditem->m_inst==(CaplInstance*)-2)	olditem->m_item=m_folders_item;
			else if(olditem->m_inst==(CaplInstance*)-4) olditem->m_item=m_pers_folders_item;
			else if(olditem->m_inst==(CaplInstance*)-3) olditem->m_item=m_categories_item;
			else if(olditem->m_inst==(CaplInstance*)-5) olditem->m_item=m_classifier_item;
			else if(olditem->m_inst==(CaplInstance*)-6) olditem->m_item=m_query_item;
			else
			{
				if(olditem->m_inst==0) continue;
				if(olditem->m_inst->GetType()==0) continue;
				if(olditem->m_inst->GetAccessmode()>aplRO) continue;
				if(olditem->m_parent==0) continue;
				if(olditem->m_parent->m_item==0) continue;

				if(m_base_items!=0)
				{
					if(m_base_items->Find(olditem->m_inst)<0) continue;
				}

				CItemData *dta1;
				HTREEITEM item;
				CItemData dta2;dta2.item=olditem->m_parent->m_item;

				if(apidata.IsKindOf(olditem->m_inst,m_api->m_folder_mgr.e_folder))
				{
//					apidata.GetAttr(olditem->m_inst,m_api->m_folder_mgr.a_folder_name,buf);
					m_api->GetItemName(olditem->m_inst,buf);
					item=m_tree.InsertItem(buf,ICON_FOLDER,ICON_FOLDER,olditem->m_parent->m_item);
					dta1=new CItemData(olditem->m_inst,item,InsertFictiveItem(&m_tree,item));
					m_tree.SetItemData(item,(DWORD)dta1);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}
				else if(apidata.IsKindOf(olditem->m_inst,m_api->m_categ_mgr.e_categ))
				{
//					apidata.GetAttr(olditem->m_inst,m_api->m_categ_mgr.a_categ_name,buf);
					m_api->GetItemName(olditem->m_inst,buf);
					item=m_tree.InsertItem(buf,ICON_CATEGORIES,ICON_CATEGORIES,olditem->m_parent->m_item);
					dta1=new CItemData(olditem->m_inst,item,InsertFictiveItem(&m_tree,item));
					m_tree.SetItemData(item,(DWORD)dta1);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}
				else if(apidata.IsKindOf(olditem->m_inst,m_api->m_prd_mgr.e_prd))
				{
					item=InsertPrdInTree(olditem->m_parent->m_item,olditem->m_inst);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}
				else if(apidata.IsKindOf(olditem->m_inst,m_api->m_prd_mgr.e_pdf))
				{
					item=InsertPdfInTree(olditem->m_parent->m_item,olditem->m_inst);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}
				else if(apidata.IsKindOf(olditem->m_inst,m_api->m_doc_mgr.e_doc))
				{
					item=InsertDocInTree(olditem->m_parent->m_item, olditem->m_inst);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}
				else if(apidata.IsKindOf(olditem->m_inst, m_api->m_bp_mgr.e_bp))
				{
					item= InsertActionInTree(olditem->m_parent->m_item, olditem->m_inst);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}
				else if(apidata.IsKindOf(olditem->m_inst, m_api->m_prd_inst_mgr.e_lot))
				{
					item= InsertLotInTree(olditem->m_parent->m_item, olditem->m_inst);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}
				else if(apidata.IsKindOf(olditem->m_inst, m_api->m_prd_inst_mgr.e_prd_inst))
				{
					item= InsertProdInstInTree(olditem->m_parent->m_item, olditem->m_inst);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}
				else if(apidata.IsKindOf(olditem->m_inst, m_api->m_query_mgr.e_apl_query))
				{
					item= InsertQueryInstInTree(olditem->m_parent->m_item, olditem->m_inst);
					olditem->m_item=item;
					InitExpand(olditem->m_parent->m_item);
				}


			}
		}
		m_old_items->Clear();
	}
	m_NoExpand=false;
	
	if(m_api->m_bModeIntegration) 
	{
		m_viewDocBtn.ModifyStyle(WS_VISIBLE, 0, 0);
	}

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}
//******************************************************************************
void CSelectInstDlg::InsertInstInTree(CaplInstance* inst,CItemData* dta)
{
	if(inst==0)return;
	if(dta==0)return;
	if(inst->GetAccessmode()==aplNO)return;
	if(apidata.IsKindOf(inst,m_api->m_prd_mgr.e_prd))
	{
		InsertPrdInTree(dta->item, inst);
	}
	else if(apidata.IsKindOf(inst,m_api->m_prd_mgr.e_pdf))
	{
		InsertPdfInTree(dta->item, inst);
	}
	else if(apidata.IsKindOf(inst,m_api->m_doc_mgr.e_doc))
	{
		InsertDocInTree(dta->item, inst);
	}
	else if(apidata.IsKindOf(inst,m_api->m_bp_mgr.e_bp))
	{
		InsertActionInTree(dta->item, inst);
	}
	else if(apidata.IsKindOf(inst, m_api->m_bp_mgr.e_apl_bp_inst))
	{
		InsertProdInstInTree(dta->item, inst);
	}
	else if(apidata.IsKindOf(inst, m_api->m_prd_inst_mgr.e_lot))
	{
		InsertLotInTree(dta->item, inst);
	}
	else if(apidata.IsKindOf(inst, m_api->m_prd_inst_mgr.e_prd_inst))
	{
		InsertProdInstInTree(dta->item, inst);
	}
	else if(apidata.IsKindOf(inst, m_api->m_query_mgr.e_apl_query))
	{
		InsertQueryInstInTree(dta->item, inst);
	}
}

//******************************************************************************
void CSelectInstDlg::OnDblclkObjTree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	*pResult = 0;
	UINT flag=TVHT_ONITEM|TVHT_ONITEMRIGHT|TVHT_NOWHERE;
	const MSG*  msg=GetCurrentMessage();
	CPoint mouseclick=msg->pt;
	m_tree.ScreenToClient(&mouseclick);
	HTREEITEM item=m_tree.HitTest(mouseclick,&flag);
	CItemData *dta=0;
	dta=(CItemData*)m_tree.GetItemData(item);
	if(dta==0) return;

	if(dta->inst==0) return;
	if(apidata.IsKindOf(dta->inst,m_api->m_query_mgr.e_apl_query))
	{
		Find(dta->inst,item);
		*pResult=1;
	}
}


//******************************************************************************
void CSelectInstDlg::ExpandQueries(HTREEITEM item) 
{
	aplExtent ext;
	CString buf;//,buf1,s_id,s_name;
	CItemData *dta=(CItemData*)m_tree.GetItemData(item);
	CItemData *dta1=0;
	if(dta==0) return;
//	CaplInstance* inst;
	COleDateTime exec_date;
	int i;
	m_api->m_query_mgr.GetFindResult(0,ext,exec_date);
	m_api->m_query_mgr.LoadQueryInfo(ext,true);
	for(i=0;i<ext.Size;i++)
	{
		if(ext[i]->GetAccessmode()==aplNO)continue;
		apidata.GetAttr(ext[i],m_api->m_query_mgr.a_apl_query_name,buf);
		int ico = m_api->GetInstIco(ext[i]);
		item=m_tree.InsertItem(buf,ico,ico,dta->item);
		dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
		m_tree.SetItemData(item,(DWORD)dta1);
	}

}

//******************************************************************************
void CSelectInstDlg::OnItemexpandingObjTree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	if(m_NoExpand==true) return;
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	// TODO: Add your control notification handler code here
	*pResult = 0;
	if(pNMTreeView==0) return;
	HTREEITEM item=pNMTreeView->itemNew.hItem;

	if(item==0) return;
	CItemData *dta=(CItemData*)m_tree.GetItemData(item);
	if(dta==0) return;

	int i;
	aplExtent ext,ext1,rels;
	CString buf,buf1,s_id,s_name;
	CItemData *dta1=0;
	CaplInstance* inst;
	COleDateTime exec_date;
	
	if(pNMTreeView->action==1)
	{
		// Закрытие
		
		if((dta->inst==NULL && dta->item!=m_perorg_item) || 
			(dta->inst && !apidata.IsKindOf(dta->inst, m_api->m_appr_mgr.e_org) &&
			!apidata.IsKindOf(dta->inst, m_api->m_appr_mgr.e_pers_org)))
		{
			RemoveItemsFromTree(item);
			dta->fictive=InsertFictiveItem(&m_tree,item);
			dta->ext.Clear();
		}
	}
	else if(pNMTreeView->action==2)
	{
		// раскрытие
		if(dta->fictive!=0)	{m_tree.DeleteItem(dta->fictive); dta->fictive=0;}
		if(dta->inst==0)
		{
			int a,b;
			m_tree.GetItemImage(item,a,b);
			switch(a)
			{
			case ICON_FOLDERS:
				m_api->m_folder_mgr.GetAllSubFolder(0,ext);
				for(i=0;i<ext.Size;i++)
				{
					if(ext[i]->GetAccessmode()==aplNO)continue;
					apidata.GetAttr(ext[i],m_api->m_folder_mgr.a_folder_name,buf);
					item=m_tree.InsertItem(buf,ICON_FOLDER,ICON_FOLDER,dta->item);
					dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
					m_tree.SetItemData(item,(DWORD)dta1);
				}
				break;
			case ICON_PERS_FOLDER:
				m_api->m_folder_mgr.GetAllSubFolder(apidata.GetCurrUser(),ext);
				for(i=0;i<ext.Size;i++)
				{
					if(ext[i]->GetAccessmode()==aplNO)continue;
					apidata.GetAttr(ext[i],m_api->m_folder_mgr.a_folder_name,buf);
					int ico = m_api->GetInstIco(ext[i]);
					item=m_tree.InsertItem(buf,ico,ico,dta->item);
					dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
					m_tree.SetItemData(item,(DWORD)dta1);
				}
				break;
			case ICON_CATEGORIES:
				m_api->m_categ_mgr.GetAllSubCategory2(0, ext, rels);
				for(i=0;i<ext.Size;i++)
				{
					if(ext[i]->GetAccessmode()==aplNO)continue;
					m_api->GetItemName(ext[i], buf);
					int ico = m_api->GetInstIco(ext[i]);
					item=m_tree.InsertItem(buf, ico, ico, dta->item);
					dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
					m_tree.SetItemData(item,(DWORD)dta1);
				}
				break;
			case ICON_CLASSIFIER_SYSTEM:
				m_api->m_classifier_mgr.LoadSubClassifierSystems(0, ext);
				for(i=0;i<ext.Size;i++)
				{
					if(ext[i]->GetAccessmode()==aplNO)continue;
					m_api->GetItemName(ext[i], buf);
					int ico = m_api->GetInstIco(ext[i]);
					item=m_tree.InsertItem(buf, ico, ico, dta->item);
					dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
					m_tree.SetItemData(item,(DWORD)dta1);
				}
				break;
			case ICON_QUERYES:
				//m_tree.SetItemState(m_query_item, TVIS_SELECTED, TVIS_EXPANDEDONCE|TVIS_SELECTED);
				m_api->m_query_mgr.GetFindResult(0,ext,exec_date);
				m_api->m_query_mgr.LoadQueryInfo(ext,true);
				for(i=0;i<ext.Size;i++)
				{
					if(ext[i]->GetAccessmode()==aplNO)continue;
					InsertQueryInstInTree(m_query_item, ext[i]);
/*					apidata.GetAttr(ext[i],m_api->m_query_mgr.a_apl_query_name,buf);
					int ico = m_api->GetInstIco(ext[i]);
					item=m_tree.InsertItem(buf,ico,ico,dta->item);
					dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
					m_tree.SetItemData(item,(DWORD)dta1);*/
				}

				break;

				/*D
				int trd1=aplStartWaitDlg(APL_T("Отображение запроса ..."));
				m_tree.SetRedraw(FALSE);
				
				HTREEITEM item;
				CString buf;
				
				for(int i= 0; i<m_query_ext.GetSize(); i++)
				{
					if(!m_query_ext[i] || !m_query_ext[i]->id || !m_query_ext[i]->GetType()) continue;
					if(m_query_ext[i]->GetAccessmode()==aplNO)continue;
					
					if(apidata.IsKindOf(m_query_ext[i], m_api->m_folder_mgr.e_folder))
					{
						apidata.GetAttr(m_query_ext[i], m_api->m_folder_mgr.a_folder_name, buf);
						int ico = m_api->GetInstIco(m_query_ext[i]);
						item= m_tree.InsertItem(buf, ico, ico, m_query_item);
						dta= new CItemData(m_query_ext[i], item, InsertFictiveItem(&m_tree,item));
						m_tree.SetItemData(item, (DWORD)dta);
					}
					else if(apidata.IsKindOf(m_query_ext[i], m_api->m_prd_mgr.e_prd))
					{
						InsertPrdInTree(m_query_item, m_query_ext[i]);
					}
					else if(apidata.IsKindOf(m_query_ext[i], m_api->m_prd_mgr.e_pdf))
					{
						InsertPdfInTree(m_query_item, m_query_ext[i]);
					}
					else if(apidata.IsKindOf(m_query_ext[i], m_api->m_doc_mgr.e_doc))
					{
						InsertDocInTree(m_query_item, m_query_ext[i]);
					}
					else if(apidata.IsKindOf(m_query_ext[i], m_api->m_bp_mgr.e_bp))
					{
						InsertActionInTree(m_query_item, m_query_ext[i]);
					}
					else if(apidata.IsKindOf(m_query_ext[i], m_api->m_categ_mgr.e_categ))
					{
						apidata.GetAttr(m_query_ext[i], m_api->m_categ_mgr.a_categ_name, buf);
						int ico = m_api->GetInstIco(m_query_ext[i]);
						item= m_tree.InsertItem(buf, ico, ico, m_query_item);
						dta= new CItemData(m_query_ext[i], item, InsertFictiveItem(&m_tree, item));
						m_tree.SetItemData(item, (DWORD)dta);				
					}
					else if(apidata.IsKindOf(m_query_ext[i], m_api->m_prd_inst_mgr.e_lot))
					{
						InsertLotInTree(m_query_item, m_query_ext[i]);
					}
					else if(apidata.IsKindOf(m_query_ext[i], m_api->m_prd_inst_mgr.e_prd_inst))
					{
						InsertProdInstInTree(m_query_item, m_query_ext[i]);
					}
				}
				m_tree.SetRedraw();
				aplEndWaitDlg(trd1);
				D*/
				break;
			}
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_folder_mgr.e_folder))
		{
			// Раскрытие Папки
			m_api->m_folder_mgr.GetAllSubFolder(dta->inst,ext);
			for(i=0;i<ext.Size;i++)
			{
				if(ext[i]->GetAccessmode()==aplNO)continue;
				apidata.GetAttr(ext[i],m_api->m_folder_mgr.a_folder_name,buf);
				int ico = m_api->GetInstIco(ext[i]);
				item=m_tree.InsertItem(buf, ico, ico, dta->item);
				dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
				m_tree.SetItemData(item,(DWORD)dta1);
			}
			m_api->m_folder_mgr.GetFolderContents(dta->inst,ext);
			if(m_show_ass_doc){
				aplExtent ext_rel,ext_ass;
				m_api->m_doc_mgr.FindAssociatedDocuments(dta->inst,ext_ass,ext_rel);
				ext.Append(ext_ass);
			}
			for(i=0;i<ext.Size;i++)
			{
				InsertInstInTree(ext[i],dta);
			}
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_query_mgr.e_apl_query))
		{
			// Раскрытие запроса
			m_api->m_query_mgr.GetFindResult(dta->inst,ext,exec_date);
			m_api->LoadExtentInfo(ext);
			for(i=0;i<ext.Size;i++)
			{
				InsertInstInTree(ext[i],dta);
			}
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_categ_mgr.e_categ))
		{
			// Раскрытие Категории
			m_api->m_categ_mgr.GetAllSubCategory2(dta->inst, ext, rels);
			for(i=0;i<ext.Size;i++)
			{
				if(ext[i]->GetAccessmode()==aplNO)continue;
				m_api->GetItemName(ext[i], buf);
				int ico = m_api->GetInstIco(ext[i]);
				item=m_tree.InsertItem(buf, ico, ico, dta->item);
				dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
				m_tree.SetItemData(item,(DWORD)dta1);
			}
			m_api->m_categ_mgr.GetCategoryContents(dta->inst,ext);
			m_api->LoadExtentInfo(ext);
			for(i=0;i<ext.Size;i++)
			{
				InsertPrdInTree(dta->item, ext[i]);
			}
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_classifier_mgr.e_apl_classifier_system))
		{
			// Раскрытие справочников
			m_api->m_classifier_mgr.LoadSubClassifierSystems(dta->inst, ext);
			for(i=0;i<ext.Size;i++)
			{
				InsertPrdInTree(dta->item, ext[i]);
//				if(ext[i]->GetAccessmode()==aplNO)continue;
//				m_api->GetItemName(ext[i], buf);
//				int ico = m_api->GetInstIco(ext[i]);
//				item=m_tree.InsertItem(buf, ico, ico, dta->item);
//				dta1=new CItemData(ext[i],item,InsertFictiveItem(&m_tree,item));
//				m_tree.SetItemData(item,(DWORD)dta1);
			}
			m_api->m_classifier_mgr.LoadSubClassifierLevels(dta->inst, ext);
			for(i=0;i<ext.Size;i++)
			{
				InsertPrdInTree(dta->item, ext[i]);
			}
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_classifier_mgr.e_apl_classifier_level))
		{
			// Раскрытие уровней справочников
			m_api->m_classifier_mgr.LoadSubClassifierLevels(dta->inst, ext);
			for(i=0;i<ext.Size;i++)
			{
				InsertPrdInTree(dta->item, ext[i]);
			}
			if(m_api->m_classifier_mgr.TestObjectLevelOfLevel(dta->inst))
			{
				m_api->m_classifier_mgr.GetSubItems(dta->inst, ext,&rels);
				for(i=0;i<ext.Size;i++)
				{
					InsertPrdInTree(dta->item, ext[i]);
				}
			}
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_prd_mgr.e_prd))
		{
			// Раскрытие PRD
			m_api->m_prd_mgr.GetAllProductVersion(dta->inst,ext);
			for(i=0;i<ext.Size;i++)
			{
				if(ext[i]->GetAccessmode()==aplNO)continue;
				InsertPdfInTree(dta->item, ext[i]);
			}
/*			m_api->m_doc_mgr.FindAssociatedDocuments(dta->inst,ext,ext1);
			for(i=0;i<ext.Size;i++)
			{
				InsertDocInTree(dta->item, ext[i]);
			}*/
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_bp_mgr.e_bp))
		{
			// Раскрытие ACTION
			aplExtent ext;
			apidata.GetAttr(dta->inst,m_api->m_bp_mgr.a_bp_elements,ext);
			m_api->m_bp_mgr.LoadBPInfo(ext);
			for(i=0;i<ext.GetSize();i++)
			{
				if(ext[i]->GetAccessmode()==aplNO)continue;
				InsertActionInTree(dta->item, ext[i]);
			}
/*			m_api->m_doc_mgr.FindAssociatedDocuments(dta->inst,ext,ext1);
			for(i=0;i<ext.Size;i++)
			{
				InsertDocInTree(dta->item, ext[i]);
			}*/
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_prd_mgr.e_pdf))
		{
			// Раскрытие PDF
			m_api->m_prd_mgr.LoadAllSubProduct(0,0,dta->inst,ext1,ext,true);
			for(i=0;i<ext.Size;i++)
			{
				if(ext[i]->GetAccessmode()==aplNO)continue;
				InsertPdfInTree(dta->item, ext[i]);
			}
/*			m_api->m_doc_mgr.FindAssociatedDocuments(dta->inst,ext,ext1);
			for(i=0;i<ext.Size;i++)
			{
				InsertDocInTree(dta->item, ext[i]);
			}*/
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_prd_inst_mgr.e_prd_inst))
		{
			aplExtent rel, ext;
			m_api->m_prd_inst_mgr.LoadInsertedInstances(dta->inst,rel, ext);
			
			CString sDate;
			CaplInstance *prd_ins;
			for(int i=0; i<rel.Size;i++)
			{
				m_api->m_data.GetAttr(rel[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_date_removed, sDate);
				if(!sDate.IsEmpty()) continue;

				m_api->m_data.GetAttr(rel[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_related, prd_ins);
				if(prd_ins->GetAccessmode()==aplNO)continue;

				if(dta->ext.Find(prd_ins)<0)
					InsertProdInstInTree(dta->item,prd_ins);
				dta->ext.Add(prd_ins);
			}
		}
		else if(apidata.IsKindOf(dta->inst,m_api->m_doc_mgr.e_doc))
		{
			m_api->m_doc_mgr.FindAssociatedDocuments(dta->inst,ext,ext1);
			for(i=0;i<ext.Size;i++)
			{
				if(ext[i]->GetAccessmode()==aplNO)continue;
				InsertDocInTree(dta->item, ext[i]);
			}
			CaplInstance *act_rev=0;
			apidata.GetAttr(dta->inst,m_api->m_doc_mgr.a_apl_doc_active,act_rev);
			if(act_rev!=0)
			{
				m_api->m_doc_mgr.FindAssociatedDocuments(act_rev,ext,ext1);
				for(i=0;i<ext.Size;i++)
				{
					if(ext[i]->GetAccessmode()==aplNO)continue;
					InsertDocInTree(dta->item, ext[i]);
				}
			}
		}
		else if(apidata.IsKindOf(dta->inst, m_api->m_doc_mgr.e_apl_doc_rev))
		{
			m_NoExpand= true;
		
			apidata.GetAttr(dta->inst, m_api->m_doc_mgr.a_apl_doc_rev_doc, inst);
			m_api->m_doc_mgr.LoadAllDocumentRevision(inst, ext1);
			
			SetObjVertionInfo(aplDoc, ICON_DOCUMENT_REV, 
				m_api->m_doc_mgr.a_apl_doc_rev_id,
				m_api->m_doc_mgr.a_apl_doc_rev_base,
				m_api->m_doc_mgr.a_apl_doc_rev_doc,
				m_api->m_doc_mgr.a_apl_doc_active);
			FillRevisionTree(dta->item, ext1);
			ClearObjVertionInfo();

			m_NoExpand= false;
		}
		else if(apidata.IsKindOf(dta->inst, m_api->m_bp_mgr.e_apl_bp_ver))
		{
			m_NoExpand= true;
			
			apidata.GetAttr(dta->inst, m_api->m_bp_mgr.a_bp_ver_bp, inst);
			m_api->m_bp_mgr.GetAllBPVersion(inst, ext1);
			
			int ico= APL_ICON_BP_VERTION;
			aplExtent subBP;
			apidata.GetAttr(inst, m_api->m_bp_mgr.a_bp_elements, subBP);
			if(subBP.GetSize()) ico+=2;
			ico = m_api->GetInstIco(inst);

			SetObjVertionInfo(aplBP, ico,
				m_api->m_bp_mgr.a_bp_ver_num,
				m_api->m_bp_mgr.a_bp_ver_base,
				m_api->m_bp_mgr.a_bp_ver_bp,
				m_api->m_bp_mgr.a_bp_act);
			FillRevisionTree(dta->item, ext1);
			ClearObjVertionInfo();			

			m_NoExpand= false;
		}
		else if(apidata.IsKindOf(dta->inst, m_api->m_prd_inst_mgr.e_lot))
		{
			m_api->m_prd_inst_mgr.FindAllLotProductInstance(dta->inst, ext1);
			for(i= 0; i<ext1.GetSize(); i++)
			{
				if(ext[i]->GetAccessmode()==aplNO)continue;
				InsertProdInstInTree(dta->item, ext1[i]);
			}
		}

		TVSORTCB tvs;
		tvs.hParent = dta->item;
		tvs.lpfnCompare = CompareHtreeItem;
		tvs.lParam = (LPARAM) &m_tree;
		m_tree.SortChildrenCB(&tvs);
	}
}
//******************************************************************************
HTREEITEM CSelectInstDlg::InsertPrdInTree(HTREEITEM parent, CaplInstance *prd)
{
	if(prd==0) return 0;
	if(!m_bShPrd) return 0;
	if(prd->GetAccessmode()==aplNO)return 0;
	
	CString buf,s_name;
	aplExtent ext;

	m_api->GetItemName(prd,buf);
	int ico = m_api->GetInstIco(prd);

	HTREEITEM item=m_tree.InsertItem(buf,ico, ico, parent);
	CItemData *dta1=new CItemData(prd,item,InsertFictiveItem(&m_tree,item));
	m_tree.SetItemData(item,(DWORD)dta1);
	return item;
}
//******************************************************************************
HTREEITEM CSelectInstDlg::InsertQueryInstInTree(HTREEITEM parent, CaplInstance *query)
{
	if(query==0) return 0;
	if(!m_bShPrd) return 0;
	if(query->GetAccessmode()==aplNO)return 0;
	
	CString buf,s_name;
	aplExtent ext;
	CaplInstance* ct;
	
	CItemData* pDta= (CItemData*)m_tree.GetItemData(parent);
	if(-1!=pDta->ext.Find(query))
	{
		HTREEITEM hItem= m_tree.GetChildItem(parent);
		
		while(1)
		{
			if(!hItem) break;
			CItemData *item= (CItemData*)m_tree.GetItemData(hItem);
			if(item->inst==query) return hItem;
			hItem= m_tree.GetNextItem(parent, TVGN_NEXT);
		}
		return 0;
	}
	pDta->ext.Add(query);
	
	apidata.GetAttr(query,m_api->m_query_mgr.a_apl_query_combined_table,ct);
	if(ct!=0)return 0;

	m_api->m_query_mgr.LoadQueryInfo(query,true);
	m_api->GetItemName(query,buf);
	int ico = m_api->GetInstIco(query);

	HTREEITEM item=m_tree.InsertItem(buf,ico, ico, parent);
	CItemData *dta1=new CItemData(query,item,InsertFictiveItem(&m_tree,item));
	m_tree.SetItemData(item,(DWORD)dta1);
	
	return item;
}
//******************************************************************************
HTREEITEM CSelectInstDlg::InsertActionInTree(HTREEITEM parent, CaplInstance *act)
{
	if(act==0) return 0;
	if(act->GetType()==0) return 0;
	if(!m_bShAct) return 0;
	if(act->GetAccessmode()==aplNO)return 0;
	
	CString buf;
	int ico;
	m_api->GetItemName(act, buf);
	ico = m_api->GetInstIco(act);
	

	HTREEITEM item=m_tree.InsertItem(buf,ico,ico,parent);
	CItemData *dta1=new CItemData(act,item,InsertFictiveItem(&m_tree,item));
	m_tree.SetItemData(item,(DWORD)dta1);
	return item;
}
//******************************************************************************
HTREEITEM CSelectInstDlg::InsertPdfInTree(HTREEITEM parent, CaplInstance *pdf)
{
	if(pdf==0) return 0;
	if(!m_bShPdf) return 0;
	if(pdf->GetAccessmode()==aplNO)return 0;
	
	CString buf,s_id,s_name;
//	CaplInstance *prd;
	int j;

/*
	apidata.GetAttr(pdf,m_api->m_prd_mgr.a_pdf_prd,prd);
	if(prd)
		apidata.GetAttr(prd,m_api->m_prd_mgr.a_prd_id,buf);
	if(buf==_T("")) buf=_T("?");
	if(prd)
		apidata.GetAttr(prd,m_api->m_prd_mgr.a_prd_name,s_name);
	if(s_name!=_T("")) { buf+=_T(" : ");buf+=s_name;}

	apidata.GetAttr(pdf,m_api->m_prd_mgr.a_pdf_id,s_id);
	if(s_id!=_T("")) { buf+=_T(" : ");buf+=s_id;}

	apidata.GetAttr(pdf,m_api->m_prd_mgr.a_apl_pdf_type,s_name);
	if(s_name==_T("assembly")) j=APL_ICON_ASSEMBLY;
	else if(s_name==_T("material")) j=APL_ICON_MATERIAL;
	else if(s_name==_T("kit")) j=APL_ICON_KIT;
	else if(s_name==_T("komplex")) j=APL_ICON_KOMPLEX;
	else j=APL_ICON_PART;
*/
	j = m_api->GetInstIco(pdf);
	m_api->GetItemName(pdf,buf);

	HTREEITEM item=m_tree.InsertItem(buf,j,j,parent);
	CItemData *dta1=new CItemData(pdf,item,InsertFictiveItem(&m_tree,item));
	m_tree.SetItemData(item,(DWORD)dta1);
	return item;
}
//******************************************************************************
HTREEITEM CSelectInstDlg::InsertDocInTree(HTREEITEM parent, CaplInstance *doc)
{
	if(doc==0) return 0;
	if(!m_bShDoc) return 0;
	if(doc->GetAccessmode()==aplNO)return 0;
	
	CString buf,s_id,s_name;
	int j;

	apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_id, s_name);
	if(s_name==_T("")) s_name=_T("?");
	apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_name, buf);
	if(buf!=_T("")) {s_name+=_T(" : "); s_name+=buf;}
	
	CaplInstance* inst= NULL;
	buf= _T("");
	apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_kind, inst);
	if(inst)
		apidata.GetAttr(inst, m_api->m_doc_mgr.a_dt_pdt, buf);
	if(buf!=_T("")) {s_name+=_T(" : "); s_name+=buf;}

/*
	j=APL_ICON_DOCUMENT;
	CaplInstance* lock= NULL;
	apidata.GetAttr(doc, m_api->m_doc_mgr.a_apl_doc_lock, lock);
	if(lock) j++;
*/
	j = m_api->GetInstIco(doc);
	
	m_api->GetItemName(doc,s_name);
	
	HTREEITEM item=m_tree.InsertItem(s_name,j,j,parent);
	CItemData *dta1=new CItemData(doc,item,InsertFictiveItem(&m_tree,item));
	m_tree.SetItemData(item,(DWORD)dta1);
	return item;
}
//******************************************************************************
HTREEITEM CSelectInstDlg::InsertRevisionInTree(HTREEITEM parent, CaplInstance *rev)
{
	if(rev==0) return 0;
	if(!m_bShDocVer) return 0;
	if(rev->GetAccessmode()==aplNO)return 0;
	
	CString buf;
	int ico= m_ItemVertionInfo._ico;
	CaplInstance* inst, *inst1;
	
	apidata.GetAttr(rev, m_ItemVertionInfo._VerIdAttr, buf);
	if(buf==_T("")) buf=_T("?");

	apidata.GetAttr(rev, m_ItemVertionInfo._VerObjAttr, inst);
	apidata.GetAttr(inst, m_ItemVertionInfo._ObjActiveVerAttr, inst1);
	if(inst1==rev) ico++;

	ico = m_api->GetInstIco(rev);

	HTREEITEM item= m_tree.InsertItem(buf, ico, ico, parent);
	CItemData *itemData=new CItemData(rev, item, InsertFictiveItem(&m_tree, item));
	m_tree.SetItemData(item, (DWORD)itemData);
	m_tree.Expand(item, TVE_EXPAND);
/*	aplExtent ext, ext1;
	m_api->m_doc_mgr.FindAssociatedDocuments(rev, ext, ext1);
	for(int i=0; i<ext.GetSize(); i++)
	{
		InsertDocInTree(item, ext[i]);
	}*/
	m_tree.SetRedraw();
	return item;
}

HTREEITEM CSelectInstDlg::InsertCharInTree(HTREEITEM parent, CaplInstance *chr_ass)
{
	if(!chr_ass) return 0;
	if(chr_ass->GetAccessmode()==aplNO)return 0;
	
	int ico;
//	ico= APL_ICON_CHAR_SEL;
	CaplInstance *unit, *type, *chr= NULL;
	CString buf,buf1;

	if(m_api->m_data.IsKindOf(chr_ass, m_api->m_charact_mgr.e_apl_charact_value))
		apidata.GetAttr(chr_ass, m_api->m_charact_mgr.a_apl_charact_val_charact, chr);
	else if(m_api->m_data.IsKindOf(chr_ass, m_api->m_charact_mgr.e_apl_charact_value_ver))
		apidata.GetAttr(chr_ass, m_api->m_charact_mgr.a_apl_charact_val_ver_charact, chr);

	if(chr) apidata.GetAttrBN(chr, _T("name"), buf);
	apidata.GetAttr(chr_ass, m_api->m_charact_mgr.a_apl_charact_val_type, type);
	if(type) apidata.GetAttrBN(type, _T("name"), buf1);
	if(!buf1.IsEmpty()) {buf+=_T(" ("); buf+=buf1; buf+=_T(")"); }
	apidata.GetAttrBN(chr, _T("unit"), unit);
//	apidata.GetAttrBN(chr_ass, _T("val"), val);

	if(chr_ass!=0)
	{
		if(chr_ass->GetAccessmode()>aplRO) buf+= APL_T(" (нет доступа)");
		else
		{
			buf+=_T(" = ");
			// чтение значения
			m_api->m_charact_mgr.PrintCharacteristicValue(chr_ass, unit, buf1);
			buf+=buf1;
		}
	}
	else buf+= APL_T(" (не задано)");

	ico = m_api->GetInstIco(chr_ass);

	HTREEITEM item= m_tree.InsertItem(buf, ico, ico, parent);
	CItemData *itemData=new CItemData(chr_ass, item, InsertFictiveItem(&m_tree, item));
	m_tree.SetItemData(item, (DWORD)itemData);

	return item;	
}

HTREEITEM CSelectInstDlg::InsertProdInstInTree(HTREEITEM parent, CaplInstance *prd_inst)
{
	if(prd_inst==0) return 0;
	if(prd_inst->GetAccessmode()==aplNO)return 0;
	int ico;
/*
	if(m_api->m_data.IsKindOf(prd_inst,m_api->m_prd_inst_mgr.e_prd_inst))
		ico= APL_ICON_PROD_INST;
	else if(m_api->m_data.IsKindOf(prd_inst,m_api->m_prd_inst_mgr.e_lot))
		ico= APL_ICON_LOT;
	else if(m_api->m_data.IsKindOf(prd_inst,m_api->m_bp_mgr.e_apl_bp_inst))
		ico = APL_ICON_ACTION_INST;
*/
	CString buf,buf1;
	
//	apidata.GetAttr(prd_inst, m_api->m_prd_inst_mgr.a_prd_inst_id, buf);
	m_api->GetItemName(prd_inst,buf);
	ico = m_api->GetInstIco(prd_inst);

	HTREEITEM item= m_tree.InsertItem(buf, ico, ico, parent);
	CItemData *itemData=new CItemData(prd_inst, item, InsertFictiveItem(&m_tree, item));
	m_tree.SetItemData(item, (DWORD)itemData);
	return item;
}

HTREEITEM CSelectInstDlg::InsertLotInTree(HTREEITEM parent, CaplInstance *lot)
{
	if(lot==0) return 0;
	if(lot->GetAccessmode()==aplNO)return 0;
	int ico;
// 	ico= APL_ICON_LOT;
	CString buf,buf1;
	
//	apidata.GetAttr(lot, m_api->m_prd_inst_mgr.a_lot_id, buf);
	m_api->GetItemName(lot,buf);
	ico = m_api->GetInstIco(lot);

	HTREEITEM item= m_tree.InsertItem(buf, ico, ico, parent);
	CItemData *itemData=new CItemData(lot, item, InsertFictiveItem(&m_tree, item));
	m_tree.SetItemData(item, (DWORD)itemData);
	return item;
}

void CSelectInstDlg::FillRevisionTree(HTREEITEM item, aplExtent& rev_ext)
{
	if(!item) return;
	CItemData* itemData= (CItemData*)m_tree.GetItemData(item);
	if(itemData==NULL) return;
	
	CaplInstance* inst= NULL;

	for(int i= 0; i<rev_ext.GetSize(); i++)
	{
		if(rev_ext[i]==0){rev_ext.Remove(i); i--; continue;}
		if(rev_ext[i]->GetAccessmode()==aplNO){rev_ext.Remove(i); i--; continue;}
		
		apidata.GetAttr(rev_ext[i], m_ItemVertionInfo._VerBaseAttr, inst);
		if(inst==itemData->inst)
		{
			FillRevisionTree(InsertRevisionInTree(itemData->item, rev_ext[i]), rev_ext);
			rev_ext.Remove(i);
			i--;
		}
	}
	
	TVSORTCB tvs;
	tvs.hParent= item;
	tvs.lpfnCompare= CompareHtreeItem;
	tvs.lParam= (LPARAM) &m_tree;
	m_tree.SortChildrenCB(&tvs);
	
	InitExpand(item);
}

void CSelectInstDlg::FillPersonOrgTree(HTREEITEM item)
{
	aplExtent Relationship, Persons, AlongPersons, RootItems, AlongOfficial;
	CArray<HTREEITEM, HTREEITEM> 
		ahRootItems, //
		ahOtherItems;
	CaplInstance* pInst, *pInst1;
	CaplAggr aggr0;
	CString sStr, buf;
	int i, j, n;
		
	apidata.GetEntityExtent(m_api->m_appr_mgr.e_org_rel, Relationship);
	apidata.GetEntityExtent(m_api->m_appr_mgr.e_pers_org, Persons);
	apidata.GetEntityExtent(m_api->m_appr_mgr.e_person, AlongPersons);
	apidata.GetEntityExtent(m_api->m_appr_mgr.e_official, AlongOfficial);
	
	//Определение корневых элементов.
	apidata.GetEntityExtent(m_api->m_appr_mgr.e_org, RootItems);
	for(i= 0; i<RootItems.GetSize(); i++)
	{
		for(j= 0; j<Relationship.GetSize(); j++)
		{
			apidata.GetAttr(Relationship[j], m_api->m_appr_mgr.a_org_rel_related, pInst);
			if(RootItems[i]==pInst)
			{
				RootItems.Remove(i);
				i--;
				break;
			}
		}
	}
	for(i= 0; i<AlongPersons.GetSize(); i++)
	{
		for(j= 0; j<Persons.GetSize(); j++)
		{
			apidata.GetAttr(Persons[j], m_api->m_appr_mgr.a_po_the_pers, pInst);
			if(AlongPersons[i]==pInst)
			{
				AlongPersons.Remove(i);
				i--;
				break;
			}
			else if(AlongOfficial[i]==pInst)
			{
				AlongOfficial.Remove(i);
				i--;
				break;
			}
		}
	}

//	RootItems.Append(AlongPersons);
//	RootItems.Append(AlongOfficial);
	
	//Построение корневых элементов
	for (i= 0; i<RootItems.GetSize(); i++)
	{	
		if(RootItems[i]->GetAccessmode()==aplNO){continue;}
		
		HTREEITEM hItem, hPerItem;
		int nImage;

		if (RootItems[i]->GetType()->name==_T("organization"))
		{
			nImage= APL_ICON_ORGANIZATION;
			apidata.GetAttr(RootItems[i], m_api->m_appr_mgr.a_org_name, sStr);
			if(!sStr.CompareNoCase( APL_NO_T("Удаленные"))) continue;
		}
		else if(RootItems[i]->GetType()->name==_T("person"))
		{
			nImage= APL_ICON_PERSON;
			m_api->m_appr_mgr.GetPersonName(RootItems[i], sStr);
		}
		else if(apidata.IsKindOf(RootItems[i], m_api->m_appr_mgr.e_official))
		{
			if((m_mode&APL_MODE_SELECT_OFFICIAL)==0) continue;
			nImage= APL_ICON_OFFICIAL;
			m_api->m_appr_mgr.GetPersonName(RootItems[i],sStr);
		}
		else
			continue;

		nImage = m_api->GetInstIco(RootItems[i]);
		
		hItem= m_tree.InsertItem(sStr, nImage, nImage, item);
		ahRootItems.Add(hItem);
		CItemData *dta= new CItemData(RootItems[i], hItem, NULL);
		m_tree.SetItemData(hItem, (DWORD)dta);

		for(j=0; j<Persons.GetSize(); j++)
		{
			if(Persons[j]->GetAccessmode()==aplNO){continue;}
			
			apidata.GetAttr(Persons[j], m_api->m_appr_mgr.a_po_the_org, pInst);
			if(RootItems[i]==pInst)
			{
				CString sEndDate;
				apidata.GetAttr(Persons[j], m_api->m_appr_mgr.a_po_end_date, sEndDate);
				if(!sEndDate.IsEmpty()) continue;//сотрудника удалили

				CaplInstance* pInst1= NULL;

				apidata.GetAttr(Persons[j], m_api->m_appr_mgr.a_po_the_pers, pInst1);
				
				if(apidata.IsKindOf(pInst1, m_api->m_appr_mgr.e_person))
				{
					nImage=APL_ICON_PERSON;
				}
				else if(apidata.IsKindOf(pInst1, m_api->m_appr_mgr.e_official))
				{
					if((m_mode&APL_MODE_SELECT_OFFICIAL)==0) continue;
				}
				else continue;

				nImage = m_api->GetInstIco(pInst1);
				
				m_api->m_appr_mgr.GetPersonName(pInst1, sStr);				
				hPerItem= m_tree.InsertItem(sStr, nImage, nImage, hItem);
				CItemData *dta= new CItemData(Persons[j], hPerItem, NULL);
				m_tree.SetItemData(hPerItem, (DWORD)dta);

				Persons.Remove(j);
				j--;
			}
		}
	}//for (i= 0; i<RootItems.GetSize(); i++)

//	m_tree.Expand(item, TVE_EXPAND);

	//Построение всех остальных элементов
	while(ahRootItems.GetSize())
	{
		for(i= 0; i<ahRootItems.GetSize(); i++)
		{
			CItemData* pInstRoot = (CItemData*)m_tree.GetItemData(ahRootItems[i]);
			
			for(j= 0; j<Relationship.GetSize(); j++)
			{
				apidata.GetAttr(Relationship[j], m_api->m_appr_mgr.a_org_rel_relating, pInst);
				if (pInstRoot->inst == pInst)
				{
					apidata.GetAttr(Relationship[j], m_api->m_appr_mgr.a_org_rel_related, pInst);
					if(!pInst)continue;if(!pInst->GetType())continue;
					if(pInst->GetAccessmode()==aplNO) continue;
					
					HTREEITEM hItem, hPerItem;
					int nImage;

					if (pInst->GetType()->name==_T("organization"))
					{
						nImage= APL_ICON_ORGANIZATION;
					}
					else
					{
						nImage= APL_ICON_PERSON;
					}
					
					nImage = m_api->GetInstIco(pInst);
					apidata.GetAttr(pInst, m_api->m_appr_mgr.a_org_name, sStr);
					hItem= m_tree.InsertItem(sStr, nImage, nImage, ahRootItems[i]);					
					CItemData *dta= new CItemData(pInst, hItem, NULL);
					m_tree.SetItemData(hItem, (DWORD)dta);
					
					ahOtherItems.Add(hItem);
					
					for(n=0; n<Persons.GetSize(); n++)
					{
						if(Persons[n]->GetAccessmode()==aplNO) continue;
						
						apidata.GetAttr(Persons[n], m_api->m_appr_mgr.a_po_the_org, pInst1);
						if(pInst==pInst1)
						{
							CString sEndDate;
							apidata.GetAttr(Persons[n], m_api->m_appr_mgr.a_po_end_date, sEndDate);
							if(!sEndDate.IsEmpty()) continue;//сотрудника удалили

							CaplInstance* pInst2= NULL;

							apidata.GetAttr(Persons[n], m_api->m_appr_mgr.a_po_the_pers, pInst2);
							if(apidata.IsKindOf(pInst2, m_api->m_appr_mgr.e_person))
							{
								nImage=APL_ICON_PERSON;
							}
							else if(apidata.IsKindOf(pInst2, m_api->m_appr_mgr.e_official))
							{
								if((m_mode&APL_MODE_SELECT_OFFICIAL)==0) continue;
								nImage= APL_ICON_OFFICIAL;
							}
							else continue;
							
							m_api->m_appr_mgr.GetPersonName(pInst2, sStr);
							
							nImage = m_api->GetInstIco(pInst2);
							hPerItem= m_tree.InsertItem(sStr, nImage, nImage, hItem);
							CItemData *dta= new CItemData(Persons[n], hPerItem, NULL);
							m_tree.SetItemData(hPerItem, (DWORD)dta);
							
							Persons.Remove(n);
							n--;
						}
					}
				}
			}
			
//			m_tree.Expand(ahRootItems[i], TVE_EXPAND);
		}
		
		//перестраиваем элементы Все рабочие группы
		ahRootItems.RemoveAll();
		for (i = 0; i < ahOtherItems.GetSize(); i++)
		{
			ahRootItems.Add(ahOtherItems[i]);
		}		
		ahOtherItems.RemoveAll();
	}
	
//	m_tree.Expand(item, TVE_EXPAND);

	TVSORTCB sortcb;
	sortcb.lpfnCompare= CompareHtreeItem;
	sortcb.lParam= (LPARAM)&m_tree;
	sortcb.hParent= item;
	m_tree.SortChildrenCB(&sortcb);
}

//******************************************************************************
void CSelectInstDlg::OnSelchangedObjTree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	// TODO: Add your control notification handler code here
	m_create_folder_btn.EnableWindow(FALSE);
	*pResult = 0;
	if(m_sel_inst!=0) return;
	m_cur_inst=0;m_sel_doc= 0;
	m_ok_btn.EnableWindow(FALSE);
	m_create_folder_btn.EnableWindow(FALSE);
	m_viewDocBtn.EnableWindow(FALSE);
	
	m_showVerBtn.EnableWindow(FALSE);
	m_showCharBtn.EnableWindow(FALSE);
	m_showDocsBtn.EnableWindow(FALSE);
	m_showActsBtn.EnableWindow(FALSE);
	m_inst_show_btn.EnableWindow(FALSE);

	if(pNMTreeView==0) return;
	HTREEITEM item=pNMTreeView->itemNew.hItem;
	if(item==0) return;
	if(item==m_folders_item) m_create_folder_btn.EnableWindow(TRUE);
	if(item==m_pers_folders_item) m_create_folder_btn.EnableWindow(TRUE);
	CItemData *dta=(CItemData*)m_tree.GetItemData(item);
	if(dta==0) return;
	if(dta->inst==0) return;
	
	bool enable=false;
	bool bIsPersonSelected= false;
	if(apidata.IsKindOf(dta->inst,m_api->m_folder_mgr.e_folder))
	{
		if((m_mode&APL_MODE_SELECT_FOLDER)>0)enable=true;
		m_create_folder_btn.EnableWindow(TRUE);		
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_categ_mgr.e_categ))
	{
		if((m_mode&APL_MODE_SELECT_CATEGORY)>0)enable=true;
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_prd_mgr.e_prd))
	{
		if((m_mode&APL_MODE_SELECT_PRD)>0)enable=true;
		m_showCharBtn.EnableWindow();
		m_showDocsBtn.EnableWindow();
		m_showActsBtn.EnableWindow();
		m_showVerBtn.EnableWindow();
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_prd_mgr.e_pdf))
	{
		if((m_mode&APL_MODE_SELECT_PDF)>0)enable=true;
		m_showCharBtn.EnableWindow();
		m_showDocsBtn.EnableWindow();
		m_showActsBtn.EnableWindow();
		m_showVerBtn.EnableWindow();
		m_inst_show_btn.EnableWindow();
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_doc_mgr.e_doc))
	{
		if((m_mode&APL_MODE_SELECT_DOC)>0)enable=true;
		m_showVerBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
		m_viewDocBtn.EnableWindow();
		m_sel_doc= dta->inst;
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_charact_mgr.e_apl_charact_value))
	{
		m_showVerBtn.EnableWindow();		
		m_sel_doc= dta->inst;
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_charact_mgr.e_apl_charact_value_ver))
	{
		if((m_mode&APL_MODE_SELECT_DOC_REVISION)>0)enable=true;
		m_sel_doc= dta->inst;
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_bp_mgr.e_bp))
	{
		if((m_mode&APL_MODE_SELECT_BP)>0)enable=true;
		m_showVerBtn.EnableWindow();
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
		m_inst_show_btn.EnableWindow();
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_bp_mgr.e_bp_res))
	{
		if((m_mode&APL_MODE_SELECT_BP_RES)>0)enable=true;
		m_showVerBtn.EnableWindow();
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
		m_inst_show_btn.EnableWindow();
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_bp_mgr.e_apl_bp_inst))
	{
		if((m_mode&APL_MODE_SELECT_BPINST)>0)enable=true;
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();		
	}
	else if(apidata.IsKindOf(dta->inst,m_api->m_bp_mgr.e_apl_bp_ver))
	{
		if((m_mode&APL_MODE_SELECT_BP_REVISION)>0)enable=true;
		m_showActsBtn.EnableWindow();
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
	}
	else if(apidata.IsKindOf(dta->inst, m_api->m_doc_mgr.e_apl_doc_rev))
	{
		if((m_mode&APL_MODE_SELECT_DOC_REVISION)>0)enable=true;		
		m_showDocsBtn.EnableWindow();
		m_viewDocBtn.EnableWindow();
		m_sel_doc= dta->inst;
	}
	else if(apidata.IsKindOf(dta->inst, m_api->m_prd_inst_mgr.e_lot))
	{
		if((m_mode&APL_MODE_SELECT_LOT)>0)enable= true;
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
	}
	else if(apidata.IsKindOf(dta->inst, m_api->m_prd_inst_mgr.e_prd_inst))
	{
		if((m_mode&APL_MODE_SELECT_PRDINST)>0)enable= true;
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
	}
	else if(apidata.IsKindOf(dta->inst, m_api->m_appr_mgr.e_org))
	{
		if((m_mode&APL_MODE_SELECT_ORG)>0)enable= true;
	}
	else if(apidata.IsKindOf(dta->inst, m_api->m_appr_mgr.e_official))
	{
		if((m_mode&APL_MODE_SELECT_OFFICIAL)>0) enable= true;		
	}
	else if(apidata.IsKindOf(dta->inst, m_api->m_appr_mgr.e_pers_org))
	{
		if((m_mode&APL_MODE_SELECT_PERSORG)>0) enable= true;
		else if((m_mode&APL_MODE_SELECT_PERSON)>0){ enable= true;bIsPersonSelected= true;}
	}
	else if(m_api->m_data.IsKindOf(dta->inst, m_api->m_change_mgr.e_chng))
	{
		if((m_mode&APL_MODE_SELECT_CHANGE)>0) enable= true;
		m_showDocsBtn.EnableWindow();
	}
	else if(m_api->m_data.IsKindOf(dta->inst, m_api->m_project_mgr->e_project))
	{
		if((m_mode&APL_MODE_SELECT_PROJECT)>0) enable= true;		
		m_showDocsBtn.EnableWindow();
	}
	else if(m_api->m_data.IsKindOf(dta->inst, m_api->m_classifier_mgr.e_apl_classifier_system))
	{
		if((m_mode&APL_MODE_SELECT_CLASSIF_SYSTEM)>0) enable= true;		
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
	}
	else if(m_api->m_data.IsKindOf(dta->inst, m_api->m_classifier_mgr.e_apl_classifier_level))
	{
		if((m_mode&APL_MODE_SELECT_CLASSIF_ELEMENT)>0) enable= true;		
		m_showDocsBtn.EnableWindow();
		m_showCharBtn.EnableWindow();
	}
	else if(m_api->m_data.IsKindOf(dta->inst, m_api->m_req_mgr.e_requirement))
	{
		if((m_mode&APL_MODE_SELECT_REQUIREMENT)>0) enable= true;
	}

	if(enable)
	{
		if(bIsPersonSelected) apidata.GetAttr(dta->inst, m_api->m_appr_mgr.a_po_the_pers, m_cur_inst);
		else m_cur_inst=dta->inst;

		m_ok_btn.EnableWindow(TRUE);
	}
}
//******************************************************************************

void CSelectInstDlg::OnOK() 
{
	m_sel_inst=m_cur_inst;
	CResizableDialog::OnOK();
}

void CSelectInstDlg::OnCreateFolder() 
{
	HTREEITEM hItem=m_tree.GetSelectedItem();
	if(hItem==0) return;
	
	CaplInstance *base_folder=0;

	//if(item==m_folders_item) m_create_folder_btn.EnableWindow(TRUE);
	CItemData *dta=(CItemData*)m_tree.GetItemData(hItem);
	if(dta!=0)
	{
		if(dta->inst!=0){
			if(apidata.IsKindOf(dta->inst,m_api->m_folder_mgr.e_folder)) base_folder=dta->inst;
		}
	}
	if(hItem==m_pers_folders_item )base_folder=apidata.GetCurrUser();
	CaplInstance *new_folder=m_api->m_folder_mgr.CreateFolder(base_folder,0,0);
	if(new_folder!=0)
	{
		if(dta->fictive==0)
		{
			if(m_tree.ItemHasChildren(hItem))
			{
				// Просто добавление
				CString buf;
				apidata.GetAttr(new_folder,m_api->m_folder_mgr.a_folder_name,buf);
				HTREEITEM item=m_tree.InsertItem(buf,APL_ICON_FOLDER,APL_ICON_FOLDER,dta->item);
				CItemData *dta1=new CItemData(new_folder,item,0);//InsertFictiveItem(&m_tree,item));
				m_tree.SetItemData(item,(DWORD)dta1);
			}
			else
			{
				dta->fictive=InsertFictiveItem(&m_tree,hItem);
				m_tree.Expand(hItem,TVE_EXPAND);
			}
		}
		else m_tree.Expand(hItem,TVE_EXPAND);
	}
}

void CSelectInstDlg::OnShowPrds() 
{
	
}

void CSelectInstDlg::OnShowChrs() 
{
	HTREEITEM hItem=m_tree.GetSelectedItem();
	if(hItem==0) return;
	CItemData *dta=(CItemData*)m_tree.GetItemData(hItem);
	CaplInstance* inst= NULL;
	aplExtent ext1, ext2;

	m_api->m_charact_mgr.FindAssociatedCharacteristic(dta->inst, ext1, ext2, false);
	for(int i= 0; i<ext1.GetSize(); i++)
	{
		if(-1==dta->ext.Find(ext1[i]))
		{
			InsertCharInTree(dta->item, ext1[i]);
			dta->ext.Add(ext1[i]);
		}
	}

//	UINT st= m_tree.GetItemState(dta->item, TVIS_EXPANDED);
//	if((st&TVIS_EXPANDED)<=0)
//	{
//		m_tree.SetItemState(dta->item, TVIS_EXPANDED, TVIS_EXPANDEDONCE|TVIS_EXPANDED);
//		InitExpand(dta->item);
//	}
	InitExpand(dta->item);
}

void CSelectInstDlg::OnShowDocs() 
{
	HTREEITEM hItem=m_tree.GetSelectedItem();
	if(hItem==0) return;
	CItemData *dta=(CItemData*)m_tree.GetItemData(hItem);
	aplExtent ext, ext1;

	m_api->m_doc_mgr.FindAssociatedDocuments(dta->inst, ext, ext1);
	for(int i=0; i<ext.GetSize(); i++)
	{
		if(-1==dta->ext.Find(ext[i]))
		{
			InsertDocInTree(dta->item, ext[i]);
			dta->ext.Add(ext[i]);
		}
	}
	//сброс флага TVIS_EXPANDEDONCE, чтобы отработал TVN_ITEMEXPANDING
//	UINT st= m_tree.GetItemState(dta->item, TVIS_EXPANDED);
//	if((st&TVIS_EXPANDED)<=0)
//	{
//		m_tree.SetItemState(dta->item, TVIS_EXPANDED, TVIS_EXPANDEDONCE|TVIS_EXPANDED);
//		InitExpand(dta->item);
//	}
	InitExpand(dta->item);
}

void CSelectInstDlg::OnShowVers() 
{
	HTREEITEM hItem=m_tree.GetSelectedItem();
	if(hItem==0) return;
	CItemData *dta=(CItemData*)m_tree.GetItemData(hItem);
	aplExtent ext, ext1;
	CaplInstance* inst;
	
	if(apidata.IsKindOf(dta->inst, m_api->m_prd_mgr.e_pdf))
	{
		apidata.GetAttr(dta->inst, m_api->m_prd_mgr.a_pdf_prd, inst);
		m_api->m_prd_mgr.GetAllProductVersion(inst, ext);
		if(1==ext.GetSize())
		{
			MessageBox( APL_T("Эта версия единственная."),  APL_T("Версии изделия"), MB_OK|MB_ICONINFORMATION);
		}
		else
		{
			for(int i= 0; i<ext.GetSize(); i++)
			{
				if(-1==dta->ext.Find(ext[i]))
				{
					InsertPdfInTree(dta->item, ext[i]);
					dta->ext.Add(ext[i]);
				}
			}
		}
	}
	else if(apidata.IsKindOf(dta->inst, m_api->m_doc_mgr.e_doc))
	{
		m_NoExpand= true;
		SetObjVertionInfo(aplDoc, APL_ICON_DOC_REVISION, 
			m_api->m_doc_mgr.a_apl_doc_rev_id,
			m_api->m_doc_mgr.a_apl_doc_rev_base,
			m_api->m_doc_mgr.a_apl_doc_rev_doc,
			m_api->m_doc_mgr.a_apl_doc_active);
		
		m_api->m_doc_mgr.LoadAllDocumentRevision(dta->inst, ext1);
		
		for(int i= 0; i<ext1.GetSize(); i++)
		{
			if(ext1[i]==0){ext1.Remove(i); i--; continue;}
			apidata.GetAttr(ext1[i], m_api->m_doc_mgr.a_apl_doc_rev_base, inst);
			if(inst==0)
			{
				if(-1==dta->ext.Find(ext1[i]))
				{
					dta->ext.Add(ext1[i]);
					FillRevisionTree(InsertRevisionInTree(dta->item, ext1[i]), ext1);
				}
			}
		}
		
		ClearObjVertionInfo();
		m_NoExpand= false;
	}
	else if(apidata.IsKindOf(dta->inst, m_api->m_bp_mgr.e_bp))
	{
		m_NoExpand= true;

		int ico= APL_ICON_BP_VERTION;
		aplExtent subBP;
		apidata.GetAttr(dta->inst, m_api->m_bp_mgr.a_bp_elements, subBP);
		if(subBP.GetSize()) ico+=2;

		SetObjVertionInfo(aplBP, ico, 
			m_api->m_bp_mgr.a_bp_ver_num,
			m_api->m_bp_mgr.a_bp_ver_base,
			m_api->m_bp_mgr.a_bp_ver_bp,
			m_api->m_bp_mgr.a_bp_act);
		
		m_api->m_bp_mgr.GetAllBPVersion(dta->inst, ext1);
		
		for(int i= 0; i<ext1.GetSize(); i++)
		{
			if(ext1[i]==0){ext1.Remove(i); i--; continue;}
			apidata.GetAttr(ext1[i], m_api->m_bp_mgr.a_bp_ver_base, inst);
			if(inst==0)
			{
				if(-1==dta->ext.Find(ext1[i]))
				{
					dta->ext.Add(ext1[i]);
					FillRevisionTree(InsertRevisionInTree(dta->item, ext1[i]), ext1);
				}
			}
		}
		ClearObjVertionInfo();			
		m_NoExpand= false;
	}
#ifdef _DEBUG	
	else if(apidata.IsKindOf(dta->inst, m_api->m_charact_mgr.e_apl_charact_value))
	{
		m_NoExpand= true;

		int ico= APL_ICON_BP_VERTION;

		SetObjVertionInfo(aplCharact, APL_ICON_DOC_REVISION, 
			m_api->m_charact_mgr.a_apl_charact_val_ver_version_num,
			m_api->m_charact_mgr.a_apl_charact_val_ver_base,
			m_api->m_charact_mgr.a_apl_charact_val_ver_char_value,
			m_api->m_charact_mgr.a_apl_charact_val_act_ver);
		
		m_api->m_charact_mgr.GetAllCharactVersion(dta->inst, ext1);
		
		for(int i= 0; i<ext1.GetSize(); i++)
		{
			if(ext1[i]==0){ext1.Remove(i); i--; continue;}
			apidata.GetAttr(ext1[i], m_api->m_charact_mgr.a_apl_charact_val_ver_base, inst);
			if(inst==0)
			{
				if(-1==dta->ext.Find(ext1[i]))
				{
					dta->ext.Add(ext1[i]);
					FillRevisionTree(InsertRevisionInTree(dta->item, ext1[i]), ext1);
				}
			}
		}
		ClearObjVertionInfo();			
		m_NoExpand= false;		
	}
#endif
//	UINT st= m_tree.GetItemState(dta->item, TVIS_EXPANDED);
//	if((st&TVIS_EXPANDED)<=0)
//	{
//		m_tree.SetItemState(dta->item, TVIS_EXPANDED, TVIS_EXPANDEDONCE|TVIS_EXPANDED);
//		InitExpand(dta->item);
//	}
	InitExpand(dta->item);
	m_tree.Select(hItem,TVGN_FIRSTVISIBLE);
}

void CSelectInstDlg::OnShowActs() 
{
	HTREEITEM hItem=m_tree.GetSelectedItem();
	if(hItem==0) return;
	CItemData *dta=(CItemData*)m_tree.GetItemData(hItem);
	aplExtent ext, ext1;
	
	if(m_api->m_data.IsKindOf(dta->inst, m_api->m_bp_mgr.e_bp) || m_api->m_data.IsKindOf(dta->inst, m_api->m_bp_mgr.e_apl_bp_ver))
		m_api->m_data.GetAttrBN(dta->inst, _T("elements"), ext);
	else
		m_api->m_bp_mgr.FindAssociatedBP(dta->inst, ext, ext1);

	for(int i= 0; i<ext.GetSize(); i++)
	{
		if(-1==dta->ext.Find(ext[i]))
		{
			dta->ext.Add(ext[i]);
			InsertActionInTree(dta->item, ext[i]);
		}
	}

//	UINT st= m_tree.GetItemState(dta->item, TVIS_EXPANDED);
//	if((st&TVIS_EXPANDED)<=0)
//	{
//		m_tree.SetItemState(dta->item, TVIS_EXPANDED, TVIS_EXPANDEDONCE|TVIS_EXPANDED);
//		InitExpand(dta->item);
//	}
	InitExpand(dta->item);
}

void CSelectInstDlg::OnFindButton() 
{
	if(!m_api || !apidata.IsConnected()) return;


	//сброс флага TVIS_EXPANDEDONCE, чтобы отработал TVN_ITEMEXPANDING
	HTREEITEM item=Find(0);
	
	UINT st= m_tree.GetItemState(m_query_item, TVIS_EXPANDED);
	if((st&TVIS_EXPANDED)<=0)
	{
		m_tree.SetItemState(m_query_item, TVIS_EXPANDED, TVIS_EXPANDEDONCE|TVIS_EXPANDED);
		InitExpand(m_query_item);
	}
	
	HTREEITEM selItem= m_tree.GetSelectedItem();
	if(selItem) 
	{
		m_tree.SetItemState(selItem, m_tree.GetItemState(selItem, TVIS_SELECTED)^TVIS_SELECTED, 
			m_tree.GetItemState(selItem, TVIS_SELECTED));
	}
	
	m_tree.SelectItem(item);
	m_tree.SetActiveWindow();
	m_tree.RedrawWindow();
}

HTREEITEM CSelectInstDlg::Find(CaplInstance* inst_prev,HTREEITEM item) 
{
	int query_count=0;
	CString name;
	if(!m_query_item)
	{
		return 0;
	}
	if(inst_prev==0){
		do{
			query_count++;
			name.Format( APL_T("Запрос из диалога выбора %i:"),query_count);
			if(!m_api->m_query_mgr.TestNameQuery(name,0,false)){
				query_count++;
				continue;
			}
			break;
		}while(true);
	}else{
		m_api->GetItemName(inst_prev,name);
	}

	CaplInstance* inst=m_api->m_query_mgr.PrepareQuery(inst_prev,name,
			false,false,false,true,_T("Query"));
	if(inst==0){
		return 0;
	}
	if(item==0){
		item=InsertQueryInstInTree(m_query_item,inst);
	}

	m_query_ext.Clear();
	int res= m_api->m_query_mgr.ExecuteQuery(inst,m_query_ext);
	if(!m_query_ext.GetSize()) 
	{
		MessageBox( APL_T("Ничего не найдено."),  APL_T("Результат запроса"), MB_ICONINFORMATION|MB_OK);
		return item;
	}
	// Проверка на большие размеры
	CString buf;
	buf.Format( APL_T(": найдено %i; данные не загружены"),m_query_ext.Size);
	m_tree.SetItemText(item,name+buf);
	if(m_query_ext.Size>1000){
		buf.Format( APL_T("Количество найденных объектов (%i) очень велико.\nЗагрузка атрибутов из БД может занять значительное время.\nЗагрузить атрибуты?"),
			m_query_ext.Size);
		if(IDYES!=AfxMessageBox(buf,MB_YESNO|MB_ICONQUESTION)){
			m_query_ext.Clear();
			return item;
		}
	}

	m_api->m_query_mgr.LoadExtentInfo(m_query_ext);

	buf.Format( APL_T(": найдено %i"),m_query_ext.Size);
	m_tree.SetItemText(item,name+buf);
	
	buf.Format( APL_T("Найдено %i объектов."), m_query_ext.GetSize());
	MessageBox(buf,  APL_T("Результат запроса"), MB_ICONQUESTION|MB_OK/*MB_YESNO*/);

	return item;
}


void CSelectInstDlg::OnViewDocument() 
{
	if(m_sel_doc)
		m_api->m_doc_mgr.View(m_sel_doc);
}

void CSelectInstDlg::OnShowInsts() 
{
	HTREEITEM hItem=m_tree.GetSelectedItem();
	if(hItem==0) return;
	CItemData *dta=(CItemData*)m_tree.GetItemData(hItem);
	if(m_api->m_data.IsKindOf(dta->inst,m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
	{
		aplExtent ext;
		m_api->m_prd_inst_mgr.FindAllPdfInstances(dta->inst,ext);
		for(int i=0; i<ext.Size;i++)
		{
			if(dta->ext.Find(ext[i])<0)
				InsertProdInstInTree(hItem,ext[i]);
			dta->ext.Add(ext[i]);
		}
	}
	else if(m_api->m_data.IsKindOf(dta->inst,m_api->m_bp_mgr.e_bp))//Экземпляры бизнес процесса
	{
		CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
		int i=ld.AddQuery(_T('b'), dta->inst->GetId(), m_api->m_bp_mgr.e_apl_bp_inst,m_api->m_bp_mgr.a_bp_inst_process, true);
			  ld.AddQuery(_T('d'), i, 0,m_api->m_bp_mgr.a_bp_inst_process, true);
		ld.LoadEx();
		aplExtent out_ext,ext;
		m_api->m_data.GetEntityExtent(m_api->m_bp_mgr.e_apl_bp_inst,out_ext);
		CaplInstance *inst=0;
		for(i=0;i<out_ext.Size;i++)
		{
			if(!out_ext[i]) if(out_ext[i]->GetAccessmode()>aplRO) continue;
			m_api->m_data.GetAttr(out_ext[i],m_api->m_bp_mgr.a_bp_inst_process,inst);
			if(inst==dta->inst) 
				ext.Add(out_ext[i]);
		}
		m_api->m_bp_mgr.LoadBPInstInfo(ext);
		for(i=0; i<ext.Size;i++)
		{
			if(dta->ext.Find(ext[i])<0)
				InsertProdInstInTree(hItem,ext[i]);
			dta->ext.Add(ext[i]);
		}
	}
	if(dta->fictive!=0) {m_tree.DeleteItem(dta->fictive); dta->fictive=0;}
	m_tree.Expand(hItem,TVE_EXPAND);
}

