// Dlg_pdf_dot.cpp : implementation file
//

#include "stdafx.h"
#include "Dlg_pdf_dot.h"

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

/////////////////////////////////////////////////////////////////////////////
// CDlg_pdf_dot dialog


CDlg_pdf_dot::CDlg_pdf_dot(CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(CDlg_pdf_dot::IDD, pParent)
	, m_bSetRecursive(FALSE)
	, m_bSetVerID(FALSE)
{
	//{{AFX_DATA_INIT(CDlg_pdf_dot)
	m_iDoc = -1;
	//}}AFX_DATA_INIT
	pResult = NULL;
	m_date= COleDateTime::GetCurrentTime();
}


void CDlg_pdf_dot::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDlg_pdf_dot)
	DDX_Control(pDX, IDC_CR_PDFBPDF_DATE, m_ctrlDate);
	DDX_Control(pDX, IDC_CR_PDFBPDF_SNO, m_ctrlSno);
	DDX_Control(pDX, IDC_CR_PDFBPDF_CONT, m_ctrlCont);
	DDX_Control(pDX, IDC_CR_PDFBPDF_STATIC11, m_ctrlStatic);
	DDX_Control(pDX, IDOK, m_ctrlOK);
	DDX_Control(pDX, IDC_CR_PDFBPDF_PDF_DOT, m_ctrlPDF_dot);
	DDX_Control(pDX, IDC_CR_PDFBPDF_PDF, m_ctrlPDF);
	DDX_Control(pDX, IDC_CR_PDFBPDF_FOLDER_PDF, m_ctrlFolder);
	DDX_Control(pDX, IDC_CR_PDFBPDF_MASK_DOT, m_ctrlMask);
	DDX_Control(pDX, IDC_CR_PDFBPDF_NEW_VAL, m_ctrlNewVal);
	DDX_Control(pDX, IDC_CR_PDFBPDF_PROGRESS, m_ctrlProgress);
	DDX_Radio(pDX, IDC_CREATE_ASSOCIATE, m_iDoc);
	//}}AFX_DATA_MAP
	DDX_Check(pDX, IDC_CR_BYDOT_REC_CHECK, m_bSetRecursive);
	DDX_Check(pDX, IDC_CR_BYDOT_EMPTY_ID_CHECK2, m_bSetVerID);
}


BEGIN_MESSAGE_MAP(CDlg_pdf_dot, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CDlg_pdf_dot)
	ON_EN_CHANGE(IDC_CR_PDFBPDF_MASK_DOT, OnChangeMaskDot)
	ON_EN_CHANGE(IDC_CR_PDFBPDF_NEW_VAL, OnChangeNewVal)
	ON_BN_CLICKED(IDC_CR_PDFBPDF_SEL_DOT, OnSelDot)
	ON_BN_CLICKED(IDC_CR_PDFBPDF_SEL_FOLDER, OnSelFolder)
	ON_BN_CLICKED(IDC_CR_PDFBPDF_SET_FILTER, OnSetFilter)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDlg_pdf_dot message handlers

void CDlg_pdf_dot::OnChangeMaskDot() 
{
	static int beeps=0;
	CString t;
	m_ctrlMask.GetWindowText(t);
	if(m_s_dot.Find(t,0)>-1) m_s_mask = t;
	else
	{
		beeps++;
		Beep(300,20);
		m_ctrlMask.SetWindowText(m_s_mask);
		m_ctrlMask.SetSel(m_s_mask.GetLength(),m_s_mask.GetLength());
		if(beeps>2)
		{
			AfxMessageBox( APL_T("Вы вводите символы, которые не присутствуют в обозначении шаблона"));
			beeps=0;
		}
	}
	m_ctrlNewVal.GetWindowText(m_s_val);
	m_s_pdf = m_s_dot;
	if(m_s_val>_T(""))
		m_s_pdf.Replace(m_s_mask,m_s_val);
	m_ctrlPDF.SetWindowText(m_s_pdf);
}

void CDlg_pdf_dot::OnChangeNewVal() 
{
	m_ctrlMask.GetWindowText(m_s_mask);
	m_ctrlNewVal.GetWindowText(m_s_val);
	m_s_pdf = m_s_dot;
	if(m_s_mask>_T("") && m_s_val>_T(""))
		m_s_pdf.Replace(m_s_mask,m_s_val);
	m_ctrlPDF.SetWindowText(m_s_pdf);
	
}

