// SelectInstanceView.cpp : implementation file
//

#include "stdafx.h"
#include "SelectInstanceView.h"
#include "SetupShowonExpand.h"

#include "SelectInstanceDlgEx.h"

#include "icons_defines.h"
#include "resource.h"

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

/************************************************************************/
/*                                                                      */
/************************************************************************/

bool CSelectInstanceTreeItem::m_bFilterSubProduct= false;

CSelectInstanceTreeItem::CSelectInstanceTreeItem(CaplAPI* api, CTreeCtrl* tree, aplTIArray* items, CaplInstance* inst, CaplInstance* rel, CString sName)
	:CaplBaseTreeItem(api, tree, items, inst, rel)
{
	m_sName= sName;	
	m_expanded= false;
	m_bExpanding= false;

	m_bShowWorkObjectsInProcess = false;

	m_ico=			-1;
	m_iRelIco=		-1;
	m_iEffIco=		-1;
	m_iStateIco=	-1;
	m_bShowRelated=true;
}

CSelectInstanceTreeItem::~CSelectInstanceTreeItem()
{
	
}

bool CSelectInstanceTreeItem::CreateTreeItem(HTREEITEM parent_item)
{
	CString sItemName;
	CString sPosition;
	CString sStr, buf, sDate;
	CString sState;
	CString sAmount;
	CaplInstance* unit, *cit = NULL;
	double rValue;
	int iPrior;
	int ico;
	COleDateTime time;

	if(m_inst)
	{
		if(m_api->m_data.IsKindOf(m_inst, m_api->m_charact_mgr.e_charact_val_group))
		{
			CaplInstance* def= NULL;
			m_api->m_data.GetAttr(m_inst, m_api->m_charact_mgr.a_charact_val_group_def, def);
			if(def)	m_api->m_data.GetAttrBN(def, _T("name"), m_sName);
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_appr_mgr.e_apl_appr))
		{
			CaplInstance* inst;
			CString buf;

			if(m_api->m_show.m_appr_status)
			{
				m_api->m_data.GetAttrBN(m_inst,_T("status"),inst);
				if(inst!=0) m_api->m_data.GetAttrBN(inst, _T("name"), m_sName);
			}

			if(m_api->m_show.m_appr_pers_role)
			{
				if(m_sName.GetLength()>0) m_sName+=_T(" ");
				m_api->m_data.GetAttrBN(m_inst,_T("role"),buf);
				m_sName+=buf;
			}
			if(m_api->m_show.m_appr_pers)
			{
				if(m_sName.GetLength()>0) m_sName+=_T(" ");
				m_api->m_data.GetAttrBN(m_inst,_T("person_organization"),inst);
				m_api->m_appr_mgr.GetPersonName(inst, buf);
				m_sName+=buf;
			}			
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_bp_mgr.e_bp_res))
		{
			CString buf=_T("");
			if(m_api->m_show.m_showbpres_id)
			{
				m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_id,buf);
				if(buf==_T("")) buf=_T("?");
				m_sName = buf;
			}
			if(m_api->m_show.m_showbpres_type)
			{
				CaplInstance *inst;
				m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_type,inst);
				if(inst!=0) m_api->m_data.GetAttr(inst,m_api->m_bp_mgr.a_bp_res_type_name,buf);
				if(buf==_T("")) buf=_T("?");
				if(m_sName>_T("")) m_sName+=_T(" : ")+buf;
				else m_sName = buf;
			}
			if(m_api->m_show.m_showbpres_object)
			{
				CaplInstance *inst;
				m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_object,inst);
				if(inst!=0) m_api->m_bp_mgr.GetItemName(inst,buf);
				if(buf==_T("")) buf=_T("?");
				if(m_sName>_T("")) m_sName+=_T(" : ")+buf;
				else m_sName = buf;
			}
			if(m_api->m_show.m_showbpres_amount)
			{
				buf=_T("");
				CaplInstance *inst;
				double v;
				CString buf1;
				m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_val,v);
				if(v!=0)
				{
					m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_unit,inst);
					m_api->m_charact_mgr.GetUnitName(inst,buf1);
					buf.Format(_T(" : %g %s"),v,LPCTSTR(buf1));
				}
				if(buf==_T("")) buf=_T("?");
				if(m_sName>_T("")) m_sName+=_T(" : ")+buf;
				else m_sName = buf;
			}			
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_pdf))
		{
			if(!m_rel)
			{
				m_api->GetItemName(m_inst, m_sName);
			}
			else
			{
				if(m_api->m_data.IsKindOf(m_rel, m_api->m_prd_mgr.e_qacu_nauo))
				{
					m_api->GetItemName(m_inst, sStr);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_pdr_id, sPosition);

					while(sPosition.GetLength()<3)
						sPosition=_T(" ")+sPosition;

					sPosition= _T("(")+sPosition+_T(") ");

					m_sName+=sPosition;
					m_sName+=sStr;

					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_apl_qacu_value, rValue);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_apl_qacu_unit, unit);
					m_api->m_charact_mgr.GetUnitName(unit, buf);
//					if(unit) m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, buf);

					sStr.Format(_T(" [%g %s]"), rValue, buf);
					m_sName+=sStr;
				}				
				else if(m_api->m_data.IsKindOf(m_rel, m_api->m_prd_mgr.e_make_from))
				{
					m_api->GetItemName(m_inst, sStr);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_pdr_id, sPosition);

					while(sPosition.GetLength()<3)
						sPosition=_T(" ")+sPosition;

					sPosition= _T("(")+sPosition+_T(") ");

					m_sName+=sPosition;
					m_sName+=sStr;
					
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_ranking, iPrior);
					sStr.Format(_T(" {%i}"), iPrior);
					m_sName+=sStr;

					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_value, rValue);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_unit, unit);
					m_api->m_charact_mgr.GetUnitName(unit, buf);
//					if(unit) m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, buf);

					sStr.Format(_T(" [%g %s]->"), rValue, buf);
					m_sName+=sStr;
					
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_derive_value, rValue);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_derive_unit, unit);
					m_api->m_charact_mgr.GetUnitName(unit, buf);
//					if(unit) m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, buf);

					sStr.Format(_T("[%g %s]"), rValue, buf);
					m_sName+=sStr;
				}
				else if(m_api->m_data.IsKindOf(m_rel, m_api->m_change_mgr.e_psc))
				{
					m_api->GetItemName(m_inst, sStr);
					m_api->m_data.GetAttr(m_rel, m_api->m_change_mgr.a_psc_position, sPosition);
					
					while(sPosition.GetLength()<3)
						sPosition=_T(" ")+sPosition;

					sPosition= _T("(")+sPosition+_T(") ");

					m_sName+=sPosition;
					m_sName+=sStr;

					m_api->m_data.GetAttr(m_rel, m_api->m_change_mgr.a_psc_value, rValue);
					m_api->m_data.GetAttr(m_rel, m_api->m_change_mgr.a_psc_unit, unit);
					m_api->m_charact_mgr.GetUnitName(unit, buf);
//					if(unit) m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, buf);

					sStr.Format(_T(" [%g %s]"), rValue, buf);
					m_sName+=sStr;
				}
				else m_api->GetItemName(m_inst, m_sName);
			}
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_change_mgr.e_avc))
		{
			// формируем имя элемента изменения документа
			m_api->LoadItemInfo(m_inst);
			m_api->m_data.GetAttr(m_inst, m_api->m_change_mgr.a_chng_item_accept_date, sDate);
			aplString2Date(sDate, time);
			sDate.Format(_T("%.2d.%.2d.%.4d"), time.GetDay(), time.GetMonth(), time.GetYear());

			m_api->m_data.GetAttr(m_inst, m_api->m_change_mgr.a_avc_doc, cit);
			if(cit)
			{
				m_api->LoadItemInfo(cit);
				m_api->GetItemName(cit, buf);
				sDate += _T(" : ") + buf;
			}

			m_api->m_data.GetAttr(m_inst, m_api->m_change_mgr.a_chng_item_id, buf);
			if(!buf.IsEmpty()) sDate = buf+_T(":")+sDate;
			
			m_sName = sDate;
		}
		/*else if(m_api->m_data.IsKindOf(m_inst, m_api->m_doc_mgr.e_doc_copy_order))
		{
			m_api->m_data.GetAttr(m_inst, m_api->m_doc_mgr.a_purchase_order_id, m_sName);
		}*/
		else if(m_api->m_data.IsKindOfBN(m_inst, _T("apl_task")))
		{
			m_sName= _T("task");
			
			if(-1==m_iStateIco)
			{
				m_api->m_data.GetAttrBN(m_inst, _T("state"), sState);
				m_iStateIco= 1;
				if(sState==_T("active") || sState==_T("work") || sState==_T("notify")) m_iStateIco++;
				else if(sState==_T("suspend"))  m_iStateIco+=2;
				else if(sState==_T("cancel"))   m_iStateIco+=3;
				else if(sState==_T("complete")) m_iStateIco+=4;	
			}
			if(-1==m_iEffIco)
			{
				CString prior;
				m_api->m_data.GetAttrBN(m_inst, _T("priority"), prior);
				if(prior==_T("low")) m_iEffIco= ICO_EFF_LOW;
				else if(prior==_T("hight")) m_iEffIco= ICO_EFF_HIGH;
				else m_iEffIco= ICO_EFF_NORMAL;
			}

			if(0==m_api->m_wf_mgr) m_api->GetItemName(m_inst, m_sName);
			else
			{
				m_sName=_T("");
				if(m_api->m_show.m_show_task_id)
				{
					m_api->m_data.GetAttrBN(m_inst, S::id, m_sName);
				}
				CString buf;
				if(m_api->m_show.m_show_task_name)
				{
					if(m_sName!=_T(""))
						m_sName+=_T(" : ");
					m_api->m_data.GetAttrBN(m_inst, S::name, buf);
					m_sName+=buf;
				}
				if(m_api->m_show.m_show_task_process_id || m_api->m_show.m_show_task_process_name)
				{
					m_sName+=_T(" [ ");
					CaplInstance *proc;
					CString buf1;
					m_api->m_data.GetAttrBN(m_inst, _T("of_process"), proc);
					if(0!=proc)
					{
						if(m_api->m_show.m_show_task_process_id )
							m_api->m_data.GetAttrBN(proc, S::id, buf);
						else buf=_T("");
						if(m_api->m_show.m_show_task_process_name )
							m_api->m_data.GetAttrBN(proc, S::name, buf1);
						else buf1=_T("");

						m_sName+=buf;
						if(buf1!=_T(""))
						{
							if(buf!=_T("")) m_sName+=_T(" : ");
							m_sName+=buf1;
						}
					}
					m_sName+=_T(" ]");
				}
			}
		}
		else m_api->GetItemName(m_inst, m_sName);

		ico = m_api->GetInstIco(m_inst);
		if(sState==_T("inactive")) ico+=3;
		else if(sState==_T("active"))	 ico+=1;
	}
	else
	{
		sItemName= m_sName;

		if(m_sName== APL_T("Категории")) ico= ICON_CATEGORIES;
		else if(m_sName== APL_T("Папки")) ico= ICON_FOLDERS;
		else if(m_sName== APL_T("Заказ-наряды и акты об уничтожении")) ico = ICON_FOLDERS;
		else if(m_sName== APL_T("Личные папки")) ico= ICON_PERS_FOLDER;
		else if(m_sName== APL_T("Справочники")) ico= ICON_CLASSIFIER_SYSTEM;
		else if(m_sName== APL_T("Организационная структура")) ico= ICON_ORGANIZATION;
		else if(m_sName== APL_T("Поиск в БД")) ico= ICON_QUERYES;
		else if(m_sName== APL_T("Мои задания")) ico= ICON_TASK-1;
	}

	InsetItem(m_sName, ico, parent_item);
	
	m_ico= ico;
	if(-1!=m_iRelIco)	SetItemImage(m_iRelIco,		IDX_IL_TREE_REL_TYPE,	true);
	if(-1!=m_iEffIco)	SetItemImage(m_iEffIco,		IDX_IL_TREE_EFF,		true);
	if(-1!=m_iStateIco)	SetItemImage(m_iStateIco,	IDX_IL_TREE_STATE,		true);
	
	SetItemImage(ico, IDX_IL_TREE_ITEM);
	
	m_fictive_item = m_tree->InsertItem(_T("fictive"), 0, 0, m_item);
	
	return true;	
}

bool CSelectInstanceTreeItem::MyExpand()
{
	UINT st= m_tree->GetItemState(m_item, TVIS_EXPANDED);
	if((st&TVIS_EXPANDED)<=0)
		m_tree->SetItemState(m_item, TVIS_EXPANDED, TVIS_EXPANDEDONCE|TVIS_EXPANDED);
	bool ret=Expand(2);
	if(ret)Sort();
	return ret;	
}

bool CSelectInstanceTreeItem::Expand(UINT action)
{
	if(action==2)
	{
		if(m_expanded) return true;
		if(m_bExpanding) return true;
		
		if(m_fictive_item)	m_tree->DeleteItem(m_fictive_item);
		m_fictive_item = NULL;
		if(m_bShowRelated) ShowRelatedItems();
		Sort();
	}
	else if(action==1)
	{
		CollapseItem();
		m_relatedInstances.Clear();
		m_relatedItems.Clear();
	}

	return true;
}

void CSelectInstanceTreeItem::ShowRelatedItems()
{
	aplExtent subItems, subRels;
	subItems.Unique= false;
	CaplAttr* related_item= NULL;
	
	m_tree->SetRedraw(FALSE);
	m_bExpanding= true;

	UINT iRelIco= -1;
	if(m_inst) GetRelatedInstances(subItems, subRels, iRelIco, &related_item);
	else GetRelatedInstancesBN(subItems);

	if(!related_item)
	{
		for(int i= 0; i<subItems.GetSize(); i++)
		{
			if(!subItems[i]) continue;
			if(subItems[i]->GetAccessmode()>aplRO) continue;

			InsertInstInTree(subItems[i], NULL, iRelIco);
		}
	}
	else
	{
		for(int i= 0; i<subRels.GetSize(); i++)
		{
			if(!subRels[i]) continue;
			if(!subItems[i]) continue;

			if(subRels[i]->GetAccessmode()>aplRO) continue;
			if(subItems[i]->GetAccessmode()>aplRO) continue;

			InsertInstInTree(subItems[i], subRels[i], iRelIco);
		}		
	}
	
	ShowExpandOptions();

	m_bExpanding= false;
	m_tree->SetRedraw(TRUE);
}

