// ShowContentsDialog.cpp : implementation file
//

#include "stdafx.h"
#include "ShowContentsDialog.h"
#include "ChooseCharacteristicsDlg.h"
#include "ProgressDialog.h"
#include "FindQueryDlg.h"
#include "FindQueryDlgEx.h"
#include "DlgListCharTypes.h"
#include "ChooseConfigDlg.h"

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

extern bool (*funcGetAppByPdf)(CaplAPI*, CaplInstance*, aplExtent&);
extern bool (*funcGetComplectationByPdf)(CaplAPI*, CaplInstance*, aplExtent&);
extern bool (*funcLoadAppsInfo)(CaplAPI*, aplExtent&);
extern bool (*funcLoadComplectationsInfo)(CaplAPI*, aplExtent&);
extern bool (*funcFilterByAppOrComplectation)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool, LPCTSTR);

bool AFX_EXT_API DoShowContentsDialog(CaplAPI *api,CaplInstance *pdf,int mode)
{

	CaplSetResourceHandle setres(module_inst);
	CShowContentsDialog dlg;
	dlg.m_pdf=pdf;
	dlg.m_api=api;
	dlg.m_mode=mode;
	dlg.DoModal();
	return true;
}
/////////////////////////////////////////////////////////////////////////////
// CShowContentsDialog dialog
#define firctcol 8


CShowContentsDialog::CShowContentsDialog(CWnd* pParent /*=NULL*/)
	: CResizableDialog(CShowContentsDialog::IDD, pParent)
{
	//{{AFX_DATA_INIT(CShowContentsDialog)
	//}}AFX_DATA_INIT
	m_pdf=0;
	m_pComplectation = NULL;
	//m_list.SetUniqueName(_T("contents"));
	m_mode=-1;
	b_no_close=false;
	m_api=0;
	m_extents=_T("");m_fields=_T("");
	m_Filter=_T("");	
	m_query=_T("");
}


void CShowContentsDialog::DoDataExchange(CDataExchange* pDX)
{
	CResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CShowContentsDialog)
	DDX_Control(pDX, IDC_RUN, m_run_btn);
	DDX_Control(pDX, IDC_SEL_CONTEXT, m_sel_context);
	DDX_Control(pDX, IDC_EFF_TIME, m_eff_time);
	DDX_Control(pDX, IDC_EFF_SN, m_eff_sn);
	DDX_Control(pDX, IDC_EFF_DATE, m_eff_date);
	DDX_Control(pDX, IDC_USE_SN, m_UseSN);
	DDX_Control(pDX, IDC_USE_DATETIME, m_UseDT);
	DDX_Control(pDX, IDC_FILTR_RAMK, m_filtr_ramk);
	DDX_Control(pDX, IDC_SHOW_ALL_PART, m_show_all_part_btn);
	DDX_Control(pDX, IDCANCEL, m_exit);
	DDX_Control(pDX, ID_SAVE_TO_FILE, m_save_to_file);
	DDX_Control(pDX, ID_SELECT_CHARACTERYSTIC_SET, m_sel_charact_set);
	DDX_Control(pDX, ID_SELECT_CHARACTERYSTIC_SET_SELECTED, m_sel_charact_set_sel);
	DDX_Control(pDX, IDC_LIST1, m_list);
	DDX_Control(pDX, IDC_PRF_SEL, m_prd_sel);
	DDX_Control(pDX, IDC_PRD_NAME, m_prd_name);
	DDX_Control(pDX, IDC_PRD_ID, m_prd_id);
	DDX_Control(pDX, IDC_PDF_ID, m_pdf_id);
	DDX_Control(pDX, IDC_PRD_RAMK, m_prd_ramk);
	DDX_Control(pDX, IDC_BTN_SELECT_COLUMN, m_BtnSelectColumns);
	DDX_Text(pDX, IDC_FILTER, m_Filter);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, ID_FILTER, m_btnFilter);
}