void CDlg_pdf_dot::OnSelDot() 
{

	CaplAttrValue tst_value;
	aplExtent ext;
	tst_value.value.Set(APL_T("_Шаблон позаказного состава"));
	tst_value.attr=m_api->m_folder_mgr.a_folder_name;
	m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_folder_mgr.e_folder,1,&tst_value,ext,false);
	m_api->m_folder_mgr.LoadFolderInfo(ext);

	if(ext.GetSize())
		m_pdf = m_api->m_prd_mgr.SelectInstance(APL_MODE_SELECT_PDF, APL_T("Выбор шаблона"), &ext);
	else
		m_pdf = m_api->m_prd_mgr.SelectInstance(APL_MODE_SELECT_PDF, APL_T("Выбор шаблона"));
	
	if(!m_pdf) return;
	CaplInstance *prd;
	m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_prd,prd);
	m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_id,m_s_dot);
	m_ctrlPDF_dot.SetWindowText(m_s_dot);
	m_s_pdf = m_s_dot;
	m_s_mask = _T("");
	m_s_val = _T("");
	m_ctrlMask.SetWindowText(_T(""));
	m_ctrlNewVal.SetWindowText(_T(""));
	m_ctrlPDF.SetWindowText(m_s_pdf);
}

void CDlg_pdf_dot::OnSelFolder() 
{
	m_folder = m_api->m_folder_mgr.SelectInstance(APL_MODE_SELECT_FOLDER|APL_MODE_SELECT_PDF, APL_T("Выбор папки"));
	if(m_folder)
	{
		if(m_api->m_data.IsKindOf(m_folder,m_api->m_folder_mgr.e_folder))
		{
			CString name=_T("");
			m_api->m_data.GetAttr(m_folder,m_api->m_folder_mgr.a_folder_name,name);
			m_ctrlFolder.SetWindowText(name);
		}
	}
}		

