// PrjMonitorDlg.cpp : implementation file
//

#include "stdafx.h"
#include "PrjMonitorDlg.h"
#include "ShowGanttDlg.h"

CFilterStruct CPrjMonitorDlg::m_filter;


bool bCPrjMonitorDlgIsTupolev=false;

// CPrjMonitorDlg dialog

IMPLEMENT_DYNAMIC(CPrjMonitorDlg, CaplResizableDialog)

CPrjMonitorDlg::CPrjMonitorDlg(CWnd* pParent /*=NULL*/)
	: CaplResizableDialog(CPrjMonitorDlg::IDD, pParent)
{
	m_api=0;
	m_prj_mgr=0;
	m_list=0;
	m_bShowPrognoz=false;
}

CPrjMonitorDlg::~CPrjMonitorDlg()
{
	int i;
	for(i=0;i<m_prev_extents.GetSize();i++)
	{
		aplExtent *pExt=m_prev_extents[i];
		delete pExt;
	}
}

void CPrjMonitorDlg::DoDataExchange(CDataExchange* pDX)
{
	CaplResizableDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDCANCEL, m_cancel_btn);
	DDX_Control(pDX, ID_SAVE2FILE, m_save2file_btn);
	DDX_Control(pDX, ID_SHOW_GANT, m_show_gant_btn);
	DDX_Control(pDX, ID_FIND, m_find_btn);
	DDX_Control(pDX, ID_PRJ_PROPERTIES, m_prj_prop_btn);
	DDX_Control(pDX, ID_SHOW_SUB_PRJ, m_show_subprj);
	DDX_Control(pDX, ID_BACK, m_backBtn);
	DDX_Control(pDX, ID_REFRESH, m_refresj_btn);
	DDX_Control(pDX, ID_PRJ_NOTES, m_prj_notes_btn);
	DDX_Control(pDX, ID_SHOW_COLOR_LEGEND, m_show_color_legend_btn);
	DDX_Control(pDX, IDC_SHOW_PROGNOZ, m_ShowPrognozBtn);
}


BEGIN_MESSAGE_MAP(CPrjMonitorDlg, CaplResizableDialog)
	ON_BN_CLICKED(ID_SAVE2FILE, &CPrjMonitorDlg::OnBnClickedSave2file)
	ON_NOTIFY(HDN_ITEMDBLCLICK, ID_LIST_CTRL, &CPrjMonitorDlg::OnNMDblclkPrjList)
	ON_BN_CLICKED(ID_SHOW_GANT, &CPrjMonitorDlg::OnBnClickedShowGant)
	ON_BN_CLICKED(ID_SHOW_SUB_PRJ, &CPrjMonitorDlg::OnBnClickedShowSubPrj)
	ON_BN_CLICKED(ID_PRJ_PROPERTIES, &CPrjMonitorDlg::OnBnClickedPrjProperties)
	ON_BN_CLICKED(ID_BACK, &CPrjMonitorDlg::OnBnClickedBack)
	ON_BN_CLICKED(ID_REFRESH, &CPrjMonitorDlg::OnBnClickedRefresh)
	ON_BN_CLICKED(ID_FIND, &CPrjMonitorDlg::OnBnClickedFind)
	ON_BN_CLICKED(ID_SHOW_COLOR_LEGEND, &CPrjMonitorDlg::OnBnClickedShowColorLegend)
	ON_BN_CLICKED(ID_PRJ_NOTES, &CPrjMonitorDlg::OnBnClickedPrjNotes)
	ON_BN_CLICKED(IDC_SHOW_PROGNOZ, &CPrjMonitorDlg::OnBnClickedShowPrognoz)
END_MESSAGE_MAP()


// CPrjMonitorDlg message handlers

