// gls_impDlg.cpp : implementation file
//

#include "stdafx.h"
#include "psm.h"
#include "gls_impDlg.h"
#include "PSMDoc.h"

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

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
#define REPAINT {MSG msg; while (::PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE|PM_NOYIELD)) DispatchMessage(&msg);while (::PeekMessage(&msg, NULL, WM_SHOWWINDOW, WM_SHOWWINDOW, PM_REMOVE|PM_NOYIELD)) DispatchMessage(&msg);}

/////////////////////////////////////////////////////////////////////////////
// CGls_impDlg dialog

CGls_impDlg::CGls_impDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CGls_impDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CGls_impDlg)
	m_prefix = _T("");
	m_use_exist_doc = FALSE;
	m_create_razd = TRUE;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_init_size=0;
	m_doc=0;

	m_ver_type=0;
	m_qm_type=0;
}

void CGls_impDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CGls_impDlg)
	DDX_Control(pDX, IDC_PREFIX, m_prefix_ctrl);
	DDX_Control(pDX, IDC_PROGRESS1, m_prgs);
	DDX_Control(pDX, IDC_GLS_BROWSE, m_gls_btn);
	DDX_Control(pDX, IDC_IMPORT, m_imp_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_LIST1, m_list);
	DDX_Text(pDX, IDC_PREFIX, m_prefix);
	DDX_Check(pDX, IDC_USE_EXIST_DOC, m_use_exist_doc);
	DDX_Check(pDX, IDC_CREATE_RAZD, m_create_razd);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CGls_impDlg, CaplResizableDialog)
	//{{AFX_MSG_MAP(CGls_impDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_GLS_BROWSE, OnGlsBrowse)
	ON_BN_CLICKED(IDC_IMPORT, OnImport)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CGls_impDlg message handlers

