// FindPrdInstDlgEx.cpp : implementation file
//

#include "stdafx.h"
#include "FindPrdInstDlgEx.h"


// CFindPrdInstDlgEx dialog

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

/////////////////////////////////////////////////////////////////////////////
// CFindPrdInstDlgEx dialog
#define aplShowDebugInformation false

CFindPrdInstDlgEx::CFindPrdInstDlgEx(CaplAPI* api, TFindPrdInstModes Mode, UINT Flags, CWnd* pParent /*=NULL*/)
: CaplTranslateDialog(CFindPrdInstDlgEx::IDD, pParent)
{
	ASSERT(api);
	ASSERT(api->m_expl_mgr);
	m_api = api;
	m_ExploitationMgr = (CaplPreExploitationMgr*)api->m_expl_mgr;
	m_iPlaner = NULL;
	m_SelectedItem = NULL;
	m_Mode = Mode;
	//m_UserFunct = NULL;
	m_UserDw = 0;

	m_Flags = Flags;
	//{{AFX_DATA_INIT(CFindPrdInstDlgEx)
	m_sSN = _T("");
	m_sName = _T("");
	m_sId = _T("");
	//}}AFX_DATA_INIT
}
/*
CFindPrdInstDlgEx::CFindPrdInstDlgEx(CaplAPI* api, TFindPrdInstModes Mode, LPUserFindFunct lpFunct, DWORD dwData, UINT Flags, CWnd* pParent )
: CaplTranslateDialog(CFindPrdInstDlgEx::IDD, pParent)
{
	ASSERT(api);
	ASSERT(api->m_expl_mgr);
	if(Mode==aplFindPrdInstCallback)
		ASSERT(lpFunct);
	m_UserDw = dwData;
	m_UserFunct = lpFunct;
	m_api = api;
	m_ExploitationMgr = (CaplPreExploitationMgr*)api->m_expl_mgr;
	m_iPlaner = NULL;
	m_SelectedItem = NULL;
	m_Mode = Mode;

	m_Flags = Flags;
	//MY_AFX_DATA_INIT(CFindPrdInstDlgEx)
	m_sSN = _T("");
	m_sName = _T("");
	m_sId = _T("");
	//MY_AFX_DATA_INIT
}
*/

void CFindPrdInstDlgEx::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFindPrdInstDlgEx)
	DDX_Control(pDX, IDC_CREATE, m_create_btn);
	DDX_Control(pDX, IDC_FIND, m_find_btn);
	DDX_Control(pDX, IDC_RESULT, m_ResultCtrl);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDC_CHECK_INCLUDE_ANALOGS, m_check_include_analogs);
	DDX_Text(pDX, IDC_SN, m_sSN);
	DDX_Text(pDX, IDC_NAME, m_sName);
	DDX_Text(pDX, IDC_ID, m_sId);
	DDX_Check(pDX, IDC_CHECK_INCLUDE_ANALOGS, m_bIncludeAnalogs);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CFindPrdInstDlgEx, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CFindPrdInstDlgEx)
	ON_BN_CLICKED(IDC_FIND, OnFind)
	ON_NOTIFY(NM_DBLCLK, IDC_RESULT, OnDblclkResult)
	ON_BN_CLICKED(IDC_CREATE, OnCreate)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFindPrdInstDlgEx message handlers

