using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Data;
using System.Web;
using ConsulenzaEvoluta;
//ISPB >>>
using ClassLibraryWS.bancafideuram.nac.token;
using System.Web.UI.WebControls;
//ISPB <<<
public partial class reportPatriImmobiliare : System.Web.UI.Page
{
    public string codCliente;
    public string tipoRete;
    public string codPB;
    public string codAs;
    public string codiceUtenteQueryString;
    public string token;
    public string userName = string.Empty;
    public string codiceApplicazione = string.Empty;
    public string checkPrivacy;

    private Nucleo _nucleo;
    public string pathNav;
    public int idReport;              //indica il modello (fixed) COMPLETO di QUESTO report da cui costruire la treeview iniziale
    private string sUtente;
    public int chiaveClientePB;
    public int chiaveClientePBCo;
    public static int tpReport = 8;        //valore proprietario (fixed) di QUESTO report //DA VALUTARE!!
    public static int idReportAlbero = 16; //valore proprietario (fixed) di QUESTO report //DA VALUTARE!!
    public static int idReportBase = 16;
    public static int idReportCompleto = 16;
    public string codiceRete;
    public string codicePB;
    public string ambiente;
    public int lastSavedReportId;
    public static string nomeReport = "PATRIMONIOIMMOBILLIARE";                   //valore proprietario (fixed) di QUESTO report
    public static string nomeReportCompleto = "Nucleo completo";  //valore proprietario (fixed) di QUESTO report 
    public static string nomeReportRischio = "NUCLEO";                   //valore proprietario (fixed) di QUESTO report
    public static string nomeReportBaseRischio = "Nucleo base";          //valore proprietario (fixed) di QUESTO report 
    public static string nomeReportCompletoRischio = "Nucleo completo";  //valore proprietario (fixed) di QUESTO report 

    public static string tabs1Href = "#tabs-1";
    public static string tabs2Href = "#tabs-2";
    public static string tabs3Href = "#tabs-3";
    public static string tabsTutteHref = "#tabs-Tutte";
    public static string tabs0Href = "#tabs0link";

    public static string blankHref = "#";


    string nomeReportPerLabel;
    string descrizioneReportPerLabel;
    public int reportIdToLoadBack = -1;
    public string endOfjob = "0";

    //private bool reportNominativo = false;
    int IDReportToLoad = -1;
    public string baseCompleto;
    public string reportName;

    private int IdModello;
    private GestReport m = new GestReport();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (ClassLibraryWS.Debug.iSDebug && Request.QueryString.Get("tipoRete") == null)
        {
           
            //Response.Redirect("reportPatriImmobiliare.aspx?codPB=" + ClassLibraryWS.Debug.Agente + "&chiaveClientePB=" + ClassLibraryWS.Debug.ChiaveClientePB + "&token=&tipoRete=" + ClassLibraryWS.Debug.Rete);
            //Response.Redirect("reportPatriImmobiliare.aspx?codPB=" + ClassLibraryWS.Debug.Agente + "&chiaveClientePB=2444" + "&token=&tipoRete=" + ClassLibraryWS.Debug.Rete);
            Response.Redirect("reportPatriImmobiliare.aspx?codPB=017016&chiaveClientePB=1837&token=&tipoRete=I");
            return;
        }



        Session.Add("token", Request.QueryString.Get("token"));
        Session.Add("codiceRete", Request.QueryString.Get("tipoRete"));
        Session.Add("tipoRete", Request.QueryString.Get("tiporete"));
        Session.Add("codicePB", Request.QueryString.Get("codPB"));
        Session.Add("codPB", Request.QueryString.Get("codpb"));
        Session.Add("codAs", Request.QueryString.Get("codas"));
        Session.Add("chiaveClientePB", Request.QueryString["chiaveClientePB"]);
        Session.Add("chiaveClientePBCo", Request.QueryString["chiaveClientePBCo"]);

        Session.Add("newChiaveClientePB", Request.QueryString["newChiaveClientePB"]);

