// aplDocCopyItem.cpp: implementation of the CaplDocCopyItem class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "psm.h"
#include "aplDocCopyItem.h"
#include "PSMDoc.h"
#include "resource.h"
#include "TabView.h"
#include "aplTreeApprovalItem.h"
#include "aplTreeCharacteristicItem.h"
#include "aplCharacteristicGroupTreeItem.h"
#include "aplProjectTreeItem.h"
#include "aplDocTreeItem.h"

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

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CaplDocCopyTreeItem::CaplDocCopyTreeItem(CTreeCtrl *tree, CPSMDoc* pDoc, CaplInstance *inst)
{
	m_inst=inst;
	m_doc = pDoc;
	m_document=0;
	m_tree = tree;
	m_folder=0;
	m_classifier=0;
	m_project=0;
	m_subitem=0;
	m_type = _T("DocHardCopy");
	if(m_doc)
		m_doc->m_items.Add(this);
	m_expanded = false;
	m_bReloadContentOnExpand=true;
	RefreshItem();
}

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

//****************************************************************
bool CaplDocCopyTreeItem::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 CaplDocCopyTreeItem::GetName(CString &name)
{
	_APL_TREE_ITEM_CHEK_PARAM_BOOL
	CHECK_GET_NAME(m_inst);

	m_doc->m_api.GetItemName(m_inst,name);


	return true;
}


//*****************************************************************************
void CaplDocCopyTreeItem::ShowAllBaseObjects()
{
	if(m_doc==0) return;
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;
		
	//Проекты
	ShowAllProjects(m_inst,false);

	if(m_ExecMyExpand)
		MyExpand(false);
}

//****************************************************************
bool CaplDocCopyTreeItem::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);
	color=0;
	font_style&=~APL_FONT_STRIKEOUT;
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_state,buf);
	if(buf== APL_T("аннулирован") || buf== APL_T("уничтожен"))
	{
		color=RGB(128,128,128);
		font_style|=APL_FONT_STRIKEOUT;
	}
	if(m_doc->m_tab_view->m_item_old==this) m_doc->ChangeItem(this);
	return true;
}

//****************************************************************
void CaplDocCopyTreeItem::ShowProperties()
{
	if(m_doc==0) return;
	CHECK_INSTANCE_ITEM(m_inst);
	
	if(m_doc->m_api.m_doc_mgr.ShowDocCopyProperties(m_inst))
	{
		//Expand(1); 
		//Expand(2);
		RefreshItem();	
	}
}
//****************************************************************
bool CaplDocCopyTreeItem::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)
		{

		}
		bool old = m_bShowNoFoundMessage;
		m_bShowNoFoundMessage = false;
		m_ExecMyExpand = false;
		if(m_doc->m_auto_expand_items.m_showintree_doc&APL_SHOW_CHARACT)
			ShowAllCharacteristic(false);
		if(m_doc->m_auto_expand_items.m_showintree_doc&APL_SHOW_APPROVAL)
			ShowAllApproval(false);
		m_bShowNoFoundMessage = old;
		m_ExecMyExpand = true;
	}
	else if(action==TVE_COLLAPSE)
	{
		CollapseItem(true);
	}
	return true;
}

