// ReportApprovalFiledsSetupDlg.cpp : implementation file
//

#include "stdafx.h"
#include <aplXML.h>
#include "ReportApprovalFiledsSetupDlg.h"


// CReportApprovalFiledsSetupDlg dialog

IMPLEMENT_DYNAMIC(CReportApprovalFiledsSetupDlg, CaplResizableDialog)

CReportApprovalFiledsSetupDlg::CReportApprovalFiledsSetupDlg(CaplAPI *api, CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CReportApprovalFiledsSetupDlg::IDD, pParent)
{
	m_api = api;
	m_pEditWnd = 0;	
	m_nCurrentItem = -1;
	m_nCurrentSubItem = -1;

	m_bDoNotProccessed = true;

	m_sEmptyString = _T("                    ");
	m_sOptionName =  APL_NO_T("Таблица ролей и статусов для документов типа aplrep");	

	m_saAbbr.Add( APL_NO_T("Разработал"));			m_saAbbr.Add(_T("Develop"));
	m_saAbbr.Add( APL_NO_T("Проверил"));			m_saAbbr.Add(_T("Checker"));
	m_saAbbr.Add( APL_NO_T("Начальник"));			m_saAbbr.Add(_T("Director"));
	m_saAbbr.Add( APL_NO_T("Нормоконтроль"));		m_saAbbr.Add(_T("NormControl"));
	m_saAbbr.Add( APL_NO_T("Техконтроль"));		m_saAbbr.Add(_T("TekhControl"));
	m_saAbbr.Add( APL_NO_T("Утвердил"));			m_saAbbr.Add(_T("Approved"));
	m_saAbbr.Add( APL_NO_T("ВП"));					m_saAbbr.Add(_T("Army"));

	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0
	if(0!=app)
	{
		m_nOpenWithoutApproval = app->GetProfileInt(_T("APLREP_Settings"), _T("OpenWithoutApproval"), 0);
		m_nOpenWithoutDates = app->GetProfileInt(_T("APLREP_Settings"), _T("OpenWithoutDates"), 0);
		m_nOpenWithoutSign = app->GetProfileInt(_T("APLREP_Settings"), _T("OpenWithoutSign"), 0);
	}
	else
	{
		m_nOpenWithoutApproval=0;
		m_nOpenWithoutDates=0;
		m_nOpenWithoutSign=0;
	}
}

CReportApprovalFiledsSetupDlg::~CReportApprovalFiledsSetupDlg()
{
}

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

	DDX_Control(pDX, IDC_LIST, m_list);
	DDX_Control(pDX, IDOK, m_ok_btn);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, IDC_COMBO, m_combo);
	DDX_Control(pDX, IDC_CLEAR, m_clear);

	DDX_Check(pDX, IDC_OPEN_WITHOUT_APPROVAL, m_nOpenWithoutApproval);
	DDX_Check(pDX, IDC_OPEN_WITHOUT_DATES, m_nOpenWithoutDates);
	DDX_Check(pDX, IDC_OPEN_WITHOUT_SIGN, m_nOpenWithoutSign);
}


BEGIN_MESSAGE_MAP(CReportApprovalFiledsSetupDlg, CaplResizableDialog)
	ON_WM_SIZE()
	ON_NOTIFY(NM_DBLCLK, IDC_LIST, &CReportApprovalFiledsSetupDlg::OnNMDblclkList)
	ON_NOTIFY(NM_CLICK, IDC_LIST, &CReportApprovalFiledsSetupDlg::OnNMClickList)
	ON_NOTIFY(NM_SETFOCUS, IDC_LIST, &CReportApprovalFiledsSetupDlg::OnNMSetfocusList)
	ON_BN_CLICKED(IDOK, &CReportApprovalFiledsSetupDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDC_CLEAR, &CReportApprovalFiledsSetupDlg::OnBnClickedClear)