BOOL CFindPrdInstDlgEx::OnInitDialog() 
{
	CaplTranslateDialog::OnInitDialog();

	if(!m_api->m_data.IsDictLoad())
	{
		AfxMessageBox( APL_T("Соединение не установлено!"), MB_OK|MB_ICONSTOP);
		EndDialog(0);
		return FALSE;
	}

	SetIcon(aplGetButtonIco(APL_24_FIND), FALSE);

	m_ok_btn.SetIcon(aplGetButtonIco(APL_24_OK));
	m_ok_btn.SetFlat(FALSE);
	m_cancel_btn.SetIcon(aplGetButtonIco(APL_24_CANCEL));
	m_cancel_btn.SetFlat(FALSE);

	m_find_btn.SetIcon(aplGetButtonIco(APL_24_FIND));
	m_find_btn.SetFlat(FALSE);

	m_create_btn.SetIcon(aplGetButtonIco(APL_24_PKI));
	m_create_btn.SetFlat(FALSE);

	//Отрабатываем флаги
	if(m_Flags&APL_FD_SHOW_CREATE_BTN)
		m_create_btn.ShowWindow(SW_SHOW);
	if(m_Flags&APL_FD_DISABLE_ID)
		((CEdit*)GetDlgItem(IDC_ID))->SetReadOnly(TRUE);
	if(m_Flags&APL_FD_DISABLE_NAME)
		((CEdit*)GetDlgItem(IDC_NAME))->SetReadOnly(TRUE);
	if(m_Flags&APL_FD_DISABLE_SN)
		((CEdit*)GetDlgItem(IDC_SN))->SetReadOnly(TRUE);

	RECT rect_check, rect_list;
	if (m_Flags & APL_FD_INCLUDE_ANALOGS)
	{
		// включать аналоги
		m_check_include_analogs.ShowWindow(SW_SHOW);

		// поднимаем список
		m_check_include_analogs.GetWindowRect(&rect_check);
		m_ResultCtrl.GetWindowRect(&rect_list);
		rect_list.bottom -= (rect_check.bottom-rect_check.top) + 4;
		ScreenToClient(&rect_list);
		m_ResultCtrl.MoveWindow(&rect_list);
	}
	else
	{
		// не включать аналоги

		m_check_include_analogs.ShowWindow(SW_HIDE);
	}

	//Заполнение полей в таблице
	CRect rect;
	int p1, p2, p3;
	bool bShowPlaceColumn = false;// aplShowPlaceColumn;
	bool bShowStateColumn = false; //aplShowStateColumn;
	m_PlaceColInd = bShowPlaceColumn==TRUE ? 3 : -1;
	m_StateColInd = bShowStateColumn==TRUE ? (m_PlaceColInd>-1 ? 4 : 3) : -1;
	m_ResultCtrl.GetClientRect(&rect);
	if(bShowPlaceColumn==FALSE && bShowStateColumn==FALSE)
	{
		p1 = 20; p2 = 60; p3 = 20;
	}
	else if(bShowStateColumn==FALSE)
	{
		p1 = 20; p2 = 50; p3 = 15;
	}
	else if(bShowPlaceColumn==FALSE)
	{
		p1 = 20; p2 = 50; p3 = 20;
	}
	else
	{
		p1 = 15; p2 = 45; p3 = 15;
	}
	rect.right-=14;
	m_ResultCtrl.InsertColumn(0,  APL_T("Шифр"), LVCFMT_LEFT, (int)(rect.Width()*(0.01*p1)));
	m_ResultCtrl.InsertColumn(1,  APL_T("Наименование"), LVCFMT_LEFT, (int)(rect.Width()*(0.01*p2)));
	m_ResultCtrl.InsertColumn(2,  APL_T("Серийный номер"), LVCFMT_LEFT, (int)(rect.Width()*(0.01*p3)));
	if(m_PlaceColInd>-1)
		m_ResultCtrl.InsertColumn(m_PlaceColInd,  APL_T("Текущее положение"), LVCFMT_LEFT, (int)(rect.Width()*0.15));
	if(m_StateColInd>-1)
		m_ResultCtrl.InsertColumn(m_StateColInd,  APL_T("Состояние"), LVCFMT_LEFT, (int)(rect.Width()*0.1));

	UpdateData(FALSE);

	m_sBaseName = m_sName;
	m_sBaseId = m_sId;

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

void CFindPrdInstDlgEx::OnFind() 
{
	if(!UpdateData()) return;

	if(m_sId.IsEmpty() && m_sName.IsEmpty() && m_sSN.IsEmpty())
	{
		if(MessageBox( APL_T("Не заданы критерии поиска. Отобразить все комплектующие изделия в БД?"),  APL_T("Поиск"), MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2)!=IDYES)
			return;
	}
	else if ((m_Flags & APL_FD_INCLUDE_ANALOGS) && !CheckCorrect())
	{
		AfxMessageBox( APL_T("Введены некорректные данные для поиска!"), MB_OK|MB_ICONINFORMATION);
		return;
	}

	if(m_Mode==aplFindPrdInstToRefusal)
		FindToRefusals();
	else if(m_Mode==aplFindAllPrdInst)
		FindAllPrdInst();
	else if(m_Mode==aplFindInstalledPrdInst)
		FindInstalledPrdInst();
	else if(m_Mode==aplFindNonused)
		FindNonUsed();
	/*else if(m_Mode==aplFindPrdInstCallback)
	{
		aplExtent ext;
		BeginWaitCursor();
		if (m_Flags & APL_FD_INCLUDE_ANALOGS)
		{
			DWORD* pDW = (DWORD*)m_UserDw;
			pDW[1] = (DWORD)m_bIncludeAnalogs;
		}
		if(m_UserFunct(m_api, ext, m_UserDw, m_sId, m_sName, m_sSN))
			ShowResult(ext);
		EndWaitCursor();
	}*/
	else if(m_Mode==aplFindItemChilds)
		FindItemChilds();
	else 
	{
		AfxMessageBox( APL_T("Не задан алгоритм поиска комплектующих!"), MB_OK|MB_ICONINFORMATION);
		return;
	}
}

void CFindPrdInstDlgEx::ShowResult(aplExtent &ext)
{
	BeginWaitCursor();
	m_ResultCtrl.DeleteAllItems();
	int i, ind=-1;
	CString sn, id, name, buf, state, pos, pdf_id;
	CString sPlaner, sItem;
	CaplInstance *pdf, *prd;//* *rel, *inst, *planer;

	for(i=0; i<ext.GetSize(); i++)
	{
		buf.Empty();

		if(ext[i]==NULL) continue;
		if(ext[i]->GetAccessmode()>aplRO) continue;

		m_api->m_data.GetAttr(ext[i], m_api->m_prd_inst_mgr.a_prd_inst_pdf, pdf);
		if(pdf==NULL) continue;
		//if(m_ExploitationMgr->IsPlaner(pdf)) continue;

		m_api->m_data.GetAttr(ext[i], m_api->m_prd_inst_mgr.a_prd_inst_sn, sn);
		m_api->m_data.GetAttr(ext[i], m_api->m_prd_inst_mgr.a_prd_inst_state, state);

		/*if(m_PlaceColInd>-1)
		{
			rel = m_ExploitationMgr->FindActualRelation(ext[i], aplCompositionDate, false);
			if(rel)
			{
				m_api->m_data.GetAttr(rel, m_api->m_prd_inst_mgr.a_prd_inst_rel_relating, inst);
				if(inst)
					m_ExploitationMgr->GetPKIName(inst, sItem);
				m_api->m_data.GetAttr(rel, m_api->m_prd_inst_mgr.a_prd_inst_rel_place, planer);
				if(planer && planer!=inst)
				{
					m_ExploitationMgr->GetPKIName(planer, sPlaner);
					if(sItem.IsEmpty()) buf = sPlaner;
					else if(!sPlaner.IsEmpty()) buf.Format(_T("%s %s"), sPlaner, sItem);
					else buf = sItem;
				}
				else
					buf = sItem;
			}
		}*/

		if(pdf==NULL) continue;
		if(pdf->GetAccessmode()>aplRO) continue;
		m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_pdf_prd, prd);
		m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_pdf_id, pdf_id);
		if(prd==NULL) continue;
		if(prd->GetAccessmode()>aplRO) continue;
		m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, id);
		m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, name);

		if(!pdf_id.IsEmpty()) id +=_T(" : ")+pdf_id;
		ind = m_ResultCtrl.InsertItem(m_ResultCtrl.GetItemCount(), id);
		m_ResultCtrl.SetItemText(ind, 1, name);
		m_ResultCtrl.SetItemText(ind, 2, sn);
		if(m_PlaceColInd>-1)
			m_ResultCtrl.SetItemText(ind, m_PlaceColInd, buf);
		if(m_StateColInd>-1)
			m_ResultCtrl.SetItemText(ind, m_StateColInd, state);
		m_ResultCtrl.SetItemData(ind, (DWORD)(ext[i]));
	}
	m_ResultCtrl.ReSort();
	EndWaitCursor();
	if(ind>-1)
	{
		//if(aplShowFoundAmountMessage)
		{
			buf.Format( APL_T("Найдено %d комплектующих изделий!"), ind+1);
			MessageBox(buf,  APL_T("Результаты поиска"), MB_OK|MB_ICONINFORMATION);
		}
	}
	else
	{
		//if(aplShowNotFoundMessage)
		{
			buf.Format( APL_T("Ничего не найдено!"));
			MessageBox(buf,  APL_T("Результаты поиска"), MB_OK|MB_ICONINFORMATION);
		}
	}
}

