// aplBPInstTreeItem.cpp: implementation of the CaplBPInstTreeItem class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "aplBPInstTreeItem.h"
#include "aplBPTreeItem.h"
#include "PSMDoc.h"
#include "resource.h"
#include "TabView.h"
#include "aplTreeApprovalItem.h"
#include "aplTreeCharacteristicItem.h"
#include "aplCharacteristicGroupTreeItem.h"
#include "aplDocTreeItem.h"
#include "act_res_treeitem.h"
#include "BPResDlg.h"
#include "TreeProductItem.h"
#include "apl_lot_item.h"
#include "apl_prd_inst_item.h"
#include "aplProjectTreeItem.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CaplBPInstTreeItem::CaplBPInstTreeItem(CTreeCtrl *tree, CPSMDoc *doc,
		CaplInstance *inst)
{
	m_type=APL_TREE_ITEM_BPINST;
	m_tree=tree;
	m_doc=doc;
	m_inst=inst;
	m_index=-1;
	m_folder=0;
	m_classifier=0;
	m_rel=0;
	m_par_bp_inst=0;
	m_subitem=0;
	m_project=0;
	if(doc!=0) 
	{
		doc->m_items.Add(this);
	}
}

CaplBPInstTreeItem::~CaplBPInstTreeItem()
{
	RemoveFromParenContents(m_inst);
}

//****************************************************************
bool CaplBPInstTreeItem::CreateTreeItem(HTREEITEM parent_item)
{
//	_APL_TREE_ITEM_CHEK_PARAM
	CString buf;
	GetName(buf);
	int ico=ICON_BP_INST;
	ico = m_doc->m_api.GetInstIco(m_inst);
	if(m_subitem!=0)
		SetItemImage(ICO_REL_WHERE_USED, IDX_IL_TREE_REL_TYPE);

	InsetItem(buf,ico,parent_item);
	SetItemImage(ico, IDX_IL_TREE_ITEM);

	m_fictive_item=m_tree->InsertItem(_T("fictive"),0,0,m_item);
	return true;
}
//****************************************************************
bool CaplBPInstTreeItem::GetName(CString &name)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	CHECK_GET_NAME(m_inst);

	CString buf;

	name=_T("");

	if(m_index>=0)
		name.Format(_T("%3i"),m_index); 
	
	if(m_doc->m_api.m_show.m_showbpinst_id)
	{
		m_doc_data.GetAttr(m_inst,m_doc->m_api.m_bp_mgr.a_bp_inst_id,buf);
/*		if(buf!=_T(""))
		{
			if(name!=_T('?')) name+=_T(" : "); else name=_T("");
			name+=buf;
		}*/
		if(buf==_T("")) buf=_T("?");
		if(name>_T("")) name+=_T(" : ")+buf;
		else name = buf;
	}
	if(m_doc->m_api.m_show.m_showbpinst_name)
	{
		m_doc_data.GetAttr(m_inst,m_doc->m_api.m_bp_mgr.a_bp_inst_name,buf);
		/*if(buf!=_T(""))
		{
			if(name!=_T('?')) name+=_T(" : "); else name=_T("");
			name+=buf;
		}*/
		if(buf==_T("")) buf=_T("?");
		if(name>_T("")) name+=_T(" : ")+buf;
		else name = buf;
	}
	if(m_doc->m_api.m_show.m_showbpinst_date)
	{
		CString val;
		m_doc_data.GetAttr(m_inst,m_doc->m_api.m_bp_mgr.a_bp_inst_date_time,val);
		COleDateTime time;
		aplString2Date(val,time);
		val = time.Format(_T("%d.%m.%Y %H:%M"));
		name+=_T(" : ")+val;
	}
	return true;
}


