// ChangeAssemblyDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ChangeAssemblyDlg.h"
#include "apl_api.h"
#include "icons_defines.h"


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

#include "ChangeParamDlg.h"

/////////////////////////////////////////////////////////////////////////////
// CChangeAssemblyDlg dialog


CChangeAssemblyDlg::CChangeAssemblyDlg(CWnd* pParent /*=NULL*/)
	: CResizableDialog(CChangeAssemblyDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CChangeAssemblyDlg)
	m_sProductId = _T("");
	m_sProductName = _T("");
	m_sProductVer = _T("");
	m_iCont = -1;
	m_bSNSelected = FALSE;
	m_bDateSelected = TRUE;
	m_oleDate = COleDateTime::GetCurrentTime();
	m_sSN = _T("");
	m_bNotShow = TRUE;
	//}}AFX_DATA_INIT

	m_mode = 0;
	m_api = NULL;
	
	m_psc = NULL;
	m_assPdf = NULL;
	m_curItem = NULL;
	
	m_items = NULL;
	m_newItems = NULL;
	m_delItems = NULL;
	
	m_index = -1;
	m_curPSC = NULL;
	m_curPSCInfo = NULL;
	
	m_sEffType = _T("none");
	m_sStartCond = _T("");
	m_sEndCond = _T("");
	
	m_change = NULL;
	
	m_bReadOnly = false;

	m_itemsList.SetUniqueName(_T("change_items_list"));
	m_whereUsedList.SetUniqueName(_T("where_used_list"));

	// при запеске диалога фильтруем состав по текущей дате
	m_bFilteredByDate = true;
	m_bFilteredBySN = false;
	m_bFilteredByContext = false;
}


void CChangeAssemblyDlg::DoDataExchange(CDataExchange* pDX)
{
	CResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CChangeAssemblyDlg)
	DDX_Control(pDX, IDC_CHG2_SET_EFF, m_setEffBtn);
	DDX_Control(pDX, IDC_CHG2_SN_CTRL, m_sn);
	DDX_Control(pDX, IDC_CHG2_DATE_CTRL, m_dateCtrl);
	DDX_Control(pDX, IDC_CHG2_CONTEXT_COMBO, m_contCtrl);
	DDX_Control(pDX, IDC_CHG2_PROP, m_itemPropBtn);
	DDX_Control(pDX, IDC_CHG2_CLEAR, m_itemClearBtn);
	DDX_Control(pDX, IDC_CHG2_ITEM_DELETE, m_itemDeleteBtn);
	DDX_Control(pDX, IDC_CHG2_ITEM_CHANGE, m_itemChngBtn);
	DDX_Control(pDX, IDC_CHG2_ITEM_ADD, m_itemAddBtn);
	DDX_Control(pDX, IDC_CHG2_ASS_SELECT, m_selectBtn);
	DDX_Control(pDX, IDC_CHG2_ASS_REFRESH, m_refreshBtn);
	DDX_Control(pDX, IDCANCEL, m_cancelBtn);
	DDX_Control(pDX, IDOK, m_okBtn);
	DDX_Control(pDX, IDC_LIST_WHERE_USED, m_whereUsedList);
	DDX_Control(pDX, IDC_CHANGE_ITEMS_LIST, m_itemsList);
	DDX_Text(pDX, IDC_CHG2_ASS_ID, m_sProductId);
	DDX_Text(pDX, IDC_CHG2_ASS_NAME, m_sProductName);
	DDX_Text(pDX, IDC_CHG2_ASS_VER, m_sProductVer);
	DDX_CBIndex(pDX, IDC_CHG2_CONTEXT_COMBO, m_iCont);
	DDX_Check(pDX, IDC_CHG2_SN_CHECK, m_bSNSelected);
	DDX_Check(pDX, IDC_CHG2_DATE_CHECK, m_bDateSelected);
	DDX_DateTimeCtrl(pDX, IDC_CHG2_DATE_CTRL, m_oleDate);
	DDX_Text(pDX, IDC_CHG2_SN_CTRL, m_sSN);
	DDX_Check(pDX, IDC_CHNGW_NOTSHOW, m_bNotShow);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CChangeAssemblyDlg, CResizableDialog)
	//{{AFX_MSG_MAP(CChangeAssemblyDlg)
	//ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_CHG2_ASS_SELECT, OnChg2AssSelect)
	ON_BN_CLICKED(IDC_CHG2_ASS_REFRESH, OnChg2AssRefresh)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_CHANGE_ITEMS_LIST, OnItemchangedChangeItemsList)
	ON_BN_CLICKED(IDC_CHG2_PROP, OnChg2Prop)
	ON_BN_CLICKED(IDC_CHG2_SET_EFF, OnChg2SetEff)
	ON_BN_CLICKED(IDC_CHG2_CLEAR, OnChg2Clear)
	ON_BN_CLICKED(IDC_CHG2_ITEM_CHANGE, OnChg2ItemChange)
	ON_BN_CLICKED(IDC_CHG2_ITEM_DELETE, OnChg2ItemDelete)
	ON_BN_CLICKED(IDC_CHG2_SN_CHECK, OnChg2SnCheck)
	ON_BN_CLICKED(IDC_CHG2_DATE_CHECK, OnChg2DateCheck)
	ON_CBN_CLOSEUP(IDC_CHG2_CONTEXT_COMBO, OnCloseupChg2ContextCombo)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_CHG2_DATE_CTRL, OnDatetimechangeChg2DateCtrl)
	ON_EN_CHANGE(IDC_CHG2_SN_CTRL, OnChangeChg2SnCtrl)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST_WHERE_USED, OnDblclkListWhereUsed)
	ON_NOTIFY(NM_DBLCLK, IDC_CHANGE_ITEMS_LIST, OnDblclkChangeItemsList)
	ON_BN_CLICKED(IDC_CHG2_ITEM_ADD, OnChg2ItemAdd)
	
	//}}AFX_MSG_MAP
	ON_NOTIFY ( NM_CUSTOMDRAW, IDC_CHANGE_ITEMS_LIST, OnCustomdrawAssemblyItemsList )
	ON_NOTIFY ( NM_CUSTOMDRAW, IDC_LIST_WHERE_USED, OnCustomdrawAssemblyWhereUsedItemsList )

	ON_NOTIFY(HDN_ITEMCLICK, 0, OnAssemblyListHeaderClicked)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChangeAssemblyDlg message handlers

void CChangeAssemblyDlg::SetAnchors()
{
	AddAnchor(IDC_ASS_STATIC, TOP_LEFT, MIDDLE_RIGHT);
	AddAnchor(IDC_CHANGE_ITEMS_LIST, TOP_LEFT, MIDDLE_RIGHT);

	AddAnchor(IDC_WHERE_USED_STATIC, MIDDLE_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_LIST_WHERE_USED, MIDDLE_LEFT, BOTTOM_RIGHT);
	
	AddAnchor(IDC_PRODUCT_STATIC, TOP_LEFT, TOP_CENTER);
	AddAnchor(IDC_CHG2_ASS_ID, TOP_LEFT, TOP_CENTER);
	AddAnchor(IDC_CHG2_ASS_NAME, TOP_LEFT, TOP_CENTER);
	AddAnchor(IDC_CHG2_ASS_VER, TOP_LEFT, TOP_CENTER);
	AddAnchor(IDC_CHG2_ASS_SELECT, TOP_CENTER);
	
	AddAnchor(IDC_FILTER_STATIC, TOP_CENTER, TOP_RIGHT);
	AddAnchor(IDC_CHG2_SN_CTRL, TOP_CENTER, TOP_RIGHT);
	AddAnchor(IDC_CHG2_DATE_CTRL, TOP_CENTER, TOP_RIGHT);
	AddAnchor(IDC_CHG2_CONTEXT_COMBO, TOP_CENTER, TOP_RIGHT);
	AddAnchor(IDC_TEXT_CON_STATIC, TOP_CENTER);
	AddAnchor(IDC_CHG2_SN_CHECK, TOP_CENTER);
	AddAnchor(IDC_CHG2_DATE_CHECK, TOP_CENTER);
	AddAnchor(IDC_CHG2_ASS_REFRESH, TOP_RIGHT);
	AddAnchor(IDC_CHNGW_NOTSHOW, TOP_CENTER, TOP_RIGHT);
	
	AddAnchor(IDOK, BOTTOM_RIGHT);	
	AddAnchor(IDCANCEL, BOTTOM_RIGHT);	
}

void CChangeAssemblyDlg::LoadSystemStrikeOutFont()
{
	LOGFONT lf;
    memset(&lf, 0, sizeof(LOGFONT));
	this->GetFont()->GetLogFont(&lf);
	lf.lfStrikeOut = TRUE;
    VERIFY(m_FontStrikeOut.CreateFontIndirect(&lf));
}