BOOL CPrjMonitorDlg::OnInitDialog()
{
	if(0==m_prj_mgr || 0==m_api) return FALSE;

	m_filter.m_api=m_api;
	m_filter.m_project_mgr=m_prj_mgr;

	CaplResizableDialog::OnInitDialog();

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

	CWnd *rect_wnd=GetDlgItem(IDC_ST_LIST);
	if(0==rect_wnd) return false;
	
	int i;
	RECT rect;
	rect_wnd->GetWindowRect(&rect);
	ScreenToClient(&rect);

	m_list= CaplSizingListCtrl::CreateListCtrl(this,rect,ID_LIST_CTRL);
	if(0==m_list) return false;

	m_list->SetCursorTextColor(RGB(0,0,0));
	m_list->SetCursorColor(RGB(0,0,255));

	CString sFirstComumnName=APL_T("№ заказа");
	CString strDistrCode;
	m_api->m_options_mgr.GetOptionValueBN( APL_NO_T("Код установки"), strDistrCode, _T(""));
	strDistrCode.MakeLower();
	if(strDistrCode == _T("tupolev")) bCPrjMonitorDlgIsTupolev=true;
	if(bCPrjMonitorDlgIsTupolev)	sFirstComumnName=APL_T("№ п/п в ТК");




	i=m_list->AddColumn(sFirstComumnName,LVCFMT_LEFT,GetOptionWidth(sFirstComumnName,70));
	i=m_list->AddColumn(APL_T("Обозначение"),LVCFMT_LEFT,GetOptionWidth(APL_T("Обозначение"),100));
	i=m_list->AddColumn(APL_T("Наименование"),LVCFMT_LEFT,GetOptionWidth(APL_T("Наименование"),150));
	i=m_list->AddColumn(APL_T("Состояние"),LVCFMT_LEFT,GetOptionWidth(APL_T("Состояние"),70));
	i=m_list->AddColumn(_T("%"),LVCFMT_CENTER,GetOptionWidth(_T("%"),40));
	i=m_list->AddColumn(APL_T("Начало\n(план)"),LVCFMT_CENTER,GetOptionWidth(APL_T("Начало\n(план)"),70));
		m_list->SetHeaderColumnSortType(i, APL_COLUMN_DATE);
	i=m_list->AddColumn(APL_T("Начало\n(факт)"),LVCFMT_CENTER,GetOptionWidth(APL_T("Начало\n(факт)"),70));
		m_list->SetHeaderColumnSortType(i, APL_COLUMN_DATE);
	i=m_list->AddColumn(APL_T("Окончание\n(план)"),LVCFMT_CENTER,GetOptionWidth(APL_T("Окончание\n(план)"),70));
		m_list->SetHeaderColumnSortType(i, APL_COLUMN_DATE);
	i=m_list->AddColumn(APL_T("Окончание\n(прогноз)"),LVCFMT_CENTER,GetOptionWidth(APL_T("Окончание\n(прогноз)"),70));
		m_list->SetHeaderColumnSortType(i, APL_COLUMN_DATE);
	i=m_list->AddColumn(APL_T("Окончание\n(факт)"),LVCFMT_CENTER,GetOptionWidth(APL_T("Окончание\n(факт)"),70));
		m_list->SetHeaderColumnSortType(i, APL_COLUMN_DATE);
	i=m_list->AddColumn(APL_T("Ответственный"),LVCFMT_LEFT,GetOptionWidth(APL_T("Ответственный"),100));
	i=m_list->AddColumn(APL_T("Исполнители"),LVCFMT_LEFT,GetOptionWidth(APL_T("Исполнители"),150));
	i=m_list->AddColumn(APL_T("Соисполнители"),LVCFMT_LEFT,GetOptionWidth(APL_T("Соисполнители"),150));
	i=m_list->AddColumn(APL_T("Заказчик"),LVCFMT_LEFT,GetOptionWidth(APL_T("Заказчик"),100));


	if(bCPrjMonitorDlgIsTupolev) m_list->SetHeaderColumnSortType(0, APL_COLUMN_NUMERIC);

	AddAnchor(IDCANCEL,BOTTOM_RIGHT);
	AddAnchor(ID_SAVE2FILE,BOTTOM_LEFT);
	AddAnchor(ID_SHOW_COLOR_LEGEND,BOTTOM_LEFT);
	AddAnchor(IDC_SHOW_PROGNOZ,BOTTOM_LEFT);
	AddAnchor(ID_SHOW_GANT,BOTTOM_LEFT);
	AddAnchor(ID_FIND,BOTTOM_LEFT);
	AddAnchor(ID_PRJ_PROPERTIES,TOP_RIGHT);
	AddAnchor(ID_PRJ_NOTES,TOP_RIGHT);

	AddAnchor(ID_LIST_CTRL,TOP_LEFT,BOTTOM_RIGHT);

	m_cancel_btn.SetIcon(GetAplStdIco16(APLSTDICO_CANCEL));
	m_cancel_btn.SetFlat(FALSE);
	m_save2file_btn.SetIcon(GetAplTableIco(APL_TABLE_SAVE));
	m_save2file_btn.SetFlat(FALSE);
	m_show_gant_btn.SetIcon(GetAplStdIco16(APLSTDICO_TREE));
	m_show_gant_btn.SetFlat(FALSE);
	m_find_btn.SetIcon(GetAplTableIco(APL_TABLE_FILTER));
	m_find_btn.SetFlat(FALSE);

	m_show_color_legend_btn.SetIcon(IDI_SHOW_COLORS);
	m_show_color_legend_btn.SetFlat(FALSE);

	m_prj_prop_btn.SetIcon(GetAplStdIco16(APLSTDICO_PROPERTIES));
	m_prj_prop_btn.SetFlat(FALSE);

	m_prj_notes_btn.SetIcon(GetAplTableIco(APL_TABLE_NOTE_NOTE));
	m_prj_notes_btn.SetFlat(FALSE);

	m_show_subprj.SetIcon(GetAplStdIco16(APLSTDICO_BOTTOM));
	m_show_subprj.SetFlat(FALSE);
	m_backBtn.SetIcon(GetAplStdIco16(APLSTDICO_LEFT));
	m_backBtn.SetFlat(FALSE);
	m_refresj_btn.SetIcon(GetAplTableIco(APL_TABLE_REFRESH));
	m_refresj_btn.SetFlat(FALSE);


	m_filter.Initialize(m_api,m_prj_mgr);
	UpdateList();

	int icurSortColumn=AfxGetApp()->GetProfileInt(_T("CPrjMonitorDlg"),_T("icurSortColumn"),0);
	BOOL bSortAscending=AfxGetApp()->GetProfileInt(_T("CPrjMonitorDlg"),_T("bSortAscending"),TRUE);

	m_list->SortItems(icurSortColumn,bSortAscending);


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

bool CPrjMonitorDlg::UpdateList()
{
	m_list->DeleteAllItems();
	int i;

	m_map_prj_index.Clear();
	m_array_progn_items.Clear();

	if(m_bShowPrognoz)
	{
		m_prj_mgr->CalcProjectsEndPrognoz(m_ext_projects,m_map_prj_index, m_array_progn_items,true);
	}


	m_list->SetRedraw(FALSE);

	for(i=0;i<m_ext_projects.GetSize();i++)
	{
		CaplInstance *prj=m_ext_projects[i];
		if(prj==0) continue;
		if(prj->GetType()==0) continue;
		if(!m_api->m_data.IsKindOf(prj,m_prj_mgr->e_project)) continue;

		if(!m_filter.FilterProject(prj)) continue;

		int item=m_list->AddItem();
		m_list->SetItemData((int)prj,item);
		UpdateItem(item);
	}
	m_list->SetRedraw(TRUE);
	m_list->RecalcItemsTextRect();
	m_list->ReSort();

	return true;
}

bool CPrjMonitorDlg::UpdateItem(int item)
{
	if(item<0) return false;
	CaplInstance *prj=(CaplInstance *)m_list->GetItemData(item);
	bool bDel=false;
	if(0==prj) bDel=true;
	else if(prj->GetType()==0) bDel=true;

	if(bDel)
	{
		m_list->DeleteItem(item);
		return true;
	}
	if(prj->GetAccessmode()>aplRO)	{ m_list->SetItemText(item,0,APL_T("### нет доступа ###"),FALSE); return true;}

	CString buf,buf1;
	COleDateTime odt;
	double procent;
	CaplInstance *inst;
	aplExtent ext;
	COLORREF color;
	LPCTSTR sDateFormst=_T("%d.%m.%Y");
	int j;

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_number,buf);
	m_list->SetItemText(item,0,buf,FALSE);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_id,buf);
	m_list->SetItemText(item,1,buf,FALSE);
	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_name,buf);
	m_list->SetItemText(item,2,buf,FALSE);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_state,buf);
	m_list->SetItemText(item,3,buf,FALSE);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_persentage,procent);
	if(procent==0) buf=_T("");
	else buf.Format(_T("%.1f"),procent);
	m_list->SetItemText(item,4,buf,FALSE);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_date_planned_begin,buf);
	if(buf!=_T("")){aplString2Date(buf,odt); buf=odt.Format((LPCTSTR)sDateFormst);}
	m_list->SetItemText(item,5,buf,FALSE);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_date_planned_end,buf);
	if(buf!=_T("")){aplString2Date(buf,odt); buf=odt.Format((LPCTSTR)sDateFormst);}
	m_list->SetItemText(item,7,buf,FALSE);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_date_actual_begin,buf);
	if(buf!=_T("")){aplString2Date(buf,odt); buf=odt.Format((LPCTSTR)sDateFormst);}
	m_list->SetItemText(item,6,buf,FALSE);

	COleDateTime end_prognoz_odt;
	if(m_bShowPrognoz)
	{
		int k=m_map_prj_index.GetByIn((long)prj);
		if(k>=0)
		{
			CaplProjectManager::CPrjPrognozItem *prgn_item=m_array_progn_items[k];
			end_prognoz_odt=prgn_item->prognoz_end;
			//item->act_date_end_prognoz=prgn_item->prognoz_end;
			//item->act_date_begin_prognoz=prgn_item->prognoz_begin;
			//item->prev_progn_prj=prgn_item->prev_progn_prj;
			//item->first_progn_sub_prj=prgn_item->first_progn_sub_prj;
			//item->last_progn_sub_prj =prgn_item->last_progn_sub_prj;
		}
	}
	else
	{
		m_prj_mgr->GetWorkedProjectEndPrognoz(prj,end_prognoz_odt);
	}
	buf=_T("");
	if(end_prognoz_odt.GetStatus()==COleDateTime::valid) buf=end_prognoz_odt.Format(sDateFormst);
	m_list->SetItemText(item,8,buf,FALSE);


	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_date_actual_end,buf);
	if(buf!=_T("")){aplString2Date(buf,odt); buf=odt.Format(sDateFormst);}
	m_list->SetItemText(item,9,buf,FALSE);


	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_kurator,inst);
	if(0==inst) buf=_T("");
	else m_api->m_appr_mgr.GetItemName(inst,buf);
	m_list->SetItemText(item,10,buf,FALSE);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_executors,ext);
	buf=_T("");
	for(j=0;j<ext.GetSize();j++)
	{
		if(j>0) buf+=_T(", ");
		m_api->m_appr_mgr.GetItemName(ext[j],buf1);
		buf+=buf1;
	}
	m_list->SetItemText(item,11,buf);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_co_executors,ext);
	buf=_T("");
	for(j=0;j<ext.GetSize();j++)
	{
		if(j>0) buf+=_T(", ");
		m_api->m_appr_mgr.GetItemName(ext[j],buf1);
		buf+=buf1;
	}
	m_list->SetItemText(item,12,buf);

	m_api->m_data.GetAttr(prj,m_prj_mgr->a_project_customer,inst);
	if(0==inst) buf=_T("");
	else m_api->m_appr_mgr.GetItemName(inst,buf);
	m_list->SetItemText(item,13,buf,FALSE);

	m_prj_mgr->GetProjectColor(prj,end_prognoz_odt,color);
	color=aplColor_GetHilightColor(color,75);
	m_list->SetItemColor(color,item);

	return true;
}

