// maindialog.cpp : implementation file
//

#include "stdafx.h"
#include "maindialog.h"

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

/////////////////////////////////////////////////////////////////////////////
// CMainDialog dialog


CMainDialog::CMainDialog(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CMainDialog::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMainDialog)
	m_csPrdID = _T("");
	m_csPrdName = _T("");
	m_csPrdVer = _T("");
	m_csSNFilter = _T("");
	m_codtDateFilter = COleDateTime::GetCurrentTime();
	m_codtTimeFilter = COleDateTime::GetCurrentTime();
	m_csCdCost = _T("");
	m_csCdWeight = _T("");
	m_csCostUnit = _T("");
	m_csWeightUnit = _T("");
	m_bCalcCost = FALSE;
	m_bCalcWeight = FALSE;
	m_bUseDT = FALSE;
	m_bUseSN = FALSE;
	//}}AFX_DATA_INIT

	m_pPrdHelper=NULL;

	m_ciCostChar=NULL;
	m_ciWeightChar=NULL;

	m_pItem=NULL;
	m_bNeedRebuild=TRUE;

		//выясняем путь запуска программы 
	CString buf;
	m_prog_path="";
	buf=AfxGetApp()->m_pszHelpFilePath;
	int i=buf.ReverseFind('\\');
	if(i>-1) m_prog_path=buf.Left(i+1);

	char cur_dir[1024];
	GetCurrentDirectory(1024,cur_dir);
	buf=cur_dir;
	buf+="\\";
	m_curFolder = AfxGetApp()->GetProfileString ("kvz_forms","m_curFolder",buf);
	buf=m_curFolder;
	int n=buf.ReverseFind('\\');
	if(n>0) buf=buf.Left(n);
	CFileFind ff;
	if(ff.FindFile(buf)==0) 
		m_curFolder=cur_dir;
	m_log_file_opened=false;

}


void CMainDialog::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMainDialog)
	DDX_Control(pDX, IDC_T_PROTOCOL, m_t_protocol_ctrl);
	DDX_Control(pDX, IDCANCEL, m_cbCancel);
	DDX_Control(pDX, IDC_B_SAVE, m_cbSave);
	DDX_Control(pDX, IDC_B_MOVE_UP, m_cbMoveUp);
	DDX_Control(pDX, IDC_B_MOVE_DOWN, m_cbMoveDown);
	DDX_Control(pDX, IDC_B_CALC, m_cbCalc);
	DDX_Check(pDX, IDC_CHECK_CALC_COST, m_bCalcCost);
	DDX_Check(pDX, IDC_CHECK_CALC_WEIGHT, m_bCalcWeight);
	DDX_Check(pDX, IDC_CHECK_USE_DATETIME, m_bUseDT);
	DDX_Check(pDX, IDC_CHECK_USE_SN, m_bUseSN);
	DDX_Control(pDX, IDC_CB_SELECT_CONTEXT, m_cbContext);
	DDX_DateTimeCtrl(pDX, IDC_DT_DATE, m_codtDateFilter);
	DDX_DateTimeCtrl(pDX, IDC_DT_TIME, m_codtTimeFilter);
	DDX_Text(pDX, IDC_E_CALCULATED_COST, m_csCdCost);
	DDX_Text(pDX, IDC_E_CALCULATED_WEIGHT, m_csCdWeight);
	DDX_Text(pDX, IDC_E_COST_UNIT, m_csCostUnit);
	DDX_Text(pDX, IDC_E_PRD_ID, m_csPrdID);
	DDX_Text(pDX, IDC_E_PRD_NAME, m_csPrdName);
	DDX_Text(pDX, IDC_E_PRD_VERSION, m_csPrdVer);
	DDX_Text(pDX, IDC_E_SN, m_csSNFilter);
	DDX_Text(pDX, IDC_E_WEIGHT_UNIT, m_csWeightUnit);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CMainDialog, CaplResizableDialog)
	//{{AFX_MSG_MAP(CMainDialog)
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_B_SAVE, OnBSave)
	ON_BN_CLICKED(IDC_CHECK_USE_SN, OnCheckFilters)
	ON_BN_CLICKED(IDC_CHECK_CALC_WEIGHT, OnCheckCalcChars)
	ON_BN_CLICKED(IDC_B_CHOOSE_WEIGHT, OnBChooseWeight)
	ON_BN_CLICKED(IDC_B_CHOOSE_COST, OnBChooseCost)
	ON_BN_CLICKED(IDC_B_MOVE_UP, OnBMoveUp)
	ON_BN_CLICKED(IDC_B_MOVE_DOWN, OnBMoveDown)
	ON_BN_CLICKED(IDC_B_CALC, OnBCalc)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DT_DATE, OnDTFilterChange)
	ON_EN_CHANGE(IDC_E_SN, OnSNFilterChange)
	ON_BN_CLICKED(IDC_CHECK_USE_DATETIME, OnCheckFilters)
	ON_BN_CLICKED(IDC_CHECK_CALC_COST, OnCheckCalcChars)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DT_TIME, OnDTFilterChange)
	ON_CBN_SELCHANGE(IDC_CB_SELECT_CONTEXT, OnContextChange)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMainDialog message handlers

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

	ControlsInitTreeList();

	m_pPrdHelper= new CPrdHelper(m_api,m_inst);
	ControlsSetAnchors();

	m_pPrdHelper->GetPrdId(m_csPrdID);
	m_pPrdHelper->GetPrdName(m_csPrdName);
	m_pPrdHelper->GetPrdVerID(m_csPrdVer);

	CCharHelper ccHlp(m_api);
	//	в начале получаем хар-ки, используемые по умолчанию.
	m_bCalcWeight=ccHlp.FindDefChar(m_ciWeightChar,m_csWeightUnit,CCharHelper::m_eWeightType);
	m_bCalcCost=ccHlp.FindDefChar(m_ciCostChar,m_csCostUnit,CCharHelper::m_eCostType);

	ControlsFillPriorityCharTypesList();
	ControlsFillContextsList();
	UpdateData(FALSE);


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