int CSelectInstanceTreeItem::GetRelatedInstancesBN(aplExtent &subItems)
{
	subItems.Clear();

	if(m_sName== APL_T("Категории"))
	{
		m_api->m_categ_mgr.GetAllSubCategory(NULL, subItems);
	}
	else if(m_sName== APL_T("Папки"))
	{
		m_api->m_folder_mgr.GetAllSubFolder(NULL, subItems,false,false);
	}
	else if(m_sName== APL_T("Заказ-наряды и акты об уничтожении"))
	{
		m_api->m_doc_mgr.GetAllPurchaseOrder(subItems);				
	}
	else if(m_sName== APL_T("Личные папки"))
	{
		m_api->m_folder_mgr.GetAllSubFolder(m_api->m_data.GetCurrUser(), subItems);		
	}
	else if(m_sName== APL_T("Справочники"))
	{
		m_api->m_classifier_mgr.LoadSubClassifierSystems(NULL, subItems);
	}
	else if(m_sName== APL_T("Организационная структура"))
	{
		aplExtent ext, rels;
		m_api->m_appr_mgr.GetAllSubOrganization(NULL, ext);
		subItems.Append(ext);
		m_api->m_appr_mgr.GetAllSubPerson(NULL, ext, rels);
		subItems.Append(ext);
	}
	else if(m_sName== APL_T("Поиск в БД"))
	{
		COleDateTime odt;
		m_api->m_query_mgr.GetFindResult(0, subItems, odt);
		m_api->m_query_mgr.LoadQueryInfo(subItems, false);
	}
	else if(0 == m_sName.CompareNoCase(APL_T("Мои задания")))
	{
		aplExtent ext;
		CString sState;
		int i;
		if(0!=m_api->m_wf_mgr)
		{
			m_api->m_wf_mgr->GetUserTaskList(m_api->m_appr_mgr.GetCurrentPerson(), ext,false,false,false);
			for(i=0; i<ext.GetSize(); i++)
			{
				m_api->m_data.GetAttrBN(ext[i], _T("state"), sState);
				if(sState!=_T("complete") && sState!=_T("cancel") && sState!=_T("suspend"))
					subItems.Add(ext[i]);
			}

			CaplEntity* ent= m_api->m_data.GetEntityBN(_T("apl_action"));
			CaplAttr* attr= m_api->m_data.GetAttrDefinition(ent, _T("id"));
			///SortById(&m_api->m_data, subItems, 0, subItems.GetSize()-1, attr);
			CSortClass::SortExtentById(subItems);
		}
	}

	return subItems.GetSize();	
}

int CSelectInstanceTreeItem::GetRelatedInstances(aplExtent &subItems, aplExtent& subRels, UINT& iRelIco, CaplAttr** related_inst/* = NULL */)
{
	aplExtent ext, rels;
	iRelIco= -1;
	
	if(m_inst)
	{
/*категория*/		
		if(m_api->m_data.IsKindOf(m_inst, m_api->m_categ_mgr.e_categ))
		{
			m_api->m_categ_mgr.GetAllSubCategory(m_inst, subItems);
			m_api->m_categ_mgr.GetCategoryContents(m_inst, ext);
			m_api->LoadExtentInfo(ext);
			subItems.Append(ext);
		}
/*папка*/		
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_folder_mgr.e_folder))
		{
			m_api->m_folder_mgr.GetFolderContents(m_inst, subItems);
			m_api->m_folder_mgr.GetAllSubFolder(m_inst, ext);
			subItems.Append(ext);
		}
/*справочник*/		
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_classifier_mgr.e_apl_classifier_system))
		{
			m_api->m_classifier_mgr.LoadSubClassifierSystems(m_inst, subItems);
			m_api->m_classifier_mgr.LoadSubClassifierLevels(m_inst, ext);
			subItems.Append(ext);
		}
/*элемент структуры справочника*/		
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_classifier_mgr.e_apl_classifier_level))
		{
			m_api->m_classifier_mgr.LoadSubClassifierLevels(m_inst, subItems);
			m_api->m_classifier_mgr.GetSubItems(m_inst, ext);
			subItems.Append(ext);
		}
/*изделие*/		
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_prd))
		{
			m_api->m_prd_mgr.GetAllProductVersion(m_inst, subItems);
			iRelIco= ICO_REL_VER;
		}
/*версия изделия*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_pdf))
		{
			aplExtent aeRels, aeItems;
			CaplInstance *cit = NULL;
			m_api->m_prd_mgr.LoadAllSubProduct(NULL, NULL, m_inst, aeRels, aeItems);
	
			// отфильровываем состав на текущую дату
			m_api->m_prd_mgr.FilterlByDate(aeRels, COleDateTime::GetCurrentTime(), subRels);

			if(m_bFilterSubProduct)
			{
				aeRels.Clear();
				aeRels.Append(subRels);
				subRels.Clear();

				aeItems.Clear();
				aeItems.Add(m_inst);
				
				m_api->m_data.GetAttrBN(m_inst, _T("locker"), cit);
				m_api->m_prd_mgr.FilterByChange(aeRels, cit, subRels, &aeItems, true);
			}
			
			aeItems.Clear();

			for(int i=0; i<subRels.Size; ++i)
			{
				if(m_api->m_data.IsKindOf(subRels[i], m_api->m_prd_mgr.e_apl_qacu))
					m_api->m_data.GetAttr(subRels[i], m_api->m_prd_mgr.a_pdr_r_ted, cit);
				else if(m_api->m_data.IsKindOf(subRels[i], m_api->m_change_mgr.e_psc))
				{
					m_api->m_data.GetAttr(subRels[i], m_api->m_change_mgr.a_psc_changing_product, cit);
					aeItems.Add(cit);
				}
				else cit= NULL;

				subItems.Add(cit);
			}
			if(aeItems.GetSize()) m_api->LoadExtentInfo(aeItems);
			if(related_inst)*related_inst= m_api->m_prd_mgr.a_pdr_r_ted;
		}
/*организация*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_appr_mgr.e_org))
		{
			m_api->m_appr_mgr.GetAllSubOrganization(m_inst, ext, false);
			subItems.Append(ext);
			m_api->m_appr_mgr.GetAllSubPerson(m_inst, ext, rels);
			subItems.Append(ext);
			m_api->m_prd_inst_mgr.LoadInsertedInstances(m_inst, rels, ext);
			subItems.Append(ext);
		}
/*бизнес процесс*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_bp_mgr.e_bp))
		{
			m_api->m_data.GetAttr(m_inst, m_api->m_bp_mgr.a_bp_elements, subItems);
//			m_api->m_bp_mgr.GetAllSubBP(m_inst, subItems);
			m_api->LoadExtentInfo(subItems);
		}
/*экземпляр бизнес процесс*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_bp_mgr.e_apl_bp_inst))
		{
			m_api->m_data.GetAttr(m_inst, m_api->m_bp_mgr.a_bp_inst_elements, subItems);
			m_api->LoadExtentInfo(subItems);
		}
/*поиск*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_query_mgr.e_apl_query))
		{
			COleDateTime odt;
			m_api->m_query_mgr.LoadQueryInfo(m_inst,true);
			m_api->m_query_mgr.GetFindResult(m_inst, subItems, odt);
			m_api->LoadExtentInfo(subItems);
		}
/*документы*/		
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_doc_mgr.e_apl_doc))
		{
			aplExtent inExt;
			CaplInstance *act_rev=0;
			apidata.GetAttr(m_inst, m_api->m_doc_mgr.a_apl_doc_active, act_rev);
			inExt.Add(m_inst); inExt.Add(act_rev);
			m_api->m_doc_mgr.FindAssociatedDocuments(inExt, subItems, subRels);			
		}
/*групповая х-ка*/		
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_charact_mgr.e_charact_val_group))
		{
			m_api->m_charact_mgr.GetGroupContents(m_inst, subItems);
		}
/*экземпляр*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_inst_mgr.e_prd_inst))
		{
			m_api->m_prd_inst_mgr.LoadInsertedInstances(m_inst, rels, subItems);
		}
/*партия*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_inst_mgr.e_lot))
		{
			m_api->m_prd_inst_mgr.LoadIncomingLots(m_inst, subItems);			
			m_api->m_prd_inst_mgr.FindAllLotProductInstance(m_inst, ext);
			subItems.Append(ext);
		}
/*проект*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_project_mgr->e_project))
		{
			aplExtent projs, projObjs, projRels;
			projs.Add(m_inst);
			m_api->m_project_mgr->GetAllSubProject(projs,subItems);
			m_api->m_project_mgr->FindAssociatedItems(m_inst, projObjs, projRels);
			m_api->m_project_mgr->LoadProjectInfo(subItems);
			subItems.Append(projObjs);
		}
/*изменение*/
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_change_mgr.e_chng))
		{
			aplExtent aeItems;

			//Вложенные изменения
			aplExtent ext_linked_change, ext_sub_changes;
			m_api->m_change_mgr.GetLinkedChange(m_inst,ext_linked_change);
			m_api->m_change_mgr.GetSubChanges(m_inst,ext_sub_changes);
			ext_sub_changes.Append(ext_linked_change);	
			if(ext_sub_changes.GetSize()>0)m_api->m_change_mgr.LoadChangeInfo(ext_sub_changes);
			subItems.Append(ext_sub_changes);

			// документы пакета изменения (это будет "Извещение об изменении")

			aplExtent ext_docs;
			m_api->m_doc_mgr.FindAssociatedDocuments(m_inst, ext_docs, subRels);
			subItems.Append(ext_docs);


			// элементы изменения
			aeItems.Clear();
			m_api->m_data.GetAttr(m_inst, m_api->m_change_mgr.a_chng_items, aeItems);

			for(int i=0; i<aeItems.GetSize(); i++)
			{
				if(m_api->m_data.IsKindOf(aeItems[i], m_api->m_change_mgr.e_avc))
					subItems.Add(aeItems[i]);
			}			
		}
/*элемент изменения*/	
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_change_mgr.e_avc))
		{
			CaplInstance *cit = NULL;
			m_api->LoadItemInfo(m_inst);
			m_api->m_data.GetAttr(m_inst, m_api->m_change_mgr.a_avc_new_rev, cit);
			
			m_api->LoadItemInfo(cit);
			subItems.Add(cit);			
		}
/* требование */
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_req_mgr.e_requirement))
		{
			aplExtent aeItems;

			m_api->m_req_mgr.LoadChildsFromBase(m_inst, aeItems, false);
			subItems.Append(aeItems);
		}
/*Задание*/
		else if(m_api->m_data.IsKindOfBN(m_inst, _T("apl_task")))
		{
			aplExtent aeSubProccess, aeItems;

			if(m_api->m_wf_mgr && !m_bShowWorkObjectsInProcess)
			{
				m_api->m_wf_mgr->GetWorkObjects(m_inst, aeItems);
				subItems.Append(aeItems);				
			}

			if(m_api->m_wf_mgr)
			{
				m_api->m_data.GetAttrBN(m_inst, _T("sub_processes"), aeSubProccess);
				subItems.Append(aeSubProccess);
			}
		}
/* Процесс */
		else if(m_api->m_data.IsKindOfBN(m_inst, _T("apl_process")))
		{
			int i;
			if(m_api->m_wf_mgr)
			{
				CString buf;
				CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
				CaplInstance *ciActiveTask = NULL;

				CaplEntity* e_task= m_api->m_data.GetEntityBN(_T("apl_task"));
				CaplAttr* a_task_proc= m_api->m_data.GetAttrDefinition(e_task, _T("of_process"));

				ld.AddQuery(0, m_inst);
				// ищем все задания процесса
				ld.AddQuery(_T('r'), 0, e_task,  a_task_proc, true);
				ld.LoadEx(true, &subItems);

				for(i=0; i<subItems.Size; ++i)
				{
					// оставляем только задания
					if(!m_api->m_data.IsKindOf(subItems[i], e_task))
					{
						subItems.Remove(i);
						i--;
					}					
				}

				if(ciActiveTask) subItems.Add(ciActiveTask); 
				m_api->LoadExtentInfo(subItems);

				// рабочие объекты
				if(m_bShowWorkObjectsInProcess)
				{
					aplExtent aeWO, aeTmp;
					CaplInstance *ciItem = NULL;
					CaplEntity* e_proc= m_api->m_data.GetEntityBN(_T("apl_process")); 
					CaplEntity* e_woc= m_api->m_data.GetEntityBN(_T("apl_work_object")); 

					CaplAttr* a_proc_wo= m_api->m_data.GetAttrDefinition(e_proc, _T("work_objects"));	
					CaplAttr* a_wo_obj= m_api->m_data.GetAttrDefinition(e_woc, _T("object"));

					m_api->m_data.GetAttr(m_inst, a_proc_wo, aeWO);
					m_api->LoadExtentInfo(aeWO);
					
					for(i=0; i<aeWO.GetSize(); i++)
					{
						m_api->m_data.GetAttr(aeWO[i], a_wo_obj, ciItem);
						subItems.Add(ciItem); aeTmp.Add(ciItem);
					}					
					m_api->LoadExtentInfo(aeTmp);
				}
			}
		}
/**/
	}

	return subItems.GetSize();
}

HTREEITEM CSelectInstanceTreeItem::RestoreTreeItem(CTreeCtrl* tree, HTREEITEM parent_item)
{
	if(tree)
	{
		m_tree= tree;
		
		m_tree->SetRedraw(FALSE);
		m_bExpanding= true;

		m_item= m_tree->InsertItem(m_sName, m_ico, m_ico, parent_item);
		m_tree->SetItemData(m_item, (DWORD)this);

		if(m_relatedItems.Size)
		{
			for(int i= 0; i<m_relatedItems.Size; i++)
			{
				((CSelectInstanceTreeItem*)m_relatedItems[i].out)->RestoreTreeItem(m_tree, m_item);
			}
			
			MyExpand();
//			m_tree->Expand(m_item, TVE_EXPAND);
			
		}
		else
		{
			m_fictive_item = m_tree->InsertItem(_T("fictive"), 0, 0, m_item);
		}

		m_tree->SetRedraw(TRUE);
		m_bExpanding= false;
		return m_item;
	}

	return 0;
}

