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

namespace bajaWare.UserControl.Aval
{
    public partial class wucAvalCredito : System.Web.UI.UserControl
    {
        public delegate void getRegistroEventHandler(string mensaje, Int16 sintTipo);
        public event getRegistroEventHandler getRegistroEvent;

        public InterfacesServicesCatalogos.IinterfacesServicesCatalogos rsCatalogos = new InterfacesServicesCatalogos.IinterfacesServicesCatalogosClient();
        public InterfacesServicePersonas.IinterfacesServiceDomicilio rsDomicilio = new InterfacesServicePersonas.IinterfacesServiceDomicilioClient();
        public InterfaceServicesAvales.IinterfacesServiceAval rsAval = new InterfaceServicesAvales.IinterfacesServiceAvalClient();

        public int intPersonaID
        {
            get
            {
                if (ViewState["intPersonaID"] == null)
                    return 0;
                else
                    return (int)ViewState["intPersonaID"];
            }
            set { ViewState.Add("intPersonaID", value); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.wucDomicilio.getRegistroEvent += new bajaWare.UserControl.Comun.wucDomicilio.getRegistroEventHandler(mantieneModal);
            if (!IsPostBack)
            {
                LlenaCombos();
               
              
            }

        }

        void LlenaCombos()
        {

            ddlPersonalidadJuridica.DataSource = rsCatalogos.ListadoPersonalidadJuridica();
            ddlPersonalidadJuridica.DataTextField = "vchInterface";
            ddlPersonalidadJuridica.DataValueField = "intInterfaceid";
            ddlPersonalidadJuridica.DataBind();
            ddlTipoAval.DataSource = rsCatalogos.ListadoTipoAval();
            ddlTipoAval.DataTextField = "vchInterface";
            ddlTipoAval.DataValueField = "intInterfaceid";
            ddlTipoAval.DataBind();
            ddlInsdustria.DataSource = rsCatalogos.ListadoIndustria();
            ddlInsdustria.DataTextField = "vchInterface";
            ddlInsdustria.DataValueField = "intInterfaceid";
            ddlInsdustria.DataBind();
            ddlRiesgoIndustria.DataSource = rsCatalogos.ListadoGradoRiesgo();
            ddlRiesgoIndustria.DataTextField = "vchInterface";
            ddlRiesgoIndustria.DataValueField = "intInterfaceid";
            ddlRiesgoIndustria.DataBind();
            dllRiesgoFinanciero.DataSource = rsCatalogos.ListadoGradoRiesgo();
            dllRiesgoFinanciero.DataTextField = "vchInterface";
            dllRiesgoFinanciero.DataValueField = "intInterfaceid";
            dllRiesgoFinanciero.DataBind();
            dllRiesgoExperienciaPago.DataSource = rsCatalogos.ListadoGradoRiesgo();
            dllRiesgoExperienciaPago.DataTextField = "vchInterface";
            dllRiesgoExperienciaPago.DataValueField = "intInterfaceid";
            dllRiesgoExperienciaPago.DataBind();
        }
        void CargaDatos(int IdPersona)
        {
            ViewState["lstDomicilio"] = rsDomicilio.ObtieneDomicilio(IdPersona, Session["negocio"].ToString());
            grvDomiciliosCliente.DataSource = ViewState["lstDomicilio"];
            grvDomiciliosCliente.DataBind();
        }
        public void LLenaDatos(int consec)
        {
            InterfaceServicesAvales.Aval aval = new InterfaceServicesAvales.Aval();
            aval = rsAval.ObtieneAvales(consec).First();
            txtNombre.Text = aval.sPrimerNombre + (aval.sSegundoNombre == string.Empty ? string.Empty : " " + aval.sSegundoNombre);
            txtApeMaterno.Text = aval.sApellidoMaterno;
            txtApePaterno.Text = aval.sApellidoPaterno;
            ddlPersonalidadJuridica.SelectedValue = aval.iCveRegimenFiscal.ToString();
            txtRFC.Text = aval.RFC;
            ddlInsdustria.SelectedValue = aval.sintActividadINEGIID.ToString();
            ddlRiesgoIndustria.SelectedValue = aval.tintRiesgoIndustriaID.ToString();
            ddlTipoAval.SelectedValue = aval.tintTipoAvalID.ToString();
            dllRiesgoExperienciaPago.SelectedValue = aval.tintRiesgoExperPagoID.ToString();
            dllRiesgoFinanciero.SelectedValue = aval.tintRiesgoFinancieroID.ToString();
            CargaDatos(aval.iParticipeId);
            intPersonaID = aval.iParticipeId;
            if (rsDomicilio.ExisteDomicilio(int.Parse(ViewState["intPersonaID"].ToString()), Session["negocio"].ToString()))
            {
                btnAgregaDomicilio.Visible = false;
            }
            else
            {
                btnAgregaDomicilio.Visible = true;
            }

            MuestraOculta();
            
             
        }

        #region GridView


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

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


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

            }

        }