BEGIN_MESSAGE_MAP(CShowContentsDialog, CResizableDialog)
	//{{AFX_MSG_MAP(CShowContentsDialog)
	ON_NOTIFY(NM_RCLICK, IDC_ST_LIST, OnRclickListObjects)
	ON_BN_CLICKED(IDC_PRF_SEL, OnPdfSel)
	ON_BN_CLICKED(IDC_RUN, OnBegin)
	ON_BN_CLICKED(IDC_SEL_FILTER, OnSelFilter)
	ON_BN_CLICKED(ID_SAVE_TO_FILE, OnSaveToFile)
	ON_BN_CLICKED(ID_SELECT_CHARACTERYSTIC_SET, OnSelectCharacterysticSet)
	ON_BN_CLICKED(IDC_SHOW_ALL_PART, OnShowAllPart)
	ON_BN_CLICKED(IDC_USE_DATETIME, OnUseDatetime)
	ON_BN_CLICKED(IDC_USE_SN, OnUseSn)
	ON_BN_CLICKED(IDC_BTN_SELECT_COLUMN, OnBtnSelectColumn)
	ON_WM_SIZE()
	ON_BN_CLICKED(ID_SELECT_CHARACTERYSTIC_SET_SELECTED, OnSelectCharacterysticSetSelected)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(ID_FILTER, &CShowContentsDialog::OnBnClickedFilter)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CShowContentsDialog message handlers
