using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections;
using System.Text;
using PDFGenerator.BusinessLayer.DataSection;
using PDFGenerator.BusinessLayer;
using PDFGenerator;

namespace PDFGenerator.BusinessLayer.DataSection
{
    public class DSFD159PatrimonioFinanziario : IDataSection
    {
        #region IDataSection Members
        public StructColor toBeFound = new StructColor();

        public DataSectionResult getDataSection(List<SessionStruct> tabelleSessione, string querySql, DataThread dataThread)
        {

            try
            {
                DataSectionResult dsr = new DataSectionResult();

                Decimal ctvTotale = 0;

                DataTable dt = SectionManager.GetDataSection(tabelleSessione, querySql, dataThread);

                DataSetS159 ds159 = new DataSetS159();
                DataRow dr;

                toBeFound.Tipo = "MacroAssetClass";
                ds159.MacroAssetClass.Columns["Controvalore"].Caption = "Controvalore <br> (€) &nbsp; &nbsp; &nbsp; &nbsp;";
                ds159.MacroAssetClass.Columns["Percentuale"].Caption = "Peso <br> (%)";

                decimal patrimonioBancaFideuramCTV = 0;
                decimal cc = 0;
                string banca = string.Empty;
                decimal totalePartiteViaggianti = 0;

                //V
                decimal residuo = dataThread.TotaleS57;
                if (dataThread.ContoCorrente < 0)
                    residuo -= dataThread.ContoCorrente;

                DataRow tuplaMaggiore = null;
                decimal controValoreMaggiore = 0;
                DataRow tuplaPercMaggiore = null;
                decimal percMaggiore = 0;
                decimal residuoPerc = 100;
                //
                foreach (DataRow row in dt.Rows)
                {
                    dr = ds159.MacroAssetClass.NewRow();
                    dr["Descrizione"] = row["assetclassname"];
                    //V
                    decimal temp = Convert.ToDecimal(row["Controvalore"]);
                    dr["Controvalore"] = temp.ToString();
                    if (temp > controValoreMaggiore)
                    {
                        controValoreMaggiore = temp;
                        tuplaMaggiore = dr;
                    }
                    residuo -= temp;

                    decimal tempPerc = Convert.ToDecimal(row["Percentuale"]);
                    tempPerc = decimal.Round(tempPerc, 2);
                    dr["Percentuale"] = tempPerc.ToString();
                    if (tempPerc > percMaggiore)
                    {
                        percMaggiore = tempPerc;
                        tuplaPercMaggiore = dr;
                    }
                    residuoPerc -= tempPerc;
                    //
                    if (patrimonioBancaFideuramCTV == 0)
                        patrimonioBancaFideuramCTV = dataThread.Patrimoniobancafideuramctv;
                    toBeFound.Codice = row["AssetClassId"].ToString();
                    if (cc == 0)
                        cc = dataThread.ContoCorrente;
                    if (banca == string.Empty)
                        banca = (string)row["banca"];
                    if (totalePartiteViaggianti == 0)
                        totalePartiteViaggianti = dataThread.PartiteViaggiantiInvestimento + dataThread.PartiteViaggiantiDisinvestimento;
                    int foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);

                    dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
                    dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
                    dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;

                    ctvTotale += (Decimal)row["Controvalore"];
                    ds159.MacroAssetClass.Rows.Add(dr);
                }
                //V
                ctvTotale += residuo;

                if (residuo != 0 && tuplaMaggiore != null)
                {
                    decimal temp = Convert.ToDecimal(tuplaMaggiore["Controvalore"]);
                    temp += residuo;
                    tuplaMaggiore["Controvalore"] = temp.ToString();
                }

                if (residuoPerc != 0 && tuplaPercMaggiore != null)
                {
                    decimal temp = Convert.ToDecimal(tuplaPercMaggiore["Percentuale"]);
                    temp += residuoPerc;
                    tuplaPercMaggiore["Percentuale"] = temp.ToString();
                }

                //
                DataSetS159.PatrimonioNonRappresentabileRow drPatrimonioNonRappresentabile;
                drPatrimonioNonRappresentabile = ds159.PatrimonioNonRappresentabile.NewPatrimonioNonRappresentabileRow();
                drPatrimonioNonRappresentabile.Descrizione = Resource.PatrimonioNonRappresentabile_label;
                //"Patrimonio non rappresentabile";

                //Arrotondamento i totali vengono presi da query differenti e avolte c'è la differenza di un decimale
                Decimal ctvNonRappr = dataThread.PatrimonioNonRappresentabile;
                if (ctvNonRappr <= 0)
                {
                    drPatrimonioNonRappresentabile.ControValore = 0;
                    ctvNonRappr = 0;
                }
                else
                {
                    drPatrimonioNonRappresentabile.ControValore = ctvNonRappr;
                    ds159.PatrimonioNonRappresentabile.Rows.Add(drPatrimonioNonRappresentabile);
                }

                DataSetS159.ContoCorrenteBancaFideuramRow drContoCorrenteBancaFideuramRow;
                drContoCorrenteBancaFideuramRow = ds159.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();
                // MZ
                drContoCorrenteBancaFideuramRow.Descrizione = "C/C a saldo negativo"; // +banca;
                drContoCorrenteBancaFideuramRow.ControValore = cc;

                if (drContoCorrenteBancaFideuramRow.ControValore < 0)
                    ds159.ContoCorrenteBancaFideuram.Rows.Add(drContoCorrenteBancaFideuramRow);

                // MIOFOGLIO 20181130

                DataSetS159.LineaSelfRow drLineaSelfRow;

                if ((dataThread != null) && (dataThread.SelfNegativeValue != null))
                {

                    foreach (var item in dataThread.SelfNegativeValue)
                    {
                        drLineaSelfRow = ds159.LineaSelf.NewLineaSelfRow();
                        drLineaSelfRow.Descrizione = item.Item1.Equals("XY") ? "Liquidità negativa \"Linee GP Eligo\"" : "Liquidità negativa \"IL MF - Liquidita\"";
                        drLineaSelfRow.ControValore = item.Item3;
                        ds159.LineaSelf.Rows.Add(drLineaSelfRow);
                    }
                }

                //DataSetS159.LineaSelfRow drLineaSelfRow;
                //drLineaSelfRow = ds159.LineaSelf.NewLineaSelfRow();
                //// MZ
                //drLineaSelfRow.Descrizione = "Liquidità negativa \"Linee GP Eligo\""; // +banca;
                //drLineaSelfRow.ControValore = dataThread.TotalSelfNegCurrentAccountValue;

                //if (drLineaSelfRow.ControValore < 0)
                //    ds159.LineaSelf.Rows.Add(drLineaSelfRow);

                //--MIOFOGLIO 20181130


                DataSetS159.PartiteViaggiantiRow drPartiteViaggiantiRow;
                drPartiteViaggiantiRow = ds159.PartiteViaggianti.NewPartiteViaggiantiRow();
                drPartiteViaggiantiRow.Descrizione = Resource.PartiteViaggianti;
                //"Investimenti in corso";
                drPartiteViaggiantiRow.ControValore = totalePartiteViaggianti;

                if (drPartiteViaggiantiRow.ControValore > 0)
                    ds159.PartiteViaggianti.Rows.Add(drPartiteViaggiantiRow);

                bool totalePresente = true;
                string totRappr = "TOTALE RAPPRESENTATO";
                if (drContoCorrenteBancaFideuramRow.ControValore >= 0 && drPartiteViaggiantiRow.ControValore <= 0 && ctvNonRappr == 0 && dataThread.TotalSelfNegCurrentAccountValue == 0)
                {
                    totalePresente = false;
                    totRappr = "TOTALE";
                }

                DataRow drTot = ds159.MacroAssetTotale.NewRow();
                drTot["Totale"] = totRappr;
                drTot["Controvalore"] = ctvTotale;
                drTot["Percentuale"] = 100.00;
                ds159.MacroAssetTotale.Rows.Add(drTot);


                if (totalePresente)
                {
                    DataSetS159.TotaleRow drTotale;
                    drTotale = ds159.Totale.NewTotaleRow();
                    //drTotale.Descrizione = "TOTALE";
                    if (dataThread.Rete.ToUpper() == "S")
                        drTotale.Descrizione = "Patrimonio Sanpaolo Invest";
                    else if (dataThread.Rete.ToUpper() == "F")
                    {
                        //FC 26062015 Aggionamento nuova Ragione Sociale
                        //drTotale.Descrizione = "Patrimonio Banca Fideuram";
                        drTotale.Descrizione = "Patrimonio Fideuram";
                    }
                    else drTotale.Descrizione = "Patrimonio IW Private Inv.";

                    //modifica luca 11/09/08
                    //i dati in caso di cc positivo sono già comprensivi del c/c quindi non va sommato di nuovo
                    //drTotale.ControValore = (ctvTotale + drPatrimonioNonRappresentabile.ControValore + drContoCorrenteBancaFideuramRow.ControValore);
                    drTotale.ControValore = (ctvTotale + ctvNonRappr);
                    if (drContoCorrenteBancaFideuramRow.ControValore < 0)
                        drTotale.ControValore += drContoCorrenteBancaFideuramRow.ControValore;
                    drTotale.ControValore += dataThread.TotalSelfNegCurrentAccountValue;
                    drTotale.ControValore += totalePartiteViaggianti;
                    ds159.Totale.Rows.Add(drTotale);
                }



                #region Risorse Percentuali
                Decimal valorePrecentuale = 0;

                DataSetS159.RisorsePercentualiRow rowRisorsePercentuali = ds159.RisorsePercentuali.NewRisorsePercentualiRow();

                if (patrimonioBancaFideuramCTV == 0)
                    rowRisorsePercentuali.ValorePercentuale = 0;
                else
                {
                    valorePrecentuale = (ctvTotale / patrimonioBancaFideuramCTV) * 100;
                    rowRisorsePercentuali.ValorePercentuale = System.Math.Round(valorePrecentuale, 2, MidpointRounding.ToEven);
                }

                ds159.RisorsePercentuali.AddRisorsePercentualiRow(rowRisorsePercentuali);
                #endregion
                //Normalizzo le percentuali
                FormatNum conv = new FormatNum();
                if (dt.Rows.Count != 0)
                    conv.NormalizePerc(ds159.MacroAssetClass, "Percentuale");
                //========================================================

                dsr.DatiSezione = ds159;
                dsr.Esito = dt.Rows.Count;

                /*** ATTENAZIONE solo per test DirectBank 21/03/2023 - Pino ***/
                //if (ctvTotale == 0)
                //    dsr.Esito = 0;
                /**************************************************************/

                return dsr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion
    }
}