void CFindPrdInstDlgEx::OnOK() 
{
	int cur=m_ResultCtrl.GetNextItem(-1, LVIS_SELECTED);
	if(cur<0)
	{
		AfxMessageBox( APL_T("Необходимо выбрать комплектующее изделие!"));
		return;
	}

	m_SelectedItem = (CaplInstance*)m_ResultCtrl.GetItemData(cur);

	CaplTranslateDialog::OnOK();
}

void CFindPrdInstDlgEx::FindToRefusals()
{
	if(!UpdateData())
		return;

	m_sId.TrimLeft();
	m_sId.TrimRight();
	m_sName.TrimLeft();
	m_sName.TrimRight();
	m_sSN.TrimLeft();
	m_sSN.TrimRight();

	CString date_filter, Date;
	aplDate2String(COleDateTime::GetCurrentTime(), Date);
	date_filter.Format(_T(".date_installed_s<='%s' AND (.date_removed_s = '' OR .date_removed_s >= '%s')"), Date, Date);

	CString sQuery;
	aplExtent ext;
	if(m_api->m_data.IsConnected())
	{
		if(m_iPlaner)
		{
			if(m_iPlaner->GetId()==0)
				m_api->SaveChanges();
			sQuery.Format(_T("SELECT ext FROM ")\
				_T("ext1 {apl_product_instance(.formation->apl_product_definition_formation(.of_product->product(.id LIKE_LEFT '%s' AND .name LIKE_LEFT '%s' ) AND . formation_type !='system') AND .serial_number LIKE_LEFT '%s')}")\
				_T("ext {apl_component(.related_product_instance IN #ext1 AND .place = #%d AND %s)}.related_product_instance ")\
				_T("END_SELECT"), m_sId, m_sName, m_sSN, m_iPlaner->GetId(), date_filter);
		}
		else
		{
			sQuery.Format(_T("SELECT ext FROM ")\
				_T("ext {apl_product_instance(.formation->apl_product_definition_formation(.of_product->product(.id LIKE_LEFT '%s' AND .name LIKE_LEFT '%s' ) AND . formation_type !='system') AND .serial_number LIKE_LEFT '%s')}")\
				_T("END_SELECT"), m_sId, m_sName, m_sSN);
		}

		if(m_api->m_data.NET_QueryEditParse(sQuery, false))// aplShowDebugInformation))
		{
			BeginWaitCursor();
			m_api->m_data.NET_QueryExecute(ext);
			m_api->m_prd_inst_mgr.LoadExtentInfo(ext);
			//if(aplShowPlaceColumn)
			//	m_ExploitationMgr->FindActualRelations(ext, NULL);
			ShowResult(ext);
			EndWaitCursor();
		}
		else
		{
			AfxMessageBox( APL_T("Не верно составлен запрос!"), MB_ICONSTOP|MB_OK);
		}
	}
	else
	{
		aplExtent tmp;
		CString pdf_type;
		CaplInstance *prd, *pdf, *rel_prd_inst, *place;
		CString DateInstall, DateRemove;
		m_api->m_data.GetEntityExtent(m_api->m_prd_inst_mgr.e_apl_component, tmp);
		for(int i=0; i<tmp.GetSize(); i++)
		{
			m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_place, place);
			if(place != m_iPlaner)
				continue;
			m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_related, rel_prd_inst);
			if(NULL == rel_prd_inst)
				continue;
			m_api->m_data.GetAttr(rel_prd_inst, m_api->m_prd_inst_mgr.a_prd_inst_pdf, pdf);
			if(NULL == pdf)
				continue;
			m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_apl_pdf_type, pdf_type);
			if(0!=pdf_type.CollateNoCase(_T("system")))
			{
				//m_sId, m_sName, m_sSN//, m_iPlaner->id;
				CString sId, sName, sSN;
				m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_pdf_prd, prd);
				if(NULL == prd)
					continue;
				m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, sId);
				m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, sName);
				m_api->m_data.GetAttr(rel_prd_inst, m_api->m_prd_inst_mgr.a_prd_inst_id, sSN);
				sId.MakeLower(); sName.MakeLower(); sSN.MakeLower();
				m_sId.MakeLower(); m_sName.MakeLower(); m_sSN.MakeLower();
				if(0==sId.Find(m_sId, 0) && 0==sName.Find(m_sName) && 0==sSN.Find(m_sSN)) 
				{
					m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_date_installed, DateInstall);
					m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_date_removed, DateRemove);
					if(DateInstall<=Date && (DateRemove.IsEmpty() || DateRemove>=Date))
						ext.Add(rel_prd_inst);
				}
			}
		}		
		ShowResult(ext);
	}
}