void CChangeAssemblyDlg::InsertText(int num, int iNexInd, CaplInstance* newPdf, double dCount, CaplInstance* unit, 
		CString sPos, CString sPosNum, CString sEffType, CString sStart, CString sEnd,
		CString sPrior)
{
	CaplInstance* inst;
	CString buf, name;

	while(sPos.GetLength()<4)
		sPos=_T(" ")+sPos;
	
	if (newPdf)
	{
		if (!newPdf->attrs!=0)m_api->m_prd_mgr.LoadPrdInfo(newPdf);
		int prdIcon = m_api->GetInstIco(newPdf); //GetPdfIcon(newPdf);
		apidata.GetAttr(newPdf, m_api->m_prd_mgr.a_pdf_prd, inst);
		if (inst)
		{
			apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_id, name);
			apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_name, buf);
			if(!name.IsEmpty()) name+=_T(":"); name+=buf;
		}
		apidata.GetAttr(newPdf, m_api->m_prd_mgr.a_pdf_id, buf);
		if(!name.IsEmpty()) name+=_T(":"); name+=buf;
		
		m_itemsList.SetItemText(num, iNexInd, name);		
		m_itemsList.SetItem(num, iNexInd++, LVIF_IMAGE, name, prdIcon, 0, 0, 0);
				
		int index= 6;
		if(1==m_mode) index++;
		if(unit)
		{
			m_api->m_charact_mgr.GetUnitName(unit, name);
//			b= m_api->m_data.GetAttr(unit, m_api->m_charact_mgr.a_apl_unit_id, name);
		}
		buf.Format(_T("%g [%s]"), dCount, name);
		
		if (0 == m_mode)
		{
			m_itemsList.SetItemText(num, iNexInd++, sPos);
			m_itemsList.SetItemText(num, iNexInd++, sPosNum);
			m_itemsList.SetItemText(num, iNexInd++, buf);
			m_itemsList.SetItemText(num, iNexInd++, PrintEffectivityInString
				(sEffType, sStart, sEnd));
			
		}
		else if (1 == m_mode)
		{
			m_itemsList.SetItemText(num, iNexInd, sPrior);
			m_itemsList.SetItemText(num, iNexInd, buf);
			m_itemsList.SetItemText(num, iNexInd, sPos);
			m_itemsList.SetItemText(num, iNexInd, PrintEffectivityInString
				(sEffType, sStart, sEnd));
		}
	}
}

CString CChangeAssemblyDlg::PrintEffectivityInString(CString type, CString start, CString end)
{
	CString buf = _T("");
	
	if (type == _T("none"))
	{
		buf =  APL_T("По дате проведения изменения");
	}
	else if (type == _T("dated"))
	{
		COleDateTime odt;
		if (!start.IsEmpty())
		{
			aplString2Date(start, odt);
			buf=  APL_T("с: ") + odt.Format(_T("%d:%m:%Y %H:%M:%S"));
		}
		if (!end.IsEmpty())
		{
			aplString2Date(end, odt);
			buf+= APL_T(" по: ") + odt.Format(_T("%d:%m:%Y %H:%M:%S"));				
		}		
	}
	else if (type==_T("numbered"))
	{
		if (!start.IsEmpty())
		{
			buf=  APL_T("с: ") + start;
		}
		if (!end.IsEmpty())
		{
			buf+= APL_T(" по: ") + end;				
		}		
	}

	return buf;
}

BOOL CChangeAssemblyDlg::OnInitDialog() 
{
	CResizableDialog::OnInitDialog();
	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   
	
	// TODO: Add extra initialization here
	
	m_imageList.Create(IDR_NAVIGATOR_ICON, 20, 11, RGB(255, 0, 255));
	
	m_chngImageList.Create(IDB_PRD_WHERE_USED, 20, 0, RGB(192, 192, 192));
	m_chngImageList.SetImageCount(2);

	m_btnImageList.Create(24, 24, ILC_COLOR24 | ILC_MASK, 1, 1);
	m_btnImageList.SetImageCount(0);

	CBitmap bm;
	bm.LoadBitmap(IDB_CLEAR_ICO);
	m_btnImageList.Add(&bm, RGB(255, 0, 255));
	bm.DeleteObject();

	bm.LoadBitmap(IDB_REPLACE_ICO);
	m_btnImageList.Add(&bm, RGB(0, 0, 0));
	bm.DeleteObject();

	
	m_cancelBtn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancelBtn.SetFlat(FALSE);

	m_okBtn.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_okBtn.SetFlat(FALSE);
	
	m_refreshBtn.SetIcon(GetAplStdIco16(APLSTDICO_PLAY));
	m_refreshBtn.SetFlat(FALSE);

	m_selectBtn.SetIcon(GetAplTableIco(APL_TABLE_FIND));
	m_selectBtn.SetFlat(FALSE);

	m_itemAddBtn.SetIcon(GetAplStdIco16(APLSTDICO_PLUS));
	m_itemAddBtn.SetFlat(FALSE);

	//m_itemChngBtn.SetIcon(GetAplTableIco(APL_TABLE_REFRESH)/*m_imageList.ExtractIcon(ICON_CHANGE)*/);
	//m_itemChngBtn.SetFlat(FALSE);

	m_itemDeleteBtn.SetIcon(GetAplStdIco16(APLSTDICO_MINUS));
	m_itemDeleteBtn.SetFlat(FALSE);

	m_itemsList.SetImageList(aplGetInstImageList(), LVSIL_SMALL);	
	m_itemsList.SetExtendedStyle(m_itemsList.GetExtendedStyle() | LVS_EX_FULLROWSELECT |
		LVS_EX_SUBITEMIMAGES);
	
	int i= 0;

	if (0 == m_mode || 2 == m_mode)
	{
		m_itemsList.InsertColumn(i++,  APL_T("Позиция"), LVCFMT_LEFT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Позиционный номер"), LVCFMT_LEFT, 50);	
		m_itemsList.InsertColumn(i++,  APL_T("Изменяемое изделие"), LVCFMT_LEFT, 100);
		m_itemsList.InsertColumn(i++,  APL_T("Количество"), LVCFMT_LEFT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Контекст"), LVCFMT_LEFT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Действие"), LVCFMT_LEFT, 70);
		m_itemsList.InsertColumn(i++,  APL_T("Заменить\\Добавить"), LVCFMT_LEFT, 100);
		m_itemsList.InsertColumn(i++,  APL_T("Позиция"), LVCFMT_LEFT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Позиционный номер"), LVCFMT_LEFT, 50);	
		m_itemsList.InsertColumn(i++,  APL_T("Количество"), LVCFMT_RIGHT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Применяемость"), LVCFMT_LEFT, 50);
		
		SetWindowText( APL_T("Изменение сборочной единицы"));
	}
	else if (1 == m_mode)
	{
		m_itemsList.InsertColumn(i++,  APL_T("Приоритет"), LVCFMT_LEFT, 30);
		m_itemsList.InsertColumn(i++,  APL_T("Материал"), LVCFMT_LEFT, 100);
		m_itemsList.InsertColumn(i++,  APL_T("Количество"), LVCFMT_RIGHT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Сортамент"), LVCFMT_LEFT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Действие"), LVCFMT_LEFT, 70);
		m_itemsList.InsertColumn(i++,  APL_T("Заменить\\Добавить"), LVCFMT_LEFT, 100);	
		m_itemsList.InsertColumn(i++,  APL_T("Приоритет"), LVCFMT_LEFT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Количество"), LVCFMT_RIGHT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Сортамент"), LVCFMT_LEFT, 50);
		m_itemsList.InsertColumn(i++,  APL_T("Применяемость"), LVCFMT_LEFT, 50);		
		
		SetWindowText( APL_T("Изменение материалов и норм расхода"));
	}

	m_whereUsedList.SetExtendedStyle(m_whereUsedList.GetExtendedStyle() |
			LVS_EX_FULLROWSELECT | LVS_EX_SUBITEMIMAGES);

	m_whereUsedList.SetImageList(&m_chngImageList, LVSIL_SMALL);
	m_whereUsedList.InsertColumn(0,  APL_T("Где используется"), LVCFMT_LEFT, 500);
	
	
	CString buf;
	int j;
	
	m_itemAddBtn.EnableWindow(FALSE);
	m_itemAddBtn.SetWindowText(_T(""));
	m_itemAddBtn.SetTooltipText( APL_T("Добавить"));

	m_itemChngBtn.EnableWindow(FALSE);
	m_itemChngBtn.SetWindowText(_T(""));
	m_itemChngBtn.SetTooltipText( APL_T("Заменить"));
	m_itemChngBtn.SetIcon(m_btnImageList.ExtractIcon(1)/*GetAplCheckIco(APL_ICON_CHECKOUT, true)*/);
	m_itemChngBtn.SetFlat(FALSE);

	m_itemDeleteBtn.EnableWindow(FALSE);
	m_itemDeleteBtn.SetWindowText(_T(""));
	m_itemDeleteBtn.SetTooltipText( APL_T("Удалить"));

	m_itemClearBtn.EnableWindow(FALSE);
	m_itemClearBtn.SetWindowText(_T(""));
	m_itemClearBtn.SetTooltipText( APL_T("Очистить"));
	m_itemClearBtn.SetFlat(FALSE);
	m_itemClearBtn.SetIcon(m_btnImageList.ExtractIcon(0));

	m_itemPropBtn.EnableWindow(FALSE);
	m_itemPropBtn.SetWindowText(_T(""));
	m_itemPropBtn.SetTooltipText( APL_T("Показать свойства"));
	m_itemPropBtn.SetFlat(FALSE);
	m_itemPropBtn.SetIcon(GetAplTableIco(APL_TABLE_PROP));

	m_setEffBtn.SetWindowText(_T(""));
	m_setEffBtn.SetTooltipText( APL_T("Условие"));
	m_setEffBtn.SetFlat(FALSE);
	m_setEffBtn.SetIcon(GetAplStdIco16(APLSTDICO_QUERY));
	
	if (m_api && apidata.IsConnected())
	{
		// заполняем контексты
		apidata.GetEntityExtent(m_api->m_prd_mgr.e_pd_context, m_contexts);
		for (int i = 0; i < m_contexts.GetSize(); i++)
		{
			apidata.GetAttr(m_contexts[i], m_api->m_prd_mgr.a_pd_context_name, buf);
			j = m_contCtrl.AddString(buf);
			m_contCtrl.SetItemData(j, (long)m_contexts[i]);
		}
		m_iCont = m_contCtrl.AddString( APL_T("Все контексты"));
		m_contCtrl.SetItemData(m_iCont, 0);
		UpdateData(FALSE);
		
		//заполняем таблицу
		CaplInstance* inst= NULL;
		if (!m_assPdf)
		{
			if (m_psc)
				apidata.GetAttr(m_psc, m_api->m_change_mgr.a_psc_changed_product, inst);		
			if (!inst)
				inst = m_pscInfo.m_pdr;
			
			if (inst)
			{
				if (apidata.IsKindOf(inst, m_api->m_prd_mgr.e_apl_pdf))
					m_assPdf = inst;
				else if (apidata.IsKindOf(inst, m_api->m_prd_mgr.e_pdr)) 
					apidata.GetAttr(inst, m_api->m_prd_mgr.a_pdr_r_ting, m_assPdf);
			}
		}

		if (m_assPdf)
		{
			m_itemAddBtn.EnableWindow();
			apidata.GetAttr(m_assPdf, m_api->m_prd_mgr.a_pdf_prd, inst);
			if (inst)
			{
				apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_id, m_sProductId);
				apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_name, m_sProductName);
			}
			apidata.GetAttr(m_assPdf, m_api->m_prd_mgr.a_pdf_id, m_sProductVer);
			
			m_itemAddBtn.EnableWindow();
			UpdateData(FALSE);
		}
		
		m_dateCtrl.EnableWindow(m_bDateSelected);
		
		OnChg2AssRefresh();
	}
	
	if (m_bReadOnly)
	{
		m_itemAddBtn.EnableWindow(FALSE);
		m_selectBtn.EnableWindow(FALSE);
		m_okBtn.EnableWindow(FALSE);
	}
	
	// создаём шрифт
	LoadSystemStrikeOutFont();

	SetAnchors();

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

