// FindPDFDlg.cpp : implementation file
//

#include "stdafx.h"
#include "FindPDFDlg.h"

CFindPDFDlg::CFindPDFDlg(CaplAPI *api, TFindPdfModes mode, UINT Flags, CWnd* pParent /*=NULL*/)
: CaplTranslateDialog(CFindPDFDlg::IDD, pParent)
{
	ASSERT(api);
	ASSERT(api->m_expl_mgr);

	m_api = api;
	m_ExploitationMgr = (CaplPreExploitationMgr*)api->m_expl_mgr;

	m_Mode = mode;
	//m_pFunct = NULL;
	//m_dwUserData = 0;
	m_Flags = Flags;
	//{{AFX_DATA_INIT(CFindPDFDlg)
	m_sId = _T("");
	m_sName = _T("");
	//}}AFX_DATA_INIT
	m_SelectedInst = NULL;
	m_bAutoExecute = false;
}
/*
CFindPDFDlg::CFindPDFDlg(CaplAPI *api, TFindPdfModes mode, UINT Flags, LPUserFindFunct lpFunct, DWORD dwData, CWnd* pParent )
: CaplTranslateDialog(CFindPDFDlg::IDD, pParent)
{
	ASSERT(api);
	ASSERT(api->m_expl_mgr);

	m_api = api;
	m_ExploitationMgr = (CaplPreExploitationMgr*)api->m_expl_mgr;

	m_Mode = mode;

	m_pFunct = lpFunct;
	m_dwUserData = dwData;
	m_Flags = Flags;

	m_sId = _T("");
	m_sName = _T("");

	m_SelectedInst = NULL;
}

CFindPDFDlg::CFindPDFDlg(CaplAPI *api, TFindPdfModes mode, UINT Flags, LPUserFindFunct lpFunct, LPUserCreateFunct lpCreateFunct, DWORD dwData, CWnd* pParent)
: CaplTranslateDialog(CFindPDFDlg::IDD, pParent)
{
	ASSERT(api);
	ASSERT(api->m_expl_mgr);

	m_api = api;
	m_ExploitationMgr = (CaplPreExploitationMgr*)api->m_expl_mgr;

	m_Mode = mode;

	m_pFunct = lpFunct;
	m_pCreateFunct = lpCreateFunct;
	m_dwUserData = dwData;
	m_Flags = Flags;

	m_sId = _T("");
	m_sName = _T("");

	m_SelectedInst = NULL;
}
*/

void CFindPDFDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFindPDFDlg)
	DDX_Control(pDX, IDC_CREATE, m_create_btn);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_LIST, m_list_ctrl);
	DDX_Control(pDX, IDC_FIND, m_find_btn);
	DDX_Text(pDX, IDC_ID, m_sId);
	DDX_Text(pDX, IDC_NAME, m_sName);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CFindPDFDlg, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CFindPDFDlg)
	ON_BN_CLICKED(IDC_FIND, OnFind)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST, OnDblclkList)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST, OnItemchangedList)
	ON_BN_CLICKED(IDC_CREATE, OnCreate)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFindPDFDlg message handlers

