#include "stdafx.h"
#include "aplFaultsReport.h"
#include "PdfAndStagesReportData.h"

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

CString GetExePath();

CaplQuery arrQueries[] =
{
	CaplQuery(APL_T("Карточка Г"), _T("GetFaultReport"), 0),
	CaplQuery(APL_T("Отчет ГРПЗ по отказам"), _T("GetGRPZReportHeader"), 0),
	CaplQuery(APL_T("Количество и процентное соотношение по изделиям и этапам"), _T("GetPdfAndStagesReportHeader"), 0),
	CaplQuery(APL_T("Карта возврата продукции"), _T("GetProductionReturnHeader"), 0),
};

//////////////////////////////////////////////////////////////////////////

DLL_EXPORT bool GetQueryList(CArray<CaplQuery, CaplQuery> *pQueriesArray)
{
	int iSize = sizeof(arrQueries) / sizeof(CaplQuery);
	
	for (int iIndex = 0; iIndex < iSize; iIndex++)
		pQueriesArray->Add(arrQueries[iIndex]);

	return true;
}

void SetPdfAndStagesReportHeader(CHeader *pHeader)
{
	pHeader->AddColumn(_T("pdf"), aplSTRING);
	pHeader->AddColumn(_T("stage"), aplSTRING);
	pHeader->AddColumn(_T("val1"), aplSTRING);
	pHeader->AddColumn(_T("val2"), aplSTRING);
}

void SetHeader(CHeader *pHeader)
{
	if(!pHeader) return;
	pHeader->AddColumn(_T("RefusalNum"), aplSTRING);
	pHeader->AddColumn(_T("TechReportNum"), aplSTRING);
	pHeader->AddColumn(_T("DetectDate"), aplSTRING);
	pHeader->AddColumn(_T("Org"), aplSTRING);
	pHeader->AddColumn(_T("Name"), aplSTRING);
	pHeader->AddColumn(_T("Id"), aplSTRING);
	pHeader->AddColumn(_T("SerialNumber"), aplSTRING);
	pHeader->AddColumn(_T("CreationDate"), aplSTRING);
	pHeader->AddColumn(_T("Manifistation"), aplSTRING);
	pHeader->AddColumn(_T("AnalysResults"), aplSTRING);
	pHeader->AddColumn(_T("ResultDisicion"), aplSTRING);
	pHeader->AddColumn(_T("Classification"), aplSTRING);
	pHeader->AddColumn(_T("AnalysDocNum"), aplSTRING);
	pHeader->AddColumn(_T("AnalysDocDate"), aplSTRING);
	pHeader->AddColumn(_T("AdditionalInfo"), aplSTRING);	
}

bool SetProductionReturnHeader(CHeader *pHeader)
{
	return true;
}

DLL_EXPORT bool GetProductionReturnHeader(CaplQuery* query, CRParamsArray& m_params, UINT mode)
{
	if (mode != APL_GET_HEADER)
		return false;

	if (query == NULL)
		return false;

	// первый лист
	m_params.Add(_T("DocNumber"));
	m_params.Add(_T("DocDate"));
	m_params.Add(_T("PrdName"));
	m_params.Add(_T("PrdId"));
	m_params.Add(_T("PrdInstId"));
	m_params.Add(_T("ParentItem"));
	m_params.Add(_T("Count"));
	m_params.Add(_T("Resources"));	

	// второй лист
	m_params.Add(_T("AnalysActNum"));	
	m_params.Add(_T("AnalysActDate"));
	m_params.Add(_T("VupuskDate"));
	m_params.Add(_T("TechnicalState"));
	m_params.Add(_T("ActualRefusal"));
	m_params.Add(_T("RefusalReason"));
	m_params.Add(_T("DeffectCode"));
	m_params.Add(_T("ReasonCode"));
	m_params.Add(_T("Classifiaction"));
	m_params.Add(_T("ListOfBadProduct"));
	m_params.Add(_T("NecassaryArrangments"));
	m_params.Add(_T("CommissionVerdict"));
	m_params.Add(_T("Expense"));	

	return SetProductionReturnHeader(query->m_header);
}

DLL_EXPORT bool GetGRPZReportHeader(CaplQuery* query, CRParamsArray& m_params, UINT mode)
{
	SetHeader(query->m_header);
	return true;
}

DLL_EXPORT bool GetPdfAndStagesReportHeader(CaplQuery* query, CRParamsArray& m_params, UINT mode)
{
	SetPdfAndStagesReportHeader(query->m_header);

	m_params.Add(_T("Year1"));
	m_params.Add(_T("Year2"));

	return true;
}