//*****************************************************************************
void CaplBPInstTreeItem::ShowAllBaseObjects()
{
	if(m_doc==0) return;
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;
		
	int i;
	aplExtent out_ext,ext;
	CaplInstance *inst=0;
	if(m_inst->GetId()!=0)
	{
		// Чтение из базы
		StartBusy();	
		if(m_doc_data.IsConnected())
		{
			CaplLoadData ld(&(m_doc->m_api.m_data),DEF_SOURCE);
			
			// ссылка
			i=ld.AddQuery(_T('b'), m_inst->GetId(), m_doc->m_api.m_bp_mgr.e_bp_inst_ref,m_doc->m_api.m_bp_mgr.a_bp_inst_ref_process, true);
			  ld.AddQuery(_T('d'), i, 0,m_doc->m_api.m_bp_mgr.a_bp_inst_ref_process, true);
			  ld.AddQuery(_T('d'), i, 0,m_doc->m_api.m_bp_mgr.a_bp_inst_ref_frames_of_reference, true);
			i=ld.AddQuery(_T('d'), i, 0,m_doc->m_api.m_bp_mgr.a_bp_inst_ref_item, true);
			  ld.AddQuery(_T('d'), i, 0,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_id, true);
			  ld.AddQuery(_T('d'), i, 0,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_pdf, true);
			  ld.AddQuery(_T('d'), i, 0,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_descr, true);
			  ld.AddQuery(_T('d'), i, 0,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_sn, true);
			  ld.AddQuery(_T('d'), i, 0,m_doc->m_api.m_prd_inst_mgr.a_prd_inst_lot, true);

		   if(!ld.LoadEx())
				AfxMessageBox(IDS_ERROR_LOAD_DATA_APL,MB_OK|MB_ICONSTOP);

		}
		StopBusy();
	}
	// Поиск связанных объектов
	m_doc_data.GetEntityExtent(m_doc->m_api.m_bp_mgr.e_bp_inst_ref,out_ext);
	for(i=0;i<out_ext.Size;i++)
	{
		m_doc_data.GetAttr(out_ext[i],m_doc->m_api.m_bp_mgr.a_bp_inst_ref_process,inst);
		if(inst!=m_inst) continue;
		if(m_doc->m_cur_context!=0)
			if(!m_doc->m_api.m_bp_mgr.IsItemInContext(out_ext[i],m_doc->m_cur_context,m_doc->m_api.m_bp_mgr.a_bp_inst_ref_frames_of_reference)) continue;
		m_doc_data.GetAttr(out_ext[i],m_doc->m_api.m_bp_mgr.a_bp_inst_ref_item,inst);
		ext.Add(inst);
	}

	// Создание item-ов для связанных объектов
	for(i=0;i<ext.Size;i++)
	{
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_parent_bps,m_inst);
	}
	//Проекты
	ShowAllProjects(m_inst,false);

	if(m_ExecMyExpand)
		MyExpand(false);
}
//****************************************************************
void CaplBPInstTreeItem::ShowAllResources(bool showMsg)
{
	if(m_tree==0) return;
	if(m_doc==0) return;
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;
	if(m_inst->GetAccessmode()>aplRO){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}
	aplExtent ext;
	StartBusy();
	m_doc->m_api.m_bp_mgr.LoadAllBPResources(m_inst,ext);
	StopBusy();

	int i;
	if(!ext.Size)
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox( APL_T("Новые ресурсы не найдены!"));
	
	for(i=0;i<ext.Size;i++)
	{
		CaplBPResourceTreeItem *new_item=0;
		InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_all_res,0,(CaplTreeItem **)(&new_item));
	}
	if(m_ExecMyExpand)
		MyExpand(false);
}
//****************************************************************
bool CaplBPInstTreeItem::RefreshItem()
{
	CString buf;
	GetName(buf);
	if(m_tree!=0) m_tree->SetItemText(m_item,buf);
	int ico=m_doc->m_api.GetInstIco(m_inst);
	if(m_subitem!=0)
		SetItemImage(ICO_REL_WHERE_USED, IDX_IL_TREE_REL_TYPE);
	SetItemImage(ico, IDX_IL_TREE_ITEM);
	if(m_doc->m_tab_view->m_item_old==this) m_doc->ChangeItem(this);
	return true;
}