void CMainDialog::OnDestroy() 
{
	CaplResizableDialog::OnDestroy();

	if(NULL!=m_pPrdHelper)
		delete m_pPrdHelper;
	if(NULL!=m_pItem)
	{
		delete m_pItem;
		m_pItem=NULL;
	}
}

BOOL CMainDialog::ControlsInitTreeList(void)
{
	RECT rect={5,5,10,10};
	CWnd* pic;


	DWORD dwStyles=0;

	pic=(CWnd*)GetDlgItem(IDC_FRM);
	pic->GetWindowRect(&rect);
	ScreenToClient(&rect);

	m_view=CaplTreeListCtrlView::CreateTreeListView(this,rect,IDC_TREELIST_CTRL);
	m_view->ShowWindow(SW_NORMAL);

	ControlsTreeListAddCols();

	m_view->m_tree.m_bSortRoot=true;
	m_view->m_bAutofit=true;
	m_view->m_tree.m_wndHeader.SetAutofit();
//	m_view->m_tree.m_dlg=NULL;
	m_view->m_tree.m_dlg=(CaplResizableDialog*)this;

	return TRUE;
}

BOOL CMainDialog::ControlsTreeListAddCols(void)
{
	CString csCols[]={"Структура","Наименование","Версия","Кол-во",
					  "Тип хар-ки для массы",
					  "Исходное значение для массы","Расчётное значение для массы",
					  "Тип хар-ки для стоимости",
					  "Исходное значение для стоимости","Расчётное значение для стоимости"};

	int i=0;

	for(i=0;i<10;i++)
		m_view->m_tree.InsertColumn(i,csCols[i],LVCFMT_LEFT,100);

	return TRUE;
}

HTREEITEM CMainDialog::ControlsTreeListSetItem(CPdfItem* pPdfItem,HTREEITEM hParentItem)
{
	HTREEITEM hItem;
	CString csColsText[10];
	CString cst;
	CStringList csItemInfo;

	CCharHelper ccHlp(m_api);

	int i=0;
	
	pPdfItem->GetInfo(csItemInfo);
	csColsText[0]=	csItemInfo.GetAt(csItemInfo.FindIndex(0));
	csColsText[1]=	csItemInfo.GetAt(csItemInfo.FindIndex(1));
	csColsText[2]=	csItemInfo.GetAt(csItemInfo.FindIndex(2));
	csColsText[3]=	csItemInfo.GetAt(csItemInfo.FindIndex(3));

	if(TRUE==m_bCalcWeight)
	{
		csColsText[4]=	csItemInfo.GetAt(csItemInfo.FindIndex(4));
		csColsText[5]=	csItemInfo.GetAt(csItemInfo.FindIndex(6));
		csColsText[6]=	csItemInfo.GetAt(csItemInfo.FindIndex(7));
	}
	else
	{
		csColsText[4]=	"";
		csColsText[5]=	"";
		csColsText[6]=	"";
	}

	if(TRUE==m_bCalcCost)
	{
		csColsText[7]=	csItemInfo.GetAt(csItemInfo.FindIndex(5));
		csColsText[8]=	csItemInfo.GetAt(csItemInfo.FindIndex(8));
		csColsText[9]=	csItemInfo.GetAt(csItemInfo.FindIndex(9));
	}
	else
	{
		csColsText[7]=	"";
		csColsText[8]=	"";
		csColsText[9]=	"";
	}

	hItem=m_view->m_tree.InsertItem("",hParentItem);
	m_view->m_tree.SetItemData(hItem,(DWORD)pPdfItem);

	for(i=0;i<11;i++)
		m_view->m_tree.SetItemText(hItem,i,csColsText[i]);

	if(pPdfItem->GetCount()>1)
	{

		CPtrArray pa;
		pPdfItem->GetChilds(pa);
		for(i=0;i<pa.GetSize();i++)
			ControlsTreeListSetItem((CPdfItem*)pa.GetAt(i),hItem);

//		m_view->m_tree.InsertItem("",hItem,TVI_LAST,true);
	}


	return hItem;
}

