// ChangeDlg.cpp : implementation file
//

#include "stdafx.h"
//#include "aplstepmgr.h"
#include "apl_api.h"

#include "ChangeDlg.h"
#include "ChangedStructItem.h"
#include "AssemblyChangeDlg.h"
#include "ChangeDocVerDlg.h"
#include "icons_defines.h"

#include "ChangeAssemblyDlg.h"
#include "ChangeWhereUsed.h"
#include <AplGuiEx.h>

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

/////////////////////////////////////////////////////////////////////////////
// CChangeDlg dialog

 
CChangeDlg::CChangeDlg(CWnd* pParent /*=NULL*/)
	: CResizableDialog(CChangeDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CChangeDlg)
	m_sId = _T("");
	m_sName =  APL_T("");
	m_sDscr = _T("");
	m_sUser = _T("");
	m_sBasis = _T("");
	m_sStock = _T("");
	//}}AFX_DATA_INIT

	m_api = NULL;
	m_change = NULL;
	m_bReadOnly = false;

	m_hLibraryGenII=0;
	m_pGenerateII=0;

	m_bHasDI_iteem=false;

	m_rep_pi=0;

	m_index = -1;
	m_iCurTab = 0;

}


void CChangeDlg::DoDataExchange(CDataExchange* pDX)
{
	CResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CChangeDlg)
	DDX_Control(pDX, IDC_CHS_BASIS, m_basis);
	DDX_Control(pDX, IDC_SELECT_TAB, m_tabCtrl);
	DDX_Control(pDX, IDC_CHS_ITEMS_LIST, m_list);
	DDX_Control(pDX, IDC_CHS_ID, m_idCtrl);
	DDX_Control(pDX, IDC_CHS_NAME, m_nameCtrl);
	DDX_Control(pDX, IDC_CHS_DSCR, m_dscrCtrl);
	DDX_Control(pDX, IDC_CHS_USER, m_userCtrl);
	DDX_Control(pDX, IDOK, m_okBtn);
	DDX_Control(pDX, IDCANCEL, m_cancelBtn);
	DDX_Control(pDX, IDC_CHS_PROP_BUTTON, m_propBtn);
	DDX_Control(pDX, IDC_CHS_DELETE_BUTTON, m_deleteBtn);
	DDX_Control(pDX, IDC_CHS_APPLY_BUTTON, m_applyBtn);
	DDX_Control(pDX, IDC_CHS_ADD_BUTTON, m_addBtn);
	DDX_Control(pDX, IDC_CHN_START_EDIT_BUTTON, m_editBtn);
	DDX_Control(pDX, IDC_CHN_NOTES_BUTTON, m_notesBtn);
	DDX_Control(pDX, ID_CREATE_II, m_create_ii_btn);
	DDX_Control(pDX, IDC_TYPE, m_type_ctrl);
	DDX_Control(pDX, IDC_CHS_STOCK_CEH, m_stock_ceh);
	DDX_Control(pDX, IDC_URGENCY, m_urgency_ctrl);
	DDX_Control(pDX, IDC_ST_NAME, m_st_name);
	DDX_Text(pDX, IDC_CHS_ID, m_sId);
	DDX_Text(pDX, IDC_CHS_NAME, m_sName);
	DDX_Text(pDX, IDC_CHS_DSCR, m_sDscr);
	DDX_Text(pDX, IDC_CHS_USER, m_sUser);

	DDX_Text(pDX, IDC_CHS_BASIS, m_sBasis);
	DDX_Text(pDX, IDC_CHS_STOCK_COMBO, m_sStock);
	DDX_Text(pDX, IDC_CHS_STOCK_CEH, m_sStock_ceh);
	DDX_Text(pDX, IDC_GRP_NUM, m_sGrpNum);
	DDX_Text(pDX, IDC_ORG_CODE, m_sOrgCode);
	DDX_Text(pDX, IDC_DOC_ID, m_sDocId);
	DDX_Text(pDX, IDC_REASON_CODE, m_sBasisCode);
	DDX_Text(pDX, IDC_USAGE, m_sUsage);
	DDX_Text(pDX, IDC_COMPLECT_NUM, m_sComplNum);
	DDX_Text(pDX, IDC_LIST, m_sList);
	DDX_Text(pDX, IDC_CHS_INTRODUCTION, m_sStockIntr);
	DDX_Text(pDX, IDC_TO_DATE, m_sTOdate);
	DDX_Text(pDX, IDC_OTD_DATE, m_sOTDdate);
	DDX_Text(pDX, IDC_CRITICAL_DATE, m_sCritDate);
	DDX_Text(pDX, IDC_SERIA_PRIMEN, m_sSeriaPrimen);
	DDX_Control(pDX, IDC_ISSUE_DATE, m_issue_date_ctrl);
	DDX_Control(pDX, IDC_VALIDITY_PI_DATE, m_validity_pi_date_ctrl);
	DDX_Text(pDX, IDC_ISSUE_DATE, m_sIssue_date);
	DDX_Control(pDX, ID_VIEW_II, m_view_ii_btn);
	DDX_Control(pDX, IDC_CHS_STOCK_COMBO, m_stock_combo);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_ST_SRC_PI, m_st_src_pi);
	DDX_Control(pDX, IDC_SRC_PI, m_src_pi_ctrl);
	DDX_Control(pDX, IDC_GRP_NUM, m_sGrpNumCtrl);
	DDX_Control(pDX, IDC_ORG_CODE, m_sOrgCodeCtrl);
	DDX_Control(pDX, IDC_SERIA_PRIMEN, m_sSeriaPrimenCtrl);
}


BEGIN_MESSAGE_MAP(CChangeDlg, CResizableDialog)
	//{{AFX_MSG_MAP(CChangeDlg)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_CHS_ITEMS_LIST, OnItemchangedChsItemsList)
	ON_BN_CLICKED(IDC_CHS_ADD_BUTTON, OnChsAddButton)
	ON_BN_CLICKED(IDC_CHS_DELETE_BUTTON, OnChsDeleteButton)
	ON_BN_CLICKED(IDC_CHS_PROP_BUTTON, OnChsPropButton)
	ON_BN_CLICKED(IDC_CHS_APPLY_BUTTON, OnChsApplyButton)
	ON_BN_CLICKED(IDC_CHN_START_EDIT_BUTTON, OnBnClickedChnStartEditButton)
	ON_BN_CLICKED(IDC_CHN_NOTES_BUTTON, OnBnClickedChnNotesButton)
	ON_NOTIFY(NM_DBLCLK, IDC_CHS_ITEMS_LIST, OnDblclkChsItemsList)
	ON_NOTIFY(TCN_SELCHANGE, IDC_SELECT_TAB, OnSelchangeSelectTab)

	ON_COMMAND(ID_ASS_CHANGE, OnAddAssemblyChange)
	ON_COMMAND(ID_ASS_CHANGE_GLOBAL, OnAddAssemblyGlobalChange)
	ON_COMMAND(ID_SE_CHANGE, OnAddSEChange)
	//}}AFX_MSG_MAP	
	ON_BN_CLICKED(IDC_CHOOSE_BASIS_CODE, OnBnClickedChooseBasisCode)
	ON_BN_CLICKED(IDC_CHOOSE_USAGE, OnBnClickedChooseUsage)
	ON_BN_CLICKED(IDC_EDIT_SERIA, &CChangeDlg::OnBnClickedEditSeria)
	ON_BN_CLICKED(ID_CREATE_II, &CChangeDlg::OnBnClickedCreateIi)
	ON_CBN_SELCHANGE(IDC_TYPE, &CChangeDlg::OnCbnSelchangeType)
	ON_BN_CLICKED(ID_VIEW_II, &CChangeDlg::OnBnClickedViewIi)
	ON_NOTIFY(NM_RCLICK, IDC_CHS_ITEMS_LIST, &CChangeDlg::OnNMRClickChsItemsList)
	ON_BN_CLICKED(IDC_SEL_ENTERPRISE, &CChangeDlg::OnBnClickedSelEnterprise)
	ON_BN_CLICKED(IDC_SEL_WG, &CChangeDlg::OnBnClickedSelWg)
	ON_BN_CLICKED(IDC_GENERATE_CHANGE_ID, &CChangeDlg::OnBnClickedGenerateChangeId)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChangeDlg message handlers

void CChangeDlg::SetControlsState()
{
	if(0==m_change) return;
	CString sState;

	BOOL bRO=FALSE;

	apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_state, sState);


	if (sState == _T("approving") && m_change->GetAccessmode() <= aplRW) 	m_editBtn.EnableWindow(TRUE);	
	else 	m_editBtn.EnableWindow(FALSE);	

	if (sState != _T("not_applied") || m_change->GetAccessmode() > aplRW)
	{
		m_bReadOnly = true;
		bRO=TRUE;
	}

	BOOL bRO_g0=bRO; //  Код предприятия
	BOOL bRO_g1=bRO; //  Разработчик
	BOOL bRO_g2=bRO; //  ОТД
	BOOL bRO_g3=bRO; //  О180
	BOOL bRO_g4=bRO; //  О103

	// Проверка по ролям только для  ГРПЗ
	if(!m_bReadOnly)
	{
		if(m_api->m_options_mgr.CheckInstallCode(_T("grpz")))
		{
			bRO_g0=TRUE;
			bRO_g1=TRUE;
			bRO_g2=TRUE;
			bRO_g3=TRUE; 
			bRO_g4=TRUE;

			if(m_api->m_appr_mgr.CheckPersonRole(0,APL_NO_T("Разработчик"))) bRO_g1=FALSE;
			if(m_api->m_appr_mgr.CheckPersonRole(0,APL_NO_T("ОТД"))) bRO_g2=FALSE;
			if(m_api->m_appr_mgr.CheckPersonRole(0,APL_NO_T("о. 103"))) bRO_g3=FALSE;
			if(m_api->m_appr_mgr.CheckPersonRole(0,APL_NO_T("ГППП 180"))||
				m_api->m_appr_mgr.CheckPersonRole(0,APL_NO_T("Начальник отдела 180"))) bRO_g4=FALSE;
		}
	}

	m_idCtrl.SetReadOnly(bRO_g1);
	m_type_ctrl.EnableWindow(!bRO_g1);
	m_urgency_ctrl.EnableWindow(!bRO_g1);
	m_nameCtrl.SetReadOnly(bRO_g1);
	m_dscrCtrl.SetReadOnly(bRO_g1);
	m_basis.SetReadOnly(bRO_g1);
	m_stock_combo.EnableWindow(!bRO_g1);
	m_stock_ceh.SetReadOnly(bRO_g1);
	m_okBtn.EnableWindow(!bRO_g1);
	m_issue_date_ctrl.SetReadOnly(bRO_g1);
	m_validity_pi_date_ctrl.EnableWindow(!bRO_g1);

	((CEdit*)GetDlgItem(IDC_ORG_CODE))->SetReadOnly(bRO_g0);
		if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) ((CEdit*)GetDlgItem(IDC_ORG_CODE))->SetReadOnly(TRUE);
	((CEdit*)GetDlgItem(IDC_GRP_NUM))->SetReadOnly(bRO_g1);
	((CEdit*)GetDlgItem(IDC_CHS_ID))->SetReadOnly(bRO_g1);
	((CEdit*)GetDlgItem(IDC_DOC_ID))->SetReadOnly(bRO_g1);
	((CEdit*)GetDlgItem(IDC_CHS_NAME))->SetReadOnly(bRO_g1);
	((CEdit*)GetDlgItem(IDC_REASON_CODE))->SetReadOnly(bRO_g1);
	((CEdit*)GetDlgItem(IDC_CHS_BASIS))->SetReadOnly(bRO_g1); 
	((CEdit*)GetDlgItem(IDC_USAGE))->SetReadOnly(bRO_g1);
	((CEdit*)GetDlgItem(IDC_COMPLECT_NUM))->SetReadOnly(bRO_g4);
	((CEdit*)GetDlgItem(IDC_LIST))->SetReadOnly(bRO_g1);
	GetDlgItem(IDC_CHS_STOCK_COMBO)->EnableWindow(!bRO_g1);
	((CEdit*)GetDlgItem(IDC_CHS_INTRODUCTION))->SetReadOnly(bRO_g1);
	((CEdit*)GetDlgItem(IDC_TO_DATE))->SetReadOnly(bRO_g3);
	((CEdit*)GetDlgItem(IDC_OTD_DATE))->SetReadOnly(bRO_g1);
	((CEdit*)GetDlgItem(IDC_CRITICAL_DATE))->SetReadOnly(bRO_g1);

	GetDlgItem(IDC_GENERATE_CHANGE_ID)->EnableWindow(!bRO_g1);
	GetDlgItem(IDC_CHOOSE_BASIS_CODE)->EnableWindow(!bRO_g1);
	GetDlgItem(IDC_CHOOSE_USAGE)->EnableWindow(!bRO_g1);

	GetDlgItem(IDC_SEL_ENTERPRISE)->EnableWindow(!bRO_g1);
	GetDlgItem(IDC_SEL_WG)->EnableWindow(!bRO_g1);
	GetDlgItem(IDC_EDIT_SERIA)->EnableWindow(!bRO_g1);

	m_addBtn.EnableWindow(!bRO_g1);

	if(sState!=_T("applied"))
	{
		// Запрет на ручную смену состояний у изменений
		int iValue= 0;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Состояния\\Запретить вручную менять состояние изменения"), iValue, 0);
		if(0!=iValue)
		{
			if(!m_api->m_data.IsAdmin())
			{
				m_editBtn.EnableWindow(FALSE);
			}
		}
	}


	if((sState==_T("not_applied") || sState==_T("canceled") || sState==_T("approving")) && m_change->GetAccessmode() < aplRW)
	{
		m_applyBtn.EnableWindow(TRUE);
	}
	else m_applyBtn.EnableWindow(FALSE);

	
	if(sState==_T("not_applied") ) m_create_ii_btn.EnableWindow(TRUE); else m_create_ii_btn.EnableWindow(FALSE);

	//Устанавливаем кнопку "Создать ИИ"

#ifdef _DEBUG
	if(0==m_hLibraryGenII) m_hLibraryGenII = AfxLoadLibrary(_T("MPSpecification_d.dll"));
#else
	if(0==m_hLibraryGenII) m_hLibraryGenII = AfxLoadLibrary(_T("MPSpecification.dll"));
#endif

	if (0!=m_hLibraryGenII)
	{
		//(FARPROC&)m_pGenerateII = GetProcAddress(hLibraryGenII, _T("GetIE"));
		if(0==m_pGenerateII) (FARPROC&)m_pGenerateII = GetProcAddress(m_hLibraryGenII, "GetIE");
	}
	if(0==m_pGenerateII) m_create_ii_btn.ShowWindow(SW_HIDE);
	else 	m_create_ii_btn.ShowWindow(SW_SHOW);

	if(0==m_change) m_view_ii_btn.ShowWindow(SW_HIDE);
	else m_view_ii_btn.ShowWindow(SW_SHOW);

	if(m_bHasDI_iteem)m_addBtn.EnableWindow(FALSE);

	if(0!=m_rep_pi) m_type_ctrl.EnableWindow(FALSE);

};

//CaplToolTip CChangeDlg_tooltip;
static WNDPROC CChangeDlg_DefListFunction=0; 

CListCtrl *CChangeDlg_List=0;
HWND CChangeDlg_List_hwnd=0;

CaplToolTip CChangeDlg::st_tooltip;

LRESULT CChangeDlg_List_Proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
/*	if(uMsg>WM_MOUSEFIRST  && uMsg<WM_PARENTNOTIFY)
	{
		CChangeDlg::st_tooltip.Hide();
	}
	if(uMsg==WM_LBUTTONDOWN && hwnd!=0)
	{
		POINT point;
		point.x = GET_X_LPARAM(lParam); 
		point.y = GET_Y_LPARAM(lParam);
		ClientToScreen(hwnd,&point);

		CChangeDlg::st_tooltip.Show(point.x+10,point.y+10,_T("AAAA"));
	}
	*/

	static bool b=false;

	if(uMsg==WM_MOUSEMOVE && hwnd!=0 && CChangeDlg_List_hwnd==hwnd)
	{
		POINT point;
		point.x = GET_X_LPARAM(lParam); 
		point.y = GET_Y_LPARAM(lParam);

		static CPoint prev_point(0,0);
		if(prev_point!=point)
		{
			prev_point=point;
			CChangeDlg::st_tooltip.Hide();
		}

		LVHITTESTINFO HitTestInfo;
		HitTestInfo.pt=point;
		HitTestInfo.flags=0;//LVHT_ONITEMLABEL|LVHT_ONITEMICON;
		HitTestInfo.iItem=-1;
		HitTestInfo.iSubItem=-1;
		CChangeDlg_List->SubItemHitTest(&HitTestInfo); 
		if(HitTestInfo.iItem>=0 && HitTestInfo.iSubItem>=0)
		{
			CString text;
			text=CChangeDlg_List->GetItemText(HitTestInfo.iItem,HitTestInfo.iSubItem);
			if(text!=_T(""))
			{
				ClientToScreen(hwnd,&point);
				CChangeDlg::st_tooltip.Show(point.x+15,point.y+15,text);
				b=true;
			}
		}
	}
	//else if(uMsg>WM_MOUSEFIRST  && uMsg<WM_PARENTNOTIFY)
	else if(uMsg!=WM_NCHITTEST && uMsg!=WM_SETCURSOR && uMsg!=WM_NOTIFY && uMsg<3000)
	{
		if(b)
			b=false;
		CChangeDlg::st_tooltip.Hide();
	}

	LRESULT rez=CallWindowProc(CChangeDlg_DefListFunction, hwnd, uMsg, wParam, lParam);

	//else CChangeDlg_tooltip.Hide();
	return rez;
}


