using System;
using Consulenza.ReportWriter.Business;
using Consulenza.ReportWriter.Business.OBJ_PDF;
using System.Data;
using Consulenza.ReportCommon;
using System.Collections.Generic;
using Consulenza.ReportWriter.Business.CHART_PDF;
using System.Linq;
using Consulenza.ReportWriter.Business.Entity;
using Dundas.Charting.WebControl;

namespace Consulenza.ReportWriter.Manager.Section.Unica
{
    public class S42 : Entity.Section
    {
       
        
        /// <summary>
        ///S42.RischioMercatoEvoluzionePatrimonio  idSezione = 85
        /// </summary>
        public S42(EnvironmentFacade environmentFacade, int idSection)
            : base(environmentFacade, idSection)
        {
            try
            {
               
                Draw();
            }
            catch (Exception ex)
            {
                SectionLogger.Write("S42", ex.Message, SectionLoggerMessageLevel.E, EnvironmentFacade.ReportEnvironment);
            }
        }

        protected override sealed void Draw()
        {
            var dati = GetDataSet();
          

            var benchmark = new ColorPDF(180, 199, 231);
            var flessibili = new ColorPDF(244, 177, 131);

            #region Tabella

            #region Prodotti Finanziari (Benchmark - Flessibili) + Istogrammi
            var dtTabella = new DataTable();
            dtTabella.Columns.Add(new DataColumn("Oggetto", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("Categoria", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("Controvalore", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("VaR", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("Oggettostacked", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("Percentuale", typeof(string)));
            dtTabella.Columns.Add(new DataColumn("Altro", typeof(bool)));

            var dtPat = dati.Tables["profilo"];//.AsEnumerable().Where(l => l.Field<bool>("Altro")).CopyToDataTable();
            foreach (DataRow ro in dtPat.Rows)
            {
                dtTabella.Rows.Add("",
                                        ro["Categoria"].ToString(), 
                                        Helper.FormatCurrency(ro["Controvalore"].ToString()), 
                                        Helper.FormatCurrency(ro["VaR"].ToString()), 
                                        "", 
                                        Helper.FormatCurrency(ro["Percentuale"].ToString())
                                       );
            }

            var tabellaProgetti = new TablePDF(EnvironmentFacade.RendererFacade.XLeftLimit, dtTabella)

            {
                Style = Style.ConsulenzaUnica,
                AlternateRow = false,
                ShowSeparationLines = true,
                MinimumRowHeight = 27,
                Footer = false

            };
            tabellaProgetti.IndexesOfSeparatorsToIgnore.Add(3);
         //   tabellaProgetti.Columns.Add(new ColumnPDF("oggetto", 15, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Objectpdf, "oggetto", string.Empty) { PaddingLeft = 3, DeltaYContent = 7 });
            tabellaProgetti.Columns.Add(new ColumnPDF("Categ", 148, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Objectpdf, "Categoria", "Categoria") { HeaderFontSize = 7, PaddingLeft = 5, VerticalAlignment = VerticalAlignmentType.Centrato });
            tabellaProgetti.Columns.Add(new ColumnPDF("Contro", 90, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "Controvalore", "Controvalore<BR>attuale (€)") { HeaderFontSize = 7, PaddingRight = 1, HeaderPaddingLeft = 25 });
            tabellaProgetti.Columns.Add(new ColumnPDF("Var", 67, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "VaR", "VaR (%)") { HeaderFontSize = 7, HeaderPaddingRight = 11, PaddingRight = 8 });
            tabellaProgetti.Columns.Add(new ColumnPDF("oggettost", 170, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Objectpdf, "Percentuale", string.Empty) { PaddingLeft = 5, HeaderBackgroundColor = ColorPDF.Bianco, DeltaYContent = 9, BackgroundColor = ColorPDF.Bianco });
          //  tabellaProgetti.Columns.Add(new ColumnPDF("Percentuale", 70, HorizontalAlignmentType.Destra, false, false, 8, ColumnType.Testo, "Percentuale", "") { HeaderBackgroundColor = ColorPDF.Bianco, BackgroundColor = ColorPDF.Bianco });

          
            var list = new List<double>();
            list.Add(Convert.ToDouble(dati.Tables["profilo"].AsEnumerable().Max(x => x["Percentuale"])));
            var max = (float)Helper.Round(list.Max());
            float larghezzaSpazioTestoPercentuale = 0;
            float larghezzaBarra = 0;
            float deltaXBarra = 0;
           
            //decimal totcontr = dati.Tables["profilo"].AsEnumerable().Sum(l => l.Field<decimal>("Controvalore"));
            //decimal totvar = dati.Tables["profilo"].AsEnumerable().Sum(l => l.Field<decimal>("VaR"));

            int i = 0;
            foreach (DataRow r in dtTabella.Rows)
            {
                tabellaProgetti.Cells[0, i].ValueObjectList = new List<Business.Entity.ObjectPDF>()
                {
                   new CirclePDF(11, 11, r["Categoria"].ToString().Contains("bench") ? benchmark : r["Categoria"].ToString().Contains("fless") ? flessibili : r["Categoria"].ToString().Contains("Totale") ? ColorPDF.Standard_Grigio_SfondoColonnaTabella : ColorPDF.Bianco){ DeltaY = 7},
                   new FormattedTextAreaPDF(r["Categoria"].ToString(), 0) 
                   {  
                        DeltaY = 5,
                        DeltaX = 15,
                        FontSize = 7
                   }      
                };
                larghezzaBarra = Helper.GetWidthProportional((float)Convert.ToDecimal(r["Percentuale"]), max, tabellaProgetti.Columns[3].Width - 50);
                larghezzaSpazioTestoPercentuale = tabellaProgetti.Columns[3].Width - larghezzaBarra;
                deltaXBarra = larghezzaBarra + 10;
                if (larghezzaSpazioTestoPercentuale < 35)
                {
                    deltaXBarra = (tabellaProgetti.Columns[3].Width - 35);
                    larghezzaSpazioTestoPercentuale = 35;
                }
                if (Convert.ToDouble(r["Percentuale"]) == 0 && r["Categoria"].ToString().Contains("bench"))
                    benchmark = ColorPDF.Bianco;
                if (Convert.ToDouble(r["Percentuale"]) == 0 && r["Categoria"].ToString().Contains("fles"))
                    flessibili = ColorPDF.Bianco;
                tabellaProgetti.Cells[3, i].ValueObjectList = new List<Business.Entity.ObjectPDF>()
                {
                    new RectanglePDF(12, larghezzaBarra, r["Categoria"].ToString().Contains("bench") ? benchmark : r["Categoria"].ToString().Contains("fless") ? flessibili : r["Categoria"].ToString().Contains("Totale") ? ColorPDF.Standard_Grigio_SfondoColonnaTabella : ColorPDF.Bianco){DeltaY=-1.1F},
                    new FormattedTextAreaPDF(Helper.FormatPercentage(r["Percentuale"].ToString(), 2), 0, larghezzaSpazioTestoPercentuale) 
                    {  
                        DeltaY =Convert.ToDouble(r["Percentuale"]) == 0 ? 2 : 0.4F,
                        TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Left, 
                        DeltaX =Convert.ToDouble(r["Percentuale"]) == 0 ? 0 : deltaXBarra,
                        FontSize = 7
                    }      
                };
                // tabellaProgetti.Cells[5, i].Value = Convert.ToDecimal(r["Percentuale"]) > 0 ? " " + Helper.FormatCurrency(r["Percentuale"].ToString()) : "";
                tabellaProgetti.Cells[1, i].HorizontalAlignment = HorizontalAlignmentType.Destra;
                i++;
            }

            AddElement(tabellaProgetti);
            AddElement(new SpacePDF(10));
            #endregion
            
            #region Totale Gestito
            AddElement(new FormattedTextAreaPDF("Totale risparmio gestito", EnvironmentFacade.RendererFacade.XLeftLimit, 148) { DeltaX = 5, FontSize = 7, BackGroundColor = ColorPDF.Standard_Grigio_SfondoColonnaTabella, FontBold = true, AutoIncrementYWritable = false });
            AddElement(new FormattedTextAreaPDF("&nbsp;&nbsp;" + Helper.FormatCurrency(dati.Tables["profilo2"].AsEnumerable().Where(l => l.Field<bool>("Altro")).Sum(o => o.Field<decimal>("Controvalore")).ToString()), EnvironmentFacade.RendererFacade.XLeftLimit + 147, 90) { FontSize = 7, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Right, BackGroundColor = ColorPDF.Standard_Grigio_SfondoColonnaTabella, FontBold = true, AutoIncrementYWritable = false });

            var row = (from o in dati.Tables["profilo2"].AsEnumerable() where Convert.ToBoolean(o["Altro"]) select o).LastOrDefault();
            AddElement(new FormattedTextAreaPDF("&nbsp;&nbsp;" + Helper.FormatCurrency(row["var"].ToString()), EnvironmentFacade.RendererFacade.XLeftLimit + 147 + 90, 67) { FontSize = 7, DeltaX = -10, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Right, BackGroundColor = ColorPDF.Standard_Grigio_SfondoColonnaTabella, FontBold = true, AutoIncrementYWritable = true });
            #endregion

            #region Altri Prodotti + Patrimonio Fideuram
            var dtTabellaA = new DataTable();
            dtTabellaA.Columns.Add(new DataColumn("Categoria", typeof(string)));
            dtTabellaA.Columns.Add(new DataColumn("Controvalore", typeof(string)));
            dtTabellaA.Columns.Add(new DataColumn("VaR", typeof(string)));

            var dtPat1 = dati.Tables["profilo2"].AsEnumerable().CopyToDataTable();
            //var dtPat1 = dati.Tables["profilo2"].AsEnumerable().Where(l => !l.Field<bool>("Altro")).CopyToDataTable();
            foreach (DataRow ro in dtPat1.Rows)
            {
                if (!ro["Categoria"].ToString().ToLower().Contains("risparmio"))
                {
                    dtTabellaA.Rows.Add(ro["Categoria"].ToString(),
                                            Helper.FormatCurrency(ro["Controvalore"].ToString()),
                                            Helper.FormatCurrency(ro["VaR"].ToString()));
                }
            } 

            var tabellaAltri1 = new TablePDF(EnvironmentFacade.RendererFacade.XLeftLimit, dtTabellaA)

            {
                Style = Style.ConsulenzaUnica,
                AlternateRow = false,
                ShowSeparationLines = true,                
                RowHeight = 27,
                Footer = true,
                Header = false
            };
            tabellaAltri1.Columns.Add(new ColumnPDF("Categ", 147, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "Categoria", "") { HeaderFontSize = 7, PaddingLeft = 2 });
            tabellaAltri1.Columns.Add(new ColumnPDF("Contro", 90, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "Controvalore", ""));
            tabellaAltri1.Columns.Add(new ColumnPDF("Var", 67, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "VaR", "") { HeaderFontSize = 7, HeaderPaddingRight = 5, PaddingRight = 5 });
            tabellaAltri1.FooterColumns.Add(new ColumnPDF("Totale", 147, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Testo));
            tabellaAltri1.FooterColumns.Add(new ColumnPDF("controvalore", 90, HorizontalAlignmentType.Destra, false, true, 7, ColumnType.Testo));
            tabellaAltri1.FooterColumns.Add(new ColumnPDF("var", 67, HorizontalAlignmentType.Destra, false, true, 7, ColumnType.Testo) { PaddingRight = 5 });

            tabellaAltri1.FooterCells[0, 0].Value = string.Format("Patrimonio {0}", Helper.ReplaceVariables("$/Banca/$", EnvironmentFacade.ReportEnvironment));
            tabellaAltri1.FooterCells[1, 0].Value = Helper.FormatCurrency(dati.Tables["patrimonioFideuram"].Rows[0]["Controvalore"].ToString());
            tabellaAltri1.FooterCells[2, 0].Value = dati.Tables["patrimonioFideuram"].Rows[0]["VaR"].ToString().Replace(".", ",");
              
            AddElement(tabellaAltri1);
            AddElement(new SpacePDF(15));
            #endregion

            #endregion

            #region Nota + Testo (Dinamico con Orizzonte Temporale)
            //if (_presenzaNota)
            //    AddElement(new FormattedTextAreaPDF(string.Format(testi.Rows[0]["testo3"].ToString(),nota), EnvironmentFacade.RendererFacade.XLeftLimit));

        
            if (getNota().Length > 0)
                tabellaAltri1.Notes.Add(
                    new TableNotePDF(TableNotePDF.TableNotePositionType.PièDiTabella,
                        getNota(),
                        new[] { "VaR" },
                        string.Empty,
                        TableNotePDF.TableNoteAsteriskPositionType.PieDiTabella) { FontSize = 6 , TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify }
                        );


            AddElement(new SpacePDF(5));

            
            #endregion
        
           if (dati.Tables["profilo"].AsEnumerable().FirstOrDefault(o => o.Field<bool>("Altro") && o.Field<decimal>("Controvalore") > 0) != null && dati.Tables["scenari"].Rows.Count > 0)
            {
                if (getTestoIntro2().Length > 0)
                    AddElement(new FormattedTextAreaPDF(getTestoIntro2(), EnvironmentFacade.RendererFacade.XLeftLimit) { FontSize = 7, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Justify });

                #region Scenari Tabella
                var dtTabellaS = new DataTable();
                dtTabellaS.Columns.Add(new DataColumn("Oggetto", typeof(string)));
                dtTabellaS.Columns.Add(new DataColumn("Descrizione", typeof(string)));
                dtTabellaS.Columns.Add(new DataColumn("Valore", typeof(string)));
                dtTabellaS.Columns.Add(new DataColumn("Scadenza", typeof(string)));

                foreach (DataRow ro in dati.Tables["scenari"].Rows)
                {
                    dtTabellaS.Rows.Add("",
                                            ro["Descrizione"].ToString(),
                                            Helper.FormatDecimal(ro["Valore"].ToString(), 2),
                                            Helper.FormatDecimal(ro["Scadenza"].ToString(), 2));
                }
                var tabellaScenari = new TablePDF(EnvironmentFacade.RendererFacade.XLeftLimit, dtTabellaS)
                {
                    Style = Style.ConsulenzaUnica,
                    Header = true,
                    Footer = false,
                    AlternateRow = false,
                    HeaderHeight = 22,
                    RowHeight = 25,
                    AutoIncrementYWritable = false
                };
                //tabellaScenari.Columns.Add(new ColumnPDF("og", 20, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Objectpdf, "ogg", "") { DeltaYContent = 11, PaddingLeft = 5 });
                tabellaScenari.Columns.Add(new ColumnPDF("descr", 120, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Objectpdf, "Descrizione", "Scenari possibili") { PaddingLeft = 5, HeaderFontSize = 7, FontSize = 7, FontBold = false });
                tabellaScenari.Columns.Add(new ColumnPDF("valore", 70, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Testo, "Valore", "A 1 anno (%)") { HeaderFontSize = 7, FontSize = 7, PaddingRight = 10, FontBold = false });
                tabellaScenari.Columns.Add(new ColumnPDF("scadenza", 90, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "Scadenza", "A scadenza (%)") { HeaderFontSize = 7, FontSize = 7, HeaderPaddingLeft = 5, PaddingRight = 10, FontBold = false });

                tabellaScenari.FooterColumns.Add(new ColumnPDF("de", 135, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Testo) { FontSize = 7, FontColor = ColorPDF.Rosso });
                tabellaScenari.FooterColumns.Add(new ColumnPDF("va", 55, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo) { FontSize = 7, BackgroundColor = ColorPDF.Bianco });
                tabellaScenari.FooterColumns.Add(new ColumnPDF("sca", 90, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo) { FontSize = 7, BackgroundColor = ColorPDF.Bianco });

                int j = 0;
                foreach (DataRow r in dati.Tables["scenari"].Rows)
                {
                    ColorPDF colore = r["Descrizione"].ToString().Equals("Ottimistico") ? new ColorPDF(0, 128, 0) : r["Descrizione"].ToString().Equals("Medio") ? new ColorPDF(0, 0, 0) : new ColorPDF(255, 0, 0);
                    tabellaScenari.Cells[0, j].ValueObjectList = new List<Business.Entity.ObjectPDF>()
                        {
                            new RectanglePDF(3, 13, colore){ DeltaY = 10},
                            new FormattedTextAreaPDF(r["Descrizione"].ToString(), 0) 
                                {  
                                  DeltaY = 4,
                                    DeltaX = 20,
                                    FontSize = 7
                                }      
                        };

                    tabellaScenari.Cells[1, j].HorizontalAlignment = HorizontalAlignmentType.Destra;
                    tabellaScenari.Cells[2, j].HorizontalAlignment = HorizontalAlignmentType.Destra;
                    j++;
                }
                AddElement(new SpacePDF(15));
                AddElement(tabellaScenari);
                #endregion

                #region Grafico Combination
                var graficoCombination = new CombinationPDF(EnvironmentFacade.RendererFacade.XLeftLimit + 320, 1.0F)
                {
                   
                    Height = 100,
                    Width = 200,
                    MinorGridAxisY = false,
          
                    AutoIncrementYWritable = true,
                    MarginAxisY = 0,
                    ShowLineAxisY = true,
                    ShowLabelAxisY = true,
                    LabelFormatAxisY = FormatType.Decimale0,
                    LabelFormatAxisX = FormatType.DataShort,
                    ShowLineAxisX = true,
                    IntervalNumberAxisX = 5,
                    ShowLegend = false,
                    LegendDeltaX = 124,
                    LegendYOffset = 6,
                    LegendSymbolHeight = 0.2f,
                    LegendSymbolDeltaY = 9.2f,
                    LegendWidthColumns = new List<int> { 20, 2, 20 },
                    RemoveWhiteSpacesY = true
                };

                // creo le Serie
                var serieCombination = new List<Serie>()
                {
                     new Serie { Name = "Ottimistico", Type = Dundas.Charting.WebControl.SeriesChartType.Line, BorderWidth = 6, ShowInLegend = false },
                     new Serie { Name = "Media", Type = Dundas.Charting.WebControl.SeriesChartType.Line, BorderWidth = 6, ShowInLegend = false},
                     new Serie { Name = "Pessimistico", Type = Dundas.Charting.WebControl.SeriesChartType.Line, BorderWidth = 6, ShowInLegend = false} ,
                     new Serie { Name = "Stripped0Line", Type = Dundas.Charting.WebControl.SeriesChartType.Line, BorderWidth = 6, BorderStyle = ChartDashStyle.Dash, ShowInLegend = true, Text = "0,00", Color = new ColorPDF(195,195,195) }
                };

                serieCombination[3].Points.Add(new Point
                {
                    Color = new ColorPDF(150, 150, 150),
                    Values = new ValuesPointXY(dati.Tables["ControvaloriLineeProtette"].Rows.OfType<DataRow>().Min(x => Convert.ToDateTime(x["Data"]).ToOADate()), 0),
                    ShowLabelAxisY = false,
                    FontSizeLabelAxisY = 7,
                    FontBoldLabelAxisY = false,
                    ShowLabelAxisX = false
                });

                serieCombination[3].Points.Add(new Point
                {
                    Color = new ColorPDF(150, 150, 150),
                    Values = new ValuesPointXY(dati.Tables["ControvaloriLineeProtette"].Rows.OfType<DataRow>().Max(x => Convert.ToDateTime(x["Data"]).ToOADate()), 0),
                    ShowLabelAxisY = false,
                    FontSizeLabelAxisY = 7,
                    FontBoldLabelAxisY = false,
                    ShowLabelAxisX = false
                });
                
                //var dataAttuale = DateTime.Now;
                //var dataFutura = dataAttuale.AddYears(Convert.ToInt32(_OrizzonteTemporale));
                //var dts = dati.Tables["ControvaloriLineeProtette"].AsEnumerable().OrderBy(o => o.Field<DateTime>("Data")).Where(o => o.Field<DateTime>("Data") <= dataAttuale).CopyToDataTable();
                //var dts = dati.Tables["ControvaloriLineeProtette"].AsEnumerable().Where(o => o.Field<DateTime>("Data") >= dataAttuale && o.Field<DateTime>("Data") <= dataFutura).OrderBy(o => o.Field<DateTime>("Data")).CopyToDataTable();

                // valorizzo le Serie
                //foreach (DataRow item in dts.Rows)
                foreach (DataRow item in dati.Tables["ControvaloriLineeProtette"].Rows)
                {
                    #region Serie Ottimistico
                    serieCombination[0].Points.Add(new Point
                    {
                        Color = new ColorPDF(0, 128, 0),
                        Values = new ValuesPointXY(Convert.ToDateTime(item["Data"]).ToOADate(), Convert.ToDouble(item["Ottimistico"])),
                        ShowLabelAxisY = false,
                        FontSizeLabelAxisY = 7,
                        LabelAxisY = Helper.FormatPercentage(Convert.ToDecimal(item["Ottimistico"]), 2),
                        FontBoldLabelAxisY = false,
                        ShowLabelAxisX = true
                    });
                    #endregion
                    #region Serie Media
                    serieCombination[1].Points.Add(new Point
                    {
                        Color = new ColorPDF(0, 0, 0),
                        Values = new ValuesPointXY(Convert.ToDateTime(item["Data"]).ToOADate(), Convert.ToDouble(item["Media"])),
                        ShowLabelAxisY = false,
                        LabelAxisY = Helper.FormatPercentage(Convert.ToDecimal(item["Media"]), 2),
                        FontSizeLabelAxisY = 7,
                        FontBoldLabelAxisY = false,
                        FontSizeLabelAxisX = 7,
                        ShowLabelAxisX = true
                    });
                    #endregion
                    #region Serie Pessimistico
                    serieCombination[2].Points.Add(new Point
                    {
                        Color = new ColorPDF(255, 0, 0),
                        Values = new ValuesPointXY(Convert.ToDateTime(item["Data"]).ToOADate(), Convert.ToDouble(item["Pessimistico"])),
                        ShowLabelAxisY = false,
                        LabelAxisY = Helper.FormatPercentage(Convert.ToDecimal(item["Pessimistico"]), 2),
                        FontSizeLabelAxisY = 7,
                        FontBoldLabelAxisY = false,

                        ShowLabelAxisX = true
                    });
                    #endregion
                }

                //aggiungo le Serie al grafico
                graficoCombination.SeriesCollection = serieCombination;
                //AddElement(new SpacePDF(10));
                //aggiungo il grafico alla pagina
                AddElement(graficoCombination);
                //AddElement(new SpacePDF(10));
                #endregion

                #region Statistiche
                var tabellaStatistiche = new TablePDF(EnvironmentFacade.RendererFacade.XLeftLimit, dati.Tables["statistiche"]) // CAMBIARE 3 con 2
                {
                    Style = Style.ConsulenzaUnica,
                    Header = true,
                    Footer = false,
                    AlternateRow = false,
                    RowHeight = 25
                };
                tabellaStatistiche.Columns.Add(new ColumnPDF("descrizione", 165, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Testo, "Descrizione", "Statistiche") { HeaderFontSize = 7, FontBold = false });
                tabellaStatistiche.Columns.Add(new ColumnPDF("valore", 115, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "Valore", "") { FontSize = 7, PaddingRight = 5 });

                AddElement(new SpacePDF(12));
                AddElement(tabellaStatistiche);
                AddElement(new SpacePDF(10));
                #endregion
            }
        }
        
        protected sealed override DataTable GetDataTable()
        {
            return null;
        }
 
        protected sealed override DataSet GetDataSet()
        {
            var ds = new DataSet();
            ds.Tables.Add(new DataTable("profilo"));
            ds.Tables.Add(new DataTable("profilo2"));
            ds.Tables.Add(new DataTable("patrimonioFideuram"));
            ds.Tables.Add(new DataTable("scenari"));
            ds.Tables.Add(new DataTable("ControvaloriLineeProtette"));
            ds.Tables.Add(new DataTable("statistiche"));

            int orzTempMesi = scadenzaTemporale();

          
            var evoluzionePatrimonio = datiSeiUnico.rischioUnit().rischio.evoluzione;
            var pianificazioneVerticale = datiSeiUnico.pianificazioneUnit().pianificazioneVerticale;
           

            #region Estrazione Profilo Finanziario
            
            ds.Tables["profilo"].Columns.Add(new DataColumn("Categoria", typeof(string)));
            ds.Tables["profilo"].Columns.Add(new DataColumn("Controvalore", typeof(decimal)));
            ds.Tables["profilo"].Columns.Add(new DataColumn("VaR", typeof(string)));
            ds.Tables["profilo"].Columns.Add(new DataColumn("Percentuale", typeof(decimal)));
            ds.Tables["profilo"].Columns.Add(new DataColumn("Altro", typeof(bool)));

            foreach (var item in evoluzionePatrimonio.strutturaRisparmioGestito)
            {
                ds.Tables["profilo"].Rows.Add(item.descrizione,
                                        item.controvalore,
                                        item.var == null ? "0" : item.var,
                                        item.pesoRelativoCtv * 100,
                                        item.descrizione.ToLower().Contains("benchmark") || item.descrizione.ToLower().Contains("fless") ? true : false);
            }
            #endregion

            #region Estrazione Altri Profili
           
            ds.Tables["profilo2"].Columns.Add(new DataColumn("Categoria", typeof(string)));
            ds.Tables["profilo2"].Columns.Add(new DataColumn("Controvalore", typeof(decimal)));
            ds.Tables["profilo2"].Columns.Add(new DataColumn("VaR", typeof(string)));
            ds.Tables["profilo2"].Columns.Add(new DataColumn("Percentuale", typeof(decimal)));
            ds.Tables["profilo2"].Columns.Add(new DataColumn("Altro", typeof(bool)));

            foreach (var item in evoluzionePatrimonio.strutturaPortafoglio)
            {
                //if (!item.descrizione.ToLower().Contains("risparmio"))
                //{ 
                var VaR = item.var == null ? "0" : (item.controvalore < 0 ? "n.c." : item.var);
                    ds.Tables["profilo2"].Rows.Add(item.descrizione,
                                            item.controvalore,
                                            item.var == null ? "0" : item.var,
                                            item.peso * 100,
                                            item.descrizione.ToLower().Contains("gestito") ? true : false);
               // }
            }
            #endregion

            #region Estrazione Patrimonio Fideuram
            
            ds.Tables["patrimonioFideuram"].Columns.Add(new DataColumn("Categoria", typeof(string)));
            ds.Tables["patrimonioFideuram"].Columns.Add(new DataColumn("Controvalore", typeof(decimal)));
            ds.Tables["patrimonioFideuram"].Columns.Add(new DataColumn("VaR", typeof(string)));
            ds.Tables["patrimonioFideuram"].Columns.Add(new DataColumn("Valore note", typeof(string)));
            ds.Tables["patrimonioFideuram"].Rows.Add(
                                                        string.Format("Patrimonio {0}", Helper.ReplaceVariables("$/Banca/$", EnvironmentFacade.ReportEnvironment)),      
                                                        pianificazioneVerticale.patrimonioTotaleRFA,
                                                        pianificazioneVerticale.varInfos.varDecodificato,
                                                        pianificazioneVerticale.varInfos.stat.copertura);
            #endregion
       

            #region Estrazione Dati Grafico

            if (evoluzionePatrimonio.listaConi != null)
            {

                ds.Tables["controvaloriLineeProtette"].Columns.Add(new DataColumn("Data", typeof(DateTime)));
                ds.Tables["controvaloriLineeProtette"].Columns.Add(new DataColumn("Ottimistico", typeof(decimal)));
                ds.Tables["controvaloriLineeProtette"].Columns.Add(new DataColumn("Pessimistico", typeof(decimal)));
                ds.Tables["controvaloriLineeProtette"].Columns.Add(new DataColumn("Media", typeof(decimal)));

                var coni = from c in evoluzionePatrimonio.listaConi
                           where c.dtRiferimento <= DateTime.Now.AddYears(orzTempMesi) //dipende da quale opzione arriva: se si decide per mesi o anni...rivedi opzioni, metodo e where
                           orderby c.dtRiferimento
                           select new
                           {
                               c.dtRiferimento,
                               quantileSup = c.quantileSup * 100,
                               quantileInf = c.quantileInf * 100,
                               quantileInter = c.quantileInter * 100
                           };

                foreach (var item in coni)
                {
                    ds.Tables["controvaloriLineeProtette"].Rows.Add(item.dtRiferimento,
                                                            Convert.ToDecimal(item.quantileSup),
                                                            Convert.ToDecimal(item.quantileInf),
                                                            Convert.ToDecimal(item.quantileInter)
                                                            );

                }
            #endregion


                #region Estrazione Scenari

                ds.Tables["scenari"].Columns.Add(new DataColumn("Descrizione", typeof(string)));
                ds.Tables["scenari"].Columns.Add(new DataColumn("Valore", typeof(decimal)));
                ds.Tables["scenari"].Columns.Add(new DataColumn("Scadenza", typeof(decimal)));


                ds.Tables["scenari"].Rows.Add(
                        "Ottimistico",
                        evoluzionePatrimonio.scenari.optScenarioOneYear,
                        Helper.FormatDecimal(coni.LastOrDefault().quantileSup.ToString(), 2)
                );
                ds.Tables["scenari"].Rows.Add(
                        "Medio",
                        evoluzionePatrimonio.scenari.stScenarioOneYear,
                        Helper.FormatDecimal(coni.LastOrDefault().quantileInter.ToString(), 2)
                );

                ds.Tables["scenari"].Rows.Add(
                    "Pessimistico",
                    evoluzionePatrimonio.scenari.pesScenarioOneYear,
                    Helper.FormatDecimal(coni.LastOrDefault().quantileInf.ToString(), 2)
               );

                #endregion

                #region Estrazione Statistiche

                ds.Tables["statistiche"].Columns.Add(new DataColumn("Descrizione", typeof(string)));
                ds.Tables["statistiche"].Columns.Add(new DataColumn("Valore", typeof(string)));

                // AM - HotFix #9720
                bool tempHorizonExist = evoluzionePatrimonio.scenari.minimumTime.ToString() != "-" &&
                    evoluzionePatrimonio.scenari.minimumTime.ToString() != null &&
                    evoluzionePatrimonio.scenari.minimumTime.ToString() != "";
                string tempHorizonString = tempHorizonExist ? evoluzionePatrimonio.scenari.minimumTime.ToString().Substring(0,2).Replace(" ", "") :
                    evoluzionePatrimonio.scenari.minimumTime.ToString();
                string tempHorizon = tempHorizonExist && (orzTempMesi < int.Parse(tempHorizonString)) ?
                    "-" : evoluzionePatrimonio.scenari.minimumTime.ToString();
                ds.Tables["statistiche"].Rows.Add("Tempo minimo di investimento", tempHorizon/*evoluzionePatrimonio.scenari.minimumTime.ToString()*/);
                ds.Tables["statistiche"].Rows.Add("Perdita massima stimata (%)", evoluzionePatrimonio.scenari.maxLoss.ToString() == "0" ? "-" : Helper.FormatDecimal(evoluzionePatrimonio.scenari.maxLoss.ToString(), 2));
                #endregion

            }

            return ds;
        }
        public virtual int scadenzaTemporale()
        {
            var pi = GetOption<Opzione5>().Valore;
             // return 0;
            return int.Parse(GetOption<Opzione5>().Valore);// int.Parse(GetOption<Opzione5>().Valore) != 6 ? int.Parse(GetOption<Opzione5>().Valore) / 12 : int.Parse(GetOption<Opzione5>().Valore);
        }
        public virtual string getNota()
        {
           
            string nota = "";
            var copertura = datiSeiUnico.pianificazioneUnit().pianificazioneVerticale.varInfos.stat.copertura;
            if (copertura < 100)
            {
                nota = string.Format(GetText().Rows[0]["testo2"].ToString(), Helper.FormatDecimal(copertura.ToString(), 2)).Trim();
            }            
            return nota;
        }
        public virtual string getTestoIntro2(){
            return string.Format(GetText().Rows[0]["testo1"].ToString(),Helper.orizzonteTemporale(GetOption<Opzione5>().Valore), Helper.ReplaceVariables("$/Banca/$",base.EnvironmentFacade.ReportEnvironment));
        }
    }
}