void CChangeAssemblyDlg::OnChg2AssSelect() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
	
	CaplInstance*  inst= m_api->m_change_mgr.SelectInstance(APL_MODE_SELECT_PDF, 
		 APL_T("Выберите изделие для изменения"));
	
	if (inst)
	{
		m_assPdf = inst;
		apidata.GetAttr(m_assPdf, m_api->m_prd_mgr.a_pdf_prd, inst);
		if (inst)
		{
			apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_id, m_sProductId);
			apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_name, m_sProductName);
		}
		apidata.GetAttr(m_assPdf, m_api->m_prd_mgr.a_pdf_id, m_sProductVer);
		UpdateData(FALSE);	
		
		m_itemAddBtn.EnableWindow();
		OnChg2AssRefresh();
	}
}

void CChangeAssemblyDlg::OnChg2AssRefresh() 
{	
	UpdateData();

	if (0 == m_mode)
		m_api->m_prd_mgr.LoadAllSubProduct(0, 0, m_assPdf, m_extRels, m_extPdfs);		
	else if(1 == m_mode)
		m_api->m_prd_mgr.LoadAllZagotov(m_assPdf, m_extRels, m_extPdfs);
	
	if(m_bNotShow)
	{
		aplExtent ext;
		if(m_bDateSelected)
		{
			m_api->m_prd_mgr.FilterlByDate(m_extRels, m_oleDate, ext);
			m_extRels.Clear();
			m_extRels.Append(ext);
			ext.Clear();
		}
		if(m_bSNSelected)
		{
			m_api->m_prd_mgr.FilterlBySN(m_extRels, m_sSN, ext);
			m_extRels.Clear(); 
			m_extRels.Append(ext);
			ext.Clear();
		}
		
		CaplInstance* cont= (CaplInstance*)m_contCtrl.GetItemData(m_contCtrl.GetCurSel());
		if(cont)
		{
			for(int i= 0; i<m_extRels.GetSize(); i++)
			{
				if(!m_api->m_prd_mgr.IsItemInContext(m_extRels[i], cont, m_api->m_prd_mgr.a_pdr_frames_of_reference))
				{
					m_extRels.Remove(i);
					i--;
					continue;
				}
			}
		}		
	}

	int i;
	bool bLoadData=false;
	CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
	for (i = 0; i < m_extRels.GetSize(); i++)
	{
		if (m_extRels[i]->GetId() == 0)
			continue;

		ld.AddQuery(0, m_extRels[i]);
		bLoadData = true;
	}
	if (bLoadData)
	{
		ld.AddQuery(_T('r'), 0, m_api->m_prd_mgr.e_pd_eff, m_api->m_prd_mgr.a_pde_usage, true, true);
		ld.LoadEx();
	}

	// если выбран фильтр по дате
	if (m_bDateSelected)
		m_bFilteredByDate = true;
	else
		m_bFilteredByDate = false;

	// если выбран фильтр по серийному номеру
	if (m_bSNSelected)
		m_bFilteredBySN = true;
	else
		m_bFilteredBySN = false;
	
	// фильтр по контексту
	CaplInstance* cont= (CaplInstance*)m_contCtrl.GetItemData(m_contCtrl.GetCurSel());

	if (cont)
		m_bFilteredByContext = true;
	else
		m_bFilteredByContext = false;
	
	// перестраиваем список
	FillAssemblyData();
}

bool CChangeAssemblyDlg::FillAssemblyData()
{
	m_itemsList.SetRedraw(FALSE);
	m_itemsList.DeleteAllItems();
	m_itemsList.SetRedraw(TRUE);
	m_itemsList.Invalidate();
	m_AssemblyItems.Clear();
	int i;
	int iLN;

	if (m_assPdf)
	{		
		CaplInstance* inst;
		CString name, buf;
		int index = -1;

		for (i = 0; i < m_extRels.GetSize(); i++)
		{
			iLN= 1;

			CaplInstance* inst2= NULL;
			apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_pdr_r_ted, inst2);
			
			if (!inst2 || !inst2->GetId() || !inst2->GetType())
				continue;

			if (inst2->GetAccessmode() > aplRO)
				continue;
			
			UINT prdIcon = m_api->GetInstIco(inst2);//GetPdfIcon(inst2);

			apidata.GetAttr(inst2, m_api->m_prd_mgr.a_pdf_prd, inst);
			if (inst)
			{
				apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_id, name);
				apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_name, buf);
				if (!name.IsEmpty())
					name += _T(":");
				name += buf;
			}

			apidata.GetAttr(inst2, m_api->m_prd_mgr.a_pdf_id, buf);
			if (!name.IsEmpty())
				name += _T(":");
			name += buf;
			
			if (m_api->m_data.IsKindOf(m_extRels[i], m_api->m_prd_mgr.e_qacu_nauo))
			{
				apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_pdr_id, buf);
			}
			else if(m_api->m_data.IsKindOf(m_extRels[i], m_api->m_prd_mgr.e_make_from))
			{
				int iRank;
				apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_make_from_ranking, iRank);
				buf.Format(_T("%i"), iRank);
			}
			while(buf.GetLength()<4)
				buf= _T(" ")+buf;

			//++index;
			//int ind
			++index; int ind= m_itemsList.InsertItem(index, buf, prdIcon);
			if (m_api->m_data.IsKindOf(m_extRels[i], m_api->m_prd_mgr.e_qacu_nauo))
			{
				m_api->m_data.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_acu_ref_des, buf);
				m_itemsList.SetItemText(index, iLN++, buf);
			}

			sAssemblyListItem* sItem = new sAssemblyListItem;
			sItem->m_iRel = m_extRels[i];

			//m_itemsList.SetItemData(index, (DWORD)relExt[i]);

			if (m_bFilteredByDate)
			{
				COleDateTime cur_time;
				if (m_bDateSelected)
				{
					m_dateCtrl.GetTime(cur_time);
					cur_time.SetDateTime(cur_time.GetYear(), cur_time.GetMonth(), cur_time.GetDay(), 0, 0, 0);
				}
				else
				{
					cur_time = COleDateTime::GetCurrentTime();
					cur_time.SetDateTime(cur_time.GetYear(), cur_time.GetMonth(), cur_time.GetDay(), 0, 0, 0);
				}

				if (!IsPrdEffByDate(m_extRels[i], cur_time))
				{
					sItem->m_Color = RGB(160, 160, 160);
					sItem->m_bActive = false;
				}
			}

			if (m_bFilteredBySN)
			{
				CString sn;
				m_sn.GetWindowText(sn);
				if (!IsPrdEffBySN(m_extRels[i], sn))
				{
					sItem->m_Color = RGB(160, 160, 160); //::GetSysColor(COLOR_GRAYTEXT);
					sItem->m_bActive = false;
				}
			}

			if (m_bFilteredByContext)
			{
				int cont_index = m_contCtrl.GetCurSel();
				CaplInstance* cont= (CaplInstance*)m_contCtrl.GetItemData(cont_index);

				if (!m_api->m_prd_mgr.IsItemInContext(m_extRels[i], cont, m_api->m_prd_mgr.a_pdr_frames_of_reference))
				{
					sItem->m_Color = RGB(160, 160, 160);
					sItem->m_bActive = false;
				}
			}

			m_itemsList.SetItemText(index, iLN++, name);
			m_itemsList.SetItemData(index, (DWORD)sItem);

			m_AssemblyItems.Add(sItem);
			
			double dbl;
			apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_apl_qacu_value, dbl);
			apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_apl_qacu_unit, inst);
			buf=_T("");
			if (inst)
			{
				m_api->m_charact_mgr.GetUnitName(inst, buf);
//				m_api->m_data.GetAttr(inst, m_api->m_charact_mgr.a_apl_unit_id, buf);
			}
			
			if (m_api->m_data.IsKindOf(m_extRels[i], m_api->m_prd_mgr.e_qacu_nauo))
			{
				name.Format(_T("%g [%s]"), dbl, buf);
			}
			else if (m_api->m_data.IsKindOf(m_extRels[i], m_api->m_prd_mgr.e_make_from))
			{
				double der_dbl;
				CaplInstance* der_unit = NULL;
				CString sUnitName;

				//apidata.GetAttrBN(m_extRels[i], _T("derive_value_component"), der_dbl);
				//apidata.GetAttrBN(m_extRels[i], _T("derive_unit_component"), der_unit);
				apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_make_from_derive_value, der_dbl);
				apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_make_from_derive_unit, der_unit);
				if (der_unit)
				{
					m_api->m_charact_mgr.GetUnitName(der_unit, sUnitName);
//					m_api->m_data.GetAttr(der_unit, m_api->m_charact_mgr.a_apl_unit_id, sUnitName);
				}
				