DLL_EXPORT bool GetFaultReport(CaplQuery *pQuery, CRParamsArray &arrParams, UINT uiMode)
{
	if (uiMode != APL_GET_HEADER)
		return false;

	if (pQuery == NULL)
		return false;

	// Лист 1
	arrParams.Add(_T("CardNumber"));
	arrParams.Add(_T("WorkshopNumber"));
	arrParams.Add(_T("AreaNumber"));
	arrParams.Add(_T("Date"));
	arrParams.Add(_T("GeneralType"));
	arrParams.Add(_T("GeneralProductNumber"));
	arrParams.Add(_T("SubsystemCode"));
	arrParams.Add(_T("PKI_Name"));
	arrParams.Add(_T("Code"));
	arrParams.Add(_T("PKI_FactoryNumber"));
	arrParams.Add(_T("ProductionDate"));
	arrParams.Add(_T("AggregateName"));
	arrParams.Add(_T("AggregateCode"));
	arrParams.Add(_T("AggregateFactoryNumber"));
	arrParams.Add(_T("AggregateProductionDate"));
	arrParams.Add(_T("TotalOperatingTime"));
	arrParams.Add(_T("DefectDescription"));
	arrParams.Add(_T("DefectCode"));
	arrParams.Add(_T("PKI_Appearance"));
	arrParams.Add(_T("DefectConditions"));
	arrParams.Add(_T("DefectConditionsCode"));
	arrParams.Add(_T("DefectEliminationMethod"));
	arrParams.Add(_T("DefectReasonCode"));
	arrParams.Add(_T("ChiefEngineerName"));
	arrParams.Add(_T("CustomerName"));
	arrParams.Add(_T("BTK_WorkerName"));

	arrParams.Add(_T("ProductName"));
	arrParams.Add(_T("ProductComplectNumber"));
	arrParams.Add(_T("FaultDescription"));
	arrParams.Add(_T("CardFillerName"));
	arrParams.Add(_T("CardFillDay"));
	arrParams.Add(_T("CardFillMonth"));
	arrParams.Add(_T("CardFillYear"));
	arrParams.Add(_T("PKI_ExaminationWorkshopNumber"));
	arrParams.Add(_T("PKI_ExaminationLaboratoryNumber"));

	// Лист 2
	arrParams.Add(_T("PVK_ExaminationResult"));
	arrParams.Add(_T("27_ChapterValue"));
	arrParams.Add(_T("28_ChapterValue"));
	arrParams.Add(_T("RepairDecisionCode"));
	arrParams.Add(_T("GuiltyDecisionCode"));
	arrParams.Add(_T("LaboratoryChiefName"));
	arrParams.Add(_T("PVK_EngineerName"));
	arrParams.Add(_T("CustomerRepresenterName"));
	arrParams.Add(_T("DefectEliminationDescription"));
	arrParams.Add(_T("DefectEliminationCode"));
	arrParams.Add(_T("WorkshopCommissionDecisionNumber"));
	arrParams.Add(_T("WorkshopCommissionDecision"));
	arrParams.Add(_T("CommissionChairman"));
	arrParams.Add(_T("CommissionMember1"));
	arrParams.Add(_T("CommissionMember2"));
	arrParams.Add(_T("SupplierRepresenterName"));

	return true;
}

DLL_EXPORT bool GenPdfAndStagesReport(CaplAPI *api, aplExtent &aeRefusal, CString strPath, BOOL bShowReport)
{
	// проверки на вшивость
	if(!api) return false;
	if(!api->m_data.IsConnected()) return false;
	if(aeRefusal.Size == 0) return false;

	// переменные
	int i;
	CaplMap mainMap;
	CRParamsArray arrParams;
	CaplReportMgr aplReportMgr;
	CDataSource	  *pDataSource;
	CString sPrd, sStage, sVal1, sVal2;
	CaplInstance *ciItem, *ciPrd, *ciPdf;
	CaplPreExploitationMgr *mgr = (CaplPreExploitationMgr*)api->m_expl_mgr;
	CString strTemplatePath = GetExePath() + CString(APL_T("Отказы_по_изделиям_по_этапам.apldot"));
	CPdfAndStagesReportData Data(api, mgr);

	// инициализация всякой лабуды
	aplReportMgr.Init();
	pDataSource = &aplReportMgr.m_data_source;
	CHeader* header = new CHeader(NULL);
	SetPdfAndStagesReportHeader(header);
	pDataSource->SetHeader(header);

	// смотрим куда будем сохранять
	if (strPath.IsEmpty())
	{
		CFileDialog dlg(FALSE, _T("aplrep"), _T(""), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, APL_T("Файлы отчётов (*.aplrep)|*.aplrep|Все файлы (*.*)|*.*||"));

		if (dlg.DoModal() != IDOK)
			return false;

		strPath = dlg.GetPathName();
	}	

	long dID = aplStartWaitDlg(APL_T("Формирование отчета..."));

	// формирование данных
	for(i=0; i<aeRefusal.Size; i++)
	{
		if(!aeRefusal[i]) continue;
		if(!aeRefusal[i]->GetType()) continue;

		// экземпляр
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_item, ciItem);
		if(!ciItem) continue;

		// версия изделия
		api->m_data.GetAttr(ciItem, api->m_prd_inst_mgr.a_prd_inst_pdf, ciPdf);
		if(!ciPdf) continue;

		// изделие
		api->m_data.GetAttr(ciPdf, api->m_prd_mgr.a_pdf_prd, ciPrd);
		if(!ciPrd) continue;

		// добавляем отказ в массив
		Data.Add(ciPrd, aeRefusal[i]);
	}

	// добавляем данные в отчет
	Data.FillReportWithData(pDataSource);	

	arrParams.Add(_T("Year1"), Data.m_CurrYear + APL_T(" год"));
	arrParams.Add(_T("Year2"), Data.m_PrevYear + APL_T(" год"));

	// генерируем отчет
	bool bRes = GenerateReport(&aplReportMgr, &arrParams, strTemplatePath, strPath, &api->m_data);
	aplEndWaitDlg(dID);

	if (bRes)
	{
		if (AfxMessageBox(_T("Отчёт успешно создан, открыть?"), MB_YESNO | MB_ICONQUESTION) == IDYES)
		{
			CString strCommandLine;

			strCommandLine = GetExePath() + CString(_T("ReportConstructor.exe"));
			ShellExecute(NULL, _T("open"), strPath, NULL, NULL, SW_SHOW);
		}
	}
	else
		AfxMessageBox(_T("Отчёт не был создан."), MB_OK | MB_ICONEXCLAMATION);

	return bRes;		
}

DLL_EXPORT bool GenGRPZReport(CaplAPI *api, aplExtent &aeRefusal, CString strPath, BOOL bShowReport)
{
	// проверки на вшивость
	if(!api) return false;
	if(!api->m_data.IsConnected()) return false;
	if(aeRefusal.Size == 0) return false;

	// переменные
	CRParamsArray arrParams;
	CaplReportMgr aplReportMgr;
	CDataSource	  *pDataSource;
	CaplPreExploitationMgr *mgr = (CaplPreExploitationMgr*)api->m_expl_mgr;
	CString strTemplatePath = GetExePath() + CString(APL_T("ГРПЗ.apldot"));

	COleDateTime time;
	CaplInstance *ciItem, *ciPdf, *ciPrd, *ciOrg, *ciDof;
	CString sAnalysDocNum, sAnalysDocDate, sAdditionalInfo;
	CString sRefNum, sTechReportNum, sDetectDate, sOrg, sName, sId, sSerialNum;
	CString sCreationDate, sManifistation, sAnalysResult, sResultDecision, sClassification;
	
	// инициализация всякой лабуды
	aplReportMgr.Init();
	pDataSource = &aplReportMgr.m_data_source;
	CHeader* header = new CHeader(NULL);
	SetHeader(header);
	pDataSource->SetHeader(header);
		
	// смотрим куда будем сохранять
	if (strPath.IsEmpty())
	{
		CFileDialog dlg(FALSE, _T("aplrep"), _T(""), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, APL_T("Файлы отчётов (*.aplrep)|*.aplrep|Все файлы (*.*)|*.*||"));

		if (dlg.DoModal() != IDOK)
			return false;

		strPath = dlg.GetPathName();
	}	

	// построение отчета
	long dID = aplStartWaitDlg(APL_T("Формирование отчета..."));
	for(int i=0; i<aeRefusal.Size; i++)
	{
		if(!aeRefusal[i]) continue;
		if(!aeRefusal[i]->GetType()) continue;

		// обнуляем
		sClassification.Empty();
		sAnalysDocNum.Empty(), sAnalysDocDate.Empty(), sAdditionalInfo.Empty();
		sRefNum.Empty(), sTechReportNum.Empty(), sDetectDate.Empty(), sOrg.Empty(); 
		sName.Empty(), sId.Empty(), sSerialNum.Empty(), sCreationDate.Empty();
		sManifistation.Empty(), sAnalysResult.Empty(), sResultDecision.Empty();

		//RefusalNum

		//TechReportNum

		//DetectDate
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_date_detection, sDetectDate);
		if(!sDetectDate.IsEmpty())
		{
			aplString2Date(sDetectDate, time);
			sDetectDate.Format(_T("%.2d.%.2d.%.4d"), time.GetDay(), time.GetMonth(), time.GetYear());
		}

		//Org
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_sector, ciOrg);
		if(!ciOrg) api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_org, ciOrg);
		if(ciOrg) api->GetItemName(ciOrg, sOrg);

		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_part, ciItem);
		if(!ciItem) api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_item, ciItem);

		if(ciItem)
		{
			bool bPdf = false;

			if(api->m_data.IsKindOf(ciItem, api->m_prd_mgr.e_pdf)) { ciPdf = ciItem; bPdf = true; }
			else api->m_data.GetAttr(ciItem, api->m_prd_inst_mgr.a_prd_inst_pdf, ciPdf);

			if(ciPdf)
			{
				api->m_data.GetAttr(ciPdf, api->m_prd_mgr.a_pdf_prd, ciPrd);
				if(ciPrd)
				{
					//Name
					api->m_data.GetAttr(ciPrd, api->m_prd_mgr.a_prd_name, sName);
					
					//Id
					api->m_data.GetAttr(ciPrd, api->m_prd_mgr.a_prd_id, sId);
				}
			}

			if(!bPdf)
			{
				//SerialNumber
				api->m_data.GetAttr(ciItem, api->m_prd_inst_mgr.a_prd_inst_sn, sSerialNum);

				//CreationDate
				api->m_data.GetAttr(ciItem, api->m_prd_inst_mgr.a_prd_inst_datetime, sCreationDate);
				if(!sCreationDate.IsEmpty())
				{
					aplString2Date(sCreationDate, time);
					sCreationDate.Format(_T("%.2d.%.2d.%.4d"), time.GetDay(), time.GetMonth(), time.GetYear());
				}
			}
		}

		//Manifistation
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_manifestation_str, sManifistation);

		//AnalysResults
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_research_result, sAnalysResult);

		//ResultDisicion
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_result_decision, sResultDecision);

		//Classification
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_dof, ciDof);
		if(ciDof) api->m_data.GetAttr(ciDof, api->m_classifier_mgr.a_apl_classifier_level_name, sClassification);

		//AnalysDocNum
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_research_act_str, sAnalysDocNum);

		//AnalysDocDate
		api->m_data.GetAttr(aeRefusal[i], mgr->a_apl_refusal_research_act_date, sAnalysDocDate);
		if(!sAnalysDocDate.IsEmpty())
		{
			aplString2Date(sAnalysDocDate, time);
			sAnalysDocDate.Format(_T("%.2d.%.2d.%.4d"), time.GetDay(), time.GetMonth(), time.GetYear());
		}

		//AdditionalInfo

		// итоговая строка отчета
		CTableRow *pRow = new CTableRow;
		pRow->AddColumn(sRefNum);
		pRow->AddColumn(sTechReportNum);
		pRow->AddColumn(sDetectDate);
		pRow->AddColumn(sOrg);
		pRow->AddColumn(sName);
		pRow->AddColumn(sId);
		pRow->AddColumn(sSerialNum);
		pRow->AddColumn(sCreationDate);
		pRow->AddColumn(sManifistation);
		pRow->AddColumn(sAnalysResult);
		pRow->AddColumn(sResultDecision);
		pRow->AddColumn(sClassification);
		pRow->AddColumn(sAnalysDocNum);
		pRow->AddColumn(sAnalysDocDate);
		pRow->AddColumn(sAdditionalInfo);

		pDataSource->AddRow(pRow);
	}

	// генерируем отчет
	bool bRes = GenerateReport(&aplReportMgr, &arrParams, strTemplatePath, strPath, &api->m_data);
	aplEndWaitDlg(dID);

	if (bRes)
	{
		if (AfxMessageBox(_T("Отчёт успешно создан, открыть?"), MB_YESNO | MB_ICONQUESTION) == IDYES)
		{
			CString strCommandLine;

			strCommandLine = GetExePath() + CString(_T("ReportConstructor.exe"));
			ShellExecute(NULL, _T("open"), strPath, NULL, NULL, SW_SHOW);
		}
	}
	else
		AfxMessageBox(_T("Отчёт не был создан."), MB_OK | MB_ICONEXCLAMATION);

	return bRes;	
}