BOOL CGls_impDlg::OnInitDialog()
{
	CaplResizableDialog::OnInitDialog();

	ModifyStyleEx(0, WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT);   
	ModifyStyle(0, WS_MAXIMIZEBOX);   
	
	ListView_SetExtendedListViewStyle(m_list.m_hWnd,
		ListView_GetExtendedListViewStyle(m_list.m_hWnd)
			|LVS_EX_UNDERLINECOLD|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	m_imp_btn.SetIcon(GetAplStdIco16(APLSTDICO_PLAY));
	m_imp_btn.SetFlat(FALSE);
	m_gls_btn.SetIcon(GetAplTableIco(APL_TABLE_OPEN));
	m_gls_btn.SetFlat(FALSE);

	m_list.InsertColumn(0,_T("ID"),LVCFMT_LEFT,75);
	m_list.InsertColumn(1, APL_T("Наименование"),LVCFMT_LEFT,920);

	AddAnchor(IDC_LIST1,TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_PREFIX,TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	AddAnchor(IDC_GLS_BROWSE,BOTTOM_LEFT);
	AddAnchor(IDC_IMPORT,BOTTOM_LEFT);
	AddAnchor(IDC_PROGRESS1,BOTTOM_LEFT,BOTTOM_RIGHT);

	// проверка наличия типов действий
	int i;
	CString buf;
	aplExtent ext;
	m_doc_data.GetEntityExtent(m_doc->m_api.m_bp_mgr.e_bp_type,ext);
	for(i=0;i<ext.Size;i++)
	{
		m_doc_data.GetAttr(ext[i],m_doc->m_api.m_bp_mgr.a_bp_type_name,buf);
		buf.MakeUpper();
		if(buf.Find( APL_T("ВЕРШИНА"))>=0)	m_ver_type=ext[i];
		if(buf.Find(_T("QM"))>=0) m_qm_type=ext[i];
	}
	if((m_qm_type==0)||(m_ver_type==0))
	{
		if((m_qm_type==0)&&(m_ver_type==0))
			AfxMessageBox( APL_T("Не заданы типы бизнес-процессов для QM процесса и вершины модели"));
		else if(m_ver_type==0)
			AfxMessageBox( APL_T("Не задан тип бизнес-процессов для вершины модели"));
		else 
			AfxMessageBox( APL_T("Не задан тип бизнес-процессов для QM процесса"));

		m_gls_btn.EnableWindow(FALSE);
		m_imp_btn.EnableWindow(FALSE);
	}
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CGls_impDlg::OnGlsBrowse() 
{
	CString buf,fname;
	CFileDialog fdlg(TRUE,0,fname,OFN_FILEMUSTEXIST|OFN_HIDEREADONLY,
		_T("Chart Files (*.gls)|*.gls|All Files (*.*)|*.*||"));
	if(fdlg.DoModal()!=IDOK) return;
	fname=fdlg.GetPathName( );
	buf=fdlg.GetFileTitle(); buf+=_T("-");
	m_prefix_ctrl.SetWindowText(buf);

	CStdioFile stfile;
	if(!stfile.Open(fname,CFile::modeRead|CFile::typeText|CFile::shareDenyWrite)){AfxMessageBox( APL_T("Ошибка открытия файла !!!")); return;}
	a_act.RemoveAll();
	m_list.DeleteAllItems();
	int j;
	CStringArray strarr;
	
	stfile.ReadString(buf); 
	if(buf==_T("")) {AfxMessageBox( APL_T("Неверный формат файла !!!")); stfile.Close(); return;}

	if(buf==_T("{Activity}"))
	{
		// Формат 4.2
		CString str;
		stfile.ReadString(buf);
		CaplCSV::StrToArray(buf,strarr);
		
		int i,i_id=-1, i_name=-1, i_descr=-1, i_max=0;;
		for(i=0;i<strarr.GetSize();i++) {strarr[i].TrimLeft(); strarr[i].TrimRight();
				if(strarr[i]==_T("TypeId")){i_id=i; break;}}
		for(i=0;i<strarr.GetSize();i++) {strarr[i].TrimLeft(); strarr[i].TrimRight();
				if(strarr[i]==_T("Name")){i_name=i; break;}}
		for(i=0;i<strarr.GetSize();i++) {strarr[i].TrimLeft(); strarr[i].TrimRight();
				if(strarr[i]==_T("Definition")){i_descr=i; break;}}

		if( i_id<0 || i_name<0 || i_descr<0) 
			{AfxMessageBox( APL_T("Неверный формат файла !!! (строка1)")); stfile.Close(); return;}
		
		i_max=i_id;
		if(i_max<i_name) i_max=i_name;
		if(i_max<i_descr) i_max=i_descr;
		i_max++;

		while(stfile.ReadString(buf))
		{
			if(buf==_T("{Icom}")) break;
			if(buf==_T("")) continue;
			if(buf[0]!=_T('\"')) {str+=buf;continue;}
			else str=buf;

			CaplCSV::StrToArray(str,strarr);
			str=_T("");
			if(strarr.GetSize()<i_max) continue;
			CActivity act;
			act.id=strarr[i_id];
			act.id.Replace(_T("\\n"),_T(" "));act.id.Replace(_T("\\r"),_T(""));act.id.Replace(_T("\\;"),_T(","));act.id.TrimLeft();act.id.TrimRight();
			act.name=strarr[i_name];
			act.name.Replace(_T("\\n"),_T(" "));act.name.Replace(_T("\\r"),_T(""));act.name.Replace(_T("\\;"),_T(","));act.name.TrimLeft();act.name.TrimRight();
			act.descr=strarr[i_descr];
			act.descr.Replace(_T("\\n"),_T("\n"));act.descr.Replace(_T("\\r"),_T("\r"));act.descr.Replace(_T("\\;"),_T(","));act.descr.TrimLeft();act.descr.TrimRight();
			a_act.Add(act);
			j=m_list.InsertItem(-1,act.id);
			m_list.SetItemText(j,1,act.name);
		}
		stfile.Close();

	}
	else
	{
		// Формат 3.7
		stfile.Close();
		CaplCSV file;
		if(!file.OpenFile(fname)){AfxMessageBox( APL_T("Ошибка открытия файла !!!")); return;}

		while(file.ReadString(strarr))
		{
			if(strarr.GetSize()<5) continue;
			buf=strarr[1];
			//buf.TrimLeft();
			//buf.TrimRight();
			buf.MakeLower();
			if(buf!=_T("activity")) continue;

			CActivity act;
			act.id=strarr[2];
			act.id.Replace(_T("\\n"),_T(" "));act.id.Replace(_T("\\r"),_T(""));act.id.Replace(_T("\\;"),_T(","));
			act.name=strarr[0];
			act.name.Replace(_T("\\n"),_T(" "));act.name.Replace(_T("\\r"),_T(""));act.name.Replace(_T("\\;"),_T(","));
			act.descr=strarr[4];
			act.descr.Replace(_T("\\n"),_T("\n"));act.descr.Replace(_T("\\r"),_T("\r"));act.descr.Replace(_T("\\;"),_T(","));
			a_act.Add(act);
			j=m_list.InsertItem(-1,act.id);
			m_list.SetItemText(j,1,act.name);
		}
		file.CloseFile();
	}
	m_prgs.SetRange32(0,a_act.GetSize());
	m_prgs.SetPos(0);
}

// Создает бизнес-процесс по обозначению
CaplInstance *CGls_impDlg::CreateBP(LPCTSTR id, LPCTSTR prefix, CaplInstance *act_type)
{
	if(id==0) return 0;
	int i,j,k=0;
	CString buf,id0,id1,id2;
	if(_strcmp(id,_T("A0"))==0) id1=_T("A"); else id1=id;
	CaplInstance *bp,*newact,*oldact;
	for(i=0;i<a_act.GetSize();i++)
	{
		REPAINT
		m_prgs.SetPos(m_init_size-a_act.GetSize()+1);
		if(a_act[i].id==id)
		{
			id0=prefix;id0+=id; id2=id0;
			bp=m_doc->m_api.m_bp_mgr.FindBPById(id2);
			oldact=bp;
			while (bp!=0)//ищется с наибольшим индексом?
			{
				REPAINT
				k++;
				id2.Format(_T("%s-%i"),LPCTSTR(id0),k);
				bp=m_doc->m_api.m_bp_mgr.FindBPById(id2);
				if(bp!=0) oldact=bp;
			}
			if(!oldact)
			{
				bp= m_doc_data.CreateInstance(m_doc->m_api.m_bp_mgr.e_bp);
				m_doc_data.PutAttr(bp,m_doc->m_api.m_bp_mgr.a_bp_id,id2);
				m_doc_data.PutAttr(bp,m_doc->m_api.m_bp_mgr.a_bp_name,a_act[i].name);
				m_doc_data.PutAttr(bp,m_doc->m_api.m_bp_mgr.a_bp_descr,a_act[i].descr);
				if(act_type!=0) 
					m_doc_data.PutAttr(bp,m_doc->m_api.m_bp_mgr.a_bp_type,act_type);
			}
			else bp=oldact;
			
			CaplInstance* bp_ver= m_doc_data.CreateInstance(m_doc->m_api.m_bp_mgr.e_apl_bp_ver);
				CaplInstance* old_act_ver= NULL;
			if(bp_ver)
			{
				m_doc_data.PutAttr(bp_ver, m_doc->m_api.m_bp_mgr.a_bp_ver_id, id2);
				m_doc_data.PutAttr(bp_ver, m_doc->m_api.m_bp_mgr.a_bp_ver_name, a_act[i].name);
				m_doc_data.PutAttr(bp_ver, m_doc->m_api.m_bp_mgr.a_bp_ver_descr, a_act[i].descr);
				m_doc_data.PutAttr(bp_ver, m_doc->m_api.m_bp_mgr.a_bp_ver_bp, bp);
				if(act_type!=0) 
					m_doc_data.PutAttr(bp_ver, m_doc->m_api.m_bp_mgr.a_bp_ver_type,act_type);	
				
				m_doc_data.GetAttr(bp, m_doc->m_api.m_bp_mgr.a_bp_act, old_act_ver);
				m_doc_data.PutAttr(bp, m_doc->m_api.m_bp_mgr.a_bp_act, bp_ver);
				m_doc_data.PutAttr(bp_ver, m_doc->m_api.m_bp_mgr.a_bp_ver_base, old_act_ver);

				m_doc_data.PutAttr(bp, m_doc->m_api.m_bp_mgr.a_bp_id, id2);
				m_doc_data.PutAttr(bp, m_doc->m_api.m_bp_mgr.a_bp_name, a_act[i].name);
				m_doc_data.PutAttr(bp, m_doc->m_api.m_bp_mgr.a_bp_descr, a_act[i].descr);
				
				CaplInstance* bp_chng= m_doc_data.CreateInstance(m_doc->m_api.m_change_mgr.e_abpc);
				if(bp_chng)
				{
					m_doc->m_api.m_data.PutAttr(bp_chng, m_doc->m_api.m_change_mgr.a_chng_item_id, m_doc->m_api.m_change_mgr.GetBPCId(bp));
					m_doc->m_api.m_data.PutAttr(bp_chng, m_doc->m_api.m_change_mgr.a_abpc_bp, bp);
					m_doc->m_api.m_data.PutAttr(bp_chng, m_doc->m_api.m_change_mgr.a_abpc_new_rev, bp_ver);
					m_doc->m_api.m_data.PutAttr(bp_chng, m_doc->m_api.m_change_mgr.a_abpc_old_rev, old_act_ver);
					
					COleDateTime odt; CString s_dt;
					m_doc->m_api.m_data.NET_GetServerDateTime(odt);
					aplDate2String(odt,s_dt);

					m_doc->m_api.m_data.PutAttr(bp_chng, m_doc->m_api.m_change_mgr.a_chng_item_accept_date, s_dt);
					m_doc->m_api.m_data.PutAttr(bp_chng, m_doc->m_api.m_change_mgr.a_chng_item_user, m_doc->m_api.m_data.GetNameCurrUser());
					m_doc->m_api.m_data.PutAttr(bp_chng, m_doc->m_api.m_change_mgr.a_chng_item_autor, m_doc->m_api.m_change_mgr.GetCurrentPerson());
				}
			}
			if(oldact!=0)
			{
				aplExtent ext0,ext1;
				int i1;
				if(m_use_exist_doc)
				{
					m_doc->m_api.m_doc_mgr.FindAssociatedDocuments(oldact, ext0, ext1);
					
					for(i1=0;i1<ext0.Size;i1++)
						m_doc->m_api.m_doc_mgr.CreateAssociation(bp_ver, ext0[i1]);
				}
			}
			
			CaplAggr aggr;
			a_act.RemoveAt(i,1);
			for(j=1;j<=9;j++)
			{
				buf.Format(_T("%s%i"),LPCTSTR(id1),j);
				newact=CreateBP(buf,prefix,act_type);
				if(newact!=0) aggr.Add(newact);
				else break;
			}
			if(aggr.GetSize()>0)
			{
				m_doc_data.PutAttr(bp, m_doc->m_api.m_bp_mgr.a_bp_elements,aggr);
				m_doc_data.PutAttr(bp_ver, m_doc->m_api.m_bp_mgr.a_bp_ver_elements,aggr);
			}
			return bp;
		}
	}
	return 0;
}

void CGls_impDlg::OnImport() 
{
	// TODO: Add your control notification handler code here
	if(a_act.GetSize()<1) {AfxMessageBox( APL_T("Нет данных !!!"),MB_OK|MB_ICONSTOP); return;}
	UpdateData(TRUE);
	if(m_prefix==_T(""))
	{
		if(IDYES!=AfxMessageBox( APL_T("Префикс не указан. Загружать без префикса ?"),MB_YESNO|MB_ICONQUESTION)) return;
	}
	CaplInstance *folder=m_doc->m_api.m_bp_mgr.SelectInstance(APL_MODE_SELECT_FOLDER, APL_T("Выберите папку"));
	if(folder!=0)
	{
		if(folder->GetAccessmode()>aplRW)
			AfxMessageBox( APL_T("У Вас недостаточно прав для внесения данных в папку !!!\n"),MB_OK|MB_ICONSTOP);
		else
		{
			m_init_size=a_act.GetSize();
			m_prgs.SetRange32(0,m_init_size);
			CaplInstance *main=CreateBP(_T("A0"),m_prefix,m_qm_type);
			if(main==0)
			{
				AfxMessageBox( APL_T("Oшибка ! Вершина модели не найдена"));
				return;
			}

			if(m_create_razd)
			{
				CString id2;
				m_doc_data.GetAttr(main,m_doc->m_api.m_bp_mgr.a_bp_id,id2);
				id2+=_T("-V");
				CaplInstance *razd=m_doc_data.CreateInstance(m_doc->m_api.m_bp_mgr.e_bp);
				m_doc_data.PutAttr(razd,m_doc->m_api.m_bp_mgr.a_bp_id,id2);
				if(m_ver_type!=0) m_doc_data.PutAttr(razd,m_doc->m_api.m_bp_mgr.a_bp_type,m_ver_type);
				CaplAggr aggr;
				aggr.Add(main);
				m_doc_data.PutAttr(razd,m_doc->m_api.m_bp_mgr.a_bp_elements,aggr);
				m_doc->m_api.m_folder_mgr.AddToFolder(folder,razd);
			}
			else m_doc->m_api.m_folder_mgr.AddToFolder(folder,main);

			
			REPAINT
		}
		m_doc_data.NET_SaveChanges();
		m_list.DeleteAllItems();
		a_act.RemoveAll();
	}
	AfxMessageBox( APL_T("Готово !"));
}
