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;
using NLog;

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

        public DataSectionResult getDataSection(List<SessionStruct> tabelleSessione, string querySql, DataThread dataThread)
        {
            NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

            try
            {
                DataSectionResult dsr = new DataSectionResult();

                Decimal ctvTotale = 0;

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

                DataSetS10 ds10 = new DataSetS10();
                DataRow dr;

                toBeFound.Tipo = "MacroAssetClass";
                ds10.MacroAssetClass.Columns["Controvalore"].Caption = "Controvalore <br> (€) &nbsp; &nbsp; &nbsp; &nbsp;";
                ds10.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;
                //
                int i = 1;
                foreach (DataRow row in dt.Rows)
                {
                    dr = ds10.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;

                    logger.Debug(string.Concat(i.ToString(), " Controvalore passato ", row["Controvalore"].ToString()));

                    decimal tempPerc = Convert.ToDecimal(row["Percentuale"]);
                    tempPerc = decimal.Round(tempPerc, 2);
                    dr["Percentuale"] = tempPerc.ToString();
                    if (tempPerc > percMaggiore)
                    {
                        percMaggiore = tempPerc;
                        tuplaPercMaggiore = dr;
                    }
                    residuoPerc -= tempPerc;

                    logger.Debug(string.Concat(i.ToString(), " Percentuale passato ", row["Percentuale"].ToString()));

                    //
                    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"];
                    ds10.MacroAssetClass.Rows.Add(dr);

                    i += 1;
                }
                //V
                ctvTotale += residuo;

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

                /* Commentata per problema di log con campi nulli Trimestrale 04-2021 - Pino */
                //logger.Debug(string.Concat("TuplaMaggiore ", tuplaMaggiore["Controvalore"].ToString()));

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

                /* Commentata per problema di log con campi nulli Trimestrale 04-2021 - Pino */
                //logger.Debug(string.Concat("TuplaPercMaggiore ", tuplaMaggiore["Percentuale"].ToString()));

                //
                DataSetS10.PatrimonioNonRappresentabileRow drPatrimonioNonRappresentabile;
                drPatrimonioNonRappresentabile = ds10.PatrimonioNonRappresentabile.NewPatrimonioNonRappresentabileRow();

                try
                {
                    drPatrimonioNonRappresentabile.Descrizione = Resource.PatrimonioNonRappresentabile_label;
                }
                catch (StrongTypingException exStrong)
                {
                    logger.Debug(string.Concat("Descrizione Patrimonio Non Rappresentabile StrongTypingException ", exStrong.Message));
                }
                catch (Exception ex)
                {
                    logger.Debug(string.Concat("Descrizione Patrimonio Non Rappresentabile errore generico ", ex.Message));
                }

                //"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;
                    ds10.PatrimonioNonRappresentabile.Rows.Add(drPatrimonioNonRappresentabile);
                }

                logger.Debug(string.Concat("Patrimonio non rappresentabile ", ctvNonRappr.ToString()));

                DataSetS10.ContoCorrenteBancaFideuramRow drContoCorrenteBancaFideuramRow;
                drContoCorrenteBancaFideuramRow = ds10.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();

                try
                {
                    drContoCorrenteBancaFideuramRow.Descrizione = "C/C a saldo negativo"; // +banca;
                    drContoCorrenteBancaFideuramRow.ControValore = cc;
                    if (drContoCorrenteBancaFideuramRow.ControValore < 0)
                        ds10.ContoCorrenteBancaFideuram.Rows.Add(drContoCorrenteBancaFideuramRow);
                }
                catch (StrongTypingException exStrong)
                {
                    logger.Debug(string.Concat("C/C a saldo negativo StrongTypingException ", exStrong.Message));
                }
                catch (Exception ex)
                {
                    logger.Debug(string.Concat("C/C a saldo negativo errore generico ", ex.Message));
                }


                logger.Debug(string.Concat("C/C a saldo negativo ", cc.ToString()));


                // MIOFOGLIO 20181206

                DataSetS10.ContoCorrenteBancaFideuramRow drLineaSelfRow;
                drLineaSelfRow = ds10.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();


                try
                {
                    if ((dataThread != null) && (dataThread.SelfNegativeValue != null))
                        logger.Debug(string.Concat("Liquidità negativa presente"));
                    else
                    {
                        if (dataThread.SelfNegativeValue == null)
                            logger.Debug(string.Concat("Liquidità negativa NULL"));
                    }


                    if ((dataThread != null) && (dataThread.SelfNegativeValue != null))
                    {
                        if (dataThread.SelfNegativeValue.Count > 0)
                        {
                            try
                            {
                                foreach (var r in dataThread.SelfNegativeValue)
                                {

                                    logger.Debug(string.Concat("Liquidità negativa ciclo - Descrizione ", r.Item2));
                                    logger.Debug(string.Concat("Liquidità negativa ciclo - Controvalore ", r.Item3));

                                    drLineaSelfRow = ds10.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();

                                    drLineaSelfRow.Descrizione = string.Format("Liquidità negativa {0}", r.Item2.ToString());//"Liquidità negativa \"Linee GP Eligo\"";
                                    drLineaSelfRow.ControValore = r.Item3;//dataThread.TotalSelfNegCurrentAccountValue;

                                    if (drLineaSelfRow.ControValore < 0)
                                        ds10.ContoCorrenteBancaFideuram.Rows.Add(drLineaSelfRow);
                                }
                            }
                            catch (Exception ex)
                            {
                                logger.Debug(string.Concat("Liquidità negativa errore ciclo ", ex.Message));
                            }

                        }

                        logger.Debug(string.Concat("Liquidità negativa ", dataThread.SelfNegativeValue.Count.ToString()));
                    }
                }
                catch (StrongTypingException exStrong)
                {
                    logger.Debug(string.Concat("Liquidità negativa StrongTypingException ", exStrong.Message));
                }
                catch (Exception ex)
                {
                    logger.Debug(string.Concat("Liquidità negativa errore generico ", ex.Message));
                }

                //DataSetS10.ContoCorrenteBancaFideuramRow drLineaSelfRow;
                //drLineaSelfRow = ds10.ContoCorrenteBancaFideuram.NewContoCorrenteBancaFideuramRow();
                //drLineaSelfRow.Descrizione = "Liquidità negativa \"Linee GP Eligo\"";
                //drLineaSelfRow.ControValore = dataThread.TotalSelfNegCurrentAccountValue;
                //if (drLineaSelfRow.ControValore < 0)
                //    ds10.ContoCorrenteBancaFideuram.Rows.Add(drLineaSelfRow);

                //--MIOFOGLIO 20181206

                DataSetS10.PartiteViaggiantiRow drPartiteViaggiantiRow;
                drPartiteViaggiantiRow = ds10.PartiteViaggianti.NewPartiteViaggiantiRow();

                if (Resource.PartiteViaggianti != null)
                    logger.Debug("Partite viaggianti non NULL");
                else
                    logger.Debug("Partite Viagginati NULL");

                logger.Debug("Partite Viaggianti Inizio");
                //logger.Debug(string.Concat("Partite Viaggianti ", Resource.PartiteViaggianti));

                drPartiteViaggiantiRow.Descrizione = Resource.PartiteViaggianti;
                logger.Debug(string.Concat("Partite Viaggianti Descrizione ", drPartiteViaggiantiRow.Descrizione));

                //"Investimenti in corso";
                drPartiteViaggiantiRow.ControValore = totalePartiteViaggianti;
                logger.Debug(string.Concat("Partite Viaggianti Controvalore ", drPartiteViaggiantiRow.ControValore.ToString()));

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

                logger.Debug("Partite Viaggianti Fine ");

                bool totalePresente = true;
                string totRappr = "TOTALE RAPPRESENTATO";

                // MIOFOGLIO 20181206

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

                logger.Debug(string.Concat("TOTALE RAPPRESENTATO ", drContoCorrenteBancaFideuramRow.ControValore.ToString()));
                logger.Debug(string.Concat("TOTALE RAPPRESENTATO ", ctvNonRappr.ToString()));

                //if (drContoCorrenteBancaFideuramRow.ControValore >= 0 &&
                //       drLineaSelfRow.ControValore >= 0 &&
                //    drPartiteViaggiantiRow.ControValore <= 0 && ctvNonRappr == 0)
                //{
                //    totalePresente = false;
                //    totRappr = "TOTALE";
                //}

                //--MIOFOGLIO 20181206

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


                if (totalePresente)
                {
                    DataSetS10.TotaleRow drTotale;
                    drTotale = ds10.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;
                    //fine modifica luca 11/09/08
                    drTotale.ControValore += totalePartiteViaggianti;
                    drTotale.ControValore += dataThread.TotalSelfNegCurrentAccountValue;
                    ds10.Totale.Rows.Add(drTotale);
                }



                #region Risorse Percentuali
                Decimal valorePrecentuale = 0;

                DataSetS10.RisorsePercentualiRow rowRisorsePercentuali = ds10.RisorsePercentuali.NewRisorsePercentualiRow();

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

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

                logger.Debug(string.Concat("Risorse Percentuali ", valorePrecentuale.ToString()));
                //========================================================

                dsr.DatiSezione = ds10;
                dsr.Esito = dt.Rows.Count;
                if (ctvTotale == 0)
                    dsr.Esito = 1; //dsr.Esito = 0;

                int xCCBF = 1;
                foreach (DataRow item in ds10.ContoCorrenteBancaFideuram.Rows)
                {
                    logger.Debug(string.Concat(xCCBF.ToString(), " ", item["Descrizione"].ToString(), " ", item["ControValore"].ToString()));

                    xCCBF += 1;
                }
                int xPNR = 1;
                foreach (DataRow item in ds10.PatrimonioNonRappresentabile.Rows)
                {
                    logger.Debug(string.Concat(xPNR.ToString(), " ", item["Descrizione"].ToString(), " ", item["ControValore"].ToString()));

                    xPNR += 1;
                }

                int xTot = 1;
                foreach (DataRow item in ds10.Totale.Rows)
                {
                    logger.Debug(string.Concat(xTot.ToString(), " ", item["Descrizione"].ToString(), " ", item["ControValore"].ToString()));

                    xTot += 1;
                }

                int xPV = 1;
                foreach (DataRow item in ds10.Totale.Rows)
                {
                    logger.Debug(string.Concat(xPV.ToString(), " ", item["Descrizione"].ToString(), " ", item["ControValore"].ToString()));

                    xPV += 1;
                }


                logger.Debug(string.Concat("Fine DSFD10PatrimonioFinanziario, Esito -- ", dsr.Esito));
                return dsr;
            }
            catch (Exception ex)
            {
                logger.Error("Catch DSFD10PatrimonioFinanziario: ", ex.Message);

                throw ex;
            }
        }

        #endregion
    }
}