//****************************************************************
void CaplBPInstTreeItem::ShowProperties()
{
	if(m_doc==0) return;
	if(m_inst==0) return;
	
	if(m_doc->m_api.m_bp_mgr.ShowBPInstProperties(m_inst,m_rel))
	{
		Expand(1); 
		Expand(2);
		RefreshItem();	
	}
}
//****************************************************************
bool CaplBPInstTreeItem::Expand(UINT action)
{
	if(action==TVE_EXPAND)
	{
		CaplAggr aggr0;
		m_doc_data.GetAttr(m_inst,m_doc->m_api.m_bp_mgr.a_bp_inst_elements,aggr0);

		if(m_expanded) return true;
		if(m_fictive_item!=0)
		{
			m_tree->DeleteItem(m_fictive_item);
			m_fictive_item=0;
		}
		if(m_hasSubItem)Expand(1);
		if(m_ShowContentsOnExpand)
		{
			StartBusy();
			CaplInstance *inst;
			int i;
			aplExtent ext;

			for(i=0;i<aggr0.GetSize();i++)
			{
				aggr0.GetByIndex(i,inst);
				if(inst==0) continue;if(inst->GetType()==0) continue;if(inst->GetAccessmode()>aplRO) continue;
				ext.Add(inst);
			}
			m_doc->m_api.m_bp_mgr.LoadBPInstInfo(ext);

			for(i=0;i<ext.GetSize();i++)
			{
				CaplBPInstTreeItem *sub_item=0;
				InsertInstInTree(ext[i],m_item,m_doc,m_tree,m_sub_bps,0,(CaplTreeItem **)(&sub_item));
				if(sub_item!=0)
				{
					sub_item->m_index=m_sub_bps.Size;
					sub_item->m_par_bp_inst=m_inst;
					sub_item->RefreshItem();
				}

			}
		}
			bool old = m_bShowNoFoundMessage;
			m_bShowNoFoundMessage = false;
			m_ExecMyExpand = false;
			if(m_doc->m_auto_expand_items.m_showintree_bpinst&APL_SHOW_DOC)
				ShowAllDocs(false,false);
			if(m_doc->m_auto_expand_items.m_showintree_bpinst&APL_SHOW_CHARACT)
				ShowAllCharacteristic(false);
			if(m_doc->m_auto_expand_items.m_showintree_bpinst&APL_SHOW_APPROVAL)
				ShowAllApproval(false);
			if(m_doc->m_auto_expand_items.m_showintree_bpinst&APL_SHOW_RES)
				ShowAllResources(false);
			m_bShowNoFoundMessage = old;
			m_ExecMyExpand = true;
		StopBusy();
	}
	else if(action==TVE_COLLAPSE)
	{
		CollapseItem(true);

		m_sub_bps.Clear();
		m_parent_bps.Clear();
		m_all_res.Clear();
	}
	return true;
}

