//		public bool DeleteByFleteTopeID(int clave)
//		{
//			using (SqlConnection conexion = new SqlConnection())
//			{
//				SqlTransaction transaccion = null;
//				conexion.ConnectionString = Config.ConnectionString;
//				try
//				{
//					conexion.Open();
//					transaccion = conexion.BeginTransaction();
//					ITarifarioTope oTariTope = this.GetTarifarioTopeByTopeID(clave);
//					if(oTariTope.Eliminar())
//					tarifariosTope.Remove(oTariTope);
//					//Se instancia un objeto de TarifarioClienteRetiroEntrega para por utilizar el metodo validar (Bety)
//					TarifarioClienteRetiroEntrega oTari= new TarifarioClienteRetiroEntrega();
//					oTari.TarifarioID=this.TarifarioID;
//					oTari.ValidarTarifario(transaccion);
//					transaccion.Commit();
//				}
//				catch (Exception)
//				{
//					transaccion.Rollback();
//					return false;
//				}
//			}
//			return true;
//		}

        public bool DeleteByFleteTopeID(int clave, int usuarioID)
        {
            using (SqlConnection conexion = new SqlConnection())
            {
                SqlTransaction transaccion = null;
                conexion.ConnectionString = Config.ConnectionString;
                try
                {
                    conexion.Open();
                    transaccion = conexion.BeginTransaction();
                    ITarifarioTope oTariTope = this.GetTarifarioTopeByTopeID(clave);
                    if (oTariTope.Eliminar(usuarioID))
                    {
                        tarifariosTope.Remove(oTariTope);
                    }
                    //Se instancia un objeto de TarifarioClienteRetiroEntrega para por utilizar el metodo validar (Bety)
                    TarifarioClienteRetiroEntrega oTari = new TarifarioClienteRetiroEntrega();
                    oTari.TarifarioID = this.TarifarioID;
                    oTari.ValidarTarifario(transaccion);
                    transaccion.Commit();
                }
                catch (Exception)
                {
                    transaccion.Rollback();
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        /// Método que recupera los topes de un tarifario, a partir de la coleccion de topes.
        /// Primero se tiene que haber consultado el tarifario y llenado las colecciones.
        /// </summary>
        /// <returns>Retorna un dataset</returns>
        public DataView GetTopesDataSet()
        {
            DataSet   ds = new DataSet();
            DataTable dt = new DataTable();
            DataRow   dr;

            dt.Columns.Add(new DataColumn("TarifarioClienteRetiroEntregaID"));
            dt.Columns.Add(new DataColumn("TopeID"));
            dt.Columns.Add(new DataColumn("TopeKgHasta", System.Type.GetType("System.Int32")));
            dt.Columns.Add(new DataColumn("Cm3Hasta"));
            dt.Columns.Add(new DataColumn("Importe"));
            dt.Columns.Add(new DataColumn("ImporteBultoExc"));
            dt.Columns.Add(new DataColumn("KgVariable"));


            for (int i = 0; i < TopesCol.getCount(); i++)
            {
                dr = dt.NewRow();
                ITarifarioTope tope = TopesCol.GetTarifarioTope(i);
                dr[0] = tope.TarifarioID;
                dr[1] = tope.Tope.TopeID;
                dr[2] = tope.Tope.TopeKgHasta;
                dr[3] = tope.Cm3Hasta;
                dr[4] = tope.Importe;
                dr[5] = tope.ImporteBultoExc;
                dr[6] = tope.KgVariable;

                dt.Rows.Add(dr);
            }
            ds.Tables.Add(dt);
            //Se ordena el arreglo mediante el criterio de Tope Hasta
            ds.Tables[0].DefaultView.Sort = "TopeKgHasta";

            return(ds.Tables[0].DefaultView);
        }
//		public bool DeleteByFleteTopeID(int clave, System.Data.SqlClient.SqlTransaction transaccion)
//		{
//			try
//			{
//				ITarifarioTope oTariTope = this.GetTarifarioTopeByTopeID(clave);
//				if(oTariTope.Eliminar(transaccion))
//					this.tarifariosTope.Remove(oTariTope);
//				return true;
//			}
//			catch(Exception)
//			{
//				return false;
//			}
//		}

        public bool DeleteByFleteTopeID(int clave, int usuarioID, System.Data.SqlClient.SqlTransaction transaccion)
        {
            try
            {
                ITarifarioTope oTariTope = this.GetTarifarioTopeByTopeID(clave);
                if (oTariTope.Eliminar(usuarioID, transaccion))
                {
                    this.tarifariosTope.Remove(oTariTope);
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
//		public bool DeleteByFleteTopeID(int clave)
//		{
//			try
//			{
//				ITarifarioTope oTariTope = this.GetTarifarioTopeByTopeID(clave);
//				if(oTariTope.Eliminar())
//					this.tarifariosTope.Remove(oTariTope);
//				return true;
//			}
//			catch(Exception)
//			{
//				return false;
//			}
//		}

        public bool DeleteByFleteTopeID(int clave, int usuarioID)
        {
            try
            {
                ITarifarioTope oTariTope = this.GetTarifarioTopeByTopeID(clave);
                if (oTariTope.Eliminar(usuarioID))
                {
                    this.tarifariosTope.Remove(oTariTope);
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public bool Consultar()
        {
            DsTarifariosClienteRetiroEntregaTope ds = (DsTarifariosClienteRetiroEntregaTope)this.GetTarifariosTopeDataSet();

            if (ds == null)
            {
                return(false);
            }
            DsTarifariosClienteRetiroEntregaTope.DatosRow dr = null;
            for (int i = 0; i < ds.Datos.Rows.Count; i++)
            {
                dr = (DsTarifariosClienteRetiroEntregaTope.DatosRow)ds.Datos.Rows[i];
                ITarifarioTope oTarifarioTope = (ITarifarioTope)this.AddTarifarioTope();
                oTarifarioTope.Cargar(dr);
            }
            return(true);
        }
//		public bool DeleteByFleteTopeID(int clave, System.Data.SqlClient.SqlTransaction transaccion)
//		{
//			try
//			{
//				ITarifarioTope oTariTope = this.GetTarifarioTopeByTopeID(clave);
//				if(oTariTope.Eliminar(transaccion))
//					tarifariosTope.Remove(oTariTope);
//
//				//Se instancia un objeto de TarifarioRetiroEntrega para por utilizar el metodo validar (Bety)
//				TarifarioRetiroEntrega oTari= new TarifarioRetiroEntrega();
//				oTari.TarifarioID=this.TarifarioID;
//				oTari.ValidarTarifario(transaccion);
//				return true;
//			}
//			catch(Exception)
//			{
//				return false;
//			}
//		}
// Borrar este método
        public bool DeleteByFleteTopeID(int clave, int usuairoID, System.Data.SqlClient.SqlTransaction transaccion)
        {
            try
            {
                ITarifarioTope oTariTope = this.GetTarifarioTopeByTopeID(clave);
                if (oTariTope.Eliminar(usuairoID, transaccion))
                {
                    tarifariosTope.Remove(oTariTope);
                }

                //Se instancia un objeto de TarifarioRetiroEntrega para por utilizar el metodo validar (Bety)
                TarifarioRetiroEntrega oTari = new TarifarioRetiroEntrega();
                oTari.TarifarioID = this.TarifarioID;
                oTari.ValidarTarifario(transaccion);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        private void butTopes_Click(object sender, System.EventArgs e)
        {
            ITarifariosTopeCol tariTopes = tari.TopesCol;

            tariTopes.TarifarioID = tari.TarifarioID;
            string vol = "";
            double importe, importeBultoExc;
            bool   bul     = false;
            bool   bulKilo = false;
            bool   isOK    = true;

            /*SFE Se agrega validador de volumen para Bulto_Variable, a pedido de Carlos Marcon*/
            if (tari.ValorizacionTarifario == SisPack.ValorizacionTarifario.Bulto || tari.ValorizacionTarifario == SisPack.ValorizacionTarifario.Bulto_Variable)
            {
                bul = true;
            }
            if (tari.ValorizacionTarifario == SisPack.ValorizacionTarifario.Bulto_Kilogramo)
            {
                bul     = true;
                bulKilo = true;
            }
            // SFE: Borrar esto si no se usa. Es decir si no se muestra el excedente por bulto_variable
//			/*SFE Agregar Validador para Bulto Variable en el importe bulto excedente*/
//			if(tari.ValorizacionTarifario == SisPack.ValorizacionTarifario.Bulto_Variable)
//			{
//				bulKilo = true;
//			}
            foreach (DataGridItem item in dtgTopesDisponibles.Items)
            {
                if (((CheckBox)item.FindControl("chkTopeDisp")).Checked)
                {
                    if (bul)
                    {
                        BaseValidator          valVolumen = (RegularExpressionValidator)((PlaceHolder)item.FindControl("phValidVol")).FindControl("valVolumen");
                        RequiredFieldValidator reqVolumen = (RequiredFieldValidator)((PlaceHolder)item.FindControl("phValidVol")).FindControl("reqVolumen");
                        valVolumen.Enabled = true;
                        reqVolumen.Enabled = true;
                        valVolumen.Validate();
                        reqVolumen.Validate();
                        if (!valVolumen.IsValid || !reqVolumen.IsValid)
                        {
                            isOK = false;
                        }
                        //}
                        if (bulKilo)
                        {
                            BaseValidator          valImporteBultoDisp = (RegularExpressionValidator)((PlaceHolder)item.FindControl("phValidImporteBultoDisp")).FindControl("valImporteBultoDisp");
                            RequiredFieldValidator reqImporteBultoDisp = (RequiredFieldValidator)((PlaceHolder)item.FindControl("phValidImporteBultoDisp")).FindControl("reqImporteBultoDisp");
                            valImporteBultoDisp.Enabled = true;
                            reqImporteBultoDisp.Enabled = true;
                            valImporteBultoDisp.Validate();
                            reqImporteBultoDisp.Validate();
                            if (!valImporteBultoDisp.IsValid || !reqImporteBultoDisp.IsValid)
                            {
                                isOK = false;
                            }
                        }
                    }
                    BaseValidator          valImporteDisp = (RegularExpressionValidator)((PlaceHolder)item.FindControl("phValidImporteDisp")).FindControl("valImporteDisp");
                    RequiredFieldValidator reqImporteDisp = (RequiredFieldValidator)((PlaceHolder)item.FindControl("phValidImporteDisp")).FindControl("reqImporteDisp");
                    valImporteDisp.Enabled = true;
                    reqImporteDisp.Enabled = true;
                    valImporteDisp.Validate();
                    reqImporteDisp.Validate();
                    if (!valImporteDisp.IsValid || !reqImporteDisp.IsValid)
                    {
                        isOK = false;
                    }
                }
            }
            if (!isOK)
            {
                return;
            }
            foreach (DataGridItem item in dtgTopesDisponibles.Items)
            {
                if (((CheckBox)item.FindControl("chkTopeDisp")).Checked)
                {
                    importe         = Convert.ToDouble(((TextBox)item.FindControl("txtImporteDisp")).Text);
                    vol             = ((TextBox)item.FindControl("txtVolumen")).Text;
                    importeBultoExc = ((TextBox)item.FindControl("txtImporteBultoDisp")).Text == "" ? 0 : Convert.ToDouble(((TextBox)item.FindControl("txtImporteBultoDisp")).Text);
                    ITarifarioTope oTariTope = tariTopes.AddTarifarioTope();
                    oTariTope.Tope.TopeID      = Convert.ToInt32(dtgTopesDisponibles.DataKeys[item.DataSetIndex]);
                    oTariTope.Tope.TopeKgHasta = Convert.ToInt32(((Label)item.FindControl("lblTopeKgHasta")).Text);
                    /*SFE Asignar el item checkeado o no en la tabla TopesDisponibles*/
                    oTariTope.KgVariable = ((CheckBox)item.FindControl("chkTopeDispVar")).Checked;
                    //oTariTope.Importe = Convert.ToDouble(((TextBox)item.FindControl("txtImporteDisp")).Text);
                    if (bul)
                    {
                        oTariTope.Cm3Hasta = Convert.ToDouble(vol);
                    }
                    if (bulKilo)
                    {
                        oTariTope.ImporteBultoExc = importeBultoExc;
                    }
                    if (tari.TarifarioRefID != 0)
                    {
                        oTariTope.Importe = CalcularImporte(importe);
                        if (bulKilo)
                        {
                            oTariTope.ImporteBultoExc = AdministrarTarifarios.CalcularImporte(importeBultoExc, tari.FactorAjuste, tari.PorcentajeAjuste, tari.ImporteAjuste);
                            if (oTariTope.ImporteBultoExc < 0)
                            {
                                oTariTope.ImporteBultoExc = 0;
                            }
                        }
                    }
                    else
                    {
                        oTariTope.Importe = importe;
                        if (bulKilo)
                        {
                            oTariTope.ImporteBultoExc = importeBultoExc;
                        }
                    }
                }
            }
            try
            {
                // Obtenemos el usuario que ejecuta la acción.
                IUsuarios usuarioConectado = UsuariosFactory.GetUsuario();
                usuarioConectado.Login = this.UsuarioConectadoID;
                usuarioConectado.ConsultarByLogin();

                tariTopes.Guardar(usuarioConectado.UsuarioID);
                this.BindGridTopesDisp(0);
                this.BindGridTopesTarif(0);
                //this.SetearPorTarifarioReferencia();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            Session["tarifario"] = tari;
        }
        protected void dtgTopesTarifario_Update(Object sender, DataGridCommandEventArgs e)
        {
            string vol             = "";
            bool   bul             = false;
            bool   bulKilo         = false;
            string importeBultoExc = "";

            if (tari.ValorizacionTarifario == SisPack.ValorizacionTarifario.Bulto)
            {
                bul = true;
            }
            if (tari.ValorizacionTarifario == SisPack.ValorizacionTarifario.Bulto_Kilogramo)
            {
                bul     = true;
                bulKilo = true;
            }
            if (bul)
            {
                vol = ((TextBox)e.Item.FindControl("txtVolumenTari")).Text;
                BaseValidator valVolumen = (RegularExpressionValidator)((PlaceHolder)e.Item.FindControl("phValidVolTari")).FindControl("valVolumenTar");
                valVolumen.Enabled = true;
                valVolumen.Validate();
                //if (!valVolumen.IsValid)
                //return;
                BaseValidator valVolumenT = (RequiredFieldValidator)((PlaceHolder)e.Item.FindControl("phValidVolTari")).FindControl("valVolumenTarifario");
                valVolumenT.Enabled = true;
                valVolumenT.Validate();
                if (!valVolumen.IsValid || !valVolumenT.IsValid)
                {
                    return;
                }
                if (bulKilo)
                {
                    importeBultoExc = ((TextBox)e.Item.FindControl("txtImporteBultoTari")).Text;
                    BaseValidator          valImporteBultoTari = (RegularExpressionValidator)((PlaceHolder)e.Item.FindControl("phValidImporteBultoTari")).FindControl("valImporteBultoTari");
                    RequiredFieldValidator reqImporteBultoTari = (RequiredFieldValidator)((PlaceHolder)e.Item.FindControl("phValidImporteBultoTari")).FindControl("reqImporteBultoTari");
                    valImporteBultoTari.Enabled = true;
                    reqImporteBultoTari.Enabled = true;
                    valImporteBultoTari.Validate();
                    reqImporteBultoTari.Validate();
                    if (!valImporteBultoTari.IsValid || !reqImporteBultoTari.IsValid)
                    {
                        return;
                    }
                }
            }
            BaseValidator valImporte = (RegularExpressionValidator)((PlaceHolder)e.Item.FindControl("phValidImporteTari")).FindControl("valImporteTari");

            valImporte.Enabled = true;
            valImporte.Validate();
            //if(!valImporte.IsValid)
            //	return;

            BaseValidator valImporteT = (RequiredFieldValidator)((PlaceHolder)e.Item.FindControl("phValidImporteTari")).FindControl("valImporteTarifario");

            valImporteT.Enabled = true;
            valImporteT.Validate();
            if (!valImporte.IsValid || !valImporteT.IsValid)
            {
                return;
            }

            int            key       = Convert.ToInt32(dtgTopesTarifario.DataKeys[(int)e.Item.ItemIndex]);
            ITarifarioTope oTariTope = tari.TopesCol.GetTarifarioTopeByTopeID(key);

            if (bul)
            {
                oTariTope.Cm3Hasta = Convert.ToDouble(vol);
            }
            if (bulKilo)
            {
                oTariTope.ImporteBultoExc = Convert.ToDouble(importeBultoExc);
            }
            oTariTope.Importe = Convert.ToDouble(((TextBox)e.Item.FindControl("txtImporteTari")).Text);
            /*SFE Asignar el valor del checkbox al editar*/
            oTariTope.KgVariable = ((CheckBox)e.Item.FindControl("chkTopeTariVar1")).Checked;
            // Obtenemos el usuario que ejecuta la acción.
            IUsuarios usuarioConectado = UsuariosFactory.GetUsuario();

            usuarioConectado.Login = this.UsuarioConectadoID;
            usuarioConectado.ConsultarByLogin();

            oTariTope.Guardar(usuarioConectado.UsuarioID);
            dtgTopesTarifario.EditItemIndex = -1;
            this.BindGridTopesTarif(0);
            //chkTopesTarifTodos.Checked = false;
            //this.SetearPorTarifarioReferencia();
        }
        public static bool RecalcularImportesTarifarioRedespacho(ITarifario tariNuevo, int usuarioID)
        {
            //if (Clienteflete)
            //else{}
            ITarifario         tariRef  = TarifarioReDespachoFactory.GetTarifarioRedespacho("C");
            ITarifariosTopeCol topesCol = tariNuevo.TopesCol;

            //Solo me interesa consultar los importes del tarifario de referencia
            //tariRef.TopesCol.TarifarioID = tariNuevo.TarifarioRefID;
            //tariRef.TopesCol.Consultar();
            tariRef.TarifarioID = tariNuevo.TarifarioRefID;
            tariRef.Consultar();


            bool esPorcentaje;

            if (tariNuevo.PorcentajeAjuste != 0)
            {
                esPorcentaje = true;
            }
            else
            {
                esPorcentaje = false;
            }
            //Calculo de importeKgExcedente para tarifario
            if (tariNuevo.FactorAjuste != "")
            {
                if (esPorcentaje)
                {
                    if (tariNuevo.FactorAjuste == "+")
                    {
                        tariNuevo.ImporteKgExcedente = tariRef.ImporteKgExcedente + (tariRef.ImporteKgExcedente * (tariNuevo.PorcentajeAjuste / 100));
                    }
                    else
                    {
                        tariNuevo.ImporteKgExcedente = tariRef.ImporteKgExcedente - (tariRef.ImporteKgExcedente * (tariNuevo.PorcentajeAjuste / 100));
                        if (tariNuevo.ImporteKgExcedente < 0)
                        {
                            tariNuevo.ImporteKgExcedente = 0;
                        }
                    }
                }
                else
                {
                    if (tariNuevo.FactorAjuste == "+")
                    {
                        tariNuevo.ImporteKgExcedente = tariRef.ImporteKgExcedente + tariNuevo.ImporteAjusteKgExcedente;
                    }
                    else
                    {
                        tariNuevo.ImporteKgExcedente = tariRef.ImporteKgExcedente - tariNuevo.ImporteAjusteKgExcedente;
                        if (tariNuevo.ImporteKgExcedente < 0)
                        {
                            tariNuevo.ImporteKgExcedente = 0;
                        }
                    }
                }
            }
            else
            {
                tariNuevo.ImporteKgExcedente = tariRef.ImporteKgExcedente;
            }

            //Iterar por la coleccion de importes de topes y asignar el importe que corresponda.



            for (int i = 0; i < topesCol.getCount(); i++)
            {
                //Recuperar el importe de Kg. Excedente del tope  de referencia
                ITarifarioTope oTope    = topesCol.GetTarifarioTope(i);
                ITarifarioTope oTopeRef = tariRef.TopesCol.GetTarifarioTopeByTopeID(oTope.Tope.TopeID);

                if (tariNuevo.FactorAjuste != "")
                {
                    if (esPorcentaje)
                    {
                        if (tariNuevo.FactorAjuste == "+")
                        {
                            oTope.Importe = oTopeRef.Importe + (oTopeRef.Importe * (tariNuevo.PorcentajeAjuste / 100));
                        }
                        else
                        {
                            oTope.Importe = oTopeRef.Importe - (oTopeRef.Importe * (tariNuevo.PorcentajeAjuste / 100));
                            if (oTope.Importe < 0)
                            {
                                oTope.Importe = 0;
                            }
                        }
                    }
                    else
                    {
                        if (tariNuevo.FactorAjuste == "+")
                        {
                            oTope.Importe = oTopeRef.Importe + tariNuevo.ImporteAjuste;
                        }
                        else
                        {
                            oTope.Importe = oTopeRef.Importe - tariNuevo.ImporteAjuste;
                            if (oTope.Importe < 0)
                            {
                                oTope.Importe = 0;
                            }
                        }
                    }
                }
                else
                {
                    oTope.Importe = oTopeRef.Importe;
                }
            }

            /*try
             * {
             *
             *              return true;
             *      else
             *              return false;
             * }
             * catch(Exception)
             * {
             *      return false;
             * }*/
            //Recalcular los importes del tarifario
            //Recorrer la col de zonastopes. Por cada Zona y tope, recuperar el importe del padre y aplicar
            try
            {
                if (tariNuevo.Guardar(usuarioID))
                {
                    if (tariNuevo.TopesCol.Guardar(usuarioID))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }