// ChooseConfigDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ChooseConfigDlg.h"


// CChooseConfigDlg dialog

extern bool (*funcGetAppByPdf)(CaplAPI*, CaplInstance*, aplExtent&);
extern bool (*funcGetAllApp)(CaplAPI*, aplExtent&);
extern bool (*funcGetComplectationByPdf)(CaplAPI*, CaplInstance*, aplExtent&);
extern bool (*funcGetComplectationByApp)(CaplAPI*, aplExtent&, aplExtent&);
extern bool (*funcLoadAppsInfo)(CaplAPI*, aplExtent&);
extern bool (*funcLoadComplectationsInfo)(CaplAPI*, aplExtent&);
extern bool (*funcFilterByAppOrComplectation)(CaplAPI*, aplExtent&, CaplInstance*, aplExtent&, bool, LPCTSTR);
extern bool (*funcSelectOrder)(CaplAPI*, CaplInstance**);
extern bool (*funcGetComplectationsByOrder)(CaplAPI*, CaplInstance*, aplExtent&);


IMPLEMENT_DYNAMIC(CChooseConfigDlg, CaplResizableDialog)

CChooseConfigDlg::CChooseConfigDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CChooseConfigDlg::IDD, pParent)
{
	m_api = NULL;
	m_pProductPDF = NULL;
	m_pOrder= NULL;
	m_pSelectedItem = NULL;
	m_bLoadConfigurationMgr= false;
}

CChooseConfigDlg::~CChooseConfigDlg()
{
}

void CChooseConfigDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);

	DDX_Control(pDX, IDC_SEL_CONFIGURATION, m_cbSelectConfiguration);
	DDX_Control(pDX, IDC_LOAD_CHOSEN_PRODUCT_CONFIGURATIONS_BUTTON, m_btnLoadProductConfigs);
	DDX_Control(pDX, IDOK, m_btnOk);
	DDX_Control(pDX, IDCANCEL, m_btnCancel);	
	DDX_Control(pDX, IDC_ORDER_CTRL, m_ctrlOrder);	
	DDX_Control(pDX, IDC_SELECT_ORDER_BTN, m_btnSelectOrder);	
	
}


BEGIN_MESSAGE_MAP(CChooseConfigDlg, CaplResizableDialog)
	ON_BN_CLICKED(IDOK, &CChooseConfigDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDC_LOAD_CHOSEN_PRODUCT_CONFIGURATIONS_BUTTON, &CChooseConfigDlg::OnBnClickedLoadChosenProductConfigurationsButton)
	ON_CBN_SELCHANGE(IDC_SEL_CONFIGURATION, &CChooseConfigDlg::OnCbnSelchangeSelConfiguration)
	ON_BN_CLICKED(IDC_SELECT_ORDER_BTN, &CChooseConfigDlg::OnBnClickedSelectOrder)
	ON_BN_CLICKED(IDC_CLEAR_ORDER_BTN, &CChooseConfigDlg::OnBnClickedClearOrder)
	
END_MESSAGE_MAP()


// CChooseConfigDlg message handlers