//				name.Format(_T("%4.2f %s -> %4.2f %s"), dbl, buf, der_dbl, sUnitName);
				name.Format(_T("%g [%s]"), dbl, buf);
			}
			
			m_itemsList.SetItemText(index, iLN++, name);
			
			if (m_api->m_data.IsKindOf(m_extRels[i], m_api->m_prd_mgr.e_qacu_nauo))
			{
				aplExtent aggr;
				apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_pdr_frames_of_reference, aggr);
				m_api->m_change_mgr.PrintItemContextInString(aggr, name);

				if (name.IsEmpty())
					name=  APL_T("Все контексты");
			}
			else if (m_api->m_data.IsKindOf(m_extRels[i], m_api->m_prd_mgr.e_make_from))
			{
				name=_T("");
				CaplInstance* assort= NULL;
				apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_make_from_assortment, assort);
				if(assort)
				{
					CString sBuf;
//					apidata.GetAttr(assort, m_api->m_prd_mgr.a_assortment_id, name);
					apidata.GetAttr(assort, m_api->m_prd_mgr.a_assortment_name, sBuf);
					if(!sBuf.IsEmpty()){if(!name.IsEmpty()) name+=_T(":"); name+=sBuf;}
				}
			}
			
			m_itemsList.SetItemText(index, iLN++, name);
			
			bool bFind = false;
			bool bContinue = true;

			CaplInstance* newPdf= NULL, *unit= NULL;
			CString sEffType, sStart, sEnd, sType, sPos, sPosNum, sPrior;
			double dCount=1;

			for (int j = 0; j < m_items->GetSize(); j++)
			{
				bContinue= true;
				CaplInstance* item= m_items->GetAt(j);
				
				if (-1 != m_delItems->Find(item))
					continue;
				
				CaplInstance* pdr_pdf = NULL, *new_pdr = NULL, *inst1 = NULL;
				
				buf = _T("");
				
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_changed_product, pdr_pdf);
				if (apidata.IsKindOf(pdr_pdf, m_api->m_prd_mgr.e_apl_pdf))
				{
					sType =  APL_T("Добавление");
					//sItem->m_Color = RGB(0, 110, 0);
				}
				else if (apidata.IsKindOf(pdr_pdf, m_api->m_prd_mgr.e_pdr))
				{
					sType =  APL_T("Замена");
					//sItem->m_Color = RGB(0, 0, 255);
				}				
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_changing_product, newPdf);
				if (!newPdf)
				{
					sType =  APL_T("Удаление");
					//sItem->m_Color = RGB(255, 0, 0);
				}
				
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_created_pdr, new_pdr);
				if(m_extRels[i] == new_pdr)//эта связь была создана в этом изменении
				{
					//удаляем ее, если это не Добавление
					bFind= true;
					bContinue= false;
					m_itemsList.DeleteItem(index);index--;
					break;
				}
				else if(m_extRels[i]==pdr_pdf)
				{
					bFind = true;
					
					if (newPdf)
					{
						if (0 == m_mode)
						{
							apidata.GetAttr(item, m_api->m_change_mgr.a_psc_position, sPos);					
							apidata.GetAttr(item, m_api->m_change_mgr.a_psc_position_num, sPosNum);					
							apidata.GetAttr(item, m_api->m_change_mgr.a_psc_value, dCount);
							apidata.GetAttr(item, m_api->m_change_mgr.a_psc_unit, unit);
						}
						else if (1 == m_mode)
						{
							CString sBuf; int iPrior;
							CaplInstance* assort= NULL;
							m_api->m_data.GetAttr(item, m_api->m_change_mgr.a_mat_assort, assort);
							if(assort)
							{
								m_api->m_data.GetAttr(assort, m_api->m_prd_mgr.a_assortment_name, sBuf);
								if(!sBuf.IsEmpty()){if(!sPos.IsEmpty()) sPos+=_T(":"); sPos+=sBuf;}									
							}
							m_api->m_data.GetAttr(item, m_api->m_change_mgr.a_psc_value, dCount);
							m_api->m_data.GetAttr(item, m_api->m_change_mgr.a_psc_unit, unit);
							m_api->m_data.GetAttr(item, m_api->m_change_mgr.a_mat_renking, iPrior);
							
							sPrior.Format(_T("%i"), iPrior);
						}
					}
					apidata.GetAttr(item, m_api->m_change_mgr.a_psc_eff_type, sEffType);
					if (sEffType == _T("dated"))
					{
						apidata.GetAttr(item, m_api->m_change_mgr.a_psc_start_date, sStart);
						apidata.GetAttr(item, m_api->m_change_mgr.a_psc_end_date, sEnd);
					}
					else if (sEffType == _T("numbered"))
					{
						apidata.GetAttr(item, m_api->m_change_mgr.a_psc_start_num, sStart);
						apidata.GetAttr(item, m_api->m_change_mgr.a_psc_end_num, sEnd);
					}

					break;
				}
			}//for(int i= 0; i<m_items->GetSize(); i++)
			if (!bFind)
			{
				for (int j = 0; j < m_newItems->GetSize(); j++)
				{
					if(apidata.IsKindOf(m_newItems->GetAt(j).m_pdr, m_api->m_prd_mgr.e_apl_pdf)) 
					{
						sType =  APL_T("Добавление");
						//sItem->m_Color = RGB(0, 110, 0);
					}
					else if(apidata.IsKindOf(m_newItems->GetAt(j).m_pdr, m_api->m_prd_mgr.e_pdr))
					{
						sType =  APL_T("Замена");
						//sItem->m_Color = RGB(0, 0, 255);
					}
					
					if(!m_newItems->GetAt(j).m_pdf)
					{
						newPdf = NULL;
						sType =  APL_T("Удаление");
						//sItem->m_Color = RGB(255, 0, 0);
					}
					else newPdf= m_newItems->GetAt(j).m_pdf;
					
					if(m_extRels[i]==m_newItems->GetAt(j).m_pdr)
					{
						bFind= true;
						if(newPdf)
						{
							if(0==m_mode)
							{
								sPos= m_newItems->GetAt(j).m_sPosition;
								sPosNum= m_newItems->GetAt(j).m_sPositionNum;
								dCount= m_newItems->GetAt(j).m_value;
								unit= m_newItems->GetAt(j).m_unit;
							}
							else if(1==m_mode)
							{
								CString sBuf;
								CaplInstance* assort= m_newItems->GetAt(j).m_sort;
								if(assort)
								{
//									apidata.GetAttr(assort, m_api->m_prd_mgr.a_assortment_id, sPos);
									apidata.GetAttr(assort, m_api->m_prd_mgr.a_assortment_name, sBuf);
									if(!sBuf.IsEmpty()){if(!sPos.IsEmpty()) sPos+=_T(":"); sPos+=sBuf;}									
								}
								
								sPrior.Format(_T("%i"), m_newItems->GetAt(j).m_prior);

								dCount= m_newItems->GetAt(j).m_value;
								unit= m_newItems->GetAt(j).m_unit;
							}
						}
						
						sEffType= m_newItems->GetAt(j).m_sEffType;
						sStart= m_newItems->GetAt(j).m_sStartCond;
						sEnd= m_newItems->GetAt(j).m_sEndCond;

						break;
					}
				}
			}

			if(!bFind)
			{//ищем в новых элементах
				for(int j= 0; j<m_newestItems.GetSize(); j++)
				{
					if(apidata.IsKindOf(m_newestItems.GetAt(j).m_pdr, m_api->m_prd_mgr.e_apl_pdf)) 
					{
						sType=  APL_T("Добавление");
						//sItem->m_Color = RGB(0, 110, 0);
					}
					else if(apidata.IsKindOf(m_newestItems.GetAt(j).m_pdr, m_api->m_prd_mgr.e_pdr))
					{
						sType=  APL_T("Замена");
						//sItem->m_Color = RGB(0, 0, 255);
					}
					
					if (!m_newestItems.GetAt(j).m_pdf)
					{
						newPdf = NULL;
						sType =  APL_T("Удаление");
						//sItem->m_Color = RGB(255, 0, 0);
					}
					else newPdf= m_newestItems.GetAt(j).m_pdf;
					
					if(m_extRels[i]==m_newestItems.GetAt(j).m_pdr)
					{
						bFind= true;
						if(newPdf)
						{
							if(0==m_mode)
							{
								sPos= m_newestItems.GetAt(j).m_sPosition;
								sPosNum= m_newestItems.GetAt(j).m_sPositionNum;
								dCount= m_newestItems.GetAt(j).m_value;
								unit= m_newestItems.GetAt(j).m_unit;
							}
							else if(m_mode==1)
							{
								CString sBuf;
								CaplInstance* assort= m_newestItems.GetAt(j).m_sort;
								if(assort)
								{
				//					apidata.GetAttr(assort, m_api->m_prd_mgr.a_assortment_id, sPos);
									apidata.GetAttr(assort, m_api->m_prd_mgr.a_assortment_name, sBuf);
									if(!sBuf.IsEmpty()){if(!sPos.IsEmpty()) sPos+=_T(":"); sPos+=sBuf;}								
								}
								
								sPrior.Format(_T("%i"), m_newestItems.GetAt(j).m_prior);

								dCount= m_newestItems.GetAt(j).m_value;
								unit= m_newestItems.GetAt(j).m_unit;
							}
								
						}
						sEffType= m_newestItems.GetAt(j).m_sEffType;
						sStart= m_newestItems.GetAt(j).m_sStartCond;
						sEnd= m_newestItems.GetAt(j).m_sEndCond;

						break;
					}
				}
			}

			if(bFind && bContinue)
			{
				m_itemsList.SetItemText(index, iLN++, sType);
				InsertText(index, iLN, newPdf, dCount, unit, sPos, sPosNum, sEffType, sStart, sEnd, sPrior);

				if (sType ==  APL_T("Замена") && sItem->m_bActive)
					sItem->m_Color = RGB(0, 0, 255);

				if (sType ==  APL_T("Удаление") && sItem->m_bActive)
					sItem->m_Color = RGB(255, 0, 0);

				if (sType ==  APL_T("Добавление") && sItem->m_bActive)
					sItem->m_Color = RGB(0, 110, 0);
			}
		}
		
		//блин, все то же самое для добавления в сборку
		//потом можно что-нибудь другое придумать
		CaplInstance *pdr_pdf, *newPdf, *unit;
		CString sEffType, sStart, sEnd, sType, sPos, sPosNum, sPrior;
		double dCount;
		int n;
			
		for(n= 0; n<m_items->GetSize(); n++)
		{
			iLN=(m_mode==0)?5:4;
			CaplInstance* item= m_items->GetAt(n);
			
			if(-1!=m_delItems->Find(item)) continue;

			apidata.GetAttr(item, m_api->m_change_mgr.a_psc_changed_product, pdr_pdf);
			if(m_assPdf==pdr_pdf)
			{
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_changing_product, newPdf);
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_position, sPos);					
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_position_num, sPosNum);					
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_value, dCount);
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_unit, unit);
				apidata.GetAttr(item, m_api->m_change_mgr.a_psc_eff_type, sEffType);
				if(sEffType==_T("dated"))
				{
					apidata.GetAttr(item, m_api->m_change_mgr.a_psc_start_date, sStart);
					apidata.GetAttr(item, m_api->m_change_mgr.a_psc_end_date, sEnd);
				}
				else if(sEffType==_T("numbered"))
				{
					apidata.GetAttr(item, m_api->m_change_mgr.a_psc_start_num, sStart);
					apidata.GetAttr(item, m_api->m_change_mgr.a_psc_end_num, sEnd);
				}
				
				if(1==m_mode)
				{
					int iPrior;
					m_api->m_data.GetAttr(item, m_api->m_change_mgr.a_mat_renking, iPrior);
					sPrior.Format(_T("%i"), iPrior);
				}

				UINT prdIcon= m_api->GetInstIco(newPdf);//GetPdfIcon(newPdf);
				
				++index; m_itemsList.InsertItem(index, _T(""), prdIcon);

				sAssemblyListItem* sItem = new sAssemblyListItem;
				sItem->m_iRel = newPdf;
				sItem->m_Color = RGB(0, 110, 0);

				//m_itemsList.SetItemData(index, (DWORD)newPdf);
				m_itemsList.SetItemData(index, (DWORD)sItem);
				m_AssemblyItems.Add(sItem);

				m_itemsList.SetItemText(index, iLN++,  APL_T("Добавление"));				
				InsertText(index, iLN, newPdf, dCount, unit, sPos, sPosNum,
					sEffType, sStart, sEnd, sPrior);
				i++;
			}
		}

		for(n= 0; n<m_newItems->GetSize(); n++)
		{
			iLN=(m_mode==0)?5:4;
			if(m_assPdf==m_newItems->GetAt(n).m_pdr)
			{
				UINT prdIcon= m_api->GetInstIco(m_newItems->GetAt(n).m_pdf);//GetPdfIcon(m_newItems->GetAt(n).m_pdf);

				++index; m_itemsList.InsertItem(index, _T(""), prdIcon);

				sAssemblyListItem* sItem = new sAssemblyListItem;
				sItem->m_iRel = m_newItems->GetAt(n).m_pdf;
				sItem->m_Color = RGB(0, 110, 0);
				m_itemsList.SetItemData(index, (DWORD)sItem);
				m_AssemblyItems.Add(sItem);

				//m_itemsList.SetItemData(i, (DWORD)m_newItems->GetAt(n).m_pdf);
				m_itemsList.SetItemText(i, iLN++,  APL_T("Добавление"));				
				
				sPrior.Format(_T("%i"), m_newItems->GetAt(n).m_prior);
				
				InsertText(index, iLN, m_newItems->GetAt(n).m_pdf, 
					m_newItems->GetAt(n).m_value, m_newItems->GetAt(n).m_unit, 
					m_newItems->GetAt(n).m_sPosition, 
					m_newItems->GetAt(n).m_sPositionNum, 
					m_newItems->GetAt(n).m_sEffType, 
					m_newItems->GetAt(n).m_sStartCond, 
					m_newItems->GetAt(n).m_sEndCond,
					sPrior);				
				i++;
			}
		}

		for(n= 0; n<m_newestItems.GetSize(); n++)
		{
			iLN=(m_mode==0)?5:4;
			if(m_assPdf==m_newestItems.GetAt(n).m_pdr)
			{
				UINT prdIcon= m_api->GetInstIco(m_newestItems.GetAt(n).m_pdf);//GetPdfIcon(m_newestItems.GetAt(n).m_pdf);

				++index; m_itemsList.InsertItem(index, _T(""), prdIcon);

				sAssemblyListItem* sItem = new sAssemblyListItem;
				sItem->m_iRel = m_newestItems.GetAt(n).m_pdf;
				sItem->m_Color = RGB(0, 110, 0);
				m_itemsList.SetItemData(index, (DWORD)sItem);
				m_AssemblyItems.Add(sItem);

				//m_itemsList.SetItemData(index, (DWORD)m_newestItems.GetAt(n).m_pdf);
				m_itemsList.SetItemText(index, iLN++,  APL_T("Добавление"));				
				
				sPrior.Format(_T("%i"), m_newestItems.GetAt(n).m_prior);
				
				InsertText(index, iLN, m_newestItems.GetAt(n).m_pdf, 
					m_newestItems.GetAt(n).m_value, m_newestItems.GetAt(n).m_unit, 
					m_newestItems.GetAt(n).m_sPosition, 
					m_newestItems.GetAt(n).m_sPositionNum, 
					m_newestItems.GetAt(n).m_sEffType, 
					m_newestItems.GetAt(n).m_sStartCond, 
					m_newestItems.GetAt(n).m_sEndCond,
					sPrior);
				
				i++;
			}			
		}

		m_itemsList.AutoSizeAllColumns();
	}

	return true;
}