void CDlg_pdf_dot::OnOK() 
{
	if(!UpdateData()) return;
	if(!m_api->m_data.IsConnected())
	{
		MessageBox( APL_T("Нет связи с БД"));
		return;
	}
	if(m_pdf==NULL) 
	{
		MessageBox( APL_T("Шаблон не выбран"));
		return;
	}
	if(m_s_mask==_T("") || m_s_val==_T("") || m_s_dot.Find(m_s_mask)<0)
	{
		MessageBox( APL_T("Не правильно задано значение маски или обозначения"));
		return;
	}
	if(m_folder==NULL) 
	{
		if(MessageBox( APL_T("Созданное изделие не будет привязано ни к какому элементу.\n Желаете продолжить?"),
			 APL_T("Внимание"),MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2)!=IDYES) return;
	}
	else if(m_folder->GetAccessmode()>aplRW)
	{
		MessageBox( APL_T("Нет доступа к объекту с которым необходимо связать изделие"));
		return;
	}
	CString p_name, d_name;
	m_ctrlPDF_dot.GetWindowText(p_name);
	m_ctrlPDF.GetWindowText(d_name);
	if(m_s_val==m_s_mask || p_name == d_name)
	{
		MessageBox( APL_T("Обозначение шаблона и изделия совпадают"));
		return;
	}
	BeginWaitCursor();
	m_cr_docs = m_iDoc;
	CString name, id, ver_id(_T(""));
	CString val;
	m_ctrlStatic.SetWindowText( APL_T("обработка состава изделия"));
	m_map.Clear();
	CString str;
	CaplInstance *prd;
	aplExtent d_oext,d_orel, t_ext;

	m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_prd,prd);
	m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_id,id);
	m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_name,name);
	m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_apl_pdf_type,str);
	if(m_bSetVerID)
		m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_id,ver_id);
	m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_descr,val);
	str.MakeLower();
	bool is_part = false;
	pr_count = 1;
	if(str==_T("part") || str==_T("material")) is_part = true;
	if(!is_part)
	{
		//Используя фильтры
		m_api->m_prd_mgr.LoadAllSubProduct(NULL,m_cont_filter,m_pdf,d_orel,d_oext);

		m_ctrlSno.GetWindowText(str);
		if(str>_T("")) 
			if(m_api->m_prd_mgr.FilterlBySN(d_orel,str,t_ext))
			{
				d_orel.Clear();
				d_orel.Append(t_ext);
			}
			else {MessageBox( APL_T("Не могу отфильтровать список")); return;}
		m_ctrlDate.GetWindowText(str);
		if(str>_T("")) 
			if(m_api->m_prd_mgr.FilterlByDate(d_orel,m_date,t_ext))
			{
				d_orel.Clear();
				d_orel.Append(t_ext);
			}
			else {MessageBox( APL_T("Не могу отфильтровать список")); return;}

		pr_count = d_orel.GetSize();
	}
	
	bool bSaveMode= m_api->m_AutoSave;
	m_api->SetAutoSave(false);

	m_ctrlProgress.SetStep(1);

	m_ctrlMask.GetWindowText(m_s_mask);
	m_ctrlNewVal.GetWindowText(m_s_val);
	CaplInstance *pr = m_pdf;
	if(id.Replace(m_s_mask,m_s_val))
	{
		CaplInstance* prd = m_api->m_prd_mgr.FindPrdById(id);
		if(prd)
		{
				CaplInstance* pdf = m_api->m_prd_mgr.FindPdfById(prd,ver_id);
				if(pdf && !pdf->attrs)
					m_api->m_prd_mgr.LoadPrdInfo(pdf);
				if(!m_bSetRecursive)
				{
// 					if(m_map.FindByOut((long)pdf)<0)
					{
						m_ctrlStatic.SetWindowText( APL_T("Изделие с таким обозначением уже существует"));
// 						MessageBox( APL_T("Изделие с таким обозначением уже существует"));
//						Undo(&m_map);
						return;
					}
				}
				pr= pdf;
		}
		else
		{
			pr = m_api->m_prd_mgr.CreatePdf(id,name,ver_id);
			pResult->Add(pr);
		}
	}
	ASSERT(pr);
	m_rez = pr;
	m_map.Add((long)m_pdf,(long)pr);
	CaplInstance *inst_prd;
	m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_pdf_prd,inst_prd);
	m_map.Add((long)prd,(long)inst_prd);

	CaplInstance *t_prd;
	m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_pdf_prd,t_prd);
	m_api->m_data.PutAttr(t_prd,m_api->m_prd_mgr.a_prd_descr,val);

	m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_descr,val);
	m_api->m_data.PutAttr(pr,m_api->m_prd_mgr.a_pdf_descr,val);

	m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_apl_pdf_type,val);
	m_api->m_data.PutAttr(pr,m_api->m_prd_mgr.a_apl_pdf_type,val);
	if(m_folder)
	{
		if(m_api->m_data.IsKindOf(m_folder,m_api->m_folder_mgr.e_folder)) 
			m_api->m_folder_mgr.AddToFolder(m_folder,pr);
		else if(m_api->m_data.IsKindOf(m_folder,m_api->m_prd_mgr.e_pdf))
			m_api->m_prd_mgr.CreatePdfRelation(NULL,m_folder,m_rez,_T(""),_T(""),1);
	}
		
	if(!is_part) 
		if(CreatePrd(m_pdf,m_folder,pr,m_s_mask,m_s_val,m_ctrlProgress,0)<0) 
		{
			MessageBox( APL_T("Не возможно выполнить операцию"));
			return;
		}
	if(m_iDoc<2)
	{
		//Обработка документов
		m_ctrlStatic.SetWindowText( APL_T("ассоциация документов"));
		Associateddocs(m_map);
	}
	//Обработка характеристик
	m_ctrlStatic.SetWindowText( APL_T("ассоциация характеристик"));
	AssociatedCharact(m_map);
	m_ctrlProgress.SetRange(0,1);
	m_ctrlProgress.SetPos(0);
	m_api->SetAutoSave(bSaveMode);
	m_api->SaveChanges();
	EndWaitCursor();
	m_ctrlStatic.SetWindowText( APL_T("Создание изделия по шаблону завершено"));
	MessageBox( APL_T("Создание изделия по шаблону завершено"), APL_T("Информация"),MB_ICONINFORMATION | MB_OK);
}

