using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;

using BeWo.Controls;
using BeWo.Core;
using BeWo.Core.Service;
using BeWo.ServiceProxy;
using BeWo.ViewModel;

using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.ClientPartials;
using BS.Shared.DataContracts.Compact;
using BS.Shared.Extensions;

using Microsoft.Win32;

namespace BeWo.View.Report.FLSReport
{
    public partial class FLSReportView : BeWoView
    {
        private FLSOverview _FLSOverview;

        private bool _GoalsChanged;

        private DateTime _LastEndDate;

        internal CompactCustomerDC _LastSelectedCustomer;

        internal CompactEmployeeDC _LastSelectedEmployee;

        private DateTime _LastStartDate;

        internal CompactCustomerDC _SelectedCustomer;

        internal CompactEmployeeDC _SelectedEmployee;

        // private bool _FLSReportCreated = false;

        public FLSReportView()
        {
	        InitializeComponent();

	        var startDate                         = DateTime.Now.AddMonths(-1);
	        datePickerStartDate.DateTime          = new DateTime(startDate.Year, startDate.Month, 1);
	        datePickerEndDate.DateTime            = DateTime.Now;
	        checkbox_showChart.IsChecked          = false;
	        checkbox_showServiceRecords.IsChecked = false;
	        checkbox_sortBySubGroup.IsChecked     = true;
	        checkbox_showMarker.IsChecked         = false;

	        _SelectedEmployee = BeWoApp.LoggedOnUser.Employee;
	        if (_SelectedEmployee != null)
	        {
		        popupedit_employee.Text = _SelectedEmployee.ToString();
	        }

	        if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_EmployeeOverviewAll_View))
	        {
		        popupedit_employee.IsEnabled = false;
		        checkbox_all.IsEnabled       = false;
	        }