void CFindPDFDlg::OnFind() 
{
	UpdateData();

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

	switch(m_Mode)
	{
	case aplFindPlanerPdf:
		FindPlanerPdf();
		break;
	case aplFindSystemPdf:
		//if (m_Flags&APL_FD_ONLY_BASE)
		//	FindBaseSystemPdf();
		//else
			FindSystemPdf();
		break;
	case aplFindZonePdf:
		FindZonePdf();
		break;
	case aplFindPKIPdf:
		FindAllPKIPdfs();
		break;
	/*case aplFindPdfUserCallback:
		{
			aplExtent res;
			if(m_pFunct(m_api, res, m_dwUserData, m_sId, m_sName, CString(_T(""))))
				ShowItems(res);
		}
		break;*/
	default: //все
		break;
	}
}

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

	SetIcon(aplGetButtonIco(APL_24_FIND), FALSE);

	if(m_Flags&APL_FD_SHOW_CREATE_BTN)
		m_create_btn.ShowWindow(SW_SHOW);

	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_find_btn.SetWindowText(_T(""));

	CRect rect;
	m_list_ctrl.GetClientRect(&rect);
	rect.right-=15;
	m_list_ctrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
	m_list_ctrl.InsertColumn(0,  APL_T("Шифр"), LVCFMT_LEFT, (int)(rect.Width()*0.3));
	m_list_ctrl.InsertColumn(1,  APL_T("Наименование"), LVCFMT_LEFT, (int)(rect.Width()*0.5));
	//if(m_ExploitationMgr->GetClientCode()==aplClient_KNAAPO)
	//	m_list_ctrl.InsertColumn(2,  APL_T("Документ на поставку"), LVCFMT_LEFT, (int)(rect.Width()*0.2));
	//else
		m_list_ctrl.InsertColumn(2,  APL_T("Версия/Исполнение"), LVCFMT_LEFT, (int)(rect.Width()*0.2));

	if(!::IsWindow(m_ToolTipCtrl.m_hWnd))
	{
		m_ToolTipCtrl.Create(this, TTS_BALLOON|TTS_NOPREFIX|TTS_ALWAYSTIP);
		m_ToolTipCtrl.SetDelayTime(0);
	}

	EnableToolTips();

	UpdateData(FALSE);

	if(m_bAutoExecute)
		OnFind();

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

void CFindPDFDlg::ShowItems(aplExtent &ext)
{
	int i, ind = -1;
	CaplInstance *prd;
	CString id, name, ver;
	CString buf;

	BeginWaitCursor();
	m_list_ctrl.DeleteAllItems();

	m_api->m_prd_mgr.LoadPrdInfo(ext);

	for(i=0; i<ext.GetSize(); i++)
	{
		if(ext[i]==NULL) continue;
		if(ext[i]->GetAccessmode()>aplRO) continue;

		m_api->m_data.GetAttr(ext[i], m_api->m_prd_mgr.a_pdf_prd, prd);
		if(prd==NULL) continue;

		m_api->m_data.GetAttr(ext[i], m_api->m_prd_mgr.a_pdf_id, ver);
		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);

		ind =	m_list_ctrl.InsertItem(m_list_ctrl.GetItemCount(), id);
		m_list_ctrl.SetItemText(ind, 1, name);
		m_list_ctrl.SetItemText(ind, 2, ver);
		m_list_ctrl.SetItemData(ind, (DWORD)ext[i]);
	}
	m_list_ctrl.ReSort();
	EndWaitCursor();

	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0

	if(ind>-1)
	{
		int k=1;
		if(0!=app) k=app->GetProfileInt(_T("FindDialog"), _T("ShowFoundAmountMessage"), 1);
		if(k>0)
		{
			buf.Format( APL_T("Найдено %d комплектующих изделий!"), ind+1);
			MessageBox(buf,  APL_T("Результаты поиска"), MB_OK|MB_ICONINFORMATION);
		}
	}
	else
	{
		int k=1;
		if(0!=app) k=app->GetProfileInt(_T("FindDialog"), _T("ShowNotfoundMessage"), 1);
		if(k>0)
		{
			buf.Format( APL_T("Ничего не найдено!"));
			MessageBox(buf,  APL_T("Результаты поиска"), MB_OK|MB_ICONINFORMATION);
		}
	}
}

