// ProductCompare.cpp : implementation file
//

#include "stdafx.h"
#include "apl_api.h"
#include "ProductCompare.h"
#include "AddDateSn.h"
#include "dictionary.h"

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

bool (*funcGetAllApp)(CaplAPI*, aplExtent&) = NULL;
bool (*funcGetAppByPdf)(CaplAPI*, CaplInstance*, aplExtent&) = NULL;
bool (*funcGetComplectationByPdf)(CaplAPI*, CaplInstance*, aplExtent&) = NULL;
bool (*funcGetComplectationByApp)(CaplAPI*, aplExtent&, aplExtent&)= NULL;
bool (*funcLoadAppsInfo)(CaplAPI*, aplExtent&) = NULL;
bool (*funcLoadComplectationsInfo)(CaplAPI*, aplExtent&) = NULL;
bool (*funcFilterByAppOrComplectation)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool, LPCTSTR) = NULL;
bool (*funcSelectOrder)(CaplAPI*, CaplInstance**) = NULL;	
bool (*funcGetComplectationsByOrder)(CaplAPI*, CaplInstance*, aplExtent&) = NULL;	
//bool (*funcFilterByApp)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool) = NULL;
//bool (*funcFilterByComplectation)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool) = NULL;

/////////////////////////////////////////////////////////////////////////////
// CProductCompare dialog

CProductCompare::CProductCompare(CWnd* pParent /*=NULL*/)
	: CResizableDialog(CProductCompare::IDD, pParent)
{
	//{{AFX_DATA_INIT(CProductCompare)
	//}}AFX_DATA_INIT
	m_last_comp_type=0;
	m_api=0;
	m_bComparedSost=true; m_bComparedCharact=true; 
	m_cmp_prd_char.SetUniqueName(_T("apl_psm_prd_cmp_list_char"));
	m_cmp_prd_sost.SetUniqueName(_T("apl_psm_prd_cmp_list_sost"));
	m_bInit=false;;
}

void CProductCompare::DoDataExchange(CDataExchange* pDX)
{
	CResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CProductCompare)
	DDX_Control(pDX, IDC_ST_COMP_TYPE, m_st_comp_type);
	DDX_Control(pDX, IDC_COMP_TYPE, m_comp_type_ctrl);
	DDX_Control(pDX, IDC_LISTCMP_FON, m_satic_fon);
	DDX_Control(pDX, IDC_BOTTOM, m_bottom_btn);
	DDX_Control(pDX, IDC_TOP, m_top_btn);
	DDX_Control(pDX, IDC_SAVE_TO_FILE, m_save_btn);
	DDX_Control(pDX, IDC_DELETE, m_del_btn);
	DDX_Control(pDX, IDC_ADD, m_add_btn);
	DDX_Control(pDX, IDC_COMPARE_SELECTED, m_comp_sel_btn);
	DDX_Control(pDX, IDC_CMP, m_cmp_btn);
	DDX_Control(pDX, IDC_LISTPRODUCT, m_prd_list);
	DDX_Control(pDX, IDC_SHOW_ONLY_DIFF, m_diff);
	DDX_Control(pDX, IDC_TAB, m_tab);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_DUBL, m_dubl_btn);
	//}}AFX_DATA_MAP
	m_bComparedSost=false,m_bComparedCharact=false;
}


BEGIN_MESSAGE_MAP(CProductCompare, CResizableDialog)
	//{{AFX_MSG_MAP(CProductCompare)
	ON_BN_CLICKED(IDC_CMP, OnCmp)
	ON_BN_CLICKED(IDC_ADD, OnAdd)
	ON_NOTIFY(TCN_SELCHANGE, IDC_TAB, OnSelchangeTab)
	ON_BN_CLICKED(IDC_DELETE, OnDelete)
	ON_NOTIFY(NM_DBLCLK, IDC_LISTPRODUCT, OnDblclkListproduct)
	ON_BN_CLICKED(IDC_SHOW_ONLY_DIFF, OnShowOnlyDiff)
	ON_BN_CLICKED(IDC_COMPARE_SELECTED, OnCompareSelected)
	ON_BN_CLICKED(IDC_SAVE_TO_FILE, OnSaveToFile)
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_TOP, OnTop)
	ON_BN_CLICKED(IDC_BOTTOM, OnBottom)
	ON_CBN_SELCHANGE(IDC_COMP_TYPE, OnSelchangeCompType)
	ON_BN_CLICKED(IDC_DUBL, OnDubl)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CProductCompare message handlers
