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;
using Consulenza.ReportWriter.Business.Headers;

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

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

        private List<Point> SortPointsList(List<Point> points)
        {
            var tmpPoints = points.OrderByDescending(x => x.ID).ToList();            
            List<Point> resultList = new List<Point>();
            
            
            resultList = tmpPoints;


            //while (tmpPoints.Any())
            //{
            //    Point biggest = null;
            //    Point smallest = null;
            //    if (tmpPoints.Any())
            //    {
            //        biggest = tmpPoints.Where(x => x.ID == tmpPoints.Max(y => y.ID)).FirstOrDefault();
            //        if (biggest != null)
            //        {
            //            tmpPoints.Remove(biggest);
            //            resultList.Add(biggest);
            //        }
            //    }
            //    if (tmpPoints.Any())
            //    {
            //        smallest = tmpPoints.Where(x => x.ID == tmpPoints.Min(y => y.ID)).FirstOrDefault();
            //        if (smallest != null)
            //        {
            //            tmpPoints.Remove(smallest);
            //            resultList.Add(smallest);
            //        }
            //    }
            //}
            return resultList;
        }


        /// <summary>
        /// Scheda2. Patrimonio immobiliare –Sintesi (distribuzione del patrimonio complessivo del cliente diviso per tipologia e cointestatari)
        /// </summary>
        protected override void Draw()
        {
            var ds = GetDataSet();

            #region Grafico torta

            #region Valorizzazione Serie

            var serieTorta = new List<Serie>();

            foreach (var row in ds.Tables["sintesiTorta"].AsEnumerable())
            {
                serieTorta.Add(new Serie { Name = row["tipologia"].ToString() });

                serieTorta[0].Points.Add(new Point
                {
                    LabelAxisX = row["tipologia"].ToString(),
                    Value = Convert.ToDouble(row["peso"]),                    
                    Color = getColor(row["tipologia"].ToString()),
                    ShowLabelAxisX = false,
                    ShowLabelAxisY = false,
                    FontSizeLabelAxisX = 10,
                    FontSizeLabelAxisY = 10,
                    ID = row["ord1"].ToString(),
                });                
                
            }
            serieTorta[0].Points = SortPointsList(serieTorta[0].Points);

            
            AddElement(new SpacePDF(90));

            //var torta = new PiePDF(48 + 395, 0.2F)
            var torta = new PiePDF(40 + 400, 0.2F)
            {
                Width = 340,
                Height = 340,
                SeriesCollection = serieTorta,
                StartAngle=220,                      //270
                ShowLabelPoints = true,     
                Style3DEnabled = false,
                AutoIncrementYWritable = true,
                LabelDecimalDigitsCount = 1,
                FontLabelSize = 5f,
                CustomPlottingHeight = 50,   
                CustomPlottingWidth = 50,    
                CustomPlottingX = 25,
                CustomPlottingY = 7,
                UseCustomPlotting = true
            };

            //AddElement(new SpacePDF(5));
            AddElement(torta);

            #endregion

            var tortaTitolo = new FormattedTextAreaPDF(string.Format("{0}", "Patrimonio immobiliare complessivo"), 85 + 395 + 28) { FontColor = new ColorPDF(91, 88, 79), FontSize = 10, FontBold = true, AutoIncrementYWritable = true };
            AddElement(new SpacePDF(-7));
            AddElement(tortaTitolo);
            //AddElement(new SpacePDF(10));
            #endregion


            #region Grafico a barre

            //AddElement(new SpacePDF(90));

            //var graficoTitolo = new FormattedTextAreaPDF(string.Format("{0}", "Patrimonio immobiliare complessivo"), 480) { FontColor = new ColorPDF(91, 88, 79), FontSize = 10, FontBold = true, AutoIncrementYWritable = true };
            //AddElement(graficoTitolo);
            //AddElement(new SpacePDF(40));

            //var graficoBarre = new StackedPDF(EnvironmentFacade.RendererFacade.XLeftLimit + 505, 1F)
            //{
            //    HeightSingleBar = 25,
            //    Width = 200,

            //    LabelFormatAxisY = FormatType.Intero,

            //    MinorGridAxisY = true,
            //    //MarginAxisY = 0,
            //    ShowLineAxisX = true,
            //    ShowLineAxisY = true,
            //    PageBreak = true,
            //    DinamicFloatXEtichettaLateraleBarra = true,
            //    RemoveWhiteSpaceBetweenChartAndAxisX = true,
            //    MarginAxisY = 0,
            //    MarginAxisYFromTop = 0,
            //    Height = 400

            //};
            ////graficoBarre.Headers.Add(new FormattedTextAreaPDF("Valute", EnvironmentFacade.RendererFacade.XLeftLimit, 100) { BackGroundColor = ColorPDF.Standard_Grigio_SfondoColonnaTabella, FontBold = true, FontSize = 7, FontColor = ColorPDF.ConsulenzaUnica_Rosso, AutoIncrementYWritable = false, BackGroundMarginLeft = 5 });
            ////graficoBarre.Headers.Add(new FormattedTextAreaPDF("Distribuzione (%)", EnvironmentFacade.RendererFacade.XLeftLimit + 110, 410) { BackGroundColor = ColorPDF.Standard_Grigio_SfondoColonnaTabella, FontBold = true, FontSize = 7, FontColor = ColorPDF.ConsulenzaUnica_Rosso, BackGroundMarginLeft = 5 });

            //var serieCollezione = new List<Serie> { new Serie { Name = "Tipologia", Border = true } };

            //foreach (DataRow item in ds.Tables["sintesiTorta"].AsEnumerable())
            //{
            //    serieCollezione[0].Points.Add(new Point
            //    {
            //        ShowLabelAxisY = true,
            //        ShowLabelAxisX = true,
            //        LabelAxisY = Helper.FormatPercentage(Convert.ToDecimal(item["peso"]), 2),
            //        LabelAxisX = item["tipologia"].ToString(),
            //        ImagePathLabelAsixX = string.Format("Flags\\{0}.png", item["tipologia"]),

            //        FontSizeLabelAxisY = 7,

            //        //Color = new ColorPDF(Convert.ToInt32(item["Red"]), Convert.ToInt32(item["Green"]), Convert.ToInt32(item["Blue"])),
            //        Color = getColor(item["tipologia"].ToString()),
            //        Value = Convert.ToDouble(item["peso"]) == 0 ? 0.01 : Convert.ToDouble(item["peso"]),

            //        ImageScaleLabelAsixX = 0.4F,
            //        ImageDeltaXLabelAsixX = 55,
            //        FontSizeLabelAxisX = 7,
            //        FontBoldLabelAxisY = false
            //    });
            //}

            //graficoBarre.SeriesCollection = serieCollezione;

            //AddElement(graficoBarre);

            #endregion


            var xLegenda = 135 + 395 + 20;

            ColorPDF coloriUsoAbitativo = new ColorPDF(207, 220, 210);
            ColorPDF coloriStrumentale = new ColorPDF(167, 192, 168);
            ColorPDF coloriInvestimento = new ColorPDF(115, 152, 109);
            ColorPDF coloriNonSpecificata = new ColorPDF(245, 245, 220);
            AddElement(new SpacePDF(230));
            foreach (var row in ds.Tables["sintesiTorta"].AsEnumerable())
            {
                switch (row["indice"].ToString())
                {

                    case "U":
                        var legendaUsoAbitativoRettangolo = new RectanglePDF(xLegenda, 12, 17, coloriUsoAbitativo) { AutoIncrementYWritable = false };
                        var legendaUsoAbitativoTesto = new FormattedTextAreaPDF(string.Format("{0}", "Immobili d'uso abitativo"), xLegenda + 25) { FontSize = 7, AutoIncrementYWritable = true };

                        AddElement(legendaUsoAbitativoRettangolo);
                        AddElement(legendaUsoAbitativoTesto);
                        AddElement(new SpacePDF(10));
                        break;

                    case "S":
                        var legendaStrumentaleRettangolo = new RectanglePDF(xLegenda, 12, 17, coloriStrumentale) { AutoIncrementYWritable = false };
                        var legendaStrumentaleTesto = new FormattedTextAreaPDF(string.Format("{0}", "Immobili strumentali"), xLegenda + 25) { FontSize = 7, AutoIncrementYWritable = true };

                        AddElement(legendaStrumentaleRettangolo);
                        AddElement(legendaStrumentaleTesto);
                        AddElement(new SpacePDF(10));
                        break;

                    case "I":
                        var legendaInvestimentoRettangolo = new RectanglePDF(xLegenda, 12, 17, coloriInvestimento) { AutoIncrementYWritable = false };
                        var legendaInvestimentoTesto = new FormattedTextAreaPDF(string.Format("{0}", "Immobili d'investimento"), xLegenda + 25) { FontSize = 7, AutoIncrementYWritable = true };

                        AddElement(legendaInvestimentoRettangolo);
                        AddElement(legendaInvestimentoTesto);
                        AddElement(new SpacePDF(10));
                        break;

                    case "NS":
                        var legendaNonSpecificataRettangolo = new RectanglePDF(xLegenda, 12, 17, coloriNonSpecificata) { AutoIncrementYWritable = false };
                        var legendaNonSpecificataTesto = new FormattedTextAreaPDF(string.Format("{0}", "Finalità non specificata"), xLegenda + 25) { FontSize = 7, AutoIncrementYWritable = true };

                        AddElement(legendaNonSpecificataRettangolo);
                        AddElement(legendaNonSpecificataTesto);
                        break;

                    default:
                        break;
                }
            }

            AddElement(new ResetterYPDF());
            var table = new TablePDF(35, ds.Tables["sintesi"], ds.Tables["sintesiTotale"])
            {
                Style = Style.Immobiliare,
                AlternateRow = false,
                HeaderHeight = 25,
                RowHeight = 10,
                ShowBorderLastLine = false,
                ShowBorderLastLineInPageBreak = false,
                ShowBorderHeader = false,

                //AdditionalSpaceBetweenHeadersAndTable = 5.0F,
                HeaderTextVerticalAlign = VerticalAlignmentType.Basso,
                AutoIncrementYWritable = false
            };

            table.Columns.Add(new ColumnPDF("tipologia", 105, HorizontalAlignmentType.Sinistra, false, false, 7, ColumnType.Testo, "tipologia", "Finalità/Tipologia") { HeaderFontSize = 7 });
            table.Columns.Add(new ColumnPDF("numero", 40, HorizontalAlignmentType.Centrato, false, false, 7, ColumnType.Testo, "numero", "Numero<br>immobili") { HeaderFontSize = 7 });

            /**************************************** FIX Mappatura Strategica 27/07/2020 PINO ********************************/
            //table.Columns.Add(new ColumnPDF("proquota", 100, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "proquota", "Valore stimato pro<br>quota (€)") { HeaderFontSize = 7 }); // Originale
            table.Columns.Add(new ColumnPDF("proquota", 100, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "proquota", "Valore stimato<br>pro quota (€)") { HeaderFontSize = 7 });
            /******************************************************************************************************************/

            table.Columns.Add(new ColumnPDF("stimato", 100, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "stimato", "Valore stimato <br>totale (€)") { HeaderFontSize = 7 });
            table.Columns.Add(new ColumnPDF("peso", 55, HorizontalAlignmentType.Destra, false, false, 7, ColumnType.Testo, "peso", "Peso (%)") { HeaderFontSize = 7 });

            table.FooterColumns.Add(new ColumnPDF("tipologiaTotale", 105, HorizontalAlignmentType.Sinistra, false, true, 7, ColumnType.Testo));
            table.FooterColumns.Add(new ColumnPDF("numeroTotale", 40, HorizontalAlignmentType.Centrato, false, true, 7, ColumnType.Testo));
            table.FooterColumns.Add(new ColumnPDF("proquotaTotale", 100, HorizontalAlignmentType.Destra, false, true, 7, ColumnType.Testo));
            table.FooterColumns.Add(new ColumnPDF("stimatoTotale", 100, HorizontalAlignmentType.Destra, false, true, 7, ColumnType.Testo));
            table.FooterColumns.Add(new ColumnPDF("pesoTotale", 55, HorizontalAlignmentType.Destra, false, true, 7, ColumnType.Testo));

            float startFrameX = table.X + table.Width + 10;
            float startFrameY = 94;
            //addFrame(startFrameX, startFrameX + 320, startFrameY, startFrameY + 350);
            addFrame(startFrameX, startFrameX + 320, startFrameY, startFrameY + 340);

            AddElement(new SpacePDF(50));
            AddElement(new RepeaterPDF(new List<ObjectPDF>() { new SpacePDF(50) }));
            AddElement(new FormattedTextAreaPDF(getTesto1(), 45, 700) { FontColor = ColorPDF.Immobiliare_Grigio_TestoStandard, FontSize = 10, TextHorizontalAlign = ceTe.DynamicPDF.TextAlign.Left });
            AddElement(new SpacePDF(15));
            AddElement(table);
        }

        public void addFrame(float XupSx, float XupDx, float Yup, float Ydown)
        {

            var horizontalTopLine = new LinePDF(XupSx, Yup, XupDx, Yup, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false };
            AddElement(horizontalTopLine);
            var horizontalBottomLine = new LinePDF(XupSx, Ydown, XupDx, Ydown, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false };
            AddElement(horizontalBottomLine);
            var verticalLeftLine = new LinePDF(XupSx, Yup, XupSx, Ydown, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false };
            AddElement(verticalLeftLine);
            var verticalRightLine = new LinePDF(XupDx, Yup, XupDx, Ydown, 0.5F, ColorPDF.Immobiliare_Grigio_TitoloPiccolo) { AutoIncrementYWritable = false };
            AddElement(verticalRightLine);
        }


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

        /// <summary>
        /// Recupera i dati necessari alla Section restituendo un DataSet.
        /// </summary>
        /// <returns></returns>
        protected override DataSet GetDataSet()
        {
            #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.ExecuteDataSetStoredProcedure(DBProvider.SqlServerConsulenzaUnica, "REP_ImmobiliareMonitoraggio_S13_MappaturaSintesi", parametri);

            DataTable table = new DataTable();
            table.Columns.Add("tipologia", typeof(string));
            table.Columns.Add("numero", typeof(string));
            table.Columns.Add("proquota", typeof(string));
            table.Columns.Add("stimato", typeof(string));
            table.Columns.Add("peso", typeof(string));

            DataTable tableTotale = new DataTable();
            tableTotale.Columns.Add("tipologiaTotale", typeof(string));
            tableTotale.Columns.Add("numeroTotale", typeof(string));
            tableTotale.Columns.Add("proquotaTotale", typeof(string));
            tableTotale.Columns.Add("stimatoTotale", typeof(string));
            tableTotale.Columns.Add("pesoTotale", typeof(string));

            DataTable tableTorta = new DataTable();
            tableTorta.Columns.Add("indice", typeof(string));
            tableTorta.Columns.Add("tipologia", typeof(string));
            tableTorta.Columns.Add("peso", typeof(decimal));
            tableTorta.Columns.Add("ord1", typeof(int));

            List<string> indiciPagina = dt.Tables[0].AsEnumerable()
                .Select(z => z.Field<string>("usoTipologia")).Distinct().ToList();

            #region Vecchio Codice 12/02/2018

            
            //List<string> indiciPagina = dt.Tables[0].AsEnumerable()
            //    .Select(z => z.Field<string>("usoTipologia")).Distinct().ToList();

            //decimal nTotalePeso = 0;
            //for (int k = 0; k < dt.Tables[0].Rows.Count; k++)
            //{
            //    nTotalePeso = nTotalePeso + (Convert.ToDecimal(Helper.FormatDecimal(dt.Tables[0].Rows[k]["peso"].ToString(), 4)) * 100); 
            //}

            //decimal nTotaleTipologia = 0;
            //foreach (var indice in indiciPagina)
            //{
            //    var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(indice));
            //    if (tabellaIndice != null)
            //    {
            //        nTotaleTipologia = nTotaleTipologia + Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100;
            //    }
            //}

            //foreach (var indice in indiciPagina)
            //{
            //    var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(indice));
            //    if (tabellaIndice != null)
            //    {
            //        // Check su Totali
            //        //decimal nPesoTotal = Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1));
            //        decimal nPesoTotal = Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100;

            //        decimal nPesoSingle = 0;
            //        foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
            //        {
            //            nPesoSingle = nPesoSingle + (Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4))*100);
            //        }


            //        // Fine Check
            //        if (nPesoTotal == nPesoSingle)
            //        {
            //            table.Rows.Add(getTipologia(indice), "",
            //                "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
            //                "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
            //                "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

            //            tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

            //            foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
            //            {
            //                table.Rows.Add(row["FinalitaTipologia"],
            //                    row["numImmobili"],
            //                    Helper.FormatCurrency(row["valProQuota"].ToString()),
            //                    Helper.FormatCurrency(row["valTotale"].ToString()),
            //                    Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
            //            }                    

            //        }
            //        else
            //        {
            //            //table.Rows.Add(getTipologia(indice), "",
            //            //    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
            //            //    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
            //            //    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

            //            //tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

            //            //foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
            //            //{
            //            //    table.Rows.Add(row["FinalitaTipologia"],
            //            //        row["numImmobili"],
            //            //        Helper.FormatCurrency(row["valProQuota"].ToString()),
            //            //        Helper.FormatCurrency(row["valTotale"].ToString()),
            //            //        Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
            //            //}

            //            if (nPesoTotal < nPesoSingle)
            //            {
            //                table.Rows.Add(getTipologia(indice), "",
            //                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
            //                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
            //                    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

            //                tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

            //                Boolean bPass = false;
            //                foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
            //                {
            //                    if (bPass)
            //                        table.Rows.Add(row["FinalitaTipologia"],
            //                            row["numImmobili"],
            //                            Helper.FormatCurrency(row["valProQuota"].ToString()),
            //                            Helper.FormatCurrency(row["valTotale"].ToString()),
            //                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
            //                    else
            //                    {
            //                        table.Rows.Add(row["FinalitaTipologia"],
            //                            row["numImmobili"],
            //                            Helper.FormatCurrency(row["valProQuota"].ToString()),
            //                            Helper.FormatCurrency(row["valTotale"].ToString()),
            //                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(row["peso"]) - Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1));
            //                        bPass = true;
            //                    }

            //                }

            //            }
            //            else
            //            {
            //                // VECCHIO CODICE
            //                //table.Rows.Add(getTipologia(indice), "",
            //                //    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
            //                //    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
            //                //    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");
            //                //tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)));

            //                // CODICE PRESENTE al 13.09.2017
            //                //table.Rows.Add(getTipologia(indice), "",
            //                //    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
            //                //    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
            //                //    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(tabellaIndice.ToList()[0]["pesoTipologia"]) + Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1) + "</B>");

            //                //tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal((((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] + Convert.ToDecimal("0,001")) * 100).ToString(), 1)));

            //                //foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
            //                //{
            //                //    table.Rows.Add(row["FinalitaTipologia"],
            //                //        row["numImmobili"],
            //                //        Helper.FormatCurrency(row["valProQuota"].ToString()),
            //                //        Helper.FormatCurrency(row["valTotale"].ToString()),
            //                //        Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
            //                //}

            //                table.Rows.Add(getTipologia(indice), "",
            //                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
            //                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
            //                    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

            //                tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

            //                Boolean bPass = false;
            //                foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
            //                {
            //                    if (bPass)
            //                        table.Rows.Add(row["FinalitaTipologia"],
            //                            row["numImmobili"],
            //                            Helper.FormatCurrency(row["valProQuota"].ToString()),
            //                            Helper.FormatCurrency(row["valTotale"].ToString()),
            //                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
            //                    else
            //                    {
            //                        table.Rows.Add(row["FinalitaTipologia"],
            //                            row["numImmobili"],
            //                            Helper.FormatCurrency(row["valProQuota"].ToString()),
            //                            Helper.FormatCurrency(row["valTotale"].ToString()),
            //                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(row["peso"]) + Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1));
            //                        bPass = true;
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}

            #endregion


            #region Commento per TEST da copia Monitoraggio Nuclei

            #region Controllo Totale e Singoli

            decimal nTipologiaGlobale = 0;
            decimal nPesoGlobale = 0;

            #region  // Ciclo per riadattare Tabella
            decimal nTipologia = 0;
            decimal nPeso = 0;
            #region  // Primo Ciclo Calcolo Pesi Singoli

            foreach (var indice in indiciPagina)
            {
                
                var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(indice));

                if (tabellaIndice != null)
                {
                    foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                    {
                        nPeso = nPeso + ((decimal)row["peso"] * 100);
                    }
                }
            }
            string sUpdate = "";
            if (nPeso != 100)
            {
                var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals("NS"));

                if (tabellaIndice.Count() > 0)
                    sUpdate = "NS";
                else
                { 
                    tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals("I"));
                    if (tabellaIndice.Count() > 0)
                        sUpdate = "I";
                    else
                    { 
                        tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals("S"));
                        if (tabellaIndice.Count() > 0)
                            sUpdate = "S";
                        else
                            sUpdate = "U";
                    }
                }

                tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(sUpdate));

                if (nPeso < 100)
                {                   
                    foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                    {
                        row["peso"] = (decimal)row["peso"] + ((100 - nPeso) / 100);
                        break;
                    }
                }
                else
                {
                    foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                    {
                        row["peso"] = (decimal)row["peso"] - ((nPeso - 100) / 100);
                        break;
                    }
                }
            }
            #endregion

            foreach (var indice in indiciPagina)
            {               
                nTipologia = 0;
                nPeso = 0;
                var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(indice));
                
                if (tabellaIndice != null)
                {
                    nTipologia = (decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100;

                    foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                    {
                        nPeso = nPeso + ((decimal)row["peso"] * 100);
                    }
                    if (nTipologia != nPeso)
                    {
                        foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                        {
                            row["pesoTipologia"] = nPeso / 100;
                        }             
                    }
                }
            }
            // Fine Ciclo
            #endregion

            foreach (var row in dt.Tables[0].AsEnumerable())
            {
                nPesoGlobale = nPesoGlobale + (Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100);
            }
            foreach (var idx in indiciPagina)
            {
                var tabellaGlobale = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(idx));
                nTipologiaGlobale = nTipologiaGlobale + Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaGlobale.ToList()[0]["pesoTipologia"] * 100).ToString(), 1));
            }

            bool bTipologia = false;
            bool bPeso = false;

            //if (nPesoGlobale != 100)
            //    bPeso = true;
            //else
            //{
            //    if (nTipologiaGlobale != 100)
            //        bTipologia = true;
            //}
            if (nPesoGlobale != 100)
                bPeso = true;

            if (nTipologiaGlobale != 100)
                bTipologia = true;

            #endregion

            #region Ciclo Totali = 100 e Singoli = 100
            if (!bTipologia && !bPeso)
            {
                foreach (var indice in indiciPagina)
                {
                    var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(indice));
                    if (tabellaIndice != null)
                    {
                        table.Rows.Add(getTipologia(indice), "",
                            "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                            "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                            "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

                        tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

                        foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                        {
                            table.Rows.Add(row["FinalitaTipologia"],
                                row["numImmobili"],
                                Helper.FormatCurrency(row["valProQuota"].ToString()),
                                Helper.FormatCurrency(row["valTotale"].ToString()),
                                Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                        }
                    }
                }
            }
            #endregion

            #region Ciclo Totali <> 100 e Singoli = 100
            if (bTipologia && !bPeso)
            {
                foreach (var indice in indiciPagina)
                {
                    var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(indice));
                    if (tabellaIndice != null)
                    {
                        // Check su Totali
                        decimal nPesoTotal = Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1));

                        decimal nPesoSingle = 0;
                        foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                        {
                            nPesoSingle = nPesoSingle + (Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100);
                        }

                        // Fine Check
                        if (nPesoTotal == nPesoSingle)
                        {
                            table.Rows.Add(getTipologia(indice), "",
                                "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

                            tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

                            foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                            {
                                table.Rows.Add(row["FinalitaTipologia"],
                                    row["numImmobili"],
                                    Helper.FormatCurrency(row["valProQuota"].ToString()),
                                    Helper.FormatCurrency(row["valTotale"].ToString()),
                                    Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                            }

                        }
                        else
                        {
                            if (nPesoTotal < nPesoSingle)
                            {
                                table.Rows.Add(getTipologia(indice), "",
                                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(tabellaIndice.ToList()[0]["pesoTipologia"]) + Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1) + "</B>");

                                tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal((((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] + Convert.ToDecimal("0,001")) * 100).ToString(), 1)));

                                foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                                {
                                    table.Rows.Add(row["FinalitaTipologia"],
                                        row["numImmobili"],
                                        Helper.FormatCurrency(row["valProQuota"].ToString()),
                                        Helper.FormatCurrency(row["valTotale"].ToString()),
                                        Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                                }
                            }
                            else
                            {
                                table.Rows.Add(getTipologia(indice), "",
                                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(tabellaIndice.ToList()[0]["pesoTipologia"]) - Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1) + "</B>");

                                tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal((((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] - Convert.ToDecimal("0,001")) * 100).ToString(), 1)));

                                foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                                {
                                    table.Rows.Add(row["FinalitaTipologia"],
                                        row["numImmobili"],
                                        Helper.FormatCurrency(row["valProQuota"].ToString()),
                                        Helper.FormatCurrency(row["valTotale"].ToString()),
                                        Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region Ciclo Totali = 100 e Singoli <> 100
            if (!bTipologia && bPeso)
            {
                foreach (var indice in indiciPagina)
                {
                    var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(indice));
                    if (tabellaIndice != null)
                    {
                        // Check su Totali
                        decimal nPesoTotal = Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1));

                        decimal nPesoSingle = 0;
                        foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                        {
                            nPesoSingle = nPesoSingle + (Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100);
                        }

                        // Fine Check
                        if (nPesoTotal == nPesoSingle)
                        {
                            table.Rows.Add(getTipologia(indice), "",
                                "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

                            tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

                            foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                            {
                                table.Rows.Add(row["FinalitaTipologia"],
                                    row["numImmobili"],
                                    Helper.FormatCurrency(row["valProQuota"].ToString()),
                                    Helper.FormatCurrency(row["valTotale"].ToString()),
                                    Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                            }

                        }
                        else
                        {
                            if (nPesoTotal < nPesoSingle)
                            {
                                table.Rows.Add(getTipologia(indice), "",
                                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

                                tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

                                Boolean bPass = false;
                                foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                                {
                                    if (bPass)
                                        table.Rows.Add(row["FinalitaTipologia"],
                                            row["numImmobili"],
                                            Helper.FormatCurrency(row["valProQuota"].ToString()),
                                            Helper.FormatCurrency(row["valTotale"].ToString()),
                                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                                    else
                                    {
                                        table.Rows.Add(row["FinalitaTipologia"],
                                            row["numImmobili"],
                                            Helper.FormatCurrency(row["valProQuota"].ToString()),
                                            Helper.FormatCurrency(row["valTotale"].ToString()),
                                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(row["peso"]) - Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1));
                                        bPass = true;
                                    }
                                }
                            }
                            else
                            {
                                table.Rows.Add(getTipologia(indice), "",
                                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                    "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                    "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(tabellaIndice.ToList()[0]["pesoTipologia"])).ToString(), 4)) * 100, 1) + "</B>");

                                tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal((((decimal)tabellaIndice.ToList()[0]["pesoTipologia"]) * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

                                Boolean bPass = false;
                                foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                                {
                                    if (bPass)
                                    {
                                        table.Rows.Add(row["FinalitaTipologia"],
                                            row["numImmobili"],
                                            Helper.FormatCurrency(row["valProQuota"].ToString()),
                                            Helper.FormatCurrency(row["valTotale"].ToString()),
                                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                                    }
                                    else
                                    {
                                        table.Rows.Add(row["FinalitaTipologia"],
                                            row["numImmobili"],
                                            Helper.FormatCurrency(row["valProQuota"].ToString()),
                                            Helper.FormatCurrency(row["valTotale"].ToString()),
                                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(row["peso"]) + Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1));
                                        bPass = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region Ciclo Totali <> 100 e Singoli <> 100
            if (bTipologia && bPeso)
            {
                foreach (var indice in indiciPagina)
                {
                    var tabellaIndice = dt.Tables[0].AsEnumerable().Where(z => z.Field<string>("usoTipologia").Equals(indice));
                    if (tabellaIndice != null)
                    {
                        // Check su Totali
                        decimal nPesoTotal = Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1));

                        decimal nPesoSingle = 0;
                        foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                        {
                            nPesoSingle = nPesoSingle + (Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100);
                        }

                        // Fine Check
                        if (nPesoTotal == nPesoSingle)
                        {
                            table.Rows.Add(getTipologia(indice), "",
                                "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

                            tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

                            foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                            {
                                table.Rows.Add(row["FinalitaTipologia"],
                                    row["numImmobili"],
                                    Helper.FormatCurrency(row["valProQuota"].ToString()),
                                    Helper.FormatCurrency(row["valTotale"].ToString()),
                                    Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                            }

                        }
                        else
                        { 

                            if (nPesoGlobale > nTipologiaGlobale)
                            {
                                if (nPesoTotal < nPesoSingle)
                                {
                                    table.Rows.Add(getTipologia(indice), "",
                                        "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                        "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                        "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(tabellaIndice.ToList()[0]["pesoTipologia"]) + Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1) + "</B>");

                                    tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal((((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] + Convert.ToDecimal("0,001")) * 100).ToString(), 1)));

                                    foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                                    {
                                        table.Rows.Add(row["FinalitaTipologia"],
                                            row["numImmobili"],
                                            Helper.FormatCurrency(row["valProQuota"].ToString()),
                                            Helper.FormatCurrency(row["valTotale"].ToString()),
                                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                                    }
                                }
                                else
                                {
                                    table.Rows.Add(getTipologia(indice), "",
                                        "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                        "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                        "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(tabellaIndice.ToList()[0]["pesoTipologia"]) - Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1) + "</B>");

                                    tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal((((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] - Convert.ToDecimal("0,001")) * 100).ToString(), 1)));

                                    foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                                    {
                                        table.Rows.Add(row["FinalitaTipologia"],
                                            row["numImmobili"],
                                            Helper.FormatCurrency(row["valProQuota"].ToString()),
                                            Helper.FormatCurrency(row["valTotale"].ToString()),
                                            Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                                    }
                                }
                            }
                            else
                            { 
                                if (nPesoTotal < nPesoSingle)
                                {
                                    table.Rows.Add(getTipologia(indice), "",
                                        "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                        "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                        "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(tabellaIndice.ToList()[0]["pesoTipologia"].ToString(), 4)) * 100, 1) + "</B>");

                                    tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal(((decimal)tabellaIndice.ToList()[0]["pesoTipologia"] * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

                                    Boolean bPass = false;
                                    foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                                    {
                                        if (bPass)
                                            table.Rows.Add(row["FinalitaTipologia"],
                                                row["numImmobili"],
                                                Helper.FormatCurrency(row["valProQuota"].ToString()),
                                                Helper.FormatCurrency(row["valTotale"].ToString()),
                                                Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                                        else
                                        {
                                            table.Rows.Add(row["FinalitaTipologia"],
                                                row["numImmobili"],
                                                Helper.FormatCurrency(row["valProQuota"].ToString()),
                                                Helper.FormatCurrency(row["valTotale"].ToString()),
                                                Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(row["peso"]) - Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1));
                                            bPass = true;
                                        }
                                    }
                                }
                                else
                                {
                                    table.Rows.Add(getTipologia(indice), "",
                                        "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valProQuotaTipologia"].ToString()) + "</B>",
                                        "<B>" + Helper.FormatCurrency(tabellaIndice.ToList()[0]["valTotaleTipologia"].ToString()) + "</B>",
                                        "<B>" + Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(tabellaIndice.ToList()[0]["pesoTipologia"])).ToString(), 4)) * 100, 1) + "</B>");

                                    tableTorta.Rows.Add(indice, getTipologia(indice), Convert.ToDecimal(Helper.FormatDecimal((((decimal)tabellaIndice.ToList()[0]["pesoTipologia"]) * 100).ToString(), 1)), tabellaIndice.ToList()[0]["ord1"]);

                                    Boolean bPass = false;
                                    foreach (var row in tabellaIndice.OrderBy(z => z.Field<int>("ord2")))
                                    {
                                        if (bPass)
                                        {
                                            table.Rows.Add(row["FinalitaTipologia"],
                                                row["numImmobili"],
                                                Helper.FormatCurrency(row["valProQuota"].ToString()),
                                                Helper.FormatCurrency(row["valTotale"].ToString()),
                                                Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(row["peso"].ToString(), 4)) * 100, 1));
                                        }
                                        else
                                        {
                                            table.Rows.Add(row["FinalitaTipologia"],
                                                row["numImmobili"],
                                                Helper.FormatCurrency(row["valProQuota"].ToString()),
                                                Helper.FormatCurrency(row["valTotale"].ToString()),
                                                Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal((Convert.ToDecimal(row["peso"]) + Convert.ToDecimal("0,001")).ToString(), 4)) * 100, 1));
                                            bPass = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #endregion


            DataRow rowTotale = dt.Tables[0].Rows[0];
            tableTotale.Rows.Add("Totale",
                rowTotale["numImmobiliTotale"],
                Helper.FormatCurrency(rowTotale["valProQuotaTotale"].ToString()),
                Helper.FormatCurrency(rowTotale["valTotaleTotale"].ToString()),
                Helper.FormatPercentage(Convert.ToDecimal(Helper.FormatDecimal(rowTotale["pesoTotale"].ToString(), 4)) * 100, 1));

            DataSet ds = new DataSet();
            table.TableName = "sintesi";
            tableTotale.TableName = "sintesiTotale";
            tableTorta.TableName = "sintesiTorta";
            ds.Tables.Add(table);
            ds.Tables.Add(tableTotale);
            ds.Tables.Add(tableTorta);

            return ds;
        }

        public string getTipologia(string tipologia)
        {
            switch (tipologia)
            {
                case "U":
                    return "<B>Uso abitativo</B>";
                case "I":
                    return "<B>Investimento</B>";
                case "S":
                    return "<B>Strumentale</B>";
                case "NS":
                    return "<B>Non specificata</B>";
                default:
                    return "";
            }
        }

        public string getTesto1()
        {
            return "Di seguito si rappresenta la distribuzione del patrimonio immobiliare in base alla finalità con cui l'immobile è detenuto.";
        }

        public ColorPDF getColor(string tipologia)
        {

            switch (tipologia)
            {
                case "<B>Uso abitativo</B>":
                    return new ColorPDF(207, 220, 210);
                case "<B>Investimento</B>":
                    return new ColorPDF(115, 152, 109);
                case "<B>Strumentale</B>":
                    return new ColorPDF(167, 192, 168);
                case "<B>Non specificata</B>":
                    return new ColorPDF(245, 245, 220);
                default:
                    return null;
            }

            //ColorPDF coloriUsoAbitativo = new ColorPDF(207,220,210);
            //ColorPDF coloriStrumentale = new ColorPDF(167,192,168);
            //ColorPDF coloriInvestimento = new ColorPDF(115,152,109);
            //ColorPDF coloriNonSpecificata = new ColorPDF(245, 245, 220);

        }
    }
}