void CFindPDFDlg::OnOK() 
{
	int cur = m_list_ctrl.GetNextItem(-1, LVIS_SELECTED);
	if(cur>-1)
		m_SelectedInst = (CaplInstance*)m_list_ctrl.GetItemData(cur);
	else
	{
		DWORD dw = GetDllVersion(_T("comctl32.dll"));
		if(dw>=PACKVERSION(5,0))
		{
			CRect rect;
			CPoint pt;
			m_ok_btn.GetWindowRect(&rect);
			CString sTitle =  APL_T("Недопустимое значение");
			m_ToolTipCtrl.DelTool(&m_ok_btn);
			m_ToolTipCtrl.AddTool(&m_ok_btn,  APL_T("Необходимо выбрать изделие!"));
			m_ToolTipCtrl.SendMessage(TTM_SETTITLE, TTI_ERROR, (LPARAM)(LPCTSTR)sTitle);

			::GetCursorPos(&pt);
			if(!rect.PtInRect(pt))
				::SetCursorPos(rect.left+15, rect.top+5);
		}
		else
		{
			MessageBox( APL_T("Необходимо выбрать изделие!"),  APL_T("Поиск изделий"), MB_OK|MB_ICONINFORMATION);
		}
		return;
	}

	CaplTranslateDialog::OnOK();
}

void CFindPDFDlg::OnDblclkList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	OnOK();

	*pResult = 0;
}

BOOL CFindPDFDlg::PreTranslateMessage(MSG* pMsg) 
{
	m_ToolTipCtrl.RelayEvent(pMsg);

	return CaplTranslateDialog::PreTranslateMessage(pMsg);
}

void CFindPDFDlg::OnItemchangedList(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
	// TODO: Add your control notification handler code here
	m_ToolTipCtrl.DelTool(&m_ok_btn);

	*pResult = 0;
}

bool CFindPDFDlg::FindPlanerPdf()
{
	if(!UpdateData()) return false;
	CaplAttrValue tst_values[2];
	aplExtent res, pdfs;
	tst_values[0].attr = m_api->m_prd_mgr.a_prd_id;
	tst_values[0].value.Set(m_sId);
	tst_values[1].attr = m_api->m_prd_mgr.a_prd_name;
	tst_values[1].value.Set(m_sName);
	long DlgId = aplStartWaitDlg( APL_T("Идет поиск комплектующих изделий..."),  APL_T("Поиск"));
	m_api->m_data.NET_FindInstancesWithAttrValues2(m_api->m_prd_mgr.e_prd, 2, &tst_values[0], res, true, false, NULL, aplSBLeft,false,DEF_SOURCE);
	m_api->m_prd_mgr.GetAllProductVersion(res, pdfs);

	CaplInstance *inst;
	aplExtent ext;
	int i;

	for(i=0; i<pdfs.GetSize(); i++)
	{
		inst = pdfs[i];
		if(inst==NULL) continue;
		if(inst->GetAccessmode()>aplRO) continue;

		//if(!m_ExploitationMgr->IsPlaner(inst)) continue;

		ext.Add(inst);
	}

	aplEndWaitDlg(DlgId);

	ShowItems(ext);

	return true;
}

bool CFindPDFDlg::FindSystemPdf()
{
	if(!UpdateData()) return false;
	CaplAttrValue tst_values[2];
	aplExtent res, pdfs;
	tst_values[0].attr = m_api->m_prd_mgr.a_prd_id;
	tst_values[0].value.Set(m_sId);
	tst_values[1].attr = m_api->m_prd_mgr.a_prd_name;
	tst_values[1].value.Set(m_sName);
	long DlgId = aplStartWaitDlg( APL_T("Идет поиск комплектующих изделий..."),  APL_T("Поиск"));
	m_api->m_data.NET_FindInstancesWithAttrValues2(m_api->m_prd_mgr.e_prd, 2, &tst_values[0], res, true, false, NULL, aplSBLeft,false,DEF_SOURCE);
	m_api->m_prd_mgr.GetAllProductVersion(res, pdfs);

	CaplInstance *inst;
	aplExtent ext;
	int i;

	for(i=0; i<pdfs.GetSize(); i++)
	{
		inst = pdfs[i];
		if(inst==NULL) continue;
		if(inst->GetAccessmode()>aplRO) continue;

		//if(!m_ExploitationMgr->IsSystem(inst)) continue;

		ext.Add(inst);
	}

	aplEndWaitDlg(DlgId);

	ShowItems(ext);

	return true;
}