BOOL CChangeDlg::OnInitDialog() 
{
	CResizableDialog::OnInitDialog();
	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
		
	m_imageList.Create(IDR_NAVIGATOR_ICON, 20, 11, RGB(255, 0, 255));
	m_list.SetImageList(&m_imageList, LVSIL_SMALL);
	
	CChangeDlg_List=&m_list;
	CChangeDlg_List_hwnd=m_list.m_hWnd;

	LOGFONT logfont;
	CFont *pFont=m_list.GetFont();
	pFont->GetLogFont( &logfont );
	//logfont.lfWeight = 700;
	logfont.lfHeight*=2;
	logfont.lfQuality=CLEARTYPE_QUALITY;
	CString fontname=_T("Tahoma");
	int i9; for(i9=0;i9<=fontname.GetLength();i9++)logfont.lfFaceName[i9]=fontname[i9];
	m_tooltip_font.CreateFontIndirect( &logfont );
	st_tooltip.m_pFont=&m_tooltip_font;


	CChangeDlg_DefListFunction=(WNDPROC)SetWindowLong(m_list.m_hWnd, GWL_WNDPROC, (long) (&(CChangeDlg_List_Proc)));

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

	m_addBtn.SetIcon(aplGetButtonIco(APL_24_PLUS));
	m_addBtn.SetFlat(FALSE);
	m_deleteBtn.SetIcon(aplGetButtonIco(APL_24_DELETE));
	m_deleteBtn.SetFlat(FALSE);
	m_propBtn.SetIcon(aplGetButtonIco(APL_24_PROPERTIES));
	m_propBtn.SetFlat(FALSE);

	m_editBtn.SetFlat(FALSE);
	m_applyBtn.SetIcon(GetAplStdIco16(APLSTDICO_PLAY));
	m_applyBtn.SetFlat(FALSE);
	m_notesBtn.SetIcon(TabCtrlImageList.ExtractIcon(13));
	m_notesBtn.SetFlat(FALSE);
	m_create_ii_btn.SetIcon(GetAplStdIco16(APLSTDICO_NEW_SECTION));
	m_create_ii_btn.SetFlat(FALSE);

	m_view_ii_btn.SetIcon(GetAplTableIco(APL_TABLE_VIEW));
	m_view_ii_btn.SetFlat(FALSE);

	COleDateTime odt;
	odt.SetStatus(COleDateTime::null);
	m_validity_pi_date_ctrl.SetTime(odt);
	
	AddAnchor(IDC_CHS_ITEMS_LIST,TOP_LEFT, BOTTOM_RIGHT);
	
	AddAnchor(IDC_CHS_DELETE_BUTTON,TOP_RIGHT);
	AddAnchor(IDC_CHS_ADD_BUTTON,TOP_RIGHT);	
	AddAnchor(IDC_CHS_PROP_BUTTON,TOP_RIGHT);
	AddAnchor(IDC_CHS_APPLY_BUTTON,TOP_RIGHT);
	
	AddAnchor(IDC_CHS_ID,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_CHS_NAME,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_CHS_BASIS,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_CHS_STOCK_COMBO,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_CHS_USER,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_CHS_FRM_STATIC,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_SELECT_TAB,TOP_LEFT, TOP_RIGHT);

	AddAnchor(IDC_CHS_DSCR, BOTTOM_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_CHS_NOTE_STATIC, BOTTOM_LEFT);
	
	AddAnchor(IDC_CHN_NOTES_BUTTON, TOP_RIGHT);
	AddAnchor(IDC_CHN_START_EDIT_BUTTON, TOP_RIGHT);
	
	AddAnchor(IDOK,BOTTOM_RIGHT);	
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);	
	AddAnchor(ID_CREATE_II,BOTTOM_LEFT);	
	
	m_list.SetExtendedStyle(m_list.GetExtendedStyle()|LVS_EX_FULLROWSELECT|
		LVS_EX_SUBITEMIMAGES | LVS_EX_GRIDLINES);
	
	int i= -1;

	m_type_ctrl.AddString(_T(""));
	m_type_ctrl.AddString(APL_T("ИИ"));
	m_type_ctrl.AddString(APL_T("ПИ"));
	m_type_ctrl.AddString(APL_T("ДИ"));
	m_type_ctrl.AddString(APL_T("ДПИ"));

	CString buf;

	bool b_stock_combo_loaded=false;
	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Изменения\\Справочник указаний о заделе"),buf,0);
	if(buf!=_T(""))
	{
		CaplInstance *system = m_api->m_classifier_mgr.GetClassifierSystemById(buf,true);
		if(0==system) 
			AfxMessageBox(APL_T("Не найден справочник указанный в настройке:\n 'Изменения\\Справочник указаний о заделе'!!!"));
		else
		{
			b_stock_combo_loaded=true;
			int i;
			aplExtent ext_levels;
			m_api->m_classifier_mgr.LoadSubClassifierLevels(system,ext_levels,true,true);

			for(i=0;i<ext_levels.GetSize();i++)
			{
				CaplInstance *level=ext_levels[i];
				if(0==level) continue;
				if(level->IsDeleted() || level->GetAccessmode()>aplRO) continue;
				m_api->m_data.GetAttr(level,m_api->m_classifier_mgr.a_apl_classifier_level_name,buf);
				if(buf!=_T("")) m_stock_combo.AddString(buf);
			}
		}
	}

	if(!b_stock_combo_loaded)
	{
		m_stock_combo.AddString(APL_T("задел использовать"));
		m_stock_combo.AddString(APL_T("не отражается"));
		m_stock_combo.AddString(APL_T("задела нет"));
		m_stock_combo.AddString(APL_T("в заделе учтено"));
		m_stock_combo.AddString(APL_T("доработать"));
	}


	if(m_api->m_options_mgr.CheckInstallCode(_T("grpz")))
	{
		m_st_name.SetWindowText(APL_T("Основание:"));
		m_urgency_ctrl.EnableWindow(FALSE);

		CWnd *wnd;
		wnd=GetDlgItem(IDC_SERIA_PRIMEN);  if(0!=wnd)wnd->ShowWindow(SW_HIDE);
		wnd=GetDlgItem(IDC_STATIC_SERIA_PRIMEN);  if(0!=wnd)wnd->ShowWindow(SW_HIDE);
		wnd=GetDlgItem(IDC_OTD_DATE);  if(0!=wnd)wnd->ShowWindow(SW_HIDE);
		wnd=GetDlgItem(IDC_STATIC_OTD_DATE);  if(0!=wnd)wnd->ShowWindow(SW_HIDE);
		wnd=GetDlgItem(IDC_EDIT_SERIA);  if(0!=wnd)wnd->ShowWindow(SW_HIDE);
		wnd=GetDlgItem(IDC_TO_DATE); 
		if(0!=wnd)
		{
			RECT rect;
			wnd->GetWindowRect(&rect);
			ScreenToClient(&rect);
			rect.right+=150;
			wnd->MoveWindow(&rect);
		}
	}
	else if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) 
	{
		CWnd *wnd;
		wnd=GetDlgItem(IDC_STATIC_SERIA_PRIMEN);  if(0!=wnd)wnd->SetWindowText(APL_T("Зависимые изделия:"));
	}
	
//	m_tabCtrl.SetImageList(aplGetInstImageList());

	// добавляем закладки
	m_tabCtrl.InsertItem(++i,  APL_T(" Изделия "), ICON_ASSEMBLY);
	m_tabCtrl.InsertItem(++i,  APL_T(" Материалы "), ICON_MATERIAL);
	m_tabCtrl.InsertItem(++i,  APL_T(" Документы "), ICON_DOCUMENT);
	m_tabCtrl.InsertItem(++i,  APL_T(" Бизнес-процессы "), ICON_BP);
	m_tabCtrl.InsertItem(++i,  APL_T(" Характеристики "), ICON_CHARACTERISTIC);


	CString sState= _T("not_applied");
	CaplAggr aggr;
	CaplInstance *ciOrganization = NULL, *ciTopOrg = NULL;
	CaplInstance *ciPerson=0;
	
	if (m_api && apidata.IsConnected())
	{	
		ciPerson= apidata.GetCurrUser();

		LoadChangeReasonSprav();
		if (m_change)
		{
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_id, m_sId);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_name, m_sName);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_dscr, m_sDscr);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_basis, m_sBasis);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_stock, m_sStock); 
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_stock_ceh, m_sStock_ceh);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_state, sState);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_urgency, m_sUrgency);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_issue_date, m_sIssue_date);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_validity_pi_date, m_sValidity_pi_date);


			COleDateTime odt;
			if(m_sValidity_pi_date!=_T(""))aplString2Date(m_sValidity_pi_date,odt);
			else odt.SetStatus(COleDateTime::null);
			m_validity_pi_date_ctrl.SetTime(odt);


			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_validity_pi_date_actual, buf);
			if(buf!=_T(""))
			{
				COleDateTime odt;
				aplString2Date(buf,odt);
				m_validity_pi_date_ctrl.SetTime(odt); 
				m_validity_pi_date_ctrl.EnableWindow(FALSE);
			}

			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_type, m_sType);
			int i=m_type_ctrl.FindString(0,m_sType);
			if(i<0) i=m_type_ctrl.AddString(m_sType);
			m_type_ctrl.SetCurSel(i);

			if(m_sType==APL_T("ПИ") || m_sType==APL_T("ДПИ")) m_validity_pi_date_ctrl.EnableWindow(TRUE);
			else m_validity_pi_date_ctrl.EnableWindow(FALSE);

			if(m_sType==APL_T("ПИ") || m_sType==APL_T("ДПИ")) m_st_src_pi.SetWindowText(APL_T("Погашающее ИИ:"));
			else m_st_src_pi.SetWindowText(APL_T("Погашаемое ПИ:"));

			
			CString sSrcPiId;
			if(m_sType==APL_T("ПИ") || m_sType==APL_T("ДПИ"))  m_rep_pi=m_api->m_change_mgr.FindRepaymentChange(m_change);
			else  apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_src_pi, m_rep_pi);
			if(0!=m_rep_pi)
			{
				 m_api->m_change_mgr.LoadChangeInfo(m_rep_pi);
				apidata.GetAttr(m_rep_pi, m_api->m_change_mgr.a_chng_id, buf);
				m_src_pi_ctrl.SetWindowText(buf);
			}

			m_urgency_ctrl.SetWindowText(m_sUrgency);

			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_org_code, m_sOrgCode);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_grp_num, m_sGrpNum);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_doc_id, m_sDocId);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_basis_code, m_sBasisCode);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_usage, m_sUsage);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_complect_num, m_sComplNum);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_list, m_sList);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_stock_introd, m_sStockIntr);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_to_date, m_sTOdate);
			if(m_api->m_options_mgr.CheckInstallCode(_T("grpz")))m_sTOdate.Replace(_T("\n"),_T(" / "));
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_otd_date, m_sOTDdate);
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_critical_date, m_sCritDate);
				
			m_sUser=_T("");
			if(sState == _T("not_applied"))		m_sUser	=APL_T("В разработке");
			else if(sState == _T("approving")) m_sUser	=APL_T("На согласовании");
			else if(sState == _T("canceled"))  m_sUser	=APL_T("Отменено");
			else if(sState == _T("applied"))
			{
				apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_apply_date, buf);
				if (buf!=_T(""))
				{
					COleDateTime odt;
					aplString2Date(buf, odt);
					m_sUser=odt.Format(APL_T("Проведено %d:%m:%Y %H:%M:%S"));
				}

				apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_autor, ciPerson);
				if(ciPerson)
				{
					m_api->m_appr_mgr.GetPersonName(ciPerson, buf); 
					m_sUser+=_T("  "); m_sUser+=buf;
				}

				apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_user, buf);
				if(buf!=_T("")){m_sUser +=_T(" ["); m_sUser+=buf; m_sUser +=_T("]");}
			}

			if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) 
			{
				apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_dependent_items, m_dependent_items);
				CString buf;
				m_api->GetItemsName(m_dependent_items,buf);
				m_sSeriaPrimenCtrl.SetWindowText(buf);
				m_sSeriaPrimen=buf;

			}
			else
			{
				// серия применения (правило применяемости)
				apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_start_num, m_sSeriaPrimenStart);
				apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_end_num, m_sSeriaPrimenEnd);
				apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_eff_type, m_sEffType);
				GetEffectivityDscr();
			}
			
			aplExtent ext;
			apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_items, ext);

			for (int i = 0; i < ext.GetSize(); i++) 
			{
				if (ext[i] == NULL)
					continue;

				if (ext[i]->GetType() == NULL)
					continue;
				
				// добавляем материалы
				if (m_api->m_data.IsKindOf(ext[i], m_api->m_change_mgr.e_mat))
					m_maters.Add(ext[i]);
				// изделия
				else if(apidata.IsKindOf(ext[i], m_api->m_change_mgr.e_psc))
					m_items.Add(ext[i]);
				// документы
				else if(apidata.IsKindOf(ext[i], m_api->m_change_mgr.e_avc))
					m_docs.Add(ext[i]);
				// бизнесс-процессы
				else if(apidata.IsKindOf(ext[i], m_api->m_change_mgr.e_abpc))
					m_bps.Add(ext[i]);
				// хар-ки
				else if (apidata.IsKindOf(ext[i], m_api->m_change_mgr.e_char_change))
					m_chars.Add(ext[i]);
				// нечто иное, что неизвестно, да и не важно
				else
					m_others.Add(ext[i]);
			}



			SetControlsState();
		}
		else	// формируем ID для изменения
		{
			if(m_sId==_T(""))  
			{
				if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) m_sId=APL_T("<Автономер>");
				else m_api->m_change_mgr.GenerateChangeId(m_sId);
				
				/*Контролы*/
				m_notesBtn.EnableWindow(FALSE);

				/* Заполняем дополнительные поля: Код предприятия, Номер подразделения */
				{
					m_sOrgCode=_T("");
					m_sGrpNum=_T("");
					CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0
					if(0!=app)
					{
						m_sOrgCode	= app->GetProfileString(_T("Settings"), _T("Organization Code"), _T(""));
						m_sGrpNum	= app->GetProfileString(_T("Settings"), _T("Group Num"), _T(""));
					}

					if(m_api->m_options_mgr.CheckInstallCode(_T("grpz"))) m_sOrgCode=_T("");
					else if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) {m_sOrgCode=_T(""); m_sGrpNum=_T("");}
				}	
			}

			m_sType=APL_T("ИИ");
			int i=m_type_ctrl.FindString(0,m_sType);
			if(i<0) i=m_type_ctrl.AddString(m_sType);
			m_type_ctrl.SetCurSel(i);
			OnCbnSelchangeType();

			m_urgency_ctrl.SetWindowText(m_sUrgency);

		}	
	}


	ShowChangedItems();	
	UpdateData(FALSE);

	ShowSizeGrip(FALSE);

	if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) ((CEdit*)GetDlgItem(IDC_ORG_CODE))->SetReadOnly(TRUE);

#ifdef _MOMA_
	m_create_ii_btn.EnableWindow(FALSE); m_create_ii_btn.ShowWindow(SW_HIDE);
	m_view_ii_btn.EnableWindow(FALSE); m_view_ii_btn.ShowWindow(SW_HIDE);
#endif

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

void CChangeDlg::LoadChangeReasonSprav()
{
	// Загружаем справочники причин изменений
	CString sSql, t_str;
	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Справочник причин изменений"), t_str, _T(""));

	CaplInstance *cit = NULL;
	if(!t_str.IsEmpty()) cit = m_api->m_classifier_mgr.GetClassifierSystemById(t_str, true);

	if(cit) m_aeSpravExt.Add(cit);
	else
	{
		sSql = _T("SELECT Ext_1 FROM Ext_1 { apl_classifier_system.id LIKE '' } END_SELECT");
		if(m_api->m_data.NET_QueryEditParse(sSql, false, &t_str) == false) return;
		m_api->m_data.NET_QueryExecute(m_aeSpravExt);		
	}

	m_api->LoadExtentInfo(m_aeSpravExt);
}

