// SelectPrdInstDlg.cpp : implementation file
//

#include "stdafx.h"
#include "resource.h"
#include "SelectPrdInstDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CSelectPrdInstDlg dialog
int FindString(CString str, CStringArray* Arr)
{
	if(Arr==0)
		return -1;
	int cnt = Arr->GetSize();
	for(int i=0; i<cnt; i++)
		if(Arr->GetAt(i)==str)
			return i;
	return -1;
}


CSelectPrdInstDlg::CSelectPrdInstDlg(CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(CSelectPrdInstDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSelectPrdInstDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	m_api = NULL;
	m_selected_prd_inst = NULL;
	m_pdf = NULL;
	m_pdfs.Clear();
	m_bShowCreate = true;
	m_sTitle =  APL_T("Выбор комплектующего");
	m_FiltersName.RemoveAll();
	m_bNOT_Name = true;
	m_FiltersId.RemoveAll();
	m_bNOT_Id = true;
	m_FiltersVer.RemoveAll();
	m_bNOT_Ver = true;
	m_FiltersSN.RemoveAll();
	m_bNOT_SN = true;
}


void CSelectPrdInstDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSelectPrdInstDlg)
	DDX_Control(pDX, IDC_LIST_PRDINST, m_prdinst_lict_ctrl);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CSelectPrdInstDlg, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CSelectPrdInstDlg)
	ON_BN_CLICKED(IDC_CREATE_PRDINST, OnCreatePrdinst)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSelectPrdInstDlg message handlers