void CChangeAssemblyDlg::OnItemchangedChangeItemsList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
	
	CString buf;
	m_curPSC = NULL;
	m_curPSCInfo = NULL;

	// очищаем список "Где используется"
	m_whereUsedList.SetRedraw(FALSE);
	m_whereUsedList.DeleteAllItems();
	m_whereUsedList.SetRedraw(TRUE);
	m_whereUsedList.Invalidate();
	m_WhereUsedItems.Clear();
	
	//if (pNMListView->uOldState == 0 && pNMListView->uNewState != 0)
	if (pNMListView->uNewState == 3)
	{	
		// индекс выбранного итема
		m_index = pNMListView->iItem;

		buf = m_itemsList.GetItemText(m_index, (m_mode==0)?5:4);
		//m_curItem = (CaplInstance*)m_itemsList.GetItemData(m_index);
		sAssemblyListItem* sItem = (sAssemblyListItem*)m_itemsList.GetItemData(m_index);
		if(sItem)
			m_curItem = sItem->m_iRel;

		if (m_curItem && apidata.IsKindOf(m_curItem, m_api->m_prd_mgr.e_pdr))
		{
			CaplInstance* inst= NULL;
			apidata.GetAttr(m_curItem, m_api->m_prd_mgr.a_pdr_r_ted, inst);
			if(inst)
			{
				aplExtent rels, ext;

				// грузим состав
				m_api->m_prd_mgr.WhereUsedProduct(inst, rels, ext);
				
				aplExtent inListExt; 
				int num= 0;

				for(int i=0; i<rels.GetSize(); i++)
				{
					if(m_mode==0 && !m_api->m_data.IsKindOf(rels[i], m_api->m_prd_mgr.e_acu)) continue;
					if(m_mode==1 && !m_api->m_data.IsKindOf(rels[i], m_api->m_prd_mgr.e_make_from)) continue;

					inst= NULL;
					apidata.GetAttr(rels[i], m_api->m_prd_mgr.a_pdr_r_ting, inst);
					if(inst && -1==inListExt.Find(inst))
					{
						inListExt.Add(inst);

						CString name, buf;
						CaplInstance* prd= NULL;
						apidata.GetAttr(inst, m_api->m_prd_mgr.a_pdf_prd, prd);
						if(prd)
						{
							apidata.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, name);
							apidata.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, buf);
							if(!name.IsEmpty()) name+=_T(":"); name+=buf;
						}
						apidata.GetAttr(inst, m_api->m_prd_mgr.a_pdf_id, buf);
						if (!name.IsEmpty())
							name += _T(":");
						name += buf;

						int ico = 0;
						if (inst == m_assPdf)
							ico = 1;

						if (!name.IsEmpty())
						{
							sWhereUsedListItem* sWhereUsedItem = new sWhereUsedListItem;
							sWhereUsedItem->m_iRel = rels[i];
							
							COleDateTime dt;

							if (m_bDateSelected)
							{
								m_dateCtrl.GetTime(dt);
								dt.SetDateTime(dt.GetYear(), dt.GetMonth(), dt.GetDay(), 0, 0, 0);
							}
							else
							{
								dt = COleDateTime::GetCurrentTime();
								dt.SetDateTime(dt.GetYear(), dt.GetMonth(), dt.GetDay(), 0, 0, 0);
							}

							sWhereUsedItem->m_bActive = IsPrdEffByDate(rels[i], dt);

							m_whereUsedList.InsertItem(num, name, ico);
							m_whereUsedList.SetItemData(num, (DWORD)sWhereUsedItem);

							m_WhereUsedItems.Add(sWhereUsedItem);


							//m_whereUsedList.SetItemData(num, (DWORD)rels[i]);
							num++;
						}
					}
				}

				m_whereUsedList.AutoSizeAllColumns();
			}
		}
	}
	else
	{
		m_index = -1;
		m_curItem = NULL;
	}

	m_itemChngBtn.EnableWindow(FALSE);
	m_itemDeleteBtn.EnableWindow(FALSE);

	m_itemClearBtn.EnableWindow(FALSE);
	m_itemPropBtn.EnableWindow(FALSE);
	
	if(buf== APL_T("Замена"))
	{
		if(!m_bReadOnly)
		{
			m_itemClearBtn.EnableWindow();
			m_itemDeleteBtn.EnableWindow();
		}

		m_itemPropBtn.EnableWindow();		
	}
	else if(buf== APL_T("Добавление"))
	{
		if(!m_bReadOnly)
			m_itemClearBtn.EnableWindow();
		
		m_itemPropBtn.EnableWindow();	
	}
	else if(buf== APL_T("Удаление"))
	{
		if(!m_bReadOnly)
		{
			m_itemClearBtn.EnableWindow();		
			m_itemChngBtn.EnableWindow();
		}

		m_itemPropBtn.EnableWindow();
	}
	else
	{
		if(m_index!=-1 && !m_bReadOnly)
		{
			m_itemChngBtn.EnableWindow();
			m_itemDeleteBtn.EnableWindow();
		}
	}

	m_itemsList.SetFocus();

	*pResult = 0;
}