CaplInstance* CChangeDlg::GetTopOrganization(CaplInstance *ciOrganization)
{
	aplExtent aeExt;
	CaplAttrValue val;

	val.attr = m_api->m_appr_mgr.a_org_rel_related;
	val.value.Set(ciOrganization);

	m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_appr_mgr.e_org_rel, 1 ,&val, aeExt, false);
	if(aeExt.Size == 0) return ciOrganization;

	return GetTopOrganization(aeExt[0]);
}

bool CChangeDlg::SaveInOk() 
{
	if(m_bReadOnly) return true;

	UpdateData();
	m_sId.TrimRight();
	m_sId.TrimLeft();
	UpdateData(FALSE);

	int i;
	CString sType;
	m_type_ctrl.GetWindowText(sType);
	m_urgency_ctrl.GetWindowText(m_sUrgency);


	if(m_sId==_T("") || m_sId==APL_T("<Автономер>")) 
	{
		if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие")))
		{
			m_api->m_change_mgr.GenerateChangeId(m_sId);
			m_idCtrl.SetWindowText(m_sId);
		}
	}

	if(m_sId.IsEmpty())
	{
		AfxMessageBox( APL_T("Не задано поле \"Обозначение\"."), MB_ICONERROR|MB_OK);
		return false;
	}

	COleDateTime odt;
	m_validity_pi_date_ctrl.GetTime(odt);
	if(odt.GetStatus()==COleDateTime::null)m_sValidity_pi_date=_T("");
	else
	{
		CString buf;
		aplDate2String(odt,buf);
		m_sValidity_pi_date=buf.Left(8);
		m_sValidity_pi_date+=_T("235959");
	}
	
	CaplAttrValue find_values[3];
	find_values[0].value.Set(m_sId);
	find_values[0].attr= m_api->m_change_mgr.a_chng_id;

	if(!apidata.NET_TestUniqueAttrValues(m_api->m_change_mgr.e_chng, m_change, 1, find_values, false))
	{
		AfxMessageBox( APL_T("Изменение с таким обозначением уже существует."),	MB_OK|MB_ICONSTOP);
		return  false;		
	}
	
//	if(m_sName.IsEmpty())
//	{
//		MessageBox(APL_T("Не задано поле \"Наименование\"."), APL_T("Ошибка"), MB_ICONERROR|MB_OK);
//		return;
//	}

	bool bSave = false;

	bool bModyfied= (m_del_items.GetSize()||m_new_items.GetSize()||
		m_del_docs.GetSize()||m_new_docs.GetSize()||
		m_del_bps.GetSize()||m_new_bps.GetSize()||
		m_del_chars.GetSize()||m_new_chars.GetSize()||
		m_del_maters.GetSize()||m_new_maters.GetSize())?true:false;
	
	for (i = 0; i < m_del_items.GetSize(); i++)
	{
		bSave= true;
		m_items.Remove(m_items.Find(m_del_items[i]));
		apidata.DeleteInstance(m_del_items[i]);
	}

	for (i = 0; i < m_new_items.GetSize(); i++)
	{
		bSave= true;		
		CaplInstance* newItem= NULL;
/*		find_values[0].value.Set(m_new_items[i].m_sId);
		find_values[0].attr= m_api->m_change_mgr.a_psc_id;
		if(!apidata.NET_TestUniqueAttrValues(m_api->m_change_mgr.e_chng_item, newItem, 1, find_values, false))
		{
			MessageBox(APL_T("Обозначение изменения: ")+m_new_items[i].m_sId+
				APL_T("\n\nИзменение с таким обозначением уже существует."), 
				APL_T("Проверка параметров"),
				MB_OK);
			if(bSave)apidata.NET_SaveChanges();
			return;		
		}*/
		
		newItem= apidata.CreateInstance(m_api->m_change_mgr.e_psc);
		if (newItem)
		{
			if(m_new_items[i].m_sId.IsEmpty())
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_api->m_change_mgr.GetPSCId(m_new_items[i].m_pdr));
			else
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_new_items[i].m_sId);				
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_name, m_new_items[i].m_sName);				
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_dscr, m_new_items[i].m_sDscr);				
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_basis, m_new_items[i].m_sBasis);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_stock, m_new_items[i].m_sStock);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_changed_product, m_new_items[i].m_pdr);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_eff_type, m_new_items[i].m_sEffType);
			if(m_new_items[i].m_sEffType==_T("dated"))
			{
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_start_date, m_new_items[i].m_sStartCond);
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_end_date, m_new_items[i].m_sEndCond);
			}
			else if(m_new_items[i].m_sEffType==_T("numbered"))
			{
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_start_num, m_new_items[i].m_sStartCond);
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_end_num, m_new_items[i].m_sEndCond);				
			}
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_changing_product, m_new_items[i].m_pdf);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_value, m_new_items[i].m_value);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_unit, m_new_items[i].m_unit);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_position, m_new_items[i].m_sPosition);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_position_num, m_new_items[i].m_sPositionNum);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_frames_of_reference, m_new_items[i].m_contexts);

			m_items.Add(newItem);
			m_new_items.RemoveAt(i); i--;
		}
	}
	
	for (i = 0; i<m_del_docs.GetSize(); i++)
	{
		bSave= true;
		m_docs.Remove(m_docs.Find(m_del_docs[i]));
		CaplAggr aggr;
		apidata.GetAttr(m_del_docs[i], m_api->m_change_mgr.a_chng_item_attachment, aggr);
		for(int l= 0; l<aggr.GetSize(); l++)
		{
			CaplInstance* blob= NULL;
			aggr.GetByIndex(l, blob);
			if(blob)
			{
				apidata.NET_DeleteBlob(blob, m_api->m_doc_mgr.a_apl_stored_document_source);
				apidata.DeleteInstance(blob);
			}
			bSave= true;
		}
		apidata.DeleteInstance(m_del_docs[i]);
		bSave= true;
	}
	
	for (i = 0; i<m_new_docs.GetSize(); i++)
	{
		bSave = true;
		CaplInstance* newItem= apidata.CreateInstance(m_api->m_change_mgr.e_avc);
		if(newItem)
		{
			if(m_new_docs[i].m_sId.IsEmpty())
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_api->m_change_mgr.GetAVCId(m_new_docs[i].m_newVer));
			else 
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_new_docs[i].m_sId);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_dscr, m_new_docs[i].m_sDscr);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_notes, m_new_docs[i].m_sNotes);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_basis, m_new_docs[i].m_sBasis);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_stock, m_new_docs[i].m_sStock);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_replace_state, m_new_docs[i].m_sNewState);
			
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_avc_new_rev, m_new_docs[i].m_newVer);
			CaplInstance* doc= NULL;
			if(0!=m_new_docs[i].m_newVer)
				apidata.GetAttr(m_new_docs[i].m_newVer, m_api->m_doc_mgr.a_apl_doc_rev_doc, doc);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_avc_doc, doc);

			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_attachment, m_new_docs[i].m_attachment);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_accept_date, m_new_docs[i].m_sDate);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_user, m_new_docs[i].m_sUser);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_autor, m_new_docs[i].m_person);

			apidata.PutAttr(newItem, m_api->m_change_mgr.a_avc_method, m_new_docs[i].m_sMethod);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_avc_items_for_add_relation, m_new_docs[i].m_ext4AddToItem);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_avc_items_for_del_relation, m_new_docs[i].m_ext4DelFromItem);
		}
		m_docs.Add(newItem);
		m_new_docs.RemoveAt(i); i--;
	}
	
	for (i = 0; i<m_del_bps.GetSize(); i++)
	{
		bSave= true;
		m_bps.Remove(m_bps.Find(m_del_bps[i]));
		
		aplExtent aggr;
		apidata.GetAttr(m_del_bps[i], m_api->m_change_mgr.a_chng_item_attachment, aggr);
		for(int l= 0; l<aggr.GetSize(); l++)
		{
			apidata.NET_DeleteBlob(aggr[l], m_api->m_doc_mgr.a_apl_stored_document_source);
			apidata.DeleteInstance(aggr[l]);
			bSave= true;
		}
		
		apidata.DeleteInstance(m_del_bps[i]);
		bSave= true;
	}
	
	for (i = 0; i<m_new_bps.GetSize(); i++)
	{
		bSave= true;
		CaplInstance* newItem= apidata.CreateInstance(m_api->m_change_mgr.e_abpc);
		if(newItem)
		{
			if(m_new_bps[i].m_sId.IsEmpty())
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_api->m_change_mgr.GetBPCId(m_new_bps[i].m_newVer));
			else 
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_new_bps[i].m_sId);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_dscr, m_new_bps[i].m_sDscr);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_notes, m_new_bps[i].m_sNotes);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_basis, m_new_bps[i].m_sBasis);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_stock, m_new_bps[i].m_sStock);
			
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_abpc_new_rev, m_new_bps[i].m_newVer);
			CaplInstance* bp= NULL;
			apidata.GetAttr(m_new_bps[i].m_newVer, m_api->m_bp_mgr.a_bp_ver_bp, bp);
			
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_abpc_bp, bp);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_attachment, m_new_bps[i].m_attachment);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_accept_date, m_new_bps[i].m_sDate);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_user, m_new_bps[i].m_sUser);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_autor, m_new_bps[i].m_person);
		}
		m_bps.Add(newItem);
		m_new_bps.RemoveAt(i); i--;
	}

	for (i = 0; i < m_del_chars.GetSize(); i++)
	{
		bSave = true;
		m_chars.Remove(m_chars.Find(m_del_chars[i]));

		aplExtent aggr;

		apidata.GetAttr(m_del_chars[i], m_api->m_change_mgr.a_chng_item_attachment, aggr);
		for (int l = 0; l < aggr.GetSize(); l++)
		{
			apidata.NET_DeleteBlob(aggr[l], m_api->m_doc_mgr.a_apl_stored_document_source);
			apidata.DeleteInstance(aggr[i]);
			bSave= true;
		}

		apidata.DeleteInstance(m_del_chars[i]);
		bSave= true;
	}

	for (i = 0; i < m_new_chars.GetSize(); i++)
	{
		bSave = true;
		CaplInstance* newItem = apidata.CreateInstance(m_api->m_change_mgr.e_char_change);
		if (newItem)
		{
			if (m_new_chars[i].m_sId.IsEmpty())
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_api->m_change_mgr.GetCHCId(m_new_chars[i].m_newVer));
			else 
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_new_chars[i].m_sId);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_dscr, m_new_chars[i].m_sDscr);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_notes, m_new_chars[i].m_sNotes);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_basis, m_new_chars[i].m_sBasis);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_stock, m_new_chars[i].m_sStock);
			
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_char_change_new_rev, m_new_chars[i].m_newVer);
			CaplInstance* charact = NULL;
			apidata.GetAttr(m_new_chars[i].m_newVer, m_api->m_charact_mgr.a_apl_charact_val_ver_char_value, charact);
			
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_char_change_val, charact);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_attachment, m_new_chars[i].m_attachment);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_accept_date, m_new_chars[i].m_sDate);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_user, m_new_chars[i].m_sUser);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_autor, m_new_chars[i].m_person);

		}
		m_chars.Add(newItem);
		m_new_chars.RemoveAt(i); i--;

	}

	for (i = 0; i < m_del_maters.GetSize(); i++)
	{
		bSave = true;
		m_items.Remove(m_maters.Find(m_del_maters[i]));
		apidata.DeleteInstance(m_del_maters[i]);
	}

	for (i = 0; i < m_new_maters.GetSize(); i++)
	{
		bSave = true;		
		CaplInstance* newItem= NULL;
		
		newItem= apidata.CreateInstance(m_api->m_change_mgr.e_mat);
		if(newItem)
		{
			if(m_new_maters[i].m_sId.IsEmpty())
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_api->m_change_mgr.GetMFCId(m_new_maters[i].m_pdr));
			else
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_id, m_new_maters[i].m_sId);				
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_basis, m_new_maters[i].m_sBasis);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_chng_item_stock, m_new_maters[i].m_sStock);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_changed_product, m_new_maters[i].m_pdr);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_eff_type, m_new_maters[i].m_sEffType);
			if(m_new_maters[i].m_sEffType==_T("dated"))
			{
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_start_date, m_new_maters[i].m_sStartCond);
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_end_date, m_new_maters[i].m_sEndCond);
			}
			else if(m_new_maters[i].m_sEffType==_T("numbered"))
			{
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_start_num, m_new_maters[i].m_sStartCond);
				apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_end_num, m_new_maters[i].m_sEndCond);				
			}
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_changing_product, m_new_maters[i].m_pdf);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_value, m_new_maters[i].m_value);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_psc_unit, m_new_maters[i].m_unit);

			apidata.PutAttr(newItem, m_api->m_change_mgr.a_mat_renking, m_new_maters[i].m_prior);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_mat_der_value, m_new_maters[i].m_der_value);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_mat_der_unit, m_new_maters[i].m_der_unit);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_mat_assort, m_new_maters[i].m_sort);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_mat_size, m_new_maters[i].m_razmer);
			apidata.PutAttr(newItem, m_api->m_change_mgr.a_mat_requir, m_new_maters[i].m_tehTreb);

			m_maters.Add(newItem);
			m_new_maters.RemoveAt(i); i--;
		}
	}
	
	if (m_change)
	{
		bSave = true;
		CString sBuf;
		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_id, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_id, m_sId);
		bModyfied|= (sBuf!=m_sId);

		if(sBuf!=m_sId) // Надо поменять обозначение в документе
		{
			int iValue=0;
			m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Изменения\\Запретить изменение обозначения ИИ при изменении обозначения пакета изменений"), iValue, 0);

			if(0==iValue)
			{
				CaplInstance *inst_doc_ii=0;
				m_api->m_data.GetAttr(m_change, m_api->m_change_mgr.a_chng_notice, inst_doc_ii);
				if(0==inst_doc_ii) inst_doc_ii=m_api->m_doc_mgr.FindDocById(sBuf);

				if(0!=inst_doc_ii)
				{
					CaplAdminModeProvider adminmode(&(m_api->m_data),-1, -1,DEF_SOURCE);
					m_api->m_data.PutAttr(inst_doc_ii, m_api->m_doc_mgr.a_doc_id, m_sId);
					m_api->m_data.PutAttr(inst_doc_ii, m_api->m_doc_mgr.a_doc_src_item,m_change);
					m_api->m_data.PutAttr(m_change, m_api->m_change_mgr.a_chng_notice, inst_doc_ii);
				}
			}
		}

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_type, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_type, sType);
		bModyfied|= (sBuf!=sType);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_urgency, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_urgency, m_sUrgency);
		bModyfied|= (sBuf!=m_sUrgency);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_issue_date, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_issue_date, m_sIssue_date);
		bModyfied|= (sBuf!=m_sIssue_date);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_validity_pi_date, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_validity_pi_date, m_sValidity_pi_date);
		bModyfied|= (sBuf!=m_sValidity_pi_date);


		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_name, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_name, m_sName);
		bModyfied|= (sBuf!=m_sName);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_dscr, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_dscr, m_sDscr);
		bModyfied|= (sBuf!=m_sDscr);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_basis, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_basis, m_sBasis);
		bModyfied|= (sBuf!=m_sBasis);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_stock, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_stock, m_sStock);
		bModyfied|= (sBuf!=m_sStock);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_stock_ceh, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_stock_ceh, m_sStock_ceh);
		bModyfied|= (sBuf!=m_sStock_ceh);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_org_code, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_org_code, m_sOrgCode);
		bModyfied|= (sBuf!=m_sOrgCode);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_grp_num, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_grp_num, m_sGrpNum);
		bModyfied|= (sBuf!=m_sGrpNum);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_doc_id, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_doc_id, m_sDocId);
		bModyfied|= (sBuf!=m_sDocId);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_basis_code, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_basis_code, m_sBasisCode);
		bModyfied|= (sBuf!=m_sBasisCode);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_usage, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_usage, m_sUsage);
		bModyfied|= (sBuf!=m_sUsage);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_complect_num, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_complect_num, m_sComplNum);
		bModyfied|= (sBuf!=m_sComplNum);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_list, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_list, m_sList);
		bModyfied|= (sBuf!=m_sList);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_stock_introd, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_stock_introd, m_sStockIntr);
		bModyfied|= (sBuf!=m_sStockIntr);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_to_date, sBuf);
		if(m_api->m_options_mgr.CheckInstallCode(_T("grpz"))) m_sTOdate.Replace(_T(" / "),_T("\n"));
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_to_date, m_sTOdate);
		bModyfied|= (sBuf!=m_sTOdate);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_otd_date, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_otd_date, m_sOTDdate);
		bModyfied|= (sBuf!=m_sOTDdate);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_critical_date, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_critical_date, m_sCritDate);
		bModyfied|= (sBuf!=m_sCritDate);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_start_num, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_start_num, m_sSeriaPrimenStart);
		bModyfied|= (sBuf!=m_sSeriaPrimenStart);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_end_num, sBuf);
		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_end_num, m_sSeriaPrimenEnd);
		bModyfied|= (sBuf!=m_sSeriaPrimenEnd);

		apidata.GetAttr(m_change, m_api->m_change_mgr.a_chng_eff_type, sBuf);
		m_api->m_data.PutAttr(m_change, m_api->m_change_mgr.a_chng_eff_type, m_sEffType);
		bModyfied|= (sBuf!=m_sEffType);

		CaplAggr aggr;
		for (i = 0; i < m_items.GetSize(); i++) 
		{
			if (!m_items[i])
				continue;
			apidata.PutAttr(m_items[i], m_api->m_change_mgr.a_chng_item_of_chng, m_change);
			aggr.Add(m_items[i]);
		}
		for (i = 0; i < m_docs.GetSize(); i++)
		{
			if (!m_docs[i])
				continue;
			apidata.PutAttr(m_docs[i], m_api->m_change_mgr.a_chng_item_of_chng, m_change);
			aggr.Add(m_docs[i]);
		}
		for (i = 0; i < m_bps.GetSize(); i++)
		{
			if (!m_bps[i])
				continue;
			apidata.PutAttr(m_bps[i], m_api->m_change_mgr.a_chng_item_of_chng, m_change);
			aggr.Add(m_bps[i]);
		}
		for (i = 0; i < m_maters.GetSize(); i++)
		{
			if (!m_maters[i])
				continue;
			apidata.PutAttr(m_maters[i], m_api->m_change_mgr.a_chng_item_of_chng, m_change);
			aggr.Add(m_maters[i]);
		}

		for (i = 0; i < m_chars.GetSize(); i++)
		{
			if (!m_chars[i])
				continue;
			apidata.PutAttr(m_chars[i], m_api->m_change_mgr.a_chng_item_of_chng, m_change);
			aggr.Add(m_chars[i]);
		}

		for (i = 0; i < m_others.GetSize(); i++)
		{
			if (!m_others[i])
				continue;
			aggr.Add(m_others[i]);
		}

		apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_items, aggr);

		if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие")))
		{
			apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_dependent_items, m_dependent_items);
		}

		/*Только если изменилось что-то*/
		if(bModyfied)
			apidata.PutAttr(m_change, m_api->m_change_mgr.a_chng_is_modify, bModyfied);
	}

	// новый номер изменения (регистрационный номер)
	CaplInstance *cit = NULL;
	CString sNumber;
	int nNumber;

	cit = m_api->m_options_mgr.FindOptionBN( APL_NO_T("Регистрационный номер\\Номер"));
	if(cit)		
	{
		nNumber = m_api->m_options_mgr.GetIntOptionValueBN( APL_NO_T("Регистрационный номер\\Номер"), 1);
		nNumber++;
		m_api->m_data.PutAttr(cit, m_api->m_options_mgr.a_int_value, nNumber);
	}


	if (bSave) apidata.NET_SaveChanges();

	// сохраняем некоторые данные
	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0
	if(0!=app)
	{
		app->WriteProfileString(_T("Settings"), _T("Group Num"), m_sGrpNum);
		app->WriteProfileString(_T("Settings"), _T("Organization Code"), m_sOrgCode);
	}

	return true;
}