//****************************************************************
//отработка нажатия кнопки Сравнить Изделия
void CProductCompare::OnCmp() 
{
	switch(m_tab.GetCurSel()) 
	{
		case 0:CompareProductCount();break;
		case 1:CompareProductChar();break;
		default: break;
	}
}
//****************************************************************
BOOL CProductCompare::OnInitDialog() 
{
	RECT rect={5,5,10,10};
	m_cmp_prd_sost.Create(/*WS_VISIBLE|*/WS_CHILD|WS_BORDER|LVS_SHOWSELALWAYS/*|LVS_SINGLESEL*/,rect,this,IDC_LISTCMP_SOST);
	m_cmp_prd_char.Create(/*WS_VISIBLE|*/WS_CHILD|WS_BORDER|LVS_SHOWSELALWAYS|LVS_SINGLESEL,rect,this,IDC_LISTCMP_CHAR);

	CResizableDialog::OnInitDialog();
	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   

	m_comp_type_ctrl.ResetContent();
	m_comp_type_ctrl.InsertString(0,APL_T("Состав на 1 уровень"));
	m_comp_type_ctrl.InsertString(1,APL_T("Подетальный состав"));
	m_comp_type_ctrl.InsertString(2,APL_T("Полный состав"));
	m_comp_type_ctrl.SetCurSel(0);

	m_satic_fon.GetWindowRect(&rect);
	ScreenToClient(&rect);
	m_cmp_prd_sost.MoveWindow(&rect);
	m_cmp_prd_char.MoveWindow(&rect);

	ListView_SetExtendedListViewStyle(m_cmp_prd_char.m_hWnd,
		ListView_GetExtendedListViewStyle(m_cmp_prd_char.m_hWnd)
			|LVS_EX_UNDERLINECOLD |LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);

	ListView_SetExtendedListViewStyle(m_cmp_prd_sost.m_hWnd,
		ListView_GetExtendedListViewStyle(m_cmp_prd_sost.m_hWnd)
			|LVS_EX_UNDERLINECOLD |LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	m_del_btn.SetIcon(GetAplTableIco(APL_TABLE_DEL));
	m_del_btn.SetFlat(FALSE);
	m_add_btn.SetIcon(GetAplStdIco16(APLSTDICO_PLUS));
	m_add_btn.SetFlat(FALSE);
	m_cmp_btn.SetIcon(GetAplStdIco16(APLSTDICO_PLAY));
	m_cmp_btn.SetFlat(FALSE);
	m_save_btn.SetIcon(GetAplTableIco(APL_TABLE_SAVE));
	m_save_btn.SetFlat(FALSE);
	m_top_btn.SetIcon(GetAplTableIco(APL_TABLE_TOP));
	m_top_btn.SetFlat(FALSE);
	m_bottom_btn.SetIcon(GetAplTableIco(APL_TABLE_BOTTOM));
	m_bottom_btn.SetFlat(FALSE);
	m_comp_sel_btn.SetFlat(FALSE);
	m_comp_sel_btn.SetIcon(GetAplStdIco16(APLSTDICO_INFO));
	m_dubl_btn.SetFlat(FALSE);
	m_dubl_btn.SetIcon(GetAplStdIco16(APLSTDICO_PLUS));
	
	AddAnchor(IDC_LISTPRODUCT,TOP_LEFT,TOP_RIGHT);
	AddAnchor(IDC_ST_N,TOP_LEFT,TOP_RIGHT);
	AddAnchor(IDC_ADD,TOP_RIGHT);
	AddAnchor(IDC_DUBL,TOP_RIGHT);
	AddAnchor(IDC_DELETE,TOP_RIGHT);
	AddAnchor(IDC_BOTTOM,TOP_RIGHT);
	AddAnchor(IDC_TOP,TOP_RIGHT);
	AddAnchor(IDC_CMP,TOP_RIGHT);
	AddAnchor(IDC_COMP_TYPE,TOP_RIGHT);
	AddAnchor(IDC_ST_COMP_TYPE,TOP_RIGHT);
	AddAnchor(IDC_TAB,TOP_LEFT,TOP_RIGHT);
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	//AddAnchor(IDC_TAB,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_SAVE_TO_FILE,BOTTOM_RIGHT);
	AddAnchor(IDC_COMPARE_SELECTED,BOTTOM_RIGHT);
	AddAnchor(IDC_SHOW_ONLY_DIFF,BOTTOM_LEFT);
	AddAnchor(IDC_LISTCMP_SOST,TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_LISTCMP_CHAR,TOP_LEFT, BOTTOM_RIGHT);


	ListView_SetExtendedListViewStyle(m_prd_list.m_hWnd,
		ListView_GetExtendedListViewStyle(m_prd_list.m_hWnd)
			|LVS_EX_UNDERLINECOLD|LVS_EX_FULLROWSELECT|
			LVS_EX_GRIDLINES/*|LVS_SHOWSELALWAYS/*|LVS_SINGLESEL*/);

#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");
//		(FARPROC&)funcFilterByApp = ::GetProcAddress(hConfigMgrLib, _T("add_FilterByConfigurationBasis"));
//		(FARPROC&)funcFilterByComplectation = ::GetProcAddress(hConfigMgrLib, _T("add_FilterByComplectation"));
	}	

	m_prd_list.InsertColumn(0,  APL_T("№"),LVCFMT_LEFT,30);
	m_prd_list.InsertColumn(1,  APL_T("Обозначение"),LVCFMT_LEFT,120);
	m_prd_list.InsertColumn(2,  APL_T("Наименование"),LVCFMT_LEFT,120);
	m_prd_list.InsertColumn(3,  APL_T("Версия"),LVCFMT_LEFT,80);
	m_prd_list.InsertColumn(4,  APL_T("Тип"),LVCFMT_LEFT,50);
	m_prd_list.InsertColumn(5,  APL_T("Контекст"),LVCFMT_LEFT,120);
	m_prd_list.InsertColumn(6,  APL_T("Дата"),LVCFMT_LEFT,120);
	m_prd_list.InsertColumn(7,  APL_T("Серийный Номер"),LVCFMT_LEFT,120);

	if (hConfigMgrLib != NULL)
		m_prd_list.InsertColumn(8,  APL_T("Базис / Конфигурация"), LVCFMT_LEFT, 400);

	m_cmp_prd_sost.InsertColumn(0,  APL_T("Обозначение"),LVCFMT_LEFT,100);
	m_cmp_prd_sost.InsertColumn(1,  APL_T("Наименование"),LVCFMT_LEFT,120);
	m_cmp_prd_sost.InsertColumn(2,  APL_T("Версия"),LVCFMT_LEFT,50);
	m_cmp_prd_sost.InsertColumn(3,  APL_T("Тип"),LVCFMT_LEFT,50);
	m_cmp_prd_sost.InsertColumn(4,  APL_T("Ед.Изм."),LVCFMT_LEFT,70);
	m_cmp_prd_sost.InsertColumn(5,  APL_T("Общeе"),LVCFMT_CENTER,50);

	m_cmp_prd_char.InsertColumn(0,  APL_T("Характеристика"),LVCFMT_LEFT,150);
	m_cmp_prd_char.InsertColumn(1,  APL_T("Ед.Изм."),LVCFMT_LEFT,70);
	m_cmp_prd_char.InsertColumn(2,  APL_T("Тип"),LVCFMT_LEFT,120);
	m_cmp_prd_char.InsertColumn(3,  APL_T("Общее"),LVCFMT_LEFT,50);

	TC_ITEM tci;
	tci.mask = TCIF_TEXT;
	tci.iImage = -1;
	tci.pszText  =  (LPTSTR)APL_T("Состав");
	m_tab.InsertItem(0, &tci);
	tci.pszText =  (LPTSTR)APL_T("Характеристики");
	m_tab.InsertItem(1, &tci);

	if(inExt.GetSize()>0) FillPrd(inExt);//в случае переданного внешнего массива PDF

	m_cmp_prd_sost.ModifyStyle(0,WS_VISIBLE);
	m_bInit=true;
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CProductCompare::AddPdf(CaplInstance *pdf)
{
	if(pdf==0) return;
	if(pdf->GetType()==0) return;
	if(pdf->GetAccessmode()>aplRO) {aplErrorMessage(S::NoAccessRight()); return;}

	CaplInstance *prd=0;
	CString bufId, bufName, bufVer,form_type;
	apidata.GetAttr(pdf,m_api->m_prd_mgr.a_pdf_prd,prd);

	//заполнение списка изделий
	int lastItem=m_prd_list.InsertItem(m_prd_list.GetItemCount(),_T(""));
	//m_prd_list.SetItemData(lastItem,(int)pdf);
	apidata.GetAttr(prd,m_api->m_prd_mgr.a_prd_id,bufId);
	m_prd_list.SetItemText(lastItem,1,bufId);
	apidata.GetAttr(prd,m_api->m_prd_mgr.a_prd_name,bufName);
	m_prd_list.SetItemText(lastItem,2,bufName);
	apidata.GetAttr(pdf,m_api->m_prd_mgr.a_pdf_id,bufVer);
	m_prd_list.SetItemText(lastItem,3,bufVer);
	apidata.GetAttr(pdf,m_api->m_prd_mgr.a_apl_pdf_type,form_type);
	form_type=m_api->m_prd_mgr.StrConvertPdfType2Rus(form_type);
	m_prd_list.SetItemText(lastItem,4,form_type);


	CProductCompareItem *newItem=new CProductCompareItem(pdf);
	m_prd_list.SetItemData(lastItem,(int)newItem);

	CString sDistrCode;
	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Код установки"), sDistrCode, _T(""));
	if(sDistrCode==_T("KVZ"))
	{
		COleDateTime odt= COleDateTime::GetCurrentTime();
		odt.SetDateTime(odt.GetYear(), odt.GetMonth(), odt.GetDay(), odt.GetHour(), 59, 59);
		newItem->dt= odt;
		m_prd_list.SetItemText(lastItem ,6, odt.Format(_T("%d.%m.%Y  %H:%M:%S")));		
	}
}

//****************************************************************
//добавление изделия
void CProductCompare::OnAdd() 
{
	CaplInstance *pdf=0;
	//вызов диалога для выбора изделия и получение его PDF
	pdf=m_api->m_prd_mgr.SelectInstance(APL_MODE_SELECT_PDF);
	if (pdf==0)return;
	AddPdf(pdf);
	
	m_bComparedSost=false; m_bComparedCharact=false;
	m_cmp_prd_sost.SetTextColor(RGB(128,128,128));m_cmp_prd_sost.RedrawWindow();
	m_cmp_prd_char.SetTextColor(RGB(128,128,128));m_cmp_prd_char.RedrawWindow();
}
void CProductCompare::OnDubl() 
{
	POSITION pos;
 	pos=m_prd_list.GetFirstSelectedItemPosition();
 	int k=m_prd_list.GetNextSelectedItem(pos);
	if(k<0) return;

	CProductCompareItem *Item=(CProductCompareItem *)m_prd_list.GetItemData(k);
	if(Item==0) return;
	AddPdf(Item->pdf);	
	m_bComparedSost=false; m_bComparedCharact=false;
	m_cmp_prd_sost.SetTextColor(RGB(128,128,128));m_cmp_prd_sost.RedrawWindow();
	m_cmp_prd_char.SetTextColor(RGB(128,128,128));m_cmp_prd_char.RedrawWindow();
}
//****************************************************************
void CProductCompare::OnSelchangeTab(NMHDR* pNMHDR, LRESULT* pResult) 
{
	if(!m_bInit) return;
	if(m_tab.GetCurSel()==0)
	{
		m_cmp_prd_char.ModifyStyle(WS_VISIBLE,0);
		m_cmp_prd_sost.ModifyStyle(0,WS_VISIBLE);
		m_cmp_prd_sost.Invalidate();

		m_st_comp_type.EnableWindow(TRUE);
		m_comp_type_ctrl.EnableWindow(TRUE);
	}
	else
	{
		m_cmp_prd_sost.ModifyStyle(WS_VISIBLE,0);
		m_cmp_prd_char.ModifyStyle(0,WS_VISIBLE);
		m_cmp_prd_char.Invalidate();

		m_st_comp_type.EnableWindow(FALSE);
		m_comp_type_ctrl.EnableWindow(FALSE);
	}
}
//****************************************************************
void CProductCompare::OnDelete() 
{//удаление изделия
	POSITION pos;
 	pos=m_prd_list.GetFirstSelectedItemPosition();
 	int k=m_prd_list.GetNextSelectedItem(pos);
	if(k<0)	{ AfxMessageBox( APL_T("Изделие не выбрано"));return;}
	
	int res=AfxMessageBox( APL_T("Выбранное изделие будет удалено из списка.\nВы уверены?"), MB_YESNO);
	if(res==IDYES)
	{
		CProductCompareItem *oldItem=(CProductCompareItem *)m_prd_list.GetItemData(k);
		if(oldItem!=0) delete oldItem;
		m_prd_list.DeleteItem(k);//удаление строки
	}
	m_bComparedSost=false; m_bComparedCharact=false;
	m_cmp_prd_sost.SetTextColor(RGB(128,128,128));m_cmp_prd_sost.RedrawWindow();
	m_cmp_prd_char.SetTextColor(RGB(128,128,128));m_cmp_prd_char.RedrawWindow();
}

//****************************************************************
//обтработка двойного клика на списке
void CProductCompare::OnDblclkListproduct(NMHDR* pNMHDR, LRESULT* pResult) 
{
	POSITION pos;
 	pos=m_prd_list.GetFirstSelectedItemPosition();
 	int k=m_prd_list.GetNextSelectedItem(pos);
	if(k<0) return;

	CProductCompareItem *Item=(CProductCompareItem *)m_prd_list.GetItemData(k);
	if(Item==0) return;

	CString buf, buf1;
	CAddDateSn dlg;
		
	dlg.m_sn=Item->sn;
	
	if(Item->dt.GetStatus()==COleDateTime::valid) dlg.m_dt=Item->dt;
		else dlg.m_dt.SetStatus(COleDateTime::null);

	dlg.m_api = m_api;
	dlg.m_pProductPDF = Item->pdf;
	dlg.m_pSelectedItem = Item->pBasisOrComplectation;
	dlg.m_context=Item->context;

 	if(dlg.DoModal()==IDOK)
 	{		
		CString s_dt, s_sn;
	
		Item->pBasisOrComplectation = dlg.m_pSelectedItem;
		Item->sn=dlg.m_sn;
		s_sn=dlg.m_sn;

		if(dlg.m_dt.GetStatus()==COleDateTime::valid)
		{
			Item->dt=dlg.m_dt;
			s_dt=Item->dt.Format(_T("%d.%m.%Y  %H:%M:%S"));
		}
		else Item->dt.SetStatus(COleDateTime::null);

		m_prd_list.SetItemText(k,6,s_dt);
		m_prd_list.SetItemText(k,7,s_sn);

		if (Item->pBasisOrComplectation != NULL)
		{
			CString strCode;
			CString strName;
			CString strInfo;
			CString strFormat = CString(_T("%s : %s (%s)"));
			BOOL bIsApp = FALSE;

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

			strInfo.Format(strFormat, strCode, strName, bIsApp ? CString( APL_T("Базис")) : CString( APL_T("Конфигурация")));
			m_prd_list.SetItemText(k, 8, strInfo);
		}
		else
			m_prd_list.SetItemText(k, 8, CString(_T("")));

		Item->context=dlg.m_context;
		if(Item->context==0) buf=_T("");
		else	apidata.GetAttr(Item->context,m_api->m_prd_mgr.a_pd_context_name,buf);

		m_prd_list.SetItemText(k,5,buf);

		m_cmp_prd_sost.SetTextColor(RGB(128,128,128));
		m_cmp_prd_sost.RedrawWindow();
	}
	*pResult = 0;
}
//****************************************************************
void CProductCompare::OnShowOnlyDiff() 
{
	switch(m_tab.GetCurSel()) 
	{
		case 0:DrawStructCompareResult();break;
		case 1:DrawCharactCompareResult();break;
		default: break;
	}

}
//****************************************************************
//отработка нажатия кнопки "Сравнить выделенные"
void CProductCompare::OnCompareSelected() 
{
	if(m_tab.GetCurSel()==1) return;
	aplExtent ext;
	int uSelectedCount = m_cmp_prd_sost.GetSelectedCount();
	int nItem=-1;
	//в случае если выделенные элементы существуют
	if (uSelectedCount <= 0) return;
	
	for (int i=0;i<uSelectedCount;i++)
	{
		nItem = m_cmp_prd_sost.GetNextItem(nItem, LVNI_SELECTED);
		int j=m_cmp_prd_sost.GetItemData(nItem);
		CaplInstance *pdf=m_struct_res_items[j]->pdf;
		ext.Add(pdf);
	}
	m_api->m_prd_mgr.StartCompareProduct(ext);
}
//****************************************************************
//функция, выполняющая заполнение списка изделий
void CProductCompare::FillPrd(aplExtent &ext)
{
	m_prd_list.DeleteAllItems();
	for(int i=0; i<ext.GetSize();i++) AddPdf(ext[i]);
	OnCmp();
}
//****************************************************************
//отработка нажатия кнопки "Сохранить в файл"
void CProductCompare::OnSaveToFile() 
{
	if(m_tab.GetCurSel()==0) apl_SaveListCtrlToFile(&m_cmp_prd_sost,0);
	else apl_SaveListCtrlToFile(&m_cmp_prd_char,0);
}
//****************************************************************
void CProductCompare::DrawStructCompareResult()
{
	BOOL bOnlyDiff=m_diff.GetCheck();
	

	m_cmp_prd_sost.SetRedraw(FALSE);
	m_cmp_prd_sost.DeleteAllItems();
	while(m_cmp_prd_sost.DeleteColumn(6));

	// Добавление столбцов
	int i,j,k;
	CString id,name,ver,buf,form_type;
	CaplInstance *prd;
	int item_count=m_prd_list.GetItemCount();
	for(i=0; i<item_count;i++)
	{
		buf.Format(_T("%i"),i+1);
		m_cmp_prd_sost.InsertColumn(i+6, buf,LVCFMT_LEFT,50);
		//m_cmp_prd.SetColumnWidth(i+5, 50);
	}
	// Заполнение строк
	for(i=0;i<m_struct_res_items.Size;i++)
	{
		bool bDiff=false;
		for(j=1;j<m_struct_res_items[i]->values.GetSize();j++)
		{
			if(m_struct_res_items[i]->values[0]!=m_struct_res_items[i]->values[j])
				{ bDiff=true; break;}
		}
		if(bOnlyDiff) {	if(!bDiff) continue;}
	
	
		apidata.GetAttr(m_struct_res_items[i]->pdf,m_api->m_prd_mgr.a_pdf_id,ver);
		apidata.GetAttr(m_struct_res_items[i]->pdf,m_api->m_prd_mgr.a_pdf_prd,prd);
		apidata.GetAttr(prd,m_api->m_prd_mgr.a_prd_id,id);
		apidata.GetAttr(prd,m_api->m_prd_mgr.a_prd_name,name);
		apidata.GetAttr(m_struct_res_items[i]->pdf,m_api->m_prd_mgr.a_apl_pdf_type,form_type);
		form_type=m_api->m_prd_mgr.StrConvertPdfType2Rus(form_type);

		k=m_cmp_prd_sost.InsertItem(i,id);
		m_cmp_prd_sost.SetItemData(k,i);
		m_cmp_prd_sost.SetItemText(k,1,name);
		m_cmp_prd_sost.SetItemText(k,2,ver);
		m_cmp_prd_sost.SetItemText(k,3,form_type);


		name=_T("");
		if(m_struct_res_items[i]->unit!=0)	m_api->m_charact_mgr.GetUnitName(m_struct_res_items[i]->unit,name);
		m_cmp_prd_sost.SetItemText(k,4,name);

		if(!bDiff) m_cmp_prd_sost.SetItemText(k,5,_T("X"));

		for(j=0;j<m_struct_res_items[i]->values.GetSize();j++)
		{
			if(m_struct_res_items[i]->values[j]!=0)
			{
				buf.Format(_T("%0.2f"),m_struct_res_items[i]->values[j]);
				int len=buf.GetLength();
				if(len==4) buf.Insert(0,_T("  "));
				else if(len==5) buf.Insert(0,_T(" "));
				m_cmp_prd_sost.SetItemText(k,j+6,buf);
			}
		}
	}
	m_bFromBase=false;
	m_cmp_prd_sost.SetRedraw(TRUE);
}

//****************************************************************
//Сравнение изделий по составу
void CProductCompare::CompareProductCount()
{
 	if(!m_bInit) return;
	if(m_bComparedSost) { DrawStructCompareResult(); return;}
	ClearCompareSostResult();	

	int i, j, k;
	aplExtent ext0, ext1,ext01;
	CaplInstance *inst1,*i_pdf;
	CString buf;

	int bCompType=m_comp_type_ctrl.GetCurSel();
	if(bCompType>0)
	{
		if(AfxMessageBox( APL_T("Сравнение полного (подетального) состава изделий может занять длительное время.\n\n Вы уверены, что хотите продолжить ?"),
			MB_YESNO|MB_ICONQUESTION)
			!=IDYES) return;
	}
	
	long wait_trd=aplStartWaitDlg( APL_T("Чтение данных"));
	int item_count=m_prd_list.GetItemCount();

	for(i=0; i<item_count;i++)
	{
		buf.Format(_T("%i"),i+1);
		m_prd_list.SetItemText(i,0,buf);
		CProductCompareItem *Item=(CProductCompareItem *)m_prd_list.GetItemData(i);
		if(Item==0) return;

		CaplInstance *pdf=Item->pdf;
		bool bLoad=true;
		if(m_loaded_pdf.Find(pdf)>=0) bLoad=false;
		
		if(bCompType<1)
		{
			// Сравнение 1-го уровня состава изделия 
			m_api->m_prd_mgr.LoadAllSubProduct(0,Item->context,pdf,ext0, ext1,bLoad);
			if(bLoad) m_loaded_pdf.Add(pdf);
		
			// Проверка применяемости
			if(Item->dt.GetStatus()==COleDateTime::valid)
			{
				m_api->m_prd_mgr.FilterlByDate(ext0,Item->dt,ext01);
				if(ext0.Size!=ext01.Size){ext0.Clear(); ext0.Append(ext01);};
			}
			if(Item->sn!=_T(""))
			{
				m_api->m_prd_mgr.FilterlBySN(ext0, Item->sn, ext01);
				if(ext0.Size!=ext01.Size){ext0.Clear(); ext0.Append(ext01);};
			}
			if (Item->pBasisOrComplectation != NULL)
			{
				funcFilterByAppOrComplectation(m_api, ext0, Item->pBasisOrComplectation, ext01, false,0);
				
				if (ext0.GetSize() != ext01.GetSize())
				{
					ext0.Clear();
					ext0.Append(ext01);
				}
			}

			// Перебор состава pdf
			for(j=0; j<ext0.GetSize();j++)
			{	
				apidata.GetAttr(ext0[j],m_api->m_prd_mgr.a_pdr_r_ted,i_pdf);
				double count=1;

				if(apidata.IsKindOf(ext0[j],m_api->m_prd_mgr.e_apl_qacu))
				{
					apidata.GetAttr(ext0[j],m_api->m_prd_mgr.a_apl_qacu_value,count);
					apidata.GetAttr(ext0[j],m_api->m_prd_mgr.a_apl_qacu_unit,inst1);
				}

				CProductStructCompareResultItem *resitem=0;
				for(k=0;k<m_struct_res_items.Size;k++)
				{
					if(m_struct_res_items[k]->pdf!=i_pdf) continue;
					if(m_struct_res_items[k]->unit!=inst1) continue;
					resitem=m_struct_res_items[k];
					break;
				}
				if(resitem==0)
				{
					resitem= new CProductStructCompareResultItem;
					resitem->pdf=i_pdf;
					resitem->unit=inst1;
					resitem->values.SetSize(item_count);
					m_struct_res_items.Add(resitem);
					for(int k1=0; k1<item_count; k1++) resitem->values[k1]=0;
				}
				resitem->values[i]+=count;
			}
		}
		else
		{
			// Сравнение полного состава изделия
//			aplInstArray array_pdf, ext_unit;
			aplExtent array_pdf, ext_unit;
			aplRealArray count_array;
			COleDateTime *time = NULL;
			CString strDateTime;
			TCHAR *sn = NULL;

			if (Item->dt.GetStatus()==COleDateTime::valid)
				time=&Item->dt;
			
			if (Item->sn!=_T(""))
				sn=(LPTSTR)LPCTSTR(Item->sn);

			if (time != NULL)
				aplDate2String(*time, strDateTime);

			bool b=false;
			
			bool bDisassemblyType=false;
			if(bCompType==1)bDisassemblyType=true;

			aplExtent extRels;

			b = m_api->m_prd_mgr.DisassemblyProduct(Item->context, pdf, extRels,
				                                    array_pdf, count_array, ext_unit, 
													strDateTime, sn, bDisassemblyType, NULL, NULL, 
													Item->pBasisOrComplectation);
			if(b)
			{
				// Перебор состава pdf
				for(j=0; j<array_pdf.GetSize();j++)
				{	
					CaplInstance *i_pdf=array_pdf[j];
					inst1=ext_unit[j];
					double count=count_array[j];

					CProductStructCompareResultItem *resitem=0;
					for(k=0;k<m_struct_res_items.Size;k++)
					{
						if(m_struct_res_items[k]->pdf!=i_pdf) continue;
						if(m_struct_res_items[k]->unit!=inst1) continue;
						resitem=m_struct_res_items[k];
						break;
					}
					if(resitem==0)
					{
						resitem= new CProductStructCompareResultItem;
						resitem->pdf=i_pdf;
						resitem->unit=inst1;
						resitem->values.SetSize(item_count);
						m_struct_res_items.Add(resitem);
						for(int k1=0; k1<item_count; k1++) resitem->values[k1]=0;
					}
					resitem->values[i]+=count;		
				}
			}
		}
	}
	aplEndWaitDlg(wait_trd);

	DrawStructCompareResult();
	
	m_bComparedSost=true;
	m_cmp_prd_sost.SetTextColor(RGB(0,0,0)); m_cmp_prd_sost.RedrawWindow();
}
//****************************************************************
void CProductCompare::DrawCharactCompareResult()
{
	BOOL bOnlyDiff=m_diff.GetCheck();

	m_cmp_prd_sost.ModifyStyle(WS_VISIBLE,0);
	m_cmp_prd_char.ModifyStyle(0,WS_VISIBLE);
	m_cmp_prd_char.Invalidate();

	m_cmp_prd_char.EnableWindow(TRUE);
	m_cmp_prd_char.SetRedraw(FALSE);
	m_cmp_prd_char.DeleteAllItems();
	while(m_cmp_prd_char.DeleteColumn(4));

	int i,j,k;
	CString id,name,ver,buf;
	CaplInstance *unit;

	// Добавление столбцов
	int item_count=m_prd_list.GetItemCount();
	for(i=0; i<item_count;i++)
	{
		buf.Format(_T("%i"),i+1);
		m_cmp_prd_char.InsertColumn(i+4, buf,LVCFMT_LEFT,80);
	}

	// Заполнение строк
	for(i=0;i<m_charact_res_items.Size;i++)
	{
		bool bDiff=false;
		for(j=1;j<m_charact_res_items[i]->values.GetSize();j++)
		{
			if(m_charact_res_items[i]->values[0]!=m_charact_res_items[i]->values[j])
				{ bDiff=true; break;}
		}
		if(bOnlyDiff) {	if(!bDiff) continue;}
	
		apidata.GetAttr(m_charact_res_items[i]->charact,m_api->m_charact_mgr.a_apl_charact_name,name);
		apidata.GetAttr(m_charact_res_items[i]->charact,m_api->m_charact_mgr.a_apl_charact_unit,unit);
		m_api->m_charact_mgr.GetUnitName(unit,id);
		if(m_charact_res_items[i]->type!=0)
			apidata.GetAttr(m_charact_res_items[i]->type,m_api->m_charact_mgr.a_apl_charact_type_name,ver);
		else ver=_T("");
		k=m_cmp_prd_char.InsertItem(i,name);
		m_cmp_prd_char.SetItemData(k,i);
		m_cmp_prd_char.SetItemText(k,1,id);
		m_cmp_prd_char.SetItemText(k,2,ver);

		if(!bDiff) m_cmp_prd_char.SetItemText(k,3,_T("X"));

		for(j=0;j<m_charact_res_items[i]->values.GetSize();j++)
		{
			m_cmp_prd_char.SetItemText(k,j+4,m_charact_res_items[i]->values[j]);
		}
	}
	m_cmp_prd_char.SetRedraw(TRUE);

}
void CProductCompare::ClearCompareSostResult()
{
	m_cmp_prd_sost.SetRedraw(FALSE);
	m_cmp_prd_sost.DeleteAllItems();
	m_cmp_prd_sost.SetRedraw(TRUE);
	m_struct_res_items.Clear();
	m_bComparedSost=false;
	if(m_tab.GetCurSel()==0)
	{
		m_cmp_prd_sost.SetTextColor(RGB(128,128,128));m_cmp_prd_sost.RedrawWindow();
		m_cmp_prd_sost.Invalidate();
	}
}
//****************************************************************
//функция отрисовки списка сравнения характеристик изделия
void CProductCompare::CompareProductChar()
{
 	if(!m_bInit) return;
	if(m_bComparedCharact) { DrawCharactCompareResult(); return;}
	m_cmp_prd_char.SetRedraw(FALSE);
	m_cmp_prd_char.DeleteAllItems();
	m_cmp_prd_char.SetRedraw(TRUE);
	m_charact_res_items.Clear();	

	int i,j,k;
	CString buf;
	aplExtent  ext_rel, extGroup;
	CaplInstance *instType,*instCharact;
	long wait_trd=aplStartWaitDlg( APL_T("Чтение данных"));
	int item_count=m_prd_list.GetItemCount();
	for(i=0; i<item_count;i++)
	{
		buf.Format(_T("%i"),i+1);
		m_prd_list.SetItemText(i,0,buf);
		CProductCompareItem *Item=(CProductCompareItem *)m_prd_list.GetItemData(i);
		if(Item==0) return;

		CaplInstance *pdf=Item->pdf;
		m_api->m_charact_mgr.FindAssociatedCharacteristic(pdf,ext_rel,extGroup);
	
		for(j=0;j<ext_rel.GetSize();j++)
		{
			apidata.GetAttr(ext_rel[j],m_api->m_charact_mgr.a_apl_charact_val_charact,instCharact);
			if(instCharact==0) continue;
			apidata.GetAttr(ext_rel[j],m_api->m_charact_mgr.a_apl_charact_val_type,instType);
			//apidata.GetAttr(instCharact,m_api->m_charact_mgr.a_apl_charact_unit,instUnit);
		
			CProductCharactCompareResultItem *item=0;
			for(k=0;k<m_charact_res_items.Size;k++)
			{
				if(m_charact_res_items[k]->charact!=instCharact) continue;
				if(m_charact_res_items[k]->type!=instType) continue;
				item=m_charact_res_items[k];
			}
			if(item==0)
			{
				item= new CProductCharactCompareResultItem();
				item->charact=instCharact;
				item->type=instType;
				item->values.SetSize(item_count);
				m_charact_res_items.Add(item);
			}
			//apidata.GetAttrBN(ext_rel[j],_T("val"),inst0);
			m_api->m_charact_mgr.PrintCharacteristicValue(ext_rel[j],0,buf);
			item->values[i]=buf;;
		}
	}
	aplEndWaitDlg(wait_trd);
	
	m_bComparedCharact=true;
	m_cmp_prd_char.SetTextColor(RGB(0,0,0)); m_cmp_prd_char.RedrawWindow();
	DrawCharactCompareResult();
}

//****************************************************************
void CProductCompare::OnDestroy() 
{
	int i,k=m_prd_list.GetItemCount();
	for(i=0;i<k;i++)
	{
		CProductCompareItem *oldItem=(CProductCompareItem *)m_prd_list.GetItemData(i);
		if(oldItem!=0) delete oldItem;
	}
	CResizableDialog::OnDestroy();
}
//****************************************************************
void CProductCompare::OnTop() {	MoveRow(-1); }
void CProductCompare::OnBottom()  {	MoveRow(+1); }
//****************************************************************
bool CProductCompare::MoveRow(int delta)
{
	int i;
	if(delta==0) return false;
	POSITION pos=m_prd_list.GetFirstSelectedItemPosition();
	if(pos==0) {AfxMessageBox( APL_T("Строка не выбрана")); return false;}
	int from=m_prd_list.GetNextSelectedItem(pos);
	if(from<0) {AfxMessageBox( APL_T("Строка не выбрана")); return false;}
	int to=from+delta;
	if(to<0) return false;
	if(to>=m_prd_list.GetItemCount()) return false;

	int nColumnCountPrd = m_prd_list.GetHeaderCtrl()->GetItemCount();

	long tempInst;
	tempInst=m_prd_list.GetItemData(to);
	CStringArray Temp;
	for(i = 0; i < nColumnCountPrd; i++)
		Temp.Add(m_prd_list.GetItemText(to, i));	
	
	m_prd_list.SetItemData(to,m_prd_list.GetItemData(from));
	m_prd_list.SetItemData(from, tempInst);

	for(i = 0; i < nColumnCountPrd; i++)
	{	
		m_prd_list.SetItemText(to,i,m_prd_list.GetItemText(from, i));
		m_prd_list.SetItemText(from,i,Temp.GetAt(i));
	}
	m_prd_list.SetItemState(to,LVIS_SELECTED| LVIS_FOCUSED, -1);
	m_prd_list.RedrawItems(0,100);

	m_bComparedSost=false; m_bComparedCharact=false;
	m_cmp_prd_sost.SetTextColor(RGB(128,128,128));m_cmp_prd_sost.RedrawWindow();
	m_cmp_prd_char.SetTextColor(RGB(128,128,128));m_cmp_prd_char.RedrawWindow();

	return true;
}


void CProductCompare::OnSelchangeCompType() 
{
	int i=m_comp_type_ctrl.GetCurSel();
	if(i!=m_last_comp_type)
	{
		if(m_bComparedSost)
		{
			if(IDNO==AfxMessageBox( APL_T("Очистить результаты сравнения ?"),MB_YESNO|MB_ICONQUESTION))
			{
				m_comp_type_ctrl.SetCurSel(m_last_comp_type);
				return;
			}
		}
		m_last_comp_type=i;
		ClearCompareSostResult();
	}
}