BOOL CMainDialog::ControlsTreeListExpandAll(HTREEITEM hItem)
{
	HTREEITEM ht,ht2;

	m_view->m_tree.SelectItem(hItem);
	m_view->m_tree.Expand(hItem,TVE_EXPAND);
	ht=hItem;

	do
	{
		ht2=m_view->m_tree.GetChildItem(ht);
		if(NULL==ht2)
		{
			ht2=m_view->m_tree.GetNextSiblingItem(ht);
			if(NULL==ht2)
			{
				ht2=m_view->m_tree.GetParentItem(ht);
				ht=m_view->m_tree.GetNextSiblingItem(ht2);
				if(NULL==ht)
					break;
				ht2=ht;
			}
		}
		ht=ht2;

		m_view->m_tree.SelectItem(ht);
		m_view->m_tree.Expand(ht,TVE_EXPAND);
	}
	while(1);

	m_view->m_tree.SelectItem(m_view->m_tree.GetRootItem());

	return TRUE;
}

void CMainDialog::ControlsSetAnchors(void)
{
	AddAnchor(IDC_GRP_PRODUCT,TOP_LEFT,TOP_RIGHT);
		AddAnchor(IDC_E_PRD_ID,TOP_LEFT,TOP_RIGHT);
		AddAnchor(IDC_E_PRD_NAME,TOP_LEFT,TOP_RIGHT);
		AddAnchor(IDC_E_PRD_VERSION,TOP_LEFT,TOP_RIGHT);

	AddAnchor(IDC_GRP_FILTER,TOP_RIGHT);
		AddAnchor(IDC_CHECK_USE_SN,TOP_RIGHT);
		AddAnchor(IDC_CHECK_USE_DATETIME,TOP_RIGHT);
		AddAnchor(IDC_T_CONTEXT,TOP_RIGHT);
		AddAnchor(IDC_E_SN,TOP_RIGHT);
		AddAnchor(IDC_DT_DATE,TOP_RIGHT);
		AddAnchor(IDC_DT_TIME,TOP_RIGHT);
		AddAnchor(IDC_CB_SELECT_CONTEXT,TOP_RIGHT);

	AddAnchor(IDC_GRP_WEIGHT,TOP_LEFT,TOP_RIGHT);
		AddAnchor(IDC_B_CHOOSE_WEIGHT,TOP_RIGHT);
		AddAnchor(IDC_E_WEIGHT_UNIT,TOP_LEFT,TOP_RIGHT);

	AddAnchor(IDC_GRP_COST,TOP_LEFT,TOP_RIGHT);
		AddAnchor(IDC_B_CHOOSE_COST,TOP_RIGHT);
		AddAnchor(IDC_E_COST_UNIT,TOP_LEFT,TOP_RIGHT);


	AddAnchor(IDC_GRP_PRIORITY,TOP_RIGHT);
		AddAnchor(IDC_LB_PRIORITY_LIST,TOP_RIGHT);
		AddAnchor(IDC_B_MOVE_UP,TOP_RIGHT);
		AddAnchor(IDC_B_MOVE_DOWN,TOP_RIGHT);

	AddAnchor(IDC_TREELIST_CTRL,TOP_LEFT,BOTTOM_RIGHT);

	AddAnchor(IDC_T_PROTOCOL,TOP_LEFT,TOP_RIGHT);

	//	кнопки
	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	AddAnchor(IDC_B_CALC,TOP_RIGHT);
	AddAnchor(IDC_B_SAVE,BOTTOM_RIGHT);

	AddAnchor(IDC_T_CALCULATED_WEIGHT,BOTTOM_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_T_CALCULATED_COST,BOTTOM_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_E_CALCULATED_WEIGHT,BOTTOM_LEFT,BOTTOM_RIGHT);
	AddAnchor(IDC_E_CALCULATED_COST,BOTTOM_LEFT,BOTTOM_RIGHT);

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

	m_cbCancel.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cbCancel.SetFlat(FALSE);

	m_cbMoveUp.SetIcon(GetAplTableIco(APL_TABLE_TOP));
	m_cbMoveUp.SetFlat(FALSE);

	m_cbMoveDown.SetIcon(GetAplTableIco(APL_TABLE_BOTTOM));
	m_cbMoveDown.SetFlat(FALSE);

	m_cbSave.SetIcon(GetAplTableIco(APL_TABLE_SAVE));
	m_cbSave.SetFlat(FALSE);

}