//****************************************************************
bool CaplBPInstTreeItem::TrackPopupMenu(CWnd *wnd, CPoint &point, UINT view_mode)
{
	if(m_inst==0) return false;
	if(m_doc==0) return false;
	CMenu menu;  gSetPsmResourceHandle();
	VERIFY(menu.LoadMenu(IDR_TREE_CONTEXT_MENU));
// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
	CaplMenu::Install(wnd); // 	VERIFY(CaplMenu::Install(wnd, ePopupMenu ));
    CMenu* pPopup = menu.GetSubMenu(INDEX_BP_INST_MENU);
    ASSERT(pPopup != NULL);
	if(pPopup==0) return false;

	AppendAddIn((CMenu*)pPopup);
	UpdateMenu((CMenu**)&pPopup, view_mode);
	
	if(m_folder==0)pPopup->EnableMenuItem(ID_REMOVE_FROM_FOLDER, MF_BYCOMMAND | MF_GRAYED);
	if(m_classifier==0){pPopup->EnableMenuItem(ID_REMOVE_FROM_CLASSIFIER, MF_BYCOMMAND | MF_GRAYED);}
	if(m_rel==0 && m_par_bp_inst==0 && m_project==0)pPopup->EnableMenuItem(ID_DELETE_DOCUMENT_REL, MF_BYCOMMAND | MF_GRAYED);

	BOOL res=pPopup->TrackPopupMenu(TPM_LEFTALIGN|
		TPM_RIGHTBUTTON|TPM_RETURNCMD,point.x, point.y,wnd);
	switch(res)
	{
	case ID_SHOW_CONTAINED_FOLDER:
		ShowContainedFolder(m_inst);
		break;
	case ID_SHOW_CONTAINED_MESSAGE: ShowContainedMessage(m_inst); break;
	case ID_SHOW_CONTAINED_TASKS: ShowContainedTasks(m_inst); break;
	case ID_SHOW_CONTAINED_ALERT: ShowContainedAlert(m_inst); break;

	case ID_SHOW_CONTAINED_CLASSIFIER:
		ShowContainedClassifier(m_inst);
		break;
		
	case ID_OPEN_ITEM_IN_NEW_WINDOW:
		if(m_inst!=0) m_doc->OpenInstanceInNewWindow(m_inst);
		break;
	case ID_REMOVE_FROM_FOLDER:
		if(m_folder!=0)
		{
			if(m_doc->m_api.m_folder_mgr.RemoveFromFolder(m_folder,m_inst))
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
		}
		break;
	case ID_REMOVE_FROM_CLASSIFIER:
		if(m_classifier!=0)
		{
			if(m_classifier->GetAccessmode()>aplRW)	{AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return true;}
			if(m_doc->m_api.m_classifier_mgr.DeleteClassifierAssociation(m_inst,m_classifier))
				m_doc->m_items.Remove(m_doc->m_items.Find(this));
		}
		break;
	case ID_DELETE_DOCUMENT_REL:RemoveRelation();break;
	
	case ID_DELETE:
		{

			if(m_inst)
			{	
				if(m_inst->GetAccessmode()>aplOWN)
				{
					AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
					return true;
				}
				if(AfxMessageBox( APL_T("Вы действительно хотите удалить описание экземпляра бизнес-процесса ?"),MB_YESNO)==IDYES)
				{
					StartBusy();
					if(m_doc->m_api.m_bp_mgr.DeleteBPInst(m_inst))
					{
						for(int i=0;i<m_doc->m_items.Size;i++)
						{
							if(m_doc->m_items[i]!=this)
							{
								if(m_doc->m_items[i]->m_type==m_type)
								{
									CaplBPInstTreeItem *item1=
										(CaplBPInstTreeItem*)m_doc->m_items[i];
									{
										if(item1->m_inst==m_inst)
										{m_doc->m_items.Remove(i); i--;}
									}
								}
							}
						}
						m_doc->m_items.Remove(m_doc->m_items.Find(this));
					}
					StopBusy();
				}
			}
		}
		break;
	case ID_CREATE_BP_INST: CreateBPInst();break;
	case ID_CREATE_RESOURCE: CreateBPResource();break;
	case ID_SHOW_ALL_BP_RESOURCE: ShowAllResources(); break;
	case ID_PRODUCT_WHERE_USED:
	{
			if(m_inst->GetAccessmode()>aplRW){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return true;}
			aplExtent ext0;
			m_doc->m_api.m_bp_mgr.WhereUsedBPInst(m_inst,ext0);
			for(int i=0;i<ext0.Size;i++)
			{
				InsertInstInTree(ext0[i],m_item,m_doc,m_tree,m_parent_bps);
//				if(m_parent_bps.Find(ext0[i])>=0) continue;
//				CaplBPInstTreeItem *act_item= new CaplBPInstTreeItem(m_tree,m_doc,ext0[i]);
//				act_item->m_subitem=m_inst;
//				act_item->CreateTreeItem(m_item);
//				act_item->RefreshItem();
//				m_parent_bps.Add(ext0[i]);
			}
			ShowAllBaseObjects();
			MyExpand();
		}
		break;
	case ID_CREATE_CHARACTERISTIC: CreateCharacteristic(m_inst); break;
	case ID_CREATE_CHARACTERISTIC_GROUP: CreateCharacteristicGroup(m_inst);break;
	case ID_SHOW_BASE_BP_INST:
		if(m_inst!=0)
		{
			CaplInstance *bp=0;
			m_doc_data.GetAttr(m_inst,m_doc->m_api.m_bp_mgr.a_bp_inst_process,bp);
			if(bp!=0)
			{
				m_doc->m_api.m_bp_mgr.LoadBPInfo(bp);
				CaplBPTreeItem *bp_item=
					new CaplBPTreeItem(m_tree,m_doc,bp);
				bp_item->CreateTreeItem(m_item);
				bp_item->RefreshItem();
				MyExpand(false);
			}
			else
				if(m_bShowNoFoundMessage) 
					AfxMessageBox( APL_T("Базовый бизнес-процесс не задан"));
		}
		break;
	case ID_SHOW_PROJECTS: ShowAllProjects(m_inst); break;
	default: PrepareContextMenu(res); 
	}
	return true;
}
//****************************************************************
void CaplBPInstTreeItem::GetAccessedInstances(aplExtent &ext)
{
	ext.Clear();
	if(m_inst!=0){if(m_inst->GetType()!=0)ext.Add(m_inst);}
}