END_MESSAGE_MAP()

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

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

	CString sValue, sField, sApproval, sRole;
	CaplXMLFile file;

	// получаем список всех ролей
	GetAllRoles();

	// получаем список всех статусов
	GetAllStatuses();

	// инициализируем список
	InitList();

	// инициализируем кнопки
	InitButtons();

	// анкоры
	InitAnchor();

	// загружаем настройку
	m_api->m_options_mgr.GetOptionValueBN(m_sOptionName, sValue, _T(""));
	if(!file.LoadFromBuffer(sValue) && !sValue.IsEmpty())
	{
		MessageBox( APL_T("Настройки ролей и статусов для документов типа \"aplrep\" прочитать не удалось.\nВозможно был нарушен формат записи!"),  APL_T("Ошибка"), MB_ICONSTOP);		
	}
	else
	{
		for(int i=0; i<file.root.subnodes.GetSize(); i++)
		{
			CaplXMLNode *node = file.root.subnodes[i];
			if(!node) continue;

			// читаем настройку
			sField = node->name;
			node->GetParam(_T("Approval"), sApproval);
			node->GetParam(_T("Role"), sRole);			

			// пишем настройку в лист
			ChangeListStringBySetupValue(sField, sRole, sApproval);
		}
	}

	CreateEditBox();
	UpdateData(FALSE);

	return TRUE;
}

void CReportApprovalFiledsSetupDlg::CreateOption()
{
	CString result;
	CaplXMLFile file;
	CString sField, sApproval, sRole;

	for(int i=0; i<m_list.GetItemCount(); i++)
	{
		sField = m_list.GetItemText(i, 0);
		sRole = m_list.GetItemText(i, 1);
		sApproval = m_list.GetItemText(i, 2);

		CaplXMLNode *node = new CaplXMLNode();
		node->parent = &file.root;
		file.root.subnodes.Add(node);

		node->name = sField;
		node->SetParam(_T("Approval"), sApproval);
		node->SetParam(_T("Role"), sRole);
		node->SetParam(_T("Abbrv"), GetAbbrvForField(sField));
	}

	file.SaveToBuffer(result);
	m_api->m_options_mgr.CreateOption(m_sOptionName, result);
}

bool CReportApprovalFiledsSetupDlg::GetAllRoles()
{
	CString str;
	aplExtent aeRoles;
	CaplLoadData ld(&m_api->m_data, DEF_SOURCE);

	ld.AddQuery(0, _T('e'), 0, m_api->m_appr_mgr.e_po_role, 0, true);
	ld.LoadEx(true, &aeRoles);

	aplQSortByAttr(&m_api->m_data, aeRoles, 0, aeRoles.Size-1,m_api->m_appr_mgr.a_po_role_name);
	for(int i=0; i<aeRoles.Size; i++)
	{
		m_api->m_data.GetAttr(aeRoles[i], m_api->m_appr_mgr.a_po_role_name, str);
		m_saRoles.Add(str);
	}

	return true;
}

bool CReportApprovalFiledsSetupDlg::GetAllStatuses()
{
	CString str;
	aplExtent aeStatuses;
	CaplLoadData ld(&m_api->m_data, DEF_SOURCE);

	ld.AddQuery(0, _T('e'), 0, m_api->m_appr_mgr.e_appr_status, 0, true);
	ld.LoadEx(true, &aeStatuses);

	aplQSortByAttr(&m_api->m_data, aeStatuses, 0, aeStatuses.Size-1,m_api->m_appr_mgr.a_appr_status_name);
	for(int i=0; i<aeStatuses.Size; i++)
	{
		m_api->m_data.GetAttr(aeStatuses[i], m_api->m_appr_mgr.a_appr_status_name, str);
		m_saStatuses.Add(str);
	}	

	return true;
}

bool CReportApprovalFiledsSetupDlg::ChangeListStringBySetupValue( CString sField, CString Role, CString sApproval )
{
	CString field;

	for(int i=0; i<m_list.GetItemCount(); i++)
	{
		field = m_list.GetItemText(i, 0);
		
		if(field == sField)
		{
			m_list.SetItemText(i, 1, Role);
			m_list.SetItemText(i, 2, sApproval);
		}
	}

	return true;
}

bool CReportApprovalFiledsSetupDlg::InitList()
{
	CRect rect;
	m_list.GetClientRect(rect);

	m_list.InsertColumn(0,  APL_T("Поле в отчете"), LVCFMT_LEFT, (int)(rect.Width()*0.2));
	m_list.InsertColumn(1,  APL_T("Роль"), LVCFMT_LEFT, (int)(rect.Width()*0.4));
	m_list.InsertColumn(2,  APL_T("Статус"), LVCFMT_LEFT, (int)(rect.Width()*0.4));

	m_list.ModifyStyle(0, LVS_OWNERDRAWFIXED);
	m_list.SetExtendedStyle(m_list.GetExtendedStyle()|LVS_EX_FULLROWSELECT|
		LVS_EX_SUBITEMIMAGES | LVS_EX_GRIDLINES);

	for(int i=0, j=0; i<m_saAbbr.GetSize(); i+=2, j++)
		m_list.InsertItem(j, m_saAbbr[i]);

	m_list.SetRowHeight(20);
	return true;	
}

bool CReportApprovalFiledsSetupDlg::InitButtons()
{
	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	m_ok_btn.SetIcon(GetAplStdIco16(APLSTDICO_OK));
	m_ok_btn.SetFlat(FALSE);
	m_clear.SetFlat(FALSE);

	return true;
}

bool CReportApprovalFiledsSetupDlg::InitAnchor()
{
	AddAnchor(IDOK, BOTTOM_RIGHT);
	AddAnchor(IDCANCEL, BOTTOM_RIGHT);
	AddAnchor(IDC_LIST, TOP_LEFT, BOTTOM_RIGHT);
	AddAnchor(IDC_CLEAR, TOP_RIGHT);
	AddAnchor(IDC_OPEN_WITHOUT_APPROVAL, BOTTOM_LEFT);
	AddAnchor(IDC_OPEN_WITHOUT_DATES, BOTTOM_LEFT);

	return true;
}

// CReportApprovalFiledsSetupDlg message handlers

void CReportApprovalFiledsSetupDlg::OnSize( UINT nType, int cx, int cy )
{
	CaplResizableDialog::OnSize(nType, cx, cy);

	if(m_list)
	{
		int k = m_list.GetHeaderCtrl()->GetItemCount();
		CRect rect;
		m_list.GetWindowRect(&rect);
		ScreenToClient(&rect);
		cx = rect.right - rect.left - 12;

		if(k>0)
		{
			int i;
			int dx=0;
			for(i=0;i<k;i++) dx += m_list.GetColumnWidth(i);

			for(i=0; i<m_list.GetHeaderCtrl()->GetItemCount(); i++)
			{
				int l = m_list.GetColumnWidth(i);
				if(l == 0) break;

				HDITEM pHeader;
				pHeader.mask = HDI_WIDTH;
				m_list.GetHeaderCtrl()->GetItem(i, &pHeader);
				pHeader.cxy = ((cx*l)/dx)+1;
				m_list.GetHeaderCtrl()->SetItem(i, &pHeader);				
			}			
		}
	}

	HideEditBox();
}

void CReportApprovalFiledsSetupDlg::OnNMDblclkList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
		
	m_nCurrentSubItem = pNMItemActivate->iSubItem;
	m_nCurrentItem = pNMItemActivate->iItem;
	
	CString str;
	CRect  itemRect;

	str = m_list.GetItemText( m_nCurrentItem, m_nCurrentSubItem);
	m_list.GetSubItemRect( m_nCurrentItem, m_nCurrentSubItem, LVIR_BOUNDS, itemRect);
	if(m_nCurrentItem == -1 || m_nCurrentSubItem == -1) return;

	if(m_nCurrentSubItem == 1 || m_nCurrentSubItem == 2)
	{			
		// очищаем значения
		while(m_combo.GetCount())
			m_combo.DeleteString(0);

		if(m_nCurrentSubItem == 1) FillComboWithRoles(str);
		else if(m_nCurrentSubItem == 2) FillComboWithStatuses(str);

		itemRect.bottom += 200;
		m_combo.MoveWindow(itemRect);
		m_combo.ShowWindow(SW_SHOW);
		m_pEditWnd = &m_combo;	

		m_combo.SetWindowText(m_list.GetItemText(m_nCurrentItem, m_nCurrentSubItem));
		m_combo.SetFocus();
		m_combo.GetWindowText(m_sPrevVal);
	}

	*pResult = 0;
}

void CReportApprovalFiledsSetupDlg::CreateEditBox()
{
	m_combo.SetParent(&m_list);
	m_combo.SetUseSpecialFirstString(true);
	m_combo.SetUnselectableString(m_sEmptyString);
}