void CShowContentsDialog::OnShowAllPart() 
{
	if(m_show_all_part_btn.GetCheck()==0)	{m_mode=0;SetWindowText( APL_T("Подетальный состав"));}
	else	{m_mode=1;SetWindowText( APL_T("Полный состав"));}
}
//********************************************************************
void CShowContentsDialog::OnUseDatetime() 
{
	Clear();
	if(m_UseDT.GetCheck())
	{
		m_eff_date.EnableWindow(TRUE);
		m_eff_time.EnableWindow(TRUE);
		//m_UseSN.SetCheck(0);
		//OnUseSn();
	}
	else
	{
		m_eff_date.EnableWindow(FALSE);
		m_eff_time.EnableWindow(FALSE);
	}
	
}
//********************************************************************
void CShowContentsDialog::OnUseSn() 
{
	Clear();
	if(m_UseSN.GetCheck())
	{
		m_eff_sn.EnableWindow(TRUE);
		//m_UseDT.SetCheck(0);
		//OnUseDatetime();
	}
	else m_eff_sn.EnableWindow(FALSE);
	
}
//********************************************************************
BOOL CShowContentsDialog::OnInitDialog() 
{
	if(m_api==0) return FALSE;
	
	m_list.CreateFromStatic(IDC_ST_LIST,this,0,true);
	CResizableDialog::OnInitDialog();

	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   
	
	// TODO: Add extra initialization here
	m_save_to_file.EnableWindow(FALSE);
	m_sel_charact_set.EnableWindow(FALSE);
	m_sel_charact_set_sel.EnableWindow(FALSE);
	//if(m_doc==0)m_prd_sel.EnableWindow(FALSE);
	m_show_all_part_btn.SetCheck(0);
	if(m_mode!=-1) m_show_all_part_btn.EnableWindow(FALSE); 
	else m_mode=0;
	
	if(m_mode==0)	{SetWindowText( APL_T("Подетальный состав")); m_show_all_part_btn.SetCheck(0);}
	else	{SetWindowText( APL_T("Полный состав")); m_show_all_part_btn.SetCheck(1);}

	if(m_pdf!=0)
	{
		m_prd_sel.EnableWindow(FALSE);
		SetPdf();
	}

//	AddAnchor(IDOK, BOTTOM_RIGHT);
	AddAnchor(IDC_PRD_RAMK, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_PRD_ID, TOP_LEFT,TOP_CENTER);
	AddAnchor(IDC_STATIC_PRD_ID, TOP_LEFT,TOP_CENTER);
	AddAnchor(IDC_PRD_NAME, TOP_CENTER, TOP_RIGHT);
	AddAnchor(IDC_STATIC_PRD_NAME, TOP_CENTER, TOP_RIGHT);
	AddAnchor(IDC_PDF_ID, TOP_RIGHT);
	AddAnchor(IDC_STATIC_PDF_ID, TOP_RIGHT);
	AddAnchor(IDC_PRF_SEL, TOP_RIGHT);

	AddAnchor(IDC_USE_SN, TOP_LEFT);
	AddAnchor(IDC_FILTR_CONTENT_RAMK, TOP_LEFT);
	AddAnchor(IDC_EFF_SN, TOP_LEFT);
	AddAnchor(IDC_USE_DATETIME, TOP_LEFT);
	AddAnchor(IDC_EFF_DATE, TOP_LEFT);
	AddAnchor(IDC_EFF_TIME, TOP_LEFT);
	AddAnchor(IDC_CONTEXT_STATIC, TOP_LEFT);
	AddAnchor(IDC_SEL_CONTEXT, TOP_LEFT);

	AddAnchor(IDC_FILTR_RESULT_RAMK, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_SEL_FILTER, TOP_RIGHT);
	AddAnchor(IDC_FILTER, TOP_LEFT,TOP_RIGHT);
	
	AddAnchor(IDC_RUN, TOP_RIGHT);
	AddAnchor(IDC_ST_LIST, TOP_LEFT, BOTTOM_RIGHT);

	AddAnchor(IDC_BTN_SELECT_COLUMN, BOTTOM_CENTER);
	AddAnchor(ID_SAVE_TO_FILE, BOTTOM_CENTER);
	AddAnchor(ID_SELECT_CHARACTERYSTIC_SET, BOTTOM_LEFT);
	AddAnchor(ID_SELECT_CHARACTERYSTIC_SET_SELECTED, BOTTOM_LEFT);
	AddAnchor(ID_FILTER, BOTTOM_RIGHT);
	AddAnchor(IDCANCEL, BOTTOM_RIGHT);

//	AddAnchor(IDC_CONTENTS, TOP_LEFT, BOTTOM_RIGHT);
	
	m_exit.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_exit.SetFlat(FALSE);
	m_run_btn.SetIcon(GetAplStdIco16(APLSTDICO_PLAY));
	m_run_btn.SetFlat(FALSE);
	m_save_to_file.SetIcon(GetAplTableIco(APL_TABLE_SAVE));
	m_save_to_file.SetFlat(FALSE);
	m_sel_charact_set.SetIcon(GetAplTableIco(APL_TABLE_SELECT_CHAR));
	m_sel_charact_set.SetFlat(FALSE);
	m_sel_charact_set_sel.SetIcon(GetAplTableIco(APL_TABLE_SELECT_CHAR));
	m_sel_charact_set_sel.SetFlat(FALSE);
	m_BtnSelectColumns.SetIcon(GetAplTableIco(APL_TABLE_WIDTH));
	m_BtnSelectColumns.SetFlat(FALSE);

	m_btnFilter.SetIcon(GetAplTableIco(APL_TABLE_TOOLS));
	m_btnFilter.SetFlat(FALSE);

	// Заполнение контекстов
	int i,j;
	CString buf;
	aplExtent ext_contexts;
	apidata.GetEntityExtent(m_api->m_prd_mgr.e_pd_context,ext_contexts);
	for(i=0;i<ext_contexts.Size;i++)
	{
		apidata.GetAttr(ext_contexts[i],m_api->m_prd_mgr.a_pd_context_name,buf);
		j=m_sel_context.AddString(buf);
		m_sel_context.SetItemData(j,(long)ext_contexts[i]);
	}
	j=m_sel_context.AddString( APL_T("Все контексты"));
	m_sel_context.SetItemData(j,0);
	m_sel_context.SetCurSel(j);

	//////////////////////////////////////////////////////////////////////////

#ifdef _DEBUG
	CString strLibFileName = CString(_T("aplConfiguratorMgrD.dll"));
#else
	CString strLibFileName = CString(_T("aplConfiguratorMgr.dll"));
#endif

	HINSTANCE hConfigMgrLib = AfxLoadLibrary(strLibFileName);

	if (hConfigMgrLib != NULL)
	{
		(FARPROC&)funcGetAppByPdf = ::GetProcAddress(hConfigMgrLib, "add_GetAppByPdf");
		(FARPROC&)funcFilterByAppOrComplectation = ::GetProcAddress(hConfigMgrLib, "add_BasisAndComplectationFilter");		
		(FARPROC&)funcGetComplectationByPdf = ::GetProcAddress(hConfigMgrLib, "add_GetComplectationByPdf");
		(FARPROC&)funcLoadAppsInfo = ::GetProcAddress(hConfigMgrLib, "add_LoadConfigurationsInfo");
		(FARPROC&)funcLoadComplectationsInfo = ::GetProcAddress(hConfigMgrLib, "add_LoadComplectationsInfo");		
	}

	BOOL bIsAppAvailable = (funcGetAppByPdf != NULL);
	BOOL bIsComplectationAvailable = (funcGetComplectationByPdf != NULL);

	m_btnFilter.ShowWindow((bIsAppAvailable || bIsComplectationAvailable) ? SW_SHOW : SW_HIDE);

	//////////////////////////////////////////////////////////////////////////

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

//********************************************************************
void CShowContentsDialog::OnPdfSel() 
{
	// TODO: Add your control notification handler code here
	if(m_api==0) return;
	m_pdf=m_api->m_prd_mgr.SelectInstance(APL_MODE_SELECT_PDF, APL_T("Выберите версию изделия"));
	if(m_pdf!=0)SetPdf();
}
//********************************************************************
void CShowContentsDialog::SetPdf()
{
	Clear();
	m_save_to_file.EnableWindow(FALSE);
	m_sel_charact_set.EnableWindow(FALSE);
	m_sel_charact_set_sel.EnableWindow(FALSE);
	m_pdf_id.SetWindowText(_T(""));
	m_prd_id.SetWindowText(_T(""));
	m_prd_name.SetWindowText(_T(""));
	if(m_api==0) return;
	if(m_pdf==0) return;
	CString buf,id,ver;
	CaplInstance *i_prd;
	apidata.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_id,ver);
	m_pdf_id.SetWindowText(ver);
	apidata.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_prd,i_prd);
	apidata.GetAttr(i_prd,m_api->m_prd_mgr.a_prd_id,id);
	m_prd_id.SetWindowText(id);
	apidata.GetAttr(i_prd,m_api->m_prd_mgr.a_prd_name,buf);
	m_prd_name.SetWindowText(buf);

	m_def_file_name=id;
	if(ver!=_T("")){m_def_file_name+=_T("-");m_def_file_name+=ver;};
