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 ceTe.DynamicPDF;
using ceTe.DynamicPDF.Text;
using PDFGenerator.Presentation.Section.Tables;
using PDFGenerator.BusinessLayer.DataSection;
using PDFGenerator.BusinessLayer;
using ContrattoSei.Utilities;
using ceTe.DynamicPDF.PageElements;
using DataAccessLayer;
using System.Collections.Generic;

namespace PDFGenerator.Presentation.Section
{
    class S178 : ISezione
    {


        private string _header = "";

        public string Header
        {
            get { return _header; }
            set { _header = value; }
        }


        private TipoReport _tipologiaReport;
        public TipoReport TipologiaReport
        {
            get { return _tipologiaReport; }
            set { _tipologiaReport = value; }
        }

        private string _testoIntroduttivo = string.Empty;
        public string TestoIntroduttivo
        {
            get { return _testoIntroduttivo; }
            set { _testoIntroduttivo = value; }
        }

        private string _testoChiusura = string.Empty;

        public static bool? isAdeguato;
        public string TestoChiusura
        {
            get { return _testoChiusura; }
            set { _testoChiusura = value; }
        }


        public S178()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region ISezione Members

        public void writeSezione(DataThread dataThread)
        {
            isAdeguato = null;
            DocumentPDF document = dataThread.DocumentPDF;
            DataSetS178 set = (DataSetS178)dataThread.Data.DatiSezione;

            ceTe.DynamicPDF.Merger.ImportedPage page = document.getCurrentPage();

            document.LastSectionCheckIn = "S178";

            //page.Elements.Add(new ceTe.DynamicPDF.PageElements.Label(document.getLastPos().ToString(), 0, document.getLastPos(), 200, 50));

            document.setSezTitoloDiagnosi(dataThread.SezioneReport.Titolo);

            //MIFID2 20180521 Gestione testo alternativo alla tabella degli indicatori, nel caso non vi fossero dati disponibili
            if (set.Tables["IndicatoriEsito"].Rows.Count > 0)
            {
                string tempTesto = dataThread.SezioneReport.TestoIntroduttivo;
                //if (dataThread.Rete.ToUpper() == "S")
                //    tempTesto = tempTesto.Replace("Fideuram", "Sanpaolo Invest");

                document.setChapterHeader(tempTesto.Replace("$/Banca/$", dataThread.NomeRete).Replace("Sanpaolo Invest", "la Banca"), 0, 520, 8);

                //La nota è stata spostata nella S184 come da requisiti 20230116_ReportDiagnosi Sei_Fid_MUA+ESG.pptx 27 lug 2023
                string nota = "";
                if (clienteAdeguato(dataThread.Rete, dataThread.CodiceFiscale, dataThread.Periodico))
                {
                    isAdeguato = true;
                    nota = dataThread.SezioneReport.Nota;
                }
                else
                    nota = dataThread.SezioneReport.NotaAlternativa;

                if (string.IsNullOrEmpty(document.NotaPieDiPagina))
                    document.NotaPieDiPagina = "";

                document.setHeaderSpace(0);

                DatiTabella datitab = new DatiTabella();
                Tabella tab = new Tabella(document.getMargineLeft(), document.getLastPos());
                if (dataThread.TipoReport.ToUpper() == "DIAGNOSI") tab.HeaderFont = 8;
                tab.Header = true;
                tab.LineaFineTabella = true;

                datitab.table = set.Tables["IndicatoriEsito"];

                datitab.table.Columns.Remove("Adeguato");

                int count = datitab.table.Rows.Count;
                if (dataThread.Rete == "W")
                    for (int i = 0; i < count; i++)
                    {
                        DataRow riga = datitab.table.Rows[i];
                        DataRow nuovaRiga = datitab.table.NewRow();
                        nuovaRiga["Esito"] = riga["Esito"].ToString().Replace("Banca", "Società");
                        foreach (DataColumn colonna in datitab.table.Columns)
                        {
                            if (colonna.ColumnName != "Esito")
                            {
                                nuovaRiga[colonna.ColumnName] = riga[colonna.ColumnName];
                            }
                        }
                        //datitab.table.Rows.Add(nuovaRiga);
                        //datitab.table.Rows.Remove(riga);
                        datitab.table.Rows.InsertAt(nuovaRiga, i);
                        datitab.table.Rows.RemoveAt(i + 1);
                    }

                tab.Datasource = datitab.table;

                datitab.setY(document.getLastPos());
                //datitab.setIsLinee(1);

                //tab.Colonne.Add(new Colonna("Indicatore", "Indicatore di valutazione", 140, TipoAllineamento.SINISTRA, true, 8, false));
                //tab.Colonne.Add(new Colonna("ImmagineSiNo", "Adeguato", 60, TipoAllineamento.SINISTRA, false, 8, false, TipoColonna.IMMAGINE));
                //tab.Colonne.Add(new Colonna("Esito", addLeftPad("Descrizione esito", 25), 320, TipoAllineamento.SINISTRA, false, 7, false));

                tab.Colonne.Add(new Colonna("Indicatore", "Indicatore di valutazione", 110, TipoAllineamento.SINISTRA, true, 7, false));
                tab.Colonne.Add(new Colonna("ImmagineSiNo", "Adeguato", 60, TipoAllineamento.SINISTRA, false, 7, false, TipoColonna.IMMAGINE));
                tab.Colonne.Add(new Colonna("Esito", addLeftPad("Descrizione esito", 34), 350, TipoAllineamento.SINISTRA, false, 7, false));

                tab.AltezzaCella = 30;

                datitab.setCellSpace(0);

                //setta posizione tabella
                tab.Draw(datitab, document, true, false); //richiama la Draw con l'opzione autoHeight=true

                //float dim = datitab.GetRowDim() * (datitab.getNumRow() + 1);

                float dim = datitab.GetTotalRowsDim() - 10;

                //float dim = datitab.GetRowDim() * (datitab.getNumRow() + 1) - 24;

                //La nota è stata spostata nella S184 come da requisiti 20230116_ReportDiagnosi Sei_Fid_MUA+ESG.pptx 27 lug 2023
                if (!string.IsNullOrEmpty(nota))
                {
                    //20180829 La nota veniva sovrapposta alla freccia di cambio pagina, tirata un po' più su
                    //FormattedTextArea text = new FormattedTextArea(nota, document.getMargineLeft(), document.getLastPos() + dim, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                    FormattedTextArea text = new FormattedTextArea(nota, document.getMargineLeft(), document.getLastPos() + dim - 5, 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 7, false);
                    //--20180829
                    text.Height = text.GetRequiredHeight();
                    text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Justify;
                    page.Elements.Add(text);
                }

                //document.setLastPos(document.getLastPos() + dim + 10);

                //document.setLastPos(document.getLastPos() - 800);

                //La sezione cambia pagina solo in caso di Diagnosi
                if (dataThread.TipoReport.ToUpper() == "DIAGNOSI")
                    document.setLastPos(document.getLastPos() - 800);
                else
                    document.addPage();
            }
            else
            {
                string testoAlternativo = set.Tables["Testi"].Rows[0]["Testo"].ToString().Replace("$/Banca/$", dataThread.NomeRete).Replace("Sanpaolo", "Fideuram S.p.A., commercializzato tramite la rete di private banker Sanpaolo Invest");
                //if (dataThread.Rete.ToUpper() == "S")
                //    tempTesto = tempTesto.Replace("Fideuram", "Sanpaolo Invest");

                //document.setChapterHeader(testoAlternativo.Replace("$/Banca/$", dataThread.NomeRete), 0, 520, 8);

                FormattedTextArea text = new FormattedTextArea(testoAlternativo, document.getMargineLeft(), document.getLastPos(), 510, 50, new ceTe.DynamicPDF.FontFamily("pipp", Globals.OpenTypeFontVerdana, Globals.OpenTypeFontVerdanaB, Globals.OpenTypeFontVerdanaZ, Globals.OpenTypeFontVerdanaZ), 8, true);
                text.Height = text.GetRequiredHeight();
                text.Style.Paragraph.Align = ceTe.DynamicPDF.TextAlign.Left;
                page.Elements.Add(text);


                document.setLastPos(document.getLastPos() + 300);
            }
        }
        #endregion