void CReportApprovalFiledsSetupDlg::HideEditBox(bool bCreateVal)
{
	if(m_pEditWnd)
	{
		CString listStr, comboStr;
			
		listStr = m_list.GetItemText(m_nCurrentItem, m_nCurrentSubItem);
		m_combo.GetWindowText(comboStr);

		if(bCreateVal)
			m_list.SetItemText(m_nCurrentItem, m_nCurrentSubItem, comboStr);

		m_bDoNotProccessed = true;
		m_pEditWnd->ShowWindow(SW_HIDE);
		m_bDoNotProccessed = false;

		m_pEditWnd->SetWindowText(_T(""));
	}		

	m_nCurrentItem = -1;
	m_nCurrentSubItem = -1;
	m_pEditWnd = 0;	

	Invalidate();
}

BOOL CReportApprovalFiledsSetupDlg::PreTranslateMessage(MSG* pMsg) 
{
	if(pMsg->message == WM_KEYDOWN)
	{
		if(m_pEditWnd)
		{
			if(pMsg->wParam == VK_RETURN)
			{
				HideEditBox();
				m_combo.ShowDropDown(FALSE);
				return TRUE;
			}
			else if(pMsg->wParam == VK_ESCAPE)
			{
				HideEditBox(false);		
				m_combo.ShowDropDown(FALSE);
				return TRUE;
			}
		}
	}

	return CaplResizableDialog::PreTranslateMessage(pMsg);
}

void CReportApprovalFiledsSetupDlg::OnNMClickList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);

	HideEditBox();

	*pResult = 0;
}

bool CReportApprovalFiledsSetupDlg::FillComboWithRoles(CString str)
{
	CString strAll =  APL_T("Любая роль");
	for(int i=0; i<m_saRoles.GetSize(); i++)
	{
		m_combo.InsertString(i, m_saRoles[i]);
		if(!str.IsEmpty() && str.Find(m_saRoles[i]) > -1) m_combo.SetCheck(i, true);
	}

	m_combo.InsertString(0, strAll);
	m_combo.InsertString(1, m_sEmptyString);
	m_combo.SetAllCategoriesString(strAll);
	if(str.IsEmpty() || str == strAll) m_combo.SelectAllCategoriesByFirstString();

	return true;
}

bool CReportApprovalFiledsSetupDlg::FillComboWithStatuses(CString str)
{
	CString strAll =  APL_T("Любой статус");
	for(int i=0; i<m_saStatuses.GetSize(); i++)
	{
		m_combo.InsertString(i, m_saStatuses[i]);
		if(!str.IsEmpty() && str.Find(m_saStatuses[i]) > -1) m_combo.SetCheck(i, true);
	}

	m_combo.InsertString(0, strAll);
	m_combo.InsertString(1, m_sEmptyString);
	m_combo.SetAllCategoriesString(strAll);
	if(str.IsEmpty() || str == strAll) m_combo.SelectAllCategoriesByFirstString();

	return true;
}
void CReportApprovalFiledsSetupDlg::OnNMSetfocusList(NMHDR *pNMHDR, LRESULT *pResult)
{
	if(!m_bDoNotProccessed) HideEditBox();
	*pResult = 0;
}

void CReportApprovalFiledsSetupDlg::OnBnClickedOk()
{
	UpdateData();

	HideEditBox();
	CreateOption();

	CWinApp *app=AfxGetApp(); // При вызове из ActiveX возвращает 0
	if(0!=app)
	{
		app->WriteProfileInt(_T("APLREP_Settings"), _T("OpenWithoutApproval"), m_nOpenWithoutApproval);
		app->WriteProfileInt(_T("APLREP_Settings"), _T("OpenWithoutDates"), m_nOpenWithoutDates);
		app->WriteProfileInt(_T("APLREP_Settings"), _T("OpenWithoutSign"), m_nOpenWithoutSign);
	}

	CaplResizableDialog::OnOK();
}

CString CReportApprovalFiledsSetupDlg::GetAbbrvForField( CString field )
{
	for(int i=0; i<m_saAbbr.GetSize(); i+=2)
		if(m_saAbbr[i] == field)
			return m_saAbbr[i+1];

	return _T("");
}
void CReportApprovalFiledsSetupDlg::OnBnClickedClear()
{
	if(MessageBox( APL_T("Вы действительно желаете обнулить настройки?"),  APL_T("Очистка настроек"), MB_ICONWARNING|MB_YESNO|MB_DEFBUTTON2) == IDNO)
		return;

	for(int i=0; i<m_list.GetItemCount(); i++)
	{
		m_list.SetItemText(i, 1, _T(""));
		m_list.SetItemText(i, 2, _T(""));	
	}
}
