// FindInContent.cpp : implementation file
//

#include "stdafx.h"
#include "resource.h"
#include "apl_api.h"
#include "FindInContent.h"
#include "FindQueryDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CFindInContent dialog


CFindInContent::CFindInContent(CWnd* pParent /*=NULL*/)
	: CResizableDialog(CFindInContent::IDD, pParent)
{
	//{{AFX_DATA_INIT(CFindInContent)
	m_Id = _T("??");
	m_Name = _T("??");
	m_Ver = _T("??");
	m_Filter = _T("");
	m_DateTime = _T("");
	m_Context = _T("");
	m_Sn = _T("");
	//}}AFX_DATA_INIT
	m_api=0;
	m_pdf=0;
	m_context=0;
	m_time.SetStatus(COleDateTime::null);
	m_reportCtrl.SetUniqueName(_T("apl_st_mgr__find_in_content"));

	m_DateTime= APL_T("не задано");
	m_Context= APL_T("все контексты");
	m_sn=_T("");
	m_def_file_name=_T("");	
	
}

CFindInContent::~CFindInContent()
{
}

void CFindInContent::DoDataExchange(CDataExchange* pDX)
{
	CResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CFindInContent)
	DDX_Control(pDX, IDC_SAVE_TO_FILE, m_BtnSaveToFile);
	DDX_Control(pDX, IDC_SELECT_TYPE, m_SelType);
	DDX_Control(pDX, IDC_FIND, m_BtnFind);
	DDX_Control(pDX, IDCANCEL, m_BtnCancel);
	DDX_Text(pDX, IDC_ID, m_Id);
	DDX_Text(pDX, IDC_NAME, m_Name);
	DDX_Text(pDX, IDC_VER, m_Ver);
	DDX_Text(pDX, IDC_FILTER, m_Filter);
	DDX_Text(pDX, IDC_DATE, m_DateTime);
	DDX_Text(pDX, IDC_CONTEXT, m_Context);
	DDX_Control(pDX, IDC_ST_LIST, m_st_list);
	DDX_Text(pDX, IDC_SN, m_Sn);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CFindInContent, CResizableDialog)
//{{AFX_MSG_MAP(CFindInContent)
ON_BN_CLICKED(IDC_SEL_CONTEXT_DATE_SN, OnSelContextDateSn)
ON_BN_CLICKED(IDC_SEL_FILTER, OnSelFilter)
ON_BN_CLICKED(IDC_FIND, OnFind)
ON_WM_SYSCOMMAND()
ON_BN_CLICKED(IDC_SAVE_TO_FILE, OnSaveToFile)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFindInContent message handlers

BOOL CFindInContent::OnInitDialog() 
{
	CResizableDialog::OnInitDialog();
	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   
	
	m_BtnFind.SetIcon(GetAplStdIco16(APLSTDICO_PLAY));
	m_BtnFind.SetFlat(FALSE);
	m_BtnSaveToFile.SetIcon(GetAplTableIco(APL_TABLE_SAVE));
	m_BtnSaveToFile.SetFlat(FALSE);
	m_BtnCancel.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_BtnCancel.SetFlat(FALSE);
	
	CString header,descr;
	// TODO: Add extra initialization here
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		pSysMenu->AppendMenu(MF_SEPARATOR);
		pSysMenu->AppendMenu(MF_STRING, ID_SHOW_STEPQL,  APL_T("Показать текст запроса"));
	}

	RECT rect={5,5,10,10};

	m_reportCtrl.Create(WS_VISIBLE|WS_CHILD|WS_BORDER|LVS_SHOWSELALWAYS|LVS_SINGLESEL,rect,this,IDC_ST_LIST1);
	
	m_st_list.GetWindowRect(&rect);
	ScreenToClient(&rect);
	m_reportCtrl.MoveWindow(&rect);
	
	ListView_SetExtendedListViewStyle(m_reportCtrl.m_hWnd,
		ListView_GetExtendedListViewStyle(m_reportCtrl.m_hWnd)
		|LVS_EX_UNDERLINECOLD |LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
	

	if(m_api!=0){
		if(m_pdf==0){
		}else{
			m_Context= APL_T("все контексты");
			m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_id,m_Ver);
			CaplInstance *tempInst=0;
			m_api->m_data.GetAttr(m_pdf,m_api->m_prd_mgr.a_pdf_prd,tempInst);
			if(tempInst)
			{
				m_api->m_data.GetAttr(tempInst,m_api->m_prd_mgr.a_prd_id,m_Id);
				m_api->m_data.GetAttr(tempInst,m_api->m_prd_mgr.a_prd_name,m_Name);
			}
			descr=m_Id+_T(" : ")+m_Name+_T(" : ")+m_Ver;

			GetWindowText(header);
			header+=_T(": ")+descr;
			SetWindowText(header);
		}
		
	}
	UpdateData(FALSE);
	
	AddAnchor(IDC_ID,TOP_LEFT, TOP_LEFT);
	AddAnchor(IDC_NAME,TOP_LEFT, TOP_LEFT);
	AddAnchor(IDC_VER,TOP_LEFT, TOP_LEFT);
	AddAnchor(IDC_CONTEXT,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_SELECT_TYPE,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_FILTER,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_STATIC_FILTER,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_DATE,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_SN,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_SEL_CONTEXT_DATE_SN,TOP_RIGHT, TOP_RIGHT);
	AddAnchor(IDC_SEL_FILTER,TOP_RIGHT, TOP_RIGHT);
	AddAnchor(IDC_ST_LIST1,TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_FIND,BOTTOM_RIGHT, BOTTOM_RIGHT);
	AddAnchor(IDCANCEL,BOTTOM_RIGHT, BOTTOM_RIGHT);
	
	m_SelType.SetCurSel(0);
	//заголовки столбцов
	RECT lpRect;
	m_reportCtrl.GetWindowRect(&lpRect);
	double width=lpRect.right-lpRect.left-1;
	m_reportCtrl.InsertColumn(0, APL_T("Обозначение"),LVCFMT_LEFT,(long)(width *.15));
	m_reportCtrl.InsertColumn(1, APL_T("Наименование"),LVCFMT_LEFT,(long)(width *.2));
	m_reportCtrl.InsertColumn(2, APL_T("Версия"),LVCFMT_LEFT,(long)(width *.1));
	m_reportCtrl.InsertColumn(3, APL_T("Описание"),LVCFMT_LEFT,(long)(width *.13));
	m_reportCtrl.InsertColumn(4, APL_T("Тип"),LVCFMT_LEFT,(long)(width *.13));
	m_reportCtrl.InsertColumn(5, APL_T("Код"),LVCFMT_LEFT,(long)(width *.1));
	m_reportCtrl.InsertColumn(6, APL_T("Источник"),LVCFMT_LEFT,(long)(width *.15));
	

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