void CChangeAssemblyDlg::OnOK() 
{
	// TODO: Add extra validation here
	for (int i = 0; i < m_newestItems.GetSize(); i++)
		m_newItems->Add(m_newestItems[i]);
	
	CResizableDialog::OnOK();
}

void CChangeAssemblyDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	
	CResizableDialog::OnCancel();
}

void CChangeAssemblyDlg::OnChg2Prop() 
{
	// TODO: Add your control notification handler code here

	CChangeParamDlg dlg;
	dlg.m_api = m_api;
	dlg.m_mode = m_mode;
	dlg.m_bReadOnly = m_bReadOnly;
	dlg.m_change= m_change;

	CString buf = m_itemsList.GetItemText(m_index, (m_mode==0)?5:4);
	if (buf ==  APL_T("Удаление"))
		dlg.m_sType= _T("delete");

	else if (buf ==  APL_T("Замена"))
		dlg.m_sType= _T("change");

	FindItem(&dlg);

	if (IDOK == dlg.DoModal())
	{
		FillAssemblyData();
	}
}

bool CChangeAssemblyDlg::FindItem(CChangeParamDlg *dlg, bool bDelete)
{
	bool bFind= false;
	m_curPSC= NULL;
	m_curPSCInfo= NULL;
	int i;
	int iPosInd= (m_mode==0)?7:6;

	for(i= 0; i<m_items->GetSize(); i++)
	{
		CaplInstance* inst= m_items->GetAt(i);

		CaplInstance* pdr= NULL, *pdf= NULL;
		CString sPos;
		CString buf= m_itemsList.GetItemText(m_index, iPosInd);
		buf.TrimRight();
		buf.TrimLeft();

		apidata.GetAttr(inst, m_api->m_change_mgr.a_psc_changed_product, pdr);
		apidata.GetAttr(inst, m_api->m_change_mgr.a_psc_changing_product, pdf);
		if(0==m_mode) apidata.GetAttr(inst, m_api->m_change_mgr.a_psc_position, sPos);
		else if(1==m_mode)
		{
			int iPrior;
			apidata.GetAttr(inst, m_api->m_change_mgr.a_mat_renking, iPrior);
			sPos.Format(_T("%i"), iPrior);
		}

		if(m_curItem==pdr || (pdr==m_assPdf && m_curItem==pdf && !buf.CompareNoCase(sPos)))
		{//могут добавлять один и тот же pdf, но под разной позицией
			bFind= true;
			m_curPSC= inst;
			if(dlg)dlg->m_psc= inst;
			if(bDelete) m_delItems->Add(inst);
			break;
		}
	}
	
	if(!bFind)
	{
		for(i= 0; i<m_newItems->GetSize(); i++)
		{
			CString buf= m_itemsList.GetItemText(m_index, iPosInd);
			buf.TrimRight();
			buf.TrimLeft();
			CString buf1;
			
			if(0==m_mode) buf1= m_newItems->GetAt(i).m_sPosition;
			else if(1==m_mode)buf1.Format(_T("%i"), m_newItems->GetAt(i).m_prior);

			if(m_curItem==m_newItems->GetAt(i).m_pdr || 
				(m_curItem==m_newItems->GetAt(i).m_pdf &&
					!buf.CompareNoCase(buf1)))
			{//могут добавлять один и тот же pdf, но под разной позицией
				bFind= true;
				m_curPSCInfo= &m_newItems->ElementAt(i);
				if(dlg)	dlg->m_pscInfo= &m_newItems->ElementAt(i);
				if(bDelete) m_newItems->RemoveAt(i);
				break;
			}
		}
	}
	if(!bFind)
	{
		for(i= 0; i<m_newestItems.GetSize(); i++)
		{
			CString buf= m_itemsList.GetItemText(m_index, iPosInd);
			buf.TrimRight();
			buf.TrimLeft();
			CString buf1;

			if(0==m_mode) buf1= m_newestItems.GetAt(i).m_sPosition;
			else if(1==m_mode)buf1.Format(_T("%i"), m_newestItems.GetAt(i).m_prior);
			
			if(m_curItem==m_newestItems.GetAt(i).m_pdr || 
				(m_curItem==m_newestItems.GetAt(i).m_pdf &&
					!buf.CompareNoCase(buf1)))
			{//могут добавлять один и тот же pdf, но под разной позицией
				bFind= true;
				m_curPSCInfo= &m_newestItems.ElementAt(i);
				if(dlg)	dlg->m_pscInfo= &m_newestItems.ElementAt(i);
				if(bDelete) m_newestItems.RemoveAt(i);
				break;
			}
		}
	}

	return bFind;
}

void CChangeAssemblyDlg::OnChg2SetEff() 
{
	// TODO: Add your control notification handler code here
	CChangeParamDlg dlg;
	dlg.m_sType = _T("eff_type");	
	
	dlg.m_sEffType = m_sEffType;
	dlg.m_sStart = m_sStartCond;
	dlg.m_sEnd = m_sEndCond;
	
	if (IDOK == dlg.DoModal())
	{
		m_sEffType = dlg.m_sEffType;
		m_sStartCond = dlg.m_sStart;
		m_sEndCond = dlg.m_sEnd;
	}
}

void CChangeAssemblyDlg::OnChg2Clear() 
{
	// TODO: Add your control notification handler code here
	if(IDYES==MessageBox( APL_T("Вы действительно хотите удалить запись об изменении?"),
		 APL_T("Удаление"), MB_YESNO|MB_ICONWARNING))
	{
		FindItem(NULL, true);
		FillAssemblyData();
	}
}

void CChangeAssemblyDlg::OnChg2ItemChange() 
{
	// TODO: Add your control notification handler code here
	CChangeParamDlg dlg;
	dlg.m_api= m_api;
	dlg.m_mode= m_mode;
	dlg.m_upLevelPdf= m_curItem;
	
	dlg.m_sType= _T("change");
	
	dlg.m_sEffType= m_sEffType;
	dlg.m_sStart= m_sStartCond;
	dlg.m_sEnd= m_sEndCond;
	
	bool bNew= false;
	if(!FindItem(&dlg))//для случая, когда элемент удален
	{
		bNew= true;
		//в диалог записываем параметры по умолчанию из pdr
		if(0==m_mode)
		{
			apidata.GetAttr(m_curItem, m_api->m_prd_mgr.a_pdr_id, dlg.m_sPosition);
			apidata.GetAttr(m_curItem, m_api->m_prd_mgr.a_acu_ref_des, dlg.m_sPositionNum);
			//apidata.GetAttrBN(m_curItem, _T("value_component"), dlg.m_iValue);
			//apidata.GetAttrBN(m_curItem, _T("unit_component"), dlg.m_unitInst);
			apidata.GetAttr(m_curItem, m_api->m_prd_mgr.a_apl_qacu_value, dlg.m_iValue);
			apidata.GetAttr(m_curItem, m_api->m_prd_mgr.a_apl_qacu_unit, dlg.m_unitInst);
		}
		else if(1==m_mode)
		{
			m_api->m_data.GetAttr(m_curItem, m_api->m_prd_mgr.a_make_from_ranking, dlg.m_iPrior);
//			m_api->m_data.GetAttrBN(m_curItem, _T("value_component"), dlg.m_iValue);
//			m_api->m_data.GetAttrBN(m_curItem, _T("unit_component"), dlg.m_unitInst);
		}
	}
	if(IDOK==dlg.DoModal())
	{
		if(bNew)
		{
			CPSCItemInfo info;
			info.m_pdr= m_curItem;
			info.m_pdf= dlg.m_newPdf;
			info.m_sId= dlg.m_sRegNum;
			info.m_sName= dlg.m_sPdrName;
			info.m_sDscr= dlg.m_sPdrDscr;
			info.m_sPosition= dlg.m_sPosition;
			info.m_sPositionNum= dlg.m_sPositionNum;
			info.m_value= dlg.m_iValue;
			info.m_unit= dlg.m_unitInst;
			
			info.m_sEffType= dlg.m_sEffType;
			info.m_sStartCond= dlg.m_sStart;
			info.m_sEndCond= dlg.m_sEnd;
		
			info.m_der_unit= dlg.m_derUnitInst;
			info.m_der_value= dlg.m_iDerValue;

			info.m_sort= dlg.m_assortment;
			info.m_prior= dlg.m_iPrior;
			info.m_razmer= dlg.m_sZagotov;
			info.m_tehTreb= dlg.m_sCondition;			
			
			info.SetContexts(dlg.m_contexts);

			aplExtent ext;
			apidata.GetAttr(m_curItem, m_api->m_prd_mgr.a_pdr_frames_of_reference, ext);
			info.SetAttachment(ext);
			
			m_newestItems.Add(info);			
		}
		FillAssemblyData();
	}
}