void CSelectPrdInstDlg::OnCreatePrdinst() 
{
	int i;
	CaplInstance* PrdInst = m_api->m_prd_inst_mgr.CreatePrdInst(m_pdf);
	if(0!=PrdInst)
	{
		//Поиск тьипов характеристик
		CaplInstance *type_nazn, *type_fact;
		type_nazn = m_api->m_charact_mgr.GetCharacteristicType( APL_T("назначенная"));
		type_fact = m_api->m_charact_mgr.GetCharacteristicType( APL_T("фактическая"));
		if(type_nazn && type_fact)
		{
			aplExtent ext, gr;
			m_api->m_charact_mgr.FindAssociatedCharacteristic(m_pdf, ext, gr);
			m_api->m_charact_mgr.LoadCharacteristic(ext);
			//Поиск динамических
			bool dynamic = false;
			CaplInstance* charact;
			for(i=0; i<ext.Size; i++)
			{
				m_api->m_data.GetAttr(ext[i], m_api->m_charact_mgr.a_apl_charact_val_charact, charact);
				m_api->m_data.GetAttr(charact, m_api->m_charact_mgr.a_apl_charact_dynamic, dynamic);
				if(!dynamic)
				{
					ext.Remove(i);
					i--;
				}
			}
			//Необходимо сделать аналогичные характеристики, только для PrdInst;
			CaplInstance* nVal, *aVer=0;
			for(i=0; i<ext.Size; i++)
			{
				m_api->m_charact_mgr.CreateCharacteristic(PrdInst,ext[i], &nVal, 0, &aVer, false, 0, false);
				ASSERT(nVal);
				m_api->m_data.PutAttr(nVal, m_api->m_charact_mgr.a_apl_charact_val_type, type_fact);
				m_api->m_data.PutAttr(aVer, m_api->m_charact_mgr.a_apl_charact_val_ver_type, type_fact);
				m_api->m_data.PutAttr(nVal, m_api->m_charact_mgr.a_apl_charact_val_meas_val, 0);
				m_api->m_data.PutAttr(aVer, m_api->m_charact_mgr.a_apl_charact_val_ver_meas_val, 0);
				m_api->m_charact_mgr.CreateCharacteristic(PrdInst,ext[i], &nVal, 0, &aVer, false, 0, false);
				ASSERT(nVal);
				m_api->m_data.PutAttr(nVal, m_api->m_charact_mgr.a_apl_charact_val_type, type_nazn);
				m_api->m_data.PutAttr(aVer, m_api->m_charact_mgr.a_apl_charact_val_ver_type, type_nazn);
			}
		}
		LoadData();
	}
}

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

	ASSERT(m_api);

	if(!m_bShowCreate)
		GetDlgItem(IDC_CREATE_PRDINST)->ShowWindow(SW_HIDE);

	if(m_pdf)
		m_pdfs.Add(m_pdf);

	m_prdinst_lict_ctrl.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT);

	m_prdinst_lict_ctrl.InsertColumn(0, APL_T("Обозначение"), LVCFMT_LEFT, 100);
	m_prdinst_lict_ctrl.InsertColumn(1, APL_T("Наименование"), LVCFMT_LEFT, 100);
	m_prdinst_lict_ctrl.InsertColumn(2, APL_T("Версия"), LVCFMT_LEFT, 100);
	m_prdinst_lict_ctrl.InsertColumn(3, APL_T("Серийный номер"), LVCFMT_LEFT, 100);
	
	LoadData();
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CSelectPrdInstDlg::LoadData()
{
	m_prdinst_lict_ctrl.DeleteAllItems();

	aplExtent ext, tmp;
	CString query;
	int i;
	if(m_pdfs.Size>0)
	{
		for(i=0; i<m_pdfs.Size;i++)
		{
			m_api->m_prd_inst_mgr.FindAllPdfInstances(m_pdfs[i], tmp);
			ext.Append(tmp);
		}
		m_api->m_prd_inst_mgr.LoadPrdInstInfo(ext);
		//Для этой инстанс ищем дату, если изделие установлено кудато, то его не выводим;
		CaplInstance* tmpInst;
		CaplLoadData ld(&m_api->m_data,DEF_SOURCE);
		for(i=0; i<ext.Size; i++)
		{
			tmp.Clear();
			ld.ClearQuery();
			int i1= ld.AddQuery(_T('b'), ext[i]->GetId(), m_api->m_prd_inst_mgr.e_prd_inst_rel, m_api->m_prd_inst_mgr.a_prd_inst_rel_related, true, true);
					ld.AddQuery(_T('d'), i1, 0, m_api->m_prd_inst_mgr.a_prd_inst_rel_relating, true, true);
			ld.LoadEx(true, &tmp);
			if(tmp.Size>0)
			{
				bool ok = false;
				CString sDateRemove;
				for(int j=0; j<tmp.Size;j++)
				{
					if(!m_api->m_data.IsKindOf(tmp[j], m_api->m_prd_inst_mgr.e_prd_inst_rel)) continue;
					m_api->m_data.GetAttr(tmp[j], m_api->m_prd_inst_mgr.a_prd_inst_rel_relating, tmpInst);
					if(tmpInst==0) continue;
					if(m_api->m_data.IsKindOf(tmpInst, m_api->m_prd_inst_mgr.e_prd_inst)) 
					{
						m_api->m_data.GetAttr(tmp[j], m_api->m_prd_inst_mgr.a_prd_inst_rel_date_removed, sDateRemove);
						if(sDateRemove.IsEmpty())
							ok = true;
					}
				}
				if(!ok) continue;
				ext.Remove(i);
				i--;
			}
		}
	}
	else
	{
		query = _T("Select\n\
					ext2\n\
				from\n\
					ext1\n\
				{apl_component(.date_removed_s='' AND .relating_product_instance->apl_product_instance.id Like '')}.related_product_instance\n\
					ext2\n\
				{apl_product_instance\
					(	.# NOT_IN #ext1)}\n\
				end_select");
		m_api->m_data.NET_QueryEditParse(query);
		m_api->m_data.NET_QueryExecute(ext);
		m_api->LoadExtentInfo(ext);
	}
	//Заполнение
	CString sId, sName, sVer, sSN, sDate;
	CaplInstance *pdf, *prd;
	int ind = 0, fInd;;
	int cnt_N = m_FiltersName.GetSize(), cnt_I = m_FiltersId.GetSize(), cnt_V = m_FiltersVer.GetSize(), cnt_S = m_FiltersSN.GetSize();
	for(i=0; i<ext.Size;i++)
	{
		sId = sName = sVer = sSN = _T("");
		m_api->m_data.GetAttr(ext[i], m_api->m_prd_inst_mgr.a_prd_inst_sn, sSN);
		if(cnt_S>0)
		{
			fInd = FindString(sSN, &m_FiltersSN);
			if(!m_bNOT_SN && fInd<0)
				continue;
			else if(fInd>-1)
				continue;
		}
		m_api->m_data.GetAttr(ext[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_pdf_prd, prd);
			m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, sId);
			if(cnt_I>0)
			{
				fInd = FindString(sId, &m_FiltersId);
				if(!m_bNOT_Id && fInd<0)
					continue;
				else if(fInd>-1)
					continue;
			}
			m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, sName);
			if(cnt_N>0)
			{
				fInd = FindString(sName, &m_FiltersName);
				if(!m_bNOT_Name && fInd<0)
					continue;
				else if(fInd>-1)
					continue;
			}
			m_api->m_data.GetAttr(pdf, m_api->m_prd_mgr.a_pdf_id, sVer);
			if(cnt_V>0)
			{
				fInd = FindString(sId, &m_FiltersVer);
				if(!m_bNOT_Ver && fInd<0)
					continue;
			}
		}
		m_prdinst_lict_ctrl.InsertItem(ind, sId);
		m_prdinst_lict_ctrl.SetItemText(ind, 1, sName);
		m_prdinst_lict_ctrl.SetItemText(ind, 2, sVer);
		m_prdinst_lict_ctrl.SetItemText(ind, 3, sSN);
		m_prdinst_lict_ctrl.SetItemData(ind, (DWORD)ext[i]);
		ind++;
	}
}

void CSelectPrdInstDlg::OnOK() 
{
	int cur = m_prdinst_lict_ctrl.GetNextItem(-1, LVIS_SELECTED);
	if(cur<0)
	{
		AfxMessageBox( APL_T("Изделие не выбрано!"));
		return;
	}
	m_selected_prd_inst = (CaplInstance*)m_prdinst_lict_ctrl.GetItemData(cur);
	
	CaplTranslateDialog::OnOK();
}
