using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

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

        public DataSectionResult getDataSection(List<SessionStruct> tabelleSessione, string querySql, DataThread dataThread)
        {
            ////Mebaid
            //querySql = "[C6MartPeriodico].PL_S1Patrimonio";
            //// End Mebaid
            FormatNum num = new FormatNum();
            DataSectionResult dsr = new DataSectionResult();
            //int foundIdx = 0;
            DataTable dt = null;

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


            dsr.Esito = dt.Rows.Count;
            if (dt.Rows.Count == 0)
            {
                return dsr;
            }

            toBeFound.Tipo = "Classi Rischio Credito";
            DataRow row;

            DataView ordina = new DataView(dt);
            ordina.Sort = "ordine";

            DataTable tabOrdinata = ordina.ToTable();

            //if (dataThread.TipoReport.ToUpper() == "MONITORAGGIO")
            //    //prendo la prima ed unica riga del datatable
            //    row = tabOrdinata.Rows[0];
            //else
            //{
                if (dataThread.Intermediario.ToUpper() == "BF")
                    row = tabOrdinata.Rows[0];
                else
                {
                    DataRow[] rows = dt.Select(" INTERMEDIARIO  = '" + dataThread.Intermediario.Replace("'", "''") + "'");
                    row = rows[0];
                }
            //}

            DataSetS167 ds167 = new DataSetS167();
            //il colore è bianco
            ds167.RischioCredito.Columns["CounterValue"].Caption = "Controvalore <br> (€) &nbsp; &nbsp; &nbsp; &nbsp;";
            ds167.RischioCredito.Columns["Percentage"].Caption = "Peso <br> (%) &nbsp;";
            DataRow dr = ds167.RischioCredito.NewRow();


            //toBeFound.Codice = "RSKCL4";
            //toBeFound.Codice = "RSKCL5";
            //foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);

            //dr = ds167.RischioCredito.NewRow();
            ////dr["RiskClassName"] = "Classe 1";
            //dr["RiskClassName"] = "Soggetto a valutazione di Rischio Credito";
            ////dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_Class1"]));
            //dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_CreditRisk"]));//V + dataThread.PartiteViaggiantiInv;
            ////dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CLASS1"]), 2, MidpointRounding.AwayFromZero);
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CreditRisk"]), 2, MidpointRounding.AwayFromZero);
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds167.RischioCredito.Rows.Add(dr);


            dr = ds167.RischioCredito.NewRow();
            dr["RiskClassName"] = "Soggetto a Rischio Credito";
            dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_CreditRisk"]));
            dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CreditRisk"]), 2, MidpointRounding.AwayFromZero);
            dr["Red"] = 252;
            dr["Green"] = 202;
            dr["Blue"] = 203;
            ds167.RischioCredito.Rows.Add(dr);


            ////dati per grafico
            //dr = ds167.ChartData.NewRow();
            ////dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CLASS1"]), 2, MidpointRounding.AwayFromZero); //row["AltroCTV"];
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CreditRisk"]), 2, MidpointRounding.AwayFromZero);
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds167.ChartData.Rows.Add(dr);

            //dati per grafico
            dr = ds167.ChartData.NewRow();
            dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_CreditRisk"]), 2, MidpointRounding.AwayFromZero);
            dr["Red"] = 252;
            dr["Green"] = 202;
            dr["Blue"] = 203;
            ds167.ChartData.Rows.Add(dr);



            //#D1DEE0	209	222	224
            //toBeFound.Codice = "RSKCL0";
            //foundIdx = ClsFunzioniGeneriche.findRightColors(toBeFound);

            //dr = ds167.RischioCredito.NewRow();
            ////dr["RiskClassName"] = "Non Applicabile";
            //dr["RiskClassName"] = "Non soggetto a valutazione di Rischio Credito";
            //dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_na"]));
            //dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_na"]), 2);
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds167.RischioCredito.Rows.Add(dr);

            dr = ds167.RischioCredito.NewRow();
            dr["RiskClassName"] = "Non soggetto a Rischio Credito";
            dr["CounterValue"] = num.ConvertNum(Convert.ToDecimal(row["CTV_na"]));
            dr["Percentage"] = Decimal.Round(Convert.ToDecimal(row["PERC_na"]), 2);
            dr["Red"] = 183;
            dr["Green"] = 203;
            dr["Blue"] = 227;
            ds167.RischioCredito.Rows.Add(dr);

            ////dati per grafico
            //dr = ds167.ChartData.NewRow();
            //dr["Percentage"] = Convert.ToDecimal(row["PERC_na"]); //row["AltroCTV"];
            //dr["Red"] = ClsFunzioniGeneriche.Colors[foundIdx].Red;
            //dr["Green"] = ClsFunzioniGeneriche.Colors[foundIdx].Green;
            //dr["Blue"] = ClsFunzioniGeneriche.Colors[foundIdx].Blue;
            //ds167.ChartData.Rows.Add(dr);

            //dati per grafico
            dr = ds167.ChartData.NewRow();
            dr["Percentage"] = Convert.ToDecimal(row["PERC_na"]);
            dr["Red"] = 183;
            dr["Green"] = 203;
            dr["Blue"] = 227;
            ds167.ChartData.Rows.Add(dr);

            if (Convert.ToDecimal(row["CTV_Notcovered"]) > 0)
            {

                // covered row
                DataRow Covered = ds167.PatrimonioCoperto.NewRow();
                Covered["RiskclassName"] = "Patrimonio coperto";

                decimal Total = 0;
                for (int i = 0; i < ds167.RischioCredito.Rows.Count; i++)
                    Total = Total + decimal.Parse(ds167.RischioCredito.Rows[i]["CounterValue"].ToString());

                Covered["CounterValue"] = Total; // +dataThread.PartiteViaggiantiInv;

                decimal TotalPeso = 0;

                //V
                //Algoritmo di approssimazione del centesimo nel caso di patrimonio non coperto
                DataRow tuplaMaggiore = ds167.RischioCredito.Rows[0];
                decimal valoreMaggiore = 0;
                bool bFlag = false;
                for (int i = 0; i < ds167.RischioCredito.Rows.Count; i++)
                {
                    decimal temp = Convert.ToDecimal(ds167.RischioCredito.Rows[i]["Percentage"]);
                    TotalPeso = TotalPeso + temp;
                    if (temp > valoreMaggiore)
                    {
                        tuplaMaggiore = ds167.RischioCredito.Rows[i];
                        valoreMaggiore = temp;
                        bFlag = true;
                    }
                }


                //Not covered row
                DataRow notCovered = ds167.PatrimonioNonCoperto.NewRow();

                /********************* Fix 29-04-2020 cambio dicitura - Pino *************************/
                //notCovered["RiskclassName"] = "Patrimonio non coperto";   // Originale
                notCovered["RiskclassName"] = "Patrimonio non rappresentabile";
                /*************************************************************************************/


                notCovered["CounterValue"] = Convert.ToDecimal(row["CTV_Notcovered"]);  // +dataThread.PartiteViaggiantiInv;
                //notCovered["Percentage"] = Decimal.Round(Convert.ToDecimal(row["Perc_notcovered"]),2,MidpointRounding.AwayFromZero);

                //decimal delta = 100 - Convert.ToDecimal(notCovered["Percentage"]) - TotalPeso;
                decimal delta = 100 - TotalPeso;
                if (delta != 0)
                {
                    if (bFlag)
                    {
                        tuplaMaggiore["Percentage"] = Convert.ToDecimal(tuplaMaggiore["Percentage"]) + delta;
                        TotalPeso += delta;
                    }
                    else
                    {
                        tuplaMaggiore["Percentage"] = Convert.ToDecimal(tuplaMaggiore["Percentage"]);
                        //TotalPeso += delta;
                    }
                }

                ds167.PatrimonioNonCoperto.Rows.Add(notCovered);

                Covered["Percentage"] = TotalPeso;
                ds167.PatrimonioCoperto.Rows.Add(Covered);


            }

            else //Algoritmo di approssimazione 
            {
                //V
                //Algoritmo di approssimazione del centesimo nel caso di patrimonio coperto
                decimal TotalPeso = 0;
                DataRow tuplaMaggiore = ds167.RischioCredito.Rows[0];
                decimal valoreMaggiore = 0;
                for (int i = 0; i < ds167.RischioCredito.Rows.Count; i++)
                {
                    decimal temp = Convert.ToDecimal(ds167.RischioCredito.Rows[i]["Percentage"]);
                    TotalPeso = TotalPeso + temp;
                    if (temp > valoreMaggiore)
                    {
                        tuplaMaggiore = ds167.RischioCredito.Rows[i];
                        valoreMaggiore = temp;
                    }
                }

                decimal delta = 100 - TotalPeso;
                if (delta != 0)
                {
                    tuplaMaggiore["Percentage"] = Convert.ToDecimal(tuplaMaggiore["Percentage"]) + delta;
                }
            }


            FormatNum formatter = new FormatNum();
            // TOTAL ROW
            DataRow drTot = ds167.RischioCreditoTotal.NewRow();
            drTot["Totale"] = "";
            //drTot["CounterValue"] = formatter.ConvertNum(Convert.ToDecimal(row["CTV_TOT"])) + "*"; // +dataThread.PartiteViaggiantiInv;
            decimal totalePartiteViaggianti = dataThread.PartiteViaggiantiInvestimento + dataThread.PartiteViaggiantiDisinvestimento;
            if (
                (dataThread.TotalNegativeCurrentAccountValue < 0 || totalePartiteViaggianti != 0 || dataThread.TotalSelfNegCurrentAccountValue!=0)
                &&
                (dataThread.Intermediario.ToUpper() == "COMPLESSIVO" || dataThread.Intermediario.ToUpper() == "BF")
                &&
                (dataThread.TipoReport.ToUpper() == TipoReport.DIAGNOSI.ToString())
                )
            {
                drTot["CounterValue"] = formatter.ConvertNum(Convert.ToDecimal(row["CTV_TOT"])) + "*";
            }
            else if (
                (dataThread.TotalNegativeCurrentAccountValue < 0 || totalePartiteViaggianti != 0)
                &&
                (dataThread.TipoReport.ToUpper() == TipoReport.MONITORAGGIO.ToString())
                )
            {
                drTot["CounterValue"] = formatter.ConvertNum(Convert.ToDecimal(row["CTV_TOT"])) + "*";
            }
            else
            {
                drTot["CounterValue"] = formatter.ConvertNum(Convert.ToDecimal(row["CTV_TOT"]));
            }
            //drTot["CounterValue"] = row["CTV_TOT"].ToString() + "(*)";
            if (Convert.ToDecimal(row["CTV_Notcovered"]) == 0)
                drTot["Percentage"] = 100;

            ds167.RischioCreditoTotal.Rows.Add(drTot);

            dsr.DatiSezione = ds167;
            dsr.Esito = dt.Rows.Count;
            return dsr;
        }
        #endregion
    }
}