//	OnBegin();
}

void CShowContentsDialog::Clear()
{
	m_list.DeleteAllItems();
	while (m_list.DeleteColumn(firctcol));
}
//********************************************************************
class CaplDAssemblyPart
{
public:
	CaplDAssemblyPart(CaplInstance *in_unit,double in_count) {unit=in_unit; count=in_count;}
	CaplInstance *unit;
	double count;
};

void CShowContentsDialog::OnBegin() 
{
	Clear();
	if(m_api==0) return;
	if(m_pdf==0) return;
	aplInstArray ext_unit;
	aplRealArray count_array;
	aplExtent ext_query;

	int i;//,k;
	CaplInstance *i_context,*i_pdf;//,*i_prd;
	CString id,name,ver,buf;
	CString buf1,buf2;
	bool ff=false;
	bool is_dialog=false;
	if(m_mode==0) ff=true; 

	i_context=(CaplInstance *)m_sel_context.GetItemData(m_sel_context.GetCurSel());

	CString sn=_T("");
	TCHAR *pSN=0;
	CString str_date=_T("");

	//StartBusy();
	bool b_ok=false;
	if((m_UseSN.GetCheck()!=0) || (m_UseDT.GetCheck()!=0))
	{
		COleDateTime *dt=0;
		
		if(m_UseSN.GetCheck()) {m_eff_sn.GetWindowText(sn); if(sn!=_T("")) pSN=(TCHAR*)LPCTSTR(sn);}
		if(m_UseDT.GetCheck())
		{
			COleDateTime date,time;
			m_eff_date.GetTime(date);
			m_eff_time.GetTime(time);
			dt=new COleDateTime(date.GetYear(),date.GetMonth(),date.GetDay(),
				time.GetHour(),time.GetMinute(),time.GetSecond());
			if(dt!=0){aplDate2String(*dt,str_date);}
		}
		if(dt!=0) delete dt;
	}
/*DIV: Начало изменений
Временно меняю новый вариант - читающий по одному PDF на старый - читающий PDF пачкой.  
		b_ok=m_api->m_prd_mgr.DisassemblyProduct(0,i_context,m_pdf,m_ext_pdf,count_array,ext_unit,ff);
/**/
	CaplMap map_pdf,map_unit;
	aplExtent ext_rel,ext_pdf,ext_unit1;
	int k,l;
	bool unit_found;
	double curr_count=0;
	CaplDAssemblyPart *dap0=0,*dap1=0;
	CString query;


	// рекурсивно дизасемблируем

	clock_t t0=clock();
	b_no_close=true;
	b_ok=m_api->m_prd_mgr.DisassemblyProduct(i_context,m_pdf,ext_rel,ext_pdf,count_array,ext_unit1,str_date,pSN,ff, NULL, NULL, m_pComplectation);
	for(k=0;k<ext_pdf.GetSize();k++){
		if(ext_pdf[k]==0) continue;
		dap0=new CaplDAssemblyPart(ext_unit1[k],count_array[k]);
		map_pdf.Add((long)ext_pdf[k],(long)dap0);
	}

	clock_t t1=clock();
	double disasembly_time =difftime(t1,t0);

	// убираем дубли и суммируем количества по юнитам
	map_pdf.SortIn();
	m_ext_pdf.Clear();count_array.RemoveAll();
	for(k=0;k<map_pdf.Size;k++){
		dap1=(CaplDAssemblyPart*)map_pdf[k].out;
		if(dap1==0)continue;
		if(k>0){
			if(map_pdf[k].in==map_pdf[k-1].in){
				dap0=(CaplDAssemblyPart*)map_pdf[k-1].out;
				if(dap0!=0){
					unit_found=false;
					// может быть, у одного pdf несколько unit-ов чередуются. Проверим что было раньше
					for(l=0;l<map_unit.Size;l++){
						if(map_unit[l].in==(long)dap1->unit){
							curr_count=count_array[map_unit[l].out];
							curr_count+=dap1->count;
							count_array.SetAt(map_unit[l].out,curr_count);
							unit_found=true;
							break;
						}
					}
					if(unit_found)continue;
				}
			}else{
				map_unit.Clear();
			}
		}
		if((CaplInstance*)map_pdf[k].in !=0 ) m_ext_pdf.Add((CaplInstance*)map_pdf[k].in);
		ext_unit.Add(dap1->unit);
		count_array.Add(dap1->count);
		map_unit.Add((long)dap1->unit,count_array.GetSize()-1);
	}
	// чистим память после разборки
	for(k=0;k<map_pdf.Size;k++){dap1=(CaplDAssemblyPart*)map_pdf[k].out;delete dap1;}
	b_no_close=false;

/*DIV: Конец изменений*/


	if(((m_fields!=_T("") && m_extents!=_T(""))||(m_query!=_T(""))) && b_ok && m_ext_pdf.Size > 0)
	{
		int indx_pdf=0;
		int size_q=0;
		aplExtent ext_query_tmp;
		while(indx_pdf<m_ext_pdf.Size)
		{
			buf1=_T("\nExt_composed_internal_PSS{");
			while(size_q < 500 && indx_pdf<m_ext_pdf.Size)
			{
				buf2.Format(_T("#%i"),m_ext_pdf.GetAt(indx_pdf)->GetId());
				if(size_q>0)buf1+=_T(",");
				buf1+=buf2;
				indx_pdf++;
				size_q++;
			}
			buf1+=_T("}\n");

			if(m_query.IsEmpty()==TRUE)
			{
				query=_T("SELECT\n");
				if(m_fields==_T(""))
				{
					query+=_T(" Ext_composed_internal_PSS\n");
				}
				else
				{
					query+=m_fields + _T(" AND Ext_composed_internal_PSS\n");
				}
				query+=_T("FROM\n")+buf1+m_extents+_T("\nEND_SELECT");
			}
			else
			{
				// пользователь ввел запрос вручную, придется похимичить
				int pos_sel,pos_from,pos_end;
				CString t_query=m_query;
				t_query.MakeUpper();
				pos_sel=t_query.Find(_T("SELECT"));
				pos_from=t_query.Find(_T("FROM"));
				pos_end=t_query.Find(_T("END_SELECT"));
				if(pos_sel==-1){AfxMessageBox( APL_T("Ошибочный запрос пользователя - отсутствует ключевое слово SELECT"));return;}
				if(pos_from==-1){AfxMessageBox( APL_T("Ошибочный запрос пользователя - отсутствует ключевое слово FROM"));return;}
				if(pos_end==-1){AfxMessageBox( APL_T("Ошибочный запрос пользователя - отсутствует ключевое слово END_SELECT"));return;}
				pos_sel+=6;
				query=_T("SELECT\n Ext_composed_internal_PSS AND (")+m_query.Mid(pos_sel,pos_from-pos_sel)+_T(")\n");
				pos_from+=4;
				query+=_T("FROM\n")+buf1+m_query.Mid(pos_from,m_query.GetLength()-pos_from);
			}

			if(is_dialog)
			{
				m_api->m_data.NET_QueryEditParse(query,true);
			}

			b_ok=m_api->m_query_mgr.ExecuteQuery(query,ext_query_tmp);
			if(!b_ok){
				AfxMessageBox( APL_T("Ошибка выполнения запроса!"));
				return;
			}
			ext_query.Append(ext_query_tmp);
			size_q =0;

		}

		CSortClass::SortExtentById(ext_query);

		
		// чтобы удаление сработало
		m_ext_pdf.ListMode=true;ext_unit.ListMode=true;
		for(i=m_ext_pdf.Size-1;i>=0;i--)
		{	
			aplQFindInstIdInExtent(ext_query,m_ext_pdf[i]->GetId(),-1,true,&(i_pdf));
			if(i_pdf==0 || i_pdf!=m_ext_pdf[i]){
				m_ext_pdf.Remove(i);
				count_array.RemoveAt(i);
				ext_unit.Remove(i);
			}
		}
	}	

	if(b_ok)
	{
		m_Items.Clear();
		
		for(i=0;i<m_ext_pdf.Size;i++){
			m_Items.Add(new SItemColumnData(m_ext_pdf.GetAt(i),count_array[i],ext_unit[i]));
		}
		
		m_list.m_api=m_api;
		m_list.SaveColumnWidths();
		m_list.SetData(m_Items);
		if(m_list.IsVisibleDefault())
		{
			m_list.VisibleColumnRemove(0,OBJ_COL_INSTANCE_ID);
			m_list.VisibleColumnRemove(0,OBJ_COL_DESCRIPT);
			m_list.VisibleColumnRemove(0,OBJ_COL_SERNUM);
			m_list.VisibleColumnRemove(0,OBJ_COL_CODE_OBJ);
			m_list.VisibleColumnRemove(0,OBJ_COL_CODE_VER);
		}
		
		m_list.FillTable();
		if(m_ext_pdf.Size==0){
			AfxMessageBox( APL_T("Ничего не найдено"));
		}

	}
	if(m_ext_pdf.Size>0)
	{
		m_save_to_file.EnableWindow(TRUE);
		m_sel_charact_set.EnableWindow(TRUE);
		m_sel_charact_set_sel.EnableWindow(TRUE);
	}

	//if(disasembly_time>7000)
	{
		buf.Format( APL_T("Готово!\n\nВремя разбора %.1f сек.\n\n Найдено %i "), disasembly_time/1000,m_ext_pdf.GetSize());
		AfxMessageBox(buf);
	}
}

