using System;
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 PDFGenerator.BusinessLayer.DataSection;
using PDFGenerator.BusinessLayer;
using System.Collections.Generic;
using NLog;

namespace PDFGenerator.BusinessLayer.DataSection
{
    public class DSFD148DistribuzioneAssetClass : IDataSection
    {
        private StructColor toBeFound = new StructColor();
        NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        public DSFD148DistribuzioneAssetClass()
        {
        }

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

            try
            {
                DataSectionResult dsr = new DataSectionResult();

                Decimal ctvTotale = 0;

                /*** Forzatura per Direct Banck da togliere 12/03/2023 - Pino ****/
                //querySql = "[C6MartPeriodico].PL_MP_S148DistribuzioneAssetClass";
                /*****************************************************************/

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

                DataSetS148 ds148 = new DataSetS148();
                DataRow dr;

                toBeFound.Tipo = "AssetClass";
                ds148.MacroAssetClass.Columns["Descrizione"].Caption = "Asset class";
                ds148.MacroAssetClass.Columns["Controvalore"].Caption = "Controvalore <br> (€) &nbsp; &nbsp; &nbsp; &nbsp;";
                ds148.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 = ds148.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"];
                    ds148.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();
                }

                //
                DataSetS148.PatrimonioNonRappresentabileRow drPatrimonioNonRappresentabile;
                drPatrimonioNonRappresentabile = ds148.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;
                    ds148.PatrimonioNonRappresentabile.Rows.Add(drPatrimonioNonRappresentabile);
                }

                DataSetS148.ContoCorrenteBancaFideuramRow drContoCorrenteBancaFideuramRow;
                drContoCorrenteBancaFideuramRow = ds148.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();
                drContoCorrenteBancaFideuramRow.Descrizione = "C/C a saldo negativo";
                drContoCorrenteBancaFideuramRow.ControValore = cc;
                //if (drContoCorrenteBancaFideuramRow.ControValore < 0)
                //    ds148.ContoCorrenteBancaFideuram.Rows.Add(drContoCorrenteBancaFideuramRow); // Andrea modifica per eliminare righe


                DataSetS148.ContoCorrenteBancaFideuramRow drLineaSelfRow;
                drLineaSelfRow = ds148.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();
                drLineaSelfRow.Descrizione = "Liquidità negativa \"Linee GP Eligo\"";
                drLineaSelfRow.ControValore = dataThread.TotalSelfNegCurrentAccountValue;
                //if (dataThread.TotalSelfNegCurrentAccountValue < 0)
                //    ds148.ContoCorrenteBancaFideuram.Rows.Add(drLineaSelfRow); // Andrea modifica per eliminare righe

                DataSetS148.PartiteViaggiantiRow drPartiteViaggiantiRow;
                drPartiteViaggiantiRow = ds148.PartiteViaggianti.NewPartiteViaggiantiRow();
                drPartiteViaggiantiRow.Descrizione = Resource.PartiteViaggianti;
                //"Investimenti in corso";
                drPartiteViaggiantiRow.ControValore = totalePartiteViaggianti;
                //if (drPartiteViaggiantiRow.ControValore > 0)
                //    ds148.PartiteViaggianti.Rows.Add(drPartiteViaggiantiRow);  // Andrea modifica per eliminare righe

                //   bool totalePresente = true; //Forzatura Andrea 
                bool totalePresente = false;
                // string totRappr = "TOTALE RAPPRESENTATO";
                string totRappr = "TOTALE"; // Modifica Andrea
                if (drContoCorrenteBancaFideuramRow.ControValore >= 0
                    && drPartiteViaggiantiRow.ControValore <= 0
                    && drLineaSelfRow.ControValore >= 0
                    && ctvNonRappr == 0)
                {
                    totalePresente = false;
                    totRappr = "TOTALE";
                }

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


                if (totalePresente)
                {
                    DataSetS148.TotaleRow drTotale;
                    drTotale = ds148.Totale.NewTotaleRow();
                    drTotale.Descrizione = "TOTALE";
                    //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;
                    if (drLineaSelfRow.ControValore < 0)
                        drTotale.ControValore += drLineaSelfRow.ControValore;
                    //fine modifica luca 11/09/08
                    drTotale.ControValore += totalePartiteViaggianti;
                    ds148.Totale.Rows.Add(drTotale);
                }



                #region Risorse Percentuali
                Decimal valorePrecentuale = 0;

                DataSetS148.RisorsePercentualiRow rowRisorsePercentuali = ds148.RisorsePercentuali.NewRisorsePercentualiRow();

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

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

                dsr.DatiSezione = ds148;
                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)
            {
                logger.Error(ex);
                throw ex;
            }
        }
        #endregion

    }
}