int CDlg_pdf_dot::CreatePrd(CaplInstance *prd, CaplInstance* folder, CaplInstance *parent, CString par, CString _par, CProgressCtrl &progress, int level)
{
	//prd - откуда найти версии, parent - куда добавить связь
	aplExtent oext,orel,t_ext;
	bool rez = m_api->m_prd_mgr.LoadAllSubProduct(NULL,m_cont_filter,prd,orel,oext);
	CString str;
	m_ctrlSno.GetWindowText(str);
	if(str>_T("")) 
		if(m_api->m_prd_mgr.FilterlBySN(orel,str,t_ext))
		{
			orel.Clear();
			orel.Append(t_ext);
		}
		else {MessageBox( APL_T("Не могу отфильтровать список")); return -1;}
	m_ctrlDate.GetWindowText(str);
	if(str>_T(""))
	{
		str=  m_date.Format(_T("%d %m %y"));
		if(m_api->m_prd_mgr.FilterlByDate(orel,m_date,t_ext))
		{
			orel.Clear();
			orel.Append(t_ext);
		}
		else {MessageBox( APL_T("Не могу отфильтровать список")); return -1;}
	}

	int count = orel.GetSize();
	if(level==0)
		{m_ctrlProgress.SetRange(0,count);	m_ctrlProgress.SetPos(0);}
	if(!rez || count<=0) return 1;
	for(int i=0; i<count; i++)
	{
		CaplInstance *pr = 0;//pdf - rel
		bool is_part = false;
		CString name, id, ver_id(_T("")), sCode;
		CaplInstance *p=0;
		CString val=_T("");//описание версии изд.
		CString pdr_id=_T(""), pdr_name=_T("");
		CaplInstance *pdr=NULL, *pdr_unit=NULL;

		m_api->m_data.GetAttr(orel[i],m_api->m_prd_mgr.a_pdr_r_ted,pr);
		m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_pdf_prd,p);
		if(m_bSetVerID)
			m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_id,ver_id);
		m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_pdf_id,ver_id);
		m_api->m_data.GetAttr(p,m_api->m_prd_mgr.a_prd_id,id);
		m_api->m_data.GetAttr(p,m_api->m_prd_mgr.a_prd_name,name);
		m_api->m_data.GetAttr(p,m_api->m_prd_mgr.a_prd_descr,val);
		bool repl=false;
		if(id.Replace(par,_par))
		{
			CaplInstance* prd = m_api->m_prd_mgr.FindPrdById(id);
			CaplInstance* pdf =NULL;
			if(prd) pdf= m_api->m_prd_mgr.FindPdfById(prd,ver_id);
			if(pdf && !pdf->attrs)
				m_api->m_prd_mgr.LoadPrdInfo(pdf);
			if(!pdf)
			{
				p = m_api->m_prd_mgr.CreatePdf(id,name,ver_id);
				pResult->Add(p);
			}
			else
			{
				if(!m_bSetRecursive)
				{
// 					if(m_map.FindByOut((long)pdf)<0)
 					{
						m_ctrlStatic.SetWindowText( APL_T("Изделие с таким обозначением уже существует"));
// 						MessageBox( APL_T("Изделие с таким обозначением уже существует"));
// 						Undo(&m_map);
						return -1;					
					}
				}
				p= pdf;					
			}
			
// 			CaplInstance* lp = m_api->m_prd_mgr.FindPrdById(id);
// 			if(!m_api->m_prd_mgr.FindPdfById(lp,ver_id))
// 			{
// 				p = m_api->m_prd_mgr.CreatePdf(id,name,_T(""));
// 				pResult->Add(p);
// 			}
// 			else
// 			{
// 				CaplInstance* prd = m_api->m_prd_mgr.FindPrdById(id);
// 				CaplInstance* pdf = m_api->m_prd_mgr.FindPdfById(prd,id);
// 				if(m_map.FindByOut((long)pdf)<0)
// 				{
// 					m_ctrlStatic.SetWindowText( APL_T("Изделие с таким обозначением уже существует"));
// 					MessageBox( APL_T("Изделие с таким обозначением уже существует"));
// 					Undo(&m_map);
// 					return -1;
// 				}
// 			}
			repl=true;
		}
		else
			p = pr;

		m_map.Add((long)pr,(long)p);
		if(m_api->m_data.IsKindOf(p,m_api->m_prd_mgr.e_pdf))
		{
			CaplInstance *_p, *_pr;
			m_api->m_data.GetAttr(p,m_api->m_prd_mgr.a_pdf_prd,_p);
			m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_pdf_prd,_pr);
			ASSERT(_p);
			ASSERT(_pr);
			m_map.Add((long)_pr,(long)_p);
			pResult->Add(_p);
		}
		
		double pdr_count=0;
		m_api->m_data.GetAttr(orel[i],m_api->m_prd_mgr.a_pdr_id,pdr_id);
		m_api->m_data.GetAttr(orel[i],m_api->m_prd_mgr.a_pdr_name,pdr_name);
		
		m_api->m_data.GetAttr(orel[i],m_api->m_prd_mgr.a_apl_qacu_value,pdr_count);

		m_api->m_data.GetAttr(orel[i],m_api->m_prd_mgr.a_apl_qacu_unit,pdr_unit);
		
		CaplInstance* t_parent = (CaplInstance*)m_map.GetByOut((long)parent);
		if(t_parent!=parent || repl)
			pdr = m_api->m_prd_mgr.CreatePdfRelation(NULL,parent,p,pdr_id,pdr_name,pdr_count,pdr_unit,true);
		else
			pdr = orel[i];
		ASSERT(pdr);
		m_map.Add((long)orel[i],(long)pdr);
		
		CaplInstance *t_prd;
		m_api->m_data.GetAttr(p,m_api->m_prd_mgr.a_pdf_prd,t_prd);
		m_api->m_data.PutAttr(t_prd,m_api->m_prd_mgr.a_prd_descr,val);

		m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_pdf_descr,val);
		m_api->m_data.PutAttr(p,m_api->m_prd_mgr.a_pdf_descr,val);

		m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_pdf_id,val);
		m_api->m_data.PutAttr(p,m_api->m_prd_mgr.a_pdf_id,val);
		
		m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_pdfwss_source,val);
		m_api->m_data.PutAttr(p,m_api->m_prd_mgr.a_pdfwss_source,val);

		m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_apl_pdf_type,val);
		m_api->m_data.PutAttr(p,m_api->m_prd_mgr.a_apl_pdf_type,val);
		if(val==_T("part") || val==_T("material")) is_part = true;

		bool stpart=false;//стандартное изд.
		m_api->m_data.GetAttr(pr,m_api->m_prd_mgr.a_apl_pdf_standard,stpart);
		m_api->m_data.PutAttr(p,m_api->m_prd_mgr.a_apl_pdf_standard,stpart);

		m_api->m_data.GetAttr(orel[i],m_api->m_prd_mgr.a_pdr_descr,val);
		m_api->m_data.PutAttr(pdr,m_api->m_prd_mgr.a_pdr_descr,val);
		
		
		aplExtent apl_Arr;
		m_api->m_data.GetAttr(orel[i],m_api->m_prd_mgr.a_pdr_frames_of_reference,apl_Arr);
		m_api->m_data.PutAttr(pdr,m_api->m_prd_mgr.a_pdr_frames_of_reference,apl_Arr);
		
		m_api->m_data.NET_SaveChanges();
		aplExtent d_oext,d_orel;
		if(!is_part && repl)
		{
			int i = m_map.FindByOut((long)p);
			int a=2;
			if(m_api->m_data.IsKindOf(p,m_api->m_prd_mgr.e_pdf)) a=3;
			if(i==m_map.Size-a)
			{
				int rez = CreatePrd(pr,folder,p,par,_par,progress, level+1);
				if(rez<0) return rez;
			}
		}
		if(level==0) progress.StepIt();
	}
	return 0;	
}