        protected void grvDomiciliosCliente_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "go")
                {
                    int intDomicilioID = int.Parse(e.CommandArgument.ToString());
                    //wucPersonaCred.InsertaDatosPErsona(rsInterfaces.ObtieneDatosPersona(intipersonaID));

                    bajaWare.InterfacesServicePersonas.clsDomicilio[] lstDomic = (bajaWare.InterfacesServicePersonas.clsDomicilio[])ViewState["lstDomicilio"];//.Where(a => a.intDomicilioID == intDomicilioID).First();                    
                    bajaWare.InterfacesServicePersonas.clsDomicilio clsDatDomicilio = lstDomic.Where(a => a.intDomicilioID == intDomicilioID).First();

                    // CargaControlesInicialesDomicilio();

                    clsDatDomicilio.intDomicilioID = int.Parse(e.CommandArgument.ToString());

                    wucDomicilio.CargaDatos(clsDatDomicilio);

                    //rsDomicilio.ObtieneDomicilio();
                    mdlDatosDomicilio.Show();

                    // Response.Redirect("../Cliente/frmClientes.aspx?personaID="+intipersonaID.ToString());
                }
                //{
                //    case "detallePrecio":

            }
            catch (Exception ex)
            {
                getRegistroEvent.Invoke(ex.Message, 2);
            }
        }



        #endregion

        public bool InsertaActualiza(InterfaceServicesAvales.Aval aval,out bool bolDomicilio)
        {
            bolDomicilio = false;
            if (grvDomiciliosCliente.Rows.Count == 0)
            {
                bolDomicilio = true;
                //Parent
                //ScriptManager.RegisterStartupScript(Parent.FindControl("UPD_pnlAccionista"), Parent.FindControl("UPD_pnlAccionista").GetType(), "Aviso", "alert('Debe Agregar un domicilio Fiscal'", true);
                return false;
            }
            aval.sPrimerNombre = txtNombre.Text.Split(' ')[0];
            if (txtNombre.Text.Split(' ').Length > 1)
                aval.sSegundoNombre = txtNombre.Text.Split(' ')[1];
            if (ddlPersonalidadJuridica.SelectedValue == "2")
            {
                aval.sApellidoPaterno = string.Empty;
                aval.sApellidoMaterno = string.Empty;
            }
            else{
                aval.sApellidoPaterno = txtApePaterno.Text;
                aval.sApellidoMaterno = txtApeMaterno.Text;
            }
            aval.RFC = txtRFC.Text;
            aval.sintActividadINEGIID = Convert.ToInt16(ddlInsdustria.SelectedValue);
            aval.tintRiesgoExperPagoID = Convert.ToInt16(dllRiesgoExperienciaPago.SelectedValue);
            aval.tintRiesgoFinancieroID = Convert.ToInt16(dllRiesgoFinanciero.SelectedValue);
            aval.tintRiesgoIndustriaID = Convert.ToInt16(ddlRiesgoIndustria.SelectedValue);
            aval.iCveRegimenFiscal = Convert.ToInt32(ddlPersonalidadJuridica.SelectedValue);
            aval.tintTipoAvalID = Convert.ToInt16(ddlTipoAval.SelectedValue);
            InterfaceServicesAvales.ServiceResult resultado= rsAval.InsertaActualizaAval(aval);
            //if (result.ServiceOk)
            //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Inserto", "alert('Se actualizo el registro correctamente')", true);
            //else
            //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Error", "No se puedo Insertar el Registro", true);
            
            return true;
        }
        // public InterfacesServicePersonas.

        protected void btnGuardaDomicilio_OnClick(object sender, EventArgs e)
        {
            try
            {
                bajaWare.InterfacesServicePersonas.clsDomicilio clsDom = wucDomicilio.ObtieneDatosDomicilio();

                if (clsDom.intDomicilioID == 0)
                    if (rsDomicilio.ExisteDomicilio(int.Parse(ViewState["intPersonaID"].ToString()),Session["negocio"].ToString()))
                    {
                  
                        ScriptManager.RegisterStartupScript(UPD_pnlGuardaDomicilio, typeof(UpdatePanel), "MsjNoExiste", "javascript:alert('No es posible agregar  mas de un domicilios fiscal.');", true);
                        return;
                    }

                clsDom.intPersonaID = int.Parse(intPersonaID.ToString());

                rsDomicilio.InsertaDomicilio(clsDom);

                CargaDatos(int.Parse(intPersonaID.ToString()));

            }
            catch (Exception ex)
            {
                getRegistroEvent.Invoke(ex.Message, 2);
            }
        }

        public void mantieneModal()
        {
            mdlDatosDomicilio.Show();
        }

        protected void btnAgregaDomicilio_Click(object sender, EventArgs e)
        {
            //mantieneModal();
            //bajaWare.InterfacesServicePersonas.clsDomicilio clsDomicilio = new InterfacesServicePersonas.clsDomicilio();
           
            //wucDomicilio.CargaDatos(clsDomicilio);
            mdlDatosDomicilio.Show();
            wucDomicilio.CargaDatos(new InterfacesServicePersonas.clsDomicilio());
            UPD_DatosDomicilio.Update();
            mdlDatosDomicilio.Show();
            
        }

        protected void btnCierraDomicilio_Click(object sender, EventArgs e)
        {
            mdlDatosDomicilio.Hide();
        }
        private void MuestraOculta()
        {
            if (ddlPersonalidadJuridica.SelectedValue == "2")
            {
                txtApePaterno.Visible = false;
                txtApeMaterno.Visible = false;
                tdApePaterno.Visible = false;
                tdApeMaterno.Visible = false;
                rfv_txtApePaterno.Enabled = false;
                rfv_txtApeMaterno.Enabled = false;
                rev_txtRFC.ValidationExpression = @"^(([A-Z]|[a-z]|\s){1})(([A-Z]|[a-z]){2})([0-9]{6})((([A-Z]|[a-z]|[0-9]){3}))|^(([A-Z]|[a-z]|\s){1})(([A-Z]|[a-z]){2})([0-9]{6})";
                fte_txtNombre.Enabled = false;
            }
            else
            {
                txtApePaterno.Visible = true;
                txtApeMaterno.Visible = true;
                tdApePaterno.Visible = true;
                tdApeMaterno.Visible = true;
                rfv_txtApePaterno.Enabled = true;
                rfv_txtApeMaterno.Enabled = true;
                rev_txtRFC.ValidationExpression = @"^(([A-Z]|[a-z]|\s){1})(([A-Z]|[a-z]){3})([0-9]{6})((([A-Z]|[a-z]|[0-9]){3}))|^(([A-Z]|[a-z]|\s){1})(([A-Z]|[a-z]){3})([0-9]{6})";
                fte_txtNombre.Enabled = true;
            }
        }

        protected void ddlPersonalidadJuridica_SelectedIndexChanged(object sender, EventArgs e)
        {
            MuestraOculta();
        }

        protected void AgregaDomicilio_OnClick(object sender, ImageClickEventArgs e)
        {
            mdlDatosDomicilio.Show();
            wucDomicilio.CargaDatos(new InterfacesServicePersonas.clsDomicilio());
            UPD_DatosDomicilio.Update();
            mdlDatosDomicilio.Show();
        }
    }
}
