// QueryFormView.cpp : implementation file
//

#include "stdafx.h"
#include "resource.h"
#include "QueryFormView.h"
// #include "FindQueryDlgEx.h"
// #include "FindAdjustApprDlg.h"
// #include "FindAdjustDocDlg.h"
// #include "FindAdjustCharactDlg.h"
// #include "FindAdjustResourceDlg.h"
// #include "FindAdjustBlobDlg.h"
// #include "FindAdjustUserDateDlg.h"
#include "apl_api.h"

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


/*
#ifdef _DEBUG
// Функции преобразования типов - нужны исключительно при отладке
QBS QPE2QBS(QPE el){return (QBS)el;}
QBS QGO2QBS(QGO el){return (QBS)el;}
QBS QF2QBS (QF  el){return (QBS)el;}

QPE QBS2QPE(QBS el){return (QPE)el;}
QGO QBS2QGO(QBS el){return (QGO)el;}
QF  QBS2QF (QBS el){return (QF )el;}
#endif
*/






// CQueryFormView

IMPLEMENT_DYNCREATE(CQueryFormView, CaplFormView)

CQueryFormView::CQueryFormView()
	: CaplFormView(CQueryFormView::IDD)
	, m_ClassifierName(_T(""))
{
	m_IsSubstring = TRUE;
	m_bFindDoc=TRUE;
	m_PrdId = _T("");
	m_PrdName = _T("");
	m_PdfId = _T("");
	m_Classifier = 0;
//	Construct();
}

CQueryFormView::~CQueryFormView()
{
}

// CQueryFormView diagnostics

#ifdef _DEBUG
void CQueryFormView::AssertValid() const
{
	CaplFormView::AssertValid();
}

#ifndef _WIN32_WCE
void CQueryFormView::Dump(CDumpContext& dc) const
{
	CaplFormView::Dump(dc);
}
#endif
#endif //_DEBUG

// CQueryFormView message handlers

/////////////////////////////////////////////////////////////////////////////
// CQueryFormView 

void CQueryFormView::DoDataExchange(CDataExchange* pDX)
{
	CaplFormView::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CQueryFormView)
	DDX_Text(pDX, IDC_PRODUCT_ID, m_PrdId);
	DDX_Text(pDX, IDC_PRODUCT_NAME, m_PrdName);
	DDX_Text(pDX, IDC_PDF_ID, m_PdfId);
	DDX_Control(pDX, ID_EXECUTE_FIND, m_BtnFind);
	DDX_Check(pDX, IDC_CHK_SUBSTRING, m_IsSubstring);
	DDX_Check(pDX, IDC_CHK_FIND_DOC, m_bFindDoc);
	//}}AFX_DATA_MAP
	DDX_Text(pDX, IDC_CLASSIFIER, m_ClassifierName);
	DDX_Control(pDX, IDC_CLEAR_FIELDS, m_clear_btn);
	DDX_Control(pDX, IDC_PRODUCT_NAME, m_name_ctrl);
	DDX_Control(pDX, IDC_PRODUCT_ID, m_id_ctrl);
	DDX_Control(pDX, IDC_PDF_ID, m_ver_ctrl);
}

BEGIN_MESSAGE_MAP(CQueryFormView, CaplFormView)
	//{{AFX_MSG_MAP(CQueryFormView)
	ON_BN_CLICKED(ID_EXECUTE_FIND, OnExecuteFind)
	ON_EN_CHANGE(IDC_PRODUCT_ID, OnChangeEdit)
	ON_EN_CHANGE(IDC_PRODUCT_NAME, OnChangeEdit)
	ON_EN_CHANGE(IDC_PDF_ID, OnChangeEdit)
//	ON_COMMAND(ID_EDIT_COPY,OnCopy)
// 	ON_COMMAND(ID_EDIT_CUT,OnCut)
// 	ON_COMMAND(ID_EDIT_PASTE,OnPaste)
ON_EN_CHANGE(IDC_CLASSIFIER, &CQueryFormView::OnEnChangeClassifier)
ON_BN_CLICKED(IDC_CLASSIFIER_SELECT, &CQueryFormView::OnBnClickedClassifierSelect)
ON_BN_CLICKED(IDC_CLEAR_FIELDS, &CQueryFormView::OnBnClickedClearFields)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CQueryFormView message handlers
// Поведение при выборе/изменении искомого объекта и его аттрибутов

void CQueryFormView::OnInitialUpdate()
{
	CaplFormView::OnInitialUpdate();
	GetParentFrame()->RecalcLayout();

	m_BtnFind.SetIcon(GetAplStdIco16(APLSTDICO_PLAY));
	m_BtnFind.SetFlat(FALSE);

	m_clear_btn.SetWindowText(_T(""));
	m_clear_btn.SetIcon(GetAplStdIco16(APLSTDICO_DELETE));
	m_clear_btn.SetFlat(FALSE);
	m_clear_btn.SetTooltipText(APL_T("Очистить поля"));
}