CSelectInstanceTreeItem* CSelectInstanceTreeItem::InsertInstInTree(CaplInstance* inst, CaplInstance* rel, UINT iRelIco, UINT iEffIco)
{
	if(!inst) return NULL;
	if(!inst->GetType()) return NULL;
	if(inst->GetAccessmode()>aplRO) return NULL;
	
	CSelectInstanceTreeItem* new_item= NULL;
	
	if(-1==m_relatedInstances.Find(inst) || (rel && -1==m_relatedInstances.Find(rel)))
	{
		new_item= new CSelectInstanceTreeItem(m_api, m_tree, m_ItemsArray, inst, rel);
		
		new_item->m_iRelIco= iRelIco;
		new_item->m_iEffIco= iEffIco;

		new_item->CreateTreeItem(m_item);
		
		m_relatedInstances.Add(inst);
		if(rel)m_relatedInstances.Add(rel);
		m_relatedItems.Add((long)inst, (long)new_item);
	}

	return new_item;
}

void CSelectInstanceTreeItem::ShowAllApproval(bool showMsg/* = true */)
{
	int i;
	if(!m_inst) return;
	
	m_tree->SetRedraw(FALSE);

	aplExtent ext;
	CaplInstance* inst= NULL;
	
	if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_apl_pdf))
	{
		m_api->m_data.GetAttr(m_inst,m_api->m_prd_mgr.a_pdf_prd, inst);
	}
	else if (m_api->m_data.IsKindOf(m_inst,m_api->m_doc_mgr.e_apl_doc))
	{
		m_api->m_data.GetAttr(m_inst,m_api->m_doc_mgr.a_apl_doc_active, inst);
	}
	else if (m_api->m_data.IsKindOf(m_inst,m_api->m_doc_mgr.e_apl_doc_rev))
	{
		m_api->m_data.GetAttr(m_inst,m_api->m_doc_mgr.a_apl_doc_rev_doc, inst);
	}
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_bp_mgr.e_bp))
	{
		m_api->m_data.GetAttr(m_inst, m_api->m_bp_mgr.a_bp_act, inst);
	}
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_charact_mgr.e_apl_charact_value))
	{
		m_api->m_data.GetAttr(m_inst, m_api->m_charact_mgr.a_apl_charact_val_act_ver, inst);
	}
	

	ext.Add(m_inst);
	if(inst) ext.Add(inst);

	aplExtent apprs, tmpExt;
	for(i= 0; i<ext.GetSize(); i++)
	{
		m_api->m_appr_mgr.LoadItemApproval(ext[i], tmpExt);
		apprs.Append(tmpExt);
	}
	
	bool bFindNewDocs= false;

	for(i= 0; i<apprs.GetSize(); i++)
	{
		if(InsertInstInTree(apprs[i], NULL))bFindNewDocs= true;
	}

	if(!bFindNewDocs && showMsg)
	{
		AfxMessageBox( APL_T("Новые электронные подписи не найдены."), MB_OK|MB_ICONINFORMATION);
	}
	else
	{
		MyExpand();
//		m_tree->Expand(m_item,TVE_EXPAND);
//		if(m_fictive_item!=0)
//		{
//			m_tree->DeleteItem(m_fictive_item);
//			m_fictive_item=0;
//		}
//		Sort();		
	}

	m_tree->SetRedraw(TRUE);	
}

void CSelectInstanceTreeItem::ShowAllCharacteristic(bool showMsg/* = true */)
{
	int i;
	if(!m_inst) return;
	m_tree->SetRedraw(FALSE);

	aplExtent ext;
	CaplInstance* inst= NULL;
	
	if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_apl_pdf))
	{
		m_api->m_data.GetAttr(m_inst,m_api->m_prd_mgr.a_pdf_prd, inst);
	}
	else if (m_api->m_data.IsKindOf(m_inst,m_api->m_doc_mgr.e_apl_doc))
	{
		m_api->m_data.GetAttr(m_inst,m_api->m_doc_mgr.a_apl_doc_active, inst);
	}
	else if (m_api->m_data.IsKindOf(m_inst,m_api->m_doc_mgr.e_apl_doc_rev))
	{
		m_api->m_data.GetAttr(inst,m_api->m_doc_mgr.a_apl_doc_rev_doc, inst);
	}
	
	ext.Add(m_inst);
	if(m_rel) ext.Add(m_rel);
	if(inst) ext.Add(inst);

	aplExtent chars, groups;
	m_api->m_charact_mgr.FindAssociatedCharacteristic(ext, chars, groups);
	
	bool bFindNew= false;
	
	for(i= 0; i<chars.GetSize(); i++)
	{
		m_api->m_data.GetAttr(chars[i], m_api->m_charact_mgr.a_apl_charact_val_group, inst);
		if(inst!=0)	if(groups.Find(inst)>=0) continue;
		if(InsertInstInTree(chars[i], NULL))bFindNew= true;
	}

	for(i= 0; i<groups.GetSize(); i++)
	{
		if(InsertInstInTree(groups[i], NULL))bFindNew= true;
	}

	if(!bFindNew && showMsg)
	{
		AfxMessageBox( APL_T("Новые характеристики не найдены."), MB_OK|MB_ICONINFORMATION);
	}
	else
	{
		MyExpand();
//		m_tree->Expand(m_item,TVE_EXPAND);
//		if(m_fictive_item!=0)
//		{
//			m_tree->DeleteItem(m_fictive_item);
//			m_fictive_item=0;
//		}
//		Sort();		
	}

	m_tree->SetRedraw(TRUE);

}

void CSelectInstanceTreeItem::ShowAllBPResources(bool bShowMessage/* = true */)
{
	aplExtent ext;
	m_api->m_bp_mgr.LoadAllBPResources(m_inst, ext);

	m_tree->SetRedraw(FALSE);	

	for(int i= 0; i<ext.GetSize(); i++)
		InsertInstInTree(ext[i], NULL);

//	m_tree->Expand(m_item,TVE_EXPAND);
//	if(m_fictive_item!=0)
//	{
//		m_tree->DeleteItem(m_fictive_item);
//		m_fictive_item=0;
//	}
//	Sort();	
	MyExpand();
	
	m_tree->SetRedraw();	
}

void CSelectInstanceTreeItem::ShowAllBPInstances(bool bShowMessage/* = true */)
{
	aplExtent ext;
	if(m_api->m_data.IsKindOf(m_inst,m_api->m_bp_mgr.e_bp))//Экземпляры бизнес процесса
	{
		if(m_api && m_api->m_data.IsConnected())
		{
			CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
			int i=ld.AddQuery(_T('b'), m_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;
		m_api->m_data.GetEntityExtent(m_api->m_bp_mgr.e_apl_bp_inst,out_ext);
		
		CaplInstance *inst=0;
		
		for(int 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==m_inst) 
				ext.Add(out_ext[i]);
		}
		m_api->m_bp_mgr.LoadBPInstInfo(ext);		
	}
	else if(m_api->m_data.IsKindOf(m_inst,m_api->m_prd_mgr.e_pdf))//Экземпляры бизнес процесса
	{
		aplExtent rels;
		m_api->m_bp_mgr.FindAssociatedBPInst(m_inst, ext, rels);
	}
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_inst_mgr.e_lot))//Экземпляры бизнес процесса
	{
		aplExtent rels;
		m_api->m_bp_mgr.FindAssociatedBPInst(m_inst, ext, rels);
	}
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_inst_mgr.e_prd_inst))//Экземпляры бизнес процесса
	{
		aplExtent rels;
		m_api->m_bp_mgr.FindAssociatedBPInst(m_inst, ext, rels);
	}
	else return;

	
	m_tree->SetRedraw(FALSE);	
	
	for(int i= 0; i<ext.GetSize(); i++)
		InsertInstInTree(ext[i], NULL);
	
//	m_tree->Expand(m_item,TVE_EXPAND);
//	if(m_fictive_item!=0)
//	{
//		m_tree->DeleteItem(m_fictive_item);
//		m_fictive_item=0;
//	}
//	Sort();	
	MyExpand();
	
	m_tree->SetRedraw(TRUE);
}

void CSelectInstanceTreeItem::ShowAllMaters(bool bShowMessage/* = true */)
{
	aplExtent ext, rels;
	UINT ico;
	CaplInstance* pdf= NULL;

	m_api->m_prd_mgr.LoadAllZagotov(m_inst, rels, ext, true);
	
	m_tree->SetRedraw(FALSE);	
	
	for(int i= 0; i<rels.GetSize();i++)
	{
		ico= -1;
		if(m_api->m_data.IsKindOf(rels[i], m_api->m_prd_mgr.e_make_from))
			ico= ICO_REL_MAKE;
		else if(m_api->m_data.IsKindOf(rels[i], m_api->m_prd_mgr.e_design_make_from))
			ico= ICO_REL_MATER;

		m_api->m_data.GetAttr(rels[i], m_api->m_prd_mgr.a_pdr_r_ted, pdf);
		InsertInstInTree(pdf, rels[i], ico);
	}
	
//	m_tree->Expand(m_item,TVE_EXPAND);
//	if(m_fictive_item!=0)
//	{
//		m_tree->DeleteItem(m_fictive_item);
//		m_fictive_item=0;
//	}
//	Sort();
	MyExpand();
	
	m_tree->SetRedraw(TRUE);	
}

void CSelectInstanceTreeItem::ShowAllPrdInstances(bool bShowMessage/* = true */)
{
	aplExtent ext;
	if(!m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
		return;
	
	m_api->m_prd_inst_mgr.FindAllPdfInstances(m_inst, ext);	

	m_tree->SetRedraw(FALSE);	

	for(int i= 0; i<ext.GetSize(); i++)
		InsertInstInTree(ext[i], NULL);
	
//	m_tree->Expand(m_item, TVE_EXPAND);
//	if(m_fictive_item!=0)
//	{
//		m_tree->DeleteItem(m_fictive_item);
//		m_fictive_item=0;
//	}
//	Sort();
	MyExpand();

	m_tree->SetRedraw();
}

void CSelectInstanceTreeItem::ShowAllDocs(bool bShowMessage/* = true */)
{
	if(!m_inst) return;
	
	m_tree->SetRedraw(FALSE);

	aplExtent ext;
	CaplInstance* inst= NULL;
	
	if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_apl_pdf))
	{
		m_api->m_data.GetAttr(m_inst,m_api->m_prd_mgr.a_pdf_prd, inst);
	}
	else if (m_api->m_data.IsKindOf(m_inst,m_api->m_doc_mgr.e_apl_doc))
	{
		m_api->m_data.GetAttr(m_inst,m_api->m_doc_mgr.a_apl_doc_active, inst);
	}

	ext.Add(m_inst);
	if(inst) ext.Add(inst);

	aplExtent docs, rels;
	CaplInstance* doc (NULL);
	m_api->m_doc_mgr.FindAssociatedDocuments(ext, docs, rels);
	
	/*Поиск исходных/зависимых документов*/
	CaplInstance* dep_doc(NULL);
	if(m_api->m_data.IsKindOf(m_inst,m_api->m_doc_mgr.e_apl_doc))
		dep_doc=m_inst;
	else if (m_api->m_data.IsKindOf(m_inst,m_api->m_doc_mgr.e_apl_doc_rev))
		m_api->m_data.GetAttr(m_inst,m_api->m_doc_mgr.a_apl_doc_rev_doc, dep_doc);

	if(dep_doc)
	{
		aplExtent dep_docs, dep_rels;
		CaplInstance *parent = m_api->m_doc_mgr.IsDependenceDocument(dep_doc);
		if(parent!=NULL)
		{
			m_api->m_doc_mgr.FindDependenceDocuments(parent, dep_docs, dep_rels);
			rels.Append(dep_rels);
		}
	}
	
	bool bFindNewDocs= false;

	for(int i= 0; i<rels.GetSize(); i++)
	{
		m_api->m_data.GetAttr(rels[i], m_api->m_doc_mgr.a_apl_doc_ref_doc, doc);
		if(dep_doc==doc)// для исходных/зависимых документов
		{
			m_api->m_data.GetAttr(rels[i], m_api->m_doc_mgr.a_apl_doc_ref_item, doc);
		}
		if(doc)
		{
			if(InsertInstInTree(doc, rels[i]))bFindNewDocs= true;
		}
	}

	if(!bFindNewDocs && bShowMessage)
	{
		AfxMessageBox( APL_T("Новые документы не найдены."), MB_OK|MB_ICONINFORMATION);
	}
	else
	{
//		m_tree->Expand(m_item,TVE_EXPAND);
//		if(m_fictive_item!=0)
//		{
//			m_tree->DeleteItem(m_fictive_item);
//			m_fictive_item=0;
//		}
//		Sort();		
		MyExpand();
	}

	m_tree->SetRedraw(TRUE);
}

void CSelectInstanceTreeItem::ShowAllBPs(bool bShowMessage/* = true */)
{
	aplExtent ext, rels;
	m_api->m_bp_mgr.FindAssociatedBP(m_inst, ext, rels);

	m_tree->SetRedraw(FALSE);	
	
	for(int i= 0; i<ext.GetSize(); i++)
		InsertInstInTree(ext[i], NULL);
	
//	m_tree->Expand(m_item,TVE_EXPAND);
//	if(m_fictive_item!=0)
//	{
//		m_tree->DeleteItem(m_fictive_item);
//		m_fictive_item=0;
//	}
//	Sort();	
	MyExpand();
	
	m_tree->SetRedraw(TRUE);
}

void CSelectInstanceTreeItem::ShowAllLots(bool bShowMessage/* = true */)
{
	aplExtent ext;
	m_api->m_prd_inst_mgr.FindAllPdfLoot(m_inst, ext);	
	
	m_tree->SetRedraw(FALSE);	

	for(int i= 0; i<ext.GetSize(); i++)
		InsertInstInTree(ext[i], NULL);
	
//	m_tree->Expand(m_item, TVE_EXPAND);
//	if(m_fictive_item!=0)
//	{
//		m_tree->DeleteItem(m_fictive_item);
//		m_fictive_item=0;
//	}
//	Sort();
	MyExpand();

	m_tree->SetRedraw(TRUE);	
}