bool GenProductReturnReport( CaplAPI *api, CaplInstance *ciRefusal, CString strPath /*= _T("")*/, BOOL bShowReport /*= TRUE*/ )
{
	if ((api == NULL) || (!api->m_data.IsConnected()) || (ciRefusal == NULL))
		return false;

	// переменные
	//double dValue;
	COleDateTime time;
	CaplPreExploitationMgr *mgr = (CaplPreExploitationMgr*)api->m_expl_mgr;
	CaplReportMgr aplReportMgr;
	CRParamsArray arrParams;
	CString sAnalysNum, sAnalysDate, sReasonName, sReasonCode;
	CDataSource	  *pDataSource = &aplReportMgr.m_data_source;
	CString       strTemplatePath = GetExePath() + CString(APL_T("Карта_возврата_продукции.apldot"));
	CString sDocNum, sDocDate, sPrdName, sPrdId, sPrdInstId, sParentItem, sCount = _T("1"), sResources;
	//CaplInstance *ciPart, *ciPdf, *ciPrd, *ciPlaner, *ciCharact, *ciCharVal, *ciLvlReason;
	CaplInstance *ciPart, *ciPdf, *ciPrd, *ciPlaner,/* *ciCharact, *ciCharVal,*/ *ciLvlReason;

	// инициализация генератора отчета
	aplReportMgr.Init();
	CHeader* header = new CHeader(NULL);
	pDataSource->SetHeader(header);	

	// узнаем куда сохранять
	if (strPath.IsEmpty())
	{
		CFileDialog dlg(FALSE, _T("aplrep"), _T(""), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, APL_T("Файлы отчётов (*.aplrep)|*.aplrep|Все файлы (*.*)|*.*||"));

		if (dlg.DoModal() != IDOK)
			return false;

		strPath = dlg.GetPathName();
	}	

	// номер документа
	api->m_data.GetAttr(ciRefusal, mgr->a_apl_refusal_doc_num, sDocNum);
	arrParams.Add(_T("DocNumber"), sDocNum);

	// дата создания документа
	api->m_data.GetAttr(ciRefusal, mgr->a_apl_refusal_doc_date, sDocDate);
	aplString2Date(sDocDate, time);
	sDocDate.Format(_T("%.2d.%.2d.%.4d"), time.GetDay(), time.GetMonth(), time.GetYear());
	arrParams.Add(_T("DocDate"), sDocDate);

	api->m_data.GetAttr(ciRefusal, mgr->a_apl_refusal_part, ciPart);
	if(ciPart)
	{
		// заводской номер
		api->m_data.GetAttr(ciPart, api->m_prd_inst_mgr.a_prd_inst_id, sPrdInstId);
		arrParams.Add(_T("PrdInstId"), sPrdInstId);

		api->m_data.GetAttr(ciPart, api->m_prd_inst_mgr.a_prd_inst_pdf, ciPdf);
		if(ciPdf)
		{
			api->m_data.GetAttr(ciPdf, api->m_prd_mgr.a_pdf_prd, ciPrd);
			if(ciPrd)
			{
				api->m_data.GetAttr(ciPrd, api->m_prd_mgr.a_prd_name, sPrdName);
				api->m_data.GetAttr(ciPrd, api->m_prd_mgr.a_prd_id, sPrdId);

				// наименование и децимальный номер
				arrParams.Add(_T("PrdName"), sPrdName);
				arrParams.Add(_T("PrdId"), sPrdId);
			}
		}
	}

	// основное изделие
	api->m_data.GetAttr(ciRefusal, mgr->a_apl_refusal_planer, ciPlaner);
	
	//if(ciPlaner) mgr->GetPlanerName(ciPlaner, sParentItem); // Убрано при отказе от ExploitationMgr
	if(ciPlaner) api->GetItemName(ciPlaner, sParentItem);

	arrParams.Add(_T("ParentItem"), sParentItem);

	// количество
	arrParams.Add(_T("Count"), sCount);

	// наработка
	/* Убрано при отказе от ExploitationMgr
	ciCharact = api->m_charact_mgr.GetCharacteristicBN(APL_T("ресурс в часах"));
	if(ciCharact)
	{
		ciCharVal = api->m_charact_mgr.FindCharacteristic(ciRefusal, ciCharact, mgr->m_ResTypes.Vyrab);
		if(ciCharVal)
		{
			api->m_data.GetAttr(ciCharVal, api->m_charact_mgr.a_apl_charact_val_meas_val, dValue);
			sResources.Format(APL_T("%g ч"), dValue);
			arrParams.Add(_T("Resources"), sResources);
		}		
	}*/

	// причина
	api->m_data.GetAttr(ciRefusal, mgr->a_apl_refusal_faultreason, ciLvlReason);
	if(ciLvlReason) api->m_data.GetAttr(ciLvlReason, api->m_classifier_mgr.a_apl_classifier_level_name, sReasonName);
	arrParams.Add(_T(""), sReasonName);

	api->m_data.GetAttr(ciRefusal, mgr->a_apl_refusal_research_act_str, sAnalysNum);
	arrParams.Add(_T("AnalysActNum"), sAnalysNum);	

	api->m_data.GetAttr(ciRefusal, mgr->a_apl_refusal_research_act_date, sAnalysDate);
	aplString2Date(sAnalysDate, time);
	sAnalysDate.Format(_T("%.2d.%.2d.%.4d"), time.GetDay(), time.GetMonth(), time.GetYear());
	arrParams.Add(_T("AnalysActDate"), sAnalysDate);

	arrParams.Add(_T("VupuskDate"), _T(""));
	arrParams.Add(_T("TechnicalState"), _T(""));
	arrParams.Add(_T("ActualRefusal"), _T(""));

	api->m_data.GetAttr(ciRefusal, mgr->a_apl_refusal_faultreason, ciLvlReason);
	if(ciLvlReason)
	{
		api->m_data.GetAttr(ciLvlReason, api->m_classifier_mgr.a_apl_classifier_level_name, sReasonName);
		api->m_data.GetAttr(ciLvlReason, api->m_classifier_mgr.a_apl_classifier_level_id, sReasonCode);
	}

	arrParams.Add(_T("RefusalReason"), sReasonName);
	arrParams.Add(_T("DeffectCode"), _T(""));
	arrParams.Add(_T("ReasonCode"), sReasonCode);

	arrParams.Add(_T("Classifiaction"), _T(""));
	arrParams.Add(_T("ListOfBadProduct"), _T(""));
	arrParams.Add(_T("NecassaryArrangments"), _T(""));
	arrParams.Add(_T("CommissionVerdict"), _T(""));
	arrParams.Add(_T("Expense"), _T(""));

	// создание отчета
	bool bRes = GenerateReport(&aplReportMgr, &arrParams, strTemplatePath, strPath, &api->m_data);

	if (bRes)
	{
		if (AfxMessageBox(_T("Отчёт успешно создан, открыть?"), MB_YESNO | MB_ICONQUESTION) == IDYES)
		{
			CString strCommandLine;

			strCommandLine = GetExePath() + CString(_T("ReportConstructor.exe"));
			ShellExecute(NULL, _T("open"), strPath, NULL, NULL, SW_SHOW);
		}
	}
	else
		AfxMessageBox(_T("Отчёт не был создан."), MB_OK | MB_ICONEXCLAMATION);

	return bRes;

}

