void GuardarDetalle()
        {
            if (autoMedicamentos.SelectedItem == null)
            {
                MessageBox.Show("Selecciona un medicamento válido");
            }
            else
            {
                if (txtCantidad.Text == "")
                {
                    MessageBox.Show("Ingresa la cantidad");
                }
                else
                {
                    dynamic med   = autoMedicamentos.SelectedItem;
                    int     idme  = med.ID_MEDICAMENTO;
                    var     medic = BaseDatos.GetBaseDatos().CATALOGO_MEDICAMENTOS.Find(idme);
                    if (medic.CANTIDAD == 0)
                    {
                        MessageBox.Show("Existencias agotadas");
                    }
                    else
                    {
                        if (Convert.ToInt32(txtCantidad.Text) > medic.CANTIDAD)
                        {
                            MessageBox.Show("Existencias: " + medic.CANTIDAD);
                        }
                        else
                        {
                            DETALLE_VENTAS dv = new DETALLE_VENTAS
                            {
                                VENTAID        = venta,
                                MEDICAMENTOID  = idme,
                                CANTIDAD       = Convert.ToInt32(txtCantidad.Text),
                                COSTO          = Decimal.Parse(txtPVenta.Text),
                                F_CADUCIDAD    = medic.CADUCIDAD,
                                SUBTOTAL       = ((Convert.ToInt32(txtCantidad.Text)) * (Decimal.Parse(txtPVenta.Text))),
                                FECHA_CREACION = dh
                            };
                            BaseDatos.GetBaseDatos().DETALLE_VENTAS.Add(dv);
                            BaseDatos.GetBaseDatos().SaveChanges();

                            //Calculamos el total
                            total         = total + ((Convert.ToInt32(txtCantidad.Text)) * (Decimal.Parse(txtPVenta.Text)));
                            txtTotal.Text = total.ToString();

                            //Llenamos la DataGrid
                            if (chbVenta.IsChecked == true)
                            {
                                VistaRadMed();
                            }
                            else
                            {
                                VistaRad();
                            }


                            //Actualizamos exixtencias
                            medic.CANTIDAD = medic.CANTIDAD - Convert.ToInt32(txtCantidad.Text);
                            BaseDatos.GetBaseDatos().SaveChanges();

                            //Limpiamos
                            Limpiar();

                            //Habilitamos el btn Finalizar
                            btnFinalizar.IsEnabled = true;

                            chbVenta.IsEnabled = false;
                        }
                    }
                }
            }
        }
        private void btnIngresar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cbxSucursal.SelectedValue != null)
                {
                    if (int.Parse(cbxSucursal.SelectedValue.ToString()) > 0)
                    {
                        if (cbxCliente.SelectedValue != null)
                        {
                            if (int.Parse(cbxCliente.SelectedValue.ToString()) > 0)
                            {
                                if (cbxTipoDocumento.SelectedValue != null)
                                {
                                    if (int.Parse(cbxTipoDocumento.SelectedValue.ToString()) > 0)
                                    {
                                        if (cbxMoneda.SelectedValue != null)
                                        {
                                            if (int.Parse(cbxTipoDocumento.SelectedValue.ToString()) > 0)
                                            {
                                                if (cbxEmpleado.SelectedValue != null)
                                                {
                                                    if (int.Parse(cbxEmpleado.SelectedValue.ToString()) > 0)
                                                    {
                                                        DataTable tabla = ((DataView)dgDetalleDocumento.ItemsSource).ToTable();
                                                        if (tabla.Rows.Count > 0)
                                                        {
                                                            MessageBox.Show("Espere mientras el documento es generado. Presione 'Aceptar para comenzar'");
                                                            int      _idCliente                = int.Parse(cbxCliente.SelectedValue.ToString());
                                                            int      _sucursal                 = int.Parse(cbxSucursal.SelectedValue.ToString());
                                                            int      _tipoDocumento            = int.Parse(cbxTipoDocumento.SelectedValue.ToString());
                                                            DateTime _fechaDocumento           = DateTime.Parse(dpkFechaCreacion.SelectedDate.ToString());
                                                            double   _neto                     = double.Parse(txtNeto.Text);
                                                            int      _idEmpleado               = int.Parse(cbxEmpleado.SelectedValue.ToString());
                                                            double   _iva                      = double.Parse(txtIva.Text);
                                                            double   _total                    = double.Parse(txtTotal.Text);
                                                            double   _totalMoneda              = double.Parse(txtTotalMoneda.Text);
                                                            int      _idMoneda                 = int.Parse(cbxTipoDocumento.SelectedValue.ToString());
                                                            List <DETALLE_VENTAS> listaDetalle = new List <DETALLE_VENTAS>();
                                                            int    cantidadTotal               = 0;
                                                            string reservas                    = "";
                                                            foreach (DataRow fila in tabla.Rows)
                                                            {
                                                                DETALLE_VENTAS detalle = new DETALLE_VENTAS();
                                                                detalle.FECHA_CREACION      = DateTime.Now;
                                                                detalle.FECHA_ULTIMO_UPDATE = DateTime.Now;
                                                                detalle.CANTIDAD            = int.Parse(fila.ItemArray[0].ToString());
                                                                detalle.MONTO_TOTAL         = int.Parse(fila.ItemArray[5].ToString());
                                                                detalle.NOMBRE_PRODUCTO     = fila.ItemArray[3].ToString();
                                                                detalle.PRECIO_VENTA        = Convert.ToDecimal(fila.ItemArray[4].ToString());
                                                                detalle.MULTI_MONEDA_ID     = _idMoneda;

                                                                if (fila.ItemArray[1].ToString() == "PRO")
                                                                {
                                                                    detalle.PRODUCTO_ID = int.Parse(fila.ItemArray[2].ToString());
                                                                    detalle.SERVICIO_ID = 1;
                                                                }
                                                                if (fila.ItemArray[1].ToString() == "SER")
                                                                {
                                                                    detalle.PRODUCTO_ID = 1;
                                                                    detalle.SERVICIO_ID = int.Parse(fila.ItemArray[2].ToString());
                                                                }
                                                                if (fila.ItemArray[1].ToString() == "OT")
                                                                {
                                                                    detalle.PRODUCTO_ID = 1;
                                                                    detalle.SERVICIO_ID = 1;
                                                                    reservas            = reservas + fila.ItemArray[2].ToString() + ";";
                                                                }
                                                                listaDetalle.Add(detalle);
                                                                cantidadTotal = cantidadTotal + int.Parse(detalle.CANTIDAD.ToString());
                                                            }
                                                            VENTAS ventas = new VENTAS();
                                                            ventas.FECHA_CREACION      = DateTime.Now;
                                                            ventas.FECHA_ULTIMO_UPDATE = DateTime.Now;
                                                            ventas.CANTIDAD_TOTAL      = cantidadTotal;
                                                            ventas.FECHA_VENTA         = DateTime.Now;
                                                            ventas.MONTO_TOTAL         = Convert.ToDecimal(_total);
                                                            ventas.CLIENTE_ID          = _idCliente;
                                                            ventas.EMPLEADO_ID         = _idEmpleado;
                                                            ventas.MULTI_MONEDA_ID     = _idMoneda;
                                                            ventas.SUCURSAL_ID         = _sucursal;
                                                            ventas.TIPO_VENTA_ID       = _tipoDocumento;
                                                            VentasNEG ventasNEG = new VentasNEG();
                                                            string    respuesta = ventasNEG.EmitirVenta(ventas, listaDetalle, reservas);
                                                            if (respuesta == "creado")
                                                            {
                                                                int       idVenta            = ventasNEG.ObtenerUtlimoIdVenta();
                                                                VentasDAL ventasDAL          = new VentasDAL();
                                                                DatosDocumentoPagoVIEW datos = ventasDAL.CargarDatos(idVenta);
                                                                datos.DETALLE_BOLETA = ventasDAL.ListarDetalleBoleta(idVenta);
                                                                ExportarArchivos PDF   = new ExportarArchivos();
                                                                string           folio = datos.FOLIO.ToString();
                                                                for (int i = 0; i < 9; i++)
                                                                {
                                                                    if (folio.Length < 8)
                                                                    {
                                                                        folio = "0" + folio;
                                                                    }
                                                                }

                                                                string       rutaDcoc     = PDF.DocumentoPagoPDF(datos, folio);
                                                                ServerCorreo abrir_server = new ServerCorreo();
                                                                Correo       correoM      = new Correo();
                                                                SmtpClient   server       = abrir_server.InstanciaServer();
                                                                //Instancia la libreria que permite armar correo electronico y llama el metodo que lo crea
                                                                MailMessage email = correoM.CorreoEnvioFactura(rutaDcoc, datos.CORREO_CLIENTE, datos.NOMBRE_CLIENTE + " " + datos.APELLIDO_CLIENTE, folio);
                                                                //envia el correo
                                                                server.Send(email);
                                                                Limpiar();

                                                                MessageBox.Show("El documento ha sido generado correctamente. Se ha enviado una copia por correo al cliente y puede tambien buscar una copia del archivo en 'Mis Documentos'");
                                                            }
                                                        }
                                                        else
                                                        {
                                                            MessageBox.Show("Deben ingresar productos o servicios al documento");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        MessageBox.Show("Debe seleccionar un empleado");
                                                    }
                                                }
                                                else
                                                {
                                                    MessageBox.Show("Debe seleccionar un empleado");
                                                }
                                            }
                                            else
                                            {
                                                MessageBox.Show("Debe seleccionar un tipo de documento");
                                            }
                                        }
                                        else
                                        {
                                            MessageBox.Show("Debe seleccionar una moneda");
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("Debe seleccionar un tipo de documento");
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Debe seleccionar un tipo de documento");
                                }
                            }
                            else
                            {
                                MessageBox.Show("Debe seleccionar un cliente");
                            }
                        }
                        else
                        {
                            MessageBox.Show("Debe seleccionar un cliente");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Debe seleccionar una sucursal");
                    }
                }
                else
                {
                    MessageBox.Show("Debe seleccionar una sucursal");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:\n" + ex.TargetSite + "\n" + ex.Message.ToString());
            }
        }