void CSelectInstanceTreeItem::ShowAllVersions(bool bShowMessage/* = true */)
{
	m_tree->SetRedraw(FALSE);	

	aplExtent ext;
	CaplInstance* inst;
	if(apidata.IsKindOf(m_inst, m_api->m_prd_mgr.e_pdf))
	{
		apidata.GetAttr(m_inst, m_api->m_prd_mgr.a_pdf_prd, inst);
		m_api->m_prd_mgr.GetAllProductVersion(inst, ext);
		if(1==ext.GetSize())
		{
			AfxMessageBox( APL_T("Эта версия единственная."), MB_OK|MB_ICONINFORMATION);
		}
		else
		{
			for(int i= 0; i<ext.GetSize(); i++)
				InsertInstInTree(ext[i], NULL, ICO_REL_VER);
		}
	}
	else if(apidata.IsKindOf(m_inst, m_api->m_doc_mgr.e_doc))
	{
		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(m_inst, ext);
		
		CaplInstance* obj= NULL, *act= NULL;

		for(int i= 0; i<ext.GetSize(); i++)
		{
			if(ext[i]==0){ext.Remove(i); i--; continue;}
			apidata.GetAttr(ext[i], m_api->m_doc_mgr.a_apl_doc_rev_base, inst);			

			if(inst==0 || (inst != 0 && inst->GetAccessmode() > aplRO))
			{
				apidata.GetAttr(ext[i], m_ItemVertionInfo._VerObjAttr, obj);
				apidata.GetAttr(obj, m_ItemVertionInfo._ObjActiveVerAttr, act);
				UINT ico= ICO_REL_VER;
				if(act==ext[i])ico= ICO_REL_ACTIVE_VER;
				CSelectInstanceTreeItem* newItem= InsertInstInTree(ext[i], NULL, ico);
				if(newItem)FillRevisionTree(newItem->m_item, ext);
			}
		}
		
		ClearObjVertionInfo();
	}
	else if(apidata.IsKindOf(m_inst, m_api->m_bp_mgr.e_bp))
	{
		int ico= APL_ICON_BP_VERTION;
		aplExtent subBP;
		apidata.GetAttr(m_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(m_inst, ext);
		CaplInstance* obj= NULL, *act= NULL;
		
		for(int i= 0; i<ext.GetSize(); i++)
		{
			if(ext[i]==0){ext.Remove(i); i--; continue;}
			apidata.GetAttr(ext[i], m_api->m_bp_mgr.a_bp_ver_base, inst);
			if(inst==0)
			{
				apidata.GetAttr(ext[i], m_ItemVertionInfo._VerObjAttr, obj);
				apidata.GetAttr(obj, m_ItemVertionInfo._ObjActiveVerAttr, act);
				UINT ico= ICO_REL_VER;
				if(act==ext[i])ico= ICO_REL_ACTIVE_VER;
				CSelectInstanceTreeItem* newItem= InsertInstInTree(ext[i], NULL, ico);
				if(newItem)FillRevisionTree(newItem->m_item, ext);
			}
		}
		ClearObjVertionInfo();			
	}
	else if(apidata.IsKindOf(m_inst, m_api->m_charact_mgr.e_apl_charact_value))
	{
		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(m_inst, ext);
		CaplInstance* obj= NULL, *act= NULL;
		
		for(int i= 0; i<ext.GetSize(); i++)
		{
			if(ext[i]==0){ext.Remove(i); i--; continue;}
			apidata.GetAttr(ext[i], m_api->m_charact_mgr.a_apl_charact_val_ver_base, inst);
			if(inst==0 && -1==m_relatedInstances.Find(ext[i]))
			{
				apidata.GetAttr(ext[i], m_ItemVertionInfo._VerObjAttr, obj);
				apidata.GetAttr(obj, m_ItemVertionInfo._ObjActiveVerAttr, act);
				UINT ico= ICO_REL_VER;
				if(act==ext[i])ico= ICO_REL_ACTIVE_VER;
				CSelectInstanceTreeItem* newItem= InsertInstInTree(ext[i], NULL, ICO_REL_VER);
				if(newItem)FillRevisionTree(newItem->m_item, ext);
			}
		}
		ClearObjVertionInfo();			
	}	
	
//	m_tree->Expand(m_item,TVE_EXPAND);
//	if(m_fictive_item!=0)
//	{
//		m_tree->DeleteItem(m_fictive_item);
//		m_fictive_item=0;
//	}
//	Sort();
	MyExpand();
	
	m_tree->SelectItem(m_item);
	m_tree->SelectDropTarget(m_item);

	m_tree->SetRedraw(TRUE);
}
//**********************************************************************************************
void CSelectInstanceTreeItem::ShowAllUsage(bool bShowMessage/* = true */)
{
	m_tree->SetRedraw(FALSE);	

	if(apidata.IsKindOf(m_inst, m_api->m_doc_mgr.e_doc) || apidata.IsKindOf(m_inst, m_api->m_doc_mgr.e_apl_doc_rev))
	{
		CaplInstance *doc=m_inst;
		if(apidata.IsKindOf(doc, m_api->m_doc_mgr.e_apl_doc_rev))
		{
			apidata.GetAttr(doc, m_api->m_doc_mgr.a_apl_doc_rev_doc, doc);
		}
		if(0==doc) return;
		if(doc->IsDeleted()) return;
		if(doc->GetAccessmode()>aplRO) return;

		aplExtent ext,ext_rel;

		m_api->m_doc_mgr.FindAssociatingDocuments(doc, ext,ext_rel);

		if(ext.GetSize()>0)
		{
			m_api->LoadExtentInfo(ext);

			for(int i= 0; i<ext.GetSize(); i++)
			{
				CaplInstance *inst=ext[i];
				if(0==inst) continue;
				if(inst->IsDeleted()) continue;
				if(inst->GetAccessmode()>aplRO) continue;

				InsertInstInTree(inst, 0, ICO_REL_WHERE_USED);
			}
		}

	}
	else return;


	//	m_tree->Expand(m_item,TVE_EXPAND);
	//	if(m_fictive_item!=0)
	//	{
	//		m_tree->DeleteItem(m_fictive_item);
	//		m_fictive_item=0;
	//	}
	//	Sort();
	MyExpand();

	m_tree->SelectItem(m_item);
	m_tree->SelectDropTarget(m_item);

	m_tree->SetRedraw(TRUE);
}



void CSelectInstanceTreeItem::FillRevisionTree(HTREEITEM item, aplExtent &revExt)
{
	if(!item) return;
	CSelectInstanceTreeItem* treeItem= (CSelectInstanceTreeItem*)m_tree->GetItemData(item);
	if(treeItem==NULL) return;
	
	CaplInstance* inst= NULL, *obj= NULL, *act= NULL;

	for(int i= 0; i<revExt.GetSize(); i++)
	{
		if(revExt[i]==0){revExt.Remove(i); i--; continue;}
		if(revExt[i]->GetAccessmode()==aplNO){revExt.Remove(i); i--; continue;}
		
		apidata.GetAttr(revExt[i], m_ItemVertionInfo._VerBaseAttr, inst);
		
		if(inst==treeItem->m_inst)
		{
			apidata.GetAttr(revExt[i], m_ItemVertionInfo._VerObjAttr, obj);
			apidata.GetAttr(obj, m_ItemVertionInfo._ObjActiveVerAttr, act);
			UINT ico= ICO_REL_VER;
			if(act==revExt[i])ico= ICO_REL_ACTIVE_VER;
			
			CSelectInstanceTreeItem* newItem= treeItem->InsertInstInTree(revExt[i], NULL, ico);

			FillRevisionTree(newItem->m_item, revExt);
			
			//revExt.Remove(i); i--; ЯАИ: при таком удалении теряются ветки
		}
	}
	
//	treeItem->m_tree->Expand(treeItem->m_item,TVE_EXPAND);
//	if(treeItem->m_fictive_item!=0)
//	{
//		treeItem->m_tree->DeleteItem(treeItem->m_fictive_item);
//		treeItem->m_fictive_item=0;
//	}
//	
//	treeItem->Sort();		
	treeItem->MyExpand();
}

void CSelectInstanceTreeItem::ShowExpandOptions()
{
	UINT iOption= -1;
	
	if (!m_inst || !m_inst->GetType()) return;

	if(m_api->m_data.IsKindOf(m_inst, m_api->m_categ_mgr.e_categ))
	{
		iOption= m_ExpandOption.m_showintree_categ;
	}
/*папка*/		
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_folder_mgr.e_folder))
	{
		iOption= -1;
	}
/*справочник*/		
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_classifier_mgr.e_apl_classifier_system))
	{
		iOption= m_ExpandOption.m_showintree_classif_s;
	}
/*элемент структуры справочника*/		
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_classifier_mgr.e_apl_classifier_level))
	{
		iOption= m_ExpandOption.m_showintree_classif_l;
	}
/*изделие*/		
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_prd))
	{
		iOption= m_ExpandOption.m_showintree_prd;
	}
/*версия изделия*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_pdf))
	{
		iOption= m_ExpandOption.m_showintree_pdf;
	}
/*организация*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_appr_mgr.e_org))
	{
		iOption= m_ExpandOption.m_showintree_org;
	}
/*сотрудник*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_appr_mgr.e_person))
	{
		iOption= m_ExpandOption.m_showintree_person;
	}
/*сотрудник*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_appr_mgr.e_official))
	{
		iOption= m_ExpandOption.m_showintree_official;
	}
/*бизнес процесс*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_bp_mgr.e_bp))
	{
		iOption= m_ExpandOption.m_showintree_bp;
	}
/*экземпляр бизнес процесс*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_bp_mgr.e_apl_bp_inst))
	{
		iOption= m_ExpandOption.m_showintree_bpinst;
	}
/*ресурс бизнес процесс*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_bp_mgr.e_apl_bp_inst))
	{
		iOption= m_ExpandOption.m_showintree_bpres;
	}
/*поиск*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_query_mgr.e_apl_query))
	{
		iOption= -1;
	}
/*документы*/		
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_doc_mgr.e_apl_doc))
	{
		iOption= m_ExpandOption.m_showintree_doc;
	}
/*групповая х-ка*/		
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_charact_mgr.e_charact_val_group))
	{
		iOption= m_ExpandOption.m_showintree_charact;
	}
/*х-ка*/		
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_charact_mgr.e_apl_charact_value))
	{
		iOption= m_ExpandOption.m_showintree_charact;
	}
/*экземпляр*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_inst_mgr.e_prd_inst))
	{
		iOption= m_ExpandOption.m_showintree_prdinst;
	}
/*партия*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_inst_mgr.e_lot))
	{
		iOption= m_ExpandOption.m_showintree_lot;
	}
/*изменение*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_change_mgr.e_chng))
	{
		iOption= m_ExpandOption.m_showintree_change;
	}
/*проект*/
	else if(m_api->m_data.IsKindOf(m_inst, m_api->m_project_mgr->e_project))
	{
		iOption= m_ExpandOption.m_showintree_project;
	}
	
	if(-1==iOption) return;

	if(iOption&APL_SHOW_DOC)
		ShowAllDocs(false);
	if(iOption&APL_SHOW_CHARACT)
		ShowAllCharacteristic(false);
	if(iOption&APL_SHOW_APPROVAL)
		ShowAllApproval(false);
	if(iOption&APL_SHOW_INST)
		ShowAllPrdInstances();
	if(iOption&APL_SHOW_BP)
		ShowAllBPs(false);
	if(iOption&APL_SHOW_BPINST)
		ShowAllBPInstances(false);
	if(iOption&APL_SHOW_LOT)
		ShowAllLots();
	if(iOption&APL_SHOW_MATERIAL)
		ShowAllMaters();
	if(iOption&APL_SHOW_VER)
		ShowAllVersions();
	if(iOption&APL_SHOW_RES)
		ShowAllBPResources();
}

aplObjVertonInfo CSelectInstanceTreeItem::m_ItemVertionInfo= {aplNo, -1, NULL, NULL, NULL};
void CSelectInstanceTreeItem::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 CSelectInstanceTreeItem::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;	
}


HTREEITEM CSelectInstanceTreeItem::Find(CaplInstance* inst_prev,HTREEITEM item) 
{
	int query_count=0;
	CString name,mode;

	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);
		m_api->m_data.GetAttr(inst_prev,m_api->m_query_mgr.a_apl_query_mode,mode);
		if(!m_api->m_data.IsConnected() && mode.CompareNoCase(_T("Find"))!=0){
			AfxMessageBox( APL_T("Нет соединения с БД. Можно работать только с быстрым поиском!"));
			return 0;
		}
	}

	CaplInstance* inst;
	if(m_api->m_data.IsConnected()){
		inst=m_api->m_query_mgr.PrepareQuery(inst_prev, name,
			false,false,false,true,_T("Query"));
	}else{
		CString mode=_T("");
		inst=m_api->m_query_mgr.PrepareFind(inst_prev,mode);
	}
	if(inst==0){
		return 0;
	}
	CSelectInstanceTreeItem* treeItem=0;

	if(item==0)
	{
		treeItem= InsertInstInTree(inst, NULL);
		if(treeItem)
		{
			
			MyExpand();
			item= treeItem->m_item;
//
//			Expand(2);
//			m_tree->Expand(m_item, TVE_EXPAND);
//			if(m_fictive_item!=0)
//			{
//				m_tree->DeleteItem(m_fictive_item);
//				m_fictive_item=0;
//			}
//			Sort();
			
			m_tree->SelectItem(treeItem->m_item);
			m_tree->SelectDropTarget(treeItem->m_item);
		}
	}
	else if(item==this->m_item)
	{
		treeItem=this;
	}
	else
	{
		MessageBox(NULL,  APL_T("Ошибка построения дерева. Перезапустите приложение."),  APL_T("Результат запроса"), MB_ICONINFORMATION|MB_OK);
		return item;
	}

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

	buf.Format( APL_T(": найдено %i"), ext.Size);
	m_tree->SetItemText(item,name+buf);

	if(treeItem==this)Expand(1);
	treeItem->MyExpand();

	return item;
}

/************************************************************************/
/*                                                                      */
/************************************************************************/

CSelectInstanceTreeItemEx::CSelectInstanceTreeItemEx(CaplAPI* api, CaplTreeListCtrlWithToolTip* tree, aplTIArray* items, CaplInstance* inst, CaplInstance* rel, CString sName)
	:CSelectInstanceTreeItem(api, tree, items, inst, rel)
{
	m_sName= sName;	
	m_expanded= false;
	m_bExpanding= false;
	m_nShowBaseDoc = false;
	
	m_iRelIco= -1;
	m_iEffIco= -1;	
	m_ToolTipTree = tree;
	m_ciParent = NULL;
}

CSelectInstanceTreeItemEx::~CSelectInstanceTreeItemEx()
{
	HTREEITEM item;
    while(1)
    {
        item=m_ToolTipTree->GetChildItem(m_item);
        if(item==0) break;
        CSelectInstanceTreeItemEx *treeitem= (CSelectInstanceTreeItemEx*)m_ToolTipTree->GetItemData(item);
		if(treeitem==this) continue;
        if(treeitem!=0) 
		{
			int index= m_ItemsArray->Find(treeitem);
			m_ItemsArray->Remove(index);
		}
        else 
		{	
			CString buf;
			//buf = m_ToolTipTree->GetItemText(item);
			CaplTreeListCtrl::CTLItem *pTLItem = (CaplTreeListCtrl::CTLItem*)m_ToolTipTree->GetTLItem(item);
			if(pTLItem!=0) delete pTLItem;
			m_tree->DeleteItem(item);
		}
    }

	CString buf;
	//buf = m_tree->GetItemText(m_item);
	CaplTreeListCtrl::CTLItem *pTLItem = (CaplTreeListCtrl::CTLItem*)m_ToolTipTree->GetTLItem(m_item);
	delete pTLItem;
	m_tree->DeleteItem(m_item);
}