void CFindPrdInstDlgEx::OnDblclkResult(NMHDR* pNMHDR, LRESULT* pResult) 
{
	OnOK();

	*pResult = 0;
}

void CFindPrdInstDlgEx::FindAllPrdInst()
{
	if(!UpdateData())
		return;

	m_sId.TrimLeft();
	m_sId.TrimRight();
	m_sName.TrimLeft();
	m_sName.TrimRight();
	m_sSN.TrimLeft();
	m_sSN.TrimRight();

	long DlgId = aplStartWaitDlg( APL_T("Выполняется поиск"),  APL_T("Поиск"));
	if(m_api->m_data.IsConnected())
	{
		CString sQuery;
		aplExtent ext;

		if(m_iPlaner)
		{
			if(m_iPlaner->GetId()==0)
				m_api->SaveChanges();
			sQuery.Format(_T("SELECT ext FROM ")\
				_T("ext1 {apl_product_instance(.formation->apl_product_definition_formation(.of_product->product(.id LIKE_LEFT '%s' AND .name LIKE_LEFT '%s' ) AND . formation_type !='system') AND .serial_number LIKE_LEFT '%s')}")\
				_T("ext {apl_component(.related_product_instance IN #ext1 AND .place = #%d)}.related_product_instance ")\
				_T("END_SELECT"), m_sId, m_sName, m_sSN, m_iPlaner->GetId());
		}
		else
		{
			sQuery.Format(_T("SELECT ext FROM ")\
				_T("ext {apl_product_instance(.formation->apl_product_definition_formation(.of_product->product(.id LIKE_LEFT '%s' AND .name LIKE_LEFT '%s' ) AND . formation_type !='system') AND .serial_number LIKE_LEFT '%s')}")\
				_T("END_SELECT"), m_sId, m_sName, m_sSN);
		}

		if(m_api->m_data.NET_QueryEditParse(sQuery, aplShowDebugInformation))
		{
			BeginWaitCursor();
			m_api->m_data.NET_QueryExecute(ext);
			m_api->m_prd_inst_mgr.LoadExtentInfo(ext);
			//if(aplShowPlaceColumn)
			//	m_ExploitationMgr->FindActualRelations(ext, NULL);
			aplEndWaitDlg(DlgId);
			ShowResult(ext);
			EndWaitCursor();
		}
		else
		{
			aplEndWaitDlg(DlgId);
			AfxMessageBox( APL_T("Не верно составлен запрос!"), MB_ICONSTOP|MB_OK);
		}
	}
	else if(m_api->m_data.IsDictLoad())
	{
		aplExtent ext;
		int i, sn_l = m_sSN.GetLength(), name_l = m_sName.GetLength(), id_l = m_sId.GetLength();
		CaplInstance *Prd, *Pdf;
		CString id, name, sn, buf;
		bool bId, bName, bSN;
		m_api->m_data.GetEntityExtent(m_api->m_prd_inst_mgr.e_prd_inst, ext);

		if(!m_sId.IsEmpty() || m_sName.IsEmpty() || m_sSN.IsEmpty())
		{
			aplExtent tmp;
			tmp.Append(ext);
			ext.Clear();
			for(i=0; i<tmp.GetSize(); i++)
			{
				bId = false;
				bName = false;
				bSN = false;
				m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_sn, sn);
				if(sn.Left(sn_l).CompareNoCase(m_sSN)==0 || m_sSN.IsEmpty())
					bSN = true;
				if(bSN)
				{
					m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_pdf, Pdf);
					if(Pdf)
					{
						m_api->m_data.GetAttr(Pdf, m_api->m_prd_mgr.a_apl_pdf_type, buf);
						if(buf.CompareNoCase(_T("system"))==0) continue;
						m_api->m_data.GetAttr(Pdf, m_api->m_prd_mgr.a_pdf_prd, Prd);
						if(Prd)
						{
							m_api->m_data.GetAttr(Prd, m_api->m_prd_mgr.a_prd_id, id);
							m_api->m_data.GetAttr(Prd, m_api->m_prd_mgr.a_prd_name, name);
							if(id.Left(id_l).CompareNoCase(m_sId)==0 || m_sId.IsEmpty())
								bId = true;
							if(name.Left(name_l).CompareNoCase(m_sName)==0 || m_sName.IsEmpty())
								bName = true;
							if(bName && bId && bSN)
								ext.Add(tmp[i]);
						}
					}
				}
			}
		}

		aplEndWaitDlg(DlgId);
		ShowResult(ext);
	}
}

