// ExportSpecificationDlg.cpp : implementation file
//

#include "stdafx.h"
#include "psm.h"
#include "ExportSpecificationDlg.h"
#include "PSMDoc.h"
#include "TreeProductItem.h"
#include <apl_api.h>
#include <process.h>


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

/////////////////////////////////////////////////////////////////////////////
// CExportSpecificationDlg dialog
BOOL	CExportSpecificationDlg::m_ins_ver_id=TRUE;
BOOL	CExportSpecificationDlg::m_use_date=FALSE;
BOOL	CExportSpecificationDlg::m_use_ser_num=FALSE;
BOOL	CExportSpecificationDlg::m_ins_docver_id=TRUE;
BOOL	CExportSpecificationDlg::m_std_individual=TRUE;
BOOL	CExportSpecificationDlg::m_del_temp_file = TRUE;
CString	CExportSpecificationDlg::m_ser_num;
CString	CExportSpecificationDlg::m_ver_id_spacer=_T(" ");
CString	CExportSpecificationDlg::m_docver_id_spacer=_T("-");
COleDateTime	CExportSpecificationDlg::m_date = COleDateTime::GetCurrentTime();
COleDateTime	CExportSpecificationDlg::m_time = COleDateTime::GetCurrentTime();

CString CExportSpecificationDlg::m_doc_substring = _T("");
BOOL CExportSpecificationDlg::m_insert_doc_only_if_substr = FALSE;

CExportSpecificationDlg::CExportSpecificationDlg(CWnd* pParent /*=NULL*/)
	: CaplTranslateDialog(CExportSpecificationDlg::IDD, pParent)
{
/*
	m_doc_out = TRUE;
	m_ins_ver_id = TRUE;
	m_material_out = TRUE;
	m_part_out = TRUE;
	m_ser_num = _T("");
	m_use_date = FALSE;
	m_use_ser_num = FALSE;
	m_ver_id_spacer = _T("-");
	m_docver_id_spacer = _T("-");
	m_ins_docver_id = TRUE;
	m_std_individual = FALSE;
	m_time = COleDateTime::GetCurrentTime();
	m_date = COleDateTime::GetCurrentTime();
*/
	//{{AFX_DATA_INIT(CExportSpecificationDlg)
	m_prd_id = _T("");
	m_prd_name = _T("");
	m_ver_id = _T("");
	m_out_file = _T("");
	//}}AFX_DATA_INIT
}


void CExportSpecificationDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplTranslateDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CExportSpecificationDlg)
	DDX_Control(pDX, IDC_SEL_CONTEXT, m_sel_context);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDC_DOC_SUBSTRING, m_doc_substring_ctrl);
	DDX_Control(pDX, IDC_INSERT_DOC_ONLY_IF_SUBSTRING, m_insert_doc_only_if_substr_ctrl);
	DDX_Control(pDX, IDC_OUT_FILE, m_out_file_ctrl);
	DDX_Text(pDX, IDC_PRD_ID, m_prd_id);
	DDX_Text(pDX, IDC_PRD_NAME, m_prd_name);
	DDX_Text(pDX, IDC_VER_ID, m_ver_id);
	DDX_Control(pDX, IDC_INS_DOCVER_ID, m_ins_docver_id_ctrl);
	DDX_Control(pDX, IDC_USE_SERNUM, m_use_ser_num_ctrl);
	DDX_Control(pDX, IDC_USE_DATE, m_use_date_ctrl);
	DDX_Control(pDX, IDC_INS_VER_ID, m_ins_ver_id_ctrl);
	DDX_Control(pDX, IDC_TIME, m_time_ctrl);
	DDX_Control(pDX, IDC_DATE, m_date_ctrl);
	DDX_Control(pDX, IDC_SERNUM, m_ser_num_ctrl);
	DDX_Control(pDX, IDC_DOCVER_ID_SPACER, m_docver_id_spacer_ctrl);
	DDX_Control(pDX, IDC_VER_ID_SPACER, m_ver_id_spacer_ctrl);
	DDX_Text(pDX, IDC_OUT_FILE, m_out_file);
	DDX_Text(pDX, IDC_DOC_SUBSTRING, m_doc_substring);
	DDX_Check(pDX, IDC_INSERT_DOC_ONLY_IF_SUBSTRING, m_insert_doc_only_if_substr);
	DDX_Check(pDX, IDC_INS_VER_ID, m_ins_ver_id);
	DDX_Text(pDX, IDC_SERNUM, m_ser_num);
	DDX_Check(pDX, IDC_USE_DATE, m_use_date);
	DDX_Check(pDX, IDC_USE_SERNUM, m_use_ser_num);
	DDX_Text(pDX, IDC_VER_ID_SPACER, m_ver_id_spacer);
	DDX_Text(pDX, IDC_DOCVER_ID_SPACER, m_docver_id_spacer);
	DDX_Check(pDX, IDC_INS_DOCVER_ID, m_ins_docver_id);
	DDX_Check(pDX, IDC_STD_PART_INDIVIDUAL, m_std_individual);
	DDX_Check(pDX, IDC_DEL_TMP_FILE, m_del_temp_file);
	DDX_DateTimeCtrl(pDX, IDC_TIME, m_time);
	DDX_DateTimeCtrl(pDX, IDC_DATE, m_date);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CExportSpecificationDlg, CaplTranslateDialog)
	//{{AFX_MSG_MAP(CExportSpecificationDlg)
	ON_BN_CLICKED(IDC_INS_VER_ID, OnInsVerId)
	ON_BN_CLICKED(IDC_USE_DATE, OnUseDate)
	ON_BN_CLICKED(IDC_USE_SERNUM, OnUseSernum)
	ON_BN_CLICKED(IDC_INS_DOCVER_ID, OnInsDocverId)
	ON_BN_CLICKED(IDC_BROWSE_FILE, OnBrowseFile)
	ON_BN_CLICKED(IDC_INSERT_DOC_ONLY_IF_SUBSTRING, OnInsertDocOnlyIfSubstring)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CExportSpecificationDlg message handlers

void CExportSpecificationDlg::OnInsVerId() 
{
	if(m_ins_ver_id_ctrl.GetCheck()) m_ver_id_spacer_ctrl.EnableWindow(TRUE);
	else m_ver_id_spacer_ctrl.EnableWindow(FALSE);
}

void CExportSpecificationDlg::OnInsDocverId() 
{
	if(m_ins_docver_id_ctrl.GetCheck()) m_docver_id_spacer_ctrl.EnableWindow(TRUE);
	else m_docver_id_spacer_ctrl.EnableWindow(FALSE);
}

void CExportSpecificationDlg::OnUseDate() 
{
	static bool recurse=false;
	if(recurse) return;
	if(m_use_date_ctrl.GetCheck())
	{
		//m_use_ser_num_ctrl.SetCheck(FALSE);
		m_date_ctrl.EnableWindow(TRUE);
		m_time_ctrl.EnableWindow(TRUE);
	}
	else
	{
		m_date_ctrl.EnableWindow(FALSE);
		m_time_ctrl.EnableWindow(FALSE);
	}
	//recurse=true; OnUseSernum(); recurse=false;
}

void CExportSpecificationDlg::OnUseSernum() 
{
	static bool recurse=false;
	if(recurse) return;
	if(m_use_ser_num_ctrl.GetCheck())
	{
		//m_use_date_ctrl.SetCheck(FALSE);
		m_ser_num_ctrl.EnableWindow(TRUE);
	}
	else m_ser_num_ctrl.EnableWindow(FALSE);
	//recurse=true; OnUseDate(); recurse=false;
}

void CExportSpecificationDlg::OnBrowseFile() 
{
	m_out_file_ctrl.GetWindowText(m_out_file);
	CFileDialog dlg(FALSE,_T("vrd"),LPCTSTR(m_out_file),OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
		_T("Visual Report Files (*.vrd)|*.vrd|All Files (*.*)|*.*||"));
	if(dlg.DoModal()==IDOK)	m_out_file=dlg.GetPathName( );
	m_out_file_ctrl.SetWindowText(m_out_file);
}