//****************************************************************
bool CaplDocCopyTreeItem::TrackPopupMenu(CWnd *wnd, CPoint &point, UINT view_mode)
{
	if(m_inst==0) return false;
	if(m_doc==0) return false;
	CHECK_INSTANCE_ITEM_B(m_inst);
	CMenu menu;  gSetPsmResourceHandle();
	VERIFY(menu.LoadMenu(IDR_TREE_CONTEXT_MENU1));
	CaplMenu::Install(wnd); 
    CMenu* pPopup = menu.GetSubMenu(INDEX_DOC_HARD_COPY_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_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_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_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(m_doc->m_api.m_doc_mgr.DeleteDocHardCopy(m_inst))
				{
					StartBusy();
					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)
							{
								CaplDocCopyTreeItem *item1=
									(CaplDocCopyTreeItem*)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_PRODUCT_WHERE_USED:
	{
			if(m_inst->GetAccessmode()>aplRW){AfxMessageBox(ID_NO_ACCESS_RIGHT,MB_OK|MB_ICONSTOP); return true;}
			ShowAllBaseObjects();
			MyExpand();
		}
		break;
	case ID_CREATE_CHARACTERISTIC: CreateCharacteristic(m_inst); break;
	case ID_CREATE_CHARACTERISTIC_GROUP: CreateCharacteristicGroup(m_inst);break;
	default: PrepareContextMenu(res); 
	}
	return true;
}
//****************************************************************
void CaplDocCopyTreeItem::GetAccessedInstances(aplExtent &ext)
{
	ext.Clear();
	if(m_inst!=0){if(m_inst->GetType()!=0)ext.Add(m_inst);}
}

//****************************************************************
bool CaplDocCopyTreeItem::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;
	i=list->InsertItem(list->GetItemCount(), APL_T("Обозначение:"));
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_id,buf);
	list->SetItemText(i,1,buf);
	buf=_T("");

	CaplInstance *copy_doc;
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_doc,copy_doc);
	if(copy_doc)
	{
		i=list->InsertItem(list->GetItemCount(), APL_T("Документ:"));
		CString doc_id=_T(""),doc_name=_T("");

		m_doc_data.GetAttr(copy_doc,m_doc->m_api.m_doc_mgr.a_doc_id,doc_id);
		if(doc_id==_T("")) doc_id=_T("?");
		buf+=doc_id;

		m_doc_data.GetAttr(copy_doc,m_doc->m_api.m_doc_mgr.a_doc_name,doc_name);
		if(doc_name==_T("")) doc_name=_T("?");
		if(doc_id>_T("")) buf+=_T(" : ") + doc_name;
		else buf+= doc_name;

		list->SetItemText(i,1,buf);
	}
	else
	{
		list->InsertItem(list->GetItemCount(),_T(""));
	}
	i=list->InsertItem(list->GetItemCount(),_T(""));
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_state,buf);
	if(buf!=_T(""))
	{
		i=list->InsertItem(list->GetItemCount(), APL_T("Состояние:"));
		list->SetItemText(i,1,buf);
	}
	
	i=list->InsertItem(list->GetItemCount(),_T(""));
	buf=_T("");
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_owner,inst);
	if(inst)
	{
		i=list->InsertItem(list->GetItemCount(), APL_T("Владелец:"));
		m_doc->m_api.GetItemName(inst,buf);
		list->SetItemText(i,1,buf);
	}
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_place_of_use,inst);
	if(inst)
	{
		i=list->InsertItem(list->GetItemCount(), APL_T("Место использования:"));
		m_doc->m_api.GetItemName(inst,buf);
		list->SetItemText(i,1,buf);
	}

	i=list->InsertItem(list->GetItemCount(),_T(""));
	COleDateTime odt;
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_issue_date,buf);
	if(buf!=_T(""))
	{
		aplString2Date(buf,odt);
		buf=odt.Format(_T("%d.%m.%Y  %H:%M:%S"));
		i=list->InsertItem(list->GetItemCount(), APL_T("Выдана:"));
		list->SetItemText(i,1,buf);
	}
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_last_update,buf);
	if(buf!=_T(""))
	{
		aplString2Date(buf,odt);
		buf=odt.Format(_T("%d.%m.%Y  %H:%M:%S"));
		i=list->InsertItem(list->GetItemCount(), APL_T("Дата последнего изменения:"));
		list->SetItemText(i,1,buf);
	}
	if(copy_doc)
	{
		i=list->InsertItem(list->GetItemCount(),_T(""));
		m_doc_data.GetAttr(copy_doc,m_doc->m_api.m_doc_mgr.a_apl_doc_active,inst);
		if(inst)
		{
			m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_id,buf);
			i=list->InsertItem(list->GetItemCount(), APL_T("Активная версия документа:"));
			list->SetItemText(i,1,buf);
		}
		m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_cur_rev,inst);
		if(inst)
		{
			m_doc_data.GetAttr(inst,m_doc->m_api.m_doc_mgr.a_apl_doc_rev_id,buf);
			i=list->InsertItem(list->GetItemCount(), APL_T("Текущая версия копии:"));
			list->SetItemText(i,1,buf);
		}
	}

	list->InsertItem(list->GetItemCount(),_T(""));
	buf=_T("");
	i=list->InsertItem(list->GetItemCount(), 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_document!=0){ comment.Add( APL_T("Документ")); ext.Add(m_document);}
	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 CaplDocCopyTreeItem::ShowCmd(long cmd)
{
	switch (cmd)
	{
		case ID_CREATE_CHARACTERISTIC: CreateCharacteristic(m_inst); break;
		case ID_ITEM_VIEW: ShowProperties(); break;
		case ID_EXPAND_ALL: {int i=1; ExpandAll(i);} break;
		default: PrepareContextMenu(cmd);break;
	}
}
BOOL CaplDocCopyTreeItem::ShowToolBarButton(CCmdUI* pCmdUI)
{
	switch(pCmdUI->m_nID)
	{
		case ID_SHOW_ALL_CHARACTERISTIC:
		case ID_SHOW_ALL_APPROVAL:
		case ID_CREATE_APPROVAL:
		case ID_CREATE_CHARACTERISTIC:
		case ID_SHOW_NOTES:
		case ID_CREATE_NOTE:
			pCmdUI->Enable(TRUE); return TRUE; break;
	}
	return FALSE;
}
//****************************************************************
bool CaplDocCopyTreeItem::PasteItem(CaplTreeItem *item, CPoint *point)
{
	if(item==0) return false;
	if (item->m_type != APL_TREE_ITEM_CHARACTERISTIC)
		if (item->m_type != APL_TREE_ITEM_CHARACTERISTICGROUP)
				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_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_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);
			}

		}
	}

	m_tree->RedrawWindow();
	return true;
}