        private bool clienteAdeguato(string pRete, string pCodiceFiscale, bool pPeriodico)
        {


            //DataAccessDE dataAccess = new DataAccessDE(DBProvider.SqlServerStampeC6);
            //DataTable dt = dataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerStampeC6, "PL_D_S178IndicatoriEsitoAdeguatezza", null);

            var parametri = new List<Parametro>
                {
                    new Parametro
                    {
                        Direction = ParameterDirection.Input,
                        DbType = DbType.String,
                        ParameterName = "Rete",
                        Value = pRete
                    },
                    new Parametro
                    {
                        Direction = ParameterDirection.Input,
                        DbType = DbType.String,
                        ParameterName = "CodiceFiscale",
                        Value = pCodiceFiscale
                    }

                };

            string sSql = "";
            if (pPeriodico)
                sSql = "[C6MartPeriodico].[PL_D_S178IndicatoriEsitoAdeguatezza]";
            else
                sSql = "[C6Mart].[PL_D_S178IndicatoriEsitoAdeguatezza]";

            var dsBatch = DataAccess.ExecuteDataSetStoredProcedure(DBProvider.SqlServerStampeC6, sSql, parametri);
            if (dsBatch.Tables[0].Rows.Count > 0)
            {
                bool bRet = true;

                for (int i = 0; i < dsBatch.Tables[0].Rows.Count; i++)
                {
                    if (dsBatch.Tables[0].Rows[i][2].ToString() == "0")
                    {
                        bRet = false;
                        break;
                    }

                }
                return bRet;
            }
            else
                return false;
        }

        private string addLeftPad(string s, int q)
        {
            string pad = "";
            for (int i = 0; i < q; i++)
            {
                pad += "&nbsp;";
            }
            return string.Concat(pad, s);
        }
    }
}