void CMainDialog::ControlsFillPriorityCharTypesList(void)
{
	aplExtent aeCTypes;
	CStringList csCTypes;
	CString cst="";
	CCharHelper ccHlp(m_api);

	CListBox* clT=NULL;
	POSITION pos=NULL;

	int i=0;

	if(FALSE==ccHlp.GetCharTypes(aeCTypes,csCTypes))
		return;

	clT=(CListBox*)GetDlgItem(IDC_LB_PRIORITY_LIST);
	for(i=0;i<aeCTypes.GetSize();i++)
	{
		pos=csCTypes.FindIndex(i);cst=csCTypes.GetAt(pos);
		clT->InsertString(i,cst);
		clT->SetItemData(i,(DWORD)aeCTypes[i]);
	}

	cst="тип не задан";
	clT->InsertString(i,cst);
	clT->SetItemData(i,(DWORD)NULL);
}


void SaveTreeList2File(CaplTreeListCtrl &treelist,HTREEITEM hItem, int level,CStdioFile &file,char razd)
{
	if(hItem==0) return;
	CString buf,buf1;
	buf.Format("%i",level);
	buf+=razd;
		int i;

	for(i=0;i<level;i++) buf+="   ";

	for(i=0;i<treelist.m_wndHeader.GetItemCount( );i++)
	{
		if(i!=0) buf+=razd;
		buf1=treelist.GetItemText(hItem,i);
		buf+="\"";buf+=buf1;buf+="\"";
	}
	buf+="\n";
	file.WriteString(buf);
	
	HTREEITEM hChildItem=treelist.GetChildItem(hItem);
	while (hChildItem != NULL)
	{
		SaveTreeList2File(treelist,hChildItem,level+1,file,razd);
		hChildItem = treelist.GetNextItem(hChildItem, TVGN_NEXT);
	}
}



void CMainDialog::OnBSave() 
{
	CString buf;
	CString cst1="",cst2="";
	CString cs_ot="",cs_fn="",cs_dfn="";

	//	iTabCount - регулирует ширину отступа для дочерних элементов.
	int iTabCount=5,i=0;

	if(m_view->m_tree.GetCount()==0)
		return;

	cs_dfn="outfile";

	CFileDialog fd(FALSE,"",cs_dfn,OFN_NOREADONLYRETURN|OFN_OVERWRITEPROMPT,
		"Текст с разделителем запятой (*.csv)|*.csv|"
		"Текст с разделителем точкой с запятой (*.csv)|*.csv||");
		//"Текст с разделителем - точкой с запятой (*.csv)|*.csv||");
		
	if(IDCANCEL==fd.DoModal())
		return;
	cs_fn=fd.GetPathName();


	char razd=',';

	if(fd.m_ofn.nFilterIndex==2) razd =';'; 


	HTREEITEM hItem=m_view->m_tree.GetRootItem();
	//HTREEITEM htitem;

//	m_view->m_tree.Expand(hItem,TVE_EXPAND);
	CStdioFile file(cs_fn,CFile::modeCreate|CFile::modeWrite|CFile::typeText);
	
	HDITEM hdi;
	hdi.mask=HDI_TEXT;
	TCHAR  lpBuffer[256];
	hdi.pszText = lpBuffer;
	hdi.cchTextMax = 256;
	

	int colums_num=m_view->m_tree.m_wndHeader.GetItemCount( );

	cst2="Уровень";

	for(i=0;i<colums_num;i++)
	{
		cst2+=razd;
		m_view->m_tree.m_wndHeader.GetItem(i,&hdi);
		cst2+="\"";cst2+=hdi.pszText;cst2+="\"";
	}
	file.WriteString(cst2);
	file.WriteString("\n");

	
	SaveTreeList2File(m_view->m_tree,m_view->m_tree.GetRootItem(),0,file,razd);


	/*do 
	{
		cst1="";cst2="";
		cst2+=cs_ot;
		//	сохраняем элемент
		for(i=0;i<colums_num;i++)
		{
			if(i!=0)cst2+=razd;
			cst1=m_view->m_tree.GetItemText(hItem,i);
			cst2+="\"";cst2+=cst1;cst2+="\"";
			
		}
		cst2+="\n";
		file.WriteString(cst2);
		//	получаем дочерний
		htitem=m_view->m_tree.GetChildItem(hItem);
		if(NULL==htitem)
		{
			//	если дочерних нет - получаем соседний на том же уровне
			htitem=m_view->m_tree.GetNextSiblingItem(hItem);
			if(NULL==htitem)
			{
				//	если соседнего нет - выходим на уровень вверх и берем соседний на том 
				//	уровне.
				htitem=m_view->m_tree.GetParentItem(hItem);
				hItem=m_view->m_tree.GetNextSiblingItem(htitem);
				//	если такого нет - выходим из цикла - обошли всё дерево
				if(NULL==hItem)
					break;
				htitem=hItem;
				cs_ot.Delete(cs_ot.GetLength()-iTabCount,iTabCount);
			}
		}
		else
		{
			for(i=0;i<iTabCount;i++)
				cs_ot+=" ";
		}
		hItem=htitem;
//		m_view->m_tree.SelectItem(hItem);
//		m_view->m_tree.Expand(hItem,TVE_EXPAND);
	} 
	while(1);*/
	

}

void CMainDialog::OnCheckFilters() 
{
	CEdit*			ceT=NULL;
	CDateTimeCtrl*	cdtT1=NULL, *cdtT2=NULL;

	UpdateData(TRUE);
	ceT=(CEdit*)GetDlgItem(IDC_E_SN);
	cdtT1=(CDateTimeCtrl*)GetDlgItem(IDC_DT_DATE);
	cdtT2=(CDateTimeCtrl*)GetDlgItem(IDC_DT_TIME);

	ceT->EnableWindow(m_bUseSN);
	cdtT1->EnableWindow(m_bUseDT);
	cdtT2->EnableWindow(m_bUseDT);

	m_bNeedRebuild=TRUE;
}

void CMainDialog::OnCheckCalcChars() 
{
	CButton* cbT1=NULL,*cbT2=NULL,*cbT3=NULL;

	UpdateData(TRUE);
	cbT1=(CButton*)GetDlgItem(IDC_B_CALC);
	cbT2=(CButton*)GetDlgItem(IDC_B_CHOOSE_WEIGHT);
	cbT3=(CButton*)GetDlgItem(IDC_B_CHOOSE_COST);
	cbT1->EnableWindow(m_bCalcWeight || m_bCalcCost);
	cbT2->EnableWindow(m_bCalcWeight);
	cbT3->EnableWindow(m_bCalcCost);
}

void CMainDialog::OnBChooseWeight() 
{
	CCharHelper ccHlp(m_api);
	CaplInstance* cit=m_ciWeightChar;
	BOOL bRet=FALSE;

	bRet=ccHlp.GetChar(cit,m_csWeightUnit,CCharHelper::m_eWeightType);
	if(cit!=m_ciWeightChar && TRUE==bRet)
	{
		m_ciWeightChar=cit;
		m_bNeedRebuild=TRUE;
	}
	UpdateData(FALSE);
	OnCheckCalcChars();
}

void CMainDialog::OnBChooseCost() 
{
	CCharHelper ccHlp(m_api);
	CaplInstance* cit=m_ciCostChar;
	BOOL bRet=FALSE;

	bRet=ccHlp.GetChar(cit,m_csCostUnit,CCharHelper::m_eCostType);
	if(cit!=m_ciCostChar && TRUE==bRet)
	{
		m_ciCostChar=cit;
		m_bNeedRebuild=TRUE;
	}
	UpdateData(FALSE);
	OnCheckCalcChars();
}

void CMainDialog::OnBMoveUp() 
{
	ControlsMoveInPriorityList(-1);
}

void CMainDialog::OnBMoveDown() 
{
	ControlsMoveInPriorityList(1);
}