void CChangeDlg::OnOK() 
{
	if(!SaveInOk()) return;
	CResizableDialog::OnOK();
}

void CChangeDlg::OnCancel()
{	
	UpdateData();

	bool bSave = false;
	int i;

	for (i = 0; i < m_new_docs.GetSize(); i++)
	{
		for (int j= 0; j < m_new_docs[i].m_attachment.GetSize(); j++)
		{
			apidata.NET_DeleteBlob(m_new_docs[i].m_attachment[j], m_api->m_doc_mgr.a_apl_stored_document_source);
			apidata.DeleteInstance(m_new_docs[i].m_attachment[j]);
			bSave = true;
		}
	}

	for (i = 0; i < m_new_chars.GetSize(); i++)
	{
		for (int j = 0; j < m_new_chars[i].m_attachment.GetSize(); j++)
		{
			apidata.NET_DeleteBlob(m_new_chars[i].m_attachment[j], m_api->m_doc_mgr.a_apl_stored_document_source);
			apidata.DeleteInstance(m_new_chars[i].m_attachment[j]);
			bSave = true;
		}
	}

	for (i = 0; i < m_new_bps.GetSize(); i++)
	{
		for (int j = 0; j < m_new_bps[i].m_attachment.GetSize(); j++)
		{
			apidata.NET_DeleteBlob(m_new_bps[i].m_attachment[j], m_api->m_doc_mgr.a_apl_stored_document_source);
			apidata.DeleteInstance(m_new_bps[i].m_attachment[j]);
			bSave = true;
		}
	}
	
	if (bSave) apidata.NET_SaveChanges();

	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0
	if(0!=app)
	{
		app->WriteProfileString(_T("Settings"), _T("Group Num"), m_sGrpNum);
		app->WriteProfileString(_T("Settings"), _T("Organization Code"), m_sOrgCode);
	}

	CResizableDialog::OnCancel();
}

void CChangeDlg::OnItemchangedChsItemsList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;

	m_index= m_list.GetNextItem(-1, LVNI_ALL|LVNI_SELECTED);
	if(-1!=m_index)
	{
		m_curItem= (CaplInstance*)m_list.GetItemData(m_index);
		if(!m_bReadOnly)
		{
			m_deleteBtn.EnableWindow(TRUE);
			m_addBtn.EnableWindow(TRUE);
		}
		m_propBtn.EnableWindow();

		if(-1==(int)m_curItem) m_addBtn.EnableWindow(FALSE);
		else if(0==m_curItem){} // ЯАИ не понял что должно быть. ДОбавил пункт чтобы не вылетало
		else if(apidata.IsKindOf(m_curItem, m_api->m_change_mgr.e_avc))
		{
			CaplInstance *ver;
			apidata.GetAttr(m_curItem, m_api->m_change_mgr.a_avc_new_rev, ver);
			if(0==ver)m_addBtn.EnableWindow(FALSE);

		}
	}
	else
	{
		m_curItem= NULL;
		m_deleteBtn.EnableWindow(FALSE);
		m_propBtn.EnableWindow(FALSE);
	}

	if(m_bHasDI_iteem)m_addBtn.EnableWindow(FALSE);

	*pResult = 0;
}

void CChangeDlg::OnChsAddButton() 
{
	UpdateData();
	switch (m_iCurTab)
	{
		case 0:	// состав
		{

//#ifdef _DEBUG
			CPoint point;
			GetCursorPos(&point);
			
			CaplMenu menu;
			CMenu* pPopup;
			
			menu.LoadMenu(IDR_ADD_ASS_CHANGE_MENU);
			menu.Install(this);
			pPopup = menu.GetSubMenu(0);

			pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON,
									point.x, point.y, this);
			m_bMenuAdd = true;
//#else
			//AddChItem(0);
//#endif
			break; 
		}

		case 1: AddChMater();	break;						// материал
		case 2: AddChDoc();		{ ChangeDocId(); OnBnClickedChooseUsage(); break; }	// документ
		case 3: AddChBP();		break;						// бизнес-процесс
		case 4: AddChCharact(); break;						// хар-ка
	}
}

void CChangeDlg::GetExistingAVCItems(aplExtent &aeAVC)
{
	for(int i=0; i<m_docs.Size; i++)
	{
		if(m_del_docs.Find(m_docs[i]) != -1) continue;
		aeAVC.Add(m_docs[i]);
	}
}

void CChangeDlg::ChangeDocId()
{
	aplExtent aeAVC;
	CaplInstance *ciDoc = NULL;

	GetExistingAVCItems(aeAVC);
	if(m_new_docs.GetSize()+aeAVC.Size == 1)
	{
		if(m_new_docs.GetSize() ==1 )
		{
			if(0!=m_new_docs[0].m_newVer)
				m_api->m_data.GetAttr(m_new_docs[0].m_newVer, m_api->m_doc_mgr.a_apl_doc_rev_doc, ciDoc);
		}
		else if(aeAVC.Size == 1) m_api->m_data.GetAttr(aeAVC[0], m_api->m_change_mgr.a_avc_doc, ciDoc);
		
		if(ciDoc) m_api->m_data.GetAttr(ciDoc, m_api->m_doc_mgr.a_doc_id, m_sDocId);
		else m_sDocId=_T("");
	}
	else if (m_new_docs.GetSize()+aeAVC.Size > 1)
	{
		m_sDocId =  APL_T("См. ниже");
	}
	else
	{
		m_sDocId=_T("");
	}

	((CEdit*)GetDlgItem(IDC_DOC_ID))->SetWindowText(m_sDocId);
}

void CChangeDlg::AddChItem(int iMode)
{
//	CChangeStructItemDlg dlg;
	/*
#ifdef _DEBUG
	CChangeAssemblyDlg dlg;
#else
	CAssemblyChangeDlg dlg;
#endif
	*/

	if (iMode == 0)
	{
		CAssemblyChangeDlg dlg;
		dlg.m_api= m_api;		
		dlg.m_change= m_change;	
		dlg.m_items= &m_items;
		dlg.m_newItems= &m_new_items;
		dlg.m_delItems= &m_del_items;
		
		if (IDOK==dlg.DoModal())
		{
			ShowChangedItems();
		}	
	}
	else if (iMode == 1)
	{
//#ifdef _DEBUG
		CChangeAssemblyDlg dlg;
		dlg.m_api= m_api;
		dlg.m_api->m_change_mgr= m_api->m_change_mgr;
		
		dlg.m_change= m_change;
		
		dlg.m_items= &m_items;
		dlg.m_newItems= &m_new_items;
		dlg.m_delItems= &m_del_items;
		
		if (IDOK==dlg.DoModal())
		{
			ShowChangedItems();
		}
//#endif
	}
	
}

void CChangeDlg::AddChMater()
{
	CAssemblyChangeDlg dlg;
	dlg.m_api= m_api;
	dlg.m_mode= 1;	
	dlg.m_change= m_change;
	
	dlg.m_items= &m_maters;
	dlg.m_newItems= &m_new_maters;
	dlg.m_delItems= &m_del_maters;
	
	if(IDOK==dlg.DoModal())
	{
		ShowChangedMaters();
	}
}

void CChangeDlg::AddChCharact()
{
	CChangeDocVerDlg dlg;
	dlg.m_api= m_api;
	dlg.m_viewMode = 2;
	
	dlg.m_change = m_change;
	
	dlg.m_items = &m_chars;
	dlg.m_newItems = &m_new_chars;
	dlg.m_delItems = &m_del_chars;
	
	if (IDOK == dlg.DoModal())
	{
		ShowChangedCharacts();
	}
}

void CChangeDlg::AddChDoc()
{
	CChangeDocVerDlg dlg;
	dlg.m_api= m_api;
	
	dlg.m_change= m_change;
	
	dlg.m_items= &m_docs;
	dlg.m_newItems= &m_new_docs;
	dlg.m_delItems= &m_del_docs;


	CString buf;
	m_type_ctrl.GetWindowText(buf);
	if(buf==APL_T("ДИ") || buf== APL_T("ДПИ")) dlg.m_bZerroDocRev=true;
	
	if(IDOK==dlg.DoModal())
	{
		ShowChangedDocs();
	}
}

void CChangeDlg::AddChBP()
{
	CChangeDocVerDlg dlg;
	dlg.m_viewMode= 1;
	dlg.m_api= m_api;
	
	dlg.m_change= m_change;
	
	dlg.m_items= &m_bps;
	dlg.m_newItems= &m_new_bps;
	dlg.m_delItems= &m_del_bps;

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

void CChangeDlg::OnChsDeleteButton() 
{
	UpdateData();
	switch (m_iCurTab)
	{
		case 0: DeleteChItem();		break;
		case 1: DeleteChMater();	break;
		case 2: DeleteChDoc();		break;
		case 3: DeleteChBP();		break;
		case 4: DeleteChCharact();	break;
	}

	if(m_iCurTab == 2)
	{
		ChangeDocId();
		OnBnClickedChooseUsage();
	}
}

void CChangeDlg::DeleteChItem()
{
	if(IDYES==MessageBox( APL_T("Вы действительно хотите удалить запись об изменении?"), 
		 APL_T("Удаление"), MB_ICONWARNING|MB_YESNO))
	{
		if(m_curItem){m_del_items.Add(m_curItem);}
		else
		{
			int n= FindCurItem();
			if(-1!=n){m_new_items.RemoveAt(n);}
		}		
		ShowChangedItems();	
	}
}

void CChangeDlg::DeleteChMater()
{
	if(IDYES==MessageBox( APL_T("Вы действительно хотите удалить запись об изменении?"), 
		 APL_T("Удаление"), MB_ICONWARNING|MB_YESNO))
	{
		if(m_curItem){m_del_maters.Add(m_curItem);}
		else
		{
			int n= FindCurMater();
			if(-1!=n){m_new_maters.RemoveAt(n);}
		}
		ShowChangedMaters();
	}
}

void CChangeDlg::DeleteChDoc()
{
	if(apidata.IsKindOf(m_curItem, m_api->m_doc_mgr.e_apl_doc_rev))
	{
		m_new_docs.RemoveAt(FindCurDoc());
	}
	else if(apidata.IsKindOf(m_curItem, m_api->m_change_mgr.e_avc))
	{
		m_del_docs.Add(m_curItem);
	}	
	ShowChangedDocs();
}

void CChangeDlg::DeleteChBP()
{
	if(apidata.IsKindOf(m_curItem, m_api->m_bp_mgr.e_apl_bp_ver))
	{
		m_new_bps.RemoveAt(FindCurBP());
	}
	else if(apidata.IsKindOf(m_curItem, m_api->m_change_mgr.e_abpc))
	{
		m_del_bps.Add(m_curItem);
	}

	ShowChangedBPs();
}

void CChangeDlg::DeleteChCharact()
{
	if (apidata.IsKindOf(m_curItem, m_api->m_charact_mgr.e_apl_charact_value_ver))
	{
		m_new_chars.RemoveAt(FindCurCharact());
	}
	else if (apidata.IsKindOf(m_curItem, m_api->m_change_mgr.e_char_change))
	{
		m_del_chars.Add(m_curItem);
	}
	
	ShowChangedCharacts();
}

void CChangeDlg::OnChsPropButton() 
{
	switch (m_iCurTab)
	{
		case 0:
		{
			
//#ifdef _DEBUG

			if(!CheckAccess())
			{
				AfxMessageBox( APL_T("Нет прав доступа!"), MB_OK|MB_ICONERROR);
				return;
			}

			CPoint point;
			GetCursorPos(&point);
			
			CaplMenu menu;
			CMenu* pPopup;
			
			menu.LoadMenu(IDR_ADD_ASS_CHANGE_MENU);
			menu.Install(this);
			pPopup = menu.GetSubMenu(0);
			
			pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON,
				point.x, point.y, this);

			m_bMenuAdd = false;
//#else

//			ShowChItemProp(0);
//#endif
			break;
		}
		case 1: ShowChMaterProp();		break;
		case 2: ShowChDocProp();		break;
		case 3: ShowChBPProp();			break;
		case 4: ShowChCharactProp();	break;
	}
}

void CChangeDlg::ShowChItemProp(int iMode)
{
//	CChangeStructItemDlg dlg;
	/*
	#ifdef _DEBUG
		CChangeAssemblyDlg dlg;
	#else
		CAssemblyChangeDlg dlg;
	#endif
	*/
	
	if (iMode == 0)
	{
		CAssemblyChangeDlg dlg;
		dlg.m_api = m_api;
		
		dlg.m_bReadOnly = m_bReadOnly;
		dlg.m_change = m_change;

		dlg.m_items = &m_items;
		dlg.m_newItems = &m_new_items;
		dlg.m_delItems = &m_del_items;
		

		if (m_curItem)
		{
			dlg.m_psc = m_curItem;
		}
		else
		{
			int n = FindCurItem();
			if(-1 != n)
			{
				dlg.m_pscInfo = m_new_items[n];
			}
		}
		
		if (IDOK == dlg.DoModal())
		{
			ShowChangedItems();
		}
	}
	else if (iMode == 1)
	{
//#ifdef _DEBUG
		CChangeAssemblyDlg dlg;

		dlg.m_api = m_api;
		
		dlg.m_bReadOnly = m_bReadOnly;
		dlg.m_change = m_change;
		
		dlg.m_items = &m_items;
		dlg.m_newItems = &m_new_items;
		dlg.m_delItems = &m_del_items;
		
		
		if (m_curItem)
		{
			dlg.m_psc = m_curItem;
		}
		else
		{
			int n = FindCurItem();
			if (-1 != n)
			{
				dlg.m_pscInfo = m_new_items[n];
			}
		}
		
		if (IDOK == dlg.DoModal())
		{
			ShowChangedItems();
		}
//#endif
	}
}