	        if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AllowFLSOverviewForCostbearer))
	        {
		        radioCostbearerReport.IsEnabled = false;
	        }

	        var teamEnabled = false;
	        if (BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AllowFLSOverviewForAllTeams))
	        {
		        teamEnabled = true;
	        }
	        else if (BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AllowFLSOverviewForTeam) && BeWoApp.LoggedOnUser.Employee.IsTeamLeader)
	        {
		        teamEnabled = true;
	        }

	        if (!BeWoApp.AppSettings.ShowMarker)
	        {
		        checkbox_showMarker.Visibility = Visibility.Collapsed;
	        }
	        radioTeamReport.IsEnabled = teamEnabled;

	        checkbox_all_client.IsChecked = true;
	        InitServiceCategoryTree();
	        InitAllGoals();
	        DownloadLinkEngine = new DownloadLinkEngine();
	        linkExcelExport.NavigateUri = DownloadLinkEngine.GenerateNewExcelLink();

	        ComboBoxTreeViewControl.Imitationheader.Width   = 300;
	        ComboBoxTreeViewControlV2.Imitationheader.Width = 300;
        }

        public DownloadLinkEngine DownloadLinkEngine { get; set; }

        private void ChangeReportType()
        {
            if (reportContent != null)
            {
                reportContent.Children.Clear();
                _FLSOverview = null;

				var key     = "EmployeeContentBrush";
				var enabled = true;

				if (radioClientReport.IsChecked != null && radioClientReport.IsChecked.Value)
                {
                    key = "CustomerContentBrush";

                    checkbox_sortBySubGroup.Content = "Nach Mitarbeiter sortieren";
                }
				else if (radioCostbearerReport.IsChecked != null && radioCostbearerReport.IsChecked.Value)
                {
                    key = "OrganisationContentBrush";
                    enabled = false;

                    checkbox_sortBySubGroup.Content = "Nach Kostenträger sortieren";
                }
				else if (radioTeamReport.IsChecked != null && radioTeamReport.IsChecked.Value)
                {
                    key = "TeamContentBrush";
                    enabled = false;

                    checkbox_sortBySubGroup.Content = "Nach Team sortieren";
                }
                else
                {
                    checkbox_sortBySubGroup.Content = "Nach Klienten sortieren";
                }

                if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_EmployeeOverviewAll_View))
                {
                    popupedit_employee.IsEnabled = false;
                    checkbox_all.IsEnabled       = false;
                }
                else
                {
                    popupedit_employee.IsEnabled = enabled;
                    checkbox_all.IsEnabled       = enabled;
                }

                checkbox_all_client.IsEnabled = enabled;
                popupedit_client.IsEnabled    = enabled;
                lblClient.IsEnabled           = enabled;
                lblEmployee.IsEnabled         = enabled;

                var brush = Application.Current.FindResource(key) as Brush;

                if (brush != null)
                {
                    reportContent.Background = brush;
                }
            }
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (popupedit_employee != null)
            {
                popupedit_employee.Text = string.Empty;
                _SelectedEmployee       = null;
            }
        }

        private void CheckBox_Customer_Checked(object sender, RoutedEventArgs e)
        {
            if (popupedit_client != null)
            {
                popupedit_client.Text = string.Empty;
                _SelectedCustomer     = null;
                UpdateGoalTree();
            }
        }

        private FLSAnalysisDataReportDC CreateDataReportDC()
        {
	        var reportDC = new FLSAnalysisDataReportDC {Groups = new List<FLSAnalysisDataGroupDC>(), DateHeaders = new List<string>()};

	        if (_FLSOverview != null && _FLSOverview.FLSOverviewRows != null)
            {
                reportDC.ReportStartDate = _FLSOverview.FLSOverviewConfig.StartDate;
                reportDC.ReportEndDate = _FLSOverview.FLSOverviewConfig.EndDate;

                switch (_FLSOverview.FLSOverviewConfig.ReportType)
                {
	                case FLSReportType.Employee:
		                reportDC.ReportType = 0;
		                break;
	                case FLSReportType.Customer:
		                reportDC.ReportType = 1;
		                break;
	                case FLSReportType.Costbearer:
		                reportDC.ReportType = 2;
		                break;
	                case FLSReportType.Team:
		                reportDC.ReportType = 3;
		                break;
                }

                reportDC.ShowServiceRecordDetails = _FLSOverview.FLSOverviewConfig.ShowServiceRecords;
                reportDC.ShowGroups = !_FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows;

                var rows = _FLSOverview.FLSOverviewRows;

                foreach (var row in rows)
                {
                    var groupDC = new FLSAnalysisDataGroupDC {Details = new List<FLSAnalysisDataDetailDC>()};

	                if (_FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Employee)
                    {
                        groupDC.Name = row.FLSAnalysisRootDC.Employee.ToString();
                        groupDC.Oid = row.FLSAnalysisRootDC.Employee.EmployeeOid;
                    }
                    else if (_FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Customer)
                    {
                        groupDC.Name = row.FLSAnalysisRootDC.Customer.ToString();
                        groupDC.Oid = row.FLSAnalysisRootDC.Customer.CustomerOid;
                    }

                    reportDC.Groups.Add(groupDC);

                    foreach (var detailRow in row.DetailRows)
                    {
                        if (!_FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                        {
                            if (detailRow.DetailRowType == DetailRowTypes.Header && reportDC.DateHeaders.Count == 0)
                            {
                                foreach (var dateValue in detailRow.DateValues)
                                {
                                    reportDC.DateHeaders.Add(dateValue.DateValueText);
                                }

                                reportDC.DateHeaders.Add(detailRow.RowTotalFLS);
                            }
                            else
                            {
                                if (detailRow.DetailRowType == DetailRowTypes.Detail)
                                {
                                    var detailDC = new FLSAnalysisDataDetailDC {ServiceRecords = new List<ServiceRecordFLSOverviewDC>(), Values = new List<string>()};
	                                groupDC.Details.Add(detailDC);

                                    detailDC.RowType = detailRow.DetailRowType == DetailRowTypes.Detail ? 0 : 1;

                                    detailDC.Name = detailRow.GroupName;

                                    foreach (var dateValue in detailRow.DateValues)
                                    {
                                        detailDC.Values.Add(dateValue.DateValueText);

                                        if (dateValue.ServiceRecordList != null)
                                        {
                                            foreach (var sr in dateValue.ServiceRecordList)
                                            {
                                                detailDC.ServiceRecords.Add(sr);
                                            }
                                        }
                                    }

                                    detailDC.Values.Add(detailRow.RowTotalFLS);
                                }
                                else if (detailRow.DetailRowType == DetailRowTypes.Total)
                                {
                                    groupDC.TotalFLM = detailRow.TotalFLM;
                                }
                            }
                        }
                        else
                        {
                            if (detailRow.DetailRowType == DetailRowTypes.Detail)
                            {
                                var detailDC = new FLSAnalysisDataDetailDC {ServiceRecords = new List<ServiceRecordFLSOverviewDC>(), Values = new List<string>()};
	                            groupDC.Details.Add(detailDC);

                                foreach (var item in detailRow.DateValues)
                                {
                                    detailDC.Name = detailRow.GroupName;

                                    detailDC.Values.Add(item.HeaderLongValue);
                                    detailDC.Values.Add(item.DateValueText);

                                    if (item.ServiceRecordList != null)
                                    {
                                        foreach (var sr in item.ServiceRecordList)
                                        {
                                            detailDC.ServiceRecords.Add(sr);
                                        }
                                    }
                                }
                            }
                            else if (detailRow.DetailRowType == DetailRowTypes.Total)
                            {
                                groupDC.TotalFLM = detailRow.TotalFLM;
                            }
                        }
                    }
                }
            }

            return reportDC;
        }

        private FLSOverviewConfig CreateFLSOverviewConfig()
        {
            var config = new FLSOverviewConfig();

	        if (radioEmployeeReport.IsChecked != null && radioEmployeeReport.IsChecked.Value)
	        {
		        config.ReportType = FLSReportType.Employee;
	        }
	        else if (radioCostbearerReport.IsChecked != null && radioCostbearerReport.IsChecked.Value)
	        {
		        config.ReportType = FLSReportType.Costbearer;
	        }
	        else if (radioTeamReport.IsChecked != null && radioTeamReport.IsChecked.Value)
		        config.ReportType = FLSReportType.Team;
	        else
	        {
		        config.ReportType = FLSReportType.Customer;
	        }

	        config.Employee           = _SelectedEmployee;
	        config.Customer           = _SelectedCustomer;
	        config.StartDate          = datePickerStartDate.DateTime.Date;
	        config.EndDate            = datePickerEndDate.DateTime.Date.AddDays(1).AddSeconds(-1);
	        config.ShowChart          = checkbox_showChart.IsChecked.Value;
	        config.ShowServiceRecords = checkbox_showServiceRecords.IsChecked.Value;
	        config.ShowOnlyTotalRows  = !checkbox_sortBySubGroup.IsChecked.Value;
	        config.ShowOnlyMarker     = checkbox_showMarker.IsChecked.Value;

	        if (radioButtonIntervalDay.IsChecked.Value)
	        {
		        config.DateInterval = DateInterval.Day;
	        }
	        else if (radioButtonIntervalWeek.IsChecked.Value)
	        {
		        config.DateInterval = DateInterval.Week;
	        }
	        else if (radioButtonIntervalMonth.IsChecked.Value)
	        {
		        config.DateInterval = DateInterval.Month;
	        }
	        else if (radioButtonIntervalQuarter.IsChecked.Value)
	        {
		        config.DateInterval = DateInterval.Quarter;
	        }
	        else if (radioButtonIntervalYear.IsChecked.Value)
	        {
		        config.DateInterval = DateInterval.Year;
	        }

	        var sdList = new List<ServiceDescriptionDC>();

	        var sctree = ComboBoxTreeViewControlV2.TreeViewSourceList;

	        foreach (var sc in sctree)
	        {
		        sdList.AddRange(from sd in sc.Children where sd.IsChecked select sd.ServiceDescription);
	        }
	        //foreach (var item in this.serviceCategoryList.Items)
	        //{
	        //    CheckBox chkBox = (CheckBox)item;
	        //    if (chkBox.IsChecked.Value)
	        //    {
	        //        scList.Add((ServiceCategoryDC)chkBox.Content);
	        //    }
	        //}

	        config.ServiceDesciptions = sdList;
	        //this.treeview_Goals.Visibility == Visibility.Visible || 
	        if (ComboBoxTreeViewControl.Visibility == Visibility.Visible)
	        {
		        config.GoalOids = GetSelectedGoalOids();
	        }

	        return config;
        }

		private List<long> GetSelectedGoalOids()
		{
			List<long> goals = new List<long>();

			AddCheckedGoals(ComboBoxTreeViewControl.TreeViewSourceList, goals);


			return goals;
		}

		private void AddCheckedGoals(List<SupportConceptGoalDC> goals, List<long> selectedGoals)
		{
			foreach (var item in goals)
			{
				if (item.Children == null || item.Children.Count == 0)
				{
					if (item.IsChecked)
					{
						selectedGoals.Add(item.GoalEntryDC.ValueListEntryOid.Value);
					}
				}
				else
				{
					AddCheckedGoals(item.Children, selectedGoals);
				}


			}
		}

        private void CreateReportView(List<FLSAnalysisRootDC> list, FLSOverviewConfig config)
        {
            _FLSOverview = new FLSOverview(list, config);
            reportContent.Children.Clear();
            reportContent.Children.Add(_FLSOverview);
        }

        private void CustomerSearchView_CustomerSelected(object sender, EventArgs<CompactCustomerDC> e)
        {
            _SelectedCustomer = e.Data;
            popupedit_client.Text = _SelectedCustomer.ToString();
            popup_customer.IsOpen = false;

            UpdateGoalTree();
        }

        private void EmployeeSearchView_CustomerSelected(object sender, EventArgs<CompactEmployeeDC> e)
        {
            _SelectedEmployee = e.Data;
            popupedit_employee.Text = _SelectedEmployee.ToString();
            popup_employee.IsOpen = false;
        }

		private void FillGoalTree(List<ValueListEntryDC> goalCategories, List<ValueListEntryDC> indGoalCategories, List<ValueListEntryDC> goals, bool removeEmptyGoalCategories)
        {
			
			var tree = GoalService.GetGoalTree(goalCategories, indGoalCategories, goals, removeEmptyGoalCategories);
            if (tree.Count == 0)
            {
                lblGoals.Visibility = Visibility.Collapsed;
                ComboBoxTreeViewControl.Visibility = Visibility.Collapsed;
            }
            else
            {
				lblGoals.Visibility = Visibility.Visible;
				ComboBoxTreeViewControl.Visibility = Visibility.Visible;
                foreach (var goal in tree.SelectMany(goalCat => goalCat.Children))
	                goal.PropertyChanged += childItem_PropertyChanged;

                ComboBoxTreeViewControl.TreeViewSourceList = tree;
            }
        }

        private void InitAllGoals()
        {
			Cache.GetInstance().GetAllValueListEntrysByTypeAsync(ValueListEntryType.SupportConceptGoalCategoryType,
				r1 => Cache.GetInstance().GetAllValueListEntrysByTypeAsync(ValueListEntryType.SupportConceptGoalType, 
                    r2 => Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => FillGoalTree(r1, null, r2, false)))));
        }

        private void InitGoalsForSelectedCustomer()
        {
			Cache.GetInstance().GetAllValueListEntrysByTypeAsync(ValueListEntryType.SupportConceptGoalCategoryType,
                cats =>
					Cache.GetInstance().GetAllValueListEntrysByTypeAsync(ValueListEntryType.SupportConceptIndividualGoalCategoryType,
						icats =>
							ServiceFacade.DoCustomerServiceAsync(
								s => s.GetAllCustomerGoals(_SelectedCustomer.CustomerOid),
									goals => Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => FillGoalTree(cats, icats, goals, true))))));
        }

        //private void InitServiceCategoryList()
        //{
        //    List<ServiceCategoryDC> categories = ServiceFacade.DoOperationsServiceSync(s => s.GetAllServiceCategories());

        //    foreach (ServiceCategoryDC dc in categories)
        //    {
        //        CheckBox chkBox = new CheckBox();
        //        chkBox.IsChecked = true;
        //        chkBox.Content = dc;
        //        this.serviceCategoryList.Items.Add(chkBox);
        //    }
        //}

        private void InitServiceCategoryTree()
        {
            Cache.GetInstance().GetServiceCategoryDescriptionDict(cb => 
                this.Dispatch(
                    delegate
                        {
                            ComboBoxTreeViewControlV2.ParentWindowHeight = ActualHeight;
                            ComboBoxTreeViewControl.ParentWindowHeight = ActualHeight;
                            InitServiceCategoryTree(cb);
                        }));
            
        }

        private void InitServiceCategoryTree(Dictionary<ServiceCategoryDC, List<ServiceDescriptionDC>> dict)
        {
            var categories = dict.Keys;
			var tree       = new List<ServiceCategoryTreeItem>();

            foreach (var dc in categories)
            {
                var catItem = new ServiceCategoryTreeItem {ServiceCategory = dc, IsChecked = false};
                foreach (var item in dict[dc])
                {
                    var descItem = new ServiceCategoryTreeItem
                        {
                            ServiceDescription = item,
                            IsChecked = false
                        };
                    catItem.Children.Add(descItem);
                }
                tree.Add(catItem);
            }
            ComboBoxTreeViewControlV2.TreeViewSourceList = tree;
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            ChangeReportType();
        }

        private void UpdatePDFExportUri(string id)
        {
			var url = String.Format("{0}/ReportView.aspx?dcid={1}eoid{2}&type={3}", BeWoApp.SiteOfOrigin, BeWoApp.Tenant, BeWoApp.LoggedOnUser.Employee.EmployeeOid, Utils.EnumName(ReportTypes.FLSReport));

            url = BeWoWpfUtils.GetHTMLEncodedURL(url);
            linkPdfExport.NavigateUri = new Uri(url);

            linkPdfExport.TargetName = Guid.NewGuid().ToString();

            // linkPdfExport2.NavigateUri = new Uri(url);

            // _FLSReportCreated = false;
        }

        private void button_generate_Click(object sender, RoutedEventArgs e)
        {
			_GoalsChanged = false;

            var config = CreateFLSOverviewConfig();

            var configDc = new FLSAnalysisConfigDC();

			if (_SelectedCustomer != null)
            {
                configDc.CustomerOid = _SelectedCustomer.CustomerOid;
            }

            if (_SelectedEmployee != null)
            {
                configDc.EmployeeOid = _SelectedEmployee.EmployeeOid;
            }

	        if (checkbox_archivierte_mitarbeiter.IsChecked != null && checkbox_archivierte_mitarbeiter.IsVisible) 
				configDc.ShouldAnalyzeArchivedEmployees = checkbox_archivierte_mitarbeiter.IsChecked.Value;

	        configDc.ReportType = config.ReportType;
			configDc.StartDate = config.StartDate;
			configDc.EndDate = config.EndDate;
			configDc.GoalOids = config.GoalOids;
	        configDc.ShowOnlyMarker = config.ShowOnlyMarker;
	        if (config.ServiceDesciptions != null)
	        {
		        configDc.ServiceDescriptionOids = config.ServiceDesciptions.Select(sd => sd.ServiceDescriptionOid != null ? sd.ServiceDescriptionOid.Value : 0).ToList();
	        }
	        if (config.ReportType == FLSReportType.Team)
            {
                List<long> teamoids = null;
                if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AllowFLSOverviewForAllTeams) && BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AllowFLSOverviewForTeam) && BeWoApp.LoggedOnUser.Employee.IsTeamLeader)
                {
                    teamoids = BeWoApp.LoggedOnUser.Employee.LeadingTeamOids;
                }
				configDc.TeamOids = teamoids;
            }

			ServiceFacade.DoAnalysisServiceAsync(s => s.GetFLSAnalysis(configDc), r => this.Dispatch(() => CreateReportView(r, config)));

			//if (config.ReportType == FLSReportType.Employee)
			//{
			//	if (employeeOid != null)
			//	{
			//		ServiceFacade.DoAnalysisServiceAsync(s => s.GetEmployeeFLSAnalysisForEmployee(employeeOid.Value, config.StartDate, config.EndDate, true, true, customerOid, config.GoalOids), r => { this.Dispatch(delegate { this.CreateReportView(r, config); }); });
			//	}
			//	else
			//	{
			//		ServiceFacade.DoAnalysisServiceAsync(s => s.GetEmployeeFLSAnalysis(config.StartDate, config.EndDate, true, true, customerOid, config.GoalOids, null, null, null, null, null),
			//			r =>
			//			{
			//				this.Dispatch(delegate
			//				{
			//					CreateReportView(r, config);
			//				});
			//			});
			//	}
			//}
			//else if (config.ReportType == FLSReportType.Customer)
			//{
			//	if (customerOid != null)
			//	{
			//		ServiceFacade.DoAnalysisServiceAsync(s => s.GetCustomerFLSAnalysisForCustomer(customerOid.Value, config.StartDate, config.EndDate, true, true, employeeOid, config.GoalOids), r => { this.Dispatch(delegate { this.CreateReportView(r, config); }); });
			//	}
			//	else
			//	{
			//		ServiceFacade.DoAnalysisServiceAsync(s => s.GetCustomerFLSAnalysis(config.StartDate, config.EndDate, true, true, employeeOid, config.GoalOids), r => { this.Dispatch(delegate { this.CreateReportView(r, config); }); });
			//	}
			//}
			//else if (config.ReportType == FLSReportType.Costbearer)
			//{
			//	ServiceFacade.DoAnalysisServiceAsync(s => s.GetCostBearerFLSAnalysis(config.StartDate, config.EndDate, true, config.GoalOids), r => { this.Dispatch(delegate { this.CreateReportView(r, config); }); });
			//}
			//else if (config.ReportType == FLSReportType.Team)
			//{
			//	List<long> teamoids = null;
			//	if (!BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AllowFLSOverviewForAllTeams) && BeWoApp.LoggedOnUser.HasRight(UserRightType.Analysis_AllowFLSOverviewForTeam) && BeWoApp.LoggedOnUser.Employee.IsTeamLeader)
			//	{
			//		teamoids = BeWoApp.LoggedOnUser.Employee.LeadingTeamOids;
			//	}

			//	ServiceFacade.DoAnalysisServiceAsync(s => s.GetTeamFLSAnalysis(config.StartDate, config.EndDate, true, config.GoalOids, teamoids),
			//			r =>
			//			{
			//				this.Dispatch(delegate
			//				{
			//					CreateReportView(r, config);
			//				});
			//			});
			//}
        
            _LastSelectedEmployee = _SelectedEmployee;
            _LastSelectedCustomer = _SelectedCustomer;
            _LastStartDate = config.StartDate;
            _LastEndDate = config.EndDate;

            UpdatePDFExportUri(string.Empty);

            if (!config.ShowServiceRecords && config.ShowOnlyTotalRows)
            {
                textblock_link_pdfexport.Visibility = Visibility.Hidden;
            }
            else
            {
                textblock_link_pdfexport.Visibility = Visibility.Visible;
            }
        }

        private void childItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            SupportConceptGoalDC selectedGoal = sender as SupportConceptGoalDC;
            if (selectedGoal != null)
            {
                this._GoalsChanged = true;
            }
        }

        private void linkExcelExport_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            if (this._FLSOverview != null && this._FLSOverview.FLSOverviewRows != null)
            {
                List<FLSOverviewRow> rows = this._FLSOverview.FLSOverviewRows;

                List<string> lHeaderCaptions = new List<string>();
                List<List<string>> lContent = new List<List<string>>();

                if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Employee)
                {
                    lHeaderCaptions.Add("Mitarbeiter/in");
                    if (!this._FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows || !this._FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                    {
                        lHeaderCaptions.Add("Klient/in");
                    }
                }
                else if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Customer)
                {
                    lHeaderCaptions.Add("Klient/in");
                    if (!this._FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows || !this._FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                    {
                        lHeaderCaptions.Add("Mitarbeiter/in");
                    }
                }
                else if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Costbearer)
                {
                    // lHeaderCaptions.Add("");
                    if (!this._FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows || !this._FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                    {
                        lHeaderCaptions.Add("Kostenträger");
                    }
                }
                else if (_FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Team)
                {
                    //lHeaderCaptions.Add("");
                    if (!_FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows || !_FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                        lHeaderCaptions.Add("Team");
                }

                if (this._FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                {
                    lHeaderCaptions.Add("Zeitraum");
                    lHeaderCaptions.Add("Summe Stunden");
                    lHeaderCaptions.Add("Datum");
                    lHeaderCaptions.Add("Startzeit");
                    lHeaderCaptions.Add("Endzeit");
                    lHeaderCaptions.Add("Minuten");
                    if (this._FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows && this._FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                    {
                        if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Employee)
                        {
                            lHeaderCaptions.Add("Klient/in");
                        }
                        else if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Customer)
                        {
                            lHeaderCaptions.Add("Mitarbeiter/in");
                        }
                        else if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Costbearer)
                        {
                            lHeaderCaptions.Add("Kostenträger");
                        }
                        else if (_FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Team)
                            lHeaderCaptions.Add("Team");
                    }

					lHeaderCaptions.Add("Leistung");
                    lHeaderCaptions.Add("Dokumentation");
                }

                foreach (FLSOverviewRow row in rows)
                {
                    bool addRoot = true;

                    foreach (FLSOverviewDetailRow detailRow in row.DetailRows)
                    {
                        if (!this._FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                        {
                            if (detailRow.DetailRowType == DetailRowTypes.Header && lHeaderCaptions.Count <= 2)
                            {
                                foreach (FLSOverviewDateValue dateValue in detailRow.DateValues)
                                {
                                    lHeaderCaptions.Add(dateValue.DateValueText);
                                }

                                lHeaderCaptions.Add(detailRow.RowTotalFLS);
                            }

                            if (detailRow.DetailRowType != DetailRowTypes.Header)
                            {
                                List<string> content = new List<string>();
                                if (addRoot)
                                {
                                    if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Employee)
                                    {
                                        content.Add(row.FLSAnalysisRootDC.Employee.ToString());
                                    }
                                    else if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Customer)
                                    {
                                        content.Add(row.FLSAnalysisRootDC.Customer.ToString());
                                    }
                                }
                                else if (_FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Costbearer && _FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Team)
                                {
                                    content.Add(string.Empty);
                                }

                                addRoot = false;

                                content.Add(detailRow.GroupName);

                                foreach (FLSOverviewDateValue dateValue in detailRow.DateValues)
                                {
                                    content.Add(dateValue.DateValueText);
                                }

                                content.Add(detailRow.RowTotalFLS);
                                lContent.Add(content);
                            }
                        }
                        else
                        {
                            // ------------------------------------------------------------------------

                            if (detailRow.DetailRowType == DetailRowTypes.Detail)
                            {
                                bool addGroupName = true;

                                foreach (var item in detailRow.DateValues)
                                {
                                    List<string> content = new List<string>();

                                    if (addRoot)
                                    {
                                        if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Employee)
                                        {
                                            content.Add(row.FLSAnalysisRootDC.Employee.ToString());
                                        }
                                        else if (this._FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Customer)
                                        {
                                            content.Add(row.FLSAnalysisRootDC.Customer.ToString());
                                        }
                                        else if (_FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Costbearer || _FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Team)
                                        {
                                            // if (row.FLSAnalysisRootDC.Organisation != null)
                                            // content.Add(row.FLSAnalysisRootDC.Organisation.ToString());
                                            // else
                                            
                                        }
                                    }
                                    else if (_FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Costbearer && _FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Team)
                                    {
                                        content.Add(string.Empty);
                                    }

                                    addRoot = false;

                                    if (!this._FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows)
                                    {
                                        if (addGroupName)
                                        {
                                            content.Add(detailRow.GroupName);
                                        }
                                        else
                                        {
                                            content.Add(string.Empty);
                                        }
                                    }

                                    addGroupName = false;

                                    content.Add(item.HeaderLongValue);
                                    content.Add(item.DateValueText);

                                    if (item.ServiceRecordList != null && item.ServiceRecordList.Count > 0)
                                    {
                                        int count = 0;

                                        foreach (var sr in item.ServiceRecordList)
                                        {
                                            if (count > 0)
                                            {
                                                content = new List<string>();
                                                content.Add(string.Empty);
                                                content.Add(string.Empty);

                                                if (_FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Costbearer && _FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Team)
                                                {
                                                    content.Add(string.Empty);
                                                }

                                                if (!this._FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows)
                                                {
                                                    content.Add(string.Empty);
                                                }
                                            }

                                            content.Add(sr.Start.Value.ToShortDateString());
                                            if (sr.Start != null && sr.Start.Value.Second == 0)
                                            {
                                                content.Add(sr.Start.Value.ToShortTimeString());
                                                content.Add(sr.Start.Value.AddMinutes((double)sr.RoundedDuration).ToShortTimeString());
                                            }
                                            else
                                            {
                                                content.Add(string.Empty);
                                                content.Add(string.Empty);
                                            }

                                            content.Add(String.Format("{0}", (int)sr.RoundedDuration));

                                            if (this._FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows)
                                            {
                                                content.Add(sr.GroupName);
                                            }

											content.Add(sr.ServiceDescription.Name);
                                            content.Add(sr.Notice);
                                            lContent.Add(content);
                                            count++;
                                        }
                                    }
                                    else
                                    {
                                        content.Add(string.Empty);
                                        content.Add(string.Empty);
                                        content.Add(string.Empty);
                                        content.Add(string.Empty);
                                        content.Add(string.Empty);
                                        if (this._FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows)
                                        {
                                            content.Add(string.Empty);
                                        }

                                        lContent.Add(content);
                                    }
                                }
                            }

                            // ------------------------------------------------------------------------
                        }
                    }
                }
				var path = BeWoApp.GetAndCreateUserAppDataPath() + "\\Stundenübersicht.xls";

                var sf = new SaveFileDialog { FileName = Path.GetFileName(path), Filter = "Microsoft Excel 97-2003-Arbeitsblatt|*.xls|Alle Dateien|*.*" };
                if (sf.ShowDialog() != true)
                    return;
                ServiceFacade.DoDownloadServiceSync(s => BeWoUtils.WriteExcelFile(s.PrepareExcelFile(DownloadLinkEngine.ExcelFileId, lHeaderCaptions, lContent), sf.FileName));

                //string navitageUri = ((Hyperlink) sender).NavigateUri.ToString();
                //BeWoUtils.NavigateToReportUri(navitageUri);

                //System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as System.Windows.Documents.Hyperlink).NavigateUri.ToString()));
                // Workaround Hyperlink mit neuem ersetzen, Navigate Uri lässt auf dem alten nicht ändern...
                //this.textblock_link.Inlines.Clear();
                //var lNewLink = new Hyperlink(new Run("Excel Export")) { NavigateUri = DownloadLinkEngine.GenerateNewExcelLink(), Foreground = Brushes.Black, TargetName = "newWindow" };
                //lNewLink.RequestNavigate += this.linkExcelExport_RequestNavigate;
                //this.textblock_link.Inlines.Add(lNewLink);
            }
        }

        private void linkPdfExport_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            // if (!_FLSReportCreated)
            // {
            // e.Handled = true;

            // _FLSReportCreated = true;
            // linkPdfExport2.DoClick();
            FLSAnalysisDataReportDC dc = this.CreateDataReportDC();
            ServiceFacade.DoOperationsServiceSync(s => s.PrepareFLSReport(dc, BeWoApp.Tenant + "eoid" + BeWoApp.LoggedOnUser.Employee.EmployeeOid));

            string navigateUri = BeWoUtils.RemoveAuthenticationInfoFromUri(((Hyperlink) sender).NavigateUri.ToString());
			BeWoUtils.NavigateToReportUri(navigateUri, "Druckvorschau");

            //System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as System.Windows.Documents.Hyperlink).NavigateUri.ToString()));
            // }
            // else
            // {
            // _FLSReportCreated = false;
            // }
        }

        private void popupedit_customer_PopUpClick(object sender, RoutedEventArgs e)
        {
            this.popup_customer.IsOpen = true;
        }

        private void popupedit_employee_PopUpClick(object sender, RoutedEventArgs e)
        {
            this.popup_employee.IsOpen = true;
        }

        private void UpdateGoalTree()
        {
            if (_SelectedCustomer == null)
                InitAllGoals();
            else
            {
                InitGoalsForSelectedCustomer();
            }
        }

        private void Popupedit_employee_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // EmployeeView
            if (_SelectedEmployee == null || !BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit) sender, e) ||
                !BeWoApp.LoggedOnUser.HasRight(UserRightType.EmployeeView_Edit))
                return;

            VMFactory.CreateEmployeeVMAsync(_SelectedEmployee.EmployeeOid,
                    cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<EmployeeVM, EmployeeDC, FLSReportView>(
                                                    cb, this, () => this.Dispatch(() => BeWoUtils.UpdateAllViews(_SelectedEmployee)))));
        }

        private void Popupedit_client_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // CustomerView
            if (_SelectedCustomer == null || !BeWoUtils.CheckPopupEditClickableSpace((PopUpEdit) sender, e) ||
                !BeWoApp.LoggedOnUser.HasRight(UserRightType.CustomerView_Edit))
                return;

            VMFactory.CreateCustomerVMAsync(_SelectedCustomer.CustomerOid,
                    cb => this.Dispatch(() => BeWoUtils.OpenModalViewWindow<CustomerVM, CustomerDC, FLSReportView>(
                                                    cb, this, () => this.Dispatch(() => BeWoUtils.UpdateAllViews(_SelectedCustomer)))));
        }
    }
}