bool CSelectInstanceTreeItemEx::CreateTreeItem(HTREEITEM parent_item, CaplInstance *ciRel)
{
	CString sItemName, sDate, buf, sStr, sPosition;
	int ico= -1;
	CaplInstance *cit = NULL, *unit = NULL;
	COleDateTime time;

	double rValue;
	int iPrior;

	if(m_inst)
	{
		if(m_api->m_data.IsKindOf(m_inst, m_api->m_charact_mgr.e_charact_val_group))
		{
			CaplInstance* def= NULL;
			m_api->m_data.GetAttr(m_inst, m_api->m_charact_mgr.a_charact_val_group_def, def);
			if(def)	m_api->m_data.GetAttrBN(def, _T("name"), m_sName);
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_appr_mgr.e_apl_appr))
		{
			CaplInstance* inst;
			CString buf;

			if(m_api->m_show.m_appr_status)
			{
				m_api->m_data.GetAttrBN(m_inst,_T("status"),inst);
				if(inst!=0) m_api->m_data.GetAttrBN(inst, _T("name"), m_sName);
			}

			if(m_api->m_show.m_appr_pers_role)
			{
				if(m_sName.GetLength()>0) m_sName+=_T(" ");
				m_api->m_data.GetAttrBN(m_inst,_T("role"),buf);
				m_sName+=buf;
			}
			if(m_api->m_show.m_appr_pers)
			{
				if(m_sName.GetLength()>0) m_sName+=_T(" ");
				m_api->m_data.GetAttrBN(m_inst,_T("person_organization"),inst);
				m_api->m_appr_mgr.GetPersonName(inst, buf);
				m_sName+=buf;
			}			
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_bp_mgr.e_bp_res))
		{
			CString buf=_T("");
			if(m_api->m_show.m_showbpres_id)
			{
				m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_id,buf);
				if(buf==_T("")) buf=_T("?");
				m_sName = buf;
			}
			if(m_api->m_show.m_showbpres_type)
			{
				CaplInstance *inst;
				m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_type,inst);
				if(inst!=0) m_api->m_data.GetAttr(inst,m_api->m_bp_mgr.a_bp_res_type_name,buf);
				if(buf==_T("")) buf=_T("?");
				if(m_sName>_T("")) m_sName+=_T(" : ")+buf;
				else m_sName = buf;
			}
			if(m_api->m_show.m_showbpres_object)
			{
				CaplInstance *inst;
				m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_object,inst);
				if(inst!=0) m_api->m_bp_mgr.GetItemName(inst,buf);
				if(buf==_T("")) buf=_T("?");
				if(m_sName>_T("")) m_sName+=_T(" : ")+buf;
				else m_sName = buf;
			}
			if(m_api->m_show.m_showbpres_amount)
			{
				buf=_T("");
				CaplInstance *inst;
				double v;
				CString buf1;
				m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_val,v);
				if(v!=0)
				{
					m_api->m_data.GetAttr(m_inst,m_api->m_bp_mgr.a_bp_res_unit,inst);
					m_api->m_charact_mgr.GetUnitName(inst,buf1);
					buf.Format(_T(" : %g %s"),v,LPCTSTR(buf1));
				}
				if(buf==_T("")) buf=_T("?");
				if(m_sName>_T("")) m_sName+=_T(" : ")+buf;
				else m_sName = buf;
			}			
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_doc_mgr.e_doc) 
			||(m_api->m_data.IsKindOf(m_inst, m_api->m_doc_mgr.e_apl_doc_rev)))
		{
			// Убрал ayatsk 16.12.2010 , т.к. из-за непрохождения этой проверки 
			// (из-за ограничений по видам документов в роли)
			// в ЦКБА не могли добавить документ в WFпроцесс
			
			//if(!IsNeedToShow(ciRel)) 
			//	return false;
				
			m_api->GetItemName(m_inst, m_sName);
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_change_mgr.e_avc))
		{
			// формируем имя элемента изменения документа
			m_api->LoadItemInfo(m_inst);
			m_api->m_data.GetAttr(m_inst, m_api->m_change_mgr.a_chng_item_accept_date, sDate);
			aplString2Date(sDate, time);
			sDate.Format(_T("%.2d.%.2d.%.4d"), time.GetDay(), time.GetMonth(), time.GetYear());

			m_api->m_data.GetAttr(m_inst, m_api->m_change_mgr.a_avc_doc, cit);
			if(cit)
			{
				m_api->LoadItemInfo(cit);
				m_api->GetItemName(cit, buf);
				sDate += _T(" : ") + buf;
			}

			m_api->m_data.GetAttr(m_inst, m_api->m_change_mgr.a_chng_item_id, buf);
			if(!buf.IsEmpty()) sDate = buf+_T(":")+sDate;
			
			m_sName = sDate;
		}
		else if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_pdf) && ciRel)
		{
			if(!m_rel)
			{
				m_api->GetItemName(m_inst, m_sName);
			}
			else
			{
				if(m_api->m_data.IsKindOf(m_rel, m_api->m_prd_mgr.e_qacu_nauo))
				{
					m_api->GetItemName(m_inst, sStr);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_pdr_id, sPosition);

					while(sPosition.GetLength()<3)
						sPosition=_T(" ")+sPosition;

					sPosition= _T("(")+sPosition+_T(") ");

					m_sName+=sPosition;
					m_sName+=sStr;

					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_apl_qacu_value, rValue);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_apl_qacu_unit, unit);
					m_api->m_charact_mgr.GetUnitName(unit, buf);
//					if(unit) m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, buf);

					sStr.Format(_T(" [%g %s]"), rValue, buf);
					m_sName+=sStr;
				}				
				else if(m_api->m_data.IsKindOf(m_rel, m_api->m_prd_mgr.e_make_from))
				{
					m_api->GetItemName(m_inst, sStr);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_pdr_id, sPosition);

					while(sPosition.GetLength()<3)
						sPosition=_T(" ")+sPosition;

					sPosition= _T("(")+sPosition+_T(") ");

					m_sName+=sPosition;
					m_sName+=sStr;
					
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_ranking, iPrior);
					sStr.Format(_T(" {%i}"), iPrior);
					m_sName+=sStr;

					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_value, rValue);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_unit, unit);
					m_api->m_charact_mgr.GetUnitName(unit, buf);
//					if(unit) m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, buf);

					sStr.Format(_T(" [%g %s]->"), rValue, buf);
					m_sName+=sStr;
					
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_derive_value, rValue);
					m_api->m_data.GetAttr(m_rel, m_api->m_prd_mgr.a_make_from_derive_unit, unit);
					m_api->m_charact_mgr.GetUnitName(unit, buf);
//					if(unit) m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, buf);

					sStr.Format(_T("[%g %s]"), rValue, buf);
					m_sName+=sStr;
				}
				else if(m_api->m_data.IsKindOf(m_rel, m_api->m_change_mgr.e_psc))
				{
					m_api->GetItemName(m_inst, sStr);
					m_api->m_data.GetAttr(m_rel, m_api->m_change_mgr.a_psc_position, sPosition);

					while(sPosition.GetLength()<3)
						sPosition=_T(" ")+sPosition;

					sPosition= _T("(")+sPosition+_T(") ");

					m_sName+=sPosition;
					m_sName+=sStr;

					m_api->m_data.GetAttr(m_rel, m_api->m_change_mgr.a_psc_value, rValue);
					m_api->m_data.GetAttr(m_rel, m_api->m_change_mgr.a_psc_unit, unit);
					m_api->m_charact_mgr.GetUnitName(unit, buf);
//					if(unit) m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, buf);

					sStr.Format(_T(" [%g %s]"), rValue, buf);
					m_sName+=sStr;
				}
				else m_api->GetItemName(m_inst, m_sName);
			}
		}		
		else m_api->GetItemName(m_inst, m_sName);
		ico = m_api->GetInstIco(m_inst);
	}	
	else
	{
		sItemName= m_sName;
		
		if(m_sName== APL_T("Категории")) ico= ICON_CATEGORIES;
		else if(m_sName== APL_T("Папки")) ico= ICON_FOLDERS;
		else if(m_sName== APL_T("Личные папки")) ico= ICON_PERS_FOLDER;
		else if(m_sName== APL_T("Справочники")) ico= ICON_CLASSIFIER_SYSTEM;
		else if(m_sName== APL_T("Организационная структура")) ico= ICON_ORGANIZATION;
		else if(m_sName== APL_T("Поиск в БД")) ico= ICON_QUERYES;
		else if(m_sName== APL_T("Мои Задания")) ico= ICON_TASK-1;
	}

	//создаем CTLItem
	m_item = m_ToolTipTree->InsertItem(m_sName, ico, ico, parent_item);
	m_ToolTipTree->SetItemData(m_item, (DWORD)this);
	
	if(-1!=m_iRelIco)SetItemImage(m_iRelIco, IDX_IL_TREE_REL_TYPE, false);
	if(-1!=m_iEffIco)SetItemImage(m_iEffIco, IDX_IL_TREE_EFF, false);
	
	SetItemImage(ico, IDX_IL_TREE_ITEM);
	
	m_fictive_item = m_tree->InsertItem(_T("fictive"), 0, 0, m_item);
	
	return true;	
}

bool CSelectInstanceTreeItemEx::IsNeedToShow(CaplInstance *ciRel)
{
	
	// проверяем, нужно ли отображать данный вид документа для пользователя с его ролями
	if(!m_api->m_data.IsAdmin())
	{	
		if(m_inst->GetAccessmode() > aplRO) return false;

		bool bCreate = false;
		aplExtent aeExt, aeDT;
		CaplInstance *cit=m_api->m_appr_mgr.GetCurrentPerson();
		
		// ищем у пользователя список ролей
		m_api->m_data.GetAttr(cit, m_api->m_appr_mgr.a_pers_roles, aeExt);			
		// ищем вид документа
		if(m_api->m_data.IsKindOf(m_inst, m_api->m_doc_mgr.e_apl_doc_rev))
		{
			m_api->m_data.GetAttr(m_inst, m_api->m_doc_mgr.a_apl_doc_rev_doc, cit); 
			m_api->m_data.GetAttr(cit, m_api->m_doc_mgr.a_doc_kind, cit);
		}
		else
		{
			m_api->m_data.GetAttr(m_inst, m_api->m_doc_mgr.a_doc_kind, cit);
		}				
				
		if(cit)
		{
			for(int i=0; i<aeExt.GetSize(); i++) 
			{
				m_api->m_data.GetAttr(aeExt[i], m_api->m_appr_mgr.a_po_role_document_types, aeDT);
				if(!aeDT.GetSize()) {bCreate=true; break;}
				
				for(int j=0; j<aeDT.GetSize(); j++)
					if(aeDT[j] == cit) bCreate = true;					
			}										
			
			if(!bCreate) return false;
		}								
	}

	// если это исходный документ, то нужно проверить: а можно ли его показывать
	CString sType;
	if(ciRel && m_api->m_data.IsKindOf(m_inst, m_api->m_doc_mgr.e_doc) && !m_nShowBaseDoc)
	{
		m_api->m_data.GetAttr(ciRel, m_api->m_doc_mgr.a_apl_doc_ref_type, sType);
		if(sType == _T("depend")) return false;
	}
		
	return true;
}

CSelectInstanceTreeItem* CSelectInstanceTreeItemEx::InsertInstInTree(CaplInstance* inst, CaplInstance* rel, UINT iRelIco, UINT iEffIco)
{
	if(!inst) return NULL;
	if(!inst->GetType()) return NULL;
	if(inst->GetAccessmode()>aplRO) return NULL;
	
	CSelectInstanceTreeItemEx* new_item= NULL;
	
	if(-1==m_relatedInstances.Find(inst) || (rel && -1==m_relatedInstances.Find(rel)))
	{
		new_item= new CSelectInstanceTreeItemEx(m_api, m_ToolTipTree, m_ItemsArray, inst, rel);
		
		new_item->m_iRelIco= iRelIco;
		new_item->m_iEffIco= iEffIco;
		new_item->m_nShowBaseDoc = m_nShowBaseDoc;
		new_item->m_ciParent = m_inst;
		if(inst&&m_inst&&m_api->m_data.IsKindOf(inst,m_api->m_prd_mgr.e_pdf)&&m_api->m_data.IsKindOfBN(m_inst,_T("apl_task")))
			m_api->m_data.GetAttr(inst,m_api->m_prd_mgr.a_apl_pdf_locker,new_item->m_ciParent);

		m_relatedInstances.Add(inst);
		if(rel)m_relatedInstances.Add(rel);
		m_relatedItems.Add((long)inst, (long)new_item);

		if(!new_item->CreateTreeItem(m_item, rel))
		{
			if(rel) m_relatedInstances.Remove(m_relatedInstances.Find(rel));
			m_relatedItems.Remove(m_relatedItems.FindByIn(long(inst)));
		}				
	}

	return new_item;
}