void CChangeDlg::ShowChMaterProp()
{
	CAssemblyChangeDlg dlg;
	
	dlg.m_mode= 1;
	dlg.m_api= m_api;
	
	dlg.m_bReadOnly= m_bReadOnly;
	dlg.m_change= m_change;

	dlg.m_items= &m_maters;
	dlg.m_newItems= &m_new_maters;
	dlg.m_delItems= &m_del_maters;
	
	dlg.m_bReadOnly= m_bReadOnly;

	if(m_curItem)
	{
		dlg.m_psc= m_curItem;
	}
	else
	{
		int n= FindCurMater();
		if(-1!=n)dlg.m_pscInfo= m_new_maters[n];
	}
	
	if(IDOK==dlg.DoModal())
	{
		ShowChangedMaters();
	}
}

void CChangeDlg::ShowChDocProp()
{
	CChangeDocVerDlg dlg;
	dlg.m_api= m_api;
	dlg.m_bReadOnly=m_bReadOnly;

	dlg.m_change= m_change;

	dlg.m_items= &m_docs;
	dlg.m_newItems= &m_new_docs;
	dlg.m_delItems= &m_del_docs;
	
	dlg.m_bReadOnly= m_bReadOnly;

	CString buf;
	m_type_ctrl.GetWindowText(buf);
	if(buf==APL_T("ДИ") || buf== APL_T("ДПИ")) dlg.m_bZerroDocRev=true;

	if((CaplInstance*)-1==m_curItem)
	{
		if(m_new_docs.GetSize()>0) 	dlg.m_newChng=&(m_new_docs[0]);
		else return;
	}
	else if(0!=m_curItem)
	{
		if(apidata.IsKindOf(m_curItem, m_api->m_change_mgr.e_avc))
		{
			dlg.m_avc= m_curItem;
		}
		else if(apidata.IsKindOf(m_curItem, m_api->m_doc_mgr.e_apl_doc_rev))
		{
			int m= FindCurDoc();
			CDAVCItemInfo *info= m_new_docs.GetData();
			info+=m;
			dlg.m_newChng= info;
			info-=m;
		}
	}

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

void CChangeDlg::ShowChBPProp()
{
	CChangeDocVerDlg dlg;
	dlg.m_api= m_api;
	dlg.m_bReadOnly=m_bReadOnly;
	
	dlg.m_change= m_change;

	dlg.m_viewMode= 1;
	dlg.m_items= &m_bps;
	dlg.m_newItems= &m_new_bps;
	dlg.m_delItems= &m_del_bps;
	
	dlg.m_bReadOnly= m_bReadOnly;
	
	if(apidata.IsKindOf(m_curItem, m_api->m_change_mgr.e_abpc))
	{
		dlg.m_avc= m_curItem;
	}
	else if(apidata.IsKindOf(m_curItem, m_api->m_bp_mgr.e_apl_bp_ver))
	{
		int m= FindCurBP();
		CDAVCItemInfo *info= m_new_bps.GetData();
		info+=m;
		dlg.m_newChng= info;
		info-=m;
	}
	

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

void CChangeDlg::ShowChCharactProp()
{
	CChangeDocVerDlg dlg;
	dlg.m_api= m_api;
	dlg.m_bReadOnly=m_bReadOnly;
	
	dlg.m_change= m_change;

	dlg.m_viewMode = 2;
	dlg.m_items = &m_chars;
	dlg.m_newItems = &m_new_chars;
	dlg.m_delItems = &m_del_chars;
	
	dlg.m_bReadOnly = m_bReadOnly;

	if (apidata.IsKindOf(m_curItem, m_api->m_change_mgr.e_char_change))
	{
		dlg.m_avc = m_curItem;
	}
	else if (apidata.IsKindOf(m_curItem, m_api->m_charact_mgr.e_apl_charact_value_ver))
	{
		int m = FindCurCharact();
		CDAVCItemInfo* info = m_new_chars.GetData();
		info += m;
		dlg.m_newChng = info;
		info -= m;
	}
	

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

void CChangeDlg::OnChsApplyButton() 
{
	if(!SaveInOk()) return;

	if(m_api->m_change_mgr.ApplyChange(m_change)==APL_CN_NO_ERR)
	{
		SetControlsState();
	}
}

void CChangeDlg::ShowChangedDocs()
{
	int i;
	m_list.DeleteAllItems();
	
	int nColumnCount = m_list.GetHeaderCtrl()->GetItemCount();
	for (i = 0; i < nColumnCount; i++)
	{
	   m_list.DeleteColumn(0);
	}
	
	m_list.InsertColumn(0,  APL_T("Регистрационный номер"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(1,  APL_T("Документ"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(2,  APL_T("Новая активная версия"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(3,  APL_T("Старая активная версия"), LVCFMT_LEFT, 150);

	CaplInstance *inst;
	CString name, buf, buf1;
	int ico= APL_ICON_CHANGE_ITEM+1;

	m_bHasDI_iteem=false;
	
	for (i = 0; i < m_docs.GetSize(); i++)
	{
		if(!m_docs[i] || !m_docs[i]->GetType()) {m_docs.Remove(i); i--; continue;}
		if(-1!=m_del_docs.Find(m_docs[i])) continue;

		apidata.GetAttr(m_docs[i], m_api->m_change_mgr.a_chng_item_id, name);
		if(name.IsEmpty()) name=  APL_T("<Не присвоен>");
		int n= m_list.GetItemCount();
		int m= m_list.InsertItem(n, name, ico);
		m_list.SetItemData(m, (DWORD)m_docs[i]);
		
		//apidata.GetAttr(m_docs[i], m_api->m_change_mgr.a_chng_item_basis, name);
		//m_list.SetItemText(m, 1, name);
		
		CaplInstance* rev= NULL;
		apidata.GetAttr(m_docs[i], m_api->m_change_mgr.a_avc_new_rev, rev);
		if(0==rev)
		{
			name=APL_T("< Описание изменения >");
			m_list.SetItemText(m, 1, name);
			m_bHasDI_iteem=true;
		}
		else 
		{
			apidata.GetAttr(rev, m_api->m_doc_mgr.a_apl_doc_rev_id, name);
			if(name.IsEmpty())
			{
	//			m_api->m_doc_mgr.LoadDocInfo(rev);
				apidata.GetAttr(rev, m_api->m_doc_mgr.a_apl_doc_rev_id, name);			
			}
			m_list.SetItemText(m, 2, name);

			CaplInstance* doc= NULL;
			apidata.GetAttr(rev, m_api->m_doc_mgr.a_apl_doc_rev_doc, doc);
			
			apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_id, name);
			apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_name, buf);
			if(!name.IsEmpty()) name+=_T(":");
			name+=buf;
			apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_kind, inst);
			if(inst!=0 && inst->GetAccessmode()!=aplNO)
			{
				apidata.GetAttrBN(inst, _T("product_data_type"), buf);
				if(!name.IsEmpty()) name+=_T(":");
				name+=buf;
			}
			if(name.IsEmpty()) name= _T("???");

			m_list.SetItemText(m, 1, name);

			apidata.GetAttr(m_docs[i], m_api->m_change_mgr.a_avc_old_rev, inst);
			if(!inst && doc!=0)apidata.GetAttr(doc, m_api->m_doc_mgr.a_apl_doc_active, inst);

			if(inst)
			{
				apidata.GetAttr(inst, m_api->m_doc_mgr.a_apl_doc_rev_id, name);
				if(name.IsEmpty())
				{
		//			m_api->m_doc_mgr.LoadDocInfo(inst);
					apidata.GetAttr(inst, m_api->m_doc_mgr.a_apl_doc_rev_id, name);		
				}
				m_list.SetItemText(m, 3, name);
			}
		}
	}

	for(i= 0; i<m_new_docs.GetSize(); i++)
	{
		int n= m_list.GetItemCount();
		if(m_new_docs[i].m_sId.IsEmpty()) name=  APL_T("<Не присвоен>");
		else name= m_new_docs[i].m_sId;
		int m= m_list.InsertItem(n, name, ico);
		
		
		if(0==m_new_docs[i].m_newVer) 
		{
			m_list.SetItemData(m, (DWORD)(-1)); // ЯАИ: Переделываю, чтобы можно было использовать пустую версию
			m_list.SetItemText(m, 1, APL_T("< Описание изменения >"));
			m_bHasDI_iteem=true;
		}
		else
		{
			m_list.SetItemData(m, (DWORD)m_new_docs[i].m_newVer);
			//m_list.SetItemText(m, 1, m_new_docs[i].m_sBasis);
		
			CaplInstance* doc= NULL;
			apidata.GetAttr(m_new_docs[i].m_newVer, m_api->m_doc_mgr.a_apl_doc_rev_doc, doc);
			
			if(0!=doc)
			{
				apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_id, name);
				apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_name, buf);

				if(!name.IsEmpty()) name+=_T(":");
				name+=buf;
				apidata.GetAttr(doc, m_api->m_doc_mgr.a_doc_kind, inst);
				if(inst!=0 && inst->GetAccessmode()!=aplNO)
				{
					apidata.GetAttrBN(inst, _T("product_data_type"), buf);
					if(!name.IsEmpty()) name+=_T(":");
					name+=buf;
				}
				if(name.IsEmpty()) name= _T("???");
				
				m_list.SetItemText(m, 1, name);

				apidata.GetAttr(m_new_docs[i].m_newVer, m_api->m_doc_mgr.a_apl_doc_rev_id, name);
				m_list.SetItemText(m, 2, name);
				apidata.GetAttr(doc, m_api->m_doc_mgr.a_apl_doc_active, inst);
				apidata.GetAttr(inst, m_api->m_doc_mgr.a_apl_doc_rev_id, name);
				m_list.SetItemText(m, 3, name);
			}
		}
	}
}

void CChangeDlg::ShowChangedCharacts()
{
	int i;
	m_list.DeleteAllItems();
	int nColumnCount = m_list.GetHeaderCtrl()->GetItemCount();
	for (i = 0; i < nColumnCount; i++)
	   m_list.DeleteColumn(0);
	
	m_list.InsertColumn(0,  APL_T("Регистрационный номер"), LVCFMT_LEFT, 50);
	m_list.InsertColumn(1,  APL_T("Объект"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(2,  APL_T("Характеристика"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(3,  APL_T("Тип"), LVCFMT_LEFT, 50);
	m_list.InsertColumn(4,  APL_T("Текущее значение"), LVCFMT_LEFT, 100);
	m_list.InsertColumn(5,  APL_T("Новое значение"), LVCFMT_LEFT, 100);
	
	CaplInstance* inst;
	CString name, buf, buf1, val;
	int ico = APL_ICON_CHANGE_ITEM + 1;
	CaplInstance* charactVal = NULL;
	CaplInstance* iType = NULL;
	CaplInstance* iCharact= NULL;
	CaplInstance* iUnit= NULL;
	CaplInstance* ipItem= NULL;
	CString sType = _T("");
	CString sVal;

	for (i = 0; i < m_chars.GetSize(); i++)
	{
		if (!m_chars[i] || !m_chars[i]->GetType())
		{
			m_chars.Remove(i);
			i--; 
			continue;
		}

		if ( -1 != m_del_chars.Find(m_chars[i]))
			continue;
		apidata.GetAttr(m_chars[i], m_api->m_change_mgr.a_char_change_val, charactVal);
		if (!charactVal)
			continue;

		// получаем регистрационный номер
		apidata.GetAttr(m_chars[i], m_api->m_change_mgr.a_chng_item_id, name);
		// если пустой, то выводим соответствующий текст
		if (name.IsEmpty())
			name =  APL_T("<Не присвоен>");

		// добавляем новый итем в список
		int n = m_list.GetItemCount();
		int m = m_list.InsertItem(n, name, ico);
		m_list.SetItemData(m, (DWORD)m_chars[i]);
		
		// получаем обоснование
		//apidata.GetAttr(m_chars[i], m_api->m_change_mgr.a_chng_item_basis, name);
		//m_list.SetItemText(m, 1, name);
		

		// получаем характеристику
		CaplInstance* charact = NULL; // apl_characteristic
		if(charactVal->attrs==NULL)
			m_api->m_charact_mgr.LoadCharacteristic(charactVal);
		apidata.GetAttr(charactVal, m_api->m_charact_mgr.a_apl_charact_val_charact, charact);
		apidata.GetAttr(charactVal, m_api->m_charact_mgr.a_apl_charact_val_item, ipItem);

		m_api->GetItemName(ipItem, name);
		m_list.SetItemText(m, 1, name);

		apidata.GetAttr(charact, m_api->m_charact_mgr.a_apl_charact_name, name);		
		m_list.SetItemText(m, 2, name);

		// тип
		apidata.GetAttr(charactVal, m_api->m_charact_mgr.a_apl_charact_val_type, iType);
		if (iType)
			apidata.GetAttr(iType, m_api->m_charact_mgr.a_apl_charact_type_name, sType);
		else
			sType =  APL_T("[Тип не задан]");
		m_list.SetItemText(m, 3, sType);
		
		// Новое значение
		m_api->m_data.GetAttr(m_chars[i], m_api->m_change_mgr.a_char_change_new_rev, inst);
		if(inst!=0)
		{
			if(inst->attrs== NULL)m_api->m_charact_mgr.LoadCharacteristic(inst);
			m_api->m_data.GetAttr(inst, m_api->m_charact_mgr.a_apl_charact_val_ver_version_num, val);
			m_api->m_data.GetAttr(inst, m_api->m_charact_mgr.a_apl_charact_val_ver_charact, iCharact);
			m_api->m_data.GetAttr(iCharact, m_api->m_charact_mgr.a_apl_charact_unit, iUnit);
			m_api->m_charact_mgr.PrintCharacteristicValue(inst, iUnit, sVal);
			m_list.SetItemText(m, 4, _T("[")+val+_T("] ")+sVal);
		}

		// Старое значение
		apidata.GetAttr(m_chars[i], m_api->m_change_mgr.a_char_change_old_rev, inst);
		
		// если old_revision == 0, то значит изменение ещё не проводилось
		CaplInstance* charactActVer = NULL;
		if (inst)
			charactActVer= inst;
		else
			apidata.GetAttr(charactVal, m_api->m_charact_mgr.a_apl_charact_val_act_ver, charactActVer);
		
		apidata.GetAttr(charactActVer, m_api->m_charact_mgr.a_apl_charact_val_ver_version_num, val);
		m_api->m_charact_mgr.PrintCharacteristicValue(charactActVer, iUnit, sVal);
		m_list.SetItemText(m, 5, _T("[")+val+_T("] ")+sVal);
	}

	for (i = 0; i < m_new_chars.GetSize(); i++)
	{
		int n = m_list.GetItemCount();

		// Регистрационный номер
		if (m_new_chars[i].m_sId.IsEmpty())
			name =  APL_T("<Не присвоен>");
		else
			name= m_new_chars[i].m_sId;
		int m = m_list.InsertItem(n, name, ico);

		m_list.SetItemData(m, (DWORD)m_new_chars[i].m_newVer);

		m_api->m_data.GetAttr(m_new_chars[i].m_newVer, m_api->m_charact_mgr.a_apl_charact_val_ver_char_value, iCharact);
		m_api->m_data.GetAttr(iCharact, m_api->m_charact_mgr.a_apl_charact_val_item, ipItem);

		m_api->GetItemName(ipItem, name);
		m_list.SetItemText(m, 1, name);

		// обоснование
		//m_list.SetItemText(m, 1, m_new_chars[i].m_sBasis);
		
		// имя хар-ки
		CaplInstance* charact= NULL; // apl_characteristic
		m_api->m_data.GetAttr(m_new_chars[i].m_newVer, m_api->m_charact_mgr.a_apl_charact_val_ver_charact, charact);
		m_api->m_data.GetAttr(charact, m_api->m_charact_mgr.a_apl_charact_unit, iUnit);
		
		apidata.GetAttr(charact, m_api->m_charact_mgr.a_apl_charact_name, name);	
		m_list.SetItemText(m, 2, name);

		// тип
		CaplInstance* iCharactVal = NULL;
		CaplInstance* iType = NULL;
		CString sType = _T("");
		apidata.GetAttr(m_new_chars[i].m_newVer, m_api->m_charact_mgr.a_apl_charact_val_ver_char_value, iCharactVal);
		apidata.GetAttr(iCharactVal, m_api->m_charact_mgr.a_apl_charact_val_type, iType);
		if(iType)
			apidata.GetAttr(iType, m_api->m_charact_mgr.a_apl_charact_type_name, sType);
		else
			sType =  APL_T("тип не задан");
		m_list.SetItemText(m, 3, sType);
		
		
		// Новое значение
		CString new_val;
		apidata.GetAttr(m_new_chars[i].m_newVer, m_api->m_charact_mgr.a_apl_charact_val_ver_version_num, new_val);
		m_api->m_charact_mgr.PrintCharacteristicValue(m_new_chars[i].m_newVer, iUnit, sVal);
		m_list.SetItemText(m, 4, _T("[")+new_val+_T("] ")+sVal);

		// Старое значение
		CString old_val;
		CaplInstance* iCharactActVer = NULL;
		apidata.GetAttr(iCharactVal, m_api->m_charact_mgr.a_apl_charact_val_act_ver, iCharactActVer);
		apidata.GetAttr(iCharactActVer, m_api->m_charact_mgr.a_apl_charact_val_ver_version_num, old_val);

		apidata.GetAttr(iCharactActVer, m_api->m_charact_mgr.a_apl_charact_val_ver_version_num, val);
		m_api->m_charact_mgr.PrintCharacteristicValue(iCharactActVer, iUnit, sVal);
		m_list.SetItemText(m, 5, _T("[")+old_val+_T("] ")+sVal);
	}
}

void CChangeDlg::ShowChangedBPs()
{
	int i;
	m_list.DeleteAllItems();
	int nColumnCount = m_list.GetHeaderCtrl()->GetItemCount();
	for (i = 0; i < nColumnCount; i++)
	{
	   m_list.DeleteColumn(0);
	}
	
	m_list.InsertColumn(0,  APL_T("Регистрационный номер"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(1,  APL_T("Бизнес-процесс"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(2,  APL_T("Новая активная версия"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(3,  APL_T("Старая активная версия"), LVCFMT_LEFT, 150);
	
	CString buf, name;
	CaplInstance* inst= NULL;
	int ico= APL_ICON_CHANGE_ITEM+2;

	for(i= 0; i<m_bps.GetSize(); i++)
	{
		if(!m_bps[i] || !m_bps[i]->GetType()) {m_bps.Remove(i); i--; continue;}
		if(-1!=m_del_bps.Find(m_bps[i])) continue;
		
		m_api->m_data.GetAttr(m_bps[i], m_api->m_change_mgr.a_chng_item_id, name);
		if(name.IsEmpty()) name=  APL_T("<Не присвоен>");
		int n= m_list.GetItemCount();
		int m= m_list.InsertItem(n, name, ico);
		m_list.SetItemData(m, (DWORD)m_bps[i]);
		
		//m_api->m_data.GetAttr(m_bps[i], m_api->m_change_mgr.a_chng_basis, buf);
		//m_list.SetItemText(m, 1, buf);

		CaplInstance* bp= NULL, *active= NULL;
		m_api->m_data.GetAttr(m_bps[i], m_api->m_change_mgr.a_abpc_new_rev, inst);
		m_api->m_data.GetAttr(m_bps[i], m_api->m_change_mgr.a_abpc_old_rev, active);
		if(inst)
		{
//			m_api->m_bp_mgr.LoadBPInfo(inst);
			m_api->m_data.GetAttr(inst, m_api->m_bp_mgr.a_bp_ver_num, buf);
			if(buf.IsEmpty())//чтобы 30 раз не читать
			{
				m_api->m_bp_mgr.LoadBPInfo(inst);
				m_api->m_data.GetAttr(inst, m_api->m_bp_mgr.a_bp_ver_num, buf);
			}
			m_list.SetItemText(m, 2, buf);
			m_api->m_data.GetAttr(inst, m_api->m_bp_mgr.a_bp_ver_bp, bp);
		}

		if(bp)
		{
			m_api->m_data.GetAttr(bp, m_api->m_bp_mgr.a_bp_id, name);
			m_api->m_data.GetAttr(bp, m_api->m_bp_mgr.a_bp_name, buf);
			
			if(name.IsEmpty())name=_T("?");
			name+=_T(":"); name+=buf;
			m_list.SetItemText(m, 1, name);
			
			if(!active)m_api->m_data.GetAttr(bp, m_api->m_bp_mgr.a_bp_act, active);
		}

		if(active)
		{
//			m_api->m_bp_mgr.LoadBPInfo(active);
			m_api->m_data.GetAttr(active, m_api->m_bp_mgr.a_bp_ver_num, buf);
			if(buf.IsEmpty())//чтобы 30 раз не читать
			{
				m_api->m_bp_mgr.LoadBPInfo(active);
				m_api->m_data.GetAttr(active, m_api->m_bp_mgr.a_bp_ver_num, buf);
			}
			m_list.SetItemText(m, 3, buf);
		}
	}

	for(i=0; i<m_new_bps.GetSize(); i++)
	{
		int n= m_list.GetItemCount();
		if(m_new_bps[i].m_sId.IsEmpty()) name= APL_T("<Не присвоен>");
		else name= m_new_bps[i].m_sId;
		int m= m_list.InsertItem(n, name, ico);
		m_list.SetItemData(m, (DWORD)m_new_bps[i].m_newVer);
		
		//m_list.SetItemText(m, 1, m_new_bps[i].m_sBasis);

		CaplInstance* bp= NULL, *active= NULL;
		if(m_new_bps[i].m_newVer)
		{
			m_api->m_data.GetAttr(m_new_bps[i].m_newVer, m_api->m_bp_mgr.a_bp_ver_num, buf);
			m_list.SetItemText(m, 2, buf);

			m_api->m_data.GetAttr(m_new_bps[i].m_newVer, m_api->m_bp_mgr.a_bp_ver_bp, bp);
		}

		if(bp)
		{
			m_api->m_data.GetAttr(bp, m_api->m_bp_mgr.a_bp_id, name);
			m_api->m_data.GetAttr(bp, m_api->m_bp_mgr.a_bp_name, buf);
			
			if(name.IsEmpty())name=_T("?");
			name+=buf;
			m_list.SetItemText(m, 1, name);
			
			m_api->m_data.GetAttr(bp, m_api->m_bp_mgr.a_bp_act, active);
		}

		if(active)
		{
			m_api->m_data.GetAttr(active, m_api->m_bp_mgr.a_bp_ver_num, buf);
			m_list.SetItemText(m, 3, buf);
		}		
	}
}

void CChangeDlg::ShowChangedMaters()
{
	int i;
	m_list.DeleteAllItems();
	
	int nColumnCount = m_list.GetHeaderCtrl()->GetItemCount();
	for (i= 0; i<nColumnCount; i++)
	{
	   m_list.DeleteColumn(0);
	}

	m_list.InsertColumn(0,  APL_T("Регистрационный номер"), LVCFMT_LEFT, 50);	
	m_list.InsertColumn(1,  APL_T("Изделие"), LVCFMT_LEFT, 200);
	m_list.InsertColumn(2,  APL_T("Материал"), LVCFMT_LEFT, 200);
	m_list.InsertColumn(3,  APL_T("Новый материал"), LVCFMT_LEFT, 200);
	m_list.InsertColumn(4,  APL_T("Правило применяемости"), LVCFMT_LEFT, 250);
	
	CString name, buf, buf1;
	int ico= APL_ICON_CHANGE_ITEM+3;
	
	for(i= 0; i<m_maters.GetSize(); i++)
	{
		if(!m_maters[i]) continue;
		if(-1!=m_del_maters.Find(m_maters[i])) continue; //...за исключением удаляемых
		
		CaplInstance* inst= NULL;
		
		m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_chng_item_id, name);
		if(name.IsEmpty()) name=  APL_T("<Не присвоен>");
		int n= m_list.GetItemCount();
		int m= m_list.InsertItem(n, name, ico);
		m_list.SetItemData(m, (DWORD)m_maters[i]);
		
		CaplInstance* pdf_inst= NULL, *mater_inst= NULL, 
			*new_mater_inst= NULL, *pdr_inst= NULL, *unit= NULL,
			*assortm= NULL;
		
		CString sPdf, sMater, sNewMater;
		int iPrior; double dValue;
		CString sEffType, sStart, sEnd, sSize, sRequir, sSortam, sUnit, sRazmer;

		m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_changed_product, pdr_inst);
		m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_changing_product, new_mater_inst);

		if(m_api->m_data.IsKindOf(pdr_inst, m_api->m_prd_mgr.e_pdr))
		{
// 			CaplLoadData ld(&apidata,DEF_SOURCE);
// 			int ii=ld.AddQuery(pdr_inst);
// 			ld.AddQuery(_T('d'), ii, 0, m_api->m_prd_mgr.a_pdr_r_ted, true);
// 			ld.AddQuery(_T('d'), ii, 0, m_api->m_prd_mgr.a_pdr_r_ting, true);
// 			ld.AddQuery(_T('d'), ii, 0, m_api->m_prd_mgr.a_make_from_ranking, true);
// 			ld.AddQuery(_T('d'), ii, 0, m_api->m_prd_mgr.a_make_from_assortment, true);
// 			ld.AddQuery(_T('d'), ii, 0, m_api->m_prd_mgr.a_make_from_unit, true);
// 			ld.AddQuery(_T('d'), ii, 0, m_api->m_prd_mgr.a_make_from_value, true);
// 			ld.AddQuery(_T('d'), ii, 0,  m_api->m_prd_mgr.a_pdr_id, true);
// 			ld.LoadEx();

			m_api->m_data.GetAttr(pdr_inst, m_api->m_prd_mgr.a_pdr_r_ting, pdf_inst);
			m_api->m_data.GetAttr(pdr_inst, m_api->m_prd_mgr.a_pdr_r_ted, mater_inst);	
			
			aplExtent prds_ext;
			if(pdf_inst && !pdf_inst->attrs!=0)prds_ext.Add(pdf_inst);
			if(mater_inst && !mater_inst->attrs!=0)prds_ext.Add(mater_inst);
			if(prds_ext.GetSize())m_api->m_prd_mgr.LoadPrdInfo(prds_ext);
 
			CaplInstance* inst= NULL;

			m_api->m_data.GetAttr(pdr_inst, m_api->m_prd_mgr.a_make_from_ranking, iPrior);
			m_api->m_data.GetAttr(pdr_inst, m_api->m_prd_mgr.a_make_from_assortment, inst);
			if(inst) m_api->m_data.GetAttr(inst, m_api->m_prd_mgr.a_assortment_name, sSortam);
			m_api->m_data.GetAttr(pdr_inst, m_api->m_prd_mgr.a_make_from_unit, inst);
			if(inst) m_api->m_charact_mgr.GetUnitName(inst, sUnit);
			m_api->m_data.GetAttr(pdr_inst, m_api->m_prd_mgr.a_make_from_value, dValue);
			m_api->m_data.GetAttr(pdr_inst, m_api->m_prd_mgr.a_pdr_id, sRazmer);

			if(mater_inst)
			{
				CaplInstance* prd_inst=NULL;
				m_api->m_data.GetAttr(mater_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
				if(prd_inst)
				{
					m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
					m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
					if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
				}

				m_api->m_data.GetAttr(mater_inst, m_api->m_prd_mgr.a_pdf_id, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			sMater.Format(_T("(%i) %s :%s {%s} [%g %s]"), iPrior, 
				sPdf, sRazmer, sSortam, dValue, sUnit);
			
			m_list.SetItemText(n, 2, sMater);			
		}
		else if(m_api->m_data.IsKindOf(pdr_inst, m_api->m_prd_mgr.e_pdf))
		{
			pdf_inst= pdr_inst;
		}
		
		if(pdf_inst)
		{
			if(!pdf_inst->attrs!=0) m_api->m_prd_mgr.LoadPrdInfo(pdf_inst);

			CaplInstance* prd_inst=NULL;
			m_api->m_data.GetAttr(pdf_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
			if(prd_inst)
			{
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			m_api->m_data.GetAttr(pdf_inst, m_api->m_prd_mgr.a_pdf_id, buf);
			if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			
			m_list.SetItemText(n, 1, sPdf);			
		}
		
		if(new_mater_inst)
		{
			if(!new_mater_inst->attrs!=0) m_api->m_prd_mgr.LoadPrdInfo(new_mater_inst);
			
			CaplInstance* prd_inst=NULL;
			m_api->m_data.GetAttr(new_mater_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
			if(prd_inst)
			{
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			m_api->m_data.GetAttr(new_mater_inst, m_api->m_prd_mgr.a_pdf_id, buf);
			if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_unit, unit);
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_value, dValue);
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_mat_renking, iPrior);
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_mat_assort, assortm);
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_mat_size, sSize);
			
			if(assortm) m_api->m_data.GetAttr(assortm, m_api->m_prd_mgr.a_assortment_name, buf);
			if(unit) m_api->m_charact_mgr.GetUnitName(unit, buf1);

			sNewMater.Format(_T("(%i) %s :%s {%s} [%g %s]"), iPrior, sPdf, sSize, buf, dValue, buf1);
			m_list.SetItemText(n, 3, sNewMater);
		}
		
		m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_eff_type, sEffType);
		if(sEffType==_T("dated"))
		{
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_start_date, sStart);
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_end_date, sEnd);
		}
		else if(sEffType==_T("numbered"))
		{
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_start_num, sStart);
			m_api->m_data.GetAttr(m_maters[i], m_api->m_change_mgr.a_psc_end_num, sEnd);
		}

		ShowEffectivityInCtrl(sEffType, sStart, sEnd, m);
	}

	for(i= 0; i<m_new_maters.GetSize(); i++)
	{
		int n= m_list.GetItemCount();
		if(m_new_maters[i].m_sId.IsEmpty()) name=  APL_T("<Не присвоен>");
		else name= m_new_maters[i].m_sId;
		int m= m_list.InsertItem(n, name, ico);
		
		CaplInstance* pdf_inst= NULL, *mater_inst= NULL, *new_mater_inst= m_new_maters[i].m_pdf;
		CString sPdf, sMater, sNewMater;
		int iPrior; double dValue; 
		CString sSortam, sUnit, sRazmer;

		if(m_api->m_data.IsKindOf(m_new_maters[i].m_pdr, m_api->m_prd_mgr.e_pdr))
		{
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_pdr_r_ting, pdf_inst);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_pdr_r_ted, mater_inst);	
			
			CaplInstance* inst= NULL;

			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_make_from_ranking, iPrior);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_make_from_assortment, inst);
			if(inst) m_api->m_data.GetAttr(inst, m_api->m_prd_mgr.a_assortment_name, sSortam);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_make_from_unit, inst);
			if(inst) m_api->m_charact_mgr.GetUnitName(inst, sUnit);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_make_from_value, dValue);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_pdr_id, sRazmer);

			if(mater_inst)
			{
				CaplInstance* prd_inst=NULL;
				m_api->m_data.GetAttr(mater_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
				if(prd_inst)
				{
					m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
					m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
					if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
				}

				m_api->m_data.GetAttr(mater_inst, m_api->m_prd_mgr.a_pdf_id, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			sMater.Format(_T("(%i) %s :%s {%s} [%g %s]"), iPrior, 
				sPdf, sRazmer, sSortam, dValue, sUnit);
			
			m_list.SetItemText(n, 2, sMater);
		}
		else if(m_api->m_data.IsKindOf(m_new_maters[i].m_pdr, m_api->m_prd_mgr.e_pdf))
		{
			pdf_inst= m_new_maters[i].m_pdr;
		}
		
		if(pdf_inst)
		{
			CaplInstance* prd_inst=NULL;
			m_api->m_data.GetAttr(pdf_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
			if(prd_inst)
			{
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			m_api->m_data.GetAttr(pdf_inst, m_api->m_prd_mgr.a_pdf_id, buf);
			if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			
			m_list.SetItemText(n, 1, sPdf);
		}

		if(new_mater_inst)
		{
			CaplInstance* prd_inst=NULL;
			m_api->m_data.GetAttr(new_mater_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
			if(prd_inst)
			{
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			m_api->m_data.GetAttr(new_mater_inst, m_api->m_prd_mgr.a_pdf_id, buf);
			if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}

			if(m_new_maters[i].m_sort) m_api->m_data.GetAttr(m_new_maters[i].m_sort, m_api->m_prd_mgr.a_assortment_name, buf);
			if(m_new_maters[i].m_unit) m_api->m_charact_mgr.GetUnitName(m_new_maters[i].m_unit, buf1);

			sNewMater.Format(_T("(%i) %s :%s {%s} [%g %s]"), m_new_maters[i].m_prior, 
				sPdf, m_new_maters[i].m_razmer, buf, 
				m_new_maters[i].m_value, buf1);

			m_list.SetItemText(n, 3, sNewMater);
		}
		
		ShowEffectivityInCtrl(m_new_maters[i].m_sEffType, 
			m_new_maters[i].m_sStartCond, m_new_maters[i].m_sEndCond, m);
	}
}

void CChangeDlg::ShowChangedItems()
{
	int i;
	m_list.SetRedraw(FALSE);
	m_list.DeleteAllItems();
	m_list.SetRedraw(TRUE);
	
	int nColumnCount = m_list.GetHeaderCtrl()->GetItemCount();
	for (i= 0; i<nColumnCount; i++)
	{
	   m_list.DeleteColumn(0);
	}

	m_list.InsertColumn(0,  APL_T("Регистрационный номер"), LVCFMT_LEFT, 50);	
	m_list.InsertColumn(1,  APL_T("Изменяемое изделие"), LVCFMT_LEFT, 200);
	m_list.InsertColumn(2,  APL_T("Заменяемое изделие"), LVCFMT_LEFT, 200);
	m_list.InsertColumn(3,  APL_T("Заменяющее изделие"), LVCFMT_LEFT, 200);
	m_list.InsertColumn(4,  APL_T("Количество"), LVCFMT_RIGHT, 100);
/*	m_list.InsertColumn(5, APL_T("Обоснование"), LVCFMT_LEFT, 150);
	m_list.InsertColumn(6, APL_T("Задел"), LVCFMT_LEFT, 150);*/
	m_list.InsertColumn(5,  APL_T("Правило применяемости"), LVCFMT_LEFT, 250);

	CString name, buf, buf1;
	int ico= APL_ICON_CHANGE_ITEM;
	
	for(i= 0; i<m_items.GetSize(); i++) //сначала весь список...
	{
		if(!m_items[i]) continue;
		if(-1!=m_del_items.Find(m_items[i])) continue; //...за исключением удаляемых
		
		CaplInstance* inst= NULL;
		
		apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_chng_item_id, name);
		if(name.IsEmpty()) name=  APL_T("<Не присвоен>");
		int n= m_list.GetItemCount();
		int m= m_list.InsertItem(n, name, ico);
		m_list.SetItemData(m, (DWORD)m_items[i]);

		CaplInstance *pdf= NULL, *pdr= NULL;
		apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_changed_product, pdr);
		apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_changing_product, pdf);
		
		ShowProductsInCtrl(pdr, pdf, m);

		double r;
		apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_value, r);
		apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_unit, inst);
		name=_T("");
		if(r!=0)
		{
			if(inst) m_api->m_charact_mgr.GetUnitName(inst, name);
			buf.Format(_T("%g [%s]"), r, name);
			m_list.SetItemText(m, 4, buf);
		}

/*		apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_chng_item_basis, buf);
		m_list.SetItemText(m, 5, buf);

		apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_chng_item_stock, buf);
		m_list.SetItemText(m, 6, buf);*/
		
		COleDateTime odt;
		CString cond1, cond2;
		apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_eff_type, name);
		
		if(name==_T("dated"))
		{
			apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_start_date, buf);
			apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_end_date, buf1);
		}
		else if(name==_T("numbered"))
		{
			apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_start_num, buf);
			apidata.GetAttr(m_items[i], m_api->m_change_mgr.a_psc_end_num, buf1);
		}

		ShowEffectivityInCtrl(name, buf, buf1, m);
	}
	for(i= 0; i<m_new_items.GetSize(); i++)
	{
		int n= m_list.GetItemCount();
		if(m_new_items[i].m_sId.IsEmpty()) name=  APL_T("<Не присвоен>");
		else name= m_new_items[i].m_sId;
		int m= m_list.InsertItem(n, name, ico);

		ShowProductsInCtrl(m_new_items[i].m_pdr, m_new_items[i].m_pdf, m);
		
		name=_T("");
		if(m_new_items[i].m_unit)
		{
			m_api->m_charact_mgr.GetUnitName(m_new_items[i].m_unit, name);
		}
		if(m_new_items[i].m_value!=0)
		{
			buf.Format(_T("%g [%s]"), m_new_items[i].m_value, name);
			m_list.SetItemText(m, 4, buf);
		}
		m_list.SetItemText(m, 5, m_new_items[i].m_sBasis);
		m_list.SetItemText(m, 6, m_new_items[i].m_sStock);
		
		ShowEffectivityInCtrl(m_new_items[i].m_sEffType, m_new_items[i].m_sStartCond, m_new_items[i].m_sEndCond, m);		
	}
}