void CShowContentsDialog::OnSaveToFile() 
{
	// формируем буфер с названием изделия
	CString buf,buf1;
	m_prd_id.GetWindowText(buf1);
	buf=buf1;
	m_prd_name.GetWindowText(buf1);
	buf+=_T(" : ")+buf1;
	m_pdf_id.GetWindowText(buf1);
	buf+=_T(" : ")+buf1;
	apl_SaveListCtrlToFile(&m_list,LPCTSTR(m_def_file_name),buf);
}

void CShowContentsDialog::OnSelectCharacterysticSet() 
{
	// TODO: Add your control notification handler code here
	m_list.SelectCharacterysticSet(0,true,-1,-1,true);

}

void CShowContentsDialog::OnSelectCharacterysticSetSelected() 
{
	// TODO: Add your control notification handler code here
	CDlgListCharTypes dlg;
	dlg.m_api=m_api;
	dlg.m_list_charact=&m_list_charact;
	if(dlg.DoModal()!=IDOK){
		return;
	}
	m_list.SetCharacterysticFromExt(m_list_charact,0,true);
}


void CShowContentsDialog::OnCancel() 
{
	if(b_no_close)	return;
	
	CResizableDialog::OnCancel();
}

void CShowContentsDialog::OnSelFilter() 
{
	// TODO: Add your control notification handler code here
	if(aplShowFilterDlg(m_api, APL_T("Фильтр на поиск по составу"), APL_MODE_SELECT_PDF, m_filter_query_buf, m_extents, m_fields, m_Filter, m_query))
	{
		UpdateData(FALSE);
	}
}