//****************************************************************
bool CaplBPInstTreeItem::ShowInListCtrl(CListCtrl *list)
{
	if(list==0) return false;
	CHECK_SHOW_LIST_CTRL(m_inst);
	if(m_doc==0)return false;

	CaplInstance *inst=0;
	CString buf=_T("");

	int i=list->InsertItem(0, APL_T("Обозначение:"));
	m_doc_data.GetAttrBN(m_inst,S::id,buf);
	list->SetItemText(i,1,buf);
	buf=_T("");

	i=list->InsertItem(1, APL_T("Наименование:"));
	m_doc_data.GetAttrBN(m_inst,S::name,buf);
	list->SetItemText(i,1,buf);
	buf=_T("");

	i=list->InsertItem(2, APL_T("Описание:"));
	m_doc_data.GetAttrBN(m_inst,S::description,buf);
	list->SetItemText(i,1,buf);
	buf=_T("");

	i=list->InsertItem(3, APL_T("Бизнес-процесс:"));
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_bp_mgr.a_bp_inst_process,inst);
	if(inst!=0) m_doc->m_api.m_bp_mgr.GetItemName(inst,buf);
	list->SetItemText(i,1,buf);
	buf=_T("");

	if(m_rel)
	{
		i=list->InsertItem(4, APL_T("Контексты:"));
		aplExtent m_bp_inst_ref_contexts;
		m_doc_data.GetAttr(m_rel,m_doc->m_api.m_bp_mgr.a_bp_inst_ref_frames_of_reference,m_bp_inst_ref_contexts);
		if(m_bp_inst_ref_contexts.GetSize()>0)
			m_doc->m_api.m_bp_mgr.PrintItemContextInString(m_bp_inst_ref_contexts,buf);
		else buf=S::all_context();
		list->SetItemText(i,1,buf);
	}
	else
		i=list->InsertItem(4,_T(""));

	list->InsertItem(5,_T(""));
	buf=_T("");
	i=list->InsertItem(6, APL_T("Доступ:"));
	GetAccessName(m_inst,buf);
	list->SetItemText(i,1,buf);

	if(m_project)
	{
		CaplInstance *rel=m_doc->m_project_mgr->FindAssociation(m_project,m_inst);
		if(rel) 
		{
			CaplInstance *control_status=0;
			m_doc_data.GetAttr(rel,m_doc->m_project_mgr->a_project_ref_control_status,control_status);
			buf= APL_T("Рабочий объект");
			if(control_status) buf= APL_T("Контрольный объект");
			list->InsertItem(list->GetItemCount(),_T(""));
			i=list->InsertItem(list->GetItemCount(), APL_T("Тип объекта:"));
			list->SetItemText(i,1,buf);
			if(control_status) 
			{
				i=list->InsertItem(list->GetItemCount(), APL_T("Контрольный статус:"));
				m_doc_data.GetAttr(control_status,m_doc->m_api.m_appr_mgr.a_appr_status_name,buf);
				list->SetItemText(i,1,buf);
			}
		}
	}
	
	aplExtent ext;
	CStringArray comment;
	if(m_inst!=0){ comment.Add( APL_T("Экземпляр БП")); ext.Add(m_inst);}
	if(m_rel!=0){ comment.Add( APL_T("Связь")); ext.Add(m_rel);}
	if(m_par_bp_inst!=0){ comment.Add( APL_T("Родительская версия БП")); ext.Add(m_par_bp_inst);}
	if(m_classifier!=0){
		CaplInstance* classif_ref;
		m_doc->m_api.m_classifier_mgr.TestClassifierAssociation(m_inst,m_classifier,&classif_ref);
		if(classif_ref!=0){
			comment.Add(_T("classifier association"));
			ext.Add(classif_ref);
		}
		comment.Add(_T("m_classifier"));
		ext.Add(m_classifier);
	}
	
	ShowInstanceInfoInListCtrl(ext,list,&comment);

	return true;
}
//****************************************************************
/*
void CaplBPInstTreeItem::CreateCharacteristic(CaplInstance *val)
{
	CaplInstance *new_val=0;
	if(m_doc->m_api.m_charact_mgr.CreateCharacteristic(m_inst,val, &new_val,0,0,true))
	{

		if(CaplTreeItem::m_AutoUzurpireCharacteristic)
		{
			aplExtent ext; ext.Add(new_val);
			m_doc_data.NET_BecomeInstancesOwner(&ext);
		}

		CaplCharacteristicTreeItem *characteristic_item=
			new CaplCharacteristicTreeItem(m_tree,m_doc,new_val);
		characteristic_item->CreateTreeItem(m_item);
		m_all_caracteristic.Add(new_val);
		MyExpand();
		m_doc->ChangeItem(0);m_doc->ChangeItem(this);
	}
}*/
//****************************************************************
void CaplBPInstTreeItem::ShowCmd(long cmd)
{
	switch (cmd)
	{
		case ID_CREATE_CHARACTERISTIC: CreateCharacteristic(m_inst); break;
		case ID_SHOW_ALL_BP_RESOURCE: ShowAllResources(); break;
		case ID_ITEM_VIEW: ShowProperties(); break;
		case ID_CREATE_BP_INST: CreateBPInst();	break;
		case ID_EXPAND_ALL: {int i=1; ExpandAll(i);} break;
		//case ID_SHOW_ALL_BP_INST: ShowAllBPInst();	break;
		default: PrepareContextMenu(cmd);break;
	}
}
BOOL CaplBPInstTreeItem::ShowToolBarButton(CCmdUI* pCmdUI)
{
	if(pCmdUI->m_nID==ID_SET_INST_ACCSESS)
	{
		aplExtent instances;
		GetAccessedInstances(instances);
		if(instances.GetSize()>0)
		{
			if(instances[0]->GetAccessmode()==aplOWN) return TRUE;
		}
		return FALSE;
	}


	switch(pCmdUI->m_nID)
	{
		case ID_SHOW_ALL_DOCS:
		case ID_SHOW_ALL_CHARACTERISTIC:
		case ID_SHOW_ALL_APPROVAL:
		case ID_CREATE_APPROVAL:
		case ID_CREATE_CHARACTERISTIC:
		case ID_CREATE_DOC:
		case ID_SHOW_ALL_BP_RESOURCE: 
		case ID_CREATE_BP_INST:
		case ID_SHOW_NOTES:
		case ID_CREATE_NOTE:
		//case ID_SHOW_ALL_BP_INST:
			pCmdUI->Enable(TRUE); return TRUE; break;
	}
	return FALSE;
}
//****************************************************************
bool CaplBPInstTreeItem::PasteItem(CaplTreeItem *item, CPoint *point)
{
	if(item==0) return false;
	if (item->m_type != APL_TREE_ITEM_DOCUMENT)
		if (item->m_type != APL_TREE_ITEM_CHARACTERISTIC)
			if (item->m_type != APL_TREE_ITEM_CHARACTERISTICGROUP)
				if (item->m_type != APL_TREE_ITEM_BPINST)
					if(item->m_type != APL_TREE_ITEM_PRODUCT) 
						if(item->m_type !=APL_TREE_ITEM_PRDINST)
							if(item->m_type !=APL_TREE_ITEM_LOT)
								if (item->m_type != APL_TREE_ITEM_BPRES)
									return false;
	if(m_tree==0) return false;
	if(m_doc==0) return false;

	CMenu menu;  gSetPsmResourceHandle();
	CMenu *pPopup=0;
	VERIFY(menu.LoadMenu(IDR_PASTE_ITEM_MENU));
// 	VERIFY(menu.LoadToolBar(IDR_MENU_ICONS));
	CaplMenu::Install(m_tree); // 	VERIFY(CaplMenu::Install(m_tree, ePopupMenu ));

	if(item->m_type == APL_TREE_ITEM_DOCUMENT)
	{
		aplExtent ext;
		item->GetAccessedInstances(ext);
		CString state;
		m_doc_data.GetAttr(ext[0],m_doc->m_api.m_doc_mgr.a_apl_doc_wf_state,state);
		if(state==_T("canceled")) return false;
		pPopup = menu.GetSubMenu(INDEX_DOCUMENT_MENU);
	}
	else if(item->m_type == APL_TREE_ITEM_CHARACTERISTIC)
		pPopup = menu.GetSubMenu(INDEX_CHARACTERISTIC_MENU);
	else if(item->m_type == APL_TREE_ITEM_CHARACTERISTICGROUP)
		pPopup = menu.GetSubMenu(INDEX_CHARACTERISTIC_MENU);

	if(pPopup!=0)
	{
		POINT pnt;
		if(point==0)
		{
			RECT rect;
			m_tree->GetItemRect(m_item,&rect,TRUE);
			m_tree->ClientToScreen(&rect);
			pnt.x=rect.right;
			pnt.y=rect.bottom;
		}
		else
		{
			pnt.x=point->x;
			pnt.y=point->y;
		}

		BOOL res=pPopup->TrackPopupMenu(TPM_LEFTALIGN|
			TPM_RIGHTBUTTON|TPM_RETURNCMD,pnt.x,pnt.y,m_tree);

		// Вставка документа
		if (res == ID_DOCUMENT_COPY)
		{
			CaplInstance *i_doc=((CaplDocTreeItem *)item)->m_inst;
			
			HTREEITEM ht = m_tree->GetNextItem(item->m_item,TVGN_PARENT);
			CaplTreeItem *Item = (CaplTreeItem*)m_tree->GetItemData(ht);
			aplAccessModeType access =aplOWN;
			if(Item)
			{
				aplExtent instances;
				Item->GetAccessedInstances(instances);
				if(instances.GetSize()>0)
					access = instances.GetAt(0)->GetAccessmode();
			}
			
			if(m_inst->GetAccessmode()>aplRW || access>aplRO)
			{
				AfxMessageBox( APL_T("Нет доступа к объекту"));
				return false;
			}
			if(CaplDocTreeItem::InsertDoc(m_doc,this,&m_all_documents,i_doc,m_inst, false))
				ShowCmd(ID_SHOW_ALL_DOCS);
		}
		//создание по образцу
		else if(res == ID_DOCUMENT_BYDOT)
		{
			CaplInstance *i_doc = ((CaplDocTreeItem *)item)->m_inst;
			
			aplExtent instances;
			GetAccessedInstances(instances);
			if(m_doc->m_api.m_doc_mgr.CreateDocumentByDot(i_doc,instances[0]))
				ShowCmd(ID_SHOW_ALL_DOCS);
		}
		//премещение документа
		else if(res == ID_DOCUMENT_MOVE)
		{
			CaplDocTreeItem *d_item = (CaplDocTreeItem*)item;
			HTREEITEM parent = m_tree->GetNextItem(d_item->m_item,TVGN_PARENT);
			CaplTreeItem *parent_item = (CaplTreeItem*)m_tree->GetItemData(parent);
			
			CaplDocTreeItem::MoveDocument(m_doc, d_item, parent_item, this);
		}
		// Вставка характеристики
		else if (res == ID_CHARACTERISTIC_COPY)
		{
			if(item->m_type == APL_TREE_ITEM_CHARACTERISTIC)
			{
				CaplInstance *i_val=((CaplCharacteristicTreeItem *)item)->m_val;
				CreateCharacteristic(i_val);
			}
			else if(item->m_type == APL_TREE_ITEM_CHARACTERISTICGROUP)
			{
				CreateCharacteristicGroup(((CaplCharacteristicGroupTreeItem*)item)->m_group);
			}

		}
	}
	else if (item->m_type == APL_TREE_ITEM_BPINST) //Вставка входящего экземпляра бп
	{
		CaplInstance *sub_bp_inst=((CaplBPInstTreeItem*)item)->m_inst;
		StartBusy();
		if(!m_doc->m_api.m_bp_mgr.AddBPInstToBPInst(sub_bp_inst,m_inst))
		{
			StopBusy();
			return false;
		}

		CaplBPInstTreeItem *sub_item=0;
		InsertInstInTree(sub_bp_inst,m_item,m_doc,m_tree,m_sub_bps,0,(CaplTreeItem **)(&sub_item));
		if(sub_item!=0)
		{
			sub_item->m_par_bp_inst=m_inst;
			sub_item->m_index=m_sub_bps.Size-1;
			sub_item->RefreshItem();
		}
		Expand(1);
		Expand(2);
		m_doc->RefreshAllItemsByType(APL_TREE_ITEM_BPINST);
		MyExpand();
		StopBusy();
		return true;
	}
	else if ( (item->m_type == APL_TREE_ITEM_PRODUCT) || (item->m_type ==APL_TREE_ITEM_PRDINST) || (item->m_type ==APL_TREE_ITEM_LOT))
	{
		CaplInstance *obj=0, *base_pdr=0;; 

		if(item->m_type == APL_TREE_ITEM_PRODUCT)
		{
			obj=((CaplProductTreeItem*)item)->m_prd;
			if(((CaplProductTreeItem*)item)->m_pdf!=0)
			{
				obj=((CaplProductTreeItem*)item)->m_pdf;
				base_pdr=((CaplProductTreeItem*)item)->m_nauo;
			}
		}
		else if(item->m_type == APL_TREE_ITEM_PRDINST) obj=((CaplPrdInstTreeItem*)item)->m_inst;
		else if(item->m_type == APL_TREE_ITEM_LOT)  obj=((CaplLotTreeItem*)item)->m_lot;

		if(obj==0) return false;
		if(obj->GetType()==0) return false;
		if(obj->GetAccessmode()>aplRO){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return false;}

		CaplInstance *new_res=m_doc->m_api.m_bp_mgr.CreateBPResource(m_inst,0,obj);
		if(new_res)
		{
			CaplBPResourceTreeItem *new_item=0;
			InsertInstInTree(new_res,m_item,m_doc,m_tree,m_all_res,0,(CaplTreeItem **)(&new_item));
			MyExpand();
		}
		return true;
	}
	else if (item->m_type == APL_TREE_ITEM_BPRES)
	{

		CaplInstance *base_res=((CaplBPResourceTreeItem*)item)->m_inst;
		if(!base_res) return false;if(base_res->GetAccessmode()>aplRO) {AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);return false;}
		
		CaplInstance *new_res=m_doc->m_api.m_bp_mgr.CreateBPResource(m_inst,base_res);
		if(new_res)
		{
			CaplBPResourceTreeItem *new_item=0;
			InsertInstInTree(new_res,m_item,m_doc,m_tree,m_all_res,0,(CaplTreeItem **)(&new_item));
			MyExpand();
		}
		MyExpand();
		return true;
	}


	m_tree->RedrawWindow();
	return true;
}

