using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using bajaWare.Clases;

namespace bajaWare.Interfaces
{
    public partial class frmBusqueda : System.Web.UI.Page
    {


        public InterfacesServicePersonas.IinterfacesServicePersonas rsInterfaces = new InterfacesServicePersonas.IinterfacesServicePersonasClient();

        public InterfacesService.IinterfacesService rsInterfaceService = new InterfacesService.IinterfacesServiceClient();

        public Permisos rsPermisos = new Permisos();



        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.wucPersonaPromo.getRegistroEventPromo += new bajaWare.UserControl.Cliente.wucPersonaPromocion.getRegistroEventHandler(MensajeSist);

                if (!IsPostBack)
                {


                    Page pagina = this;

                    //ScriptManager.RegisterStartupScript(this, GetType(), "Ruta", "alert('" + Request.Url.LocalPath.ToString() + "');", true);

                    InterfacesServicesPermisos.IinterfacesServicePermisos wsPerm = new InterfacesServicesPermisos.IinterfacesServicePermisosClient();

                    int intRolSist = 1;//wsPerm.ObtieneRolSistema(short.Parse(Session["sintSistemaID"].ToString()), int.Parse(Session["UserId"].ToString()));

                    rsPermisos.SecurityAgentPage(ref pagina, intRolSist, Request.Url.LocalPath.ToString());

                    //Session["sintDepartamentoID"] = "16";
                    //Session["negocio"] = "I";



                    string strOrigen = Request.QueryString["operacion"] == null ? "" : Request.QueryString["operacion"].ToString();

                    if (strOrigen == "")
                    {
                        if (Session["negocio"].ToString() == "I")
                            btnCreditos.ImageUrl = "../Images/HipCasa.jpg";
                        mdlSeleccion.Show();
                        // return;
                    }
                    else
                        btnCreditos_OnClick(null, null);


                    if (Session["bitCapturaTodo"].ToString() == "1")
                    {
                        tabCredito.Visible = true;
                        Tabs.ActiveTab = tabCredito;
                        tabPromocion.Visible = true;
                        btnGuardaPersona.ValidationGroup = "vsg_PersonaCred";
                    }
                    else
                        if (Session["sintDepartamentoID"].ToString() == "16" || Session["sintDepartamentoID"].ToString() == "17")//Credito
                        {
                            tabCredito.Visible = true;
                            Tabs.ActiveTab = tabCredito;
                            tabPromocion.Visible = false;

                            btnGuardaPersona.ValidationGroup = "vsg_PersonaCred";
                        }
                        else if (Session["sintDepartamentoID"].ToString() == "28")
                        {
                            tabCredito.Visible = false;
                            tabPromocion.Visible = true;
                            Tabs.ActiveTab = tabPromocion;
                            btnGuardaPersona.ValidationGroup = "vsg_PersonaProm";
                        }
                    //else
                    //{
                    //    tblBusPersonas.Visible = false;
                    //    UPD_MotBusPersonas.Update();
                    //}

                }
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }

        }


        public void MensajeSist(string strMsj, short shTipoErr)
        {
            wucMensajeSist.setMensaje(strMsj, shTipoErr);
        }

        protected void btnCancelSeleccion_OnClick(object sender, EventArgs e)
        {
            //Session["negocio"] = null;
            //Session["Area"] = null;
            tblBusPersonas.Visible = false;
            tblBusCredito.Visible = false;
            UPD_MotBusCredito.Update();
            UPD_MotBusPersonas.Update();
            mdlSeleccion.Hide();
        }

        protected void btnClientes_OnClick(object sender, EventArgs e)
        {

            if (Session["sintDepartamentoID"].ToString() == "16" || Session["sintDepartamentoID"].ToString() == "17" || Session["sintDepartamentoID"].ToString() == "28" || Session["bitCapturaTodo"].ToString() == "1")
            {
                txtIDCliente.Text = Session["sintClienteID"].ToString() == "0" ? "" : Session["sintClienteID"].ToString();
                btnBuscarClientes_OnClick(null, null);
                tblBusPersonas.Visible = true;
                tblBusCredito.Visible = false;
                UPD_MotBusCredito.Update();
                UPD_MotBusPersonas.Update();
                mdlSeleccion.Hide();
            }
            else
            {
                wucMensajeSist.setMensaje("Sin Acceso al Modulo de captura de clientes", 2);
            }
        }

        protected void btnBuscarClientes_OnClick(object sender, EventArgs e)
        {
            try
            {
                InterfacesServicePersonas.interfacePersona intPers = new InterfacesServicePersonas.interfacePersona();
                intPers.vchTipo = Session["negocio"].ToString();
                intPers.vchNombre = txtNombrePersona.Text;
                intPers.intClienteID = int.Parse(txtIDCliente.Text == "" ? "0" : txtIDCliente.Text);


                ViewState["lstClientes"] = rsInterfaces.ListaBajawarePersonas(intPers);

                if (Session["negocio"].ToString() == "E")
                {
                    grvClientes.Columns[2].Visible = false;
                    grvClientes.Columns[3].Visible = false;
                    grvClientes.Columns[4].Visible = false;
                }
                else
                    grvClientes.Columns[5].Visible = false;

                grvClientes.DataSource = ViewState["lstClientes"];
                grvClientes.DataBind();
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }

        }

        protected void btnCreditos_OnClick(object sender, EventArgs e)
        {
            try
            {
                txtIDProyecto.Text = Session["sintCreditoID"].ToString() == "0" ? "" : Session["sintCreditoID"].ToString();
                btnBuscaCred_OnClick(null, null);
                tblBusPersonas.Visible = false;
                tblBusCredito.Visible = true;
                txtNombreProyecto.Visible = true;
                UPD_MotBusCredito.Update();
                UPD_MotBusPersonas.Update();

                mdlSeleccion.Hide();
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }
        }



        protected void btnGuardaPersona_Onclick(object sender, EventArgs e)
        {
            try
            {
                short shArea = 0;
                InterfacesServicePersonas.clsDatosPersona cls = null;

                if (Tabs.ActiveTab == tabPromocion)
                {
                    shArea = 1;

                    if (wucPersonaPromo.NoCorreos() == 0)
                    {
                        wucMensajeSist.setMensaje("El Correo Electronico es Obligatorio.", 3);
                        return;
                    }


                    if (!wucPersonaPromo.ExisteDomicilioFiscResid())
                    {
                        wucMensajeSist.setMensaje("Es Necesario Agregar el domicilio " + Session["negocio"].ToString() == "E" ? " Fiscal " : "Empresarial", 3);
                        return;
                    }

                    cls = wucPersonaPromo.ObtieneDatos();
                }
                else if (Tabs.ActiveTab == tabCredito)
                {
                    shArea = 2;

                    cls = wucPersonaCred.ObtieneDatos();
                }

                InterfacesServicePersonas.ServiceResult result = rsInterfaces.InsertaDatosPersonas(cls, shArea);
                wucMensajeSist.setMensaje(result.ErrorMessage, result.ServiceOk == true ? (short)1 : (short)2);

                if (result.ServiceOk == true)
                    mdlDatosPersna.Hide();
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }

        }



        #region Metodos grvPersonas

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvClientes_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownList dropDown = (DropDownList)sender;
                this.grvClientes.PageSize = int.Parse(dropDown.SelectedValue);
                grvClientes.DataSource = ViewState["lstClientes"];
                grvClientes.DataBind();
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvPersonas_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridView gridView = (GridView)sender;

            if (e.Row.RowType == DataControlRowType.Header)
            {

            }

            // Body
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

            }

            if (e.Row.RowType == DataControlRowType.Pager)
            {
                Label lblTotalNumberOfPages = (Label)e.Row.FindControl("grvClientes_lblTotalNumberOfPages");
                lblTotalNumberOfPages.Text = gridView.PageCount.ToString();

                TextBox txtGoToPage = (TextBox)e.Row.FindControl("grvClientes_txtGoToPage");
                txtGoToPage.Text = (gridView.PageIndex + 1).ToString();

                DropDownList ddlPageSize = (DropDownList)e.Row.FindControl("grvClientes_ddlPageSize");
                ddlPageSize.SelectedValue = gridView.PageSize.ToString();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvPersonas_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            if (e.NewPageIndex >= 0)
            {
                grvClientes.PageIndex = e.NewPageIndex;
                grvClientes.DataSource = ViewState["lstClientes"];
                grvClientes.DataBind();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvClientes_GoToPage_TextChanged(object sender, EventArgs e)
        {
            try
            {
                TextBox txtGoToPage = (TextBox)sender;

                int pageNumber;
                if (int.TryParse(txtGoToPage.Text.Trim(), out pageNumber) && pageNumber > 0 && pageNumber <= this.grvClientes.PageCount)
                {
                    this.grvClientes.PageIndex = pageNumber - 1;
                    grvClientes.DataSource = ViewState["lstClientes"];
                    grvClientes.DataBind();
                }
                else
                {
                    this.grvClientes.PageIndex = 0;
                    grvClientes.DataSource = ViewState["lstClientes"];
                    grvClientes.DataBind();
                }
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }

        }

        protected void grvPersonas_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "go")
                {


                    int intipersonaID = int.Parse(e.CommandArgument.ToString());

                    InterfacesServicePersonas.clsDatosPersona clsPers = rsInterfaces.ObtieneDatosPersona(intipersonaID, Session["negocio"].ToString());


                    if (Session["bitCapturaTodo"].ToString() == "1")
                    {
                        wucPersonaCred.HabilitaControles(Session["negocio"].ToString() == "I" ? true : false);
                        wucPersonaCred.HabilitaControlesPF(clsPers.intPersonalidadJuridica == 1 ? true : false);
                        wucPersonaCred.InsertaDatosPersona(clsPers);
                        wucPersonaPromo.HabilitaControles(Session["negocio"].ToString() == "I" ? true : false);
                        wucPersonaPromo.CargaDatos(intipersonaID);
                    }
                    else

                        if (Session["sintDepartamentoID"].ToString() == "16" || Session["sintDepartamentoID"].ToString() == "17")//Credito                    
                        {


                            wucPersonaCred.HabilitaControles(Session["negocio"].ToString() == "I" ? true : false);
                            wucPersonaCred.HabilitaControlesPF(clsPers.intPersonalidadJuridica == 1 ? true : false);
                            wucPersonaCred.InsertaDatosPersona(clsPers);
                        }

                        else
                        {
                            wucPersonaPromo.HabilitaControles(Session["negocio"].ToString() == "I" ? true : false);
                            wucPersonaPromo.CargaDatos(intipersonaID);
                        }



                    UPD_DatosCredito.Update();
                    UPD_DatosPromocion.Update();
                    mdlDatosPersna.Show();
                }
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }

        }

        #endregion




        #region Metodos grvCreditos
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvCreditos_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList dropDown = (DropDownList)sender;
            this.grvCreditos.PageSize = int.Parse(dropDown.SelectedValue);

            grvCreditos.DataSource = ViewState["lstCreditos"];
            grvCreditos.DataBind();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvCreditos_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridView gridView = (GridView)sender;

            if (e.Row.RowType == DataControlRowType.Header)
            {

                //
            }

            // Body
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

            }

            if (e.Row.RowType == DataControlRowType.Pager)
            {
                Label lblTotalNumberOfPages = (Label)e.Row.FindControl("grvCreditos_lblTotalNumberOfPages");
                lblTotalNumberOfPages.Text = gridView.PageCount.ToString();

                TextBox txtGoToPage = (TextBox)e.Row.FindControl("grvCreditos_txtGoToPage");
                txtGoToPage.Text = (gridView.PageIndex + 1).ToString();

                DropDownList ddlPageSize = (DropDownList)e.Row.FindControl("grvCreditos_ddlPageSize");
                ddlPageSize.SelectedValue = gridView.PageSize.ToString();
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvCreditos_RowDataBound(object sender, GridViewPageEventArgs e)
        {
            if (e.NewPageIndex >= 0)
            {
                grvCreditos.PageIndex = e.NewPageIndex;


                grvCreditos.DataSource = ViewState["lstCreditos"];
                grvCreditos.DataBind();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvCreditos_GoToPage_TextChanged(object sender, EventArgs e)
        {
            TextBox txtGoToPage = (TextBox)sender;

            int pageNumber;
            if (int.TryParse(txtGoToPage.Text.Trim(), out pageNumber) && pageNumber > 0 && pageNumber <= this.grvCreditos.PageCount)
            {
                this.grvCreditos.PageIndex = pageNumber - 1;

                grvCreditos.DataSource = ViewState["lstCreditos"];
                grvCreditos.DataBind();
            }
            else
            {
                this.grvCreditos.PageIndex = 0;
                grvCreditos.DataSource = ViewState["lstCreditos"];
                grvCreditos.DataBind();
            }
        }



        protected void grvCreditos_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandArgument.ToString() != "Next" && e.CommandArgument.ToString() != "Prev")
                {
                    int intCredID = int.Parse(e.CommandArgument.ToString());
                    short shDepto = Session["bitCapturaTodo"].ToString() == "1" ? (short)-1 : short.Parse(Session["sintDepartamentoID"].ToString());

                    wucListaInterfaces.CargaGrid(rsInterfaceService.ListadoInterfacesPorNegocio(char.Parse(Session["negocio"].ToString()), shDepto), intCredID);
                    mdlListaInterface.Show();
                }
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }
        }


        #endregion


        #region Creditos


        protected void btnBuscaCred_OnClick(object sender, EventArgs e)
        {

            try
            {
                InterfacesService.CreditosBusqueda busqueda = new InterfacesService.CreditosBusqueda();

                busqueda.intOperacionID = int.Parse(txtIDProyecto.Text == "" ? "0" : txtIDProyecto.Text);
                busqueda.strNombre = txtNombreAcred.Text;
                busqueda.strDesarrollo = txtNombreProyecto.Text;
                busqueda.strTipoNegocio = Session["negocio"].ToString();

                ViewState["lstCreditos"] = rsInterfaceService.ObtieneCreditos(busqueda);

                if (Session["negocio"].ToString() == "I")
                {
                    grvCreditos.Columns[3].Visible = false;
                }

                grvCreditos.DataSource = ViewState["lstCreditos"];
                grvCreditos.DataBind();
                UPD_MotBusCredito.Update();
            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }
        }

        #endregion


        protected void btnGenera_OnClick(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect("frmInterfaces.aspx");

            }
            catch (Exception ex)
            {
                wucMensajeSist.setMensaje(ex.Message, 2);
            }
        }

    }
}