int CALLBACK CSelectInstanceTreeItemEx::CompareHtreeItem(LPARAM lParam1, LPARAM lParam2,LPARAM lParamSort)
{
	if(lParam1==0) return 0;
	if(lParam2==0) return 0;

	CaplTreeListCtrl::CTLItem *pTLitem1 = ((CaplTreeListCtrl::CTLItem*)lParam1);
	CaplTreeListCtrl::CTLItem *pTLitem2 = ((CaplTreeListCtrl::CTLItem*)lParam2);

	CSelectInstanceTreeItemEx *pItem1 = (CSelectInstanceTreeItemEx*)pTLitem1->itemData;
	CSelectInstanceTreeItemEx *pItem2 = (CSelectInstanceTreeItemEx*)pTLitem2->itemData;

	HTREEITEM item1=pItem1->m_item;
	HTREEITEM item2=pItem2->m_item;

	int img1,img2,img0;
	pItem1->m_tree->GetItemImage(item1,img1,img0);
	pItem1->m_tree->GetItemImage(item2,img2,img0);

	CaplAPI* api = pItem1->m_api;

	int rel1=0,rel2=0;
	int eff1=0,eff2=0;
	int state1=0,state2=0;
	
	CaplTreeItemData *itemdata1=(CaplTreeItemData*) pItem1;
	if(itemdata1!=0)
	{
		if(itemdata1->icons[IDX_IL_TREE_ITEM]>0)
			img1=itemdata1->icons[IDX_IL_TREE_ITEM];
		if(itemdata1->icons[IDX_IL_TREE_REL_TYPE]>=0)
			rel1=itemdata1->icons[IDX_IL_TREE_REL_TYPE];
		if(itemdata1->icons[IDX_IL_TREE_EFF]>=0)
			eff1=itemdata1->icons[IDX_IL_TREE_EFF];
		if(itemdata1->icons[IDX_IL_TREE_STATE]>=0)
			state1=itemdata1->icons[IDX_IL_TREE_STATE];
	}
	
	CaplTreeItemData *itemdata2=(CaplTreeItemData*) pItem2;
	if(itemdata2!=0)
	{
		if(itemdata2->icons[IDX_IL_TREE_ITEM]>0)
			img2=itemdata2->icons[IDX_IL_TREE_ITEM];
		if(itemdata2->icons[IDX_IL_TREE_REL_TYPE]>=0)
			rel2=itemdata2->icons[IDX_IL_TREE_REL_TYPE];
		if(itemdata2->icons[IDX_IL_TREE_EFF]>=0)
			eff2=itemdata2->icons[IDX_IL_TREE_EFF];
		if(itemdata2->icons[IDX_IL_TREE_STATE]>=0)
			state2=itemdata2->icons[IDX_IL_TREE_STATE];
	}
	
	int compare = api->aplCompareItemsImage(img1, img2);
	
	if(compare==0)
	{
		if(rel1<rel2) return -1;
		if(rel1>rel2) return  1;
		if(eff1>eff2) return 1;
		if(eff1<eff2) return -1;
		if(state1<state2) return -1;
		if(state1>state2) return 1;
		return (pItem1->m_ToolTipTree->GetItemText(item1)).Compare(pItem1->m_ToolTipTree->GetItemText(item2));
	}
	else
	{
		return compare;
	}
	return 0;
}

void CSelectInstanceTreeItemEx::Sort(bool bRefreshParent/* =false */)
{
	if(m_tree==0) return;
	if(m_item==0) return;

	if(bRefreshParent)
	{
		if (m_tree->ItemHasChildren(m_item))
		{
		   HTREEITEM hChildItem = m_tree->GetChildItem(m_item);

		   while (hChildItem != NULL)
		   {
				CSelectInstanceTreeItemEx *item=(CSelectInstanceTreeItemEx*)m_tree->GetItemData(hChildItem);
				if(item!=0)item->RefreshItem();
				hChildItem = m_tree->GetNextItem(hChildItem, TVGN_NEXT);
		   }
		}
	}
	
	TVSORTCB sortcb;
	sortcb.hParent=m_item;
	sortcb.lpfnCompare=CompareHtreeItem;
	sortcb.lParam=1;
	m_tree->SortChildrenCB(&sortcb);
}

void CSelectInstanceTreeItemEx::CollapseItem(bool bInsertFictive/* = true */)
{
	while(1)
	{
		HTREEITEM item1=m_tree->GetChildItem(m_item);
		if(item1==0) break;
		CSelectInstanceTreeItemEx *item=(CSelectInstanceTreeItemEx*)m_ToolTipTree->GetItemData(item1);
		if(item!=0)
		{
			int nFindItem = m_ItemsArray->Find(item);
			m_ItemsArray->Remove(nFindItem);			
		}			
		else
		{
			CaplTreeListCtrl::CTLItem *pTLItem = (CaplTreeListCtrl::CTLItem*)m_ToolTipTree->GetTLItem(item1);
			delete pTLItem;
			m_tree->DeleteItem(item1);
		}
	
	}
	
	m_relatedItems.Clear();
	m_relatedInstances.Clear();

	m_bExpanding= false;
	m_fictive_item=m_tree->InsertItem(_T("fictive"),0,0,m_item);	
}


void CSelectInstanceTreeItemEx::FillRevisionTree(HTREEITEM item, aplExtent &revExt)
{
	if(!item) return;
	CSelectInstanceTreeItemEx* treeItem= (CSelectInstanceTreeItemEx*)m_ToolTipTree->GetItemData(item);
	if(treeItem==NULL) return;
	
	CaplInstance* inst= NULL, *obj= NULL, *act= NULL;

	for(int i= 0; i<revExt.GetSize(); i++)
	{
		if(revExt[i]==0){revExt.Remove(i); i--; continue;}
		if(revExt[i]->GetAccessmode()==aplNO){revExt.Remove(i); i--; continue;}
		
		apidata.GetAttr(revExt[i], m_ItemVertionInfo._VerBaseAttr, inst);
		
		if(inst==treeItem->m_inst)
		{
			apidata.GetAttr(revExt[i], m_ItemVertionInfo._VerObjAttr, obj);
			apidata.GetAttr(obj, m_ItemVertionInfo._ObjActiveVerAttr, act);
			UINT ico= ICO_REL_VER;
			if(act==revExt[i])ico= ICO_REL_ACTIVE_VER;
			
			CSelectInstanceTreeItem* newItem= treeItem->InsertInstInTree(revExt[i], NULL, ico);

			FillRevisionTree(newItem->m_item, revExt);
			revExt.Remove(i);
			i--;
		}
	}
	
	treeItem->MyExpand();
}

void CSelectInstanceTreeItemEx::ShowRelatedItems()
{
	CaplAttr *related_item = NULL;
	CaplInstance *cit = NULL, *ciRed = NULL;
	aplExtent aeSubRelItems;
	aplExtent subItems;
	subItems.Unique= false;
	m_bExpanding= true;
		
	UINT iRelIco= -1;
	if(m_inst) GetRelatedInstances(subItems, aeSubRelItems, iRelIco, &related_item);
	else GetRelatedInstancesBN(subItems);

	m_nShowBaseDoc = m_api->m_options_mgr.GetIntOptionValueBN( APL_NO_T("Настройки АРМ\\Отображать исходные документы"), 0);
	
	if(!related_item)
	{
		for(int i= 0; i<subItems.GetSize(); i++)
		{
			if(!subItems[i]) continue;
			if(subItems[i]->GetAccessmode()>aplRO) continue;
			 
			InsertInstInTree(subItems[i], NULL, iRelIco);    
		}
	}
	else
	{
		for(int i= 0; i<aeSubRelItems.GetSize(); i++)
		{
			if(!aeSubRelItems[i]) continue;
			if(!subItems[i]) continue;
			if(aeSubRelItems[i]->GetAccessmode()>aplRO) continue;			
			if(subItems[i]->GetAccessmode()>aplRO) continue;
						
			InsertInstInTree(subItems[i], aeSubRelItems[i], iRelIco);
		}		
	}

	/*Если в состов изделия что-то входит несколько раз, то отображается только одно из них...*/
// 	for(int i= 0; i<subItems.GetSize(); i++)
// 	{
// 		if(subItems[i]->GetAccessmode()>aplRO) continue;
// 		cit = aeSubRelItems[i];
// 		
// 		// если изделие, то нужно находить соответствие
// 		if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_pdf))
// 		{
// 			for(int j=0; j<aeSubRelItems.GetSize(); j++)
// 			{
// 				m_api->m_data.GetAttr(aeSubRelItems[j], m_api->m_prd_mgr.a_pdr_r_ted, ciRed);
// 				if(ciRed == subItems[i]) 
// 				{
// 					cit=aeSubRelItems[j]; 
// 					break;
// 				}
// 			}
// 		}
// 
// 		// вставляем новый элемент
// 		InsertInstInTree(subItems[i], cit, iRelIco);
// 	}

	ShowExpandOptions();	
}

bool CSelectInstanceTreeItemEx::MyExpand()
{
	UINT st= m_ToolTipTree->GetItemState(m_item, TVIS_EXPANDED);
	if((st&TVIS_EXPANDED)<=0)
		m_ToolTipTree->SetItemState(m_item, TVIS_EXPANDED, TVIS_EXPANDEDONCE|TVIS_EXPANDED);
	bool ret=Expand(2);
	if(ret)Sort();
	return ret;	
}

int CSelectInstanceTreeItemEx::GetRelatedInstances(aplExtent &subItems, aplExtent& subRels, UINT& iRelIco, CaplAttr** related_inst/* = NULL */)
{
	aplExtent ext, rels;
	aplExtent aeBuf;
	aplExtent aeChanges;
	int i;

	iRelIco= -1;

	if(m_inst)
	{
		/*версия изделия*/
		if(m_api->m_data.IsKindOf(m_inst, m_api->m_prd_mgr.e_pdf))
		{
			aplExtent aeRels, aeItems;
			CaplInstance *cit = NULL;
			m_api->m_prd_mgr.LoadAllSubProduct(NULL, NULL, m_inst, aeRels, aeItems);

			// отфильровываем состав на текущую дату
			m_api->m_prd_mgr.FilterlByDate(aeRels, COleDateTime::GetCurrentTime(), subRels);
			aeRels.Clear();aeRels.Append(subRels);subRels.Clear();
			m_api->m_prd_mgr.FilterlByLastSN(aeRels, subRels);

			if(m_bFilterSubProduct)
			{
				aeRels.Clear();
				aeRels.Append(subRels);
				subRels.Clear();

				aeItems.Clear();
				aeItems.Add(m_inst);

				if (m_api->m_change_mgr.GetAllChanges(m_inst,aeChanges,true))
				{
					if (aeChanges.Size)
					{
						for(i=0;i<aeChanges.Size;i++)
						{
							m_api->m_prd_mgr.FilterByChange(aeRels,aeChanges[i],aeBuf,&aeItems,true);
							aeRels.Clear();
							aeRels.Append(aeBuf);
						}
					}
					subRels.Clear();
					subRels.Append(aeRels);
				}
			}

			aeItems.Clear();

			for(int i=0; i<subRels.Size; ++i)
			{
				if(m_api->m_data.IsKindOf(subRels[i], m_api->m_prd_mgr.e_apl_qacu))
					m_api->m_data.GetAttr(subRels[i], m_api->m_prd_mgr.a_pdr_r_ted, cit);
				else if(m_api->m_data.IsKindOf(subRels[i], m_api->m_change_mgr.e_psc))
				{
					m_api->m_data.GetAttr(subRels[i], m_api->m_change_mgr.a_psc_changing_product, cit);
					aeItems.Add(cit);
				}
				else cit= NULL;

				subItems.Add(cit);
			}
			if(aeItems.GetSize()) m_api->LoadExtentInfo(aeItems);
			if(related_inst)*related_inst= m_api->m_prd_mgr.a_pdr_r_ted;
		}
		else
			return CSelectInstanceTreeItem::GetRelatedInstances(subItems,subRels,iRelIco,related_inst);
	}
	return subItems.GetSize();
}

/************************************************************************/
/*                                                                      */
/************************************************************************/


/////////////////////////////////////////////////////////////////////////////
// CSelectInstanceView

aplTIArray CSelectInstanceView::m_allItems;
aplTIArray CSelectInstanceView::m_rootItems;
CSelectInstanceTreeItem* CSelectInstanceView::m_lastSelectedItem= NULL;

IMPLEMENT_DYNCREATE(CSelectInstanceView, CaplTreeView)

CSelectInstanceView::CSelectInstanceView()
{
	m_api= NULL;
	m_selectedInstance= NULL;
	m_BaseItems= NULL;

	m_selectMode= 0;
	m_enableBtn= NULL;
	m_pDlg= NULL;
	m_rootItems.AutoKillReference= false;
}

CSelectInstanceView::~CSelectInstanceView()
{
}


BEGIN_MESSAGE_MAP(CSelectInstanceView, CaplTreeView)
	//{{AFX_MSG_MAP(CSelectInstanceView)
	ON_NOTIFY_REFLECT(TVN_ITEMEXPANDING, OnItemexpanding)
	ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnItemchanged)
	ON_WM_CREATE()
	ON_WM_DESTROY()
	ON_WM_LBUTTONDBLCLK()
	ON_COMMAND(ID_SI_SHOW_ALL_DOCS, OnShowAllDocs)
	ON_COMMAND(ID_SI_SHOW_ALL_APPROVAL, OnShowAllApproval)
	ON_COMMAND(ID_SI_SHOW_ALL_BP, OnShowAllBp)
	ON_COMMAND(ID_SI_SHOW_ALL_BP_INST, OnShowAllBpInst)
	ON_COMMAND(ID_SI_SHOW_ALL_BP_RESOURCE, OnShowAllBpResource)
	ON_COMMAND(ID_SI_SHOW_ALL_CHARACTERISTIC, OnShowAllCharacteristic)
	ON_COMMAND(ID_SI_SHOW_ALL_PRD_INST, OnShowAllPrdInst)
	ON_COMMAND(ID_SI_SHOW_ALL_VERSION, OnShowAllVersion)
	ON_COMMAND(ID_SI_SHOW_ALL_USAGE, OnShowAllUsage)
	ON_COMMAND(ID_SI_SHOW_ALL_LOT, OnShowAllLot)
	ON_COMMAND(ID_SI_SHOW_EXPAND_OPTIONS, OnShowExpandOptions)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_DOCS, OnUpdateSiShowAllDocs)
	ON_COMMAND(ID_SI_PRODUCT_SHOW_ALL_ZAGOTOV, OnSiProductShowAllZagotov)
	ON_COMMAND(ID_SI_FIND, OnSiFind)
	ON_COMMAND(ID_BUTTON33091, OnButton61864)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_CHARACTERISTIC, OnUpdateSiShowAllCharacteristic)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_APPROVAL, OnUpdateSiShowAllApproval)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_BP, OnUpdateSiShowAllBp)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_LOT, OnUpdateSiShowAllLot)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_PRD_INST, OnUpdateSiShowAllPrdInst)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_BP_INST, OnUpdateSiShowAllBpInst)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_BP_RESOURCE, OnUpdateSiShowAllBpResource)
	ON_UPDATE_COMMAND_UI(ID_SI_PRODUCT_SHOW_ALL_ZAGOTOV, OnUpdateSiProductShowAllZagotov)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_VERSION, OnUpdateSiShowAllVersion)
	ON_UPDATE_COMMAND_UI(ID_SI_SHOW_ALL_USAGE, OnUpdateSiShowAllUsage)
	ON_COMMAND(ID_SI_CREATE_FOLDER, OnSiCreateFolder)
	ON_UPDATE_COMMAND_UI(ID_SI_CREATE_FOLDER, OnUpdateSiCreateFolder)
	ON_COMMAND(ID_SI_VIEW_DOCUMENT, OnSiViewDocument)
	ON_UPDATE_COMMAND_UI(ID_SI_VIEW_DOCUMENT, OnUpdateSiViewDocument)
	ON_WM_LBUTTONDOWN()
	ON_UPDATE_COMMAND_UI(ID_SI_FIND, OnUpdateSiFind)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSelectInstanceView drawing