//****************************************************************
bool CaplBPInstTreeItem::PasteFile(LPCTSTR file, CPoint *point)
{
	if(file==0) return false;
	CreateDoc(m_inst,file);
	return true;
}/*
//****************************************************************
void CaplBPInstTreeItem::CreateCharacteristicGroup(CaplInstance *group)
{
	CaplInstance *group_new=0;
	if(m_doc->m_api.m_charact_mgr.CreateCharacteristicGroup(m_inst,&group_new,group))
	{
		if(group!=0)
		{
			if(CaplTreeItem::m_AutoUzurpireCharacteristic)
			{
				aplExtent ext; ext.Add(group);
				m_doc_data.NET_BecomeInstancesOwner(&ext);
			}

		}
		CaplCharacteristicGroupTreeItem *characteristic_group_item=
			new CaplCharacteristicGroupTreeItem(m_tree,m_doc,group_new);
		characteristic_group_item->CreateTreeItem(m_item);
		m_all_caracteristic.Add(group_new);
		MyExpand();
		m_doc->ChangeItem(0);m_doc->ChangeItem(this);
	}
}*/

//****************************************************************
void CaplBPInstTreeItem::CreateBPInst()
{
	if(m_tree==0) return;
	if(m_doc==0) return;
	if(m_inst==0)return;
	if(m_inst->GetType()==0)return;
	if(m_inst->GetAccessmode()>aplRW){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}

	m_doc->m_api.m_bp_mgr.LoadBPInstInfo(m_inst);
	
	CaplInstance *sub_bp_inst=m_doc->m_api.m_bp_mgr.CreateBPInst(m_inst);
	
	if(sub_bp_inst!=0)
	{
		m_doc_data.NET_SaveChanges();
		CaplBPInstTreeItem *sub_item= new CaplBPInstTreeItem(m_tree,m_doc,sub_bp_inst);
		CaplAggr aggr0;
		m_doc_data.GetAttr(m_inst,m_doc->m_api.m_bp_mgr.a_bp_inst_elements,aggr0);
		sub_item->m_par_bp_inst=m_inst;	
		sub_item->m_index=aggr0.GetSize();
		sub_item->CreateTreeItem(m_item);
		m_sub_bps.Add(sub_bp_inst);
	}
	Expand(1);
	Expand(2);
	m_doc->RefreshAllItemsByType(APL_TREE_ITEM_BPINST);
	MyExpand();	

}