void CaplDocCopyTreeItem::RemoveRelation()
{
	if(!m_project) return;
	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));
}

//****************************************************************
void CaplDocCopyTreeItem::ShowAllDocs(bool bExpand, bool showMsg)
{
	if(m_doc==0) return;
	
	if(m_inst==0) return;
	if(m_inst->GetType()==0) return;
	if(m_inst->GetAccessmode()>aplRO)
	{if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),m_inst);return;};

	int count0=m_all_documents.Size;
	CaplInstance *base_doc=0;
	m_doc_data.GetAttr(m_inst,m_doc->m_api.m_doc_mgr.a_doc_copy_doc,base_doc);
	if(!base_doc) return;
	if(base_doc->GetType()==0) return;
	if(base_doc->GetAccessmode()>aplRO)
	{if(m_bShowNoFoundMessage) aplErrorMessage(S::NoAccessRight(),base_doc);return;};

	if(m_bShowNoFoundMessage) m_tree->SetRedraw(FALSE);
	if(m_all_documents.Find(base_doc)==-1)
	{
		CaplDocTreeItem *doc_item= new CaplDocTreeItem(m_tree,m_doc,base_doc);
		doc_item->CreateTreeItem(m_item);
		m_all_documents.Add(base_doc);
		doc_item->m_par_item_docs_ext=&m_all_documents;
	}
	if(m_bShowNoFoundMessage) m_tree->SetRedraw(TRUE);
	if(count0==m_all_documents.Size)
	{
		if(m_bShowNoFoundMessage && showMsg) AfxMessageBox(APL_T("Новые документы не найдены !"));
	}
	else {if(bExpand && m_ExecMyExpand)MyExpand(false);}
	
	return ;
}