void CChangeAssemblyDlg::OnChg2ItemDelete() 
{
	// TODO: Add your control notification handler code here
	CChangeParamDlg dlg;
	if(!FindItem(&dlg))
	{
		//новая запись об изменении
		dlg.m_api= m_api;
		dlg.m_mode= m_mode;
		dlg.m_upLevelPdf= m_curItem;

		dlg.m_sType= _T("delete");
	
		dlg.m_sEffType= m_sEffType;
		dlg.m_sStart= m_sStartCond;
		dlg.m_sEnd= m_sEndCond;
		
		if(IDOK==dlg.DoModal())
		{
			CPSCItemInfo info;
			info.m_pdr= m_curItem;
			info.m_pdf= NULL;
			info.m_sId= dlg.m_sRegNum;
			info.m_sPosition= _T("");
			info.m_sPositionNum= _T("");
			info.m_value= 0;
			info.m_unit= NULL;
			
			info.m_der_unit= 0;
			info.m_der_value= NULL;

			info.m_sort= NULL;
			info.m_prior= 0;
			info.m_razmer= _T("");
			info.m_tehTreb= _T("");			
			
			info.m_sEffType= dlg.m_sEffType;
			info.m_sStartCond= dlg.m_sStart;
			info.m_sEndCond= dlg.m_sEnd;

			info.SetContexts(dlg.m_contexts);

			m_newestItems.Add(info);
		}
	} 
	else//для случая, когда элемент заменен
	{
		CaplInstance* inst= NULL;
		if(m_curPSC) 
		{
			apidata.PutAttr(m_curPSC, m_api->m_change_mgr.a_psc_changing_product, (CaplInstance*)NULL);
			apidata.PutAttr(m_curPSC, m_api->m_change_mgr.a_psc_position, _T(""));
			apidata.PutAttr(m_curPSC, m_api->m_change_mgr.a_psc_position_num, _T(""));
			apidata.PutAttr(m_curPSC, m_api->m_change_mgr.a_psc_value, 0.0);
			apidata.PutAttr(m_curPSC, m_api->m_change_mgr.a_psc_unit, inst);

			if(m_api->m_data.IsKindOf(m_curPSC, m_api->m_change_mgr.e_mat))
			{
				m_api->m_data.PutAttr(m_psc, m_api->m_change_mgr.a_mat_assort, (CaplInstance*)NULL);
				m_api->m_data.PutAttr(m_psc, m_api->m_change_mgr.a_mat_der_unit, (CaplInstance*)NULL);
				m_api->m_data.PutAttr(m_psc, m_api->m_change_mgr.a_mat_der_value, 0.0);
				m_api->m_data.PutAttr(m_psc, m_api->m_change_mgr.a_mat_renking, 0);
				m_api->m_data.PutAttr(m_psc, m_api->m_change_mgr.a_mat_requir, _T(""));
				m_api->m_data.PutAttr(m_psc, m_api->m_change_mgr.a_mat_size, _T(""));
			}
		}
		else if(m_curPSCInfo) 
		{
			m_curPSCInfo->m_pdf= inst;
			m_curPSCInfo->m_sPosition= _T("");
			m_curPSCInfo->m_sPositionNum= _T("");
			m_curPSCInfo->m_value= 0;
			m_curPSCInfo->m_unit= NULL;
			
			m_curPSCInfo->m_der_unit= 0;
			m_curPSCInfo->m_der_value= NULL;

			m_curPSCInfo->m_sort= NULL;
			m_curPSCInfo->m_prior= 0;
			m_curPSCInfo->m_razmer= _T("");
			m_curPSCInfo->m_tehTreb= _T("");			
		}
	}
	FillAssemblyData();
}

void CChangeAssemblyDlg::OnChg2SnCheck() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
	if (m_bSNSelected)
		m_sn.SetReadOnly(FALSE);
	else
		m_sn.SetReadOnly();	
}

void CChangeAssemblyDlg::OnChg2DateCheck() 
{
	// TODO: Add your control notification handler code here
	UpdateData();
	m_dateCtrl.EnableWindow(m_bDateSelected);
}

void CChangeAssemblyDlg::OnCloseupChg2ContextCombo() 
{
	// TODO: Add your control notification handler code here
	m_refreshBtn.EnableWindow();
}

void CChangeAssemblyDlg::OnDatetimechangeChg2DateCtrl(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	m_refreshBtn.EnableWindow();
	*pResult = 0;
}

void CChangeAssemblyDlg::OnChangeChg2SnCtrl() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CResizableDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	m_refreshBtn.EnableWindow();
}

void CChangeAssemblyDlg::OnDblclkListWhereUsed(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	int index= m_whereUsedList.GetNextItem(-1, LVNI_ALL|LVNI_SELECTED);	
	if(index!=-1)
	{
		sWhereUsedListItem* sWUStruct= (sWhereUsedListItem*)m_whereUsedList.GetItemData(index);
		CaplInstance* inst= NULL;
		if(sWUStruct->m_iRel)
		{
			m_api->m_data.GetAttr(sWUStruct->m_iRel, m_api->m_prd_mgr.a_pdr_r_ting, m_assPdf);

			apidata.GetAttr(m_assPdf, m_api->m_prd_mgr.a_pdf_prd, inst);
			if (inst)
			{
				apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_id, m_sProductId);
				apidata.GetAttr(inst, m_api->m_prd_mgr.a_prd_name, m_sProductName);
			}
			apidata.GetAttr(m_assPdf, m_api->m_prd_mgr.a_pdf_id, m_sProductVer);
			UpdateData(FALSE);	

			m_itemAddBtn.EnableWindow();
			OnChg2AssRefresh();
		}
	}
	//*pResult = 0;
}

void CChangeAssemblyDlg::OnDblclkChangeItemsList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	
	CString buf;
	if (-1 != m_index)
		buf = m_itemsList.GetItemText(m_index, (m_mode==0)?5:4);

	if (!buf.IsEmpty())
		OnChg2Prop();

	*pResult = 0;
}

void CChangeAssemblyDlg::OnChg2ItemAdd() 
{
	// TODO: Add your control notification handler code here
	CChangeParamDlg dlg;
	dlg.m_api= m_api;
	dlg.m_mode= m_mode;
	dlg.m_upLevelPdf= m_assPdf;

	dlg.m_sEffType= m_sEffType;
	dlg.m_sStart= m_sStartCond;
	dlg.m_sEnd= m_sEndCond;

	if(IDOK==dlg.DoModal())
	{
		CPSCItemInfo info;
		info.m_pdr= m_assPdf;
		info.m_pdf= dlg.m_newPdf;
		info.m_sId= dlg.m_sRegNum;
		info.m_sName= dlg.m_sPdrName;
		info.m_sDscr= dlg.m_sPdrDscr;
		info.m_sPosition= dlg.m_sPosition;
		info.m_sPositionNum= dlg.m_sPositionNum;
		info.m_value= dlg.m_iValue;
		info.m_unit= dlg.m_unitInst;
		
		info.m_sEffType= dlg.m_sEffType;
		info.m_sStartCond= dlg.m_sStart;
		info.m_sEndCond= dlg.m_sEnd;
		
		info.m_der_unit= dlg.m_derUnitInst;
		info.m_der_value= dlg.m_iDerValue;

		info.m_sort= dlg.m_assortment;
		info.m_prior= dlg.m_iPrior;
		info.m_razmer= dlg.m_sZagotov;
		info.m_tehTreb= dlg.m_sCondition;			

		info.SetContexts(dlg.m_contexts);

		m_newestItems.Add(info);
		FillAssemblyData();
	}
}

void CChangeAssemblyDlg::OnCustomdrawAssemblyItemsList ( NMHDR* pNMHDR, LRESULT* pResult )
{
	NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
	//NMCUSTOMDRAW pLV = (NMCUSTOMDRAW)pLVCD->nmcd;

	*pResult = CDRF_DODEFAULT;

	if ( CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage )
	{
        *pResult |= CDRF_NOTIFYITEMDRAW;
	}
    else if ( CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage )
	{
		/*
		COLORREF color = ::GetSysColor(COLOR_WINDOWTEXT);

		CString buf = m_itemsList.GetItemText(pLVCD->nmcd.dwItemSpec, 4);
		if (buf == APL_T("Добавление"))
			color = RGB(0, 110, 0);
		else if (buf == APL_T("Замена"))
			color = RGB(0, 0, 255);
		else if (buf == APL_T("Удаление"))
			color = RGB(255, 0, 0);

		if (m_bFilteredByDate)
		{
			CaplInstance* inst = (CaplInstance*)m_itemsList.GetItemData(pLVCD->nmcd.dwItemSpec);

			COleDateTime cur_time;
			if (m_bDateSelected)
			{
				m_dateCtrl.GetTime(cur_time);
				cur_time.SetDateTime(cur_time.GetYear(), cur_time.GetMonth(), cur_time.GetDay(), 0, 0, 0);
			}
			else
			{
				cur_time = COleDateTime::GetCurrentTime();
				cur_time.SetDateTime(cur_time.GetYear(), cur_time.GetMonth(), cur_time.GetDay(), 0, 0, 0);
			}

			if (!IsPrdEffByDate(inst, cur_time))
				color = RGB(160, 160, 160); //::GetSysColor(COLOR_GRAYTEXT);
		}

		if (m_bFilteredBySN)
		{
			//

			CaplInstance* inst = (CaplInstance*)m_itemsList.GetItemData(pLVCD->nmcd.dwItemSpec);

			CString sn;
			m_sn.GetWindowText(sn);
			if (!IsPrdEffBySN(inst, sn))
				color = RGB(160, 160, 160); //::GetSysColor(COLOR_GRAYTEXT);
		}

		if (m_bFilteredByContext)
		{
			CaplInstance* cont= (CaplInstance*)m_contCtrl.GetItemData(m_contCtrl.GetCurSel());
			CaplInstance* inst = (CaplInstance*)m_itemsList.GetItemData(pLVCD->nmcd.dwItemSpec);

			if (!m_api->m_prd_mgr.IsItemInContext(inst, cont, m_api->m_prd_mgr.a_pdr_frames_of_reference))
				color = RGB(160, 160, 160); //::GetSysColor(COLOR_GRAYTEXT);
		}
		*/
		int iIndex= m_itemsList.GetItemCount();
		sAssemblyListItem* sItem = (sAssemblyListItem*)m_itemsList.GetItemData(pLVCD->nmcd.dwItemSpec);

		if(sItem)
			pLVCD->clrText = sItem->m_Color;
			
		*pResult |= CDRF_NEWFONT; //CDRF_DODEFAULT;
	}
}

