using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using ceTe.DynamicPDF.Merger;
using PDFGenerator.BusinessLayer.DataSection;
using PDFGenerator.Presentation.Section.Tables;
using PDFGenerator.BusinessLayer;
using ceTe.DynamicPDF.Text;
using PDFGenerator.Presentation.Section;
using ceTe.DynamicPDF.PageElements;
using NLog;

namespace PDFGenerator.Presentation.Section
{
    public class S43BIS : ISezione
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        string Titolo = " ";
        DataSetS43BIS set;

        ImportedPage page;
        private bool _versatonetto_utileperdita = false;
        private bool _mostrarendimentodainizioanno = false;
        private bool _mostrarendimentodadatasottoscrizione = false;
        // private bool _mostratitolosezione = false;

        //MIFID2 20180420
        string notaSezione = string.Empty;
        bool notaSezioneStampata = false;
        bool moreTables = false;
        int tableCount;
        //--MIFID2

        private TipologiaReport _tipologiaReport = TipologiaReport.MONITORAGGIO; // la S43BIS è usata solo per il monitoraggio fase 2 (monitoraggio senza albero.)


        public S43BIS()
        {

        }

        string _Area;
        string _Progetto;



        #region ISezione Members


        public void writeSezione(DataThread dataThread)
        {
            dataThread.SETDATA();

            DocumentPDF document = dataThread.DocumentPDF;
            DatiTabella datitab = new DatiTabella();
            set = (DataSetS43BIS)dataThread.Data.DatiSezione;

            //MIFID2 20180529 decremento il conteggio delle aree da stampare (per MONITORAGGIO)
            document.AreasCount--;
            //--MIFID2

            //MIFID2 20180424
            notaSezione = dataThread.SezioneReport.Nota;
            //notaSezione = "NOTA PROVA 43Bis " + dataThread.Area;

            /*************  Modifica per la gestione della nota dinamica in base ai prodotti FAI 11/03/2021 - Pino *********************/
            //string testoNotaFAI = " Il controvalore dei fondi Perennius Global Yield Private 2011, Idea Crescita Globale, FAI Private Debt Special Opportunities e FAI Private Markets Insight esposto nella rendicontazione è determinato tramite il NAV trimestrale al #dataFAI# (ultimo disponibile alla data di predisposizione del presente rendiconto) al netto delle distribuzioni avvenute nel trimestre e accreditate sul conto corrente indicato in fase di sottoscrizione.";
            string testoNotaFAI = " Il controvalore dei fondi di Investimento alternativi è determinato tenuto conto del NAV ufficiale trimestrale al #dataFAI# (ultimo disponibile alla data di predisposizione del presente rendiconto) al netto di eventuali richiami e/o distribuzioni di capitale effettuati successivamente.";


            string _flagNotaFAI = set.FlagNotaFAI.Rows[0][0].ToString();
            if (_flagNotaFAI == "S")
            {
                testoNotaFAI = testoNotaFAI.Replace("#dataFAI#", set.FlagNotaFAI.Rows[0][1].ToString());
                notaSezione += testoNotaFAI;
            }
            /***************************************************************************************************************************/

            document.NotaPieDiPagina = notaSezione;

            // Controlla se ci sono vari codici aree bisogno, in tal caso la nota statica va a fondo pagina, altrimenti, se c'è un solo codice area, va a fine tabella
            DataView viewDistinctAreas = new DataView(set.Tables["ProdottiAreeBisogno"]);
            DataTable distinctValues = viewDistinctAreas.ToTable(true, "CodiceAreaBisogno");
            moreTables = distinctValues.Rows.Count > 1;
            //--MIFID2

            //if (document.checkMargin(datitab.GetRowDim() * 5))  {
            //    document.addPage();
            //}
            dataThread.UltimaSezioneStampata = "";

            page = document.getCurrentPage();
            DataView view;


            if (_Area == null || _Area == "Liq")
            {
                datitab.table = set.Tables["ProdottiAreeBisogno"];
                view = new DataView(datitab.table);
                view.RowFilter = ("CodiceAreaBisogno = 'Liq'");
                if (view.Count > 0)
                {
                    //MIFID2 20180528 se cambia pagina resetto il flag notastampata
                    //orig:
                    //if (document.checkMargin(datitab.GetRowDim() * 4))
                    //    document.addPage();

                    if (document.checkMargin(datitab.GetRowDim() * 4))
                    {
                        document.addPage();
                        notaSezioneStampata = false;
                    }

                    //--MIFID2

                    this.writeArea(datitab, document, "Liq", dataThread);

                }
            }

            if (Area == null || Area == "Ris")
            {

                datitab.table = set.Tables["ProdottiAreeBisogno"];
                view = new DataView(datitab.table);
                view.RowFilter = ("CodiceAreaBisogno = 'Ris'");
                if (view.Count > 0)
                {
                    //MIFID2 20180528 se cambia pagina resetto il flag notastampata
                    //orig:
                    //if (document.checkMargin(datitab.GetRowDim() * 4))
                    //    document.addPage();

                    if (document.checkMargin(datitab.GetRowDim() * 4))
                    {
                        document.addPage();
                        notaSezioneStampata = false;
                    }

                    //--MIFID2

                    this.writeArea(datitab, document, "Ris", dataThread);
                }
            }

            if (Area == null || Area == "Pre")
            {
                datitab.table = set.Tables["ProdottiAreeBisogno"];
                view = new DataView(datitab.table);
                view.RowFilter = ("CodiceAreaBisogno = 'Pre'");
                if (view.Count > 0)
                {
                    //MIFID2 20180528 se cambia pagina resetto il flag notastampata
                    //orig:
                    //if (document.checkMargin(datitab.GetRowDim() * 4))
                    //    document.addPage();

                    if (document.checkMargin(datitab.GetRowDim() * 4))
                    {
                        document.addPage();
                        notaSezioneStampata = false;
                    }

                    //--MIFID2

                    this.writeArea(datitab, document, "Pre", dataThread);
                }
            }

            if (Area == null || Area == "Inv")
            {
                //document.setSezTitoloWithoutNumber("Investimento");

                datitab.table = set.Tables["ProdottiAreeBisogno"];
                view = new DataView(datitab.table);
                view.RowFilter = ("CodiceAreaBisogno = 'Inv'");
                if (view.Count > 0)
                {
                    //MIFID2 20180528 se cambia pagina resetto il flag notastampata
                    //orig:
                    //if (document.checkMargin(datitab.GetRowDim() * 4))
                    //    document.addPage();

                    if (document.checkMargin(datitab.GetRowDim() * 4))
                    {
                        document.addPage();
                        notaSezioneStampata = false;
                    }

                    //--MIFID2

                    this.writeAreaProgetto(datitab, document, "Inv", dataThread.Progetto, dataThread);
                }
            }

            if (Area == null || Area == "Ext")
            {
                datitab.table = set.Tables["ProdottiAreeBisogno"];
                view = new DataView(datitab.table);
                view.RowFilter = ("CodiceAreaBisogno = 'Ext'");
                if (view.Count > 0)
                {

                    //MIFID2 20180528 se cambia pagina resetto il flag notastampata
                    //orig:
                    //if (document.checkMargin(datitab.GetRowDim() * 4))
                    //    document.addPage();

                    if (document.checkMargin(datitab.GetRowDim() * 4))
                    {
                        document.addPage();
                        notaSezioneStampata = false;
                    }

                    //--MIFID2

                    this.writeArea(datitab, document, "Ext", dataThread);
                }
            }

            if (Area == null || Area == "Na")
            {
                // Risorse non associate
                datitab.table = set.Tables["ProdottiAreeBisogno"];
                view = new DataView(datitab.table);
                view.RowFilter = ("CodiceAreaBisogno = 'Na'");
                if (view.Count > 0)
                {
                    if (Area == null)
                        //MIFID2 20180528 se cambia pagina resetto il flag notastampata
                        //orig:
                        //if (document.checkMargin(datitab.GetRowDim() * 4))
                        //    document.addPage();

                        if (document.checkMargin(datitab.GetRowDim() * 4))
                        {
                            document.addPage();
                            notaSezioneStampata = false;
                        }

                    //--MIFID2

                    this.writeArea(datitab, document, "Na", dataThread);

                }
            }

            if (document.Areas.Rows.Count == 0)
            {
                var segnaposto = 0;
                if (document.DocumentNotes.Rows.Count > 0)
                    document.WriteNote2(notaSezione, dataThread.IsSavingMap, dataThread.IsAPC103);
            }

            document.setLastPos(5);

            /*** TEST - Verifica Tempistica 09/11/2023 - Pino ****/
            /*** Inserimento log per verifica tempistica della sezione ***/
            //DateTimeOffset dateOffsetValueFin = DateTimeOffset.Parse(DateTime.Now.ToString("hh:mm:ss.ffff"));
            //var tDiff = dateOffsetValueFin - dateOffsetValueIni;
            //logger.Trace("S43BIS " + tDiff);
            /**************************************************************/
        }