void CFindInContent::OnSelContextDateSn() 
{
	// TODO: Add your control notification handler code here
	if(m_api==0)return;
	if(m_time.GetStatus()!=COleDateTime::valid) m_time.SetStatus(COleDateTime::null);
	CaplInstance *new_cont=0;
	m_DateTime= APL_T("не задано");
	m_Context= APL_T("все контексты");
	if(m_api->m_prd_mgr.SelectDateSN(m_sn,m_time,m_context,&new_cont))
	{
		m_Sn=m_sn;
		CString buf=_T("");
		if(m_time.GetStatus()==COleDateTime::valid){
			buf=m_time.Format(_T("%d.%m.%Y  %H:%M:%S"));
		}else{
			m_DateTime= APL_T("не задано");
		}
		m_DateTime=buf;
		buf=_T("");
		m_context=new_cont;
		if(m_context)
		{
			aplExtent aggr;
			aggr.Add(m_context);
			m_api->m_prd_mgr.PrintItemContextInString(aggr,buf);
		}else{
			buf= APL_T("все контексты");
		}
		m_Context=buf;
	}
	UpdateData(FALSE);
}

void CFindInContent::OnSelFilter() 
{
	// TODO: Add your control notification handler code here
	m_extents=_T("");m_fields=_T("");
	CFindQueryDlg dlg_std;
	dlg_std.m_can_save=false;
	dlg_std.m_api=m_api;
	dlg_std.m_can_make_table=false;
	dlg_std.m_StringNameQuery= APL_T("Фильтр на поиск по составу");
	dlg_std.m_vis_mode=APL_MODE_SELECT_PDF;
	dlg_std.m_instance=0;
	dlg_std.m_mode_slave=true;
	
	dlg_std.SetDataBuf(m_filter_query_buf);
	if(dlg_std.DoModal()!=IDCANCEL){
		dlg_std.GetDataBuf(m_filter_query_buf);
		m_extents=dlg_std.m_extents;
		m_fields=dlg_std.m_fields;
		m_Filter=dlg_std.m_descrtiption;
	}
	UpdateData(FALSE);
}