BOOL CDlg_pdf_dot::OnInitDialog() 
{
	if(!pResult)
	{
#ifdef _DEBUG
		AfxMessageBox( APL_T("Не определен массив результата"));
#endif
		SendMessage(WM_CLOSE);
	}
	else
	{
		CaplTranslateDialog::OnInitDialog();
		
		m_ctrlDate.SetWindowText( APL_T("Не задана"));
		m_ctrlSno.SetWindowText( APL_T("Не задан"));
		m_ctrlCont.SetWindowText( APL_T("Все контексты"));

		m_iDoc = 0;
		UpdateData(FALSE);

		pResult->Clear();
		m_rez = NULL;
		m_api->m_categ_mgr.LoadContextInfo();

		m_cont_filter = NULL;
		m_pdf = NULL;
		if(m_folder != NULL)
		{
/*			if(m_api->m_data.IsKindOf(m_folder,m_api->m_folder_mgr.e_folder))
			{
				CString name=_T("");
				m_api->m_data.GetAttr(m_folder,m_api->m_folder_mgr.a_folder_name,name);
				m_ctrlFolder.SetWindowText(name);
			}
			else
			if(m_api->m_data.IsKindOf(m_folder,m_api->m_prd_mgr.e_apl_pdf))
			{
				CString name=_T("");
				CaplInstance *prd=NULL;
				m_api->m_data.GetAttr(m_folder,m_api->m_prd_mgr.a_pdf_prd,prd);
				ASSERT(prd);
				m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_id,name);
				if(m_pdf==NULL)
				{
					m_ctrlPDF_dot.SetWindowText(name);
					m_pdf = m_folder;
					m_folder = NULL;
					m_s_dot = name;
				}
			}
*/
			CString name;
			m_api->GetItemName(m_folder, name);
			m_ctrlFolder.SetWindowText(name);
		}
		m_s_mask = _T("");
		m_s_val = _T("");
	}
	
	return TRUE;  // return TRUE unless you set the focus to a control
}

