// OrgStrDlg.cpp : implementation file
//

#include "stdafx.h"
#include "OrgStrDlg.h"
#include "FindOrgDlg.h"
#include <AplGuiEx.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// COrgStrDlg dialog

COrgStrDlg::COrgStrDlg(CaplAPI*	api, CaplInstance* ciInst /*= NULL*/, CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(COrgStrDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(COrgStrDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	//m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_hIcon=0;
	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0
	if(0!=app) m_hIcon = app->LoadIcon(IDI_FIND);
	m_api=api;
	m_inst=ciInst;

	m_sTitle =  APL_T("Выбор организации");
}

void COrgStrDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(COrgStrDlg)
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_BTNFIND, m_find_btn);
	DDX_Control(pDX, IDC_TREE1, m_tree);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(COrgStrDlg, CaplTranslateDialog)
	//{{AFX_MSG_MAP(COrgStrDlg)
	ON_NOTIFY(TVN_ITEMEXPANDING, IDC_TREE1, OnItemexpandingTree1)
	ON_BN_CLICKED(IDC_BTNFIND, OnBtnfind)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// COrgStrDlg message handlers

BOOL COrgStrDlg::OnInitDialog()
{
	CaplTranslateDialog::OnInitDialog();

 	SetIcon(m_hIcon, TRUE);			// Set big icon
 	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	SetWindowText(m_sTitle);

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

	m_tree.SetImageList(aplGetInstImageList(), TVSIL_NORMAL);

	m_api->m_data.GetEntityExtent(m_api->m_appr_mgr.e_org_rel, m_ext_rel);
	m_api->m_data.GetEntityExtent(m_api->m_appr_mgr.e_org, m_ext);

	bool isExpand=false;
	if(!m_ext_root.Size)
		FindRootInst();
	else
		isExpand=true;
	
	CString name;	

	//исключаем intance, к котоым нет доступа
	int i,j=m_ext_root.GetSize(); 
	for(i=0;i<j;i++)
	{
		if(m_ext_root.GetAt(i)->GetAccessmode()>aplRO)
		{
			m_ext_root.Remove(i); 
			i++; j--;
		}
	}


	aplQSortByAttr(&m_api->m_data, m_ext_root,0, m_ext_root.Size-1, m_api->m_appr_mgr.a_org_name);	
	for(int i=0; i<m_ext_root.Size; i++)
	{
		CaplInstance* inst = m_ext_root[i];
		m_api->m_data.GetAttr(inst,m_api->m_appr_mgr.a_org_name,name);
		//m_api->GetItemName(inst,name);
		if(name== APL_NO_T("Удаленные"))
			continue;	
		int img=m_api->GetInstIco(inst);
		COrgStrTreeItem* tritem=new COrgStrTreeItem(&m_tree);
		tritem->inst=inst;
		tritem->InsetItem(name,img,TVI_ROOT);
		
		m_listItems.Add(tritem);
		
	}
	
	if(isExpand || m_inst)
	{
		HTREEITEM hItem=m_tree.GetRootItem();
		COrgStrTreeItem* item=0;
		while (hItem != NULL)
		{
			m_tree.Expand(hItem,TVE_EXPAND);
			hItem = m_tree.GetNextItem(hItem, TVGN_NEXT);
		}
	}

	if (m_inst)
	{
		// есть инициализирующая организация - выделяем ее в дереве
		int ind = -1;
		for(int i=0; i<m_listItems.Size; ++i)
		{
			if (m_listItems[i]->inst == m_inst)
			{
				ind = i;
				break;
			}
		}
		
		if (ind>=0)
		{
			m_tree.Select(m_listItems[ind]->m_item, TVGN_CARET);
		}
	}
	return TRUE;  // return TRUE  unless you set the focus to a control
}



void COrgStrDlg::OnItemexpandingTree1(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	// TODO: Add your control notification handler code here
	
     HTREEITEM item = pNMTreeView->itemNew.hItem;
     BOOL expanded = pNMTreeView->action & TVM_EXPAND;
	 if(!expanded)
	 {
		 *pResult = 0;
		 return;
	 }	
	if(!item)
		return;

	Expand((COrgStrTreeItem*)pNMTreeView->itemNew.lParam);
	*pResult = 0;
}
void COrgStrDlg::FindInstParent(CArray<CaplInstance*,CaplInstance*> &arr)
{

	CaplValue val;
	val.Set(arr[0]);
	int ind=aplQFindInstInExtentByAttr(&m_api->m_data, m_ext_rel, m_api->m_appr_mgr.a_org_rel_related, &val, false);
	if(ind>-1)
	{
		CaplInstance* ing;
		m_api->m_data.GetAttr(m_ext_rel[ind],m_api->m_appr_mgr.a_org_rel_relating,ing);
		arr.InsertAt(0,ing);
		FindInstParent(arr);
	}	
}


void COrgStrDlg::FindRootInst()
{
	if(m_ext_rel.Size>=m_ext.Size)
	{
		
		aplQSortByAttr(&m_api->m_data, m_ext_rel,0, m_ext_rel.Size-1, m_api->m_appr_mgr.a_org_rel_related);		
		for(int i=0; i<m_ext.Size; i++)
		{
			CaplInstance* inst = m_ext[i];
			CaplValue val;
			val.Set(inst);
			if(aplQFindInstInExtentByAttr(&m_api->m_data, m_ext_rel, m_api->m_appr_mgr.a_org_rel_related, &val, false)==-1)
				m_ext_root.Add(inst);
		}
	}
	else
	{
		m_api->m_data.GetEntityExtent(m_api->m_appr_mgr.e_org, m_ext_root);
		m_ext_root.Sort();
	
		CaplInstance* ed;
		for(int i=0; i<m_ext_rel.Size; i++)
		{
			m_api->m_data.GetAttr(m_ext_rel[i],m_api->m_appr_mgr.a_org_rel_related,ed);
			int ind=aplQFindInstInExtent(m_ext_root,ed, false);
			if(ind>-1)
				m_ext_root.Remove(ind);				
		}
		
	}
	
}

void COrgStrDlg::Expand(COrgStrTreeItem* ptr)
{
	if(ptr==NULL) return;

	CaplInstance* inst=ptr->inst;
	if(inst && !ptr->m_isExpand)
	{
		aplQSortByAttr(&m_api->m_data, m_ext_rel,0, m_ext_rel.Size-1, m_api->m_appr_mgr.a_org_rel_relating);		
		CaplValue val;
		val.Set(inst);
		bool isfind=false;
		for(int i=0;i<m_ext_rel.Size;i++)
		{
			CaplInstance* ed;
			CaplInstance* ing;
			m_api->m_data.GetAttr(m_ext_rel[i],m_api->m_appr_mgr.a_org_rel_relating,ing);
			if(ing==inst)
			{
				m_api->m_data.GetAttr(m_ext_rel[i],m_api->m_appr_mgr.a_org_rel_related,ed);
				CaplInstance* inst_ch=ed;
				if(inst_ch && inst_ch->GetAccessmode()<=aplRO)
				{
					CString name;
					//m_api->m_data.GetAttr(inst_ch,m_api->m_appr_mgr.a_org_name,name);
					m_api->GetItemName(inst_ch,name);
					int img=m_api->GetInstIco(inst);
					COrgStrTreeItem* tritem=new COrgStrTreeItem(&m_tree);
					tritem->inst=inst_ch;
					tritem->InsetItem(name,img,ptr->m_item);
					m_listItems.Add(tritem);
					isfind=true;
				}
			}
			else
				continue;
		}
			
		
		if(!isfind)
		{
			COrgStrTreeItem* tritem=(COrgStrTreeItem*)m_tree.GetItemData(ptr->m_item);
			if(tritem)
			{
				tritem->m_isExpand=true;
				m_tree.DeleteItem(tritem->m_dummy);
				tritem->m_dummy=NULL;
			}
		}
		m_tree.SortChildren(ptr->m_item);
	}
}

void COrgStrDlg::OnBtnfind() 
{
	int i;
	CFindOrgDlg dlg(m_api);
	if(dlg.DoModal()==IDCANCEL || !dlg.m_inst)
	{
		m_tree.SetFocus();
		return;
	}

	m_inst = dlg.m_inst;

	CaplTranslateDialog::OnOK();

	return;
	
	CArray<CaplInstance*,CaplInstance*> arr;
	arr.InsertAt(0,dlg.m_inst);
	aplQSortByAttr(&m_api->m_data, m_ext_rel,0, m_ext_rel.Size-1, m_api->m_appr_mgr.a_org_rel_related);
	FindInstParent(arr);
	COrgStrTreeItem* item=0;
	HTREEITEM hItem=m_tree.GetRootItem();
	ASSERT(hItem);
	bool isfind=false;
	for(i=0;i<arr.GetSize();i++)
	{
		isfind=false;
		hItem=i?m_tree.GetChildItem(hItem):m_tree.GetRootItem();
		while (hItem != NULL)
		{
			item=(COrgStrTreeItem*)m_tree.GetItemData(hItem);
			if(item->inst==arr[i])
			{
				Expand(item);
				isfind=true;
				break;
			}
			hItem = m_tree.GetNextItem(hItem, TVGN_NEXT);
		}
	}
	if(i==arr.GetSize() && hItem)
		m_tree.SelectItem(hItem);
	m_tree.SetFocus();
	
}

void COrgStrDlg::OnOK() 
{
	HTREEITEM hItem=m_tree.GetSelectedItem();
	if(hItem)
	{
		COrgStrTreeItem* item=(COrgStrTreeItem*)m_tree.GetItemData(hItem);
		m_inst=item->inst;
		CaplTranslateDialog::OnOK();
	}
	else
		MessageBox( APL_T("Выберите организацию."),_T(""));
}