bool GenFaultReportSheet(CaplAPI *pAPI, CaplInstance *pRefusalInstance, CString strPath/* = _T("")*/, BOOL bShowReport/* = TRUE*/)
{
	if ((pAPI == NULL) || (!pAPI->m_data.IsConnected()) || (pRefusalInstance == NULL))
		return false;

	CaplPreExploitationMgr *pMgr = (CaplPreExploitationMgr*)pAPI->m_expl_mgr;
	CaplInstance *pRefusalPlaner = NULL;
	CaplInstance *pRefusalSystem = NULL;
	CaplInstance *pRefusalPart = NULL;
	CaplInstance *pRefusalItem = NULL;
	CaplInstance *pRefusalConditions = NULL;
	CaplInstance *pRefusalMethod = NULL;
	CaplInstance *pRefusalFaultReason = NULL;
	CaplInstance *pRefusalType = NULL;
	CaplInstance *pRefusalTestDeduction = NULL;
	CaplInstance *pRefusalCulpritDeduction = NULL;
	CaplInstance *pProductPDF = NULL;
	CaplInstance *pProductPRD = NULL;
	CaplInstance *pOrg = NULL;
	CString strDescr = _T("");
	CString strVersion = _T("");
	CString strName = _T("");
	CString strValue = _T("");

	CaplReportMgr aplReportMgr;
	CRParamsArray arrParams;
	CDataSource	  *pDataSource = &aplReportMgr.m_data_source;
	CString       strTemplatePath = GetExePath() + CString(APL_T("Карточка_Г.apldot"));
	TCHAR arrMonth[12][10] = 
		{
			{_T("января")}, {_T("февраля")}, {_T("марта")}, 
			{_T("апреля")}, {_T("мая")}, {_T("июня")}, 
			{_T("июля")}, {_T("августа")}, {_T("сентября")}, 
			{_T("октября")}, {_T("ноября")}, {_T("декабря")}
		};

	aplReportMgr.Init();
	
	//Заголовок
	CHeader* header = new CHeader(NULL);
//	SetHeader(header);
	pDataSource->SetHeader(header);
	
	if (strPath.IsEmpty())
	{
		CFileDialog dlg(FALSE, _T("aplrep"), _T(""), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, APL_T("Файлы отчётов (*.aplrep)|*.aplrep|Все файлы (*.*)|*.*||"));

		if (dlg.DoModal() != IDOK)
			return false;

		strPath = dlg.GetPathName();
	}	

	// Лист 1
	// 1
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_doc_num, strValue);
	arrParams.Add(_T("CardNumber"), strValue);
	strValue.Empty();

	// 2
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_org, pOrg);

	if (pOrg != NULL)
		pAPI->m_data.GetAttr(pOrg, pAPI->m_appr_mgr.a_org_id, strDescr);

	arrParams.Add(_T("WorkshopNumber"), strDescr);
	strDescr.Empty();

	// 3
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_sector, pOrg);

	if (pOrg != NULL)
		pAPI->m_data.GetAttr(pOrg, pAPI->m_appr_mgr.a_org_id, strDescr);

	arrParams.Add(_T("AreaNumber"), _T(""));
	strDescr.Empty();

	// 4
	COleDateTime dtDateTime;
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_date_detection, strValue);
	if(!strValue.IsEmpty())
	{
		aplString2Date(strValue, dtDateTime);
		strValue.Format(_T("%.2d.%.2d.%.4d"), dtDateTime.GetDay(), dtDateTime.GetMonth(), dtDateTime.GetYear());
	}

	arrParams.Add(_T("Date"), strValue);
	strValue.Empty();

	// 5
	// NB! Проверить: то ли мы выводим ("обозначение + исполнение" в качестве "тип основного")
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_planer, pRefusalPlaner);

	if (pRefusalPlaner != NULL)
	{
		pAPI->m_data.GetAttr(pRefusalPlaner, pAPI->m_prd_inst_mgr.a_prd_inst_pdf, pProductPDF);

		if (pProductPDF != NULL)
		{
			pAPI->m_data.GetAttr(pProductPDF, pAPI->m_prd_mgr.a_pdf_prd, pProductPRD);

			if (pProductPRD != NULL)
			{
				pAPI->m_data.GetAttr(pProductPRD, pAPI->m_prd_mgr.a_prd_id, strDescr);
				pAPI->m_data.GetAttr(pProductPDF, pAPI->m_prd_mgr.a_pdf_id, strVersion);
				strValue = strDescr;
				
				if (!strVersion.IsEmpty())
					strValue =+ CString(_T(" - ")) + strVersion;
			}
		}
	}
	
	arrParams.Add(_T("GeneralType"), strValue);
	strDescr.Empty();
	strVersion.Empty();
	strValue.Empty();

	// 6
	if (pRefusalPlaner != NULL)
		pAPI->m_data.GetAttr(pRefusalPlaner, pAPI->m_prd_inst_mgr.a_prd_inst_sn, strValue);		

	arrParams.Add(_T("GeneralProductNumber"), strValue);
	strValue.Empty();

	// 7
	// NB!
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_system, pRefusalSystem);

	if (pRefusalSystem != NULL)
	{
		pAPI->m_data.GetAttr(pRefusalSystem, pAPI->m_prd_inst_mgr.a_prd_inst_pdf, pProductPDF);

		if (pProductPDF != NULL)
		{
			pAPI->m_data.GetAttr(pProductPDF, pAPI->m_prd_mgr.a_pdf_prd, pProductPRD);
			pAPI->m_data.GetAttr(pProductPRD, pAPI->m_prd_mgr.a_prd_id, strDescr);
		}		
	}

	arrParams.Add(_T("SubsystemCode"), strDescr);
	strDescr.Empty();

	// 8, 9, 10
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_part, pRefusalPart);

	if (pRefusalPart != NULL)
	{
		if(pAPI->m_data.IsKindOf(pRefusalPart, pAPI->m_prd_mgr.e_pdf)) pProductPDF = pRefusalPart;
		else 
		{
			pAPI->m_data.GetAttr(pRefusalPart, pAPI->m_prd_inst_mgr.a_prd_inst_pdf, pProductPDF);
			pAPI->m_data.GetAttr(pRefusalPart, pAPI->m_prd_inst_mgr.a_prd_inst_sn, strValue);
		}

		if (pProductPDF != NULL)
		{
			pAPI->m_data.GetAttr(pProductPDF, pAPI->m_prd_mgr.a_pdf_prd, pProductPRD);

			if (pProductPRD != NULL)
			{
				pAPI->m_data.GetAttr(pProductPRD, pAPI->m_prd_mgr.a_prd_id, strDescr);
				pAPI->m_data.GetAttr(pProductPRD, pAPI->m_prd_mgr.a_prd_name, strName);				
			}			
		}		
	}
	
	arrParams.Add(_T("PKI_Name"), strName);	
	arrParams.Add(_T("Code"), strDescr);	
	arrParams.Add(_T("PKI_FactoryNumber"), strValue);
	strDescr.Empty();
	strName.Empty();
	strValue.Empty();

	// 11
	if (pRefusalPart != NULL)
	{		
		pAPI->m_data.GetAttr(pRefusalPart, pAPI->m_prd_inst_mgr.a_prd_inst_datetime, strValue);

		if (!strValue.IsEmpty())
		{
			aplString2Date(strValue, dtDateTime);
			strValue.Format(_T("%.2d.%.2d.%.4d"), dtDateTime.GetDay(), dtDateTime.GetMonth(), dtDateTime.GetYear());
		}		
	}
	
	arrParams.Add(_T("ProductionDate"), strValue);
	strValue.Empty();

	// 12, 13, 14
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_item, pRefusalItem);	

	if (pRefusalItem != NULL)
	{
		pAPI->m_data.GetAttr(pRefusalItem, pAPI->m_prd_inst_mgr.a_prd_inst_pdf, pProductPDF);
		pAPI->m_data.GetAttr(pRefusalItem, pAPI->m_prd_inst_mgr.a_prd_inst_sn, strValue);

		if (pProductPDF != NULL)
		{
			pAPI->m_data.GetAttr(pProductPDF, pAPI->m_prd_mgr.a_pdf_prd, pProductPRD);

			if (pProductPRD != NULL)
			{
				pAPI->m_data.GetAttr(pProductPRD, pAPI->m_prd_mgr.a_prd_id, strDescr);
				pAPI->m_data.GetAttr(pProductPRD, pAPI->m_prd_mgr.a_prd_name, strName);				
			}			
		}		
	}
	
	arrParams.Add(_T("AggregateName"), strName);
	arrParams.Add(_T("AggregateCode"), strDescr);
	arrParams.Add(_T("AggregateFactoryNumber"), strValue);
	strDescr.Empty();
	strName.Empty();
	strValue.Empty();

	// 15
	if (pRefusalItem != NULL)
	{
		pAPI->m_data.GetAttr(pRefusalItem, pAPI->m_prd_inst_mgr.a_prd_inst_datetime, strValue);

		if (!strValue.IsEmpty())
		{
			aplString2Date(strValue, dtDateTime);
			strValue.Format(_T("%.2d.%.2d.%.4d"), dtDateTime.GetDay(), dtDateTime.GetMonth(), dtDateTime.GetYear());
		}		
	}
	
	arrParams.Add(_T("AggregateProductionDate"), strValue);
	strValue.Empty();

	// 16
	aplExtent extCharacts;
	CaplInstance *pCharactType = NULL;
	double fValue = 0.0;

	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_resources_str, strValue);
	arrParams.Add(_T("TotalOperatingTime"), strValue);
	strValue.Empty();

	// 17
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_description, strValue);
	arrParams.Add(_T("DefectDescription"), strValue);
	strValue.Empty();

	// 18
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_type, pRefusalType);

	if (pRefusalType != NULL)
		pAPI->m_data.GetAttr(pRefusalType, pAPI->m_classifier_mgr.a_apl_classifier_level_id, strValue);

	arrParams.Add(_T("DefectCode"), strValue);
	strValue.Empty();

	// 19
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_ext_view, strValue);
	arrParams.Add(_T("PKI_Appearance"), strValue);
	strValue.Empty();

	// 20, 21
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_conditions, pRefusalConditions);

	if (pRefusalConditions != NULL)
	{
		pAPI->m_data.GetAttr(pRefusalConditions, pAPI->m_classifier_mgr.a_apl_classifier_level_id, strDescr);
		pAPI->m_data.GetAttr(pRefusalConditions, pAPI->m_classifier_mgr.a_apl_classifier_level_name, strName);
	}

	arrParams.Add(_T("DefectConditions"), strName);
	arrParams.Add(_T("DefectConditionsCode"), strDescr);
	strName.Empty();
	strDescr.Empty();

	// 22
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_method, pRefusalMethod);

	if (pRefusalMethod != NULL)
		pAPI->m_data.GetAttr(pRefusalMethod, pAPI->m_classifier_mgr.a_apl_classifier_level_name, strName);

	arrParams.Add(_T("DefectEliminationMethod"), strName);
	strName.Empty();

	// 23
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_faultreason, pRefusalFaultReason);

	if (pRefusalFaultReason != NULL)
		pAPI->m_data.GetAttr(pRefusalFaultReason, pAPI->m_classifier_mgr.a_apl_classifier_level_id, strValue);

	arrParams.Add(_T("DefectReasonCode"), strValue);
	strValue.Empty();

	//24

	//25
	arrParams.Add(_T("ChiefEngineerName"), _T(""));
	arrParams.Add(_T("CustomerName"), _T(""));
	arrParams.Add(_T("BTK_WorkerName"), _T(""));

	arrParams.Add(_T("ProductName"), _T(""));
	arrParams.Add(_T("ProductComplectNumber"), _T(""));
	arrParams.Add(_T("FaultDescription"), _T(""));	
	arrParams.Add(_T("CardFillerName"), _T(""));

	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_doc_date, strValue);
	if(!strValue.IsEmpty())
	{
		aplString2Date(strValue, dtDateTime);

		strValue.Format(_T("%.2d"), dtDateTime.GetDay());
		arrParams.Add(_T("CardFillDay"), strValue);

		strValue.Format(_T("%s"), arrMonth[dtDateTime.GetMonth()]);
		arrParams.Add(_T("CardFillMonth"), strValue);

		strValue.Format(_T("%.4d"), dtDateTime.GetYear());
		arrParams.Add(_T("CardFillYear"), strValue);
	}

	arrParams.Add(_T("PKI_ExaminationWorkshopNumber"), _T(""));
	arrParams.Add(_T("PKI_ExaminationLaboratoryNumber"), _T(""));

	// Лист 2
	// 26
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_research_result, strValue);
	arrParams.Add(_T("PVK_ExaminationResult"), strValue);
	strValue.Empty();

	// 27
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_research_lab, pOrg);

	if (pOrg != NULL)
		pAPI->m_data.GetAttr(pOrg, pAPI->m_appr_mgr.a_org_id, strValue);

	arrParams.Add(_T("27_ChapterValue"), strValue);
	strValue.Empty();

	// 28
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_research_sector, pOrg);

	if (pOrg != NULL)
		pAPI->m_data.GetAttr(pOrg, pAPI->m_appr_mgr.a_org_id, strValue);

	arrParams.Add(_T("28_ChapterValue"), strValue);
	strValue.Empty();

	// 29
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_test_deduction, pRefusalTestDeduction);

	if (pRefusalTestDeduction != NULL)
		pAPI->m_data.GetAttr(pRefusalTestDeduction, pAPI->m_classifier_mgr.a_apl_classifier_level_id, strValue);

	arrParams.Add(_T("RepairDecisionCode"), strValue);
	strValue.Empty();

	// 30
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_culprit_deduction, pRefusalCulpritDeduction);

	if (pRefusalCulpritDeduction != NULL)
		pAPI->m_data.GetAttr(pRefusalCulpritDeduction, pAPI->m_classifier_mgr.a_apl_classifier_level_id, strValue);

	arrParams.Add(_T("GuiltyDecisionCode"), strValue);

	// 31, 32, 33
	arrParams.Add(_T("LaboratoryChiefName"), _T(""));
	arrParams.Add(_T("PVK_EngineerName"), _T(""));
	arrParams.Add(_T("CustomerRepresenterName"), _T(""));

	// 34
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_dispose_data, strValue);
	arrParams.Add(_T("DefectEliminationDescription"), strValue);
	strValue.Empty();

	// 35
	if (pRefusalMethod != NULL)
		pAPI->m_data.GetAttr(pRefusalMethod, pAPI->m_classifier_mgr.a_apl_classifier_level_name, strName);

	arrParams.Add(_T("DefectEliminationCode"), strName);
	strName.Empty();

	// 36
	arrParams.Add(_T("WorkshopCommissionDecisionNumber"), _T(""));
	pAPI->m_data.GetAttr(pRefusalInstance, pMgr->a_apl_refusal_result_decision, strValue);
	arrParams.Add(_T("WorkshopCommissionDecision"), strValue);

	arrParams.Add(_T("CommissionChairman"), _T(""));
	arrParams.Add(_T("CommissionMember1"), _T(""));
	arrParams.Add(_T("CommissionMember2"), _T(""));
	arrParams.Add(_T("SupplierRepresenterName"), _T(""));

	bool bRes = GenerateReport(&aplReportMgr, &arrParams, strTemplatePath, strPath, &pAPI->m_data);

	if (bRes)
	{
		if (AfxMessageBox(_T("Отчёт успешно создан, открыть?"), MB_YESNO | MB_ICONQUESTION) == IDYES)
		{
			CString strCommandLine;
				
			strCommandLine = GetExePath() + CString(_T("ReportConstructor.exe"));
			ShellExecute(NULL, _T("open"), strPath, NULL, NULL, SW_SHOW);
		}
	}
	else
		AfxMessageBox(_T("Отчёт не был создан."), MB_OK | MB_ICONEXCLAMATION);

	return bRes;
}

//////////////////////////////////////////////////////////////////////////

CString GetExePath()
{
	CString strExePath;
	HMODULE hModule = GetModuleHandle(NULL);
	TCHAR szModuleName[2048];	

	if (hModule != NULL)
	{
		if (GetModuleFileName(hModule, szModuleName, 2048) > 0)
		{
			CString strBuffer;

			strBuffer = szModuleName;
			strExePath = strBuffer.Left(strBuffer.ReverseFind(_T('\\')) + 1);
		}
	}

	return strExePath;
}