/////////////////////////////////////////////////////////////////////////////////////
// Математика формирования запроса

void CQueryFormView::OnExecuteFind() 
{
 	aplExtent ext,ext1,ext_classif;
 	CString attr_prd = _T("");
	CString attr_stql;
	CString attr_4user;
	CString attr_condition = _T("");
	
	// Окончательный запрос
	CString QL_query_pdf;
	CString QL_query_doc;
	CString query_classif = _T(" ");
	CString buf;

	int i;

	if(m_pTableView == 0 ) 
	{
		AfxMessageBox(APL_T("Не выполнена инициализация таблицы!"));
		return;
	}

	UpdateData(TRUE);

	if(m_PrdId == _T("") && m_PrdName == _T("") && m_PdfId == _T(""))
	{
		AfxMessageBox(APL_T("Необходимо задать хотя бы одно условие!"));
		return;
	}

	if(m_Classifier == 0)
	{
		QL_query_pdf = _T("SELECT Ext_ FROM \n\t\t")
			_T("Ext_{apl_product_definition_formation(");
		QL_query_doc = _T("SELECT Ext_ FROM \n\t\t")
			_T("Ext_{document(");
	}
	else
	{
		QL_query_pdf = _T("SELECT Ext_ca FROM \n\t\t")
			_T("Ext_{apl_product_definition_formation(");
		QL_query_doc = _T("SELECT Ext_ca FROM \n\t\t")
			_T("Ext_{document(");

		//система (читаем все. возвращаем или 0 уровень, или все)
		if(m_api->m_data.IsKindOf(m_Classifier, m_api->m_classifier_mgr.e_apl_classifier_system))
		{
			// раскручиваем дерево справочников и находим все вложенные справочники
			m_api->m_classifier_mgr.LoadSubClassifierSystems(m_Classifier,ext_classif,true);
			ext_classif.Add(m_Classifier);
			query_classif = _T("\nExt_ca{apl_classifier_association (.item IN #Ext_ AND (");
			for(i=0;i<ext_classif.GetSize();i++)
			{
				buf.Format(_T(".system = #%i"),ext_classif.GetAt(i)->GetId());
				if(i>0)query_classif += _T(" OR ");
				query_classif += buf;
			}	
			query_classif += _T("))}.item\n");
		}
		else if(m_api->m_data.IsKindOf(m_Classifier, m_api->m_classifier_mgr.e_apl_classifier_level))
		{
			// раскручиваем дерево элементов справочников и находим все вложенные уровни
			m_api->m_classifier_mgr.LoadSubClassifierLevels(m_Classifier,ext_classif,true);
			ext_classif.Add(m_Classifier);
			query_classif = _T("\nExt_ca{apl_classifier_association (.item IN #Ext_ AND (");
			for(i=0;i<ext_classif.GetSize();i++)
			{
				buf.Format(_T(".classifier = #%i"),ext_classif.GetAt(i)->GetId());
				if(i>0)query_classif += _T(" OR ");
				query_classif += buf;
			}	
			query_classif += _T("))}.item\n");
		}
		else
		{
			AfxMessageBox(APL_T("Выбранный объект не является справочником или уровнем справочника!"));
			return;
		}
	}

	if(m_PrdId != _T(""))
	{
		attr_stql = _T(".id");
		attr_4user = APL_T("Обозначение изделия");
		m_PrdId.TrimLeft();m_PrdId.TrimRight();
		if(m_IsSubstring==TRUE)
		{
			m_api->m_query_mgr.MakeAttrConditionWithGroup(m_PrdId,attr_stql,attr_4user,false,attr_condition);
		}
		else
		{
			attr_condition = attr_stql + _T(" LIKE '") + m_PrdId + _T("'");
		}
		attr_prd = attr_condition;
	}
	if(m_PrdName != _T(""))
	{
		attr_stql = _T(".name");
		attr_4user = APL_T("Наименование изделия");
		m_PrdName.TrimLeft();m_PrdName.TrimRight();
		if(m_IsSubstring==TRUE)
		{
			m_api->m_query_mgr.MakeAttrConditionWithGroup(m_PrdName,attr_stql,attr_4user,false,attr_condition);
		}
		else
		{
			attr_condition = attr_stql + _T(" LIKE '") + m_PrdName + _T("'");
		}
		if(attr_prd != _T("")) attr_prd += _T(" AND ");
		attr_prd += attr_condition;
	}
	if(attr_prd != _T("")) QL_query_pdf += _T(".of_product->product(") + attr_prd + _T(") ");
	if(m_PdfId != _T(""))
	{
		attr_stql = _T(".id");
		attr_4user = APL_T("Версия изделия");
		m_PdfId.TrimLeft();m_PdfId.TrimRight();
		if(m_IsSubstring==TRUE)
		{
			m_api->m_query_mgr.MakeAttrConditionWithGroup(m_PdfId,attr_stql,attr_4user,false,attr_condition);
		}
		else
		{
			attr_condition = attr_stql + _T(" LIKE '") + m_PdfId + _T("'");
		}
		if(attr_prd != _T("")) QL_query_pdf += _T(" AND \n\t\t");
		QL_query_pdf += attr_condition;
	}
	QL_query_pdf += _T(")\n}") + query_classif + _T("END_SELECT");

	m_api->m_query_mgr.ExecuteQuery(QL_query_pdf,ext);
	//m_pTableView->UpdateTable(ext);

	
	//**********************************
	// теперь ищем документы
	//**********************************	

	if(m_bFindDoc && (m_PrdId!=_T("") || m_PrdName!=_T("")))
	{

		if(m_PrdId != _T(""))
		{
			attr_stql = _T(".id");
			attr_4user = APL_T("Обозначение документа");
			//m_PrdId.TrimLeft();m_PrdId.TrimRight();
			if(m_IsSubstring==TRUE)
			{
				m_api->m_query_mgr.MakeAttrConditionWithGroup(m_PrdId,attr_stql,attr_4user,false,attr_condition);
			}
			else
			{
				attr_condition = attr_stql + _T(" LIKE '") + m_PrdId + _T("'");
			}
			attr_prd = attr_condition;
		}
		if(m_PrdName != _T(""))
		{
			attr_stql = _T(".name");
			attr_4user = APL_T("Наименование документа");
			m_PrdName.TrimLeft();m_PrdName.TrimRight();
			if(m_IsSubstring==TRUE)
			{
				m_api->m_query_mgr.MakeAttrConditionWithGroup(m_PrdName,attr_stql,attr_4user,false,attr_condition);
			}
			else
			{
				attr_condition = attr_stql + _T(" LIKE '") + m_PrdName + _T("'");
			}
			if(attr_prd != _T("")) attr_prd += _T(" AND ");
			attr_prd += attr_condition;
		}
		QL_query_doc += attr_prd ;
		QL_query_doc += _T(")\n}") + query_classif + _T("END_SELECT");

		m_api->m_query_mgr.ExecuteQuery(QL_query_doc,ext1);
	}
	if(ext1.GetSize()>0 ) ext.Append(ext1);
	
	m_pTableView->UpdateTable(ext);
};


