vista.ventas.DialogEntregas.java Source code

Java tutorial

Introduction

Here is the source code for vista.ventas.DialogEntregas.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vista.ventas;

import entidades.Sucursal;
import entidades.articulo.Articulo;
import entidades.articulo.PrecioArticulo;
import entidades.cliente.Cliente;
import entidades.cliente.Organismo;
import entidades.cliente.Persona;
import entidades.promocion.DiaSemana;
import entidades.promocion.Promocion;
import entidades.promocion.PromocionArticulo;
import entidades.usuario.Usuario;
import entidades.venta.Entrega;
import entidades.venta.EntregaParcial;
import entidades.venta.OrdenDeCompra;
import entidades.venta.OrdenDeCompraArticulo;
import entidades.venta.Venta;
import entidades.venta.VentaArticulo;
import facade.ArticuloFacade;
import facade.ClienteFacade;
import facade.EntregaFacade;
import facade.EntregaParcialFacade;
import facade.OrdenDeCompraArticuloFacade;
import facade.OrdenDeCompraFacade;
import facade.PrecioArticuloFacade;
import facade.PromocionFacade;
import facade.VentaFacade;
import giovynet.serial.Com;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import includes.Comunes;
import includes.Impresora;
import includes.ModeloTablaNoEditable;
import includes.SuperDialog;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.Timer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.apache.commons.validator.routines.BigIntegerValidator;
import vista.articulos.DiagBuscarArticulo;
import vista.frPrincipal;

/**
 *
 * @author franco
 */
public class DialogEntregas extends SuperDialog {

    private Cliente cliente;
    CommPortIdentifier idPuerto = null;
    static List<String> listaPuertos;
    static Com com1;
    // variables nuevas 
    static CommPortIdentifier IdPuerto;
    static Enumeration portList;
    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;
    private boolean hiloIniciado;
    private Articulo articulo;
    private PrecioArticulo precioArticulo;
    private List<VentaArticulo> listaVentaArticulos = new ArrayList<>();
    private ModeloTablaNoEditable modeloTablaArticulos;
    private BigDecimal subTotal = new BigDecimal(0.0);
    private BigDecimal precioPromocion = new BigDecimal("0.0");
    private Usuario usuario;
    private Sucursal sucursal;
    private BigDecimal subTotalArticulo;
    private ModeloTablaNoEditable modeloTablaOrdenes;
    private OrdenDeCompra ordenDeCompraSeleccionada;
    private ModeloTablaNoEditable modeloTablaItems;
    private ModeloTablaNoEditable modeloTablaEntregas;
    private EntregaParcial entregaParcial;
    private List<EntregaParcial> entregasParciales = new ArrayList();
    private Entrega entrega;
    private BigDecimal pendiente;
    private OrdenDeCompraArticulo ordenDeCompraArticulo;