void CFindPrdInstDlgEx::FindInstalledPrdInst()
{
	if(!UpdateData())
		return;

	m_sId.TrimLeft();
	m_sId.TrimRight();
	m_sName.TrimLeft();
	m_sName.TrimRight();
	m_sSN.TrimLeft();
	m_sSN.TrimRight();

	aplExtent ext;

	if(m_api->m_data.IsConnected())
	{
		if(m_iPlaner==NULL)
		{
			AfxMessageBox( APL_T("Борт не задан!"), MB_OK|MB_ICONINFORMATION);
			return;
		}
		long DlgId = aplStartWaitDlg( APL_T("Выполняется поиск"),  APL_T("Поиск"));
		if(m_iPlaner->GetId()==0)
			m_api->SaveChanges();

		CString sQuery;
		sQuery.Format(_T("SELECT\r\n   rels_filter\r\n")\
			_T("FROM\r\n")\
			_T("   rels_filter{apl_component(.place = #%d AND .related_product_instance->apl_product_instance(.formation->apl_product_definition_formation.of_product->product(.id LIKE_LEFT '%s' AND .name LIKE_LEFT '%s') AND .serial_number LIKE_LEFT '%s'))}.related_product_instance\r\n")
			_T("END_SELECT"), m_iPlaner->GetId(), m_sId, m_sName, m_sSN);
		if(m_api->m_data.NET_QueryEditParse(sQuery, aplShowDebugInformation))
		{
			m_api->m_data.NET_QueryExecute(ext);
			m_api->m_prd_inst_mgr.LoadPrdInstInfo(ext);
			//if(aplShowPlaceColumn)
			//	m_ExploitationMgr->FindActualRelations(ext, NULL);
		}
		aplEndWaitDlg(DlgId);
	}
	else
	{
		long DlgId = aplStartWaitDlg( APL_T("Выполняется поиск"),  APL_T("Поиск"));
		if(m_iPlaner)
		{
			if(m_iPlaner->GetId()==0)
				m_api->SaveChanges();
		}
		aplExtent tmp;
		CString pdf_type;
		CaplInstance *prd, *pdf, *rel_ed_prd_inst, *rel_ing_prd_inst,*place;
		CString buf;
		m_api->m_data.GetEntityExtent(m_api->m_prd_inst_mgr.e_apl_component, tmp);
		for(int i=0; i<tmp.GetSize(); i++)
		{
			m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_place, place);
			if(place != m_iPlaner)
				continue;
			m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_date_removed, buf);
			if(buf!=_T(""))
				continue;
			m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_related, rel_ed_prd_inst);
			if(NULL == rel_ed_prd_inst)
				continue;
			m_api->m_data.GetAttr(rel_ed_prd_inst, m_api->m_prd_inst_mgr.a_prd_inst_pdf, pdf);
			if(NULL == pdf)
				continue;
			m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_apl_pdf_type, pdf_type);
			if(pdf_type.CollateNoCase(_T("system"))==0) 
				continue;
			m_api->m_data.GetAttr(tmp[i], m_api->m_prd_inst_mgr.a_prd_inst_rel_relating, rel_ing_prd_inst);
			if(NULL == rel_ing_prd_inst)
				continue;
			if(m_api->m_data.IsKindOf(rel_ing_prd_inst,m_api->m_appr_mgr.e_org))
				continue;
			//m_sId, m_sName, m_sSN//, m_iPlaner->id;
			CString sId, sName, sSN;
			m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_pdf_prd, prd);
			if(NULL == prd)
				continue;
			m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, sId);
			m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, sName);
			m_api->m_data.GetAttr(rel_ed_prd_inst, m_api->m_prd_inst_mgr.a_prd_inst_id, sSN);
			sId.MakeLower(); sName.MakeLower(); sSN.MakeLower();
			m_sId.MakeLower(); m_sName.MakeLower(); m_sSN.MakeLower();
			if(0==sId.Find(m_sId, 0) && 0==sName.Find(m_sName) && 0==sSN.Find(m_sSN)) 
				ext.Add(rel_ed_prd_inst);
		}		
		aplEndWaitDlg(DlgId);
	}
	ShowResult(ext);
}