void CChangeDlg::ShowProductsInCtrl(CaplInstance *prd_ed, CaplInstance *prd_ing, int n)
{
	CaplInstance* inst= NULL, *pdf= NULL;
	CString name, buf;
	
	if(prd_ed)
	{
		if(apidata.IsKindOf(prd_ed, m_api->m_prd_mgr.e_pdr))
		{
// 			CaplLoadData ld(&apidata,DEF_SOURCE);
// 			i=ld.AddQuery(prd_ed);
// 			ld.AddQuery(_T('d'), i, 0, m_api->m_prd_mgr.a_pdr_r_ted, true);
// 			ld.AddQuery(_T('d'), i, 0, m_api->m_prd_mgr.a_pdr_r_ting, true);
// 			ld.AddQuery(_T('d'), i, 0, m_api->m_prd_mgr.a_apl_qacu_unit, true);
// 			ld.AddQuery(_T('d'), i, 0, m_api->m_prd_mgr.a_apl_qacu_value, true);
// 			ld.LoadEx();

			apidata.GetAttr(prd_ed, m_api->m_prd_mgr.a_pdr_r_ted, pdf);
			if(pdf)
			{
				if(pdf->GetAccessmode()>aplRO)
				{
					buf=  APL_T("[ Нет доступа ]");
				}
				else
				{
//					m_api->m_prd_mgr.LoadPrdInfo(pdf);
					m_api->GetItemName(pdf, buf);
				}

				m_list.SetItemText(n, 2, buf);						
			}

			apidata.GetAttr(prd_ed, m_api->m_prd_mgr.a_pdr_r_ting, pdf);
		}
		else if(apidata.IsKindOf(prd_ed, m_api->m_prd_mgr.e_apl_pdf))
		{
			pdf= prd_ed;
		}

		if(pdf->GetAccessmode()>aplRO)
		{
			buf=  APL_T("[ Нет доступа ]");
		}
		else
		{
//			m_api->m_prd_mgr.LoadPrdInfo(pdf);
			m_api->GetItemName(pdf, buf);
		}

		m_list.SetItemText(n, 1, buf);
	}

	if(prd_ing)
	{
		if(prd_ing->GetAccessmode()>aplRO)
		{
			buf=  APL_T("[ Нет доступа ]");
		}
		else
		{
//			m_api->m_prd_mgr.LoadPrdInfo(prd_ing);
			m_api->GetItemName(prd_ing, buf);
		}

		m_list.SetItemText(n, 3, buf);
	}
}