void CMainDialog::ControlsMoveInPriorityList(int iDir)
{
	CListBox* clT=NULL;

	int i=0, iCount=0;

	CString cst="";
	DWORD dwItemData=0;

	clT=(CListBox*)GetDlgItem(IDC_LB_PRIORITY_LIST);
	iCount=clT->GetCount();
	if(LB_ERR==iCount)
		return;
	i=clT->GetCurSel();
	if(LB_ERR==i)
		return;
	if(iDir!=-1 && iDir!=1)
		return;
	if(-1==iDir && 0==i)
		return;
	if(1==iDir && iCount-1==i)
		return;

	clT->GetText(i,cst);
	dwItemData=clT->GetItemData(i);
	clT->DeleteString(i);
	clT->InsertString(i+(1*iDir),cst);
	clT->SetItemData(i+(1*iDir),dwItemData);
	clT->SetCurSel(i+(1*iDir));
}

void CMainDialog::ControlsGetPriorityList(aplExtent& aeCharTypes)
{
	CListBox* clT=NULL;
	int i=0;

	clT=(CListBox*)GetDlgItem(IDC_LB_PRIORITY_LIST);

	for(i=0;i<clT->GetCount();i++)
	{
		aeCharTypes.Add((CaplInstance*)clT->GetItemData(i));
	}
}

void CMainDialog::ControlsFillContextsList(void)
{
	aplExtent aeContexts;
	CStringList csContexts;
	CString cst="";
	CCharHelper ccHlp(m_api);
	POSITION pos=NULL;

	int i=0;

	if(FALSE==ccHlp.GetContexts(aeContexts,csContexts))
		return;

	for(i=0;i<aeContexts.GetSize();i++)
	{
		pos=csContexts.FindIndex(i);cst=csContexts.GetAt(pos);
		m_cbContext.InsertString(i,cst);
		m_cbContext.SetItemData(i,(DWORD)aeContexts[i]);
	}

	i++;
	cst="Все контексты";
	i=m_cbContext.InsertString(-1,cst);
	m_cbContext.SetItemData(i,(DWORD)NULL);	

	m_cbContext.SetCurSel(i);
}

BOOL CMainDialog::ControlsGetDTFilter(COleDateTime& codtFilter)
{
	
	if(TRUE==m_bUseDT)
	{
		codtFilter.SetDateTime(m_codtDateFilter.GetYear(),m_codtDateFilter.GetMonth(),
								 m_codtDateFilter.GetDay(),m_codtTimeFilter.GetHour(),
								 m_codtTimeFilter.GetMinute(),m_codtTimeFilter.GetSecond());
	}
	else
	{
		codtFilter.SetStatus(COleDateTime::invalid);
	}
	return TRUE;
}

BOOL CMainDialog::ControlsGetSNFilter(CString& csFilter)
{
	if(TRUE==m_bUseSN)
		csFilter=m_csSNFilter;
	else
		csFilter="";
	return TRUE;
}

BOOL CMainDialog::ControlsShowCalculatedChars(double* dChars)
{
	CaplInstance* ciUnit;
	CString cst="";
	int i=0;

	if(TRUE==m_bCalcCost)
	{
		m_api->m_data.GetAttr(m_ciCostChar,m_api->m_charact_mgr.a_apl_charact_unit,ciUnit);
		m_api->m_charact_mgr.GetUnitName(ciUnit,cst);
		m_csCdCost.Format("%g [%s]",dChars[i],cst);
		i++;
	}
	if(TRUE==m_bCalcWeight)
	{
		m_api->m_data.GetAttr(m_ciWeightChar,m_api->m_charact_mgr.a_apl_charact_unit,ciUnit);
		m_api->m_charact_mgr.GetUnitName(ciUnit,cst);
		m_csCdWeight.Format("%g [%s]",dChars[i],cst);
		i++;
	}
	UpdateData(FALSE);
	return TRUE;
}