BOOL CExportSpecificationDlg::OnInitDialog() 
{
	if(m_item!=0)
	{
		m_item->m_doc_data.GetAttrBN(m_item->m_prd,S::id,m_prd_id);
		m_item->m_doc_data.GetAttrBN(m_item->m_prd,S::name,m_prd_name);
		m_item->m_doc_data.GetAttrBN(m_item->m_pdf,S::id,m_ver_id);
	}
	CString tmp; aplGetTempPath(tmp);
	m_out_file=tmp+m_prd_id+_T("-")+m_ver_id+_T(".vrd");
	
	CaplTranslateDialog::OnInitDialog();

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	m_ok_btn.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_ok_btn.SetFlat(FALSE);


	OnUseSernum();
	OnUseDate();
	if(m_insert_doc_only_if_substr) m_doc_substring_ctrl.EnableWindow(TRUE);
	else m_doc_substring_ctrl.EnableWindow(FALSE);
	
	if(m_ins_ver_id) m_ver_id_spacer_ctrl.EnableWindow(TRUE);
	else m_ver_id_spacer_ctrl.EnableWindow(FALSE);

	if(m_ins_docver_id) m_docver_id_spacer_ctrl.EnableWindow(TRUE);
	else m_docver_id_spacer_ctrl.EnableWindow(FALSE);

	// Заполнение контекстов
	int i,j;
	CString buf;
	aplExtent ext_contexts;
	m_item->m_doc_data.GetEntityExtent(m_item->m_doc->m_api.m_prd_mgr.e_pd_context,ext_contexts);
	for(i=0;i<ext_contexts.Size;i++)
	{
		m_item->m_doc_data.GetAttr(ext_contexts[i],m_item->m_doc->m_api.m_prd_mgr.a_pd_context_name,buf);
		j=m_sel_context.AddString(buf);
		m_sel_context.SetItemData(j,(long)ext_contexts[i]);
	}
	j=m_sel_context.AddString( APL_T("Все контексты"));
	m_sel_context.SetItemData(j,0);
	m_sel_context.SetCurSel(j);

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

void CExportSpecificationDlg::OnOK() 
{
	// TODO: Add extra validation here
	UpdateData(TRUE);
	CaplAPI *m_api=&m_item->m_doc->m_api;
	if(m_api==0) return;
	int i;
	aplExtent ext,ext1,ext_rel;

	CaplInstance *i_context=(CaplInstance *)m_sel_context.GetItemData(m_sel_context.GetCurSel());

	// Путь к ехешнику
	TCHAR szBuff[_MAX_PATH];
	if(0==GetModuleFileName(0,szBuff,_MAX_PATH))throw(APLAPIERR_FILE_IO);
	CString my_path,path=szBuff;
	i=path.ReverseFind(_T('\\'));
	if (i!=-1) my_path=path.Left(i+1);

	CString tmp, fn_doc, fn_part, fn_ass, fn_material, fn_kit, fn_komplex, fn_global,fn_std;
	tmp.GetEnvironmentVariable(_T("temp"));
	fn_doc=tmp+_T("\\doc.csv"); fn_part=tmp+_T("\\part.csv"); fn_ass=tmp+_T("\\assembling.csv");
	fn_kit=tmp+_T("\\kit.csv");fn_komplex=tmp+_T("\\komplex.csv");
	fn_material=tmp+_T("\\material.csv"); fn_global=tmp+_T("\\global.csv");fn_std=tmp+_T("\\std.csv");

	i=m_out_file.ReverseFind(_T('.'));
	if(i==-1)m_out_file+=_T(".vrd");

	CStdioFile f_doc,f_global;
	CString format,zone,pos,id,name,count,descr,type,buf;
	CArray <CSpecificationItem*, CSpecificationItem*> a_doc, a_part, a_ass, a_kit, a_komplex, a_std, a_mater;


	// Вывод документов
	m_api->m_doc_mgr.FindAssociatedDocuments(m_item->m_prd,ext,ext_rel);
	m_api->m_doc_mgr.FindAssociatedDocuments(m_item->m_pdf,ext1,ext_rel);
	ext.Append(ext1);
	for(i=0;i<ext.Size;i++)
	{
		format=_T(""); zone=_T(""); pos=_T(""); id=_T(""); name=_T(""); descr=_T("");
		apidata.GetAttrBN(ext[i],S::id,id);
		apidata.GetAttrBN(ext[i],S::name,name);
		apidata.GetAttrBN(ext[i],S::description,descr);

		bool f_add=true;
		if(m_insert_doc_only_if_substr)
		{
			if(descr.Find(m_doc_substring)==-1)f_add=false;
			descr=_T("");
		}
		if(f_add)
		{
			if(m_ins_docver_id)
			{
				CaplInstance *act_rev;
				apidata.GetAttrBN(ext[i],S::active,act_rev);
				if(act_rev!=0)
				{
					apidata.GetAttrBN(act_rev,S::revision_id,tmp);
					apidata.GetAttrBN(act_rev,S::description,format);
					if(tmp!=_T(""))id+=m_docver_id_spacer;id+=tmp;
				}
			}
			CSpecificationItem *new_item =new CSpecificationItem;
			new_item->Identification=id;
			new_item->Pos=pos;
			new_item->Name=name;
			new_item->Count=count;
			new_item->Comments=descr;
			new_item->Format=format;

			a_doc.Add(new_item);
		}
	}

	// Вывод изделий
	bool std_pdf;
	CString id_add;

	m_api->m_prd_mgr.LoadAllSubProduct(0,i_context,m_item->m_pdf,ext, ext1);

	if(m_use_ser_num)
	{
		i=ext.GetSize();
		m_api->m_prd_mgr.FilterlBySN(ext,m_ser_num,ext1);
		if(i!=ext1.GetSize())
		{
			id_add.Format(_T("\n(%s)"),LPCTSTR(m_ser_num));
			ext.Clear();
			ext.Append(ext1);
		}
	}
	if(m_use_date)
	{
		COleDateTime time(m_date.GetYear(),m_date.GetMonth(),m_date.GetDay(),
			m_time.GetHour(),m_time.GetMinute(),m_time.GetSecond());
		i=ext.GetSize();
		m_api->m_prd_mgr.FilterlByDate(ext,time,ext1);
		if(i!=ext1.GetSize())
		{
			tmp=time.Format();
			id_add.Format(_T(" (%s)"),LPCTSTR(tmp));
			ext.Clear();
			ext.Append(ext1);
		}
	}
	// формирование таблиц
	CaplInstance *inst,*i_prd,*i_pdf;
	for(i=0;i<ext.Size;i++)
	{
		format=_T(""); zone=_T(""); pos=_T(""); id=_T(""); name=_T(""); descr=_T("");count=_T("");
		apidata.GetAttrBN(ext[i],S::related_pd,i_pdf);
		apidata.GetAttrBN(ext[i],S::id,pos);
		apidata.GetAttrBN(ext[i],S::description,descr);
		apidata.GetAttrBN(i_pdf,S::of_product,i_prd);
		apidata.GetAttrBN(i_pdf,S::formation_type,type);
		apidata.GetAttrBN(i_pdf,S::is_standard_part,std_pdf);
		apidata.GetAttrBN(i_prd,S::id,id);
		apidata.GetAttrBN(i_prd,S::name,name);
		double r_count;
		apidata.GetAttrBN(ext[i],S::value_component,r_count);
		
		if(id.Find(name)>=0) id.Replace(name,_T("")); // Если имя уже входит в обозначение

		if(r_count==0) 
			count=_T(""); 
		else 	
			count = Double2Str(r_count);
//			count.Format(_T("%g"),r_count);

		if(m_ins_ver_id) // добавление версии к модификации
		{
			apidata.GetAttrBN(i_pdf,S::id,tmp);
			if(tmp!=_T(""))
			{
				if(tmp.Find(id)!=-1) id=tmp;
				else {id+=m_ver_id_spacer;id+=tmp;}
			}
		}

		if(type==_T("material"))
		{
			apidata.GetAttrBN(ext[i],S::unit_component,inst);
			if(inst!=0)apidata.GetAttrBN(inst,S::id,descr);
		}
		// Преобр имен станжартных изделий
		if(m_std_individual==TRUE)
		{
			if((std_pdf)||(type==_T("material"))) {if(id!=_T("")) {name+=_T(" ");name+=id;id=_T("");}}
		}

		CSpecificationItem *new_item =new CSpecificationItem;
		new_item->Identification=id;
		new_item->Pos=pos;
		new_item->Name=name;
		new_item->Count=count;
		new_item->Comments=descr;

		//дополнение для удобства сортировки
		buf=_T("");
		for(int i=0;i<4-pos.GetLength();i++) buf+=_T(" ");
		buf+=pos;

		new_item->pos1=buf;

		// разбиение на файлы
		if(m_std_individual==TRUE)
		{
			if(std_pdf) 
			{
				if(type==_T("material")) a_mater.Add(new_item);
				else a_std.Add(new_item);
				continue;
			}
		}
		if(type==_T("kit")) a_kit.Add(new_item);
		else if(type==_T("komplex"))  a_komplex.Add(new_item);
		else if(type==_T("material")) a_mater.Add(new_item);
		else if(type==_T("assembly")) a_ass.Add(new_item);
		else a_part.Add(new_item);
	}

	// Сортировка
	SortItems(a_part);
	SortItems(a_ass);
	SortItems(a_mater);
	SortItems(a_kit);
	SortItems(a_komplex);
	SortItems(a_std);
	SortItems(a_doc);

	//вывод данных
	PrintItemsToFile(a_part,fn_part);
	PrintItemsToFile(a_ass,fn_ass);
	PrintItemsToFile(a_mater,fn_material);
	PrintItemsToFile(a_kit,fn_kit);
	PrintItemsToFile(a_komplex,fn_komplex);
	PrintItemsToFile(a_std,fn_std);
	PrintItemsToFile(a_doc,fn_doc);

	//CString templ_0=_T("spec_v.vrd");
	CString templ_0=_T("spec_v_f.vrd");
	//if((a_kit.GetSize()>0)||(a_komplex.GetSize()>0))templ_0=_T("spec_v_f.vrd");
	CString templ_1=my_path+templ_0;

	FreeItems(a_part);
	FreeItems(a_ass);
	FreeItems(a_mater);
	FreeItems(a_kit);
	FreeItems(a_komplex);
	FreeItems(a_std);
	FreeItems(a_doc);

	// вывод глобальной информации
	m_prd_id+=id_add;
	f_global.Open(fn_global,CFile::modeCreate|CFile::modeWrite|CFile::typeText);
	f_global.WriteString(_T("First_Usage,Info_Number,Identification,Developed,Name,Checked,Chief,Controller,Proved"));
	tmp.Format(_T("\n\"\",\"\",\"%s\",\"\",\"%s\",\"\",\"\",\"\",\"\""),
		LPCTSTR(m_prd_id),LPCTSTR(m_prd_name));
	f_global.WriteString(tmp);
	f_global.Flush();f_global.Close();


	//Запуск гегератора
	tmp.Format(_T("\"%sVisualReport.exe\" \"%s\"  \"/queryglobal=%s\" \"/querydoc=%s\" \"/querypart=%s\" ")
		_T("\"/queryassembling=%s\" \"/querystd=%s\" \"/querykit=%s\" \"/querykomplex=%s\" \"/querymaterial=%s\" \"/result%s\""),
		LPCTSTR(my_path),LPCTSTR(templ_1),
		LPCTSTR(fn_global),LPCTSTR(fn_doc),LPCTSTR(fn_part),LPCTSTR(fn_ass),
		LPCTSTR(fn_std),LPCTSTR(fn_kit),LPCTSTR(fn_komplex),LPCTSTR(fn_material),LPCTSTR(m_out_file));
	
	if(aplCreateProcess(0,LPCTSTR(tmp),true)==-1)
	{
		CString buf; 
		buf.Format( APL_T("Ошибка приз запуске генератора\n%s"),LPCTSTR(tmp));
		AfxMessageBox(LPCTSTR(buf));
	}
	else
	{
		if(AfxMessageBox( APL_T("Генерация завершена!\nОткрыть созданный отчет ?"),MB_YESNO)==IDYES)
		{
			tmp.Format(_T("\"%sVisualReport.exe\" \"%s\""),LPCTSTR(my_path),LPCTSTR(m_out_file));
			aplCreateProcess(0,LPCTSTR(tmp),false);
		}
	}
	if(m_del_temp_file)
	{
		DeleteFile(fn_std);DeleteFile(fn_part);DeleteFile(fn_ass);DeleteFile(fn_material);
		DeleteFile(fn_doc);DeleteFile(fn_global);

	}
	CaplTranslateDialog::OnOK();
}


void CExportSpecificationDlg::OnInsertDocOnlyIfSubstring() 
{
	// TODO: Add your control notification handler code here
	BOOL k=m_insert_doc_only_if_substr_ctrl.GetCheck();
	if(k) m_doc_substring_ctrl.EnableWindow(TRUE);
	else  m_doc_substring_ctrl.EnableWindow(FALSE);
	
}

void CExportSpecificationDlg::PrintItemsToFile(CArray <CSpecificationItem*, CSpecificationItem*> &items, LPCTSTR file)
{
	CStdioFile f_std;
	CString buf,empty_buf=_T("\n\"\",\"\",\"\",\"\",\"\",\"\",\"\"") ,razd=_T(" ,-:_/\\*");
	f_std.Open(file,CFile::modeCreate|CFile::modeWrite|CFile::typeText);
	f_std.WriteString(_T("Format,Zone,Pos,Identification,Name,Count,Comments"));
	
	if(items.GetSize()>0) f_std.WriteString(empty_buf);
	for(int i=0;i<items.GetSize();i++)
	{
		CString format=items[i]->Format,zone=items[i]->Zone,pos=items[i]->Pos,
			count=items[i]->Count,descr=items[i]->Comments;
		CString id=items[i]->Identification,id0,name=items[i]->Name,name0;

		while(1)
		{
			if(id.GetLength()>36) 
			{ 
				bool found=false;
				for(int j=36; j>3;j--)
				{
					if(razd.Find(id[j])>=0)
					{
						id0=id.Left(j+1);
						buf=id.Right(id.GetLength()-j-1);
						id=buf;
						found=true;
						break;
					}
				}
				if(!found){id0=id; id=_T("");}
			}
			else {id0=id; id=_T("");}

			if(name.GetLength()>28) 
			{ 
				bool found=false;
				for(int j=28; j>3;j--)
				{
					if(razd.Find(name[j])>=0)
					{
						name0=name.Left(j+1);
						buf=name.Right(name.GetLength()-j-1);
						name=buf;
						found=true;
						break;
					}
				}
				if(!found){name0=name; name=_T("");}
			} else {name0=name; name=_T("");}

			buf.Format(_T("\n\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\""),
				LPCTSTR(format), LPCTSTR(zone), LPCTSTR(pos),
				LPCTSTR(id0),LPCTSTR(name0),
				LPCTSTR(count), LPCTSTR(descr));
			f_std.WriteString(buf);
		
			if((id==_T(""))&&(name==_T(""))) break;
			format=_T("");zone=_T("");pos=_T("");count=_T("");descr=_T("");
		}
	}
	if(items.GetSize()>0) f_std.WriteString(empty_buf);
	f_std.Flush();f_std.Close();
}

void CExportSpecificationDlg::FreeItems(CArray <CSpecificationItem*, CSpecificationItem*> &items)
{
	for(int i=0;i<items.GetSize();i++) delete items[i];
	items.RemoveAll();
}

void CExportSpecificationDlg::SortItems(CArray <CSpecificationItem*, CSpecificationItem*> &items)
{
	for(int i=1;i<items.GetSize();i++)
	{
		for(int j=i;j>0;j--)
		{
			if(items[j]->pos1<items[j-1]->pos1)
			{
				CSpecificationItem *x_item=items[j];
				items[j]=items[j-1];
				items[j-1]=x_item;
			}
			else break;
		}
	}
}