void CSelectInstanceView::OnDraw(CDC* pDC)
{
//	CaplTreeView::OnDraw(pDC);
}

/////////////////////////////////////////////////////////////////////////////
// CSelectInstanceView diagnostics

#ifdef _DEBUG
void CSelectInstanceView::AssertValid() const
{
	CaplTreeView::AssertValid();
}

void CSelectInstanceView::Dump(CDumpContext& dc) const
{
	CaplTreeView::Dump(dc);
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CSelectInstanceView message handlers
bool CSelectInstanceView::IsCanReturnInstance(CaplInstance *inst)
{
	if (!inst) 
		return false;
	
	if (!inst->GetType())
		return false;

	// папка
	if (apidata.IsKindOf(inst,m_api->m_folder_mgr.e_folder))
	{
		if ((m_selectMode & APL_MODE_SELECT_FOLDER) > 0)
			return true;
	}
	// категория
	else if (apidata.IsKindOf(inst,m_api->m_categ_mgr.e_categ))
	{
		if ((m_selectMode & APL_MODE_SELECT_CATEGORY) > 0)
			return true;
	}
	// изделие
	else if (apidata.IsKindOf(inst,m_api->m_prd_mgr.e_prd))
	{
		if ((m_selectMode & APL_MODE_SELECT_PRD) > 0)
			return true;
	}
	// версия изделия
	else if (apidata.IsKindOf(inst,m_api->m_prd_mgr.e_pdf))
	{
		if ((m_selectMode & APL_MODE_SELECT_PDF) > 0)
			return true;
	}
	// документ
	else if (apidata.IsKindOf(inst,m_api->m_doc_mgr.e_doc))
	{
		if ((m_selectMode & APL_MODE_SELECT_DOC) > 0)
			return true;
	}
	// заказ-наряд
	else if (m_api->m_data.IsKindOf(inst, m_api->m_doc_mgr.e_doc_copy_order))
	{
		if ((m_selectMode & APL_MODE_SELECT_ORDER) > 0)
			return true;		
	}
	// значение хар-ки
	else if (apidata.IsKindOf(inst,m_api->m_charact_mgr.e_apl_charact_value))
	{
		if ((m_selectMode & APL_MODE_SELECT_CHARACT) > 0)
			return true;
	}
	// версия хар-ки
	else if (apidata.IsKindOf(inst,m_api->m_charact_mgr.e_apl_charact_value_ver))
	{
		if ((m_selectMode & APL_MODE_SELECT_DOC_REVISION) > 0)
			return true;

		if ((m_selectMode & APL_MODE_SELECT_CHARACT_REVISION) > 0)
			return true;
	}
	// бизнес-процесс
	else if(apidata.IsKindOf(inst,m_api->m_bp_mgr.e_bp))
	{
		if ((m_selectMode & APL_MODE_SELECT_BP) > 0)
			return true;
	}
	// ресурс
	else if(apidata.IsKindOf(inst,m_api->m_bp_mgr.e_bp_res))
	{
		if ((m_selectMode & APL_MODE_SELECT_BP_RES) > 0)
			return true;
	}	
	// экземпляр бизнес-процесса
	else if (apidata.IsKindOf(inst,m_api->m_bp_mgr.e_apl_bp_inst))
	{
		if ((m_selectMode & APL_MODE_SELECT_BPINST) > 0)
			return true;
	}
	// неисправность
	else if (m_api->m_expl_mgr && apidata.IsKindOf(inst,m_api->m_expl_mgr->e_apl_refusal))
	{
		if ((m_selectMode & APL_MODE_SELECT_BPINST) > 0)
			return true;
	}
	else if (apidata.IsKindOf(inst,m_api->m_bp_mgr.e_apl_bp_ver))
	{
		if ((m_selectMode & APL_MODE_SELECT_BP_REVISION) > 0)
			return true;
	}
	else if (apidata.IsKindOf(inst, m_api->m_doc_mgr.e_apl_doc_rev))
	{
		if ((m_selectMode & APL_MODE_SELECT_DOC_REVISION) > 0)
			return true;		
	}
	else if (apidata.IsKindOf(inst, m_api->m_prd_inst_mgr.e_lot))
	{
		if ((m_selectMode & APL_MODE_SELECT_LOT) > 0)
			return true;
	}
	else if (apidata.IsKindOf(inst, m_api->m_prd_inst_mgr.e_prd_inst))
	{
		if ((m_selectMode & APL_MODE_SELECT_PRDINST) > 0)
			return true;
	}
	else if (apidata.IsKindOf(inst, m_api->m_appr_mgr.e_org))
	{
		if ((m_selectMode & APL_MODE_SELECT_ORG) > 0)
			return true;
	}
	else if (apidata.IsKindOf(inst, m_api->m_appr_mgr.e_person))
	{
		if ((m_selectMode & APL_MODE_SELECT_PERSON) > 0)
			return true;
	}
	else if (apidata.IsKindOf(inst, m_api->m_appr_mgr.e_official))
	{
		if ((m_selectMode & APL_MODE_SELECT_OFFICIAL) > 0)
			return true;		
	}
	else if (apidata.IsKindOf(inst, m_api->m_appr_mgr.e_pers_org))
	{
		if ((m_selectMode & APL_MODE_SELECT_PERSORG) > 0)
			return true;
		else if ((m_selectMode & APL_MODE_SELECT_PERSON) > 0)
			return true;
	}
	else if (m_api->m_data.IsKindOf(inst, m_api->m_change_mgr.e_chng))
	{
		if ((m_selectMode & APL_MODE_SELECT_CHANGE) > 0)
			return true;
	}
	else if (m_api->m_data.IsKindOf(inst, m_api->m_project_mgr->e_project))
	{
		if ((m_selectMode & APL_MODE_SELECT_PROJECT) > 0)
			return true;		
	}
	else if (m_api->m_data.IsKindOf(inst, m_api->m_classifier_mgr.e_apl_classifier_system))
	{
		if ((m_selectMode & APL_MODE_SELECT_CLASSIF_SYSTEM) > 0)
			return true;		
	}
	else if (m_api->m_data.IsKindOf(inst, m_api->m_classifier_mgr.e_apl_classifier_level))
	{
		if ((m_selectMode & APL_MODE_SELECT_CLASSIF_ELEMENT) > 0)
			return true;		
	}	
	else if (m_api->m_data.IsKindOf(inst, m_api->m_req_mgr.e_requirement))
	{
		if ((m_selectMode & APL_MODE_SELECT_REQUIREMENT) > 0)
			return true;		
	}	

	return false;
}

bool CSelectInstanceView::GetSelectedItems(aplExtent &ext)
{
	ext.Clear();

	int i;
	HTREEITEM ht;
	CaplBaseTreeItem* item;
	
	for(i=0; i<GetCountOfSelect(); i++)
	{
		ht = GetSelectedInArray(i);
		if(ht==NULL) continue;
		item = (CaplBaseTreeItem*)GetTreeCtrl().GetItemData(ht);
		if(item->m_inst && IsCanReturnInstance(item->m_inst)) 
		{
			ext.Add(item->m_inst);
		}
	}

	return ext.Size>0;
}

bool CSelectInstanceView::CheckAndRestore()
{
	if(!m_rootItems.Size || (m_selectMode & APL_MODE_NO_RESTORE)) return false;

	int i,j;
	/*Проверяем, совпадают ли корневые items и восстанавливаем дерево*/
	if(m_BaseItems)//ищем, все ли m_BaseItems есть... могут быть варианты
	{
		bool bFind= true;

		for(i=0; i<m_BaseItems->GetSize() && bFind; i++)
		{
			bFind= false;
			for(j= 0; j<m_rootItems.Size && !bFind; j++)
			{
				if(((CSelectInstanceTreeItem*)m_rootItems[j])->m_inst==m_BaseItems->GetAt(i))
					bFind= true;
			}
		}

		if(!bFind)
			return false;
	}
	else// все должны быть корневые
	{
		for(i= 0; i<m_rootItems.Size; i++)
		{
			if(((CSelectInstanceTreeItem*)m_rootItems[i])->m_inst!=NULL)
				return false;
		}
	}

	CTreeCtrl* tree= &GetTreeCtrl();

	//восстановление одной ветки
	for(i= 0; i<m_rootItems.Size; i++)
	{
		((CSelectInstanceTreeItem*)m_rootItems[i])->RestoreTreeItem(tree, TVI_ROOT);
	}
	
	if (m_lastSelectedItem)
	{
		tree->SelectItem(m_lastSelectedItem->m_item);
		tree->SelectDropTarget(m_lastSelectedItem->m_item);
	}

	return true;
}

void CSelectInstanceView::ClearRestoreData()
{
	m_lastSelectedItem= NULL;

	m_allItems.Clear();
	
	m_rootItems.AutoKillReference= false;
	m_rootItems.Clear();
}

void CSelectInstanceView::OnInitialUpdate() 
{
	CaplTreeView::OnInitialUpdate();

	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0
	
	POSITION pos=0;
	if(0!=app) pos= app->GetFirstDocTemplatePosition();
	if(pos)
	{
		CDocTemplate* docTmpl=0;
		if(0!=app) app->GetNextDocTemplate(pos);
		if(docTmpl)
		{
			pos= docTmpl->GetFirstDocPosition();
			if(pos) 
			{
				CDocument* doc= docTmpl->GetNextDoc(pos);
				if(doc)
				{
//					doc->AddView(this);
				}
			}
		}
	}
	
	CaplBaseTreeItem::m_ExpandOption.InitializeTreeExpandOptions();
	
	CTreeCtrl* tree= &GetTreeCtrl();

	tree->SetImageList(aplGetInstImageList(), TVSIL_NORMAL);	
	SetImageList(aplGetRelImageList(),IDX_IL_TREE_REL_TYPE);	
	SetImageList(aplGetEffImageList(),IDX_IL_TREE_EFF);
	SetImageList(aplGetInstImageList(),IDX_IL_TREE_ITEM);
	SetImageList(aplGetStateImageList(),IDX_IL_TREE_STATE);
	SetImageList(aplGetObjStateImageList(),IDX_IL_TREE_OBJ_STATE);
	SetImageList(aplGetItemSubtypeImageList(),IDX_IL_TREE_ITEM_SUBTYPE);

	if(m_api /*&& m_api->m_data.IsConnected()*/)
	{
		if(!CheckAndRestore())
		{
			ClearRestoreData();

			if(m_BaseItems && m_BaseItems->GetSize())
			{
				for(int i= 0; i<m_BaseItems->GetSize(); i++)
				{
					if(!m_BaseItems->GetAt(i)) continue;
					if(m_BaseItems->GetAt(i)->GetAccessmode()>aplRO) continue;
					
					CSelectInstanceTreeItem* new_item= new CSelectInstanceTreeItem(
						m_api, tree, &m_allItems, m_BaseItems->GetAt(i));
					new_item->CreateTreeItem(TVI_ROOT);
					m_rootItems.Add(new_item);
					if(m_selectMode & APL_MODE_NO_RESTORE) new_item->MyExpand();
				}
			}
			else
			{
				CSelectInstanceTreeItem * pTaskItems = new CSelectInstanceTreeItem(
					m_api, tree, &m_allItems, 0, 0,  APL_T("Мои задания"));
				pTaskItems->CreateTreeItem(TVI_ROOT);
				m_rootItems.Add(pTaskItems);

				CSelectInstanceTreeItem * pRootPerFolder = new CSelectInstanceTreeItem(
					m_api, tree, &m_allItems, 0, 0,  APL_T("Личные папки"));
				pRootPerFolder->CreateTreeItem(TVI_ROOT);
				m_rootItems.Add(pRootPerFolder);
				
				CSelectInstanceTreeItem * pRootFolder = new CSelectInstanceTreeItem(
					m_api, tree, &m_allItems, 0, 0,  APL_T("Папки"));
				pRootFolder->CreateTreeItem(TVI_ROOT);
				m_rootItems.Add(pRootFolder);


				if (m_api->m_options_mgr.CheckInstallCode(_T("KVZ")))
				{
					CSelectInstanceTreeItem * pCustomerFolder = new CSelectInstanceTreeItem(
						m_api, tree, &m_allItems, 0, 0,  APL_T("Заказ-наряды и акты об уничтожении"));
					pCustomerFolder->CreateTreeItem(TVI_ROOT);
					m_rootItems.Add(pCustomerFolder);
				}
				
				/*
				CSelectInstanceTreeItem *categ_item= new CSelectInstanceTreeItem(
					m_api, tree, &m_allItems, 0, 0,  APL_T("Категории"));
				categ_item->CreateTreeItem(TVI_ROOT);
				m_rootItems.Add(categ_item);
				*/
				
				CSelectInstanceTreeItem *classif_item= new CSelectInstanceTreeItem(
					m_api, tree, &m_allItems, 0, 0,  APL_T("Справочники"));
				classif_item->CreateTreeItem(TVI_ROOT);
				m_rootItems.Add(classif_item);
				
				CSelectInstanceTreeItem *org = new CSelectInstanceTreeItem(
					m_api, tree, &m_allItems, 0, 0,  APL_T("Организационная структура"));
				org->CreateTreeItem(TVI_ROOT);
				m_rootItems.Add(org);
				
				CSelectInstanceTreeItem *queries = new CSelectInstanceTreeItem(
					m_api, tree, &m_allItems, 0, 0,  APL_T("Поиск в БД"));
				queries->CreateTreeItem(TVI_ROOT);
				m_rootItems.Add(queries);
			}
		}

	}

	GetParentFrame()->SendMessageToDescendants(WM_IDLEUPDATECMDUI,
				(WPARAM)TRUE, 0, TRUE, TRUE);	
}

int CSelectInstanceView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (CaplTreeView::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	return 0;
}

void CSelectInstanceView::OnItemchanged(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	
	HTREEITEM cur_item= pNMTreeView->itemNew.hItem;
	CSelectInstanceTreeItem *item=(CSelectInstanceTreeItem*)(GetTreeCtrl().GetItemData(cur_item));
	
	if(item)
		CSelectInstanceView::m_lastSelectedItem= item;
	else
		CSelectInstanceView::m_lastSelectedItem= NULL;

	GetParentFrame()->SendMessageToDescendants(WM_IDLEUPDATECMDUI,
				(WPARAM)TRUE, 0, TRUE, TRUE);	
	*pResult = 0;
}

void CSelectInstanceView::OnItemexpanding(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	HTREEITEM cur_item= pNMTreeView->itemNew.hItem;
	CSelectInstanceTreeItem *item=(CSelectInstanceTreeItem*)(GetTreeCtrl().GetItemData(cur_item));
	if(item!=0)
	{
		if(item->m_inst && item->m_inst->GetType())
		{
			if(m_api->m_data.IsKindOf(item->m_inst, m_api->m_doc_mgr.e_doc))
			{
				if(m_selectMode & APL_MODE_HIDE_ASSOCIATED_DOCS)
				{
					item->m_bShowRelated=false;
				}
				
			}
		}
		item->Expand(pNMTreeView->action);	
	}
	*pResult = 0;
}

void CSelectInstanceView::OnDestroy() 
{
//	m_allItems.Clear();
	for(int i= 0; i<m_allItems.GetSize(); i++)
	{
		((CSelectInstanceTreeItem*)m_allItems[i])->m_tree= NULL;
		((CSelectInstanceTreeItem*)m_allItems[i])->m_item= 0;
	}
	CaplTreeView::OnDestroy();
}

void CSelectInstanceView::OnLButtonDown(UINT nFlags, CPoint point) 
{
	if(!m_bMultiSelect)
	{
		UINT flag=TVHT_ONITEM|TVHT_ONITEMRIGHT;
		HTREEITEM hItem= GetTreeCtrl().HitTest(point, &flag);
		CaplInstance* inst= NULL;
		if(hItem)
		{
			CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
			if (item) inst= item->m_inst;
		}

		if (IsCanReturnInstance(inst)) 
		{
			if (m_enableBtn)m_enableBtn->EnableWindow(TRUE);
			m_selectedInstance = inst;
		}
		else
		{
			if (m_enableBtn)m_enableBtn->EnableWindow(FALSE);
			m_selectedInstance= NULL;
		}
	}

	CaplTreeView::OnLButtonDown(nFlags, point);

	if(m_bMultiSelect)
	{
		//Проверяем есть ли среди выделенных объектов доступного типа
		BOOL bEnable = FALSE;
		int i;
		HTREEITEM ht;
		CSelectInstanceTreeItem* item;

		for(i=0; i<GetCountOfSelect(); i++)
		{
			ht = GetSelectedInArray(i);
			if(ht==NULL) continue;
			item = (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(ht);
			if(item && item->m_inst && IsCanReturnInstance(item->m_inst)) 
			{
				m_selectedInstance= item->m_inst;
				bEnable = TRUE;
				break;
			}
		}

		m_enableBtn->EnableWindow(bEnable);
	}
}

void CSelectInstanceView::OnLButtonDblClk(UINT nFlags, CPoint point) 
{
	UINT flag=TVHT_ONITEM|TVHT_ONITEMRIGHT;
	HTREEITEM hItem= GetTreeCtrl().HitTest(point, &flag);
	CSelectInstanceTreeItem* item= NULL;
	if(hItem) item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	CaplInstance* inst= NULL;
	if(item) inst= item->m_inst;

	if (inst && inst->GetType())
	{
		if(m_api->m_data.IsKindOf(inst, m_api->m_query_mgr.e_apl_query))
		{
			item->Find(inst, hItem);
			return;
		}
		else
		{
			if(m_pDlg && (m_selectMode&APL_MODE_SELECT_MULTY)==0 && (m_selectMode&APL_MODE_SELECT_DBLCLICK)>0)
			{
				m_pDlg->OnOK();
				return;
			}
		}
	}

	CaplTreeView::OnLButtonDblClk(nFlags, point);
}

void CSelectInstanceView::OnShowAllDocs() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;

	item->ShowAllDocs(true);
}

void CSelectInstanceView::OnShowAllApproval() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;

	item->ShowAllApproval(true);	
}