void CPrjMonitorDlg::OnNMDblclkPrjList(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;

	if(0==pNMItemActivate) return;
	CaplInstance *prj=(CaplInstance *)m_list->GetItemData(pNMItemActivate->iItem);
	if(0==prj) return;

	aplExtent extSubPrj;
	m_prj_mgr->GetAllSubProject(prj,extSubPrj);
	if(extSubPrj.GetSize()>0)
	{
		//m_prj_mgr->ShowProjectsMonitor(extSubPrj);
		OnBnClickedShowSubPrj();
	}
	else
	{
		if(m_prj_mgr->ShowProjectProperties(prj))
		{
			UpdateItem(pNMItemActivate->iItem);
			m_list->RecalcItemsTextRect(0,pNMItemActivate->iItem);
		}
	}
}

void CPrjMonitorDlg::OnBnClickedSave2file()
{
	m_list->SaveToFile(0);
}

void CPrjMonitorDlg::OnBnClickedShowGant()
{
	// убрано т.к. нельзя передать APL_FILTER_TO_ROOT
	//m_prj_mgr->ShowGanttDlg(m_ext_projects,false);
	
	CShowGanttDlg dlg;
	dlg.m_api=m_api;
	dlg.m_filter.m_filter_type=APL_FILTER_TO_ROOT;
	dlg.m_project_mgr=m_prj_mgr;;
	dlg.m_projects=m_ext_projects;
	dlg.DoModal();
	UpdateList();
}

void CPrjMonitorDlg::OnBnClickedShowSubPrj()
{
	int nItem=m_list->GetFirstSelectedItem();
	if(nItem<0) return;
	CaplInstance *prj=(CaplInstance *)m_list->GetItemData(nItem);
	aplExtent extSubPrj;
	m_prj_mgr->GetAllSubProject(prj,extSubPrj);
	if(extSubPrj.GetSize()<1) {AfxMessageBox(APL_T("Нет подпроектов!")); return;}
	//m_prj_mgr->ShowProjectsMonitor(extSubPrj);
	m_prj_mgr->LoadExtentInfo(m_ext_projects);
	aplExtent *pExt=new aplExtent;
	pExt->Append(m_ext_projects);
	m_prev_extents.Add(pExt);
	m_ext_projects.Clear();
	m_ext_projects.Append(extSubPrj);
	UpdateList();
	
}

void CPrjMonitorDlg::OnBnClickedPrjProperties()
{
	int nItem=m_list->GetFirstSelectedItem();
	if(nItem<0) {AfxMessageBox(APL_T("Проект не выбран!")); return;}
	CaplInstance *prj=(CaplInstance *)m_list->GetItemData(nItem);
	if(m_prj_mgr->ShowProjectProperties(prj))
	{
		UpdateItem(nItem);
		m_list->RecalcItemsTextRect(0,nItem);
	}
}

