using DevExpress.Export;
using DevExpress.Web;
using DevExpress.XtraPrinting;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OlympiaIntranet
{
    public partial class GestioneOrdiniGuardian : System.Web.UI.Page
    {
        DataTable dtTitoli, dtClienti;
        string Isin = "", Description = "",  DivisaTitolo = "", LastDate = "";
        string Last = "", Ask = "";
        string paramGruppi = "";
        DateTime LastDateNET = Convert.ToDateTime("01/01/1900");

        protected void Page_Init(object sender, EventArgs e)
        {
            // Imposta data odierna di default 
            ASPxDataUltimaModifica.Date = DateTime.Now.Date;
            ASPxDataInvio.Date = DateTime.Now.Date;

            // Setta gruppi a seconda dell'utente

            // Utenza Anna
            ASPxCBLGruppi.Items.Clear();
            ASPxCBLGruppiExcel.Items.Clear();
            if (Page.User.Identity.Name == "anna" || Page.User.Identity.Name == "federico" || Page.User.Identity.Name == "admin" || Page.User.Identity.Name == "ecanziani" || Page.User.Identity.Name == "fcostalonga" || Page.User.Identity.Name == "agamba")
            {
                ASPxCBLGruppi.Items.Add("ANNA_BIL", "ANNA_BIL");
                ASPxCBLGruppi.Items.Add("ANNA_UBS", "ANNA_UBS");
                ASPxCBLGruppi.Items.Add("ANNA_UBS_CH", "ANNA_UBS_CH");

                ASPxCBLGruppiExcel.Items.Add("ANNA_BIL", "ANNA_BIL");
                ASPxCBLGruppiExcel.Items.Add("ANNA_UBS", "ANNA_UBS");
                ASPxCBLGruppiExcel.Items.Add("ANNA_UBS_CH", "ANNA_UBS_CH");

            }

            // Utenza Stefano
            if (Page.User.Identity.Name == "stefano" || Page.User.Identity.Name == "sbettinelli")
            {
                ASPxCBLGruppi.Items.Add("STE_ITA", "STE_ITA");
                ASPxCBLGruppi.Items.Add("STE_EST", "STE_EST");

                ASPxCBLGruppiExcel.Items.Add("STE_ITA", "STE_ITA");
                ASPxCBLGruppiExcel.Items.Add("STE_EST", "STE_EST");
            }
           
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated == false)
            {
                Response.Redirect("~/SignIn.aspx");
            }

            ReloadTables();
           
        }

        protected void ASPxRBLTipoTitolo_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Evento gestito tramite javascript in ClientSideEvents SelectedIndexChanged
        //    "function(s, e) {

        //        if (rblTipoTitolo.GetSelectedIndex() == 0) // Tipo Codice : ISIN
        //    {
        //        comboboxStrumento.SetEnabled(true);
        //    }
        //    else
        //    if (rblTipoTitolo.GetSelectedIndex() == 1) // Tipo Codice : Ticker BBG
        //    {
        //        comboboxStrumento.SetSelectedIndex(-1);
        //        comboboxStrumento.SetEnabled(false);
        //    }
        //}"

            //if (ASPxRBLTipoTitolo.SelectedIndex == 0) // Tipo Codice : ISIN
            //{
            //    ASPxStrumento.Enabled = true;
            //}
            //else
            //if (ASPxRBLTipoTitolo.SelectedIndex == 1) // Tipo Codice : Ticker BBG
            //{
            //    ASPxStrumento.SelectedIndex = -1;
            //    ASPxStrumento.Enabled = false;
            //}
        }

        protected void ASPxButtonQueryBBG_Click(object sender, EventArgs e)
        {
            // Pulisce Label varie
            ASPxLabelQueryStatus.Text = "";
            ASPxLabelDescrizioneBBG.Text = "";
            ASPxLabelDivisaTitoloBBG.Text = "";
            ASPxLabelPrezzoBBG.Text = "";
            ASPxLabelDataPrezzoBBG.Text = "";            

            // Controllo Codice Titolo 
            if (String.IsNullOrEmpty(ASPxCodiceTitolo.Text))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Codice Titolo mancante!\");", true);
                return;
            }

            // Controllo Tipo Titolo 
            if (ASPxRBLTipoTitolo.SelectedIndex == -1)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Selezionare tipo ISIN o Ticker BBG!\");", true);
                return;
            }
            // Controllo correttezza ISIN (se selezionato ISIN in radiobuttonlist)
            if (ASPxRBLTipoTitolo.SelectedIndex == 0 && (ASPxCodiceTitolo.Text.Length != 12 || (ASPxCodiceTitolo.Text.Any(Char.IsWhiteSpace))))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Formato ISIN non corretto!\");", true);
                return;
            }
            // Controllo Strumento (solo se è selezionato Tipo Codice ISIN)
            //if (ASPxRBLTipoTitolo.SelectedIndex == 0 && ASPxStrumento.SelectedIndex == -1)
            // Controllo Strumento
            if (ASPxStrumento.SelectedIndex == -1)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Selezionare Strumento!\");", true);
                return;
            }
            //// Controllo Mercato
            //if (ASPxMercato.SelectedIndex == -1)
            //{
            //    ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Selezionare Mercato!\");", true);
            //    return;
            //}

            // Controllo PCS Obbligazioni se è selezionato Obbligazioni come Strumento
            //if (ASPxStrumento.SelectedIndex == 4 && ASPxPCSObbligazioni.SelectedIndex == -1)
            //{
            //    ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Selezionare PCS!\");", true);
            //    return;
            //}

            // Compone link BBG
            //string suffixBBG = "";
            string security = "";
            string field = "ID_ISIN,SECURITY_NAME,PX_LAST,CRNCY,PX_CLOSE_DT,PX_ASK"; // Nel caso di strumento = Certificates allora la descrizione la prenderò componendola dal DB              
            if (ASPxRBLTipoTitolo.SelectedIndex == 0) // Selezionato ISIN
            {
                if (ASPxStrumento.SelectedIndex != 4)  security = "/isin/" + ASPxCodiceTitolo.Text.ToUpper();
                else security = "/isin/" +  ASPxCodiceTitolo.Text + "@"+ ASPxPCS.Text; // se Strumento è obbligazioni allora compone diversamente la security (esempio /isin/DE000A2GSB86@GERM)
            }
            else
             if (ASPxRBLTipoTitolo.SelectedIndex == 1) // Selezionato Ticker BBG
            {
                security = ASPxCodiceTitolo.Text;
            }

            // Effettua chiamata a BBG
            string IPBBG = CommonClass.IsBBGServiceOnline()[1]; // Scarica dati rt da Londra
            bool callEsito = (IPBBG != "N/A");
            int hits = 0;
            int numFields = 6;
            //string linkBBG = string.Format("http://188.172.147.202:50000/api/bbgservice?security={0}&field={1}&type=json",security,field);
            if (!callEsito)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"BBG OFFLINE!\");", true);
                return;
            }
            hits += numFields;
            string linkBBG = string.Format("http://{0}/api/bbgservice?security={1}&field={2}&type=json", IPBBG, security, field);
            string json = "";
            string error = "";
            try
            {
                using (WebClient web = new WebClient())
                {
                    json = web.DownloadString(linkBBG);
                }
                if (CommonClass.IsValidJson(json) == false)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"ERRORE CHIAMATA BBG SERVICE! ("+ linkBBG + ") \");", true);
                    return;
                }
                JArray root = JArray.Parse(json);

                foreach (var item in root)
                {
                    Isin = (string)item.SelectToken("ID_ISIN");      // usato solo se Tipo Titolo è Ticker BBG
                    Description = (string)item.SelectToken("SECURITY_NAME"); // usato solo se Strumento non è Certificates
                    //Last = Convert.ToDecimal(((string)item.SelectToken("PX_LAST")).Replace('.', ','));
                    //Ask = Convert.ToDecimal(((string)item.SelectToken("PX_ASK")).Replace('.', ','));
                    Last = (string)item.SelectToken("PX_LAST");
                    Ask = (string)item.SelectToken("PX_ASK");
                    DivisaTitolo = (string)item.SelectToken("CRNCY");
                    LastDate = (string)item.SelectToken("PX_CLOSE_DT");
                    if (LastDate != "0")
                    {
                        var arrLastDate = LastDate.Split('-'); // Splitta data in formato yyyy-mm-dd per convertirla in C#.Net
                        LastDateNET = new DateTime(Convert.ToInt16(arrLastDate[0]), Convert.ToInt16(arrLastDate[1]), Convert.ToInt16(arrLastDate[2]));
                    } else LastDateNET = new DateTime(1900, 01, 01);
                }

                CommonClass.SaveHits(1, hits);

            }
            catch (Exception ex)
            {
                error = ex.Message;
                string Errore = string.Format("alert(\"{0} (Errore : {1})\");", "Errore esecuzione query su BBG Service!",error);
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", Errore, true);
            }

            if (!string.IsNullOrEmpty(error)) return; // Se s'è errore in Query BBG allora esce...

            // Verifica esistenza Isin in tabella TitoliGDN e nel caso ne carica i dati altrimenti li salva e li visualizza
            int IDTitoli = (from r in dtTitoli.AsEnumerable()
                            where r.Field<string>("ISIN").ToUpper() == Isin
                            select r.Field<int>("IDTitoli")).SingleOrDefault<int>();
            if (IDTitoli == 0) // Se Isin non esiste nel DB allora lo salva
            {
                ASPxLabelISIN.Text = Isin;
                if (ASPxStrumento.Text == "Certificates")
                {
                    ASPxLabelDescrizioneBBG.Text = ExecSP("GDN_DescrizioneTitolo", Isin);
                    ASPxLabelPrezzoBBG.Text = String.Format("{0:F}", Ask);                    
                    var layoutItem = ASPxFLTitoli.FindItemOrGroupByName("ASPxLayoutItemPrezzo");
                    layoutItem.Caption = "Prezzo (Ask)";
                    ASPxLabelDataPrezzoBBG.Text = DateTime.Now.Date.ToString("dd-MM-yyyy");
                }
                else
                {
                    ASPxLabelDescrizioneBBG.Text = Description;
                    ASPxLabelPrezzoBBG.Text = String.Format("{0:F}", Last);
                    var layoutItem = ASPxFLTitoli.FindItemOrGroupByName("ASPxLayoutItemPrezzo");
                    layoutItem.Caption = "Prezzo (Last)";
                    ASPxLabelDataPrezzoBBG.Text = LastDateNET.ToString("dd-MM-yyyy");
                }
                
                ASPxLabelDataPrezzoBBG.Text = LastDateNET.ToString("dd-MM-yyyy"); 
                ASPxLabelDivisaTitoloBBG.Text = DivisaTitolo;
                SalvaTitoli(); // salva record in TitoliGDN
                ReloadTables();
                ASPxLabelQueryStatus.Text = string.Format("Titolo {0} salvato nel database", ASPxCodiceTitolo.Text);
            }
            else // Se Isin esiste allora aggiorna Px_Last,Px_Date,MercatiID e TipoStrumento in tabella TitoliGDN e Prezzo in tabella OrdiniGDN per tutti i record che hanno quel titolo
            {
                AggiornaTitoli_Ordini(); 
                ReloadTables();
                ASPxLabelQueryStatus.Text = string.Format("Titolo {0} rilevato nel database, dati aggiornati", ASPxCodiceTitolo.Text);
                ASPxLabelISIN.Text = Isin;
                if (ASPxStrumento.Text == "Certificates")
                {
                    var layoutItem = ASPxFLTitoli.FindItemOrGroupByName("ASPxLayoutItemPrezzo");
                    layoutItem.Caption = "Prezzo (Ask)";
                }
                else
                {
                    var layoutItem = ASPxFLTitoli.FindItemOrGroupByName("ASPxLayoutItemPrezzo");
                    layoutItem.Caption = "Prezzo (Last)";
                }
                    ASPxLabelDescrizioneBBG.Text = (from r in dtTitoli.AsEnumerable()
                                                where r.Field<string>("ISIN").ToUpper() == Isin
                                                select r.Field<string>("Descrizione")).SingleOrDefault<string>();
                ASPxLabelPrezzoBBG.Text        = String.Format("{0:F}",(from r in dtTitoli.AsEnumerable()
                                                                        where r.Field<string>("ISIN").ToUpper() == Isin
                                                                        select r.Field<double>("Px_Last")).SingleOrDefault<double>());
                ASPxLabelDataPrezzoBBG.Text = (from r in dtTitoli.AsEnumerable()
                                             where r.Field<string>("ISIN").ToUpper() == Isin
                                             select r.Field<DateTime>("Px_Date")).SingleOrDefault<DateTime>().ToString("dd-MM-yyyy");
                ASPxLabelDivisaTitoloBBG.Text = (from r in dtTitoli.AsEnumerable()
                                                 where r.Field<string>("ISIN").ToUpper() == Isin
                                                 select r.Field<string>("DivisaTitolo")).SingleOrDefault<string>();
                //ASPxMercato.SelectedItem.Value = (from r in dtTitoli.AsEnumerable()
                //                             where r.Field<string>("ISIN").ToUpper() == Isin
                //                             select r.Field<int>("MercatiID")).SingleOrDefault<int>();
               // if (ASPxRBLTipoTitolo.SelectedIndex == 0)
               // {
                    ASPxStrumento.SelectedItem.Value = (from r in dtTitoli.AsEnumerable()
                                                        where r.Field<string>("ISIN").ToUpper() == Isin
                                                        select r.Field<string>("TipoStrumento")).SingleOrDefault<string>();
                //}
                //else ASPxStrumento.SelectedIndex = -1;
            }
            ReloadOrdini();
            ReloadOrdiniPerExcel();
            ASPxOrdiniPerExcel.Selection.SelectAll();

        }

        protected void ASPxMercato_Callback(object sender, DevExpress.Web.CallbackEventArgsBase e)
        {
            (sender as DevExpress.Web.ASPxComboBox).DataBind();
        }

        protected void ASPxGVOrdini_BeforePerformDataSelect(object sender, EventArgs e)
        {
            Session["ISIN"]     = ASPxLabelISIN.Text;
            Session["fromDate"] = ASPxDataUltimaModifica.Date.ToString("yyyy-MM-dd");
        }

        protected void ASPxButtonCaricaClienti_Click(object sender, EventArgs e)
        {
            // Controllo Codice Titolo 
            if (String.IsNullOrEmpty(ASPxCodiceTitolo.Text))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Codice Titolo mancante!\");", true);
                return;
            }
            SalvaDataRegolamento();

            ReloadOrdini();
        }

        private void SalvaDataRegolamento()
        {
            // Rileva gruppi selezionati per la visualizzazione degli ordini relativi ai clienti associati ai gruppi
            paramGruppi = "";
            foreach (ListEditItem item in ASPxCBLGruppi.SelectedItems)
            {
                paramGruppi = paramGruppi + item.Text + ",";
            }
            // Salva DataRegolamento per quelle righe (ordini) che hanno solo un conto (quindi una valuta) in modo che l'utente non debba editare le righe a manina.
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_OrdiniDataRegUPD",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@ISIN", SqlDbType.VarChar).Value = ASPxLabelISIN.Text;
                cmd.Parameters.Add("@Gruppi", SqlDbType.VarChar).Value = paramGruppi;
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        protected void ASPxButtonSavePrezzo_Click(object sender, EventArgs e)
        {
            // Controlla Modifica prezzo valorizzato
            if (String.IsNullOrEmpty(ASPxTextBoxModificaPrezzo.Text))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Prezzo da aggiornare mancante!\");", true);
                return;
            }
            // Controlla inserimento punto decimale invece che virgola
            if (ASPxTextBoxModificaPrezzo.Text.IndexOf(",") != -1)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Inserire prezzo con punto (.) come decimale (es: 900.25)\");", true);
                return;
            }
            // Ciclo per rilevare IDOrdini in griglia ASPxGVOrdini
            for (int i = 0; i < ASPxGVOrdini.VisibleRowCount; i++)
            {
                if (ASPxGVOrdini.GetRowLevel(i) == ASPxGVOrdini.GroupCount)
                {
                    object keyValue = ASPxGVOrdini.GetRowValues(i, new string[] { ASPxGVOrdini.KeyFieldName });
                    if (keyValue != null)
                        //ASPxMemo1.Text += keyValue.ToString() + "\n";
                        AggiornaPrezzo_Ordini(Convert.ToInt16(keyValue),Convert.ToDouble(ASPxTextBoxModificaPrezzo.Text));
                }
            }
            ReloadOrdini();
            ReloadOrdiniPerExcel();
            ASPxOrdiniPerExcel.Selection.SelectAll();
        }

        private void InserisceOrdini(string gruppo, string ISIN)
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_OrdiniINS_v1",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@Gruppo", SqlDbType.VarChar).Value = gruppo;
                cmd.Parameters.Add("@ISIN", SqlDbType.VarChar).Value = ISIN;
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        protected void ASPxButtonCaricaOrdiniExcel_Click(object sender, EventArgs e)
        {
            if (ASPxCBLGruppiExcel.SelectedItems.Count == 0)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Selezionare almeno un gruppo!\");", true);
                return;
            }
            ReloadOrdiniPerExcel();

            // Seleziona tutti i record (default)
            ASPxOrdiniPerExcel.Selection.SelectAll();
        }

        private void AggiornaTitoli_Ordini()
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_TitoliUPD_v1",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                //cmd.Parameters.Add("@MercatiID", SqlDbType.Int).Value = Convert.ToInt16(ASPxMercato.SelectedItem.Value);
                cmd.Parameters.Add("@ISIN", SqlDbType.VarChar).Value = Isin;
                if (ASPxStrumento.Text == "Certificates")
                {
                    cmd.Parameters.Add("@Px_Last", SqlDbType.Float).Value = Ask;
                    cmd.Parameters.Add("@Px_Date", SqlDbType.Date).Value = DateTime.Now.Date;
                }
                else
                {
                    cmd.Parameters.Add("@Px_Last", SqlDbType.Float).Value = Last;
                    cmd.Parameters.Add("@Px_Date", SqlDbType.Date).Value = LastDate;
                }
                cmd.Parameters.Add("@TipoStrumento", SqlDbType.VarChar).Value = ASPxStrumento.SelectedItem.Value;
                cmd.Parameters.Add("@DivisaTitolo", SqlDbType.VarChar).Value = DivisaTitolo;

                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        protected void ASPxButtonExportOrdiniExcel_Click(object sender, EventArgs e)
        {
            // Controlla che la colonna cod_div_reg sia sempre valorizzata 
            bool bValutaMancante = false;
            for (int i = 0; i < ASPxOrdiniPerExcel.VisibleRowCount; i++)
            {
                if (ASPxOrdiniPerExcel.Selection.IsRowSelected(i))
                {
                    if (ASPxOrdiniPerExcel.GetRowLevel(i) == ASPxOrdiniPerExcel.GroupCount)
                    {
                        object keyValue = ASPxOrdiniPerExcel.GetRowValues(i, "cod_div_reg");
                        if (keyValue != null)
                        {
                            if (String.IsNullOrEmpty(keyValue.ToString()))
                            {
                                bValutaMancante = true;
                            }
                        }
                    }
                }
            }
            if (bValutaMancante)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Verificare colonna Divisa Regolamento (cod_div_reg) , valuta mancante individuata in una o più righe!\");", true);
                return;
            }
            // Aggiorna data invio in tutti gli ordini selezionati prima di generare l'excel
            // Ciclo per rilevare IDOrdini in griglia ASPxGVOrdini
            for (int i = 0; i < ASPxOrdiniPerExcel.VisibleRowCount; i++)
            {
                if (ASPxOrdiniPerExcel.Selection.IsRowSelected(i))
                {
                    if (ASPxOrdiniPerExcel.GetRowLevel(i) == ASPxOrdiniPerExcel.GroupCount)
                    {
                        object keyValue = ASPxOrdiniPerExcel.GetRowValues(i, new string[] { ASPxOrdiniPerExcel.KeyFieldName });
                        if (keyValue != null)
                            AggiornaDataInvio_Ordini(Convert.ToInt16(keyValue), ASPxDataInvio.Date);
                    }
                }
            }
            ReloadOrdiniPerExcel();

            // Esporta Griglia in Excel
            SettaColonneExcel(true);
            ASPxGridViewExporter1.FileName = DateTime.Now.ToString("yyyyMMdd_HHmm") + " - ordini";
            XlsxExportOptionsEx option = new XlsxExportOptionsEx { ExportType = ExportType.DataAware, TextExportMode = TextExportMode.Value };
            ASPxGridViewExporter1.WriteXlsxToResponse(option);
            SettaColonneExcel(false);
        }

        protected void ASPxGridViewExporter1_RenderBrick(object sender, ASPxGridViewExportRenderingEventArgs e)
        {
            // ref : https://www.devexpress.com/Support/Center/Question/Details/Q444559
            // Disabilita esportazione griglia in Excel
            e.BrickStyle.BorderWidth = 1;

            // ref : https://www.devexpress.com/Support/Center/Question/Details/S37578
            // Formatta campo prezzo in excel in formato numerico (non usato perchè non risolve problema importazione in Guardian)
            //GridViewDataColumn dataColumn = e.Column as GridViewDataColumn;
            //if (e.RowType == GridViewRowType.Data && dataColumn != null && dataColumn.FieldName == "prezzo")
            //{
            //    e.TextValueFormatString = "{0:N2}";
            //}
        }

        private void AggiornaDataInvio_Ordini(int idOrdini, DateTime dataInvio)
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_DataInvioOrdiniUPD",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@IDOrdini", SqlDbType.Int).Value = idOrdini;
                cmd.Parameters.Add("@DataInvio", SqlDbType.Date).Value = dataInvio;
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        private void AggiornaDataValidita_Ordini(int idOrdini, DateTime? dataValidita)
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_DataValiditaOrdiniUPD",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@IDOrdini", SqlDbType.Int).Value = idOrdini;
                if (dataValidita != null) cmd.Parameters.Add("@DataValidita", SqlDbType.Date).Value = dataValidita;
                else cmd.Parameters.Add("@DataValidita", SqlDbType.Date).Value = DBNull.Value;
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }



        private void SalvaTitoli()
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_TitoliINS",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                //cmd.Parameters.Add("@MercatiID", SqlDbType.Int).Value = Convert.ToInt16(ASPxMercato.SelectedItem.Value);
                cmd.Parameters.Add("@ISIN", SqlDbType.VarChar).Value = Isin;
                if (ASPxRBLTipoTitolo.SelectedIndex == 1) cmd.Parameters.Add("@Ticker_bbg", SqlDbType.VarChar).Value = ASPxCodiceTitolo.Text;
                if (ASPxRBLTipoTitolo.SelectedIndex == 0) cmd.Parameters.Add("@Ticker_bbg", SqlDbType.VarChar).Value = DBNull.Value;
                cmd.Parameters.Add("@Descrizione", SqlDbType.VarChar).Value = ASPxLabelDescrizioneBBG.Text;
                if (ASPxStrumento.Text == "Certificates") cmd.Parameters.Add("@Px_Last", SqlDbType.Float).Value = Ask;
                else cmd.Parameters.Add("@Px_Last", SqlDbType.Float).Value = Last;
                cmd.Parameters.Add("@Px_Date", SqlDbType.Date).Value = LastDateNET;
                cmd.Parameters.Add("@DivisaTitolo", SqlDbType.VarChar).Value = DivisaTitolo;
                cmd.Parameters.Add("@TipoStrumento", SqlDbType.VarChar).Value = ASPxStrumento.SelectedItem.Value;
                con.Open();
                cmd.ExecuteNonQuery();                
            }
        }

        protected void ASPxPageControl1_ActiveTabChanged(object source, TabControlEventArgs e)
        {
            //if (ASPxPageControl1.ActiveTabPage.Name=="Crea Excel")
            //{
            //    ReloadOrdiniPerExcel();
            //}
        }

        protected void ASPxGVOrdini_RowUpdated(object sender, DevExpress.Web.Data.ASPxDataUpdatedEventArgs e)
        {
            ReloadOrdiniPerExcel();
            ASPxOrdiniPerExcel.Selection.SelectAll();
        }

        protected void ASPxButtonCancellaOrdini_Click(object sender, EventArgs e)
        {
            // Controllo Codice Titolo 
            if (String.IsNullOrEmpty(ASPxCodiceTitolo.Text))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Codice Titolo mancante!\");", true);
                return;
            }

            // Esegue codice sottostante solo se è stato accettato il confirm in ClientSideEvent in ASPxButtonCancellaOrdini
            CancellaOrdini();
        }

        private void CancellaOrdini()
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_CancellaOrdiniPerTitolo",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@ISIN", SqlDbType.VarChar).Value = ASPxCodiceTitolo.Text;
                con.Open();
                cmd.ExecuteNonQuery();
            }
            ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Ordini cancellati per "+ ASPxCodiceTitolo.Text+" !\");", true);
        }

        protected void ASPxButtonSaveDataValidita_Click(object sender, EventArgs e)
        {

            // Controlla Modifica Data Validità valorizzato
            if (String.IsNullOrEmpty(ASPxDateDataValidita.Text))
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"Data Validità da aggiornare mancante!\");", true);
                return;
            }

            // Ciclo per rilevare IDOrdini in griglia ASPxGVOrdini
            for (int i = 0; i < ASPxGVOrdini.VisibleRowCount; i++)
            {
                if (ASPxGVOrdini.GetRowLevel(i) == ASPxGVOrdini.GroupCount)
                {
                    object keyValue = ASPxGVOrdini.GetRowValues(i, new string[] { ASPxGVOrdini.KeyFieldName });
                    if (keyValue != null)
                        AggiornaDataValidita_Ordini(Convert.ToInt16(keyValue), ASPxDateDataValidita.Date);
                }
            }
            ReloadOrdini();
            ReloadOrdiniPerExcel();
            ASPxOrdiniPerExcel.Selection.SelectAll();
        }

        protected void ASPxCancellaDataValidita_Click(object sender, EventArgs e)
        {
            // Ciclo per rilevare IDOrdini in griglia ASPxGVOrdini
            for (int i = 0; i < ASPxGVOrdini.VisibleRowCount; i++)
            {
                if (ASPxGVOrdini.GetRowLevel(i) == ASPxGVOrdini.GroupCount)
                {
                    object keyValue = ASPxGVOrdini.GetRowValues(i, new string[] { ASPxGVOrdini.KeyFieldName });
                    if (keyValue != null)
                    {
                        DateTime? dataValidita = null;
                        AggiornaDataValidita_Ordini(Convert.ToInt16(keyValue), dataValidita);
                    }
                }
            }
            ReloadOrdini();
            ReloadOrdiniPerExcel();
            ASPxOrdiniPerExcel.Selection.SelectAll();
        }

        protected void ASPxOrdiniPerExcel_BeforePerformDataSelect(object sender, EventArgs e)
        {
            string paramGruppi = "";
            if (ASPxCBLGruppiExcel.SelectedItems.Count > 0)
            {
                foreach (ListEditItem item in ASPxCBLGruppiExcel.SelectedItems)
                {
                    paramGruppi = paramGruppi + item.Text + ",";
                }

                Session["Gruppi"] = paramGruppi;
                Session["fromDate"] = ASPxDataUltimaModifica.Date;
            }
        }

        protected void ASPxButtonSaveTipoOp_Click(object sender, EventArgs e)
        {
            // Ciclo per rilevare IDOrdini in griglia ASPxGVOrdini
            for (int i = 0; i < ASPxGVOrdini.VisibleRowCount; i++)
            {
                if (ASPxGVOrdini.GetRowLevel(i) == ASPxGVOrdini.GroupCount)
                {
                    object keyValue = ASPxGVOrdini.GetRowValues(i, new string[] { ASPxGVOrdini.KeyFieldName });
                    if (keyValue != null)
                        AggiornaTipoOp_Ordini(Convert.ToInt16(keyValue), ASPxRBLTipoOp.SelectedItem.Value.ToString());
                }
            }
            
            ReloadOrdini();
            ReloadOrdiniPerExcel();
            ASPxOrdiniPerExcel.Selection.SelectAll();
        }

        private void AggiornaTipoOp_Ordini(int idOrdini, string tipoOp)
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_TipoOpOrdiniUPD",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@IDOrdini", SqlDbType.Int).Value = idOrdini;
                cmd.Parameters.Add("@TipoOp", SqlDbType.VarChar).Value = tipoOp;
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        //private void AzzeraDataValidita_Ordini(int idOrdini)
        //{
        //    string connectionString = Properties.Settings.Default.DBSettings;
        //    using (var con = new SqlConnection(connectionString))
        //    {
        //        var cmd = new SqlCommand
        //        {
        //            CommandText = "dbo.GDN_DataValiditaNULLOrdiniUPD",
        //            CommandType = CommandType.StoredProcedure,
        //            Connection = con
        //        };
        //        cmd.Parameters.Add("@IDOrdini", SqlDbType.Int).Value = idOrdini;
        //        con.Open();
        //        cmd.ExecuteNonQuery();
        //    }
        //}

        private static string ExecSP(string proc, string param)
        {
            string result;
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = proc,
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@Isin", SqlDbType.VarChar).Value = param;
                con.Open(); // Open the SqlConnection.
                result = cmd.ExecuteScalar().ToString();
            }
            return (result);
        }

        protected void ASPxImportaQty_Click(object sender, EventArgs e)
        {
            // Ciclo per rilevare IDOrdini in griglia ASPxGVOrdini
            for (int i = 0; i < ASPxGVOrdini.VisibleRowCount; i++)
            {
                if (ASPxGVOrdini.GetRowLevel(i) == ASPxGVOrdini.GroupCount)
                {
                    object keyValue = ASPxGVOrdini.GetRowValues(i, new string[] { ASPxGVOrdini.KeyFieldName });
                    object Qta = ASPxGVOrdini.GetRowValues(i, "QtaInPtf");
                    if (keyValue != null) AggiornaQty_Ordini(Convert.ToInt16(keyValue), Convert.ToDecimal(Qta));
                }
            }
            ReloadOrdini();
            ReloadOrdiniPerExcel();
            ASPxOrdiniPerExcel.Selection.SelectAll();
        }

        private void AggiornaQty_Ordini(int idOrdini, Decimal QtaInPtf)
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_QtaOrdiniUPD",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@IDOrdini", SqlDbType.Int).Value = idOrdini;
                cmd.Parameters.Add("@Qta", SqlDbType.Decimal).Value = QtaInPtf;
                con.Open();
                cmd.ExecuteNonQuery();
            }
            //ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", "alert(\"ID Ordini = "+idOrdini + " QtaInPtf = " + QtaInPtf + "\");", true);
        }

        protected void ASPxGVOrdini_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
        {
            // Colora cella della colonna DivisaRegolamento se è presente (*) ovvero non è salvato nel db il valore         
            if (e.DataColumn.FieldName.Contains("DivisaRegolamento") && e.CellValue.ToString().IndexOf("(*)") != -1)
            {
                e.Cell.BackColor = System.Drawing.Color.OrangeRed;
            }
            // Colora cella della colonna DivisaRegolamento se è vuota
            if (e.DataColumn.FieldName.Contains("DivisaRegolamento") && String.IsNullOrEmpty(e.CellValue.ToString()))
            {
                e.Cell.BackColor = System.Drawing.Color.Red;
            }
        }

        //protected void ASPxStrumento_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    ASPxPCSObbligazioni.Enabled = (ASPxStrumento.SelectedIndex == 4);
        //}

        private void ReloadTables()
        {
            //dtMercati = ((DataView)SqlDSMercati.Select(DataSourceSelectArguments.Empty)).Table;
            dtTitoli = ((DataView)SqlDSTitoli.Select(DataSourceSelectArguments.Empty)).Table;
            dtClienti = ((DataView)SqlDSClienti.Select(DataSourceSelectArguments.Empty)).Table;
            //ReloadOrdini();
        }

        private void ReloadOrdini()
        {
            // Rileva gruppi selezionati per la visualizzazione degli ordini relativi ai clienti associati ai gruppi
            paramGruppi = "";
            foreach (ListEditItem item in ASPxCBLGruppi.SelectedItems)
            {
                InserisceOrdini(item.Text, ASPxLabelISIN.Text); // *** da rimettere 
                //InserisceOrdini(item.Text, "XS1119159546"); *** per debug 
                paramGruppi = paramGruppi + item.Text + ",";
            }

            SqlDSOrdini.SelectCommand = "GDN_LoadOrdini_v3";
            SqlDSOrdini.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
            Parameter p = SqlDSOrdini.SelectParameters["ISIN"];
            SqlDSOrdini.SelectParameters.Remove(p);
            Parameter q = SqlDSOrdini.SelectParameters["Gruppi"];
            SqlDSOrdini.SelectParameters.Remove(q);
            SqlDSOrdini.SelectParameters.Add("ISIN", ASPxLabelISIN.Text); //*** da rimettere 
            //SqlDSOrdini.SelectParameters.Add("ISIN", "XS1119159546"); *** per debug
            SqlDSOrdini.SelectParameters.Add("Gruppi", paramGruppi);
            ASPxGVOrdini.KeyFieldName = "IDOrdini";
            ASPxGVOrdini.DataBind();
        }

        private void ReloadOrdiniPerExcel()
        {
            // Rileva gruppi selezionati per il caricamento degli ordini relativi ai clienti associati ai gruppi
            string paramGruppi = "";
            if (ASPxCBLGruppiExcel.SelectedItems.Count > 0)
            {
                foreach (ListEditItem item in ASPxCBLGruppiExcel.SelectedItems)
                {
                    paramGruppi = paramGruppi + item.Text + ",";
                }

                SqlDSOrdiniPerExcel.SelectCommand = "GDN_LoadExcelOrdini_v3";
                SqlDSOrdiniPerExcel.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
                Parameter p = SqlDSOrdiniPerExcel.SelectParameters["fromDate"];
                SqlDSOrdiniPerExcel.SelectParameters.Remove(p);
                Parameter q = SqlDSOrdiniPerExcel.SelectParameters["Gruppi"];
                SqlDSOrdiniPerExcel.SelectParameters.Remove(q);
                SqlDSOrdiniPerExcel.SelectParameters.Add("fromDate", ASPxDataUltimaModifica.Date.ToString("yyyy-MM-dd"));
                SqlDSOrdiniPerExcel.SelectParameters.Add("Gruppi", paramGruppi);
                ASPxOrdiniPerExcel.KeyFieldName = "IDOrdini";
                ASPxOrdiniPerExcel.DataBind();
            }
        }

        private void AggiornaPrezzo_Ordini(int idOrdini, double prezzo)
        {
            string connectionString = Properties.Settings.Default.SqlConnection;
            using (var con = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand
                {
                    CommandText = "dbo.GDN_PrezzoOrdiniUPD",
                    CommandType = CommandType.StoredProcedure,
                    Connection = con
                };
                cmd.Parameters.Add("@IDOrdini", SqlDbType.Int).Value = idOrdini;
                cmd.Parameters.Add("@Prezzo", SqlDbType.Float).Value = prezzo;
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        private void SettaColonneExcel(bool Show)
        {
            ASPxOrdiniPerExcel.Columns["prog"].Visible = Show;
            //ASPxOrdiniPerExcel.Columns["prog"].ExportWidth = 5;
            ASPxOrdiniPerExcel.Columns["rif"].Visible = Show;
            //ASPxOrdiniPerExcel.Columns["rif"].ExportWidth = 5;
            ASPxOrdiniPerExcel.Columns["simulazione"].Visible = Show;
            //ASPxOrdiniPerExcel.Columns["simulazione"].ExportWidth = 5;
            ASPxOrdiniPerExcel.Columns["spuntato"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["storicizzato"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["storno"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["annullato"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["ora_ope"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cod_tit"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cod_esterno"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["rateo"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cambiom"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cod_dep_liq"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cod_dep_liq2"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["ctv_rat_dn"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["comp_dep_dn"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["coma_dep_dn"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["comp_alt_dn"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["coma_alt_dn"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["spese_dn"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["imposte_dn"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["margini_dn"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["ctv_rat_dr"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["comp_dep_dr"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["coma_dep_dr"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["comp_alt_dr"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["coma_alt_dr"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["spese_dr"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["imposte_dr"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["des_mov"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["rif_est"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["coordinate1"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["coordinate2"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["data_sto"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["progr_sto"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["prezzo_car"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cod_div_ds"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cambiom_ds"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cambiod_ds"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["ctv_tot_ds"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cod_mer"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["cash"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["des_tit"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["divisore"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["moltiplicatore"].Visible = Show;
            ASPxOrdiniPerExcel.Columns["leva"].Visible = Show;

        }
    }
}