bool CFindPDFDlg::FindBaseSystemPdf()
{
	return false;
	/*if(!UpdateData()) return false;
	aplExtent rels, ext;

	CString sIdSQL, sNameSQL;
	sIdSQL.Format(_T("%s%%"), m_sId);
	sIdSQL.MakeUpper();
	sNameSQL.Format(_T("%s%%"), m_sName);
	sNameSQL.MakeUpper();
	CString sSQL;
	sSQL.Format(_T("select instance_id, entity_id, access_def, chk_personal from e000007\n")\
		_T("where exists(select instance_id from e000005 where instance_id = e000007.a000186 and\n")\
		_T("exists(select instance_id from e000000 where instance_id = e000005.a000166 and\n")\
		_T("UPPER(a000145) like '%s' and UPPER(a000146) like '%s'))"), sIdSQL, sNameSQL);

	long DlgId = aplStartWaitDlg( APL_T("Идет поиск систем..."),  APL_T("Поиск"));

	SaplSQLError err;
	APL_BEFOR_RUN_SQL;
	m_api->m_data.NET_RunSqlReturnExtent(NULL, rels, &err, sSQL, APL_IN_RUNSQL, 0, true);
	if(!err.m_LastErrDescr.IsEmpty())
	{
		TRACE_TO_FILE(err.m_LastErrDescr);
		aplEndWaitDlg(DlgId);
		return false;
	}

	// грузим аттрибуты
	CaplLoadData ld(&m_api->m_data, DEF_SOURCE);
	bool bLoad = false;
	for(int i=0; i<rels.Size; ++i)
	{
		ld.AddQuery(0, rels[i]);
		bLoad = true;
	}
	if (bLoad)
	{
		int i1 = ld.AddQuery(_T('d'), 0, 0, m_api->m_prd_mgr.a_pdr_r_ted, true);
		int i2 = ld.AddQuery(_T('d'), 0, 0, m_api->m_prd_mgr.a_pdr_r_ting, true);
		int i1_1 = ld.AddQuery(_T('d'), i1, 0, m_api->m_prd_mgr.a_pdf_prd, true);
		int i2_1 = ld.AddQuery(_T('d'), i2, 0, m_api->m_prd_mgr.a_pdf_prd, true);
		ld.AddQuery(_T('d'), i1_1, 0, m_api->m_prd_mgr.a_prd_id, true);
		ld.AddQuery(_T('d'), i1_1, 0, m_api->m_prd_mgr.a_prd_name, true);
		ld.AddQuery(_T('d'), i2_1, 0, m_api->m_prd_mgr.a_prd_id, true);
		ld.AddQuery(_T('d'), i2_1, 0, m_api->m_prd_mgr.a_prd_name, true);
		ld.LoadEx();
	}

	// читаем все связи из кэша
	m_api->m_data.GetEntityExtent(m_api->m_prd_mgr.e_pdr, rels);

	CaplInstance *pdf_r_ting, *pdf_r_ted, *prd;
	CString sBuf;
	for(int i=0; i<rels.Size; ++i)
	{
		if (!rels[i])
			continue;

		m_api->m_data.GetAttr(rels[i], m_api->m_prd_mgr.a_pdr_r_ting, pdf_r_ting);
		if (!pdf_r_ting)
			continue;

		m_api->m_data.GetAttr(rels[i], m_api->m_prd_mgr.a_pdr_r_ted, pdf_r_ted);
		if (!pdf_r_ted)
			continue;

		m_api->m_data.GetAttr(pdf_r_ted, m_api->m_prd_mgr.a_pdf_prd, prd);
		if (!prd)
			continue;

		if (!m_sId.IsEmpty())
		{
			m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_id, sBuf);
			if (sBuf.IsEmpty() || sBuf.GetLength()<m_sId.GetLength() || m_sId.CompareNoCase(sBuf.Left(m_sId.GetLength()))!=0)
				continue;
		}

		if (!m_sName.IsEmpty())
		{
			m_api->m_data.GetAttr(prd, m_api->m_prd_mgr.a_prd_name, sBuf);
			if (sBuf.IsEmpty() || sBuf.GetLength()<m_sName.GetLength() || m_sName.CompareNoCase(sBuf.Left(m_sName.GetLength()))!=0)
				continue;
		}

		if (!m_ExploitationMgr->IsPlaner(pdf_r_ting))
			continue;

		ext.Add(pdf_r_ted);
	}


	aplEndWaitDlg(DlgId);

	ShowItems(ext);

	return true;*/
}