    /**
     * Creates new form DialogEntregas
     */
    public DialogEntregas(java.awt.Frame parent, boolean modal, Usuario usuario, Sucursal sucursal) {
        super(parent, modal);
        this.usuario = usuario;
        this.sucursal = sucursal;
        initComponents();
        inicializarComponentes();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        ftfDocumento = new javax.swing.JFormattedTextField();
        jButton1 = new javax.swing.JButton();
        tfCliente = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        tfNumero = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        tfPesoBalanza = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        ftfCantidad = new javax.swing.JFormattedTextField();
        jPanel3 = new javax.swing.JPanel();
        tfCodigo = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        tfDescripcion = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        tfPrecio = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        tfSubTotalArticulo = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        tfCodigo1 = new javax.swing.JTextField();
        tfDescripcion1 = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblArticulos = new javax.swing.JTable();
        btnConfirmarPesada = new javax.swing.JButton();
        tfTotal = new javax.swing.JTextField();
        btnEmitirTicket = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblOrdenesDeCompra = new javax.swing.JTable();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        tblItems = new javax.swing.JTable();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbEntregas = new javax.swing.JTable();
        btnMostrarOrdenes = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jPanel2.border.title"))); // NOI18N

        jLabel3.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel3.text")); // NOI18N

        ftfDocumento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
                new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("########"))));
        ftfDocumento.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.ftfDocumento.text")); // NOI18N
        ftfDocumento.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        ftfDocumento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ftfDocumentoActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/buscar2.png"))); // NOI18N
        jButton1.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        tfCliente.setEditable(false);
        tfCliente.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfCliente.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfCliente.text")); // NOI18N

        jLabel4.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel4.text")); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(jPanel2Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ftfDocumento, javax.swing.GroupLayout.PREFERRED_SIZE, 127,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 38,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(tfCliente,
                                javax.swing.GroupLayout.PREFERRED_SIZE, 245,
                                javax.swing.GroupLayout.PREFERRED_SIZE)));
        jPanel2Layout
                .setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout
                                .createSequentialGroup()
                                .addComponent(
                                        ftfDocumento, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                .addContainerGap())
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(tfCliente, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(jPanel2Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 27,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(jLabel3).addComponent(jLabel4)))
                                .addGap(0, 8, Short.MAX_VALUE)));

        jLabel10.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel10.text")); // NOI18N

        tfNumero.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfNumero.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfNumero.text")); // NOI18N
        tfNumero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfNumeroActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jPanel1.border.title"))); // NOI18N

        jLabel1.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel1.text")); // NOI18N

        tfPesoBalanza.setEditable(false);
        tfPesoBalanza.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfPesoBalanza.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfPesoBalanza.text")); // NOI18N

        jLabel2.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel2.text")); // NOI18N

        ftfCantidad.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
                new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("####.#"))));
        ftfCantidad.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.ftfCantidad.text")); // NOI18N
        ftfCantidad.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        ftfCantidad.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ftfCantidadFocusGained(evt);
            }
        });
        ftfCantidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ftfCantidadActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout
                .setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tfPesoBalanza, javax.swing.GroupLayout.PREFERRED_SIZE, 117,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(7, 7, 7).addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(ftfCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 81,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap()));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(ftfCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2).addComponent(jLabel1))
                        .addComponent(tfPesoBalanza, javax.swing.GroupLayout.PREFERRED_SIZE, 22,
                                javax.swing.GroupLayout.PREFERRED_SIZE)));

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jPanel3.border.title"))); // NOI18N

        tfCodigo.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfCodigo.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfCodigo.text")); // NOI18N
        tfCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfCodigoActionPerformed(evt);
            }
        });

        jLabel5.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel5.text")); // NOI18N

        tfDescripcion.setEditable(false);
        tfDescripcion.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfDescripcion.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfDescripcion.text")); // NOI18N

        jLabel6.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel6.text")); // NOI18N

        tfPrecio.setEditable(false);
        tfPrecio.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfPrecio.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfPrecio.text")); // NOI18N

        jLabel7.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel7.text")); // NOI18N

        tfSubTotalArticulo.setEditable(false);
        tfSubTotalArticulo.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfSubTotalArticulo.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class,
                "DialogEntregas.tfSubTotalArticulo.text")); // NOI18N

        jLabel9.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel9.text")); // NOI18N

        tfCodigo1.setEditable(false);
        tfCodigo1.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfCodigo1.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfCodigo1.text")); // NOI18N

        tfDescripcion1.setEditable(false);
        tfDescripcion1.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfDescripcion1.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfDescripcion1.text")); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(jPanel3Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup().addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(tfCodigo1, javax.swing.GroupLayout.PREFERRED_SIZE, 80,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel5).addComponent(tfCodigo,
                                        javax.swing.GroupLayout.PREFERRED_SIZE, 80,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel3Layout.createSequentialGroup().addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 79,
                                                Short.MAX_VALUE))
                                .addComponent(tfDescripcion1).addComponent(tfDescripcion))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel3Layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(tfPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 69,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(10, 10, 10).addComponent(tfSubTotalArticulo,
                                                javax.swing.GroupLayout.PREFERRED_SIZE, 89,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(jPanel3Layout.createSequentialGroup().addGap(10, 10, 10)
                                        .addComponent(jLabel7).addGap(32, 32, 32).addComponent(jLabel9)))
                        .addContainerGap()));
        jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup().addContainerGap().addGroup(jPanel3Layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel7).addComponent(jLabel9))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel5).addComponent(jLabel6)))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel3Layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
                                        .addComponent(tfDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(jPanel3Layout.createSequentialGroup().addGroup(jPanel3Layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(tfCodigo1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(tfDescripcion1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(tfPrecio, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(tfSubTotalArticulo, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE)))));

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jPanel4.border.title"))); // NOI18N

        tblArticulos
                .setModel(new javax.swing.table.DefaultTableModel(new Object[][] { {}, {}, {}, {} }, new String[] {

        }));
        tblArticulos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblArticulosKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(tblArticulos);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(jPanel4Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel4Layout.createSequentialGroup().addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addContainerGap()));
        jPanel4Layout.setVerticalGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel4Layout.createSequentialGroup().addComponent(jScrollPane2,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 14, Short.MAX_VALUE)));

        btnConfirmarPesada.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/add.png"))); // NOI18N
        btnConfirmarPesada.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class,
                "DialogEntregas.btnConfirmarPesada.text")); // NOI18N
        btnConfirmarPesada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmarPesadaActionPerformed(evt);
            }
        });

        tfTotal.setEditable(false);
        tfTotal.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        tfTotal.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.tfTotal.text")); // NOI18N

        btnEmitirTicket.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/accept.png"))); // NOI18N
        btnEmitirTicket.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.btnEmitirTicket.text")); // NOI18N
        btnEmitirTicket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEmitirTicketActionPerformed(evt);
            }
        });

        jLabel13.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        jLabel13.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jLabel13.text")); // NOI18N

        jPanel5.setBorder(javax.swing.BorderFactory
                .createTitledBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle
                        .getMessage(DialogEntregas.class, "DialogEntregas.jPanel5.border.border.title")))); // NOI18N

        tblOrdenesDeCompra
                .setModel(new javax.swing.table.DefaultTableModel(new Object[][] { {}, {}, {}, {} }, new String[] {

        }));
        tblOrdenesDeCompra.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblOrdenesDeCompraMouseClicked(evt);
            }
        });
        tblOrdenesDeCompra.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblOrdenesDeCompraKeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(tblOrdenesDeCompra);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(jPanel5Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel5Layout.createSequentialGroup().addComponent(jScrollPane3,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 437, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 8, Short.MAX_VALUE)));
        jPanel5Layout.setVerticalGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE));

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(
                javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle
                        .getMessage(DialogEntregas.class, "DialogEntregas.jPanel6.border.border.title")),
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jPanel6.border.title"))); // NOI18N

        tblItems.setModel(new javax.swing.table.DefaultTableModel(new Object[][] { {}, {}, {}, {} }, new String[] {

        }));
        tblItems.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblItemsMouseClicked(evt);
            }
        });
        tblItems.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblItemsKeyPressed(evt);
            }
        });
        jScrollPane4.setViewportView(tblItems);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(jPanel6Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel6Layout.createSequentialGroup().addComponent(jScrollPane4,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 581, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 4, Short.MAX_VALUE)));
        jPanel6Layout.setVerticalGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel6Layout.createSequentialGroup().addComponent(jScrollPane4,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 33, Short.MAX_VALUE)));

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder(
                javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle
                        .getMessage(DialogEntregas.class, "DialogEntregas.jPanel7.border.border.title")),
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jPanel7.border.title"))); // NOI18N

        tbEntregas
                .setModel(new javax.swing.table.DefaultTableModel(new Object[][] { {}, {}, {}, {} }, new String[] {

        }));
        jScrollPane1.setViewportView(tbEntregas);

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout
                .setHorizontalGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel7Layout.createSequentialGroup().addContainerGap()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 570,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        jPanel7Layout.setVerticalGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel7Layout.createSequentialGroup().addComponent(jScrollPane1,
                        javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 11, Short.MAX_VALUE)));

        btnMostrarOrdenes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/buscar2.png"))); // NOI18N
        btnMostrarOrdenes.setText(org.openide.util.NbBundle.getMessage(DialogEntregas.class,
                "DialogEntregas.btnMostrarOrdenes.text")); // NOI18N
        btnMostrarOrdenes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMostrarOrdenesActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/print.png"))); // NOI18N
        jButton3.setText(
                org.openide.util.NbBundle.getMessage(DialogEntregas.class, "DialogEntregas.jButton3.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout
                                        .createSequentialGroup()
                                        .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, 599,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(
                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED, 137,
                                                Short.MAX_VALUE)
                                        .addComponent(jLabel13)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(layout.createSequentialGroup().addGap(121, 121,
                                                        121).addComponent(btnConfirmarPesada,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 144,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addGroup(layout.createSequentialGroup()
                                                        .addComponent(tfTotal,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 115,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(
                                                                btnEmitirTicket,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 144,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                                        .addContainerGap())
                                .addGroup(layout.createSequentialGroup().addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18).addComponent(jPanel4,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(jLabel10).addComponent(tfNumero,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 80,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(
                                                        jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addGroup(layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(jButton3)
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addComponent(btnMostrarOrdenes,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 127,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addGap(18, 18, 18).addComponent(jPanel3,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))))
                                        .addGap(0, 0, Short.MAX_VALUE)))));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING,
                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING,
                                                layout.createSequentialGroup().addContainerGap()
                                                        .addComponent(jLabel10)))
                                .addGap(10, 10, 10))
                        .addComponent(tfNumero, javax.swing.GroupLayout.Alignment.TRAILING,
                                javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING,
                                javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(8, 8, 8))
                                .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(layout.createSequentialGroup().addGap(53, 53, 53)
                                                        .addComponent(btnMostrarOrdenes).addGap(18, 18, 18)
                                                        .addGroup(layout
                                                                .createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.LEADING)
                                                                .addComponent(jButton3).addComponent(jPanel4,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(9, 9, 9)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(btnConfirmarPesada, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(layout.createSequentialGroup().addGap(43, 43, 43).addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jLabel13)
                                                .addComponent(tfTotal, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(btnEmitirTicket,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 39,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ftfDocumentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ftfDocumentoActionPerformed
        buscarClientePorDNI();
    }//GEN-LAST:event_ftfDocumentoActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        buscarCliente();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void ftfCantidadFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ftfCantidadFocusGained
        ftfCantidad.selectAll();
    }//GEN-LAST:event_ftfCantidadFocusGained

    private void tfCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfCodigoActionPerformed
        buscarArticulo();
    }//GEN-LAST:event_tfCodigoActionPerformed

    private void btnConfirmarPesadaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarPesadaActionPerformed
        confirmarPesada();
    }//GEN-LAST:event_btnConfirmarPesadaActionPerformed

    private void btnEmitirTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEmitirTicketActionPerformed
        realizarVenta();
    }//GEN-LAST:event_btnEmitirTicketActionPerformed

    private void tblOrdenesDeCompraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblOrdenesDeCompraMouseClicked
        if (evt.getClickCount() == 2) {
            seleccionarOrdenDeCompra();
        }
    }//GEN-LAST:event_tblOrdenesDeCompraMouseClicked

    private void tblItemsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblItemsKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            cargarArticuloDeItem();
        }
    }//GEN-LAST:event_tblItemsKeyPressed

    private void tblItemsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblItemsMouseClicked
        if (evt.getClickCount() == 2) {
            cargarArticuloDeItem();
        }
    }//GEN-LAST:event_tblItemsMouseClicked

    private void tblOrdenesDeCompraKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblOrdenesDeCompraKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            seleccionarOrdenDeCompra();
        }
    }//GEN-LAST:event_tblOrdenesDeCompraKeyPressed

    private void tfNumeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfNumeroActionPerformed
        buscarPorNumero();
    }//GEN-LAST:event_tfNumeroActionPerformed

    private void btnMostrarOrdenesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMostrarOrdenesActionPerformed
        buscarOrdenesCliente();
    }//GEN-LAST:event_btnMostrarOrdenesActionPerformed

    private void ftfCantidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ftfCantidadActionPerformed
        cargarArticulo();
        calcularSubtotalArticulo();
        btnConfirmarPesada.requestFocus();
    }//GEN-LAST:event_ftfCantidadActionPerformed

    private void tblArticulosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblArticulosKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_DELETE && tblArticulos.getSelectedRow() != -1) {
            quitarArticuloLista();
        }
    }//GEN-LAST:event_tblArticulosKeyPressed

    private void buscarClientePorDNI() {
        cliente = ClienteFacade.getInstance().getPersonaXDni(ftfDocumento.getText());
        if (cliente != null) {
            tfCliente.setText(cliente.toString());
            tfNumero.requestFocus();
            cargarOdenesDeCompra();

        } else {
            tfCliente.setText("");
            buscarCliente();

        }

    }

    private void buscarCliente() {
        tfCliente.setText("");
        DiagBuscarCliente diagBuscarCliente = new DiagBuscarCliente(null, true);
        diagBuscarCliente.setLocation(Comunes.centrarDialog(diagBuscarCliente));
        diagBuscarCliente.setVisible(true);
        if (diagBuscarCliente.getCliente() != null) {
            cliente = diagBuscarCliente.getCliente();
            tfCliente.setText(cliente.toString());
            tfNumero.requestFocus();

            cargarOdenesDeCompra();

        } else {
            if (diagBuscarCliente.getCliente() != null) {
                cliente = diagBuscarCliente.getCliente();
                tfCliente.setText(cliente.toString());
                tfNumero.requestFocus();
                cargarOdenesDeCompra();

            }
        }

    }

    private void realizarVenta() {
        if (validarVenta()) {
            Venta venta = new Venta();
            venta.setFecha(Comunes.obtenerFechaActualDesdeDB());
            try {
                venta.setMonto(BigDecimal.valueOf(Double.valueOf(tfTotal.getText())));
            } catch (NumberFormatException numberFormatException) {
            }
            venta.setVentasArticulos(listaVentaArticulos);
            venta.setNumeroTicket(VentaFacade.getInstance().getUltimoNumeroTicket() + 1);
            if (cliente.getClass() == Persona.class) {
                //ES PERSONA
                venta.setCliente(((Persona) cliente).toString());
                try {
                    venta.setDniCliente(((Persona) cliente).getDocumentoIdentidad().getNumero());
                } catch (Exception e) {
                    venta.setDniCliente("");
                }
                venta.setEsPersona(true);

            } else {
                //ES ORGANISMO
                venta.setCliente(((Organismo) cliente).toString());
                try {
                    venta.setDniCliente(((Organismo) cliente).getCUIT());
                } catch (Exception e) {
                    venta.setDniCliente("");
                }
                venta.setEsPersona(false);
            }
            venta.setUsuario(usuario);
            venta.setSucursal(sucursal);
            venta.setDescuento(BigDecimal.ZERO);
            VentaFacade.getInstance().alta(venta);
            Long id = venta.getId();
            System.out.println("Entro");
            Venta ventaAux = new Venta();
            ventaAux = VentaFacade.getInstance().buscar(id);
            System.out.println(ventaAux);
            entrega = new Entrega();
            entrega.setOrdenDeCompra(ordenDeCompraSeleccionada);
            System.out.println("ordenCompra: " + ordenDeCompraSeleccionada.getNumeroOrden());
            System.out.println("entregas parciales : " + entregasParciales.toString());
            entrega.setVenta(ventaAux);
            entrega.setEntregasParciales(entregasParciales);
            EntregaFacade.getInstance().alta(entrega);
            JOptionPane.showMessageDialog(null, "Venta realizada!");
            try {
                new Impresora().imprimirEntrega(venta);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Error imprimiendo, compruebe impresora!");

            }
            inicializarComponentes();
            limpiarCamposArticulo();
            limpiarTablas();
            reinciarCampos();
            ftfDocumento.requestFocus();
        }
    }

    private boolean validarVenta() {
        if (cliente == null) {
            JOptionPane.showMessageDialog(null, "Debe seleccionar cliente", "Mensaje", JOptionPane.ERROR_MESSAGE);
            ftfDocumento.requestFocus();
            ftfDocumento.selectAll();
            return false;
        }
        if (listaVentaArticulos.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Debe cargar articulos", "Mensaje", JOptionPane.ERROR_MESSAGE);
            tfCodigo.requestFocus();
            tfCodigo.selectAll();
            return false;
        }
        if (tfTotal.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Debe confirmar pesadas", "Mensaje", JOptionPane.ERROR_MESSAGE);
            tfCodigo.requestFocus();
            tfCodigo.selectAll();
            return false;
        }
        return true;
    }

    private void botonesMultilinea() {
        //botones multilinea
        String htmlButton = "<html><div align=\"center\">Confirmar Pesada</div></html>";
        btnConfirmarPesada.setText(htmlButton);
        String htmlButton2 = "<html><div align=\"center\">Emitir Ticket</div></html>";
        btnEmitirTicket.setText(htmlButton2);
        String htmlButton3 = "<html><div align=\"center\">Mostrar Orden</div></html>";
        btnMostrarOrdenes.setText(htmlButton3);
        //
    }

    private void cerrar() {
        this.dispose();
    }

    private void buscarArticulo() {
        if (cliente != null) {
            articulo = ArticuloFacade.getInstance().buscarPorCodigo(tfCodigo.getText());
            if (articulo != null) {
                if (entregaParcial.getOrdenDeCompraArticulo().getArticulo().getUnidadMedida().isEsPeso()) {
                    cargarArticulo();
                    calcularSubtotalArticulo();
                    tfCodigo.selectAll();
                } else {
                    cargarArticulo();
                    ftfCantidad.requestFocus();
                }
            } else {
                DiagBuscarArticulo buscarArticulo = new DiagBuscarArticulo(null, true);
                buscarArticulo.setLocation(Comunes.centrarDialog(buscarArticulo));
                buscarArticulo.setVisible(true);
                if (buscarArticulo.getArticulo() != null) {
                    articulo = buscarArticulo.getArticulo();
                    if (entregaParcial.getOrdenDeCompraArticulo().getArticulo().getUnidadMedida().isEsPeso()) {
                        cargarArticulo();
                        calcularSubtotalArticulo();
                        tfCodigo.selectAll();
                    } else {
                        cargarArticulo();
                        ftfCantidad.requestFocus();
                    }
                } else {
                    tfCodigo.requestFocus();
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "Primero debe seleccionar un Cliente");
        }

    }

    private void cargarArticulo() {
        tfCodigo.setText(articulo.getCodigoBarra());
        tfDescripcion.setText(articulo.getDescripcion());
        cargarPrecioArticulo();
    }

    private void agregarArticulo() {
        if (validarArticulo()) {
            try {
                entregaParcial = new EntregaParcial();
                VentaArticulo ventaArticulo = new VentaArticulo();
                ventaArticulo.setArticuloDescripcion(articulo.getDescripcionReducida());
                ventaArticulo.setArticuloCodigo(articulo.getCodigoBarra());
                //segun sea por peso o cantidad la venta
                if (!ftfCantidad.getText().isEmpty()) {
                    ventaArticulo.setCantidadPeso(BigDecimal.valueOf(Double.parseDouble(ftfCantidad.getText())));
                } else {
                    ventaArticulo.setCantidadPeso(BigDecimal.valueOf(Double.parseDouble(tfPesoBalanza.getText())));
                }
                ventaArticulo.setPrecioPromocion(precioArticulo.getPrecio());
                ventaArticulo
                        .setPrecioUnitario(PrecioArticuloFacade.getInstance().get(articulo, sucursal).getPrecio());
                ventaArticulo
                        .setPrecio(ventaArticulo.getPrecioPromocion().multiply(ventaArticulo.getCantidadPeso()));
                //Lista para cargar tabla
                listaVentaArticulos.add(ventaArticulo);
                entregaParcial.setVentaArticulo(ventaArticulo);
                entregaParcial.setOrdenDeCompraArticulo(ordenDeCompraArticulo);
                entregasParciales.add(entregaParcial);
                cargarTablaArticulos(listaVentaArticulos);
                limpiarCamposArticulo();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(rootPane, "Error agregando articulo");
            }
        }

    }

    private void cargarTablaArticulos(List<VentaArticulo> listaVentaArticulos) {
        modeloTablaArticulos = new ModeloTablaNoEditable();
        cargarEncabezadosTablaArticulos(modeloTablaArticulos);
        configurarTabla(tblArticulos);
        try {
            cargarArticulos(listaVentaArticulos);
        } catch (Exception ex) {
            Logger.getLogger(FrVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargarEncabezadosTablaArticulos(ModeloTablaNoEditable modeloTablaArticulos) {
        modeloTablaArticulos.addColumn("Codigo");
        modeloTablaArticulos.addColumn("Articulo");
        modeloTablaArticulos.addColumn("Peso Neto/Cantidad");
        modeloTablaArticulos.addColumn("Precio U.");
        modeloTablaArticulos.addColumn("Promo");
        modeloTablaArticulos.addColumn("SubTotal");
        tblArticulos.setModel(modeloTablaArticulos);
    }

    private void configurarTabla(JTable tbl) {
        JViewport scroll = (JViewport) tbl.getParent();
        int ancho = scroll.getWidth();
        int anchoColumna = 0;
        TableColumnModel modeloColumna = tbl.getColumnModel();
        TableColumn columnaTabla;
        for (int i = 0; i < tbl.getColumnCount(); i++) {
            columnaTabla = modeloColumna.getColumn(i);
            switch (i) {
            case 0:
                anchoColumna = 1 / 100;
                break;
            case 1:
                anchoColumna = (20 * ancho) / 100;
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            case 12:
                anchoColumna = (5 * ancho) / 100;
                break;
            }
            columnaTabla.setPreferredWidth(anchoColumna);
            tbl.setColumnModel(modeloColumna);
        }
        tbl.getTableHeader().setBackground(java.awt.Color.WHITE);
        tbl.getTableHeader().setForeground(Color.BLACK);
        tbl.getTableHeader().setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 14));
        //Si le queremos cambiar el tamao a la tablita
        tbl.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 14));
    }

    private void cargarArticulos(List<VentaArticulo> listaVentaArticulos) {
        try {
            modeloTablaArticulos = new ModeloTablaNoEditable();
            cargarEncabezadosTablaArticulos(modeloTablaArticulos);
            for (VentaArticulo ventaArt : listaVentaArticulos) {
                cargarArticulos(ventaArt);
            }

            tblArticulos.setModel(modeloTablaArticulos);
        } catch (Exception ex) {
            Logger.getLogger(FrVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargarArticulos(VentaArticulo ventaArticulo) {

        Object[] fila = new Object[6];
        fila[0] = ventaArticulo.getArticuloCodigo();
        fila[1] = ventaArticulo.getArticuloDescripcion();
        fila[2] = ventaArticulo.getCantidadPeso();
        fila[3] = ventaArticulo.getPrecioUnitario();
        fila[4] = ventaArticulo.getPrecioPromocion();
        fila[5] = ventaArticulo.getCantidadPeso().multiply(ventaArticulo.getPrecioPromocion());
        modeloTablaArticulos.addRow(fila);
    }

    private void cambiarEstadoTFPesoBalanza() {
        if (ftfCantidad.getText().length() > 0) {
            tfPesoBalanza.setEnabled(false);
        } else {
            tfPesoBalanza.setEnabled(true);
        }
    }

    private void calcularSubtotalGral() {
        subTotal = BigDecimal.ZERO;
        for (VentaArticulo va : listaVentaArticulos) {
            subTotal = subTotal.add(va.getPrecio());
        }
        tfTotal.setText(subTotal.toString());
    }

    private void eventosDeTeclas() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.addKeyEventDispatcher(new KeyEventDispatcher() {
            public boolean dispatchKeyEvent(KeyEvent e) {
                if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow().getClass()
                        .getSimpleName().equals("DialogEntregas")) {
                    if (e.getID() == KeyEvent.KEY_PRESSED) {
                        if (e.getKeyCode() == KeyEvent.VK_F3) {
                            agregarArticulo();
                            calcularSubtotalGral();
                        }
                        if (e.getKeyCode() == KeyEvent.VK_F7) {
                            realizarVenta();
                        }
                        if (e.getKeyCode() == KeyEvent.VK_F4) {
                            cerrar();
                        }

                    }
                }

                return false;
            }
        });
    }

    private void limpiarCamposArticulo() {
        ftfCantidad.setText("");
        tfDescripcion.setText("");
        tfPrecio.setText("");
        tfSubTotalArticulo.setText("");
        tfPrecio.setText("");
        tfCodigo.setText("");
        tfCodigo1.setText("");
        tfDescripcion1.setText("");
        articulo = null;

    }

    private void cargarPrecioArticulo() {
        precioArticulo = new PrecioArticulo();
        precioArticulo.setArticulo(articulo);
        precioArticulo.setPrecio(entregaParcial.getOrdenDeCompraArticulo().getPrecio());
        tfPrecio.setText(precioArticulo.getPrecio().toString());
    }

    private void calcularSubtotalArticulo() {
        try {
            if (entregaParcial.getOrdenDeCompraArticulo().getArticulo().getUnidadMedida().isEsPeso()
                    && !ftfCantidad.getText().isEmpty()) {
                //por cantidad
                subTotalArticulo = new BigDecimal(ftfCantidad.getText());
                tfSubTotalArticulo.setText(subTotalArticulo.multiply(precioArticulo.getPrecio()).toString());
            } else {
                //por peso
                if (!tfPesoBalanza.getText().isEmpty()) {
                    subTotalArticulo = new BigDecimal(tfPesoBalanza.getText());
                    tfSubTotalArticulo.setText(subTotalArticulo.multiply(precioArticulo.getPrecio()).toString());
                }
            }
        } catch (HeadlessException headlessException) {
            JOptionPane.showMessageDialog(null, "No se pudo calcular el subtotal");

        }
    }

    private boolean validarArticulo() {
        if (cliente == null) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un cliente", "Mensaje",
                    JOptionPane.ERROR_MESSAGE);
            ftfDocumento.requestFocus();
            return false;
        }
        if (articulo == null) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un articulo", "Mensaje",
                    JOptionPane.ERROR_MESSAGE);
            tfCodigo.requestFocus();
            return false;
        }

        return true;
    }

    private void cargarTablaArticulos() {
        modeloTablaArticulos = new ModeloTablaNoEditable();
        cargarEncabezadosTablaArticulos(modeloTablaArticulos);
        configurarTabla(tblArticulos);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConfirmarPesada;
    private javax.swing.JButton btnEmitirTicket;
    private javax.swing.JButton btnMostrarOrdenes;
    private javax.swing.JFormattedTextField ftfCantidad;
    private javax.swing.JFormattedTextField ftfDocumento;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable tbEntregas;
    private javax.swing.JTable tblArticulos;
    private javax.swing.JTable tblItems;
    private javax.swing.JTable tblOrdenesDeCompra;
    private javax.swing.JTextField tfCliente;
    private javax.swing.JTextField tfCodigo;
    private javax.swing.JTextField tfCodigo1;
    private javax.swing.JTextField tfDescripcion;
    private javax.swing.JTextField tfDescripcion1;
    private javax.swing.JTextField tfNumero;
    private javax.swing.JTextField tfPesoBalanza;
    private javax.swing.JTextField tfPrecio;
    private javax.swing.JTextField tfSubTotalArticulo;
    private javax.swing.JTextField tfTotal;
    // End of variables declaration//GEN-END:variables

    private void cargarOdenesDeCompra() {
        cargarTablaOrdenesDeCompra();
    }

    private void inicializarComponentes() {
        precioPromocion.setScale(12, 2);
        eventosDeTeclas();
        //        tfPesoBalanza.setText("");
        if (frPrincipal.peso != null) {
            int delay = 500; //milliseconds
            ActionListener taskPerformer = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    tfPesoBalanza.setText(frPrincipal.peso);
                    //                System.out.println("peso: "+frPrincipal.peso);
                }
            };
            new Timer(delay, taskPerformer).start();
        } else {
            tfPesoBalanza.setEditable(true);
        }
        botonesMultilinea();
        //maximizamos frame
        // this.setSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize()));
        //configuramos tabla
        cargarTablaArticulos();
    }

    private void cargarTablaOrdenesDeCompra() {
        List<OrdenDeCompra> ordenDeCompras = OrdenDeCompraFacade.getInstance()
                .listaOrdenDeComprasDescendente(cliente);
        cargarTablaOrdenes(ordenDeCompras);

    }

    private void cargarTablaOrdenes(List<OrdenDeCompra> ordenDeCompras) {
        modeloTablaOrdenes = new ModeloTablaNoEditable();
        cargarEncabezadosTablaOrdenes(modeloTablaOrdenes);
        configurarTabla(tblOrdenesDeCompra);
        try {
            cargarOrdenes(ordenDeCompras);
        } catch (Exception ex) {
            Logger.getLogger(FrVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargarEncabezadosTablaOrdenes(ModeloTablaNoEditable modeloTablaOrdenes) {
        modeloTablaOrdenes.addColumn("Id");
        modeloTablaOrdenes.addColumn("Nmero");
        modeloTablaOrdenes.addColumn("Cliente");
        modeloTablaOrdenes.addColumn("DNI/CUIT");
        modeloTablaOrdenes.addColumn("Fecha");
        modeloTablaOrdenes.addColumn("Monto");
        tblOrdenesDeCompra.setModel(modeloTablaOrdenes);
    }

    private void cargarOrdenes(List<OrdenDeCompra> ordenDeCompras) {
        try {
            modeloTablaOrdenes = new ModeloTablaNoEditable();
            cargarEncabezadosTablaOrdenes(modeloTablaOrdenes);
            for (OrdenDeCompra ventaArt : ordenDeCompras) {
                cargarOrdenes(ventaArt);
            }
            tblOrdenesDeCompra.setModel(modeloTablaOrdenes);
        } catch (Exception ex) {
            Logger.getLogger(FrVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargarOrdenes(OrdenDeCompra ordenDeCompra) {

        Object[] fila = new Object[6];
        fila[0] = ordenDeCompra.getId();
        fila[1] = ordenDeCompra.getNumeroOrden();
        try {
            fila[2] = ordenDeCompra.getCliente().toString();
        } catch (Exception e) {
        }
        try {
            if (ordenDeCompra.getCliente().getClass() == Persona.class) {
                fila[3] = ((Persona) ordenDeCompra.getCliente()).getDocumentoIdentidad().getNumero();
            } else {
                fila[3] = ((Organismo) ordenDeCompra.getCliente()).getCUIT();
            }
        } catch (Exception e) {
        }
        try {
            fila[4] = new SimpleDateFormat("dd/MM/yyyy").format(ordenDeCompra.getFecha());
        } catch (Exception e) {
        }
        try {
            fila[5] = ordenDeCompra.getMonto().toString();
        } catch (Exception e) {
        }
        modeloTablaOrdenes.addRow(fila);
    }

    private void buscarOrden() {
        if (!tfNumero.getText().isEmpty() && BigIntegerValidator.getInstance().isValid(tfNumero.getText())) {
            List<OrdenDeCompra> ordenDeCompras = OrdenDeCompraFacade.getInstance()
                    .buscarOrdenDeCompraNumeroTicket(tfNumero.getText());
            cargarTablaOrdenes(ordenDeCompras);
            tblOrdenesDeCompra.requestFocus();
        }
    }

    private void seleccionarOrdenDeCompra() {
        if (tblOrdenesDeCompra.getSelectedRow() != -1) {
            ordenDeCompraSeleccionada = OrdenDeCompraFacade.getInstance()
                    .buscar((Long) tblOrdenesDeCompra.getValueAt(tblOrdenesDeCompra.getSelectedRow(), 0));
            cargarOrdenDeCompraSeleccionada();
        }
    }

    private void cargarOrdenDeCompraSeleccionada() {
        List<OrdenDeCompraArticulo> ordenDeCompraArticulos = ordenDeCompraSeleccionada.getOrdenDeCompraArticulos();
        cargarTablaItems(ordenDeCompraArticulos);
        List<Entrega> entregas = EntregaFacade.getInstance().buscar(ordenDeCompraSeleccionada);
        cargarTablaEntregas(entregas);
        actualizarPendientes();

        tblItems.requestFocus();
        if (cliente == null) {
            cliente = ordenDeCompraSeleccionada.getCliente();
        }
        listaVentaArticulos = new ArrayList<>();
        articulo = new Articulo();
        subTotal = BigDecimal.ZERO;
    }

    private void cargarTablaItems(List<OrdenDeCompraArticulo> ordenDeCompraArticulos) {
        modeloTablaItems = new ModeloTablaNoEditable();
        cargarEncabezadosTablaItems(modeloTablaItems);
        configurarTabla(tblItems);
        try {
            cargarItems(ordenDeCompraArticulos);
        } catch (Exception ex) {
            Logger.getLogger(FrVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargarEncabezadosTablaItems(ModeloTablaNoEditable modeloTablaItems) {
        modeloTablaItems.addColumn("Id");
        modeloTablaItems.addColumn("Cd.");
        modeloTablaItems.addColumn("Articulo");
        modeloTablaItems.addColumn("Peso/Cant.");
        modeloTablaItems.addColumn("Precio");
        modeloTablaItems.addColumn("Pendiente");
        tblItems.setModel(modeloTablaItems);
    }

    private void cargarItems(List<OrdenDeCompraArticulo> ordenDeCompras) {
        try {
            modeloTablaItems = new ModeloTablaNoEditable();
            cargarEncabezadosTablaItems(modeloTablaItems);
            for (OrdenDeCompraArticulo ventaArt : ordenDeCompras) {
                cargarItems(ventaArt);
            }
            tblItems.setModel(modeloTablaItems);
        } catch (Exception ex) {
            Logger.getLogger(FrVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargarItems(OrdenDeCompraArticulo ordenDeCompra) {

        Object[] fila = new Object[6];
        try {
            fila[0] = ordenDeCompra.getId();
        } catch (Exception e) {
        }
        try {
            fila[1] = ordenDeCompra.getArticulo().getCodigoBarra();
        } catch (Exception e) {
        }
        try {
            fila[2] = ordenDeCompra.getArticulo().getDescripcionReducida();
        } catch (Exception e) {
        }
        try {
            fila[3] = ordenDeCompra.getCantidadPeso();
        } catch (Exception e) {
        }
        try {
            fila[4] = ordenDeCompra.getPrecio();

        } catch (Exception e) {
        }

        try {
            fila[5] = ordenDeCompra.getCantidadPeso()
                    .subtract(EntregaParcialFacade.getInstance().totalOrdenDeCompraArticulo(ordenDeCompra)); //hacer consulta que busque pendientes
        } catch (Exception e) {
        }
        modeloTablaItems.addRow(fila);
    }

    private void cargarTablaEntregas(List<Entrega> entregas) {
        modeloTablaEntregas = new ModeloTablaNoEditable();
        cargarEncabezadosTablaEntregas(modeloTablaEntregas);
        configurarTabla(tbEntregas);
        try {
            cargarEntregas(entregas);
        } catch (Exception ex) {
            Logger.getLogger(FrVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargarEncabezadosTablaEntregas(ModeloTablaNoEditable modeloTablaOrdenes) {
        modeloTablaOrdenes.addColumn("Id");
        modeloTablaOrdenes.addColumn("Fecha");
        modeloTablaOrdenes.addColumn("Cdigo");
        modeloTablaOrdenes.addColumn("Articulo");
        modeloTablaOrdenes.addColumn("Cantidad/Peso");
        modeloTablaOrdenes.addColumn("Precio U.");
        modeloTablaOrdenes.addColumn("Total");
        modeloTablaOrdenes.addColumn("Ticket");
        modeloTablaOrdenes.addColumn("Item");
        tbEntregas.setModel(modeloTablaEntregas);
    }

    private void cargarEntregas(List<Entrega> ordenDeCompras) {
        try {
            modeloTablaEntregas = new ModeloTablaNoEditable();
            cargarEncabezadosTablaEntregas(modeloTablaEntregas);
            for (Entrega ventaArt : ordenDeCompras) {
                cargarEntrega(ventaArt);
            }
            tbEntregas.setModel(modeloTablaEntregas);
        } catch (Exception ex) {
            Logger.getLogger(FrVentas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargarEntrega(Entrega ordenDeCompra) {

        for (EntregaParcial va : ordenDeCompra.getEntregasParciales()) {
            Object[] fila = new Object[9];
            fila[0] = ordenDeCompra.getId();
            try {
                fila[1] = new SimpleDateFormat("dd/MM/yyyy").format(ordenDeCompra.getVenta().getFecha());
            } catch (Exception e) {
            }
            try {
                fila[2] = va.getVentaArticulo().getArticuloCodigo();
            } catch (Exception e) {
            }
            try {
                fila[3] = va.getVentaArticulo().getArticuloDescripcion();

            } catch (Exception e) {
            }
            try {
                fila[4] = va.getVentaArticulo().getCantidadPeso();
            } catch (Exception e) {
            }
            try {
                fila[5] = va.getVentaArticulo().getPrecioPromocion();
            } catch (Exception e) {
            }
            try {
                fila[6] = va.getVentaArticulo().getPrecio();
            } catch (Exception e) {
            }
            try {
                fila[7] = ordenDeCompra.getVenta().getNumeroTicket();
            } catch (Exception e) {
            }
            try {
                fila[8] = va.getOrdenDeCompraArticulo().getId();
            } catch (Exception e) {
            }
            modeloTablaEntregas.addRow(fila);
        }
    }

    private void cargarArticuloDeItem() {
        try {
            if (tblItems.getSelectedRow() != -1) {
                articulo = (ArticuloFacade.getInstance()
                        .buscarPorCodigo(tblItems.getValueAt(tblItems.getSelectedRow(), 1).toString()));
                ordenDeCompraArticulo = new OrdenDeCompraArticulo();
                ordenDeCompraArticulo = OrdenDeCompraArticuloFacade.getInstance()
                        .buscar((Long) tblItems.getValueAt(tblItems.getSelectedRow(), 0));
                pendiente = (BigDecimal) tblItems.getValueAt(tblItems.getSelectedRow(), 5);
                if (pendiente.compareTo(BigDecimal.ZERO) > 0) {
                    entregaParcial = new EntregaParcial();
                    entregaParcial.setOrdenDeCompraArticulo(ordenDeCompraArticulo);
                    if (!articulo.getUnidadMedida().isEsPeso()) {
                        ftfCantidad.setEnabled(true);
                    } else {
                        ftfCantidad.setEnabled(false);
                    }
                    tfCodigo1.setText(articulo.getCodigoBarra());
                    tfDescripcion1.setText(articulo.getDescripcion());
                    cargarArticulo();
                    tfCodigo.requestFocus();
                } else {
                    JOptionPane.showMessageDialog(rootPane, "El item seleccionado no tiene pendientes");
                    tblItems.requestFocus();
                }

            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "No se pudo cargar el articulo");
        }
    }

    private void limpiarTablas() {
        modeloTablaArticulos = new ModeloTablaNoEditable();
        modeloTablaEntregas = new ModeloTablaNoEditable();
        modeloTablaItems = new ModeloTablaNoEditable();
        modeloTablaOrdenes = new ModeloTablaNoEditable();
        tblArticulos.setModel(modeloTablaArticulos);
        tbEntregas.setModel(modeloTablaEntregas);
        tblItems.setModel(modeloTablaItems);
        tblOrdenesDeCompra.setModel(modeloTablaOrdenes);
    }

    private void reinciarCampos() {
        entrega = null;
        ordenDeCompraSeleccionada = null;
        cliente = null;
        articulo = null;
        precioArticulo = null;
        listaVentaArticulos = new ArrayList<>();
        subTotal = new BigDecimal(0.0);
        precioPromocion = new BigDecimal("0.0");
        entregaParcial = null;
        entregasParciales = new ArrayList<>();
        entrega = null;
        ftfDocumento.setText("");
        tfCliente.setText("");
        tfTotal.setText("");
    }

    private void buscarOrdenesCliente() {
        if (cliente != null) {
            if (!tfNumero.getText().isEmpty() && BigIntegerValidator.getInstance().isValid(tfNumero.getText())) {
                List<OrdenDeCompra> ordenDeCompras = OrdenDeCompraFacade.getInstance()
                        .buscarOrdenDeCompraNumeroTicketCliente(tfNumero.getText(), cliente);
                cargarTablaOrdenes(ordenDeCompras);
                tblOrdenesDeCompra.requestFocus();
            } else {
                cargarOdenesDeCompra();
            }
        } else if (!tfNumero.getText().isEmpty() && BigIntegerValidator.getInstance().isValid(tfNumero.getText())) {
            List<OrdenDeCompra> ordenDeCompras = OrdenDeCompraFacade.getInstance()
                    .buscarOrdenDeCompraNumeroTicket(tfNumero.getText());
            cargarTablaOrdenes(ordenDeCompras);
            tblOrdenesDeCompra.requestFocus();
        }
    }

    private void buscarPorNumero() {
        if (!tfNumero.getText().isEmpty()) {
            buscarOrden();
        } else if (cliente != null) {
            tblOrdenesDeCompra.requestFocus();
        }
    }

    private void confirmarPesada() {
        if (validarEntrega()) {
            //Ejecuta if true si la unidad de medida es por peso
            if (entregaParcial.getOrdenDeCompraArticulo().getArticulo().getUnidadMedida().isEsPeso()) {
                //JOptionPane.showMessageDialog(null, entregaParcial.getOrdenDeCompraArticulo().getArticulo().getUnidadMedida());
                if (tfPesoBalanza.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(null, "No se puede leer el peso \n Verifique balanza");
                } else {
                    if (pendiente.compareTo(new BigDecimal(tfPesoBalanza.getText())) >= 0) {
                        agregarArticulo();
                        calcularSubtotalGral();
                        actualizarPendientes();
                        tblItems.requestFocus();
                    } else {
                        JOptionPane.showMessageDialog(null, "El peso no puede ser mayor a lo pendiente");
                    }

                }
                //Ejecuta el bloque del else si es por cantidad
            } else if (ftfCantidad.getText().isEmpty()) {
                JOptionPane.showMessageDialog(null, "Debe colocar cantidad");
                ftfCantidad.requestFocus();
            } else {
                // JOptionPane.showMessageDialog(null, entregaParcial.getOrdenDeCompraArticulo().getArticulo().getUnidadMedida());
                if (pendiente.compareTo(new BigDecimal(ftfCantidad.getText())) >= 0) {
                    agregarArticulo();
                    calcularSubtotalGral();
                    actualizarPendientes();
                    tblItems.requestFocus();
                } else {
                    JOptionPane.showMessageDialog(null, "La cantidad no puede ser mayor a lo pendiente");
                    ftfCantidad.requestFocus();
                }
            }
        }

    }

    private void actualizarPendientes() {
        for (int i = 0; i < tblItems.getRowCount(); i++) {
            try {
                if (Objects.equals((Long) tblItems.getValueAt(i, 0),
                        entregaParcial.getOrdenDeCompraArticulo().getId())) {
                    BigDecimal pendiente = (BigDecimal) tblItems.getValueAt(i, 5);
                    tblItems.setValueAt(pendiente.subtract(entregaParcial.getVentaArticulo().getCantidadPeso()), i,
                            5);
                }
            } catch (Exception e) {
            }
        }
    }

    private void deshacerActualizarPendientes(EntregaParcial entregaParcial) {
        for (int i = 0; i < tblItems.getRowCount(); i++) {
            try {
                if (Objects.equals((Long) tblItems.getValueAt(i, 0),
                        entregaParcial.getOrdenDeCompraArticulo().getId())) {
                    BigDecimal pendienteARestar = (BigDecimal) tblItems.getValueAt(i, 5);
                    tblItems.setValueAt(pendienteARestar.add(entregaParcial.getVentaArticulo().getCantidadPeso()),
                            i, 5);
                }
            } catch (Exception e) {
            }
        }
    }

    private boolean validarEntrega() {
        if (cliente == null) {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un cliente", "Mensaje",
                    JOptionPane.ERROR_MESSAGE);
            ftfDocumento.requestFocus();
            return false;
        }
        if (ordenDeCompraSeleccionada == null) {
            JOptionPane.showMessageDialog(null, "Debe seleccionar Orden de compra", "Mensaje",
                    JOptionPane.ERROR_MESSAGE);
            tblOrdenesDeCompra.requestFocus();
            return false;
        }
        if (entregaParcial == null) {
            JOptionPane.showMessageDialog(null, "Debe seleccionar entrega", "Mensaje", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (articulo == null) {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un producto", "Mensaje",
                    JOptionPane.ERROR_MESSAGE);
            tfCodigo.requestFocus();
            return false;
        }
        return true;
    }

    public void quitarArticuloLista() {

        int i = JOptionPane.showConfirmDialog(null, "Desea eliminar el articulo seleccionado?",
                "Confirmar eliminacion", JOptionPane.YES_NO_OPTION);
        if (i == 0) {
            int selectedRow = tblArticulos.getSelectedRow();
            EntregaParcial ep = entregasParciales.get(selectedRow);
            listaVentaArticulos.remove(selectedRow);
            entregasParciales.remove(selectedRow);//faltaba borrar la entrega
            //cargarTablaArticulos(listaVentaArticulos); //no hace falta cargar tenes q borrar de la que esta
            ((ModeloTablaNoEditable) tblArticulos.getModel()).removeRow(selectedRow);
            calcularSubtotalGral();
            deshacerActualizarPendientes(ep);//tenes q pasarle la entrega para que sume esa y sino suma la ultima
            tfCodigo.requestFocus();
            tfCodigo.selectAll();

        }
    }
}