        #endregion


        /// <summary>
        /// Disegna la tabella per il dettaglio monitoraggio x Area. 
        /// </summary>
        /// <param name="datitab"></param>
        /// <param name="document"></param>
        /// <param name="area"></param>
        private void writeArea(DatiTabella datitab, DocumentPDF document, string area, DataThread dataThread)
        {
            //MIFID2 20180528
            tableCount--;
            //--MIFID2

            //MIFID2 20180529 Elimino dalla proprietà datatable del document la riga relativa all'area che sto stampando
            if (dataThread.TipoReport.ToUpper().Equals("MONITORAGGIO"))
            {

                foreach (DataRow row in document.Areas.Rows)
                {
                    if (row.Field<string>("NEED_AREA").ToUpper().Equals(area.ToUpper()))
                        row.Delete();
                }
                document.Areas.AcceptChanges();
            }
            //--MIFID2

            float dim = 0;
            page = document.getCurrentPage();
            FormatNum conv = new FormatNum();
            string notaGradoCopertura = string.Empty;

            //setta la datatable
            datitab.table = set.Tables["ProdottiAreeBisogno"];

            // filtro per l'area
            DataView view = new DataView(datitab.table);
            view.RowFilter = ("CodiceAreaBisogno = '" + area + "'");
            datitab.table = view.ToTable();

            #region Tabella Dati

            // Disegno la tabella
            Tabella tabellaDettaglio_Area = new Tabella(document.getMargineLeft(), document.getLastPos());
            tabellaDettaglio_Area.HeaderFont = 8;
            tabellaDettaglio_Area.Header = true;
            tabellaDettaglio_Area.Datasource = datitab.table;
            tabellaDettaglio_Area.Id = "tabella_S43BIS" + area;
            tabellaDettaglio_Area.AltezzaCella = 23;
            tabellaDettaglio_Area.LineaFineTabella = true;


            #region Settaggio delle Note di piè di pagina e delle note a piedi della tabella

            //MIFID2 20180619 Se il documento non ha nessuna nota nella lista di note, mi serve aggiungerne una "finta" per avere il numero di asterischi che parte da 2 (includendo la nota fissa sul Ctv)
            if (document.Note.Count == 0)
                document.Note.Add(new Nota(Nota.TipologiaNota.NonImpostato, tabellaDettaglio_Area.Id, ""));
            //--MIFID2

            //Nota a piedi della tabella
            // Imposto la nota a piedi della Tabella   
            notaGradoCopertura = datitab.table.Rows[0]["Copertura"] == DBNull.Value ? string.Empty : datitab.table.Rows[0]["Copertura"].ToString();
            if (notaGradoCopertura.Length > 0)
            {
                document.Note.Add(new Nota(Nota.TipologiaNota.GradoCopertura, tabellaDettaglio_Area.Id, notaGradoCopertura));
                tabellaDettaglio_Area.NotaTabella.Add(document.Note.Find(Nota.TipologiaNota.GradoCopertura, tabellaDettaglio_Area.Id).Testo);
            }

            document.Note.RemoveAt(0);

            #endregion

            //tabellaDettaglio_Area.Colonne.Add(new Colonna("DataAssociazione", "Data ass.", 60, TipoAllineamento.SINISTRA, false, 7, false));
            //tabellaDettaglio_Area.Colonne.Add(new Colonna("<IMAGE>", " ", 5, TipoAllineamento.DESTRA, false, 7, false, TipoColonna.IMMAGINE));
            //tabellaDettaglio_Area.Colonne.Add(new Colonna("Descrizione", "Descrizione", 87, TipoAllineamento.SINISTRA, false, 7, false));

            tabellaDettaglio_Area.Colonne.Add(new Colonna("DataAssociazione", "Data ass.", 45, TipoAllineamento.SINISTRA, false, 7, false));
            tabellaDettaglio_Area.Colonne.Add(new Colonna("<IMAGE>", " ", 5, TipoAllineamento.DESTRA, false, 7, false, TipoColonna.IMMAGINE));
            //tabellaDettaglio_Area.Colonne.Add(new Colonna("Descrizione", "Descrizione", 110, TipoAllineamento.SINISTRA, false, 7, false));
            tabellaDettaglio_Area.Colonne.Add(new Colonna("Descrizione", "Descrizione", 175, TipoAllineamento.SINISTRA, false, 7, false)); // dimensioni con la rimozione della colonna rischio credito


            //tabellaDettaglio_Area.Colonne.Add(new Colonna("DataAssociazione", "Data assoc.", 55, TipoAllineamento.SINISTRA, false, 7, false));
            //tabellaDettaglio_Area.Colonne.Add(new Colonna("<IMAGE>", " ", 15, TipoAllineamento.DESTRA, false, 7, false, TipoColonna.IMMAGINE));
            //tabellaDettaglio_Area.Colonne.Add(new Colonna("Descrizione", "Descrizione", 82, TipoAllineamento.SINISTRA, false, 7, false));


            //MIFID2 20180424 Asterisco + nota a pie' pagina (o fine tabella)
            //tabellaDettaglio_Area.Colonne.Add(new Colonna("Controvalore", "Controvalore (€)", 80, TipoAllineamento.DESTRA, false, 7, false));
            tabellaDettaglio_Area.Colonne.Add(new Colonna("Controvalore", "Controvalore (€)*", 80, TipoAllineamento.DESTRA, false, 7, false));
            //--MIFID2
            tabellaDettaglio_Area.Colonne.Add(new Colonna("VersatoNetto", "Versato netto<BR>da assoc. (€)", 80, TipoAllineamento.DESTRA, false, 7, false));
            tabellaDettaglio_Area.Colonne.Add(new Colonna("UtilePerdita", "Utile/perdita<BR>da assoc. (€)", 80, TipoAllineamento.DESTRA, false, 7, false));
            //tabellaDettaglio_Area.Colonne.Add(new Colonna("CreditRisk", "Rischio<BR>Credito", 65, TipoAllineamento.DESTRA, false, 7, false));
            tabellaDettaglio_Area.Colonne.Add(new Colonna("Var", "Rischio<BR>(VaR %)", 55, TipoAllineamento.DESTRA, false, 7, false));


            //MIFID2 20180530
            string NomeArea = string.Format("{0}-{1}", area, datitab.table.Rows[0]["Progetto"]);

            document.DocumentNotes.Rows.Add(NomeArea, 0, document.CurrentPage);
            //--MIFID2

            // Scrivo la tabella tabella Dati
            //MIFID2 20180514
            //orig:
            //tabellaDettaglio_Area.Draw(datitab, document);
            //tabellaDettaglio_Area.Draw(datitab, document, notaSezione, tableCount == 0, ref notaSezioneStampata);
            tabellaDettaglio_Area.DrawMonitoraggio(datitab, document, notaSezione, tableCount == 0, ref notaSezioneStampata);
            //--MIFID2

            #endregion Tabella Dati

            #region Tabella Totali

            datitab = new DatiTabella();
            datitab.table = set.Tables["ProdottiTotale"];
            datitab.CellClear();

            //Imposto gli asterischi di rimando nel caso in cui sia presente la nota del grado copertura
            if (notaGradoCopertura.Length > 0)
                datitab.table.Rows[0]["Var"] = datitab.table.Rows[0]["Var"].ToString() + document.Note.Find(Nota.TipologiaNota.GradoCopertura, tabellaDettaglio_Area.Id).ToString();

            /*************************************** Fix Levi Trimestrale 10/2020 - Pino **********************************************************************/
            //Tabella tabellaTotali_Area = new Tabella(document.getMargineLeft(), document.getLastPos() + tabellaDettaglio_Area.AltezzaTabella + 25);
            Tabella tabellaTotali_Area = new Tabella(document.getMargineLeft(), document.getLastPos() + tabellaDettaglio_Area.AltezzaTabella + 29);
            /**************************************************************************************************************************************************/
            tabellaTotali_Area.HeaderFont = 8;
            tabellaTotali_Area.Header = false;
            tabellaTotali_Area.SaltoPagina = false;

            /*************************************** Fix Levi Trimestrale 10/2020 - Pino **********************************************************************/
            //tabellaTotali_Area.Colonne.Add(new Colonna("Totale", "", 122, TipoAllineamento.SINISTRA, true, 8, true));
            //tabellaTotali_Area.Colonne.Add(new Colonna("Controvalore", "", 110, TipoAllineamento.DESTRA, true, 8, true));
            //tabellaTotali_Area.Colonne.Add(new Colonna("Var", "", 280, TipoAllineamento.DESTRA, true, 8, true));

            //tabellaTotali_Area.Colonne.Add(new Colonna("Totale", "", 122, TipoAllineamento.SINISTRA, true, 8, true));
            tabellaTotali_Area.Colonne.Add(new Colonna("Totale", "", 187, TipoAllineamento.SINISTRA, true, 8, true));
            tabellaTotali_Area.Colonne.Add(new Colonna("Controvalore", "", 118, TipoAllineamento.DESTRA, true, 8, true));
            tabellaTotali_Area.Colonne.Add(new Colonna("Var", "", 215, TipoAllineamento.DESTRA, true, 8, true));
            /**************************************************************************************************************************************************/

            // it should fix problem
            if (document.checkMargin(datitab.GetRowDim() * 4 + 20)) // + 20 because of '(*) Grado di copertura: 80,29%'
            //MIFID2 20180528
            {
                document.addPage();
                notaSezioneStampata = false;
            }
            //--MIFID2

            // Scrive la tabella Totali
            tabellaTotali_Area.Draw(datitab, document);

            dim = tabellaTotali_Area.AltezzaTabella + tabellaDettaglio_Area.AltezzaTabella;


            //MIFID2 20180529 DocumentNotes
            // Memorizzare la posizione della nota e il numero pagina
            //document.DocumentNotes.Rows.Add(NomeArea, document.getLastPos() + dim, document.CurrentPage);

            //20180619 Se c'è anche la nota sulla Copertura, bisogna dare un po' di spazio in più
            //document.AddDocumentNote(NomeArea, document.getLastPos() + dim, document.CurrentPage);
            if (!string.IsNullOrEmpty(notaGradoCopertura))
            {
                document.AddDocumentNote(NomeArea, document.getLastPos() + dim + 10, document.CurrentPage);
                document.setLastPos(dim);
            }
            else
            {
                document.AddDocumentNote(NomeArea, document.getLastPos() + dim, document.CurrentPage);
                /*************  Modifica per la gestione della nota dinamica in base ai prodotti FAI 12/03/2021 - Pino *********************/
                //document.setLastPos(dim + 10);
                document.setLastPos(dim + 50);
                /******************************************************************************************************************************/
            }


            //--MIFID2


            //page.Elements.Add(new TextArea("PROVA "+ document.NumPage.ToString(), document.getMargineLeft(), 500, 510, 10));
            //var p = document.getPageAt(document.CurrentPage-1);
            //p.Elements.Add(new TextArea("PROVA 0", document.getMargineLeft(), 500, 510, 10));

            #endregion
            //MIFID2 20180424 da collocare dopo l'ultima tabella (o a fondo pagina)
            //if (!moreTables)
            //{
            //    if (!string.IsNullOrEmpty(notaSezione) && !notaSezioneStampata)
            //    {
            //        FormattedTextArea text = new FormattedTextArea(notaSezione, document.getMargineLeft(), document.getLastPos(), 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
            //        text.Height = text.GetRequiredHeight();
            //        text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            //        page.Elements.Add(text);
            //        notaSezioneStampata = true;
            //    }
            //}
            //else
            //{
            //    if (!string.IsNullOrEmpty(notaSezione) && !notaSezioneStampata)
            //    {
            //        FormattedTextArea text = new FormattedTextArea(notaSezione, document.getMargineLeft(), 720, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
            //        text.Height = text.GetRequiredHeight();
            //        text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            //        page.Elements.Add(text);
            //        notaSezioneStampata = true;
            //    }
            //}

            //if (!string.IsNullOrEmpty(notaSezione) && !notaSezioneStampata)
            //{
            //    FormattedTextArea text = new FormattedTextArea(notaSezione, document.getMargineLeft(), 720, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
            //    text.Height = text.GetRequiredHeight();
            //    text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
            //    page.Elements.Add(text);
            //    notaSezioneStampata = true;
            //}
            //--MIFID2

            //MIFID2 20180528
            notaSezioneStampata = true;
            if (tableCount == 0)
                document.setLastPos(10);
            //--MIFID2
        }