BOOL CChooseConfigDlg::OnInitDialog()
{
	CaplResizableDialog::OnInitDialog();
	if(m_api==NULL)
	{
		EndDialog(0);
		return FALSE;
	}

	// предотвращаем потерю модальности после диалога с бочками из aplSocketTransport
	CORRECT_LOOSE_MODAL_ON_CLASS(&(m_api->m_data));

	ModifyStyle(0, WS_MAXIMIZEBOX);
	SetAnchors();

	m_btnOk.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_btnOk.SetFlat(FALSE);
	m_btnCancel.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_btnCancel.SetFlat(FALSE);

	m_cbSelectConfiguration.AddString( APL_T("Все базисы / конфигурации"));

	if(m_bLoadConfigurationMgr)
	{
#ifdef _DEBUG
		CString strLibFileName = CString(_T("aplConfiguratorMgrD.dll"));
#else
		CString strLibFileName = CString(_T("aplConfiguratorMgr.dll"));
#endif

		HINSTANCE hConfigMgrLib = AfxLoadLibrary(strLibFileName);

		if (hConfigMgrLib != NULL)
		{

			(FARPROC&)funcGetAllApp = ::GetProcAddress(hConfigMgrLib, "add_GetAllApp");
			(FARPROC&)funcGetComplectationByApp = ::GetProcAddress(hConfigMgrLib, "add_GetComplectationByAppearences");
			(FARPROC&)funcSelectOrder = ::GetProcAddress(hConfigMgrLib, "add_SelectOrder");	
			(FARPROC&)funcGetComplectationsByOrder = ::GetProcAddress(hConfigMgrLib, "add_GetComplectationsByOrder");	

			(FARPROC&)funcGetAppByPdf = ::GetProcAddress(hConfigMgrLib, "add_GetAppByPdf");
			(FARPROC&)funcGetComplectationByPdf = ::GetProcAddress(hConfigMgrLib, "add_GetComplectationByPdf");

			(FARPROC&)funcFilterByAppOrComplectation = ::GetProcAddress(hConfigMgrLib, "add_BasisAndComplectationFilter");		
			(FARPROC&)funcLoadAppsInfo = ::GetProcAddress(hConfigMgrLib, "add_LoadConfigurationsInfo");
			(FARPROC&)funcLoadComplectationsInfo = ::GetProcAddress(hConfigMgrLib, "add_LoadComplectationsInfo");		
				
		}
	}

	UpdateOrderInfo();
	UpdateComplectationsList();

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

void CChooseConfigDlg::OnBnClickedLoadChosenProductConfigurationsButton()
{
	if ((funcGetAppByPdf == NULL) || 
		(funcGetComplectationByPdf == NULL) || 
		(funcFilterByAppOrComplectation == NULL))
		return;	

	CaplInstance* pTmp = m_api->m_prd_mgr.SelectInstance(APL_MODE_SELECT_PDF, CString( APL_T("Выбор версии изделия")));
	if(pTmp!=NULL)
	{
		m_pProductPDF= pTmp;
		m_pOrder= NULL;
		UpdateOrderInfo();
		UpdateComplectationsList();
	}
	
	
}

void CChooseConfigDlg::OnCbnSelchangeSelConfiguration()
{
	int iSelItem = m_cbSelectConfiguration.GetCurSel();

	if (iSelItem == -1)
		return;

	m_pSelectedItem = (CaplInstance*)m_cbSelectConfiguration.GetItemData(iSelItem);
}

void CChooseConfigDlg::UpdateComplectationsList(bool bForceSelectComplectation/*=false*/)
{
	aplExtent extApps;
	CaplStrMap mapApps;
	aplExtent extComplectations;	
	CaplStrMap mapComplectations;

// 	if (pProductPDF == NULL)
// 		return;

	int nCount = m_cbSelectConfiguration.GetCount();

	for (int iIndex = 0; iIndex < (nCount - 1); iIndex++)
		m_cbSelectConfiguration.DeleteString(1);

	m_cbSelectConfiguration.SetCurSel(0);

	//////////////////////////////////////////////////////////////////////////
	// Базисы
	if(m_pOrder==NULL)//если заказ задан, базисы не отображаем	
	{
		if(m_pProductPDF==NULL)
		{
			funcGetAllApp(m_api, extApps);
		}
		else
		{
			funcGetAppByPdf(m_api, m_pProductPDF, extApps);
		}
		funcLoadAppsInfo(m_api, extApps);	

		for (int iIndex = 0; iIndex < extApps.GetSize(); iIndex++)
		{
			CaplInstance *pApp = extApps[iIndex];
			CString strAppCode;
			CString strAppName;
			CString strAppInfo;

			m_api->m_data.GetAttrBN(pApp, _T("code"), strAppCode);
			m_api->m_data.GetAttrBN(pApp, _T("name"), strAppName);

			strAppInfo = CString(_T("(")) + strAppCode + CString(_T(" : ")) + strAppName + CString(_T(")"));
			mapApps.Add(strAppInfo, pApp);
		}

		mapApps.Sort();

		for (int iIndex = 0; iIndex < mapApps.GetSize(); iIndex++)
		{
			CaplInstance *pApp = (CaplInstance*)mapApps.GetAt(iIndex)->val;
			CString strAppCode;
			CString strAppName;
			CString strAppInfo;

			m_api->m_data.GetAttrBN(pApp, _T("code"), strAppCode);
			m_api->m_data.GetAttrBN(pApp, _T("name"), strAppName);

			strAppInfo = CString(_T("(")) + strAppCode + CString(_T(" : ")) + strAppName + CString(_T(")"));
			m_cbSelectConfiguration.AddString(strAppInfo);
			m_cbSelectConfiguration.SetItemData(iIndex + 1, (DWORD)pApp);

			//////////////////////////////////////////////////////////////////////////
			// Сравниваем с переданной, чтобы сразу выделить
			if (pApp == m_pSelectedItem)
				m_cbSelectConfiguration.SetCurSel(iIndex + 1);
		}
	}
	//////////////////////////////////////////////////////////////////////////
	// Комплектации
	if(m_pOrder!=NULL)//если задан заказ, остальное уже не важно, отбираем конфигурации для него
	{
		UpdateOrderInfo();
		funcGetComplectationsByOrder(m_api, m_pOrder, extComplectations);
	}
	else if(m_pProductPDF!=NULL)
	{
		funcGetComplectationByPdf(m_api, m_pProductPDF, extComplectations);
	}
	else 
	{
		funcGetComplectationByApp(m_api, extApps, extComplectations);
	}
	funcLoadComplectationsInfo(m_api, extComplectations);

	for (int iIndex = 0; iIndex < extComplectations.GetSize(); ++iIndex)
	{
		CaplInstance *pComplectation = extComplectations[iIndex];
		CString strCompCode;
		CString strCompName;
		CString strComplectationInfo;

		m_api->m_data.GetAttrBN(pComplectation, _T("code"), strCompCode);
		m_api->m_data.GetAttrBN(pComplectation, _T("name"), strCompName);

		strComplectationInfo = strCompCode + CString(_T(" : ")) + strCompName;
		mapComplectations.Add(strComplectationInfo, pComplectation);
	}

	mapComplectations.Sort();

	for (int iIndex = 0; iIndex < mapComplectations.GetSize(); iIndex++)
	{
		CaplInstance *pComplectation = (CaplInstance*)mapComplectations.GetAt(iIndex)->val;
		CString strCompCode;
		CString strCompName;
		CString strComplectationInfo;

		m_api->m_data.GetAttrBN(pComplectation, _T("code"), strCompCode);
		m_api->m_data.GetAttrBN(pComplectation, _T("name"), strCompName);

		strComplectationInfo = strCompCode + CString(_T(" : ")) + strCompName;
		m_cbSelectConfiguration.AddString(strComplectationInfo);
		m_cbSelectConfiguration.SetItemData(extApps.GetSize() + iIndex + 1, (DWORD)pComplectation);

		//////////////////////////////////////////////////////////////////////////
		// Сравниваем с переданной, чтобы сразу выделить
		if (pComplectation == m_pSelectedItem)
			m_cbSelectConfiguration.SetCurSel(extApps.GetSize() + iIndex + 1);
	}
	if(m_pSelectedItem==NULL && bForceSelectComplectation)//если только что выбрали заказ и есть связанные конфигурации, принудительно выберем первую из них
	{
		if(extComplectations.GetSize()>0 && m_cbSelectConfiguration.GetCount()>1)
		{
			m_cbSelectConfiguration.SetCurSel(1);
			OnCbnSelchangeSelConfiguration();
		}
	}
}

void CChooseConfigDlg::SetAnchors()
{
	AddAnchor(IDC_SEL_CONFIGURATION, TOP_LEFT, TOP_RIGHT);
	AddAnchor(IDC_LOAD_CHOSEN_PRODUCT_CONFIGURATIONS_BUTTON, TOP_RIGHT);
	AddAnchor(IDOK, BOTTOM_RIGHT);
	AddAnchor(IDCANCEL, BOTTOM_RIGHT);
}

void CChooseConfigDlg::OnBnClickedOk()
{
	CaplResizableDialog::OnOK();
}

void CChooseConfigDlg::OnBnClickedSelectOrder()
{
	CaplInstance* pTmp= m_pOrder;
	funcSelectOrder(m_api, &pTmp);
	if(pTmp!=NULL)
	{
		m_pOrder= pTmp;
		m_pProductPDF= NULL;
		m_pSelectedItem= NULL;
		UpdateOrderInfo();
		UpdateComplectationsList(true);
	}
}

void CChooseConfigDlg::OnBnClickedClearOrder()
{
	m_pOrder= NULL;
	UpdateOrderInfo();
	UpdateComplectationsList();
}

void CChooseConfigDlg::UpdateOrderInfo()
{
	CString sOrderName= APL_T("< правило применяемости не задано >");

	if(m_pOrder!=NULL)
	{
		m_api->m_data.GetAttrBN(m_pOrder, _T("sn"), sOrderName);
		if(sOrderName.IsEmpty()==true)
		{
			m_api->m_data.GetAttrBN(m_pOrder, _T("factory_number"), sOrderName);
		}
		if(sOrderName.IsEmpty()==true)
		{
			sOrderName= APL_T("< серийный и заводской номер не заданы >");
		}
	}
	m_ctrlOrder.SetWindowText(sOrderName);

}