BOOL CMainDialog::RebuildPdfStructure(void)
{
	CaplInstance*	ciContext	=NULL;
	CaplInstance*	ciUnit		=NULL;
	
	//	аттрибуты для получения значений хар-к.
	CaplTAggr<CaplAttr*,CaplAttr*,APLAGGR_LIST> caCharVals;
	//	хар-ки для подсчёта.
	CaplTAggr<CaplInstance*,CaplInstance*,APLAGGR_LIST> caChars;

	//	id хар-к для сбора
	int iCharsToCollect[2]={CPdfItem::m_eCostChar,CPdfItem::m_eWeightChar};
	
	COleDateTime	codtDTFilter;
	CString			csSNFilter;

	//WriteToLog("ControlsGetSNFilter",true,false,true);
	ControlsGetSNFilter(csSNFilter);
	//WriteToLog("ControlsGetDTFilter",true,false,true);
	ControlsGetDTFilter(codtDTFilter);
	ciContext=(CaplInstance*)m_cbContext.GetItemData(m_cbContext.GetCurSel());

	if(NULL!=m_pItem)
	{
		delete m_pItem;m_pItem=NULL;
	}
	//dmibor 30/05/06
	m_t_protocol_ctrl.SetWindowText("Загрузка состава изделия...");
	//WriteToLog("чтение струтуры изделия из БД (DisassemblyProduct)",true,false,true);
	aplExtent ext_rel;aplExtent ext_pdf; aplRealArray count_array; aplExtent ext_unit;
	m_api->m_prd_mgr.DisassemblyProduct(0,m_inst,ext_rel,ext_pdf,count_array,ext_unit);
	m_t_protocol_ctrl.SetWindowText("Загрузка характеристик...");
	//WriteToLog("чтение характеристик (FindAssociatedCharacteristic)",true,false,true);
	aplExtent ext_char;
	ext_pdf.Add(m_inst);
	m_api->m_charact_mgr.FindAssociatedCharacteristic(ext_pdf,ext_char,false,false,true);
		
	//WriteToLog("обработка структуры",true,false,true);
	m_t_protocol_ctrl.SetWindowText("Обработка данных...");
	m_pItem=new CPdfItem(m_api,m_inst,codtDTFilter,csSNFilter,ciContext);

	caChars.Add(m_ciCostChar);
	caChars.Add(m_ciWeightChar);

	if(NULL!=m_ciCostChar)
	{
		m_api->m_data.GetAttr(m_ciCostChar,m_api->m_charact_mgr.a_apl_charact_unit,ciUnit);

		if(m_api->m_data.IsKindOf(ciUnit,m_api->m_charact_mgr.e_apl_monetary_unit))
			caCharVals.Add(m_api->m_charact_mgr.a_apl_charact_val_monet_val);
		else
		if(m_api->m_data.IsKindOf(ciUnit,m_api->m_charact_mgr.e_apl_step_unit))
			caCharVals.Add(m_api->m_charact_mgr.a_apl_charact_val_meas_val);
	}
	else
		caCharVals.Add(NULL);

	ciUnit=NULL;

	if(NULL!=m_ciWeightChar)
	{
		m_api->m_data.GetAttr(m_ciWeightChar,m_api->m_charact_mgr.a_apl_charact_unit,ciUnit);

		if(m_api->m_data.IsKindOf(ciUnit,m_api->m_charact_mgr.e_apl_step_unit))
			caCharVals.Add(m_api->m_charact_mgr.a_apl_charact_val_meas_val);
		else
		if(m_api->m_data.IsKindOf(ciUnit,m_api->m_charact_mgr.e_apl_monetary_unit))
			caCharVals.Add(m_api->m_charact_mgr.a_apl_charact_val_monet_val);
	}
	else
		caCharVals.Add(NULL);

	//WriteToLog("LoadChars",true,false,true);
	m_pItem->LoadChars(caCharVals,caChars,iCharsToCollect,2);
	
	m_bNeedRebuild=FALSE;

	return TRUE;
}

void CMainDialog::OnBCalc() 
{
	//	собственно подсчет.


	DWORD t1=0,t2=0;

	long lid=0;

	//	приоритет типов хар-к.
	aplExtent aePriorityOfTypes;

	//	id хар-к для посчёта
	int	iCharsToCount[2]={0,0};
	int i=0;
	//	массив для возвращаемых значений хар-к
	double	dRets[2]={0,0};

	UpdateData(TRUE);
	m_csCdWeight="";m_csCdCost="";
	UpdateData(FALSE);

	//WriteToLog("Старт",true,false,true);

	m_view->m_tree.DeleteAllItems();

	//	если необходимо - создаем структуру заново
	if(TRUE==m_bNeedRebuild)
	{
		//WriteToLog("RebuildPdfStructure",true,false,true);
		RebuildPdfStructure();
	}

	//	получаем список типов хар-к - приоритетов
	ControlsGetPriorityList(aePriorityOfTypes);
	if(TRUE==m_bCalcCost)
	{
		//	если считаем стоимость - добавляем флаг для ее подсчета
		iCharsToCount[i]=CPdfItem::m_eCostChar;
		i++;
	}
	if(TRUE==m_bCalcWeight)
	{
		//	если считаем массу - добавляем флаг для ее подсчета
		iCharsToCount[i]=CPdfItem::m_eWeightChar;
		i++;
	}
	//	подсчитываем
	m_t_protocol_ctrl.SetWindowText("Расчет массы и стоимости...");
	//WriteToLog("CalcChars",true,false,true);
	m_pItem->CalcChars(dRets,iCharsToCount,i,aePriorityOfTypes);
	//	выводим на экран
	//WriteToLog("ControlsShowCalculatedChars",true,false,true);
	ControlsShowCalculatedChars(dRets);

	//	заполняем дерево результатами
	//WriteToLog("ControlsTreeListSetItem",true,false,true);
	ControlsTreeListSetItem(m_pItem,TVI_ROOT);
	m_view->m_tree.SelectItem(m_view->m_tree.GetRootItem());
	//	раскрываем дерево
	m_view->Expand(0);

	CString buf;
	buf.Format("   Протокол расчета : получено %i записей",m_view->m_tree.GetItemCount());
	m_t_protocol_ctrl.SetWindowText(buf);

	//WriteToLog("Финиш",true,false,true);
}

