using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using BS.Shared.Core;
using System.Windows.Media;
using BS.Shared.DataContracts.ClientPartials;
using BS.Shared.Extensions;
using BeWo.Core;
using System.Windows.Documents;
using BeWo.Core.Service;
using System.Windows.Threading;
using BS.Shared.DataContracts;
using BeWo.ServiceProxy;
using BS.Shared;
using Microsoft.Win32;


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

        private DateTime _LastStartDate;
        private DateTime _LastEndDate;

        private bool _TextValuesChanged = false;

        private bool _GoalsChanged = false;
        
        public FLSReportView()
        {
            InitializeComponent();

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

            InitServiceCategoryList();
            InitGoals();
            DownloadLinkEngine = new DownloadLinkEngine();
            linkExcelExport.NavigateUri = DownloadLinkEngine.GenerateNewExcelLink();
        }

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

        private void FillGoalTree(List<ValueListEntryDC> goalCategories, List<ValueListEntryDC> goals)
        {

            var tree = GoalService.GetGoalTree(goalCategories, null, goals, true);
            if (tree.Count == 0)
            {
                lblGoals.Visibility = Visibility.Collapsed;
                treeview_Goals.Visibility = Visibility.Collapsed;
            }
            else
            {
                
                foreach (var goalCat in tree)
                {
                    foreach (var goal in goalCat.Children)
                    {
                        goal.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(childItem_PropertyChanged);
                    }
                }



                treeview_Goals.ItemsSource = tree;
                
            }
        }

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

        public DownloadLinkEngine DownloadLinkEngine { get; set; }

        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;
                serviceCategoryList.Items.Add(chkBox);
            }
        }



        private void button_generate_Click(object sender, RoutedEventArgs e)
        {
            FLSOverviewConfig config = CreateFLSOverviewConfig();

            _GoalsChanged = false;
            
            _TextValuesChanged = false;

         
            String text1 = txtText1.Text;
            String text2 = txtText2.Text;
            String text3 = txtText3.Text;
            String text4 = txtText4.Text;
            String text5 = txtText5.Text;

         
            ServiceFacade.DoAnalysisServiceAsync(s => s.GetEmployeeFLSAnalysis(config.StartDate, config.EndDate, true, true, null, config.GoalOids, text1, text2, text3, text4, text5),
                    r =>
                    {
                        this.Dispatch(delegate
                        {
                            CreateReportView(r, config);
                        });
                    });
                
           

            _LastStartDate = config.StartDate;
            _LastEndDate = config.EndDate;

            UpdatePDFExportUri("");

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

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

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

            config.ReportType = FLSReportType.Employee;
            
            config.StartDate = datePickerStartDate.DateTime.Date;
            config.EndDate = datePickerEndDate.DateTime.Date.AddDays(1).AddSeconds(-1);
            config.ShowServiceRecords = checkbox_showServiceRecords.IsChecked.Value;
            config.ShowOnlyTotalRows = !checkbox_sortBySubGroup.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;

            List<ServiceCategoryDC> scList = new List<ServiceCategoryDC>();
            foreach (var item in serviceCategoryList.Items)
            {
                CheckBox chkBox = (CheckBox)item;
                if (chkBox.IsChecked.Value)
                {
                    scList.Add((ServiceCategoryDC)chkBox.Content);
                }
            }
            config.ServiceCategories = scList;

            if (treeview_Goals.Visibility == Visibility.Visible)
            {
                List<long> oids = new List<long>();

                List<SupportConceptGoalDC> goals = treeview_Goals.ItemsSource as List<SupportConceptGoalDC>;

                foreach (var cat in goals)
                {
                    foreach (var goal in cat.Children)
                    {
                        if (goal.IsChecked)
                        {
                            oids.Add(goal.GoalEntryDC.ValueListEntryOid.Value);
                        }
                    }
                }
                config.GoalOids = oids;
            }

            return config;
        }

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

                //_FLSReportCreated = true;
                //linkPdfExport2.DoClick();

                FLSAnalysisDataReportDC dc = CreateDataReportDC();
                ServiceFacade.DoOperationsServiceSync(s => s.PrepareFLSReport(dc, BeWoApp.Tenant + "eoid" + BeWoApp.LoggedOnUser.Employee.EmployeeOid));
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as System.Windows.Documents.Hyperlink).NavigateUri.ToString()));
            //}
            //else
            //{
            //    _FLSReportCreated = false;
            //}
        }

        private void UpdatePDFExportUri(String id)
        {
            String url = BeWoApp.SiteOfOrigin.ToString()
                        + "/ReportView.aspx?dcid="
                        + BeWoApp.Tenant + "eoid" + BeWoApp.LoggedOnUser.Employee.EmployeeOid
                        + "&subtype=Mitarbeiterauswertung"
                        + "&type=" + Utils.EnumName<ReportTypes>(ReportTypes.FLSReport);

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

            linkPdfExport.TargetName = Guid.NewGuid().ToString();
            //linkPdfExport2.NavigateUri = new Uri(url);

            //_FLSReportCreated = false;

            
            
        }

        private FLSAnalysisDataReportDC CreateDataReportDC()
        {
            FLSAnalysisDataReportDC reportDC = new FLSAnalysisDataReportDC();
            reportDC.Groups = new List<FLSAnalysisDataGroupDC>();
            reportDC.DateHeaders = new List<string>();
            
            if (_FLSOverview != null && _FLSOverview.FLSOverviewRows != null)
            {
                reportDC.ReportStartDate = _FLSOverview.FLSOverviewConfig.StartDate;
                reportDC.ReportEndDate = _FLSOverview.FLSOverviewConfig.EndDate;
                
                reportDC.ReportType = 0;
                
                reportDC.ShowServiceRecordDetails = true;
                reportDC.ShowGroups = true;

                List<FLSOverviewRow> rows = _FLSOverview.FLSOverviewRows;

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

                    
                    groupDC.Name = row.FLSAnalysisRootDC.Employee.ToString();
                    groupDC.Oid = row.FLSAnalysisRootDC.Employee.EmployeeOid;
                    groupDC.CustomField1 = txtText1.Text;
                    groupDC.CustomField2 = txtText2.Text;
                    groupDC.CustomField3 = txtText3.Text;
                    groupDC.CustomField4 = txtText4.Text;
                    groupDC.CustomField5 = txtText5.Text;
                    
                    reportDC.Groups.Add(groupDC);

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

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


                                    if (detailRow.DetailRowType == DetailRowTypes.Detail)
                                        detailDC.RowType = 0;
                                    else
                                        detailDC.RowType = 1;


                                    detailDC.Name = detailRow.GroupName;
                                    detailDC.CustomValue1 = detailRow.Text1;
                                    detailDC.CustomValue2 = detailRow.Text2;
                                    detailDC.CustomValue3 = detailRow.Text3;
                                    
                                    foreach (FLSOverviewDateValue 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)
                            {
                                FLSAnalysisDataDetailDC detailDC = new FLSAnalysisDataDetailDC();
                                detailDC.ServiceRecords = new List<ServiceRecordFLSOverviewDC>();
                                detailDC.Values = new List<string>();
                                groupDC.Details.Add(detailDC);

                                foreach (var item in detailRow.DateValues)
                                {
                                    detailDC.Name = detailRow.GroupName;
                                    detailDC.CustomValue1 = detailRow.Text1;
                                    detailDC.CustomValue2 = detailRow.Text2;
                                    detailDC.CustomValue3 = detailRow.Text3;
                                    //detailDC.CustomValue4 = detailRow.Text4;
                                    //detailDC.CustomValue5 = detailRow.Text5;

                                    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;
                            }
                        }
                    }

                }
                if (reportDC.Groups != null)
                {
                    foreach (var item in reportDC.Groups)
                    {
                        reportDC.TotalFLM += item.TotalFLM;
                    }
                }
            }

            return reportDC;
        }
        private void linkExcelExport_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            if (_FLSOverview != null && _FLSOverview.FLSOverviewRows != null)
            {
                List<FLSOverviewRow> rows = _FLSOverview.FLSOverviewRows;

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

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

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

                    foreach (FLSOverviewDetailRow detailRow in row.DetailRows)
                    {
                        if (!_FLSOverview.FLSOverviewConfig.ShowServiceRecords)
                        {
                            if (detailRow.DetailRowType == DetailRowTypes.Header && lHeaderCaptions.Count <= 2)
                            {
                                lHeaderCaptions.Add("Abteilung");
                                lHeaderCaptions.Add("Status");
                                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)
                                    content.Add(row.FLSAnalysisRootDC.Employee.ToString());
                                else
                                    content.Add("");
                                
                                addRoot = false;

                                content.Add(detailRow.GroupName);
                                content.Add(detailRow.Text1);
                                content.Add(detailRow.Text2);
                                
                                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 (_FLSOverview.FLSOverviewConfig.ReportType == FLSReportType.Employee)
                                            content.Add(row.FLSAnalysisRootDC.Employee.ToString());
                                        else if (_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
                                            //    content.Add("test");
                                        }
                                    }
                                    else if (_FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Costbearer && _FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Team)
                                        content.Add("");

                                    addRoot = false;

                                    if (!_FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows)
                                    {
                                        if (addGroupName)
                                        {
                                            content.Add(detailRow.GroupName);
                                        }
                                        else
                                            content.Add("");
                                    }
                                    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("");
                                                content.Add("");

                                                if (_FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Costbearer && _FLSOverview.FLSOverviewConfig.ReportType != FLSReportType.Team)
                                                    content.Add("");
                                                if (!_FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows)
                                                {
                                                    content.Add("");
                                                }
                                            }
                                            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("");
                                                content.Add("");
                                            }
                                            content.Add(String.Format("{0}", (int)sr.RoundedDuration));

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

                                            lContent.Add(content);
                                            count++;
                                        }
                                    }
                                    else
                                    {
                                        content.Add("");
                                        content.Add("");
                                        content.Add("");
                                        content.Add("");
                                        content.Add("");
                                        if (_FLSOverview.FLSOverviewConfig.ShowOnlyTotalRows)
                                        {
                                            content.Add("");
                                        }
                                        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));
                //System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as Hyperlink).NavigateUri.ToString()));
                //Workaround Hyperlink mit neuem ersetzen, Navigate Uri lässt auf dem alten nicht ändern...
                //textblock_link.Inlines.Clear();
                //var lNewLink = new Hyperlink(new Run("Excel Export"))
                //{
                //    NavigateUri = DownloadLinkEngine.GenerateNewExcelLink(),
                //    Foreground = Brushes.Black,
                //    TargetName = "newWindow"
                //};
                //lNewLink.RequestNavigate += linkExcelExport_RequestNavigate;
                //textblock_link.Inlines.Add(lNewLink);
            }
        }

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

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

                String key = "EmployeeContentBrush";


                checkbox_sortBySubGroup.Content = "Nach Klienten sortieren";
                
                Brush brush = BeWoApp.Current.FindResource(key) as Brush;

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

        }

        private void txtText_TextChanged(object sender, TextChangedEventArgs e)
        {
            _TextValuesChanged = true;
        }
    }
}