bool CFindPDFDlg::FindZonePdf()
{
	if(!UpdateData()) return false;
	CaplAttrValue tst_values[2];
	aplExtent res, pdfs;
	tst_values[0].attr = m_api->m_prd_mgr.a_prd_id;
	tst_values[0].value.Set(m_sId);
	tst_values[1].attr = m_api->m_prd_mgr.a_prd_name;
	tst_values[1].value.Set(m_sName);
	long DlgId = aplStartWaitDlg( APL_T("Идет поиск комплектующих изделий..."),  APL_T("Поиск"));
	m_api->m_data.NET_FindInstancesWithAttrValues2(m_api->m_prd_mgr.e_prd, 2, &tst_values[0], res, true, false, NULL, aplSBLeft,false,DEF_SOURCE);
	m_api->m_prd_mgr.GetAllProductVersion(res, pdfs);

	CaplInstance *inst;
	aplExtent ext;
	int i;

	for(i=0; i<pdfs.GetSize(); i++)
	{
		inst = pdfs[i];
		if(inst==NULL) continue;
		if(inst->GetAccessmode()>aplRO) continue;

		//if(!m_ExploitationMgr->IsZone(inst)) continue;

		ext.Add(inst);
	}

	aplEndWaitDlg(DlgId);

	ShowItems(ext);

	return true;
}

bool CFindPDFDlg::FindAllPKIPdfs()
{
	if(!UpdateData()) return false;
	CaplAttrValue tst_values[2];
	aplExtent res, pdfs;
	tst_values[0].attr = m_api->m_prd_mgr.a_prd_id;
	tst_values[0].value.Set(m_sId);
	tst_values[1].attr = m_api->m_prd_mgr.a_prd_name;
	tst_values[1].value.Set(m_sName);
	long DlgId = aplStartWaitDlg( APL_T("Идет поиск комплектующих изделий..."),  APL_T("Поиск"));
	m_api->m_data.NET_FindInstancesWithAttrValues2(m_api->m_prd_mgr.e_prd, 2, &tst_values[0], res, true, false, NULL, aplSBLeft,false,DEF_SOURCE);
	m_api->m_prd_mgr.GetAllProductVersion(res, pdfs);

	CaplInstance *inst;
	aplExtent ext;
	int i;

	for(i=0; i<pdfs.GetSize(); i++)
	{
		inst = pdfs[i];
		if(inst==NULL) continue;
		if(inst->GetAccessmode()>aplRO) continue;

		//if(m_ExploitationMgr->IsPlaner(inst)) continue;
		//if(m_ExploitationMgr->IsSystem(inst)) continue;
		//if(m_ExploitationMgr->IsZone(inst)) continue;

		ext.Add(inst);
	}

	aplEndWaitDlg(DlgId);

	ShowItems(ext);

	return true;
}

void CFindPDFDlg::OnCreate() 
{
	if(!UpdateData()) return;
	if(m_Flags&APL_FD_AUTOCREATE)
	{
		if(m_sId.IsEmpty())
		{
			AfxMessageBox( APL_T("Необходимо указать шифр изделия"));
			return;
		}
		CaplInstance *pdf = m_api->m_prd_mgr.CreatePdf(m_sId, m_sName, _T(""));
		if(pdf)
		{
			aplExtent ext;
			ext.Add(pdf);
			ShowItems(ext);
		}
	}
	/*else
	{
		if(m_pCreateFunct)
		{
			CaplInstance* item = NULL;
			if(m_pCreateFunct(m_api, &item))
			{
				aplExtent ext;
				ext.Add(item);
				ShowItems(ext);
			}
		}
	}*/
}