void CDlg_pdf_dot::OnSetFilter() 
{
	m_api->m_categ_mgr.LoadContextInfo();

	CaplInstance *new_cont=0;
	
	CString sn;
	m_ctrlSno.GetWindowText(sn);
	if(sn== APL_T("Не задан")) sn= _T("");

	CString date;
	m_ctrlDate.GetWindowText(date);
	if(date==_T("")||date== APL_T("Не задана")) m_date.SetStatus(COleDateTime::invalid);
	
	if(m_api->m_prd_mgr.SelectDateSN(sn, m_date, m_cont_filter, &new_cont))
	{
		if(sn.IsEmpty()) m_ctrlSno.SetWindowText( APL_T("Не задан"));
		else m_ctrlSno.SetWindowText(sn);
		
		CString buf=_T("");
		if(m_date.GetStatus()==COleDateTime::valid)
			buf=m_date.Format(_T("%d.%m.%Y  %H:%M:%S"));
		else
			buf=  APL_T("Не задана");

		m_ctrlDate.SetWindowText(buf);
		buf=_T("");
		
		m_cont_filter = new_cont;
		if(m_cont_filter)
		{
			aplExtent aggr;
			aggr.Add(m_cont_filter);
			m_api->m_prd_mgr.PrintItemContextInString(aggr,buf);
		}
		else
			buf= APL_T("Все контексты");
		
		m_ctrlCont.SetWindowText(buf);
	}
}

bool CDlg_pdf_dot::Associateddocs(CaplMap &map)
{
	aplExtent docs;
	for(int i=0; i<map.Size; i++)
	{
		CaplInstance *p = (CaplInstance*)map[i].in;
		docs.Add(p);
	}
	doc_map.Clear();
	CreateDocs(docs,0,map);
	doc_map.Clear();
	return true;
}