void CChangeDlg::ShowEffectivityInCtrl(CString type, CString start, CString end, int n)
{
	CString buf;
	
	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;				
		}		
	}
	if(0==m_iCurTab)
	{
		m_list.SetItemText(n, 5, buf);
		if(buf.IsEmpty())
			m_list.SetItemText(n, 5, m_sSeriaPrimen);
	}
	else if(3==m_iCurTab) m_list.SetItemText(n, 4, buf);
}

int CChangeDlg::FindCurMater()
{
	CString sStr= m_list.GetItemText(m_index, 2) + 
		m_list.GetItemText(m_index, 1) +
		m_list.GetItemText(m_index, 3);	
	
	CString buf, buf1, name;
	int i;

	for(i= 0; i<m_new_maters.GetSize(); i++)
	{
		CaplInstance* pdf_inst= NULL, *mater_inst= NULL, *new_mater_inst= m_new_maters[i].m_pdf;
		CString sPdf, sMater, sNewMater;
		int iPrior; double dValue; 
		CString sSortam, sUnit, sRazmer;

		if(m_api->m_data.IsKindOf(m_new_maters[i].m_pdr, m_api->m_prd_mgr.e_pdr))
		{
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_pdr_r_ting, pdf_inst);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_pdr_r_ted, mater_inst);	
			
			CaplInstance* inst= NULL;

			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_make_from_ranking, iPrior);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_make_from_assortment, inst);
			if(inst) m_api->m_data.GetAttr(inst, m_api->m_prd_mgr.a_assortment_name, sSortam);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_make_from_unit, inst);
			if(inst) m_api->m_charact_mgr.GetUnitName(inst, sUnit);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_make_from_value, dValue);
			m_api->m_data.GetAttr(m_new_maters[i].m_pdr, m_api->m_prd_mgr.a_pdr_id, sRazmer);

			if(mater_inst)
			{
				CaplInstance* prd_inst=NULL;
				m_api->m_data.GetAttr(mater_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
				if(prd_inst)
				{
					m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
					m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
					if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
				}

				m_api->m_data.GetAttr(mater_inst, m_api->m_prd_mgr.a_pdf_id, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			sMater.Format(_T("(%i) %s :%s {%s} [%.2f %s]"), iPrior, 
				sPdf, sRazmer, sSortam, dValue, sUnit);			
		}
		else if(m_api->m_data.IsKindOf(m_new_maters[i].m_pdr, m_api->m_prd_mgr.e_pdf))
		{
			pdf_inst= m_new_maters[i].m_pdr;
		}
		
		if(pdf_inst)
		{
			CaplInstance* prd_inst=NULL;
			m_api->m_data.GetAttr(pdf_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
			if(prd_inst)
			{
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			m_api->m_data.GetAttr(pdf_inst, m_api->m_prd_mgr.a_pdf_id, buf);
			if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			
			sMater+=sPdf;
		}

		if(new_mater_inst)
		{
			CaplInstance* prd_inst=NULL;
			m_api->m_data.GetAttr(new_mater_inst, m_api->m_prd_mgr.a_pdf_prd, prd_inst);
			if(prd_inst)
			{
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_id, sPdf);
				m_api->m_data.GetAttr(prd_inst, m_api->m_prd_mgr.a_prd_name, buf);
				if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}
			}

			m_api->m_data.GetAttr(new_mater_inst, m_api->m_prd_mgr.a_pdf_id, buf);
			if(!buf.IsEmpty()){if(!sPdf.IsEmpty())sPdf+=_T(":"); sPdf+=buf;}

			if(m_new_maters[i].m_sort) m_api->m_data.GetAttr(m_new_maters[i].m_sort, m_api->m_prd_mgr.a_assortment_name, buf);
			if(m_new_maters[i].m_unit) m_api->m_charact_mgr.GetUnitName(m_new_maters[i].m_unit, buf1);

			sNewMater.Format(_T("(%i) %s :%s {%s} [%.2f %s]"), m_new_maters[i].m_prior, 
				sPdf, m_new_maters[i].m_razmer, buf, 
				m_new_maters[i].m_value, buf1);

			sMater+=sNewMater;

			if(sStr==sMater) return i;
		}
	}	
	return -1;
}

int CChangeDlg::FindCurItem()
{
	CString buf= m_list.GetItemText(m_index, 2) + 
		m_list.GetItemText(m_index, 1) +
		m_list.GetItemText(m_index, 3);
	
	CString name, str;
	CaplInstance* inst= NULL, *pdf= NULL;
	int i;

	for(i= 0; i<m_new_items.GetSize(); i++)
	{
		name=_T(""); str=_T("");
		if(m_new_items[i].m_pdr)
		{
			if(apidata.IsKindOf(m_new_items[i].m_pdr, m_api->m_prd_mgr.e_pdr))
			{
				apidata.GetAttr(m_new_items[i].m_pdr, m_api->m_prd_mgr.a_pdr_r_ted, pdf);
				if(pdf) m_api->GetItemName(pdf, name);str+=name;					

				apidata.GetAttr(m_new_items[i].m_pdr, m_api->m_prd_mgr.a_pdr_r_ting, pdf);
			}
			else if(apidata.IsKindOf(m_new_items[i].m_pdr, m_api->m_prd_mgr.e_apl_pdf))
			{
				pdf= m_new_items[i].m_pdr;
			}
			
			if(pdf) m_api->GetItemName(pdf, name);
			str+=name;								
		}

		if(m_new_items[i].m_pdf)
		{				
			m_api->GetItemName(m_new_items[i].m_pdf, name);
			str+=name;					
		}
		
		if(buf==str)
		{
			return i;
		}
	}

	return -1;
}

int CChangeDlg::FindCurDoc()
{
	for(int i= 0; i<m_new_docs.GetSize(); i++)
	{
		if(m_new_docs[i].m_newVer==m_curItem)
		{
			return i;
		}
	}
	return -1;
}

int CChangeDlg::FindCurBP()
{
	for(int i= 0; i<m_new_bps.GetSize(); i++)
	{
		if(m_new_bps[i].m_newVer==m_curItem)
		{
			return i;
		}
	}
	return -1;	
}

int CChangeDlg::FindCurCharact()
{
	for (int i = 0; i < m_new_chars.GetSize(); i++)
	{
		if (m_new_chars[i].m_newVer == m_curItem)
		{
			return i;
		}
	}
	return -1;	
}

void CChangeDlg::OnDblclkChsItemsList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	if(-1!=m_index)
	{
		OnChsPropButton();
	}
	*pResult = 0;
}

void CChangeDlg::OnSelchangeSelectTab(NMHDR* pNMHDR, LRESULT* pResult) 
{
	m_iCurTab= m_tabCtrl.GetCurSel();
	if(m_iCurTab==0)//изделия
	{
		m_index= -1;
		m_propBtn.EnableWindow(FALSE);
		m_deleteBtn.EnableWindow(FALSE);
		ShowChangedItems();
	}
	else if(m_iCurTab==1)
	{
		m_index= -1;
		m_propBtn.EnableWindow(FALSE);
		m_deleteBtn.EnableWindow(FALSE);
		ShowChangedMaters();
	}
	else if(m_iCurTab==2)
	{
		m_index= -1;
		m_propBtn.EnableWindow(FALSE);
		m_deleteBtn.EnableWindow(FALSE);
		ShowChangedDocs();
	}
	else if(m_iCurTab==3)
	{
		m_index= -1;
		m_propBtn.EnableWindow(FALSE);
		m_deleteBtn.EnableWindow(FALSE);
		ShowChangedBPs();		
	}
	else if(m_iCurTab==4)
	{
		m_index= -1;
		m_propBtn.EnableWindow(FALSE);
		m_deleteBtn.EnableWindow(FALSE);
		ShowChangedCharacts();				
	}
	*pResult = 0;
}

bool CChangeDlg::CheckAccess()
{
	CaplInstance* rel= NULL, *pdf= NULL;

	if(!m_curItem) return true;

	if(m_api->m_data.IsKindOf(m_curItem, m_api->m_change_mgr.e_psc))
	{
		m_api->m_data.GetAttr(m_curItem, m_api->m_change_mgr.a_psc_changed_product, rel);
		if(!rel)
		{
			AfxMessageBox( APL_T("Измененяемая связь было удалена (сборка правилась вручную)!"), MB_OK|MB_ICONERROR);
			return false;
		}

		if(m_api->m_data.IsKindOf(rel, m_api->m_prd_mgr.e_pdr))
		{
			m_api->m_data.GetAttr(rel, m_api->m_prd_mgr.a_pdr_r_ting, pdf);
			if(!pdf)
			{
				AfxMessageBox( APL_T("Некорректная связь!!"), MB_OK|MB_ICONERROR);
				return false;
			}
			if(pdf->GetAccessmode()>aplRO) return false;
			m_api->m_data.GetAttr(rel, m_api->m_prd_mgr.a_pdr_r_ted, pdf);
			if(!pdf)
			{
				AfxMessageBox( APL_T("Некорректная связь!!"), MB_OK|MB_ICONERROR);
				return false;
			}
			if(pdf->GetAccessmode()>aplRO) return false;
		}
		else
		{
			if(rel->GetAccessmode()>aplRO) return false;
		}

		m_api->m_data.GetAttr(m_curItem, m_api->m_change_mgr.a_psc_changing_product, pdf);
		if(pdf && pdf->GetAccessmode()>aplRO) return false;
	}

	return true;
}

void CChangeDlg::OnAddAssemblyChange()
{
	if (m_bMenuAdd)
		AddChItem(0);
	else
		ShowChItemProp(0);
}

void CChangeDlg::OnAddSEChange()
{
	if (m_bMenuAdd)
		AddChItem(1);
	else
		ShowChItemProp(1);
}