void CQueryFormView::OnChangeEdit() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CResizableDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO: Add your control notification handler code here
	CWnd* wnd_f = GetFocus();
	UpdateData(TRUE);
	if(m_PrdId != _T("") || m_PrdName != _T("") || m_PdfId != _T(""))
	{
		m_BtnFind.EnableWindow(TRUE);
	}
	else
	{
		m_BtnFind.EnableWindow(FALSE);
	}
	if(wnd_f != 0)wnd_f->SetFocus();
}

// void CQueryFormView::OnCopy()
// {
// 	CWnd* top_wnd = GetFocus();
// 	if(top_wnd)top_wnd->SendMessage(WM_COPY,0,0);
// }
//
// void CQueryFormView::OnCut()
// {
// 	CWnd* top_wnd = GetFocus();
// 	if(top_wnd)top_wnd->SendMessage(WM_CUT,0,0);
// }
// 
// void CQueryFormView::OnPaste()
// {
// 	CWnd* top_wnd = GetFocus();
// 	if(top_wnd)top_wnd->SendMessage(WM_PASTE,0,0);
// }

void CQueryFormView::OnEnChangeClassifier()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CaplFormView::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	SelectClassifier();
}

void CQueryFormView::OnBnClickedClassifierSelect()
{
	// TODO: Add your control notification handler code here
	SelectClassifier();
}

void CQueryFormView::SelectClassifier()
{
	m_Classifier = m_api->m_classifier_mgr.SelectInstanceEx(APL_MODE_SELECT_CLASSIF_ELEMENT | APL_MODE_SELECT_CLASSIF_SYSTEM,APL_T("Выбор справочника"));
	if(m_Classifier==0)
	{
		m_ClassifierName = _T("");
	}
	else
	{
		if(m_api->m_data.IsKindOf(m_Classifier, m_api->m_classifier_mgr.e_apl_classifier_level))
		{
			CString buf;
			CaplInstance* system;
			m_api->m_data.GetAttr(m_Classifier,m_api->m_classifier_mgr.a_apl_classifier_level_system,system);
			m_api->m_classifier_mgr.GetItemName(system,m_ClassifierName);
			m_ClassifierName += _T("::");
			m_api->m_classifier_mgr.GetItemName(m_Classifier,buf);
			m_ClassifierName += buf;
		}
		else
		{
			m_api->m_classifier_mgr.GetItemName(m_Classifier,m_ClassifierName);
		}
	}
	UpdateData(FALSE);
}
void CQueryFormView::OnBnClickedClearFields()
{
	m_name_ctrl.SetWindowText(_T(""));
	m_id_ctrl.SetWindowText(_T(""));
	m_ver_ctrl.SetWindowText(_T(""));
}