void CPrjMonitorDlg::OnBnClickedPrjNotes()
{
	int nItem=m_list->GetFirstSelectedItem();
	if(nItem<0) {AfxMessageBox(APL_T("Проект не выбран!")); return;}
	CaplInstance *prj=(CaplInstance *)m_list->GetItemData(nItem);
	if(prj!=0) m_api->m_appr_mgr.ShowNotes(prj,0,false);
}


void CPrjMonitorDlg::OnBnClickedBack()
{
	int i=m_prev_extents.GetSize()-1;
	if(i<0) return;
	aplExtent *pExt=m_prev_extents[i];
	m_ext_projects.Clear();
	m_ext_projects.Append(*pExt);
	delete pExt;
	m_prev_extents.RemoveAt(i);
	UpdateList();
}

void CPrjMonitorDlg::OnBnClickedRefresh()
{
	m_prj_mgr->LoadExtentInfo(m_ext_projects);
	UpdateList();
}

void CPrjMonitorDlg::OnBnClickedFind()
{
	CFilterDlg dlg;
	dlg.bMonitorMode=true;
	dlg.m_filter=&m_filter;
	dlg.m_api=m_api;
	dlg.m_project_mgr=m_prj_mgr;
	if(dlg.DoModal()==IDOK)
	{
		UpdateList();
	}
}


void CPrjMonitorDlg::OnBnClickedShowColorLegend() {CaplProjectManager::ShowColorLegend();}



void CPrjMonitorDlg::OnBnClickedShowPrognoz()
{
	BOOL bShow=m_ShowPrognozBtn.GetCheck();

	if(bShow) m_bShowPrognoz=true; else m_bShowPrognoz=false;

	UpdateList();
}

BOOL CPrjMonitorDlg::DestroyWindow()
{
	// Сохранение сорnировки
	int icurSortColumn=m_list->GetCurSortColumn();
	BOOL bSortAscending=m_list->GetCurSortAscending();

	AfxGetApp()->WriteProfileInt(_T("CPrjMonitorDlg"),_T("icurSortColumn"),icurSortColumn);
	AfxGetApp()->WriteProfileInt(_T("CPrjMonitorDlg"),_T("bSortAscending"),bSortAscending);

	// Сохранение ширины
	CaplListHeaderCtrl *header=m_list->GetHeader();
	if(0!=header)
	{
		int i;
		CString buf,name;
		for(i=0;i<header->m_headerItems.GetSize();i++)
		{
			if(header->m_headerItems[i].m_rowText.GetSize()>0)
			{
				buf=_T("width_"); 
				buf+=header->m_headerItems[i].m_rowText[0];
				AfxGetApp()->WriteProfileInt(_T("CPrjMonitorDlg"),buf,header->m_headerItems[i].m_nWidth);
			}
		}
	}

	return CaplResizableDialog::DestroyWindow();
}

int CPrjMonitorDlg::GetOptionWidth(LPCTSTR sOption, int default_width)
{
	if(0==sOption) return default_width;
	CString buf=_T("width_"); 
	buf+=sOption;
	int width=AfxGetApp()->GetProfileInt(_T("CPrjMonitorDlg"),buf,default_width);
	if(width<15)return default_width;
	return width;
}