void CFindPrdInstDlgEx::FindNonUsed()
{
	if(!UpdateData())
		return;

	aplExtent ext;
	//int i;

	m_sId.TrimLeft();
	m_sId.TrimRight();
	m_sName.TrimLeft();
	m_sName.TrimRight();
	m_sSN.TrimLeft();
	m_sSN.TrimRight();

	long DlgId = aplStartWaitDlg( APL_T("Выполняется поиск"),  APL_T("Поиск"));
	if(m_api->m_data.IsConnected())
	{
		CString sQuery, sAllWithoutRelation, sAllInOrg;

		sAllWithoutRelation.Format(_T("all_without_rel{&aplINSTANCE&select instance_id from E000064 where not exists(select A000460 from E000065 where A000460 = E000064.instance_id and E000065.A000570 = 'NO Value')}\r\n"));
		sAllInOrg.Format(_T("  apl_all_in_org{apl_component(.date_removed_s='' AND .relating_product_instance->organization.id LIKE_LEFT '')}.related_product_instance\r\n"));

		sQuery.Format(_T("SELECT\r\n  ext\r\nFROM\r\n  %s%s")\
			_T("ext{apl_product_instance((.# IN #all_without_rel OR .# IN #apl_all_in_org) ")\
			_T("AND .serial_number LIKE_LEFT '%s'")\
			_T("AND .formation->apl_product_definition_formation.of_product->product(.id LIKE_LEFT '%s' AND .name LIKE_LEFT '%s'))}\r\n")
			_T("END_SELECT"), sAllWithoutRelation, sAllInOrg, m_sSN, m_sId, m_sName);

		if(!m_api->m_data.NET_QueryEditParse(sQuery))
			return; 
		BeginWaitCursor();
		m_api->m_data.NET_QueryExecute(ext);
		m_api->m_prd_inst_mgr.LoadExtentInfo(ext);
		//if(aplShowPlaceColumn)
		//	m_ExploitationMgr->FindActualRelations(ext, NULL);
		EndWaitCursor();

	}
	else
	{
		AfxMessageBox( APL_T("Поиск возможен только при работе с БД!"));
		ShowResult(ext);
		return;
	}
	//К полученному результату добавляем ПКИ из техаптечки выбранного борта (если такова есть и борт указан)
	/*if(m_iPlaner)
	{
		if(m_ExploitationMgr->IsPlaner(m_iPlaner))
		{
			aplExtent childs, tmp;
			CaplInstance *pdf;

			m_ExploitationMgr->GetChildItems(m_iPlaner, childs);
			for(i=0; i<childs.GetSize(); i++)
			{
				m_api->m_data.GetAttr(childs[i], m_api->m_prd_inst_mgr.a_prd_inst_pdf, pdf);
				if(pdf==NULL) //таким образом у нас обозначена аптечка
				{
					m_ExploitationMgr->GetChildItems(childs[i], tmp);
					ext.Append(tmp);
				}
			}
		}
	}
	for(i=0; i<ext.GetSize(); i++)
	{
		if(m_ExploitationMgr->IsPlaner(ext[i]) || m_ExploitationMgr->IsSystem(ext[i]))
			ext.Remove(i--);
	}*/
	aplEndWaitDlg(DlgId);
	ShowResult(ext);
}