void CChangeDlg::OnAddAssemblyGlobalChange()
{
//#ifdef _DEBUG
	CChangeWhereUsed dlg;

	if (m_bMenuAdd)
	{
		dlg.m_api = m_api;		
		dlg.m_change = m_change;	
		dlg.m_items = &m_items;
		dlg.m_newItems = &m_new_items;
		dlg.m_delItems = &m_del_items;

		if (IDOK == dlg.DoModal())
		{
			ShowChangedItems();
		}
	}
	else
	{
		dlg.m_api= m_api;
		
		dlg.m_bReadOnly = m_bReadOnly;
		dlg.m_change = m_change;
		
		dlg.m_items = &m_items;
		dlg.m_newItems = &m_new_items;
		dlg.m_delItems = &m_del_items;
		
		if (m_curItem)
		{
			dlg.m_psc = m_curItem;
		}
		else
		{
			int n= FindCurItem();
			if (-1 != n)
			{
				dlg.m_pscInfo = m_new_items[n];
			}
		}
		
		if (IDOK == dlg.DoModal())
		{
			ShowChangedItems();
		}
	}
//#endif
}
void CChangeDlg::OnBnClickedChnStartEditButton()
{
	if(!m_change) return;
	if(!m_api->m_change_mgr.ReturnChangeToEdit(m_change)) return;

	SetControlsState();
}

void CChangeDlg::OnBnClickedChnNotesButton()
{
	if(m_change)
		m_api->m_change_mgr.ShowNotes(m_change);
}

void CChangeDlg::OnBnClickedChooseBasisCode()
{
	CString buf;
	CaplInstance *system=0;
	
	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Изменения\\Справочник кодов причин изменений"),buf,0);
	if(buf!=_T(""))
	{
		system = m_api->m_classifier_mgr.GetClassifierSystemById(buf,true);
		if(0==system) 
			AfxMessageBox(APL_T("Не найден справочник указанный в настройке:\n 'Изменения\\Справочник кодов причин изменений'!!!"));
	}

	if(0==system) system=m_api->m_classifier_mgr.GetClassifierSystemById( APL_NO_T("КПИ"));

	CaplInstance *ciMater=0;
	if(!m_api->m_classifier_mgr.SelectItem(&ciMater,system,APL_SELECT_CLASSIFIER_LEVEL, APL_T("Выберите причину изменения:"))) return;

	if(!ciMater) return;

	m_api->m_data.GetAttr(ciMater, m_api->m_classifier_mgr.a_apl_classifier_level_id, m_sBasisCode);
	m_api->m_data.GetAttr(ciMater, m_api->m_classifier_mgr.a_apl_classifier_level_name, m_sBasis);

	((CEdit*)GetDlgItem(IDC_REASON_CODE))->SetWindowText(m_sBasisCode);
	((CEdit*)GetDlgItem(IDC_CHS_BASIS))->SetWindowText(m_sBasis);
}

void CChangeDlg::OnBnClickedChooseUsage()
{
	m_sUsage=_T("");
	
	int i = 0;
	CString t_str;
	CaplInstance *ciDoc = NULL;
	aplExtent aeAVCItems, aeAllPrdUsage;
	GetExistingAVCItems(aeAVCItems);

	// ищем все применения у существующих AVC
	for(i=0; i<aeAVCItems.Size; i++)
	{
		m_api->m_data.GetAttr(aeAVCItems[i], m_api->m_change_mgr.a_avc_doc, ciDoc);
		if(0==ciDoc) continue;

		FindAllDocUsage(ciDoc, aeAllPrdUsage);
	}

	// ищем все применения у новых элементов
	for(i=0; i<m_new_docs.GetSize(); i++)
	{
		if(0!=m_new_docs[i].m_newVer)
		{
			m_api->m_data.GetAttr(m_new_docs[i].m_newVer, m_api->m_doc_mgr.a_apl_doc_rev_doc, ciDoc);
			if(0==ciDoc) continue;
			FindAllDocUsage(ciDoc, aeAllPrdUsage);
		}
		else aeAllPrdUsage.Clear();

	}

	// выводим обозначения изделий в поле
	for(i=0; i<aeAllPrdUsage.Size; i++)
	{
		m_api->m_data.GetAttr(aeAllPrdUsage[i], m_api->m_prd_mgr.a_prd_id, t_str);
		m_sUsage += t_str + _T(", ");
	}

	m_sUsage.Delete(m_sUsage.GetLength()-2, 2);
	((CEdit*)GetDlgItem(IDC_USAGE))->SetWindowText(m_sUsage);
}

void CChangeDlg::FindAllDocUsage(CaplInstance *ciDoc, aplExtent &aeAllPrdUsage)
{
	int i= 0;
	CaplAttrValue Val;
	aplExtent aeExt, aePdf;
	aplExtent aeOutRel, aeOutPdf;
	CaplInstance *ciItem = NULL;

	if(0==ciDoc) return;

	Val.attr = m_api->m_doc_mgr.a_apl_doc_ref_doc;
	Val.value.Set(ciDoc);

	// ищем связи документа
	m_api->m_data.NET_FindInstancesWithAttrValues(m_api->m_doc_mgr.e_apl_doc_ref, 1, &Val, aeExt, false);
	
	// отфильтровываем только связи на изделиях
	m_api->LoadExtentInfo(aeExt);
	for(i=0; i<aeExt.Size; i++)
	{
		m_api->m_data.GetAttr(aeExt[i], m_api->m_doc_mgr.a_apl_doc_ref_item, ciItem);
		if(m_api->m_data.IsKindOf(ciItem, m_api->m_prd_mgr.e_pdf)) aePdf.Add(ciItem);
	}

	// узнеам, где используются эти изделия
	m_api->m_prd_mgr.WhereUsedProduct(aePdf, aeOutRel, aeOutPdf);
	for(i=0; i<aeOutPdf.Size; i++)
	{
		m_api->m_data.GetAttr(aeOutPdf[i], m_api->m_prd_mgr.a_pdf_prd, ciItem);
		aeAllPrdUsage.Add(ciItem);
	}
}

// серия применения (правило применяемости)
void CChangeDlg::OnBnClickedEditSeria()
{
	if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) 
	{
		CString sSprav;
		m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Изменения\\Справочник зависимых объектов"), sSprav);
		if(sSprav!=_T(""))
		{
			CaplInstance *item=0, *sprav=m_api->m_classifier_mgr.GetClassifierSystemById(sSprav);
			if(0==sprav) AfxMessageBox(APL_T("Не найден справочник указанный в настройке 'Изменения\\Справочник зависимых объектов'!!!"));

			if(m_api->m_prd_mgr.EditExtent(APL_MODE_SELECT_PDF,m_dependent_items,APL_T("Зависимые изделия:"),APL_T("Список изделий"),sprav))
			{
				CString buf;
				m_api->GetItemsName(m_dependent_items,buf);
				m_sSeriaPrimenCtrl.SetWindowText(buf);
			}
		}
		else AfxMessageBox(APL_T("Не задан справочник  в настройке 'Изменения\\Справочник зависимых объектов'!!!"));
		return;
	}
	m_api->m_change_mgr.SetChangeEffectivity(m_change, m_sEffType, m_sSeriaPrimenStart, m_sSeriaPrimenEnd);
	GetEffectivityDscr();
	UpdateData(FALSE);
}

void CChangeDlg::GetEffectivityDscr()
{
	m_sSeriaPrimen = _T("");
	if(m_sEffType==_T("dated"))
	{
		COleDateTime odt;
		CString buf;
		if(!m_sSeriaPrimenStart.IsEmpty()) 
		{
			aplString2Date(m_sSeriaPrimenStart, odt);
			m_sSeriaPrimen= APL_T("с: ") + odt.Format(_T("%d/%m/%Y"))+_T(" ");
		}

		if(!m_sSeriaPrimenEnd.IsEmpty())
		{
			aplString2Date(m_sSeriaPrimenEnd, odt);
			m_sSeriaPrimen+= APL_T("по: ") + odt.Format(_T("%d/%m/%Y"))+_T(" ");
		}
	}
	else if(m_sEffType==_T("numbered"))
	{
		if(!m_sSeriaPrimenStart.IsEmpty())
			m_sSeriaPrimen= APL_T("с: ")+m_sSeriaPrimenStart+_T(" ");
		if(!m_sSeriaPrimenEnd.IsEmpty())
			m_sSeriaPrimen+= APL_T("по: ")+m_sSeriaPrimenEnd;
	}
	else if(m_sEffType==_T("none"))
	{
		m_sSeriaPrimen = APL_T("По дате проведения изменения");
	}
}
void CChangeDlg::OnBnClickedCreateIi()
{
	if(0==m_change){AfxMessageBox(APL_T("Изменение еще не сохранено в БД!")); return;}
	if(0==m_pGenerateII) return;

	if(!SaveInOk()) return;

	aplExtent ext;
	ext.Add(m_change);
	m_pGenerateII(m_api,ext,false);
}

void CChangeDlg::OnCbnSelchangeType()
{
	CString sId,sType,buf;
	m_type_ctrl.GetWindowText(sType);
	if(sType==APL_T("ИИ"))sType=_T("");
	m_idCtrl.GetWindowText(sId);
	if(m_sType!=_T("")) sId.Replace(m_sType,sType);
	buf=sId; buf.MakeUpper();
	if(sType!=_T(""))
	{
		if(buf.Find(sType)<0) sId+=sType;  
	}
	m_idCtrl.SetWindowText(sId);
	m_sType=sType;

	if(sType==APL_T("ПИ") || sType==APL_T("ДПИ")) 
	{
		m_validity_pi_date_ctrl.EnableWindow(TRUE);
		m_st_src_pi.SetWindowText(APL_T("Погашающее ИИ:"));
	}
	else
	{
		m_validity_pi_date_ctrl.EnableWindow(FALSE);
		m_st_src_pi.SetWindowText(APL_T("Погашаемое ПИ:"));
	}
}

void CChangeDlg::OnBnClickedViewIi()
{
	if(!SaveInOk()) return;
	CString sId;
	m_idCtrl.GetWindowText(sId);
	CaplInstance *doc=m_api->m_doc_mgr.FindDocById(sId);
	if(0==doc){AfxMessageBox(APL_T("Извещение не создано!"),MB_OK|MB_ICONSTOP); return;}
	m_api->m_doc_mgr.ViewWithMarkView(doc);
	EndDialog(0);
}

void CChangeDlg::OnNMRClickChsItemsList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;

	CMenu menu;CMenu* pPopup;
	VERIFY(menu.LoadMenu(IDR_CONTEXT_MENU1));
	CaplMenu::Install(this);
	pPopup = menu.GetSubMenu(0);

	CPoint point=pNMItemActivate->ptAction;
	m_list.ClientToScreen(&point);

	if(pNMItemActivate->iItem<0)
	{
		pPopup->RemoveMenu(ID_EDIT_COPY, MF_BYCOMMAND);
		pPopup->RemoveMenu(ID_EDIT_COPY_CELL, MF_BYCOMMAND);
	}
	else if(pNMItemActivate->iSubItem<0)pPopup->RemoveMenu(ID_EDIT_COPY_CELL, MF_BYCOMMAND);

	BOOL res=pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON |TPM_RETURNCMD,	point.x, point.y,this); // use main window for cmds
	switch(res)
	{
	case ID_FILE_SAVE:
		apl_SaveListCtrlToFile(&m_list,_T(""),_T(""));
		 break;
	case ID_EDIT_COPY_CELL:
		{
			CString text;
			if(pNMItemActivate->iItem>=0)
			{
				if(pNMItemActivate->iSubItem<0 )pNMItemActivate->iSubItem=0;
				text=m_list.GetItemText(pNMItemActivate->iItem,pNMItemActivate->iSubItem);
			}
			if(text!=_T(""))
			{
				COleDataSource*	pSource = new COleDataSource();
				if(pSource==0) return;
				HGLOBAL hMem;

				hMem=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT,sizeof(TCHAR)*(text.GetLength()+1));
				if (!hMem) return;
				TCHAR *xxx=(TCHAR*)GlobalLock(hMem);
				memcpy(xxx,LPCTSTR(text),sizeof(TCHAR)*(text.GetLength()+1));		
				GlobalUnlock(hMem);
				pSource->CacheGlobalData(CF_TEXT, hMem);
				pSource->SetClipboard();
			}

		}	break;
	case ID_EDIT_COPY:
		{
			COleDataSource*	pSource = new COleDataSource();
			if(pSource==0) return;
			HGLOBAL hMem;

			CString text,text1;
			text.Empty();
			CHeaderCtrl* hc=m_list.GetHeaderCtrl();
			if(hc==0)return;
			int col_max=hc->GetItemCount();

			TCHAR buf[256];
			HDITEM HeaderItem;
			HeaderItem.mask = HDI_TEXT;
			HeaderItem.pszText = buf;
			HeaderItem.cchTextMax = 256;

			int line=pNMItemActivate->iItem;
			if(line<0) return;

			for(int col=0;col<col_max;col++){
				if(col!=0){text+=_T("; ");}
				hc->GetItem(col, &HeaderItem);
				text += buf;
				text +=_T(": ");
				text1=m_list.GetItemText(line,col);
				text+=text1;
			}

			hMem=GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT,sizeof(TCHAR)*(text.GetLength()+1));
			if (!hMem) return;
			TCHAR *xxx=(TCHAR*)GlobalLock(hMem);
			memcpy(xxx,LPCTSTR(text),sizeof(TCHAR)*(text.GetLength()+1));		
			GlobalUnlock(hMem);
			pSource->CacheGlobalData(CF_TEXT, hMem);
			pSource->SetClipboard();

		}
		break;
	case ID_COPY_CELL:
		break;
	}


}


void CChangeDlg::OnBnClickedSelEnterprise()
{
	CString buf,sTopOrgId;
	//if(m_api->m_options_mgr.CheckInstallCode(_T("grpz"))) sTopOrgId=APL_T("АО \"ГРПЗ\"");
	//else

	CString sSprav;
	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Изменения\\Справочник предприятий"), sSprav);
	if(sSprav!=_T(""))
	{
		CaplInstance *org=0, *sprav=m_api->m_classifier_mgr.GetClassifierSystemById(sSprav);
		if(0==sprav) AfxMessageBox(APL_T("Не найден справочник указанный в настройке 'Изменения\\Справочник предприятий'!!!"));
		m_api->m_classifier_mgr.SelectItem(&org,sprav);
		if(0==org) return;

		CString sId;
		m_api->m_data.GetAttr(org,m_api->m_appr_mgr.a_org_id,sId);
		if(sId!=_T("")) m_sOrgCodeCtrl.SetWindowText(sId);
		return;
	}


	if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие")))sTopOrgId=APL_T("Контрагенты");
	CaplInstance *org=0;
	aplExtent ext; 

	if(sTopOrgId!=_T(""))
	{
		CaplInstance *org1=m_api->m_appr_mgr.FindOrganizationById(sTopOrgId);
		if(0==org1)
		{
			buf.Format(APL_T("Не найдена корневая рабочая группа!\n(%s)"),LPCTSTR(sTopOrgId));
			AfxMessageBox(buf);
		}
		else ext.Add(org1);
	}

	m_api->m_appr_mgr.SelectOrganization(&org,APL_T("Выберите подразделение"),&ext);
	if(org!=0)
	{
		CString sId;
		m_api->m_data.GetAttr(org,m_api->m_appr_mgr.a_org_id,sId);
		if(sId!=_T("")) m_sOrgCodeCtrl.SetWindowText(sId);
	}
}


void CChangeDlg::OnBnClickedSelWg()
{
	CString buf,sTopOrgId;
	if(m_api->m_options_mgr.CheckInstallCode(_T("grpz"))) sTopOrgId=APL_T("АО \"ГРПЗ\"");
	else if(m_api->m_options_mgr.CheckInstallCode(APL_NO_T("Созвездие"))) sTopOrgId=APL_T("АО \"Концерн \"Созвездие\"");

	CaplInstance *org=0;
	aplExtent ext; 

	if(sTopOrgId!=_T(""))
	{
		CaplInstance *org1=m_api->m_appr_mgr.FindOrganizationById(sTopOrgId);
		if(0==org1)
		{
			buf.Format(APL_T("Не найдена корневая рабочая группа!\n(%s)"),LPCTSTR(sTopOrgId));
			AfxMessageBox(buf);
		}
		else ext.Add(org1);
	}

	m_api->m_appr_mgr.SelectOrganization(&org,APL_T("Выберите подразделение"),&ext);
	if(org!=0)
	{
		CString sId;
		m_api->m_data.GetAttr(org,m_api->m_appr_mgr.a_org_id,sId);
		if(sId!=_T("")) m_sGrpNumCtrl.SetWindowText(sId);
	}
}

void CChangeDlg::OnBnClickedGenerateChangeId()
{
	CString buf,idnew;
	m_idCtrl.GetWindowText(buf);

	if(! (buf==_T("") || buf==APL_T("<Автономер>")))
	{
		if(IDYES!=AfxMessageBox(APL_T("Обозначение уже задано!\n\nДействительно сгенерировать новое?"),MB_ICONWARNING|MB_YESNO)) return;
	}
	m_api->m_change_mgr.GenerateChangeId(idnew);
	if(idnew==buf) {AfxMessageBox(APL_T("Текущее обозначение не используется.\n\n Оставлено текущее обозначение."),MB_ICONWARNING|MB_OK); return;}
	m_idCtrl.SetWindowText(idnew);
}