bool CFindInContent::MakeExtent(bool is_dialog)
{
	bool flag;
	bool res;
	int i;
	aplInstArray ext_pdf;
	aplRealArray count_array;
	aplInstArray ext_unit;
	CString buf1,buf2;
	
	m_result_ext.Clear();
	m_SelType.GetWindowText(buf1);
	flag=(buf1!= APL_T("полном составе"));
	m_query=_T("");

	TCHAR *pSN=0;
	COleDateTime *dt=0;
	
	if(m_sn!=_T("")) {pSN=(LPTSTR)LPCTSTR(m_sn);}
	if(m_time.GetStatus()==COleDateTime::valid)
	{
		dt=new COleDateTime(m_time.GetYear(),m_time.GetMonth(),m_time.GetDay(),
			m_time.GetHour(),m_time.GetMinute(),m_time.GetSecond());
	}
	res=m_api->m_prd_mgr.DisassemblyProductEx(0,m_context,m_pdf,ext_pdf,count_array,ext_unit,
		dt,pSN,flag);
	
	if(dt!=0) delete dt;
	if(!res){
		AfxMessageBox( APL_T("Ошибка получения состава изделия!"));
		return false;
	}
	if(ext_pdf.Size==0){
		AfxMessageBox( APL_T("Состав изделия отсутствует!"));
		return false;
	}
	if(m_fields==_T("") && m_extents==_T("")){
		m_result_ext.Append(*((aplExtent*)&ext_pdf));
	}else{
		buf1=_T("\nExt_composed{");
		for(i=0;i<ext_pdf.Size;i++){
			buf2.Format(_T("#%i"),ext_pdf.GetAt(i)->GetId());
			if(i>0)buf1+=_T(",");
			buf1+=buf2;
		}
		buf1+=_T("}\n");
		
		m_query=_T("SELECT\n");
		if(m_fields==_T("")){
			m_query+=_T(" Ext_composed");
		}else{
			m_query+=m_fields + _T(" AND Ext_composed");
		}
		m_query+=_T("\nFROM\n")+buf1+m_extents+_T("\nEND_SELECT");
		if(is_dialog){
			m_api->m_data.NET_QueryEditParse(m_query,true);
		}
		
		res=m_api->m_query_mgr.ExecuteQuery(m_query,m_result_ext);
		if(!res){
			AfxMessageBox( APL_T("Ошибка выполнения запроса!"));
			return false;
		}	
	}	
	
	return true;
}

void CFindInContent::OnFind() 
{
	// TODO: Add your control notification handler code here
	int i;
	CaplInstance *pdf,*prd;
	aplInstArray ext_pdf;
	aplRealArray count_array;
	aplInstArray ext_unit;
	CString buf1,buf2;
	m_reportCtrl.DeleteAllItems();
	
	if(!MakeExtent())
		return;

	buf1.Format( APL_T("Найдено %i"),m_result_ext.Size);
	AfxMessageBox(buf1);
	// Вставка результата
	for(i=0;i<m_result_ext.Size;i++){
		pdf=m_result_ext.GetAt(i);
		if(pdf==0)continue;
		if(pdf->GetType()==0)continue;
		m_api->m_data.GetAttr(pdf,m_api->m_prd_mgr.a_pdf_prd,prd);
		if(prd==0)continue;
		if(prd->GetType()==0)continue;
		
		m_reportCtrl.InsertItem(i,buf1);
		//"Обозначение изделия"
		m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_id,buf1);
		m_reportCtrl.SetItemText(i,0,buf1);
			
		//"Наименование",LVCFMT
		m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_name,buf1);
		m_reportCtrl.SetItemText(i,1,buf1);
		//"Обозначение версии",
		m_api->m_data.GetAttr(pdf,m_api->m_prd_mgr.a_pdf_id,buf1);
		m_reportCtrl.SetItemText(i,2,buf1);
		//"Описание",LVCFMT_LEF
		m_api->m_data.GetAttr(prd,m_api->m_prd_mgr.a_prd_descr,buf1);
		m_reportCtrl.SetItemText(i,3,buf1);
		//"Тип",LVCFMT_LEFT,(lo
		m_api->m_data.GetAttr(pdf,m_api->m_prd_mgr.a_apl_pdf_type,buf1);
		buf1=m_api->m_prd_mgr.StrConvertPdfType2Rus(buf1);
		m_reportCtrl.SetItemText(i,4,buf1);
		//"Код",LVCFMT_RIGHT,(l}
		m_api->m_data.GetAttr(pdf,m_api->m_prd_mgr.a_pdf_code,buf1);
		m_reportCtrl.SetItemText(i,5,buf1);
		//"Источник",LVCFMT_RIG	
		m_api->m_data.GetAttr(pdf,m_api->m_prd_mgr.a_pdfwss_source,buf1);
		buf1=m_api->m_prd_mgr.StrConvertMakeOrBuy2Rus(buf1);
		m_reportCtrl.SetItemText(i,6,buf1);
	}
	
}

void CFindInContent::OnSaveToFile() 
{
	// TODO: Add your control notification handler code here
	apl_SaveListCtrlToFile(&m_reportCtrl,LPCTSTR(m_def_file_name));
}

void CFindInContent::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID ) == ID_SHOW_STEPQL)
	{
		MakeExtent(true);
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