void CFindPrdInstDlgEx::FindItemChilds()
{
	if(!UpdateData())
		return;

	aplExtent ext;
	//int i;

	m_sId.TrimLeft();
	m_sId.TrimRight();
	m_sName.TrimLeft();
	m_sName.TrimRight();
	m_sSN.TrimLeft();
	m_sSN.TrimRight();

	long DlgId = aplStartWaitDlg( APL_T("Выполняется поиск"),  APL_T("Поиск"));
	if(m_api->m_data.IsConnected() && m_iPlaner)
	{
		CString sQuery;

		sQuery.Format(_T("SELECT\r\n  ext\r\nFROM\r\n")\
			_T("ext{apl_component(.date_removed_s = '' AND ")\
			_T(".related_product_instance->apl_product_instance(")\
			_T(".serial_number LIKE_LEFT '%s'")\
			_T("AND .formation->apl_product_definition_formation.of_product->product(.id LIKE_LEFT '%s' AND .name LIKE_LEFT '%s'))")\
			_T("AND .relating_product_instance = #%d)}.related_product_instance\r\n")\
			_T("END_SELECT"), m_sSN, m_sId, m_sName, m_iPlaner->GetId());

		if(!m_api->m_data.NET_QueryEditParse(sQuery, aplShowDebugInformation))
			return; 
		BeginWaitCursor();
		m_api->m_data.NET_QueryExecute(ext);
		m_api->m_prd_inst_mgr.LoadExtentInfo(ext);
		EndWaitCursor();
	}
	else
	{
		ASSERT(0);
		aplEndWaitDlg(DlgId);
		ShowResult(ext);
		return;
	}
	//К полученному результату добавляем ПКИ из техаптечки выбранного борта (если такова есть и борт указан)
	/*for(i=0; i<ext.GetSize(); i++)
	{
		if(m_ExploitationMgr->IsPlaner(ext[i]) || m_ExploitationMgr->IsSystem(ext[i]) || m_ExploitationMgr->IsZone(ext[i]))
			ext.Remove(i--);
	}*/

	aplEndWaitDlg(DlgId);
	ShowResult(ext);
}

void CFindPrdInstDlgEx::OnCreate() 
{
	if(!UpdateData()) return;

	/*if(m_Flags&APL_FD_USE_SIMPLE_CREATE_DIALOG)
	{
		aplExtent ext;
		if(m_ExploitationMgr->ShowPKIDlg(NULL, ext))
		{
			ShowResult(ext);
		}
	}
	else if(m_Flags&APL_FD_AUTOCREATE)
	{
		m_sId.TrimLeft(); m_sId.TrimRight();
		m_sName.TrimLeft(); m_sName.TrimRight();
		m_sSN.TrimLeft(); m_sSN.TrimRight();

		if(m_sId.IsEmpty())
		{
			AfxMessageBox( APL_T("Шифр изделия не должен быть пустым!"), MB_OK|MB_ICONINFORMATION);
			return;
		}

		//Пытаемся найти такое изделие в БД
		CaplInstance* TstPrd, *Pdf = NULL;
		CaplInstance* nInst = NULL;
		CString buf;
		aplExtent ext;
		int i;

		TstPrd = m_api->m_prd_mgr.FindPrdById(m_sId);
		if(TstPrd!=NULL)
		{
			m_api->m_data.GetAttr(TstPrd, m_api->m_prd_mgr.a_prd_name, buf);
			if(buf.CompareNoCase(m_sName)!=0)
			{
				if(IDYES!=AfxMessageBox( APL_T("В БД найдено изделие с указанным шифром, но с другим наименованием. Использовать найденное изделие?"), MB_YESNO|MB_ICONQUESTION))
					return;
			}
			m_api->m_prd_mgr.GetAllProductVersion(TstPrd, ext);
			for(i=0; i<ext.GetSize(); i++)
			{
				m_api->m_data.GetAttr(ext[i], m_api->m_prd_mgr.a_pdf_id, buf);
				if(buf.IsEmpty())
					Pdf = ext[i];
			}
		}

		CString date;
		aplDate2String(COleDateTime::GetCurrentTime(), date);
		if(Pdf==NULL)
		{
			Pdf = m_api->m_prd_mgr.CreatePdf(m_sId, m_sName, _T(""), false);
			CPKIData pd;
			pd.BasePdf = Pdf;
			pd.sDateManaf = date;
			pd.sDateProvide = date;
			pd.bAttrsFromPdf = true;
			pd.sSN = m_sSN;
			pd.sState =  APL_T("Исправен");
			if(m_ExploitationMgr->CreatePKI(pd))
				nInst = pd.PrdInst;
		}
		else
		{
			//Ищем такое ПКИ. если найдем возвращаем его, если нет, то создадим новое
			nInst = m_api->m_prd_inst_mgr.FindPrdInstByPDFSN(Pdf, m_sSN);
			if(nInst==NULL)
			{
				CPKIData pd;
				pd.BasePdf = Pdf;
				pd.sDateManaf = date;
				pd.sDateProvide = date;
				pd.bAttrsFromPdf = true;
				pd.sSN = m_sSN;
				pd.sState =  APL_T("Исправен");
				if(m_ExploitationMgr->CreatePKI(pd))
					nInst = pd.PrdInst;
				else
				{
					CString msg;
					m_ExploitationMgr->GetLastError(msg);
					AfxMessageBox(msg);
				}
			}
			else
			{
				AfxMessageBox( APL_T("В БД присутствует экземпляр изделия с данным шифром и серийным номером!"), MB_OK|MB_ICONINFORMATION);
				m_api->m_prd_inst_mgr.LoadPrdInstInfo(nInst);
			}
		}
		if(nInst)
		{
			ext.Add(nInst);
			ShowResult(ext);
		}
	}
	else
	{
		aplExtent ext;
		if(m_ExploitationMgr->CreatePKIDlg(NULL, NULL, NULL, &ext))
		{
			ShowResult(ext);
		}
	}*/
}