void CSelectInstanceView::OnShowAllBp() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;
	
	if(!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
		return;
	
	item->ShowAllBPs();
}

void CSelectInstanceView::OnShowAllBpInst() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;
	
	item->ShowAllBPInstances();	
}

void CSelectInstanceView::OnShowAllBpResource() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;
	
	if(!m_api->m_data.IsKindOf(item->m_inst,m_api->m_bp_mgr.e_bp) &&
		!m_api->m_data.IsKindOf(item->m_inst,m_api->m_bp_mgr.e_apl_bp_ver) &&
		!m_api->m_data.IsKindOf(item->m_inst,m_api->m_bp_mgr.e_apl_bp_inst))//Экземпляры бизнес процесса
		return;

	item->ShowAllBPResources();
}

void CSelectInstanceView::OnShowAllCharacteristic() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;

	item->ShowAllCharacteristic(true);	
}

void CSelectInstanceView::OnShowAllPrdInst() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;
	
	item->ShowAllPrdInstances();
}

void CSelectInstanceView::OnShowAllVersion() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;

	item->ShowAllVersions();
}

void CSelectInstanceView::OnShowAllUsage() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;

	item->ShowAllUsage();
}


void CSelectInstanceView::OnSiProductShowAllZagotov() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;
	
	if(!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
		return;
	
	item->ShowAllMaters();
}

void CSelectInstanceView::OnShowAllLot() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item) return;
	if	(!item->m_inst)	return;
	if	(!item->m_inst->GetType()) return;
	
	aplExtent ext;
	if(!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
		return;
	
	item->ShowAllLots();
}

void CSelectInstanceView::OnShowExpandOptions() 
{
	CaplBaseTreeItem::m_ExpandOption.EditTreeExpandOptions();
}

void CSelectInstanceView::OnButton61864() 
{
	m_api->m_show.ShowOption();	
}

void CSelectInstanceView::OnSiFind() 
{
	CSelectInstanceTreeItem* item= NULL;
	HTREEITEM hItem= GetTreeCtrl().GetChildItem(TVI_ROOT);
	while(!item)
	{
		if(hItem==0) break;
		if(GetTreeCtrl().GetItemText(hItem)== APL_T("Поиск в БД"))
		{
			item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
			item->Find(0);
		}
		hItem= GetTreeCtrl().GetNextItem(hItem, TVGN_NEXT);
	}
}

void CSelectInstanceView::OnUpdateSiFind(CCmdUI* pCmdUI) 
{
	/*Чтобы пользователи зря не мурыжили кнопочку "Найти" :D*/

	BOOL bCanFind= FALSE;

	HTREEITEM hItem= GetTreeCtrl().GetChildItem(TVI_ROOT);
	while(hItem)
	{
		if(GetTreeCtrl().GetItemText(hItem)== APL_T("Поиск в БД"))
		{
			bCanFind= TRUE;
			break;
		}
		hItem= GetTreeCtrl().GetNextItem(hItem, TVGN_NEXT);
	}

	pCmdUI->Enable(bCanFind);
}

void CSelectInstanceView::OnUpdateSiShowAllDocs(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}

	if(m_api->m_data.IsKindOf(item->m_inst, m_api->m_folder_mgr.e_folder) ||
		m_api->m_data.IsKindOf(item->m_inst, m_api->m_classifier_mgr.e_apl_classifier_system) ||
		m_api->m_data.IsKindOf(item->m_inst, m_api->m_classifier_mgr.e_apl_classifier_level))
	{
		pCmdUI->Enable(FALSE); 
		return;
	}

	pCmdUI->Enable();
}

void CSelectInstanceView::OnUpdateSiShowAllCharacteristic(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}

	if(m_api->m_data.IsKindOf(item->m_inst, m_api->m_folder_mgr.e_folder) ||
		m_api->m_data.IsKindOf(item->m_inst, m_api->m_classifier_mgr.e_apl_classifier_system) ||
		m_api->m_data.IsKindOf(item->m_inst, m_api->m_classifier_mgr.e_apl_classifier_level))
	{
		pCmdUI->Enable(FALSE); 
		return;
	}

	pCmdUI->Enable();	
}

void CSelectInstanceView::OnUpdateSiShowAllApproval(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}
	
	if(m_api->m_data.IsKindOf(item->m_inst, m_api->m_folder_mgr.e_folder) ||
		m_api->m_data.IsKindOf(item->m_inst, m_api->m_classifier_mgr.e_apl_classifier_system) ||
		m_api->m_data.IsKindOf(item->m_inst, m_api->m_classifier_mgr.e_apl_classifier_level) ||
		m_api->m_data.IsKindOf(item->m_inst, m_api->m_query_mgr.e_apl_query))
	{
		pCmdUI->Enable(FALSE); 
		return;
	}

	pCmdUI->Enable();	
}

void CSelectInstanceView::OnUpdateSiShowAllBp(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}

	if(!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
	{pCmdUI->Enable(FALSE); return;}

	pCmdUI->Enable();
}

void CSelectInstanceView::OnUpdateSiShowAllLot(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}

	if(!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
	{pCmdUI->Enable(FALSE); return;}

	pCmdUI->Enable();	
}

void CSelectInstanceView::OnUpdateSiShowAllPrdInst(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}

	if(!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
	{pCmdUI->Enable(FALSE); return;}

	pCmdUI->Enable();	
}

void CSelectInstanceView::OnUpdateSiShowAllBpInst(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}
	
	if(!m_api->m_data.IsKindOf(item->m_inst,m_api->m_bp_mgr.e_bp)//Экземпляры бизнес процесса
	&&
	!m_api->m_data.IsKindOf(item->m_inst,m_api->m_prd_mgr.e_pdf)//Экземпляры бизнес процесса
	&&
	!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_inst_mgr.e_lot)//Экземпляры бизнес процесса
	&&
	!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_inst_mgr.e_prd_inst))
	{pCmdUI->Enable(FALSE); return;}
	
	pCmdUI->Enable();	
}

void CSelectInstanceView::OnUpdateSiShowAllBpResource(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}
	
	//Бизнес процессы и их версии
	//Экземпляры бизнес процесса
	if(!m_api->m_data.IsKindOf(item->m_inst,m_api->m_bp_mgr.e_bp)&&
		!m_api->m_data.IsKindOf(item->m_inst,m_api->m_bp_mgr.e_apl_bp_ver)&&
		!m_api->m_data.IsKindOf(item->m_inst,m_api->m_bp_mgr.e_apl_bp_inst)
		)
	{pCmdUI->Enable(FALSE); return;}
	
	pCmdUI->Enable();
}

void CSelectInstanceView::OnUpdateSiProductShowAllZagotov(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}

	if(!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_mgr.e_pdf))//Экземпляры продукта
	{pCmdUI->Enable(FALSE); return;}

	pCmdUI->Enable();	
}

void CSelectInstanceView::OnUpdateSiShowAllVersion(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}

	if(!m_api->m_data.IsKindOf(item->m_inst, m_api->m_prd_mgr.e_pdf)
	&&
	!m_api->m_data.IsKindOf(item->m_inst, m_api->m_doc_mgr.e_doc)
	&&
	!m_api->m_data.IsKindOf(item->m_inst, m_api->m_bp_mgr.e_bp)
	&&
	!m_api->m_data.IsKindOf(item->m_inst, m_api->m_charact_mgr.e_apl_charact_value))
	{pCmdUI->Enable(FALSE); return;}

	pCmdUI->Enable();
}

void CSelectInstanceView::OnUpdateSiShowAllUsage(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if	(!item)						{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst)				{pCmdUI->Enable(FALSE); return;}
	if	(!item->m_inst->GetType())	{pCmdUI->Enable(FALSE); return;}


	if(m_api->m_data.IsKindOf(item->m_inst, m_api->m_doc_mgr.e_doc) ||
		m_api->m_data.IsKindOf(item->m_inst, m_api->m_doc_mgr.e_apl_doc_rev))
		pCmdUI->Enable(TRUE);
	else
		pCmdUI->Enable(FALSE);
}

void CSelectInstanceView::OnSiCreateFolder() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;
	
	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	CSelectInstanceTreeItem* crItem;

//	if (!item || !item->m_inst || !item->m_inst->GetType()) return;
	if (!item) return;
	if (!item->m_inst && item->m_sName!= APL_T("Папки")) return;

	CaplInstance* folder= m_api->m_folder_mgr.CreateFolder(item->m_inst, _T(""), _T(""));
	CRect rect;

	if (folder)
	{
		item->MyExpand();
		for(int i= 0; i<item->m_ItemsArray->GetSize(); i++)
		{
			crItem= (CSelectInstanceTreeItem*)item->m_ItemsArray->GetAt(i);

			if(folder==crItem->m_inst)
			{
				crItem->m_tree->EnsureVisible(crItem->m_item);
				
				crItem->m_tree->GetItemRect(crItem->m_item, rect, TRUE);
				OnLButtonDown(1, CPoint(rect.left+1, rect.top+1));
				break;
			}
		}
	}
}

void CSelectInstanceView::OnUpdateSiCreateFolder(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if (!item)	{ pCmdUI->Enable(FALSE); return; }

	if (!item->m_inst || !item->m_inst->GetType())
	{
		if (item->m_sName.CompareNoCase( APL_T("Папки")))
			pCmdUI->Enable(FALSE);

		return;
	}

	if(m_api->m_data.IsKindOf(item->m_inst, m_api->m_folder_mgr.e_folder))
		{pCmdUI->Enable(); return;}

	pCmdUI->Enable(FALSE);	
}

void CSelectInstanceView::OnSiViewDocument() 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem) return;
	
	CSelectInstanceTreeItem* item= (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);
	if(!item) return;
	if(!item->m_inst) return;

	m_api->m_doc_mgr.View(item->m_inst);
}

void CSelectInstanceView::OnUpdateSiViewDocument(CCmdUI* pCmdUI) 
{
	HTREEITEM hItem= GetTreeCtrl().GetSelectedItem();
	if(!hItem){pCmdUI->Enable(FALSE); return;}

	CSelectInstanceTreeItem* item = (CSelectInstanceTreeItem*)GetTreeCtrl().GetItemData(hItem);

	if (!item)						{ pCmdUI->Enable(FALSE); return;	}
	if (!item->m_inst)				{ pCmdUI->Enable(FALSE); return;	}
	if (!item->m_inst->GetType())	{ pCmdUI->Enable(FALSE); return;	}

	if(apidata.IsKindOf(item->m_inst, m_api->m_doc_mgr.e_apl_doc))
		{pCmdUI->Enable(); return;}
	if (apidata.IsKindOf(item->m_inst, m_api->m_doc_mgr.e_apl_doc_rev))
		{pCmdUI->Enable(); return;}		

	pCmdUI->Enable(FALSE);	
}
