using DevExpress.Web;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Native;
using DevExpress.XtraCharts.Web;
using DevExpress.Pdf;
using DevExpress.XtraPrinting;
using DevExpress.XtraGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OlympiaIntranet
{

    public partial class GPMAssetAllocationAPI : System.Web.UI.Page
    {
        string cod_ges = String.Empty;
        //string cod_adv = String.Empty;
        string cod_lin = String.Empty;

        protected void Page_Load(object sender, EventArgs e) // Parametri input : cod_ges,cod_adv,cod_lin
        {
            // (@cod_ges AS VARCHAR(50), @cod_adv AS VARCHAR(50), @cod_lin AS VARCHAR(50))
            cod_ges = Request.QueryString["cod_ges"];
            //cod_adv = Request.QueryString["cod_adv"];
            cod_lin = Request.QueryString["cod_lin"];

            //Session["cod_ges"] = cod_ges; // serve per popolare gridlookupLinea!!                                             

            PlottaFullStackedBar();

            buttonEsportaPdf_Click(this, null);
        }

        protected void buttonGeneraGrafici_Click(object sender, EventArgs e)
        {
            PlottaFullStackedBar();
        }

        private void PlottaFullStackedBar()
        {
            //if (!(String.IsNullOrEmpty(cod_ges) == false && String.IsNullOrEmpty(cod_adv) == false && String.IsNullOrEmpty(cod_lin) == false)) return;
            if (!(String.IsNullOrEmpty(cod_ges) == false && String.IsNullOrEmpty(cod_lin) == false)) return;
            // Carica dati in dtStackedBarsData

            DataTable dtStackedBarsData = CommonClass.execQuery_Datatable_Sql("GDN_GPMAssetAllocation_StackedBars2", 
                                                                              Properties.Settings.Default.SqlConnection, 
                                                                              cod_ges, 
                                                                              "", 
                                                                              cod_lin,
                                                                              -1,
                                                                              -1,
                                                                              null,
                                                                              "",
                                                                              "",
                                                                              null,
                                                                              "");
            Session["dtStackedBarsData"] = dtStackedBarsData;
            var listAssetClass = (from r in dtStackedBarsData.AsEnumerable()
                                  group r by r["Asset Class"]);


            fullStackedBarChart.DataSource = dtStackedBarsData;

            // Cancella tutte le serie prima di plottare 
            fullStackedBarChart.Series.Clear();

            // Cancella tutti i titoli della serie prima di plottare
            fullStackedBarChart.Titles.Clear();

            // Rimuove legenda aggiuntiva dei portafogli
            fullStackedBarChart.Legends.Clear();

            // Setta titolo del grafico
            SettaTitoloGrafico(fullStackedBarChart);


            foreach (var groupedAssetClass in listAssetClass)
            {
                string AssetClass = (string)groupedAssetClass.Key;
                Series series = new Series(AssetClass, ViewType.FullStackedBar);
                foreach (var seriesPoint in groupedAssetClass)
                {
                    series.Points.Add(new SeriesPoint(seriesPoint["Codice Portafoglio"], seriesPoint["Esposizione"]));
                }
                series.ArgumentScaleType = ScaleType.Qualitative;
                series.CrosshairContentShowMode = CrosshairContentShowMode.Default;
                series.CrosshairLabelPattern = "{S}: {V:F2}%"; // ref link : https://docs.devexpress.com/CoreLibraries/DevExpress.XtraCharts.SeriesBase.CrosshairLabelPattern

                FullStackedBarSeriesView seriesView = (FullStackedBarSeriesView)series.View;
                switch (AssetClass)
                {
                    case "Fondi Bilanciati e Flessibili":
                        seriesView.Color = Color.LightCyan;
                        break;
                    case "Liquidità":
                        seriesView.Color = Color.LightGreen;
                        break;
                    case "Obbligazioni e Fondi Obbligazionari":
                        seriesView.Color = Color.LightSalmon;
                        break;
                    case "Prodotti Strutturati":
                        seriesView.Color = Color.MediumPurple;
                        break;
                    case "Azioni e Fondi Azionari":
                        seriesView.Color = Color.OrangeRed;
                        break;
                    case "Real Estate":
                        seriesView.Color = Color.Orange;
                        break;
                    default:
                        break;
                }
                seriesView.BarWidth = 0.4;
                fullStackedBarChart.Series.Add(series);
            }

            // Posiziona la legenda sopra e fuori dal grafico 
            // ref link: https://docs.devexpress.com/CoreLibraries/DevExpress.XtraCharts.LegendBase.AlignmentHorizontal
            Legend legend = fullStackedBarChart.Legend;
            legend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
            legend.AlignmentVertical = LegendAlignmentVertical.TopOutside;
            legend.MaxHorizontalPercentage = 100;
            legend.Direction = LegendDirection.LeftToRight;

            // Hide the legend (if necessary).
            fullStackedBarChart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True;
            fullStackedBarChart.CrosshairOptions.GroupHeaderPattern = "Portafoglio: {A}";

            // Add the chart to the form.
            //this.Controls.Add(fullStackedBarChart);

            // Ruota etichetta sulle ascisse di 180
            XYDiagram diagram = (XYDiagram)fullStackedBarChart.Diagram;
            if (diagram != null)
            {
                // Ruota etichetta sulle ascisse di 180
                diagram.AxisX.Label.Angle = -90;
                diagram.AxisX.QualitativeScaleOptions.AutoGrid = false; // ref link: https://supportcenter.devexpress.com/ticket/details/t567170/how-to-force-displaying-all-axis-labels-when-the-qualitative-scale-type-is-used
                diagram.AxisX.QualitativeScaleOptions.GridSpacing = 1;

                // Rimuove margini su asse Y
                diagram.AxisY.WholeRange.AutoSideMargins = false;
                diagram.AxisY.WholeRange.EndSideMargin = 0;
                diagram.AxisY.WholeRange.StartSideMargin = 0;

                // Setta Ordinate (Asse Y) in percentuale
                diagram.AxisY.Label.TextPattern = "{VP:P0}";

                // Aggiunge legenda relativa ai ptf in basso              
                Legend ptfLegend = new Legend();
                fullStackedBarChart.Legends.Add(ptfLegend);

                ptfLegend.DockTarget = diagram.Panes.GetPaneByName("Default");
                ptfLegend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
                ptfLegend.AlignmentVertical = LegendAlignmentVertical.BottomOutside;
                ptfLegend.ItemVisibilityMode = LegendItemVisibilityMode.AutoGeneratedAndCustom;
                ptfLegend.MarkerMode = LegendMarkerMode.None;
                ptfLegend.MaxHorizontalPercentage = 100;
                ptfLegend.Direction = LegendDirection.LeftToRight;

                AggiungeItemLegend(ptfLegend, "(A) = ATTIVO");
                AggiungeItemLegend(ptfLegend, "(AR) = ATTIVO-RIC");
                AggiungeItemLegend(ptfLegend, "(V) = VIRTUALE");
                //AggiungeItemLegend(ptfLegend, "(P) = PENDING");
                //AggiungeItemLegend(ptfLegend, "(C) = IN CHIUSURA");
            }

            fullStackedBarChart.DataBind();
        }

        private void AggiungeItemLegend(Legend ptfLegend, string legendText)
        {
            CustomLegendItem item = new CustomLegendItem
            {
                Text = legendText
            };
            ptfLegend.CustomItems.Add(item);
        }

        private string TitoloFiltri()
        {
            string filtro = String.Empty;
            if (String.IsNullOrEmpty(cod_ges) == true) { filtro += "Gestore: tutti "; } else { filtro += $"Gestore: {cod_ges} "; }
            //if (String.IsNullOrEmpty(cod_adv) == true) { filtro += "Advisor: tutti "; } else { filtro += $"Advisor: {cod_adv} "; }
            if (String.IsNullOrEmpty(cod_lin) == true) { filtro += "Linea: tutti "; } else { filtro += $"Linea: {cod_lin} "; }
            return (filtro);
        }

        private void SettaTitoloGrafico(WebChartControl chartControl)
        {
            // Create chart titles.
            ChartTitle chartTitle1 = new ChartTitle();
            ChartTitle chartTitle2 = new ChartTitle();
            // Define the text for the titles.
            chartTitle1.Text = "<b>GPM ASSET ALLOCATION</b>";

            chartTitle2.Text = TitoloFiltri();

            chartTitle2.WordWrap = true;
            chartTitle2.MaxLineCount = 2;

            // Define the alignment of the titles.
            chartTitle1.Alignment = StringAlignment.Center;
            chartTitle2.Alignment = StringAlignment.Center;

            // Place the titles where it's required.
            chartTitle1.Dock = ChartTitleDockStyle.Top;
            chartTitle2.Dock = ChartTitleDockStyle.Top;

            // Customize a title's appearance.
            chartTitle1.EnableAntialiasing = DevExpress.Utils.DefaultBoolean.True;
            chartTitle1.Font = new Font("Tahoma", 14, FontStyle.Bold);
            chartTitle1.TextColor = Color.Blue;
            chartTitle1.Indent = 10;

            // Customize a title's appearance.
            chartTitle2.EnableAntialiasing = DevExpress.Utils.DefaultBoolean.True;
            chartTitle2.Font = new Font("Arial", 10, FontStyle.Bold);
            chartTitle2.TextColor = Color.Black;
            chartTitle2.Indent = 10;

            // Add the titles to the chart.
            chartControl.Titles.AddRange(new ChartTitle[] { chartTitle1, chartTitle2 });
        }

        protected void buttonEsportaPdf_Click(object sender, EventArgs e)
        {

            // Esporta grafico in pdf 
            var ps = new PrintingSystem();
            ps.PageSettings.Landscape = true;
            var link1 = new PrintableComponentLink();
            fullStackedBarChart.DataBind();
            link1.Component = ((IChartContainer)fullStackedBarChart).Chart;
            link1.Landscape = true;
            link1.PrintingSystem = ps;
            link1.CreateDocument();
            ps.Document.AutoFitToPagesWidth = 1; // Fit to page 

            using (var stream = new MemoryStream())
            {
                link1.PrintingSystem.ExportToPdf(stream);
                Response.Clear();
                Response.Buffer = false;
                Response.AppendHeader("Content-Type", "application/pdf");
                Response.AppendHeader("Content-Transfer-Encoding", "binary");
                Response.AppendHeader("Content-Disposition", $"attachment; filename=GPMAssetAllocation_{cod_ges}_{cod_lin}_{DateTime.Now.Date.ToString("yyyyMMdd")}.pdf");
                Response.BinaryWrite(stream.GetBuffer());
                Response.End();
            }
            ps.Dispose();

        }
    }
    //public partial class GPMAssetAllocationAPI : System.Web.UI.Page
    //{
    //    string cod_ges = String.Empty;
    //    string cod_pro = String.Empty;
    //    string cod_lin = String.Empty;

    //    protected void Page_Load(object sender, EventArgs e) // Parametri input : cod_ges,cod_pro,cod_lin
    //    {
    //            // (@cod_ges AS VARCHAR(50), @cod_pro AS VARCHAR(50), @cod_lin AS VARCHAR(50))
    //            cod_ges = Request.QueryString["cod_ges"];
    //            cod_pro = Request.QueryString["cod_pro"];
    //            cod_lin = Request.QueryString["cod_lin"];

    //            Session["cod_ges"] = cod_ges; // serve per popolare gridlookupLinea!!                                             

    //            PlottaFullStackedBar();

    //            buttonEsportaPdf_Click(this, null);
    //    }

    //    protected void buttonGeneraGrafici_Click(object sender, EventArgs e)
    //    {
    //        PlottaFullStackedBar();
    //    }

    //    private void PlottaFullStackedBar()
    //    {
    //        if (!(String.IsNullOrEmpty(cod_ges) == false && String.IsNullOrEmpty(cod_pro) == false && String.IsNullOrEmpty(cod_lin) == false)) return;

    //        // Carica dati in dtStackedBarsData

    //        DataTable dtStackedBarsData = CommonClass.execQuery_Datatable_Sql("GDN_GPMAssetAllocation_StackedBars", Properties.Settings.Default.SqlConnection, cod_ges, cod_pro, cod_lin);
    //        Session["dtStackedBarsData"] = dtStackedBarsData;
    //        var listAssetClass = (from r in dtStackedBarsData.AsEnumerable()
    //                              group r by r["Asset Class"]);


    //        fullStackedBarChart.DataSource = dtStackedBarsData;

    //        // Cancella tutte le serie prima di plottare 
    //        fullStackedBarChart.Series.Clear();

    //        // Cancella tutti i titoli della serie prima di plottare
    //        fullStackedBarChart.Titles.Clear();

    //        // Rimuove legenda aggiuntiva dei portafogli
    //        fullStackedBarChart.Legends.Clear();

    //        // Setta titolo del grafico
    //        SettaTitoloGrafico(fullStackedBarChart);


    //        foreach (var groupedAssetClass in listAssetClass)
    //        {
    //            string AssetClass = (string)groupedAssetClass.Key;
    //            Series series = new Series(AssetClass, ViewType.FullStackedBar);
    //            foreach (var seriesPoint in groupedAssetClass)
    //            {
    //                series.Points.Add(new SeriesPoint(seriesPoint["Codice Portafoglio"], seriesPoint["Esposizione"]));
    //            }
    //            series.ArgumentScaleType = ScaleType.Qualitative;
    //            series.CrosshairContentShowMode = CrosshairContentShowMode.Default;
    //            series.CrosshairLabelPattern = "{S}: {V:F2}%"; // ref link : https://docs.devexpress.com/CoreLibraries/DevExpress.XtraCharts.SeriesBase.CrosshairLabelPattern

    //            FullStackedBarSeriesView seriesView = (FullStackedBarSeriesView)series.View;
    //            switch (AssetClass)
    //            {
    //                case "Fondi Bilanciati e Flessibili":
    //                    seriesView.Color = Color.LightCyan;
    //                    break;
    //                case "Liquidità":
    //                    seriesView.Color = Color.LightGreen;
    //                    break;
    //                case "Obbligazioni e Fondi Obbligazionari":
    //                    seriesView.Color = Color.LightSalmon;
    //                    break;
    //                case "Prodotti Strutturati":
    //                    seriesView.Color = Color.MediumPurple;
    //                    break;
    //                case "Azioni e Fondi Azionari":
    //                    seriesView.Color = Color.OrangeRed;
    //                    break;
    //                case "Real Estate":
    //                    seriesView.Color = Color.Orange;
    //                    break;
    //                default:
    //                    break;
    //            }
    //            seriesView.BarWidth = 0.4;
    //            fullStackedBarChart.Series.Add(series);
    //        }

    //        // Posiziona la legenda sopra e fuori dal grafico 
    //        // ref link: https://docs.devexpress.com/CoreLibraries/DevExpress.XtraCharts.LegendBase.AlignmentHorizontal
    //        Legend legend = fullStackedBarChart.Legend;
    //        legend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
    //        legend.AlignmentVertical = LegendAlignmentVertical.TopOutside;
    //        legend.MaxHorizontalPercentage = 100;
    //        legend.Direction = LegendDirection.LeftToRight;

    //        // Hide the legend (if necessary).
    //        fullStackedBarChart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True;
    //        fullStackedBarChart.CrosshairOptions.GroupHeaderPattern = "Portafoglio: {A}";

    //        // Add the chart to the form.
    //        //this.Controls.Add(fullStackedBarChart);

    //        // Ruota etichetta sulle ascisse di 180
    //        XYDiagram diagram = (XYDiagram)fullStackedBarChart.Diagram;
    //        if (diagram != null)
    //        {
    //            // Ruota etichetta sulle ascisse di 180
    //            diagram.AxisX.Label.Angle = -90;
    //            diagram.AxisX.QualitativeScaleOptions.AutoGrid = false; // ref link: https://supportcenter.devexpress.com/ticket/details/t567170/how-to-force-displaying-all-axis-labels-when-the-qualitative-scale-type-is-used
    //            diagram.AxisX.QualitativeScaleOptions.GridSpacing = 1;

    //            // Rimuove margini su asse Y
    //            diagram.AxisY.WholeRange.AutoSideMargins = false;
    //            diagram.AxisY.WholeRange.EndSideMargin = 0;
    //            diagram.AxisY.WholeRange.StartSideMargin = 0;

    //            // Setta Ordinate (Asse Y) in percentuale
    //            diagram.AxisY.Label.TextPattern = "{VP:P0}";

    //            // Aggiunge legenda relativa ai ptf in basso              
    //            Legend ptfLegend = new Legend();
    //            fullStackedBarChart.Legends.Add(ptfLegend);

    //            ptfLegend.DockTarget = diagram.Panes.GetPaneByName("Default");
    //            ptfLegend.AlignmentHorizontal = LegendAlignmentHorizontal.Center;
    //            ptfLegend.AlignmentVertical = LegendAlignmentVertical.BottomOutside;
    //            ptfLegend.ItemVisibilityMode = LegendItemVisibilityMode.AutoGeneratedAndCustom;
    //            ptfLegend.MarkerMode = LegendMarkerMode.None;
    //            ptfLegend.MaxHorizontalPercentage = 100;
    //            ptfLegend.Direction = LegendDirection.LeftToRight;

    //            AggiungeItemLegend(ptfLegend, "(A) = ATTIVO");
    //            //AggiungeItemLegend(ptfLegend, "(C) = IN CHIUSURA");
    //            AggiungeItemLegend(ptfLegend, "(AR) = ATTIVO-RIC");
    //            AggiungeItemLegend(ptfLegend, "(V) = VIRTUALE");
    //            //AggiungeItemLegend(ptfLegend, "(P) = PENDING");
    //        }

    //        fullStackedBarChart.DataBind();
    //    }

    //    private void AggiungeItemLegend(Legend ptfLegend, string legendText)
    //    {
    //        CustomLegendItem item = new CustomLegendItem
    //        {
    //            Text = legendText
    //        };
    //        ptfLegend.CustomItems.Add(item);
    //    }

    //    private string TitoloFiltri()
    //    {
    //        string filtro = String.Empty;
    //        if (String.IsNullOrEmpty(cod_ges) == true) { filtro += "Gestore: tutti "; } else { filtro += $"Gestore: {cod_ges} "; }
    //        if (String.IsNullOrEmpty(cod_pro) == true) { filtro += "Consulente: tutti "; } else { filtro += $"Consulente: {cod_pro} "; }
    //        if (String.IsNullOrEmpty(cod_lin) == true) { filtro += "Linea: tutti "; } else { filtro += $"Linea: {cod_lin} "; }
    //        return (filtro);
    //    }

    //    private void SettaTitoloGrafico(WebChartControl chartControl)
    //    {
    //        // Create chart titles.
    //        ChartTitle chartTitle1 = new ChartTitle();
    //        ChartTitle chartTitle2 = new ChartTitle();
    //        // Define the text for the titles.
    //        chartTitle1.Text = "<b>GPM ASSET ALLOCATION</b>";

    //        chartTitle2.Text = TitoloFiltri();

    //        chartTitle2.WordWrap = true;
    //        chartTitle2.MaxLineCount = 2;

    //        // Define the alignment of the titles.
    //        chartTitle1.Alignment = StringAlignment.Center;
    //        chartTitle2.Alignment = StringAlignment.Center;

    //        // Place the titles where it's required.
    //        chartTitle1.Dock = ChartTitleDockStyle.Top;
    //        chartTitle2.Dock = ChartTitleDockStyle.Top;

    //        // Customize a title's appearance.
    //        chartTitle1.EnableAntialiasing = DevExpress.Utils.DefaultBoolean.True;
    //        chartTitle1.Font = new Font("Tahoma", 14, FontStyle.Bold);
    //        chartTitle1.TextColor = Color.Blue;
    //        chartTitle1.Indent = 10;

    //        // Customize a title's appearance.
    //        chartTitle2.EnableAntialiasing = DevExpress.Utils.DefaultBoolean.True;
    //        chartTitle2.Font = new Font("Arial", 10, FontStyle.Bold);
    //        chartTitle2.TextColor = Color.Black;
    //        chartTitle2.Indent = 10;

    //        // Add the titles to the chart.
    //        chartControl.Titles.AddRange(new ChartTitle[] { chartTitle1, chartTitle2 });
    //    }

    //    protected void buttonEsportaPdf_Click(object sender, EventArgs e)
    //    {

    //        // Esporta grafico in pdf 
    //        var ps = new PrintingSystem();
    //        ps.PageSettings.Landscape = true;
    //        var link1 = new PrintableComponentLink();
    //        fullStackedBarChart.DataBind();
    //        link1.Component = ((IChartContainer)fullStackedBarChart).Chart;
    //        link1.Landscape = true;
    //        link1.PrintingSystem = ps;
    //        link1.CreateDocument();
    //        ps.Document.AutoFitToPagesWidth = 1; // Fit to page 

    //        using (var stream = new MemoryStream())
    //        {
    //            link1.PrintingSystem.ExportToPdf(stream);
    //            Response.Clear();
    //            Response.Buffer = false;
    //            Response.AppendHeader("Content-Type", "application/pdf");
    //            Response.AppendHeader("Content-Transfer-Encoding", "binary");
    //            Response.AppendHeader("Content-Disposition", $"attachment; filename=GPMAssetAllocation_{cod_ges}_{cod_lin}_{DateTime.Now.Date.ToString("yyyyMMdd")}.pdf");
    //            Response.BinaryWrite(stream.GetBuffer());
    //            Response.End();
    //        }
    //        ps.Dispose();

    //    }
    //}
}