void CDlg_pdf_dot::AssociatedCharact(CaplMap &map)
{
	aplExtent charact, all_charact;
	int i;
	for(i=0; i<map.Size; i++)
	{
		if((CaplInstance*)map[i].in!=(CaplInstance*)map[i].out)
		{
			CaplInstance *p = (CaplInstance*)map[i].in;
			charact.Add(p);
			p = (CaplInstance*)map[i].out;
			all_charact.Add(p);
		}
	}
	aplExtent ext, gr, old_gr, groups;
	
	all_charact.Append(charact);
	m_api->m_charact_mgr.FindAssociatedCharacteristic(all_charact,ext, gr);
	m_api->m_charact_mgr.FindAssociatedCharacteristic(charact,ext, gr, false, false, false);

	int count_g = gr.GetSize();
	int count_e = ext.GetSize();
	m_ctrlProgress.SetRange(0,count_e);
	m_ctrlProgress.SetStep(1);
	m_ctrlProgress.SetPos(0);
	for(i=0; i<count_e; i++)
	{
		CaplInstance *in_group, *old=0, *_new=0, *old_char_val= 0, *old_char= 0, *old_type= 0;
		m_api->m_data.GetAttr(ext[i],m_api->m_charact_mgr.a_apl_charact_val_item,old);//_pdf);
		_new = (CaplInstance*)map.QGetPointerByIn((long)old);
		m_api->m_data.GetAttr(ext[i],m_api->m_charact_mgr.a_apl_charact_val_charact,old_char);
		m_api->m_data.GetAttr(ext[i],m_api->m_charact_mgr.a_apl_charact_val_type,old_type);
		old_char_val= m_api->m_charact_mgr.FindCharacteristic(_new, old_char, old_type, false, false);

		CaplInstance *ch = m_api->m_charact_mgr.CreateCopyCharacteristicVal(ext[i], old_char_val);
		ASSERT(ch);
		pResult->Add(ch);

		m_api->m_data.PutAttr(ch,m_api->m_charact_mgr.a_apl_charact_val_item,_new);

		m_api->m_data.GetAttr(ext[i],m_api->m_charact_mgr.a_apl_charact_val_group,in_group);
		if(in_group)
		{
			bool ok=false;
			for(int j=0; j<old_gr.GetSize();j++)
				if(old_gr[j]==in_group) 
				{
					m_api->m_data.PutAttr(ch,m_api->m_charact_mgr.a_apl_charact_val_group,groups[j]);
					ok = true;
				}
			if(!ok)
			{
				CaplInstance *gr = m_api->m_data.CreateInstance(m_api->m_charact_mgr.e_charact_val_group);
				ASSERT(gr);
				pResult->Add(gr);
				groups.Add(gr);
				old_gr.Add(in_group);
				CaplInstance *temp;
				m_api->m_data.GetAttr(in_group,m_api->m_charact_mgr.a_charact_val_group_def,temp);
				m_api->m_data.PutAttr(gr,m_api->m_charact_mgr.a_charact_val_group_def,temp);

				m_api->m_data.PutAttr(gr,m_api->m_charact_mgr.a_charact_val_group_item,_new);
				m_api->m_data.PutAttr(ch,m_api->m_charact_mgr.a_apl_charact_val_group,gr);
			}
		}
		m_ctrlProgress.StepIt();
	}
	groups.Clear();
	return;

}

bool CDlg_pdf_dot::CreateDocs(aplExtent& docs, int level, CaplMap &map)
{
	aplExtent o_ext, o_rel;
	if(!m_api->m_doc_mgr.FindAssociatedDocuments(docs,o_ext,o_rel,NULL)) return false;
	if(o_ext.Size==0 || o_rel.Size==0) return false;
	m_ctrlProgress.SetRange32(0,o_rel.Size);
	m_ctrlProgress.SetStep(1);
	m_ctrlProgress.SetPos(0);
	for(int i = 0; i<o_rel.Size; i++)
	{
		CaplInstance *pdf_o, *pdf_n, *d;
		m_api->m_data.GetAttr(o_rel[i],m_api->m_doc_mgr.a_apl_doc_ref_item,pdf_o);
		m_api->m_data.GetAttr(o_rel[i],m_api->m_doc_mgr.a_apl_doc_ref_doc,d);
		if(level==0)pdf_n = (CaplInstance*)map[map.FindByIn((long)pdf_o)].out;
		else pdf_n = (CaplInstance*)doc_map[doc_map.FindByIn((long)pdf_o)].out;
		CaplInstance *doc, *n_d=d;
		if(m_cr_docs>0)
		{
			TCHAR dir[255]=_T("");
			CString tmp_path, tmp; 
			aplGetTempPath(tmp_path);

			m_api->m_doc_mgr.GetFileName(d,tmp);
			tmp_path+=tmp;
			m_api->m_doc_mgr.LoadRevision(d,tmp_path,true);

			CString doc_id=_T(""), doc_name=_T(""), doc_desc=_T(""),doc_path=_T("");
			CaplInstance *doc_type;
			m_api->m_data.GetAttr(d,m_api->m_doc_mgr.a_doc_id,doc_id);
			m_api->m_data.GetAttr(d,m_api->m_doc_mgr.a_doc_name,doc_name);
			m_api->m_data.GetAttr(d,m_api->m_doc_mgr.a_doc_descr,doc_desc);
			m_api->m_data.GetAttr(d,m_api->m_doc_mgr.a_doc_kind,doc_type);
			int c_pos = doc_id.Replace(m_s_mask,m_s_val);
			int ind = doc_map.FindByIn((long)d);
			if(c_pos!=0 && ind<0)
			{
				n_d = m_api->m_doc_mgr.CreateDocument(doc_id,doc_name,doc_desc,doc_type,tmp_path,true,pdf_n,&doc);
				ASSERT(n_d);
				pResult->Add(n_d);
				RecursiveCreateNewDocs(d,n_d);
			}
			else if(c_pos!=0)
				m_api->m_doc_mgr.CreateAssociation(pdf_n,(CaplInstance*)doc_map.GetByIn((long)d));
			ASSERT(n_d);
		}
		else
		{
			CaplInstance* p1;
			p1 = (CaplInstance*)map.GetByIn((long)pdf_o);
			if(p1!=pdf_o)
				doc = m_api->m_doc_mgr.CreateAssociation(pdf_n,d);
			n_d = d;
		}
		ASSERT(doc);
		doc_map.Add((long)d,(long)n_d);
		
		m_ctrlProgress.StepIt();
	}

	return true;
}