void CShowContentsDialog::OnBtnSelectColumn() 
{
	// TODO: Add your control notification handler code here
	m_list.SelectColumnsOrder(0);
	
}

void CShowContentsDialog::OnRclickListObjects(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	*pResult = 0;
	aplExtent ext;
	CUIntArray array;
	const MSG* msg;
	CaplInstance *inst;
	int i=0;
	bool has_chg_state=false, has_other=false;

	msg=GetCurrentMessage();


	m_list.GetSelectedElements(array);

// 	CString str;str.Format( APL_T("Всего строк %i; выделено строк %i"),m_CountALlString,array.GetSize());
// 	m_CountString.SetWindowText(str);

	if(m_Items.GetSize()==0)
		return;
	ext.Clear();

	for(i=0;i<array.GetSize();i++)
	{
		inst = m_Items.GetAt(array[i])->m_inst;

		if(m_api->m_data.IsKindOf(inst,m_api->m_prd_mgr.e_pdf) || m_api->m_data.IsKindOf(inst,m_api->m_doc_mgr.e_doc) || 
			m_api->m_data.IsKindOf(inst,m_api->m_bp_mgr.e_bp) || m_api->m_data.IsKindOf(inst,m_api->m_change_mgr.e_chng) || 
			m_api->m_data.IsKindOf(inst,m_api->m_req_mgr.e_requirement))
		{
			has_chg_state = true;
		}
		else
		{
			has_other = true;
		}
		ext.Add(inst);
	}

	CaplTAggr<SMenuItemDescription*,SMenuItemDescription*,APLAGGR_AUTOKILLREF> add_menu;
// 	add_menu.Add(new SMenuItemDescription(ID_MENU_DELETE, APL_T("Удалить выделенные объекты из списка"),true));
// 	add_menu.Add(new SMenuItemDescription(ID_MENU_DELETE_ALL, APL_T("Удалить все объекты из списка")));
// 	add_menu.Add(new SMenuItemDescription(ID_MENU_DELETE_FROM_BD, APL_T("Удалить выделенные объекты из БД")));

	if(has_chg_state)
	{
		UINT nFlags = MF_SEPARATOR;
// 		add_menu.Add(new SMenuItemDescription(0, _T(""),false,nFlags));
		if(!m_api->m_data.IsAdmin() || has_other) nFlags = MF_GRAYED|MF_STRING; else nFlags = 0;
		add_menu.Add(new SMenuItemDescription(ID_MENU_CHANGE_STATE, APL_T("Изменить состояние выделенных объектов"),true,nFlags));
	}

	// если от CInstPropertyCtrl нужно только стандартное контестное меню, то проще
	// не обрабатывать RClick, а вызвать в OnInitDialog функцию CInstPropertyCtrl::SetContexMenuMode
	UINT command=m_list.ProcessContextMenu(msg->pt,true,true,false,&add_menu,true,true/*,&removed*/);
	switch (command)
	{
	case ID_MENU_CHANGE_STATE:
		m_api->m_doc_mgr.ChangeWFState(ext);
		break;
// 	case ID_MENU_DELETE_ALL: 
// 		if(AfxMessageBox(m_delete_message_all,MB_YESNO)==IDYES){
// 			m_content->Clear();
// 			FeelTableCtrl();
// 			m_changed=true;
// 		}
// 		break;
// 	case ID_MENU_DELETE: 
// 		if(AfxMessageBox(m_delete_message,MB_YESNO)==IDYES){
// 			for(i=0;i<ext.GetSize();i++){
// 				for(j=0;j<m_content->GetSize();j++){
// 					if(ext.GetAt(i)==m_content->GetAt(j)){
// 						m_content->Remove(j);
// 						break;
// 					}
// 				}
// 			}
// 			FeelTableCtrl();
// 			m_changed=true;
// 		}
// 		break;
// 	case ID_MENU_DELETE_FROM_BD: 
// 		if(m_api==0){break;}
// 		if(AfxMessageBox(m_delete_message_from_BD,MB_YESNO)==IDYES){
// 			m_api->SetModeInteractive(false);
// 			bool prevAutoSave=m_api->m_AutoSave;
// 			m_api->SetAutoSave(false);
// 			long trd=aplStartWaitDlg( APL_T("Удаление элементов"));
// 			int count_not_del=0;
// 			bool err=false;
// 			for(i=0;i<ext.GetSize();i++){
// 				if(ext.GetAt(i)->GetAccessmode()>aplOWN){
// 					count_not_del++;
// 					continue;
// 				}
// 				if(!m_api->DeleteItem(ext[i]))
// 				{
// 					err=true;
// 				}else{
// 					for(j=0;j<m_content->GetSize();j++){
// 						if(ext.GetAt(i)==m_content->GetAt(j)){
// 							m_content->Remove(j);
// 							break;
// 						}
// 					}
// 				}
// 			}
// 			aplEndWaitDlg(trd);
// 			m_api->SetAutoSave(prevAutoSave);
// 			if(prevAutoSave)m_api->SaveChanges();
// 			if(err)
// 			{
// 				AfxMessageBox( APL_T("Не удалось удалить некоторые элементы!"));
// 			}
// 			m_api->SetModeInteractive(true);
// 			FeelTableCtrl();
// 			m_changed=true;
// 			if(count_not_del!=0)
// 			{
// 				str.Format( APL_T("Не удалось удалить %i объектов - нет прав доступа"));
// 				AfxMessageBox(str);
// 			}
// 		}
// 		break;
	}
}