void CChangeAssemblyDlg::OnCustomdrawAssemblyWhereUsedItemsList( NMHDR* pNMHDR, LRESULT* pResult )
{
	NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
	NMCUSTOMDRAW pLV = (NMCUSTOMDRAW)pLVCD->nmcd;

	*pResult = CDRF_DODEFAULT;

	if ( CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage )
	{
        *pResult |= CDRF_NOTIFYITEMDRAW;
	}
    else if ( CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage )
	{
		//CaplInstance* inst = (CaplInstance*)m_whereUsedList.GetItemData(pLVCD->nmcd.dwItemSpec);
		sWhereUsedListItem* sItem = (sWhereUsedListItem*)m_whereUsedList.GetItemData(pLVCD->nmcd.dwItemSpec);

		if (sItem)
		{
			/*
			COleDateTime cur_time;
			if (m_bDateSelected)
			{
				m_dateCtrl.GetTime(cur_time);
				cur_time.SetDateTime(cur_time.GetYear(), cur_time.GetMonth(), cur_time.GetDay(), 0, 0, 0);
			}
			else
			{
				cur_time = COleDateTime::GetCurrentTime();
				cur_time.SetDateTime(cur_time.GetYear(), cur_time.GetMonth(), cur_time.GetDay(), 0, 0, 0);
			}
			
			if (!IsPrdEffByDate(inst, cur_time))
			{
				::SelectObject(pLV.hdc, m_FontStrikeOut);
				pLVCD->clrText = RGB(160, 160, 160); //::GetSysColor(COLOR_GRAYTEXT);
			}
			else
				pLVCD->clrText = ::GetSysColor(COLOR_WINDOWTEXT);
			*/

			if (sItem->m_bActive)
				pLVCD->clrText = ::GetSysColor(COLOR_WINDOWTEXT);
			else
			{
				::SelectObject(pLV.hdc, m_FontStrikeOut);
				pLVCD->clrText = RGB(160, 160, 160);
			}
		}

		*pResult |= CDRF_NEWFONT; //CDRF_DODEFAULT;
	}
}

void CChangeAssemblyDlg::OnAssemblyListHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult)
{
	HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;

	*pResult = NULL;
}

bool CChangeAssemblyDlg::IsPrdEffByDate(CaplInstance* rel, COleDateTime date)
{
	aplExtent eff_ext;
/*
	CaplAttrValue val[1];
	val[0].attr = m_api->m_prd_mgr.a_pde_usage;
	val[0].value.Set(rel);

	apidata.NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_pd_eff, 1, &val[0], eff_ext, false);
	
	m_api->LoadExtentInfo(eff_ext);
*/
	CString date_start, date_end;
	//COleDateTime start_time, end_time;
	CString dt;
	aplDate2String(date, dt);
	
	int size = 0;
	int i;
	CaplInstance *inst;

	m_api->m_data.GetEntityExtent(m_api->m_prd_mgr.e_pd_eff, eff_ext);

	for (i = 0; i < eff_ext.GetSize(); i++)
	{
		apidata.GetAttr(eff_ext[i], m_api->m_prd_mgr.a_pde_usage, inst);
		if (inst != rel)
			continue;

		if (apidata.IsKindOf(eff_ext[i],m_api->m_prd_mgr.e_dat_eff))
		{
			apidata.GetAttr(eff_ext[i], m_api->m_prd_mgr.a_dat_eff_start_s, date_start);
			apidata.GetAttr(eff_ext[i], m_api->m_prd_mgr.a_dat_eff_end_s, date_end);
			
			
			/*
			aplString2Date(date_start, start_time);
			aplString2Date(date_end, end_time);
			
			
			if (date_start.IsEmpty())
				start_time.SetDateTime(1900, 1, 1, 0, 0, 0);
			
			if (date_end.IsEmpty())
				end_time.SetDateTime(2050, 1, 1, 0, 0, 0);
				
			if (date > start_time && date < end_time)
				return true;
				*/

			
			if (date_start.IsEmpty())
				return false;

			if (date_start > dt)
				return false;

			if (date_end.IsEmpty())
				return true;

			if (date_end >= dt)
				return true;

			size++;
		}
	}

	if (size == 0)
		return true;

	return false;
}

bool CChangeAssemblyDlg::IsPrdEffByCurDate(CaplInstance* rel)
{
	COleDateTime cur_time = COleDateTime::GetCurrentTime();
	cur_time.SetDateTime(cur_time.GetYear(), cur_time.GetMonth(), cur_time.GetDay(), 0, 0, 0);

	return IsPrdEffByDate(rel, cur_time);
}

bool CChangeAssemblyDlg::IsPrdEffBySN(CaplInstance* rel, const TCHAR* sn)
{
	aplExtent eff_ext;

	/*
	CaplAttrValue val[1];
	val[0].attr = m_api->m_prd_mgr.a_pde_usage;
	val[0].value.Set(rel);
	
	apidata.NET_FindInstancesWithAttrValues(m_api->m_prd_mgr.e_pd_eff, 1, &val[0], eff_ext, false);
	*/
	
	CString sn_start, sn_end;
	CString strSN = CString(sn);
	
	int size = 0;
	int i;
	CaplInstance *inst;

	m_api->m_data.GetEntityExtent(m_api->m_prd_mgr.e_pd_eff, eff_ext);

	for (i = 0; i < eff_ext.GetSize(); i++)
	{
		apidata.GetAttr(eff_ext[i], m_api->m_prd_mgr.a_pde_usage, inst);
		if (inst != rel)
			continue;

		if (apidata.IsKindOf(eff_ext[i],m_api->m_prd_mgr.e_sn_eff))
		{
			apidata.GetAttr(eff_ext[i], m_api->m_prd_mgr.a_sn_eff_start, sn_start);
			apidata.GetAttr(eff_ext[i], m_api->m_prd_mgr.a_sn_eff_end, sn_end);

			if (sn_start.IsEmpty())
				return false;

// 			if (sn_start > sn)
// 				return false;
			if (m_api->m_prd_mgr.funcCompareSN == NULL)
				return false;

			if (m_api->m_prd_mgr.funcCompareSN(sn_start, strSN) == 1)
				return false;

			if (sn_end.IsEmpty())
				return true;

// 			if (sn_end >= sn)
// 				return true;
			if (m_api->m_prd_mgr.funcCompareSN(sn_end, strSN) != -1)
				return true;

			size++;
		}
	}

	if (size == 0)
		return true;

	return false;
}

void CChangeAssemblyDlg::OnDestroy() 
{
	int i, k = m_itemsList.GetItemCount();
	for (i = 0; i < k; i++)
	{
		sAssemblyListItem* oldItem = (sAssemblyListItem*)m_itemsList.GetItemData(i);
		if (oldItem != 0)
			delete oldItem;
	}
	
	CResizableDialog::OnDestroy();
}

void CChangeAssemblyDlg::FillWhereUsedList()
{
	m_whereUsedList.SetRedraw(FALSE);
	m_whereUsedList.DeleteAllItems();
	m_whereUsedList.SetRedraw(TRUE);
	
	if (m_assPdf)
	{
		CaplInstance* inst;
		int i;
		int num = 0;
		for (i = 0; i < m_extRels.GetSize(); i++)
		{
			if (m_mode == 2 && !apidata.IsKindOf(m_extRels[i], 
										m_api->m_prd_mgr.e_acu))
				continue;

			apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_pdr_r_ting, inst);

			CString name, buf;
			CaplInstance* prd = NULL;
			apidata.GetAttr(inst, m_api->m_prd_mgr.a_pdf_prd, prd);
			if (prd)
			{
				apidata.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, name);
				apidata.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, buf);
				if (!name.IsEmpty())
					name += _T(":");
				
				name += buf;
			}

			apidata.GetAttr(inst, m_api->m_prd_mgr.a_pdf_id, buf);
			if (!name.IsEmpty())
				name += _T(":");
			
			name += buf;

			// читаем позицию
			apidata.GetAttr(m_extRels[i], m_api->m_prd_mgr.a_pdr_id, buf);
			while (buf.GetLength()<4)
				buf= _T(" ")+buf;			

			if (!name.IsEmpty())
			{
				m_whereUsedList.InsertItem(num, buf, m_api->GetInstIco(inst));
				m_whereUsedList.SetItemText(num, 1, name);
				m_whereUsedList.SetItemData(num, (DWORD)m_extRels[i]);
				num++;
			}
		}

		m_whereUsedList.AutoSizeAllColumns();
	}
}