bool CDlg_pdf_dot::Undo(CaplMap *map)
{
	m_ctrlProgress.SetPos(0);
	m_ctrlProgress.SetRange32(0,map->Size);
	m_ctrlProgress.SetStep(1);
	for(int i=0; i<map->Size; i++)
	{
		if(map->Data[i].in!=map->Data[i].out)
		{
			CaplInstance *prd;
			if(m_api->m_data.IsKindOf((CaplInstance*)map->Data[i].out,m_api->m_prd_mgr.e_pdf)) 
			{//только если пдф...
				m_api->m_data.GetAttr((CaplInstance*)map->Data[i].out,m_api->m_prd_mgr.a_pdf_prd,prd);
				m_api->m_data.DeleteInstance(prd);
			}
			m_api->m_data.DeleteInstance((CaplInstance*)map->Data[i].out);
		}
		m_ctrlProgress.StepIt();
	}
	return true;
}

bool CDlg_pdf_dot::RecursiveCreateNewDocs(CaplInstance *doc, CaplInstance *new_doc)
{
	aplExtent ext,rel;
	if(doc==NULL) return false;
	m_api->m_doc_mgr.FindAssociatedDocuments(doc,ext,rel);
	if(ext.Size==0) return true;

	TCHAR dir[255]=_T("");
	CString tmp_path,tmp; 
	aplGetTempPath(tmp_path);

	for(int i=0; i<ext.Size;i++)
	{
		m_api->m_doc_mgr.GetFileName(ext[i],tmp);
		tmp_path+=tmp;
		m_api->m_doc_mgr.LoadRevision(ext[i],tmp_path,true);

		CString doc_id=_T(""), doc_name=_T(""), doc_desc=_T(""),doc_path=_T("");
		CaplInstance *doc_type;
		m_api->m_data.GetAttr(ext[i],m_api->m_doc_mgr.a_doc_id,doc_id);
		m_api->m_data.GetAttr(ext[i],m_api->m_doc_mgr.a_doc_name,doc_name);
		m_api->m_data.GetAttr(ext[i],m_api->m_doc_mgr.a_doc_descr,doc_desc);
		m_api->m_data.GetAttr(ext[i],m_api->m_doc_mgr.a_doc_kind,doc_type);
		int c_pos = doc_id.Replace(m_s_mask,m_s_val);
		int ind = doc_map.FindByIn((long)ext[i]);
		if(c_pos!=0 && ind<0)
		{
			CaplInstance *n_d = m_api->m_doc_mgr.CreateDocument(doc_id,doc_name,doc_desc,doc_type,tmp_path,true,new_doc);
			ASSERT(n_d);
			pResult->Add(n_d);
			doc_map.Add((long)ext[i],(long)n_d);
			RecursiveCreateNewDocs(ext[i],n_d);
		}
	}
	return true;
}