void CShowContentsDialog::OnBnClickedFilter()
{
	CChooseConfigDlg dlg;

	dlg.m_api = m_api;
	dlg.m_pSelectedItem = m_pComplectation;
	dlg.m_pProductPDF = m_pdf;
	dlg.m_bLoadConfigurationMgr= true;

	if (dlg.DoModal() == IDOK)
	{
		m_pComplectation = dlg.m_pSelectedItem;

		m_btnFilter.EnableToolTips();

		if (m_pComplectation != NULL)
		{
			CString strCode;
			CString strName;
			CString strInfo;
			CString strButtonText;
			CString strFormat = CString(_T("%s : %s (%s)"));
			BOOL bIsApp = FALSE;

			bIsApp = m_api->m_data.IsKindOfBN(m_pComplectation, _T("apl_product_appearance"));
			m_api->m_data.GetAttrBN(m_pComplectation, _T("code"), strCode);
			m_api->m_data.GetAttrBN(m_pComplectation, _T("name"), strName);

			strInfo.Format(strFormat, strCode, strName, bIsApp ?  APL_T("Базис") :  APL_T("Конфигурация"));
			m_btnFilter.SetTooltipText(strInfo);
			strButtonText = strInfo;

			if (strButtonText.GetLength() > 30)
				strButtonText = strButtonText.Left(30) + CString(_T("..."));

			m_btnFilter.SetWindowText(strButtonText);
		}
		else
		{
			m_btnFilter.SetWindowText( APL_T("Фильтр не задан"));
			m_btnFilter.SetTooltipText( APL_T("Фильтр не задан"));
		}
	}
}
