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

namespace bajaWare.UserControl.Cliente
{
    public partial class wucPersonaPromocion : System.Web.UI.UserControl
    {

        public delegate void getRegistroEventHandler(string mensaje, Int16 sintTipo);
        public event getRegistroEventHandler getRegistroEventPromo;



        public InterfacesServicesCatalogos.IinterfacesServicesCatalogos rsCatalogos = new InterfacesServicesCatalogos.IinterfacesServicesCatalogosClient();

        public InterfacesServicePersonas.IinterfacesServiceDomicilio rsDomicilio = new InterfacesServicePersonas.IinterfacesServiceDomicilioClient();

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



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

            try
            {
                if (!IsPostBack)
                {
                    CargaDropDownList();
                }
            }
            catch (Exception ex)
            {
                getRegistroEventPromo.Invoke(ex.Message, 2);
            }
        }


        public void CargaDatos(int intPersonaID)
        {
            try
            {
                ViewState["intPersonaID"] = intPersonaID;

                InterfacesServicePersonas.clsDatosPersona clsPersona = rsDatosPersona.ObtieneDatosPersona(intPersonaID, Session["negocio"].ToString());

                CargaDropDownList();


                txtNombre.Text = clsPersona.strNombre;
                txtApPaterno.Text = clsPersona.strApPaterno;
                txtApMaterno.Text = clsPersona.strApMaterno;

                if (Session["negocio"].ToString() == "E")
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "Oculta", "javascript:FisicaMoral('M');", true);
                    regexRFCValid.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})";
                }

                txtRFC.Text = clsPersona.strRFC;
                txtNumEmpleados.Text = clsPersona.shNumeroEmpleados.ToString();
                txtTelefono.Text = clsPersona.strTelefono.ToString();
                txtNombreCNBV.Text = clsPersona.strNombreCNBV;

                ddlFisicaMoral.SelectedValue = clsPersona.intPersonalidadJuridica.ToString();
                if (clsPersona.intPersonalidadJuridica.ToString() == "1")
                    rfv_txtNumEmpleados.ValidationGroup = "";
                else
                    rfv_txtNumEmpleados.ValidationGroup = "vsg_PersonaProm";

                try
                {
                    ddlEjecutivo.SelectedValue = clsPersona.intEjecutivoID.ToString() == "0" ? "-1" : clsPersona.intEjecutivoID.ToString();
                }
                catch
                {
                    ddlEjecutivo.SelectedValue = "-1";

                }



                try
                {
                    ddlIndustria.SelectedValue = clsPersona.shIndustria.ToString();
                }
                catch { }
                try
                {
                    ddlSectorEconomico.SelectedValue = clsPersona.shSectorEconomico.ToString();
                }
                catch { }
                try
                {
                    ddlSucursal.SelectedValue = clsPersona.shSucursalID.ToString();
                }
                catch { }
                try
                {
                    ddlActividadEconomica.SelectedValue = clsPersona.shActividadEconomicaID.ToString();
                }
                catch { }


                ViewState["lstDomicilio"] = rsDomicilio.ObtieneDomicilio(intPersonaID, Session["negocio"].ToString());

                grvDomiciliosCliente.DataSource = ViewState["lstDomicilio"];
                grvDomiciliosCliente.DataBind();
                UPD_DatosDomicilio.Update();
                FillGridCorreo(intPersonaID);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public void HabilitaControles(bool isIndividual)
        {
            txtNumEmpleados.Enabled = !isIndividual;
            if (isIndividual)
            {
                txtNumEmpleados.BackColor = System.Drawing.Color.Orange;
                rfv_txtNumEmpleados.ValidationGroup = "";
            }
        }


        public InterfacesServicePersonas.clsDatosPersona ObtieneDatos()
        {
            try
            {
                InterfacesServicePersonas.clsDatosPersona clsPersona = new InterfacesServicePersonas.clsDatosPersona();


                clsPersona.intPersonaID = int.Parse(ViewState["intPersonaID"].ToString());
                clsPersona.strNegocio = Session["negocio"].ToString();

                clsPersona.strRFC = txtRFC.Text;

                clsPersona.strNombre = txtNombre.Text;
                clsPersona.strApPaterno = txtApPaterno.Text;
                clsPersona.strApMaterno = txtApMaterno.Text;

                clsPersona.shActividadEconomicaID = short.Parse(ddlActividadEconomica.SelectedValue == "" ? "0" : ddlActividadEconomica.SelectedValue);
                clsPersona.shNumeroEmpleados = short.Parse(txtNumEmpleados.Text);
                clsPersona.strTelefono = txtTelefono.Text;
                clsPersona.intPersonalidadJuridica = int.Parse(ddlFisicaMoral.SelectedValue);
                clsPersona.intEjecutivoID = int.Parse(ddlEjecutivo.SelectedValue);
                clsPersona.shIndustria = short.Parse(ddlIndustria.SelectedValue);
                clsPersona.shSectorEconomico = short.Parse(ddlSectorEconomico.SelectedValue);
                clsPersona.strNombreCNBV = txtNombreCNBV.Text;
                clsPersona.shSucursalID = short.Parse(ddlSucursal.SelectedValue);

                return clsPersona;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        public void CargaDropDownList()
        {
            try
            {
                ddlActividadEconomica.DataSource = rsCatalogos.ListaActivides();
                ddlActividadEconomica.DataTextField = "vchInterface";
                ddlActividadEconomica.DataValueField = "intInterfaceid";
                ddlActividadEconomica.DataBind();

                ddlSectorEconomico.DataSource = rsCatalogos.ListaActivides();
                ddlSectorEconomico.DataTextField = "vchInterface";
                ddlSectorEconomico.DataValueField = "intInterfaceid";
                ddlSectorEconomico.DataBind();

                ddlFisicaMoral.DataSource = rsCatalogos.ListaPersonalidadJuridica();
                ddlFisicaMoral.DataTextField = "vchInterface";
                ddlFisicaMoral.DataValueField = "intInterfaceid";
                ddlFisicaMoral.DataBind();

                ddlEjecutivo.DataSource = rsCatalogos.ListadoEjecutivosBancarios();
                ddlEjecutivo.DataTextField = "vchInterface";
                ddlEjecutivo.DataValueField = "intInterfaceid";
                ddlEjecutivo.DataBind();

                ddlSucursal.DataSource = rsCatalogos.ListadoSucursalesBancarias();
                ddlSucursal.DataTextField = "vchInterface";
                ddlSucursal.DataValueField = "intInterfaceid";
                ddlSucursal.DataBind();

                ddlIndustria.DataSource = rsCatalogos.ListadoIndustria();
                ddlIndustria.DataTextField = "vchInterface";
                ddlIndustria.DataValueField = "intInterfaceid";
                ddlIndustria.DataBind();

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        protected void AgregaDomicilio_OnClick(object sender, EventArgs e)
        {

            if (Session["negocio"].ToString() == "E")
                ScriptManager.RegisterStartupScript(this, GetType(), "Oculta", "javascript:FisicaMoral('M');", true);
            wucDomicilio.CargaDatos(new InterfacesServicePersonas.clsDomicilio());
            UPD_DatosDomicilio.Update();
            mdlDatosDomicilio.Show();
        }





        #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());
                    bajaWare.InterfacesServicePersonas.clsDomicilio[] lstDomic = (bajaWare.InterfacesServicePersonas.clsDomicilio[])ViewState["lstDomicilio"];
                    bajaWare.InterfacesServicePersonas.clsDomicilio clsDatDomicilio = lstDomic.Where(a => a.intDomicilioID == intDomicilioID).First();
                    clsDatDomicilio.intDomicilioID = int.Parse(e.CommandArgument.ToString());
                    wucDomicilio.CargaDatos(clsDatDomicilio);
                    UPD_Datos.Update();
                    mdlDatosDomicilio.Show();
                }
            }
            catch (Exception ex)
            {
                getRegistroEventPromo.Invoke(ex.Message, 2);
            }
        }

        #endregion

        #region GridView Correo

        public void FillGridCorreo(int iPersonaID)
        {

            InterfacesServicePersonas.CorreoPersona[] lstCorreos = rsDatosPersona.ObtieneCorreos(iPersonaID);


            if (lstCorreos.Count() > 0)
            {
                grdContact.DataSource = lstCorreos;
                grdContact.DataBind();
            }
            else
            {
                InterfacesServicePersonas.CorreoPersona clsCorr = new InterfacesServicePersonas.CorreoPersona();
                InterfacesServicePersonas.CorreoPersona[] ls = { clsCorr };

                grdContact.DataSource = ls;
                grdContact.DataBind();

                int TotalColumns = grdContact.Rows[0].Cells.Count;
                grdContact.Rows[0].Cells.Clear();
                grdContact.Rows[0].Cells.Add(new TableCell());
                grdContact.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                grdContact.Rows[0].Cells[0].Text = "Sin Correos";
            }

            UPD_Correo.Update();
        }

        protected void grdContact_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
            }
        }

        protected void grdContact_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grdContact.EditIndex = -1;
            FillGridCorreo(int.Parse(ViewState["intPersonaID"].ToString()));
        }

        protected void grdContact_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {


            InterfacesServicePersonas.CorreoPersona clsCorr = new InterfacesServicePersonas.CorreoPersona();

            TextBox txtName = (TextBox)grdContact.Rows[e.RowIndex].FindControl("txtCorreo");

            HiddenField hdnID = (HiddenField)grdContact.Rows[e.RowIndex].FindControl("hdnID");
            clsCorr.intCorreoID = int.Parse(hdnID.Value);
            clsCorr.strCorreo = txtName.Text;
            InterfacesServicePersonas.CorreoPersona[] ls = { clsCorr };
            rsDatosPersona.InsertaCorreos(ls, int.Parse(ViewState["intPersonaID"].ToString()));

            grdContact.EditIndex = -1;
            FillGridCorreo(int.Parse(ViewState["intPersonaID"].ToString()));

        }

        protected void grdContact_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //ContactTableAdapter contact = new ContactTableAdapter();
            int id = Convert.ToInt32(grdContact.DataKeys[e.RowIndex].Values[0].ToString());
            rsDatosPersona.EliminarCorreos(id);
            FillGridCorreo(int.Parse(ViewState["intPersonaID"].ToString()));
        }

        protected void grdContact_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Insert"))
            {

                InterfacesServicePersonas.CorreoPersona clsCorr = new InterfacesServicePersonas.CorreoPersona();

                TextBox txtNewCorreo = (TextBox)grdContact.FooterRow.FindControl("txtNewCorreo");
                clsCorr.intCorreoID = 0;
                clsCorr.strCorreo = txtNewCorreo.Text;
                InterfacesServicePersonas.CorreoPersona[] ls = { clsCorr };
                rsDatosPersona.InsertaCorreos(ls, int.Parse(ViewState["intPersonaID"].ToString()));
                FillGridCorreo(int.Parse(ViewState["intPersonaID"].ToString()));

            }
        }

        protected void grdContact_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grdContact.EditIndex = e.NewEditIndex;
            FillGridCorreo(int.Parse(ViewState["intPersonaID"].ToString()));
        }



        #endregion


        protected void ddlFisicaMoral_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlFisicaMoral.SelectedValue == "1")
                ScriptManager.RegisterStartupScript(this, GetType(), "Oculta", "javascript:FisicaMoral('F');", true);
            else
                ScriptManager.RegisterStartupScript(this, GetType(), "Oculta", "javascript:FisicaMoral('M');", true);


        }

        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()))
                    {
                        String strTipDom = Session["negocio"].ToString() == "E" ? " Fiscal " : " de Residencia";

                        ScriptManager.RegisterStartupScript(UPD_pnlGuardaDomicilio, typeof(UpdatePanel), "MsjNoExiste", "javascript:alert('No es posible agregar  mas de un domicilio " + strTipDom + ".');", true);
                        return;
                    }


                clsDom.intPersonaID = int.Parse(ViewState["intPersonaID"].ToString());
                InterfacesServicePersonas.ServiceResult result = rsDomicilio.InsertaDomicilio(clsDom);

                if (result.ServiceOk == true)
                    mdlDatosDomicilio.Hide();


                getRegistroEventPromo.Invoke(result.ErrorMessage, result.ServiceOk == true ? (short)1 : (short)2);

                ViewState["lstDomicilio"] = rsDomicilio.ObtieneDomicilio(int.Parse(ViewState["intPersonaID"].ToString()), Session["negocio"].ToString());
                grvDomiciliosCliente.DataSource = ViewState["lstDomicilio"];
                grvDomiciliosCliente.DataBind();

                UPD_GridDomicilio.Update();



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

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

        public int NoCorreos()
        {
            if (grdContact.Rows[0].Cells[0].Text == "Sin Correos")
            {
                return 0;
            }

            return grdContact.Rows.Count;
        }

        public bool ExisteDomicilioFiscResid()
        {
            bool blIsFiscal = false;

            foreach (GridViewRow item in grvDomiciliosCliente.Rows)
            {

                if (item.Cells[2].Text == "FISCAL" || item.Cells[2].Text == "RESIDENCIA")
                    blIsFiscal = true;


            }
            return blIsFiscal;

        }
    }
}