void CMainDialog::OnDTFilterChange(NMHDR* pNMHDR, LRESULT* pResult) 
{
	m_bNeedRebuild=TRUE;
	*pResult = 0;
}

void CMainDialog::OnSNFilterChange() 
{
	m_bNeedRebuild=TRUE;
}

void CMainDialog::OnContextChange() 
{
	m_bNeedRebuild=TRUE;
}

bool CMainDialog::Expand(UINT iAction)
{
	HTREEITEM hItem=m_view->m_tree.GetSelectedItem();
	if(NULL==hItem)
		return false;
	return Expand(hItem,iAction);
}

bool CMainDialog::Expanded(HTREEITEM hItem,UINT iAction, HWND hWnd)
{
	return true;
}

void CMainDialog::UpdateUserData()
{
	return;
}

void CMainDialog::Sort(int nCol)
{
	return;
}

bool CMainDialog::Expand(HTREEITEM hItem,UINT iAction)
{
/*
//	HTREEITEM hItem,htItem1,htItem2;
	HTREEITEM htItem1,htItem2;
	CPdfItem* pPdfItem=NULL;
	CPtrArray paChilds;
	int i=0;

//	hItem=m_view->m_tree.GetSelectedItem();
	if(NULL==hItem)
		return false;
	pPdfItem=(CPdfItem*)m_view->m_tree.GetItemData(hItem);
	m_view->m_tree.DeleteSubItems(hItem);
	if(iAction==TVE_EXPAND)
	{
		if(pPdfItem->GetCount()>1)
		{
			pPdfItem->GetChilds(paChilds);
			m_view->m_tree.SetRedraw(FALSE);
			m_view->m_bAutofit=false;
			m_view->m_tree.m_wndHeader.SetAutofit(false);

			for(i=0;i<paChilds.GetSize();i++)
				ControlsTreeListSetItem((CPdfItem*)paChilds.GetAt(i),hItem);

			m_view->m_tree.SetRedraw(TRUE);
			m_view->m_bAutofit=true;
			m_view->m_tree.m_wndHeader.SetAutofit();
		}
	}
	else
	{
		htItem1=m_view->m_tree.GetChildItem(hItem);
		while(htItem1!=NULL)
		{
			htItem2=m_view->m_tree.GetNextSiblingItem(htItem1);
			m_view->m_tree.DeleteItem(htItem1);
			htItem1=htItem2;
		}

		m_view->m_tree.InsertItem("",hItem,TVI_LAST,true);
	}
*/
	return true;
}

void CMainDialog::RefreshAllItems(void)
{
	return;
}

void CMainDialog::WriteToLog(const char *message, bool to_file,bool show_msg_box,bool show_time)
{
	if(!message) return;
	CString msg=message,buf;
	if(show_time)
	{
		COleDateTime dt=COleDateTime::GetCurrentTime();
		buf=dt.Format("%H:%M:%S ");
		msg=buf+msg;
	}
	if(!m_log_file_opened)
	{
		if(m_log_file.Open(m_curFolder+"weightCostCalcLog.log",CFile::modeWrite|CFile::typeText|CFile::shareDenyNone))
		{
			m_log_file_opened=true;
		}
		else
		{
			if(m_log_file.Open(m_curFolder+"weightCostCalcLog.log",CFile::modeCreate|CFile::modeWrite|CFile::typeText|CFile::shareDenyNone))
			{
				m_log_file_opened=true;	
			}
		}
		if(m_log_file_opened)
		{
			m_log_file.SeekToEnd();
		}
		else
		{
			AfxMessageBox("Ошибка открытия лог-файла!");
		}
	}
	if(to_file && m_log_file_opened)
	{
		m_log_file.WriteString(msg+"\n");
		m_log_file.Flush();
	}
	if(show_msg_box)
	{
		AfxMessageBox(message);
	}
	m_log_file.Close();
	m_log_file_opened=false;

	
}