        try
        {

            //token = Request.QueryString.Get("token");
            //codiceRete = Request.QueryString.Get("tipoRete");
            //tipoRete = Request.QueryString.Get("tiporete").ToUpper();
            //codicePB = Request.QueryString.Get("codPB");
            //codPB = Request.QueryString.Get("codpb").ToUpper();

            token = Request.QueryString.Get("token") != null ? Request.QueryString.Get("token") : string.Empty;
            codiceRete = Request.QueryString.Get("tipoRete") != null ? Request.QueryString.Get("tipoRete") : string.Empty;
            tipoRete = Request.QueryString.Get("tiporete") != null ? Request.QueryString.Get("tiporete").ToUpper() : string.Empty;
            codicePB = Request.QueryString.Get("codPB") != null ? Request.QueryString.Get("codPB") : string.Empty;
            codPB = Request.QueryString.Get("codpb") != null ? Request.QueryString.Get("codpb").ToUpper() : string.Empty;
            codAs = Request.QueryString.Get("codas") != null ? Request.QueryString.Get("codas").ToUpper() : string.Empty;
            codiceUtenteQueryString = tipoRete.Trim() + codicePB.Trim();
            chiaveClientePB = Request.QueryString.Get("chiaveClientePB") != null ? Convert.ToInt32(Request.QueryString.Get("chiaveClientePB")) : 0; 
            chiaveClientePBCo = Request.QueryString.Get("chiaveClientePBCo") != null ? Convert.ToInt32(Request.QueryString.Get("chiaveClientePBCo")) : 0; 
            IdModello = codiceRete.Equals("S") ? 6 : 5;
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message + "');</script>");
        }
        //token = "32324";
        //codiceRete = "S";
        //tipoRete = "I";
        //codicePB = "044496";
        //codPB = "11020";
        //codAs = string.Empty;
        //codiceUtenteQueryString = tipoRete.Trim() + codicePB.Trim();
        //chiaveClientePB = 2617;// 17;// 3385;// 130;//1885
        //IdModello = codiceRete.Equals("S") ? 5 : 5;



        if (DDLModello.Text.Equals("tipologia"))
        {

            IdModello = codiceRete.Equals("S") ? 5: 5;
        }
        else
        {
            IdModello = codiceRete.Equals("S") ?  12 : 11;
        }




        if (!Page.IsPostBack)
        {

        
            caricatutto();


        }
    }

    public static bool IsNewTabRequired(int chiaveClientePB, out DataTable data)
    {
        List<Parametro> parametri = new List<Parametro>();
        parametri.Add(new Parametro() { ParameterName = "chiaveClientePB", Value = chiaveClientePB });
        data = DataAccess.ExecuteDataTableStoredProcedure(DBProvider.SqlServerConsulenzaEvoluta, "GetClientsDataByChiaveClientePb", parametri);
        return data.Rows.Count > 1;
    }

    protected void ButApplica_Click(object sender, EventArgs e)
    {
        try
        {

            caricatutto();

        }
        catch(Exception ex){
            string s = ex.Message;
        }
        finally
        {
        }
    }


    private void caricatutto()
    {


        var v = Session["newChiaveClientePB"];
        DataTable dt = new DataTable();
        bool newTab = IsNewTabRequired(chiaveClientePB, out dt);

        if (newTab && v == null)
        {
            // tabs0link.Visible = true;
            tabs0.Visible = true;
            testX.Visible = false;
            tabs1.HRef = blankHref;
            tabs2.HRef = blankHref;
            tabs3.HRef = blankHref;
            tabsTutte.HRef = blankHref;
            ButImportaTutto.Visible = false;

            string fullName = "";

            foreach (DataRow r in dt.Rows)
            {
                var xv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                //HyperLink b = new HyperLink();

                HyperLink b = new HyperLink();
                b.Width = 600;
                b.ID = r["chiaveclientepbFiglio"].ToString();
                if (r["chiaveclientepbPAdre"].ToString() == "")
                    chiaveClientePBCo = 0;
                else
                    chiaveClientePBCo = Convert.ToInt32(r["chiaveclientepbPAdre"]);

                b.NavigateUrl = BuildURI(b.ID);
                fullName += r["nomeCliente"].ToString() + ";";
                b.Text = r["nomeCliente"].ToString();
                b.Style.Add("margin-bottom", "10px");
               // b.ImageUrl = "schede-1Fptma.jpg";
                xv.Controls.Add(b);
                tabs0link.Controls.Add(xv);
            }
            if (fullName != "")
            {
                var xv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                HyperLink b = new HyperLink();

                b.ID = dt.Rows[0]["chiaveclientepbPAdre"].ToString();
                if (dt.Rows[0]["chiaveclientepbPAdre"].ToString() == "")
                    chiaveClientePBCo = 0;
                else
                    chiaveClientePBCo = Convert.ToInt32(dt.Rows[0]["chiaveclientepbPAdre"]);

                b.NavigateUrl = BuildURI(b.ID);
                b.Width = 600;
                b.Text = fullName.Substring(0, fullName.Length - 1);
                b.Style.Add("margin-bottom", "10px");
                xv.Controls.Add(b);
                tabs0link.Controls.Add(xv);                
            }


        }
        else
        {
            tabs0.Visible = false;
            //tabs0link.Visible = false;
            tabs1.Style.Add("width", "110px");
            tabs2.Style.Add("width", "110px");
            tabs3.Style.Add("width", "110px");
            tabsTutte.Style.Add("width", "110px");
            testX.Visible = true;

            ButImportaTutto.Visible = true;
            tabs1.HRef = tabs1Href;
            tabs2.HRef = tabs2Href;
            tabs3.HRef = tabs3Href;
            tabsTutte.HRef = tabsTutteHref;

        }



        #region From Gestione Modelli
        #endregion

        GestReport m = new GestReport();
        if (!DatiHidden.Value.Equals(""))
        {
            m.SetHtmlClient(DatiHidden.Value);
            m.Template = new SchedaReport[0];
        }

        string subModello = "finalità";
        if (IdModello == 5 || IdModello == 6)
            subModello = "Immobiliare";


        if (HFERRORMSG.Value.Equals(""))
        {
          
                m.TipoRete = codiceRete.Equals("I") ? "Intesa Sanpaolo Private Banking" : "SanPaolo Invest";
            m.AcquisisciModello(IdModello);

            if (subModello.Equals("Immobiliare"))
                m.AcquisisciElencoFabbricati(chiaveClientePB);
            else
                m.AcquisisciElencoFabbricatiFinalità(chiaveClientePB);
        }


        List<string> vincoli = new List<string>();// m.GetVincoliSchedeImmobigliare(chiaveClientePB);

        if (subModello.Equals("Immobiliare"))
        {
            vincoli = m.GetVincoliSchedeImmobigliare(chiaveClientePB);
            m.SetEnableSchede(vincoli);
            foreach (SchedaReport sr in m.Modello)
            {
                if (sr.Sezioni == "37" && !vincoli.Exists(item => item == "flaganomaliafabbricati"))
                    sr.Vincoli += "&CON_40_Sono presenti anomalie catastali(fabbricati). è necessario inserire la scheda 8 o eliminare la scheda 5";
                if (sr.Sezioni == "38" && !vincoli.Exists(item => item == "flaganomaliaterreni"))
                    sr.Vincoli += "&CON_40_Sono presenti anomalie catastali(terreni). è necessario inserire la scheda 8 o eliminare la scheda 6";
            }
        }

        else
        {
            vincoli = m.GetVincoliSchedeImmobigliareFinalità(chiaveClientePB);
            m.SetEnableSchede(vincoli);
            foreach (SchedaReport sr in m.Modello)
            {
                if (sr.Sezioni == "143" && !vincoli.Exists(item => item == "flaganomaliafabbricati"))
                    sr.Vincoli += "&CON_146_Sono presenti anomalie catastali(fabbricati). è necessario inserire la scheda 8 o eliminare la scheda 5";
                if (sr.Sezioni == "144" && !vincoli.Exists(item => item == "flaganomaliaterreni"))
                    sr.Vincoli += "&CON_146_Sono presenti anomalie catastali(terreni). è necessario inserire la scheda 8 o eliminare la scheda 6";
            }
        }

            //if (vincoli.Exists(item => item == "flagfinalita")) {
            //    DDLModello.Enabled = false;
            //    ButApplica.Enabled = false;
            //    ButApplica.Attributes.Add("style", "disabled: disabled;");
            //    ButApplica.Attributes.Add("style", "opacity: 0.5;");
              
            //}
            DatiHidden.Value = m.GetHtmlClient();
        
        SessionGeneratorPdf spdf = new SessionGeneratorPdf(chiaveClientePB, chiaveClientePBCo, null, subModello, null);

        #region Recupero token da AnagraficaWS.GetVersion

        if (string.IsNullOrEmpty(token))
        {
            string codPortal = WebConfigParameter.getParameter("CODICEPORTALEPERVERSIONESIMPB");

            InfoClient infoCliente = new InfoClient();
            infoCliente.codiceApplicazione = WebConfigParameter.getParameter("CODICEAPPLICAZIONE").ToString();
            infoCliente.codiceRete = codiceRete;
            infoCliente.versioneDatabaseSIMPB = 0;

            AnagraficaWS wsana = new AnagraficaWS();
            //ISPB >>>
            TokenRes risposta = wsana.GetVersion(infoCliente, codPortal);
            token = risposta.info.versioneDatabaseSIMPB.ToString();
            //ISPB <<<
        }

        #endregion

        #region InfoClient e ChiaveCliente di GlobalPosition e Anagrafica

        // Global Position
        ClassLibraryWS.bancafideuram.nac.globalposition.InfoClient _infoCliente_GlobalPosition = new ClassLibraryWS.bancafideuram.nac.globalposition.InfoClient();
        _infoCliente_GlobalPosition.codiceApplicazione = WebConfigParameter.getParameter("CODICEAPPLICAZIONE").ToString();
        _infoCliente_GlobalPosition.versioneDatabaseSIMPB = int.Parse(token);


        ClassLibraryWS.bancafideuram.nac.globalposition.ChiaveCliente _chiaveCliente_GlobalPosition = new ClassLibraryWS.bancafideuram.nac.globalposition.ChiaveCliente();
        //ISPB  _chiaveCliente_GlobalPosition.potenzialeClienteNAC = true;

        #endregion



        #region Gestione Autorizzazione

        if (WebConfigParameter.getParameter("Ambiente") == "esterno")
            userName = User.Identity.Name;
        else
            userName = WebConfigParameter.getParameter("UtenzaWindowsAccessoHP");

        //1) utente loggato (VINCENZO UT.PROVA 2 MAGRI)
        //2) utente impersonificato (VIOTTI GIANCARLO)

        string AbilitazionePrimaria = string.Empty;

        codiceApplicazione = WebConfigParameter.getParameter("CodiceApplicazione");

        string codiceUtente = tipoRete + codicePB; // è il codiceutente con cui andrò a interrogare la ConsulenzaBase.dbo.PromotoreBancario per recuperare le informazioni dell'utente loggato

        Utente utenteLoggato_WS = Utente.GetAutorizzazioniAccessoGestioneControlli(userName, codiceApplicazione); // utente loggato (VINCENZO UT.PROVA 2 MAGRI), informazioni prese dai WS
        Utente utenteLoggato = Utente.GetProfiloUtente(codiceUtente, utenteLoggato_WS.ProfiloUtenteLoggato); // utente loggato (VINCENZO UT.PROVA 2 MAGRI) , informazioni prese da DB
        utenteLoggato.ProfiloUtenteLoggato = utenteLoggato_WS.ProfiloUtenteLoggato;
        utenteLoggato.AbilitazionePrimaria = utenteLoggato_WS.AbilitazionePrimaria;
        utenteLoggato.IsUtenteImpersonificato = utenteLoggato_WS.IsUtenteImpersonificato;
        utenteLoggato.UtenteAutorizzatoApplicazione = utenteLoggato_WS.UtenteAutorizzatoApplicazione;

        Utente utenteImpersonificato = Utente.GetProfiloUtente(codiceUtenteQueryString, null); // utente impersonificato (VIOTTI GIANCARLO)
        utenteImpersonificato.AbilitazionePrimaria = utenteLoggato.AbilitazionePrimaria;
        utenteImpersonificato.IsUtenteImpersonificato = utenteLoggato.IsUtenteImpersonificato;
        utenteImpersonificato.UtenteAutorizzatoApplicazione = utenteLoggato.UtenteAutorizzatoApplicazione;

        // FIX da valutare per TK T-300675-L4Y3
        if (!codAs.Equals(codPB))
            codiceUtenteQueryString = codiceUtente;

        Utente utenteSoloPerAutorizzazione = Utente.GetAutorizzazioni(userName, codiceApplicazione, tipoRete, codiceUtenteQueryString, Convert.ToInt32(token));

        if (utenteSoloPerAutorizzazione.UtenteAutorizzatoApplicazione)
        {
            if (Request.Browser.Cookies)
            {
                #region utente Loggato (UtenteLoggatoDiSessione)

                string utenteLoggatoString = Utente.SerializeMessage(utenteLoggato);

                utenteLoggatoString = HttpUtility.UrlDecode(utenteLoggatoString.TrimStart().TrimEnd());
                Session.Add("UtenteLoggatoDiSessione", utenteLoggatoString);

                #endregion

                #region utente Impersonificato (UtenteImpersonificatoDiSessione)

                string utenteImpersonificatoString = Utente.SerializeMessage(utenteImpersonificato);

                utenteImpersonificatoString = HttpUtility.UrlDecode(utenteImpersonificatoString.TrimStart().TrimEnd());
                Session.Add("UtenteImpersonificatoDiSessione", utenteImpersonificatoString);

                #endregion
            }
            else
            {
                AbilitazionePrimaria = string.Empty;
                if (utenteLoggato != null)
                    if (utenteLoggato.AbilitazionePrimaria != null)
                        AbilitazionePrimaria = utenteLoggato.AbilitazionePrimaria;

                Response.Redirect("error.aspx?UtenteWindows=" + userName + "&UtentePB=" + codiceUtenteQueryString + "&CodiceApplicazione=" + WebConfigParameter.getParameter("CODICEAPPLICAZIONE") + "&VersioneSIMPB=" + token.ToString() + "&AbilitazionePrimaria=" + AbilitazionePrimaria);
            }
        }
        else
        {
            AbilitazionePrimaria = string.Empty;
            if (utenteLoggato != null)
                if (utenteLoggato.AbilitazionePrimaria != null)
                    AbilitazionePrimaria = utenteLoggato.AbilitazionePrimaria;

            Response.Redirect("error.aspx?UtenteWindows=" + userName + "&UtentePB=" + codiceUtenteQueryString + "&CodiceApplicazione=" + WebConfigParameter.getParameter("CODICEAPPLICAZIONE") + "&VersioneSIMPB=" + token.ToString() + "&AbilitazionePrimaria=" + AbilitazionePrimaria + "&UtenteAutorizzato=" + utenteLoggato_WS.UtenteAutorizzatoApplicazione.ToString());
        }


        #endregion
    }

    private string BuildURI(string sid)
    {


        string redirectString = "reportPatriImmobiliare.aspx?";
        List<String> sessionItems = new List<string>();
        sessionItems.Add("token");
        sessionItems.Add("codiceRete");
        sessionItems.Add("tipoRete");
        sessionItems.Add("codicePB");
        sessionItems.Add("codPB");
        sessionItems.Add("codAs");
        //  sessionItems.Add("chiaveClientePB");
        //sessionItems.Add("newChiaveClientePB");

        foreach (String s in sessionItems)
        {
            redirectString += s + "=" + Session[s] + "&";

        }
        redirectString += "chiaveClientePB=" + sid;
        redirectString += "&newChiaveClientePB=" + sid;
        redirectString += "&chiaveClientePBCo=" + chiaveClientePBCo;

        return redirectString;


    }





}