void CaplBPInstTreeItem::CreateBPResource()
{
	if(m_tree==0) return;
	if(m_doc==0) return;
	if(m_inst==0)return;
	if(m_inst->GetType()==0)return;
	if(m_inst->GetAccessmode()>aplRW){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return;}

	CaplInstance *new_res=m_doc->m_api.m_bp_mgr.CreateBPResource(m_inst);
	if(new_res)
	{
		CaplBPResourceTreeItem *new_item=0;
		InsertInstInTree(new_res,m_item,m_doc,m_tree,m_all_res,0,(CaplTreeItem **)(&new_item));
		MyExpand();
	}
}
void CaplBPInstTreeItem::RemoveRelation()
{
	if(!m_rel && !m_par_bp_inst && !m_project) return;
	if(m_rel)
	{
		if(m_rel->GetAccessmode()>aplOWN)
		{
			AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);return;
		}
		CaplInstance *inst;
		m_doc_data.GetAttr(m_rel,m_doc->m_api.m_bp_mgr.a_bp_inst_ref_item,inst);
		if(inst>0)
		{
			if(inst->GetAccessmode()>aplRW)
			{
				AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP);
				return;
			}
		}
		if(AfxMessageBox( APL_T("Вы действительно хотите удалить связь ?"),MB_YESNO)==IDYES)
		{
			for(int i=0;i<m_doc->m_items.Size;i++)
			{
				if(m_doc->m_items[i]!=this)
				{
					if(m_doc->m_items[i]->m_type==m_type)
					{
						CaplBPInstTreeItem *item1=
							(CaplBPInstTreeItem*)m_doc->m_items[i];
						{
							if(item1->m_rel==m_rel)
							{m_doc->m_items.Remove(i); i--;}
						}
					}
				}
			}
			m_doc_data.DeleteInstance(m_rel);
		}	
	}
	else if(m_par_bp_inst)
	{
		m_doc->m_api.m_bp_mgr.LoadBPInstInfo(m_par_bp_inst);
					
		if(AfxMessageBox( APL_T("Вы действительно хотите удалить связь ?"),MB_YESNO)==IDNO) return;
		
		if(!m_doc->m_api.m_bp_mgr.DeleteBPInstRelation(m_inst,m_par_bp_inst)) return;
		
	}
	else if(m_project)
	{
		if(!m_inst) return;
		if(AfxMessageBox( APL_T("Вы уверены ?"),MB_YESNO|MB_DEFBUTTON2)!=IDYES) return;
		if(!m_doc->m_project_mgr->DeleteAssociation(m_project,m_inst)) return;
		CaplProjectTreeItem *prj_item=(CaplProjectTreeItem*)GetParentItem(this);
		if(prj_item) prj_item->m_all_items.Remove(prj_item->m_all_items.Find(m_inst));
	}
	m_doc->m_items.Remove(m_doc->m_items.Find(this));

}