        /// <summary>
        /// Disegna la tabella per il dettaglio monitoraggio x Area/Progetto.
        /// Usata per area Investimento. 
        /// </summary>
        /// <param name="datitab"></param>
        /// <param name="document"></param>
        /// <param name="area"></param>
        private void writeAreaProgetto(DatiTabella datitab, DocumentPDF document, string area, string nomeprogetto, DataThread dataThread)
        {
            //bool checkPartiteViaggiantiCrossProgetto = false;
            FormatNum conv = new FormatNum();
            float dim = 0;

            //if (area == "Inv")
            //{
            //    if (dataThread.TipoReport.ToUpper().Equals("MONITORAGGIO"))
            //    {
            //        if ((document.CurrentPage - document.NumLastPage) > 1)
            //        {
            //            document.RemoveLastPage(document.NumLastPage+1);
            //            //eliminatoPaginaBianca = true;
            //        }
            //        //else
            //        //    eliminatoPaginaBianca = true;
            //    }
            //}

            page = document.getCurrentPage();

            //decimal totProgetto = 0;
            // string varProgetto = " ";
            //bool stampatatabellaTitoloProgetto = false;
            // float ytabella = 0; // unico incremento per la y di tutte le tabelle.
            string notaGradoCopertura = string.Empty;


            //Tabella tabellaDatiProgetto = null;
            //Tabella tabTotali = null;


            //setta la datatable
            datitab.table = set.Tables["ProdottiAreeBisogno"];

            // filtro per l'area
            DataView view = new DataView(datitab.table);
            view.RowFilter = ("CodiceAreaBisogno = '" + area + "' and Progetto='" + nomeprogetto.Replace("'", "''") + "'");
            datitab.table = view.ToTable();

            //MIFID2 20180529 Elimino dalla proprietà datatable del document la riga relativa all'area che sto stampando
            if (dataThread.TipoReport.ToUpper().Equals("MONITORAGGIO"))
            {

                foreach (DataRow row in document.Areas.Rows)
                {
                    if (row.Field<string>("NEED_AREA").ToUpper().Equals(area.ToUpper()) && row.Field<string>("NOME_PROGETTO").ToUpper().Equals(nomeprogetto.ToUpper()))
                        row.Delete();
                }
                document.Areas.AcceptChanges();
            }
            //--MIFID2

            if (datitab.table.Rows.Count > 0)
            {
                #region Tabella Dati

                // Disegno la tabella
                //Tabella tabellaDettaglio_Area = new Tabella(document.getMargineLeft(), document.getLastPos() + ytabella);
                Tabella tabellaDettaglio_Area = new Tabella(document.getMargineLeft(), document.getLastPos());  //-10
                tabellaDettaglio_Area.HeaderFont = 8;
                tabellaDettaglio_Area.Header = true;
                tabellaDettaglio_Area.Datasource = datitab.table;
                tabellaDettaglio_Area.Id = "tabella_S43BIS" + area + "_" + nomeprogetto;
                tabellaDettaglio_Area.AltezzaCella = 21; //23;
                tabellaDettaglio_Area.LineaFineTabella = true;


                #region Settaggio delle Note a piedi della tabella

                //MIFID2 20180619 Se il documento non ha nessuna nota nella lista di note, mi serve aggiungerne una "finta" per avere il numero di asterischi che parte da 2 (includendo la nota fissa sul Ctv)
                if (document.Note.Count == 0)
                    document.Note.Add(new Nota(Nota.TipologiaNota.NonImpostato, tabellaDettaglio_Area.Id, ""));
                //--MIFID2

                //Nota a piedi della tabella
                // Imposto la nota a piedi della Tabella   
                notaGradoCopertura = datitab.table.Rows[0]["Copertura"] == DBNull.Value ? string.Empty : datitab.table.Rows[0]["Copertura"].ToString();
                if (notaGradoCopertura.Length > 0)
                {
                    document.Note.Add(new Nota(Nota.TipologiaNota.GradoCopertura, tabellaDettaglio_Area.Id, notaGradoCopertura));
                    tabellaDettaglio_Area.NotaTabella.Add(document.Note.Find(Nota.TipologiaNota.GradoCopertura, tabellaDettaglio_Area.Id).Testo);
                }

                document.Note.RemoveAt(0);

                #endregion

                //tabellaDettaglio_Area.Colonne.Add(new Colonna("DataAssociazione", "Data assoc.", 60, TipoAllineamento.SINISTRA, false, 7, false));
                //tabellaDettaglio_Area.Colonne.Add(new Colonna("<IMAGE>", " ", 5, TipoAllineamento.DESTRA, false, 7, false, TipoColonna.IMMAGINE));                
                //tabellaDettaglio_Area.Colonne.Add(new Colonna("Descrizione", "Descrizione", 87, TipoAllineamento.SINISTRA, false, 7, false));
                tabellaDettaglio_Area.Colonne.Add(new Colonna("DataAssociazione", "Data ass.", 45, TipoAllineamento.SINISTRA, false, 7, false));
                tabellaDettaglio_Area.Colonne.Add(new Colonna("<IMAGE>", " ", 5, TipoAllineamento.DESTRA, false, 7, false, TipoColonna.IMMAGINE));
                //tabellaDettaglio_Area.Colonne.Add(new Colonna("Descrizione", "Descrizione", 110, TipoAllineamento.SINISTRA, false, 7, false));
                tabellaDettaglio_Area.Colonne.Add(new Colonna("Descrizione", "Descrizione", 175, TipoAllineamento.SINISTRA, false, 7, false)); // nuova dimensione con la rimozione della colonna rischio credito


                //MIFID2 20180424 Asterisco + nota a pie' pagina (o fine tabella)
                //tabellaDettaglio_Area.Colonne.Add(new Colonna("Controvalore", "Controvalore (€)", 80, TipoAllineamento.DESTRA, false, 7, false));
                tabellaDettaglio_Area.Colonne.Add(new Colonna("Controvalore", "Controvalore (€)*", 80, TipoAllineamento.DESTRA, false, 7, false));
                //--MIFID2
                tabellaDettaglio_Area.Colonne.Add(new Colonna("VersatoNetto", "Versato netto<BR>da assoc. (€)", 80, TipoAllineamento.DESTRA, false, 7, false));
                tabellaDettaglio_Area.Colonne.Add(new Colonna("UtilePerdita", "Utile/perdita<BR>da assoc. (€)", 80, TipoAllineamento.DESTRA, false, 7, false));
                //tabellaDettaglio_Area.Colonne.Add(new Colonna("CreditRisk", "Rischio<BR>Credito", 65, TipoAllineamento.DESTRA, false, 7, false));
                tabellaDettaglio_Area.Colonne.Add(new Colonna("Var", "Rischio<BR>(VaR %)", 55, TipoAllineamento.DESTRA, false, 7, false));

                // Scrivo la tabella tabella Dati
                //MIFID2 20180528
                //tabellaDettaglio_Area.Draw(datitab, document);

                //MIFID2 20180530
                string NomeArea = string.Format("{0}-{1}", area, datitab.table.Rows[0]["Progetto"]);
                document.DocumentNotes.Rows.Add(NomeArea, 0, document.CurrentPage);
                //--MIFID2

                //tabellaDettaglio_Area.Draw(datitab, document, notaSezione, tableCount == 0, ref notaSezioneStampata);
                tabellaDettaglio_Area.DrawMonitoraggio(datitab, document, notaSezione, tableCount == 0, ref notaSezioneStampata);
                //--MIFID2

                #endregion Tabella Dati

                ////MIFID2 20180424 Serve per stampare la nota a piè pagina nelle pagine in cui viene splittata la tabella relativa agli investimenti
                //int numPag = 1;
                //foreach (var pag in tabellaDettaglio_Area.PagineDisegnate)
                //{
                //    //Nell'ultima pagina la nota va a fine tabella
                //    if (numPag < tabellaDettaglio_Area.PagineDisegnate.Count)
                //    {
                //        FormattedTextArea text = new FormattedTextArea(notaSezione, document.getMargineLeft(), 720, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                //        text.Height = text.GetRequiredHeight();
                //        text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
                //        pag.Pagina.Elements.Add(text);
                //    }
                //    numPag++;
                //}
                ////--MIFID2  

                #region Tabella Totali

                datitab = new DatiTabella();
                datitab.table = set.Tables["ProdottiTotale"];
                datitab.CellClear();

                //Imposto gli asterischi di rimando nel caso in cui sia presente la nota del grado copertura
                if (notaGradoCopertura.Length > 0)
                    datitab.table.Rows[0]["Var"] = datitab.table.Rows[0]["Var"].ToString() + document.Note.Find(Nota.TipologiaNota.GradoCopertura, tabellaDettaglio_Area.Id).ToString();

                /*************************************** Fix Levi Trimestrale 10/2020 - Pino **********************************************************************/
                //Tabella tabellaTotali_Area = new Tabella(document.getMargineLeft(), document.getLastPos() + tabellaDettaglio_Area.AltezzaTabella + 25);
                Tabella tabellaTotali_Area = new Tabella(document.getMargineLeft(), document.getLastPos() + tabellaDettaglio_Area.AltezzaTabella + 29);
                /**************************************************************************************************************************************************/

                tabellaTotali_Area.HeaderFont = 8;
                tabellaTotali_Area.Header = false;
                tabellaTotali_Area.SaltoPagina = false;

                /*************************************** Fix Levi Trimestrale 10/2020 - Pino **********************************************************************/
                //tabellaTotali_Area.Colonne.Add(new Colonna("Totale", "", 130, TipoAllineamento.SINISTRA, true, 8, true));
                //tabellaTotali_Area.Colonne.Add(new Colonna("Controvalore", "", 102, TipoAllineamento.DESTRA, true, 8, true));
                //tabellaTotali_Area.Colonne.Add(new Colonna("Var", "", 280, TipoAllineamento.DESTRA, true, 8, true));

                //tabellaTotali_Area.Colonne.Add(new Colonna("Totale", "", 130, TipoAllineamento.SINISTRA, true, 8, true));
                tabellaTotali_Area.Colonne.Add(new Colonna("Totale", "", 195, TipoAllineamento.SINISTRA, true, 8, true));

                tabellaTotali_Area.Colonne.Add(new Colonna("Controvalore", "", 110, TipoAllineamento.DESTRA, true, 8, true));
                //tabellaTotali_Area.Colonne.Add(new Colonna("Var", "", 280, TipoAllineamento.DESTRA, true, 8, true));
                tabellaTotali_Area.Colonne.Add(new Colonna("Var", "", 215, TipoAllineamento.DESTRA, true, 8, true));

                /**************************************************************************************************************************************************/

                // Scrive la tabella Totali
                tabellaTotali_Area.Draw(datitab, document);

                dim = tabellaTotali_Area.AltezzaTabella + tabellaDettaglio_Area.AltezzaTabella;

                //MIFID2 20180529 DocumentNotes
                // Memorizzare la posizione della nota e il numero pagina
                //document.DocumentNotes.Rows.Add(NomeArea, document.getLastPos() + dim, document.CurrentPage);

                if (!string.IsNullOrEmpty(notaGradoCopertura))
                {
                    document.AddDocumentNote(NomeArea, document.getLastPos() + dim + 10, document.CurrentPage);
                    document.setLastPos(dim);
                }
                else
                {
                    document.AddDocumentNote(NomeArea, document.getLastPos() + dim, document.CurrentPage);
                    document.setLastPos(dim + 10);    // document.setLastPos(dim + 10);
                }

                //--MIFID2

                //MIFID2 20180424 INSERISCE LA NOTA STATICA ALLA FINE DELLA SEZIONE

                //document.setLastPos(lastPosition + 10);
                //document.setLastPos(dim);

                //if (!string.IsNullOrEmpty(notaSezione))
                //{
                //    FormattedTextArea text = new FormattedTextArea(notaSezione, document.getMargineLeft(), document.getLastPos(), 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                //    text.Height = text.GetRequiredHeight();
                //    text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
                //    page = document.getCurrentPage();
                //    page.Elements.Add(text);
                //}



                document.setLastPos(dim + 200);

                //--MIFID2

                //document.setLastPos(dim + 10);

                notaSezioneStampata = true;


                #endregion
            }

        }



        public void setTitolo(string label)
        {
            Titolo = label;
        }

        public string Area
        {
            get
            {
                return _Area;
            }
            set
            {
                _Area = value;
            }
        }

        public string Progetto
        {
            get
            {
                return _Progetto;
            }
            set
            {
                _Progetto = value;
            }
        }

        public bool VersatoNetto_UtilePerdita
        {
            get { return _versatonetto_utileperdita; }
            set { _versatonetto_utileperdita = value; }
        }

        public bool MostraRendimentoDaInizioAnno
        {
            get { return _mostrarendimentodainizioanno; }
            set { _mostrarendimentodainizioanno = value; }
        }

        public bool MostraRendimentoDaDataSottoscrizione
        {
            get { return _mostrarendimentodadatasottoscrizione; }
            set { _mostrarendimentodadatasottoscrizione = value; }
        }

        public TipologiaReport TipologiaReport
        {
            get { return _tipologiaReport; }
            set { _tipologiaReport = value; }
        }
    }
}