bool CFindPrdInstDlgEx::CheckCorrect()
{
	if (m_sId==m_sBaseId && m_sName==m_sBaseName)
		return true;

	//CaplInstance *base_pdf;
	aplExtent ext;

	// сначала ищем само изделие
	CString sql;
	CString buf;
	//sql = _T("select ext from\n");
	//buf.Format(_T("ext{apl_product_definition_formation(.of_product->product(.id = '%s' and .name = '%s')}\n"),m_sBaseId,m_sBaseName);
	//sql += buf;
	//sql += _T("end_select");

	//CString err_msg;
	//m_api->m_data.NET_QueryEditParse(sql,false,&err_msg);

	//m_api->m_data.NET_QueryExecute(ext);
	//if (ext.Size!=1)
	//	return false;
	//m_api->m_prd_mgr.LoadExtentInfo(ext);
	//base_pdf = ext[0];

	CaplInstance *pdf, *prd;
	if (!m_sId.IsEmpty())
	{
		if (m_sId!=m_sBaseId)
		{
			// ищем аналоги для изделия по-умолчанию
			ext.Clear();
			sql = _T("select ext from\n");
			sql += _T("ext{product_definition_substitute(\n");
			buf.Format(_T(".context_relationship->product_definition_relationship.related_product_definition->apl_product_definition_formation.of_product->product.id = '%s'\n"), m_sBaseId);
			sql += buf;
			if (m_iPlaner)
			{
				buf.Format(_T("and .parent_item = #%d\n"),m_iPlaner->GetId());
				sql += buf;
			}
			sql += _T(")}\n");
			sql += _T("end_select");

			CString err_msg;
			m_api->m_data.NET_QueryEditParse(sql,false,&err_msg);

			m_api->m_data.NET_QueryExecute(ext);
			if (ext.Size<1)
				return false;
			m_api->m_prd_mgr.LoadExtentInfo(ext);
			bool bIsFind = false;
			for(int i=0; i<ext.Size && !bIsFind; ++i)
			{
				m_api->m_data.GetAttr(ext[i], m_api->m_prd_mgr.a_pdf_subst_pdf, pdf);
				if (!pdf)
					continue;
				if (pdf->GetAccessmode()>=aplRO)
					continue;
				m_api->m_prd_mgr.LoadPrdInfo(pdf);
				m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_pdf_prd, prd);
				if (!prd)
					continue;
				if (prd->GetAccessmode()>=aplRO)
					continue;
				m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, buf);
				if (buf==m_sId)
					bIsFind = true;
			}
			if (!bIsFind)
				return false;
		}
	}

	if (!m_sName.IsEmpty())
	{
		if (m_sName!=m_sBaseName)
		{
			// ищем аналоги для изделия по-умолчанию
			ext.Clear();
			sql = _T("select ext from\n");
			sql += _T("ext{product_definition_substitute(\n");
			buf.Format(_T(".context_relationship->product_definition_relationship.related_product_definition->apl_product_definition_formation.of_product->product.id = '%s'\n"), m_sBaseName);
			sql += buf;
			if (m_iPlaner)
			{
				buf.Format(_T("and .parent_item = #%d\n"),m_iPlaner->GetId());
				sql += buf;
			}
			sql += _T(")}\n");
			sql += _T("end_select");

			CString err_msg;
			m_api->m_data.NET_QueryEditParse(sql,false,&err_msg);

			m_api->m_data.NET_QueryExecute(ext);
			if (ext.Size<1)
				return false;
			m_api->m_prd_mgr.LoadExtentInfo(ext);
			bool bIsFind = false;
			for(int i=0; i<ext.Size && !bIsFind; ++i)
			{
				m_api->m_data.GetAttr(ext[i], m_api->m_prd_mgr.a_pdf_subst_pdf, pdf);
				if (!pdf)
					continue;
				if (pdf->GetAccessmode()>=aplRO)
					continue;
				m_api->m_prd_mgr.LoadPrdInfo(pdf);
				m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_pdf_prd, prd);
				if (!prd)
					continue;
				if (prd->GetAccessmode()>=aplRO)
					continue;
				m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, buf);
				if (buf==m_sName)
					bIsFind = true;
			}
			if (!bIsFind)
				return false;
		}
	}

	return true;
}