using System;
using System.Collections.Generic;
using System.Linq;
using Consulenza.ExternalServices;
using Consulenza.ReportWriter.Business;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using System.Data;
using Consulenza.ReportWriter.Business.CHART_PDF;
using Consulenza.ReportCommon;
using Consulenza.ReportWriter.Business.Entity;
using System.Text;

namespace Consulenza.ReportWriter.Manager.Section.Immobiliare.Monitoraggio
{
    /// <summary>
    /// Scheda 22
    /// </summary>
    public class S22 : Entity.Section
    {

        public S22(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S22", ex.Message, SectionLoggerMessageLevel.E, EnvironmentFacade.ReportEnvironment);
            }
        }

        /// <summary>
        /// Scheda2. Patrimonio immobiliare –Sintesi (distribuzione del patrimonio complessivo del cliente diviso per tipologia e cointestatari)
        /// </summary>
        protected override sealed void Draw()
        {
            var data = GetDataTable();
            FormattedTextAreaPDF testoPagina = null;

            if (data.Rows.Count > 0)
            {
                testoPagina = new FormattedTextAreaPDF("Di seguito si riassumono le anomalie catastali rilevate.", 35) { FontSize = 10, FontColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo, AutoIncrementYWritable = true, Width = 740, FixedHeight = 20 };
                var listaOggettiDaRipetere = new List<ObjectPDF> { new SpacePDF(30), testoPagina, new SpacePDF(10) };
                AddElement(listaOggettiDaRipetere);

                AddElement(new RepeaterPDF(listaOggettiDaRipetere));

                /********************* Fix Dettaglio immobili – Anomalie catastali 27/08/2020 -- Pino *************************/
                var tabella = new TablePDF(35, data)
                {
                    Style = Style.Immobiliare,
                    Footer = false,
                    // Inserito il 24/04/2018 per spazio su prima riga
                    AdditionalSpaceBetweenHeadersAndTable = 7,
                    //
                    ShowBorderLastLine = true,
                    ShowSeparationLines = true
                };

                //var tabella = new TablePDF(EnvironmentFacade.RendererFacade.XLeftLimit, data)
                //{
                //    Style = Style.Immobiliare,
                //    Footer = false,
                //    // Inserito il 24/04/2018 per spazio su prima riga
                //    AdditionalSpaceBetweenHeadersAndTable = 7,
                //    //
                //    ShowBorderLastLine = true,
                //    ShowSeparationLines = true
                //};
                /**************************************************************************************************************/

                tabella.Columns.Add(new ColumnPDF("descrizione", 240, HorizontalAlignmentType.Sinistra, false, false, 8, ColumnType.Testo, "descrizione", "Descrizione") { FontColor = ColorPDF.Nero, VerticalAlignment = VerticalAlignmentType.Alto, DeltaYContent= -5 });
                tabella.Columns.Add(new ColumnPDF("valorestimato", 100, HorizontalAlignmentType.Destra, false, false, 8, ColumnType.Decimale, "valorestimato", "Valore stimato<br>totale (€)") { FontColor = ColorPDF.Nero, VerticalAlignment = VerticalAlignmentType.Alto, DeltaYContent = -5 });
                tabella.Columns.Add(new ColumnPDF("SEP1", 20, HorizontalAlignmentType.Nonimpostato, false, false, 8, ColumnType.Testo, "sep1", string.Empty)); //Separatore

                /********************* Fix Dettaglio immobili – Anomalie catastali 27/08/2020 -- Pino *************************/
                tabella.Columns.Add(new ColumnPDF("anomalierilevate", 365, HorizontalAlignmentType.Sinistra, false, false, 8, ColumnType.Testo, "anomalierilevate", "Anomalie rilevate") { VerticalAlignment = VerticalAlignmentType.Alto, DeltaYContent = -5 });
                //tabella.Columns.Add(new ColumnPDF("anomalierilevate", 395, HorizontalAlignmentType.Sinistra, false, false, 8, ColumnType.Testo, "anomalierilevate", "Anomalie rilevate") { VerticalAlignment = VerticalAlignmentType.Alto, DeltaYContent = -5 });
                /**************************************************************************************************************/

                //{
                //    HeaderBackgroundColor = ColorPDF.Immobiliare_Grigio_TitoloPiccolo,
                //    FontColor = ColorPDF.Nero,
                //    BackgroundColor = new ColorPDF(196, 196, 187)
                //});

                AddElement(tabella);
            }

        }

        /// <summary>
        /// Recupera i dati necessari alla Section restituendo un DataTable.
        /// </summary>
        /// <returns></returns>
        protected override DataSet GetDataSet()
        {
            return null;
        }

        /// <summary>
        /// Recupera i dati necessari alla Section restituendo un DataSet.
        /// </summary>
        /// <returns></returns>
        protected override DataTable GetDataTable()
        {
            #region Definizione dei parametri

            var parametri = new List<Parametro>
            {
                new Parametro
                {
                    Direction = ParameterDirection.Input,
                    DbType = DbType.Int64,
                    ParameterName = "ChiaveClientePB",
                    Value = EnvironmentFacade.ReportEnvironment.Cliente.Chiave
                }
            };

            #endregion

            var dt = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerConsulenzaUnica, "REP_Immobiliare_S8_DettaglioImmobiliAnomalieCatastali", parametri);


            //Riaggregazione
            var query = (from p in dt.AsEnumerable()
                         orderby p.Field<string>("tipoImmobile") ascending, p.Field<decimal>("ValoreStimato") descending 
                         group p by p.Field<string>("IdImmobileCatasto") into g
                         
                         select new
                         {
                             IdImmobileCatasto = g.Key,
                             Descrizione = g.Select(x => x.Field<string>("Descrizione")).FirstOrDefault(),
                             ValoreStimato = g.Select(x => x.Field<decimal>("ValoreStimato")).FirstOrDefault(),
                             AnomalieRilevate = string.Join("<BR><BR>", g.Select(x => x.Field<string>("AnomalieRilevate")))
                         }).ToList();


            var dtResult = dt.Clone();

            foreach (var item in query)
                dtResult.Rows.Add(item.IdImmobileCatasto, item.Descrizione, item.ValoreStimato, string.Empty, item.AnomalieRilevate);


            return dtResult;
        }
    }
}
