private void btn_guardar_Click(object sender, EventArgs e)
        {
            if (_estado == estados.nuevo)
            {
                if (dgv_detalle.Rows.Count >= 1)
                {
                    List<DetalleOrdenCompra> detalle = new List<DetalleOrdenCompra>();

                    for (int c = 0; c < dgv_detalle.RowCount; c++)
                    {
                        DetalleOrdenCompra de = new DetalleOrdenCompra();
                        Producto p = new Producto();

                        p.idProducto = (int)dgv_detalle.Rows[c].Cells["idProductodetalle"].Value;
                        p.precio = (double)dgv_detalle.Rows[c].Cells["preciodetalle"].Value;

                        de.cantidad = Convert.ToDouble(dgv_detalle.Rows[c].Cells["cantidad"].Value);
                        de.precio = (double)dgv_detalle.Rows[c].Cells["preciodetalle"].Value;
                        de.subTotal = (double)dgv_detalle.Rows[c].Cells["sub"].Value;

                        de.producto = p;

                        detalle.Add(de);
                    }
                    Persona prov = new Persona();
                    prov.idPersona = (int)cmb_proveedores.SelectedValue;
                    OrdenDeCompra oc = new OrdenDeCompra()
                      {
                          detalleOrdenCompra = detalle,
                          proveedor = prov,
                          monto = Convert.ToDouble(txt_monto_total.Text),
                          fechaOrden = dtp_creacion_OT.Value.Date

                      };
                    try
                    {
                        OrdenDeCompraDAO.Insert(oc);
                        MessageBox.Show("Registrado con Exito", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        limpiarCampos();
                        btn_guardar.Enabled = false;

                    }
                    catch (ApplicationException ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    }

                }
                else
                {
                    MessageBox.Show("La orden de compra no tiene productos, Por favor carguelos", "ATENCION");
                }

            }
        }
        private void dgv_pedidos_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv_pedidos.CurrentCell is DataGridViewButtonCell)
            {
                if ((int)dgv_pedidos.Rows[dgv_pedidos.CurrentRow.Index].Cells["idestado"].Value==31)
                {
                    if (cerraronLosHIjo())
                    {
                        try
                        {
                            List<DetalleOrdenCompra> detalle = new List<DetalleOrdenCompra>();

                            double montoReal = 0;
                            for (int i = 0; i < dgv_detalle_pedido.Rows.Count; i++)//SE CARGA CADA DETALLE PARA LUEGO ACTUALIZAR STOCK DE MP
                            {
                                DetalleOrdenCompra det = new DetalleOrdenCompra();

                                det.producto = new Producto() { idProducto = (int)dgv_detalle_pedido.Rows[i].Cells["codProd"].Value };
                                det.cantidadRealIngresada = Convert.ToDouble(dgv_detalle_pedido.Rows[i].Cells["cantReal"].Value);
                                UnidadMedida u = new UnidadMedida();

                                if ((string)dgv_detalle_pedido.Rows[i].Cells["unidadReal"].Value == "g")
                                {
                                    u.Descripcion = "g";
                                }
                                else
                                    u.Descripcion = "";
                                det.producto.Unidad = u;
                                det.precio = (Double)dgv_detalle_pedido.Rows[i].Cells["precio"].Value;
                                if(((string)dgv_detalle_pedido.Rows[i].Cells["unidad"].Value).Equals("g"))
                                {
                                    det.precio = det.precio/1000;
                                }
                                montoReal += det.cantidadRealIngresada * det.precio;
                                detalle.Add(det);
                            }

                            OrdenDeCompra ord = new OrdenDeCompra();
                            ord.montoReal=montoReal;
                            ord.detalleOrdenCompra = detalle;
                            ord.idOrdenCompra = (int)dgv_pedidos.CurrentRow.Cells["idOrden"].Value;
                            ord.estado = new Estado() { idEstado = 32 };

                            OrdenDeCompraDAO.UpdateEstadoOrdenCompra(ord);

                            MessageBox.Show("Finalizado con éxito", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

                        }
                        catch (ApplicationException ex)
                        {
                            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Falta Registrar la Cantidades de Productos", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    }

                    cargarGrilla();
                    dgv_detalle_pedido.Rows.Clear();
                }
            }
        }
        private void dgv_detalle_pedido_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv_detalle_pedido.CurrentCell is DataGridViewButtonCell)
            {
                try
                {
                    double? valor = ((Double?)dgv_detalle_pedido.CurrentRow.Cells["cantReal"].Value);

                    if (valor == null)
                    {
                        double canti = (double)dgv_detalle_pedido.Rows[dgv_detalle_pedido.CurrentRow.Index].Cells["cant"].Value;
                        string resul = Microsoft.VisualBasic.Interaction.InputBox("Ingrese la Cantidad Comprada", "Orden de Compra", canti.ToString());
                        try
                        {
                            if (!string.IsNullOrEmpty(resul))
                            {

                                DetalleOrdenCompra det = new DetalleOrdenCompra();

                                //det.ordenCompra  = new OrdenDeCompra (){ idOrdenCompra =  (int)dgv_detalle_pedido.Rows[dgv_detalle_pedido.CurrentRow.Index].Cells["codProd"].Value};
                                det.producto = new Producto() { idProducto = (int)dgv_detalle_pedido.Rows[dgv_detalle_pedido.CurrentRow.Index].Cells["codProd"].Value };
                                det.cantidad = canti;
                                det.cantidadRealIngresada = Convert.ToDouble(resul);

                                //OrdenDeTrabajoDAO.finalizarOTHija(det);

                                MessageBox.Show("Finalizado con éxito", "Exito", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);

                                dgv_detalle_pedido.CurrentRow.Cells["cantReal"].Value = resul;
                                dgv_detalle_pedido.CurrentRow.Cells["carrar"].Value = "Sin Opción";
                                cerraronLosHIjo();
                            }
                            dgv_detalle_pedido.ClearSelection();

                        }
                        catch (ApplicationException ex)
                        {
                            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                        }
                        catch (FormatException ex)
                        {

                            MessageBox.Show("Ingrese solo números", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

                        }
                    }

                }
                catch (InvalidCastException ex)
                {

                }

            }
        }
        public static void Insert(DetalleOrdenCompra  det, SqlConnection cn, SqlTransaction tran, int idOrden)
        {
            Acceso ac = new Acceso();

            //SqlConnection conexion = new SqlConnection(ac.getCadenaConexion());

            SqlCommand cmd = new SqlCommand("sp_insertar_detalle_orden_compra", cn);

            cmd.Parameters.AddWithValue("@idOrdenCompra", idOrden);
            cmd.Parameters.AddWithValue("@idProducto", det.producto.idProducto);
            cmd.Parameters.AddWithValue("@cantidad", det.cantidad);
            cmd.Parameters.AddWithValue("@precio", det.precio);
            cmd.Parameters.AddWithValue("@subtotal", det.subTotal );

            try
            {
                cmd.Connection = cn;
                cmd.Transaction = tran;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.ExecuteNonQuery();

            }
            catch (ArgumentException ex)
            {
                throw new ApplicationException(ex.Message);
            }
            catch (SqlException ex)
            {
                throw new ApplicationException("Error en BD: " + ex.Message);
            }
        }
        public static List<DetalleOrdenCompra> GetDetalleXOrdenDeCompra(int oc)
        {
            Acceso ac = new Acceso();

            List<DetalleOrdenCompra> detalles = new List<DetalleOrdenCompra>();

            string sql = "SELECT * from CONSULTAR_DETALLE_ORDEN_COMPRA where idOrdenCompra = @oc";
            SqlCommand cmd = new SqlCommand();
            cmd.Parameters.AddWithValue("@oc", oc);
            SqlConnection conexion = new SqlConnection(ac.getCadenaConexion());

            try
            {
                conexion.Open();

                cmd.Connection = conexion;
                cmd.CommandText = sql;
                cmd.CommandType = CommandType.Text;

                SqlDataReader dr = cmd.ExecuteReader();

                DetalleOrdenCompra d;
                Producto p;
                UnidadMedida u;
                OrdenDeCompra o;

                while (dr.Read())
                {
                    o = new OrdenDeCompra();
                    o.idOrdenCompra = Convert.ToInt32(dr["idOrdenCompra"]);

                    u = new UnidadMedida();

                    u.IDUnidad = Convert.ToInt32(dr["idUnidadMedida"]);
                    u.Nombre = dr["Unidad"].ToString();

                    p = new Producto();

                    p.Nombre = dr["nombre"].ToString();
                    p.Unidad = u;
                    p.idProducto = Convert.ToInt16(dr["idProducto"]);
                    p.StockDisponible = Convert.ToDouble(dr["stockDisponible"]);
                    p.StockRiesgo = Convert.ToDouble(dr["stockdeRiesgo"]);
                    p.StockActual = Convert.ToDouble(dr["stockactual"]);
                    p.StockReservado = Convert.ToDouble(dr["stockreservado"]);

                    d = new DetalleOrdenCompra();

                    d.cantidad = Convert.ToDouble(dr["cantidad"]);
                    d.producto = p;
                    d.precio = Convert.ToDouble(dr["precio"]);
                    d.subTotal = Convert.ToDouble(dr["subTotal"]);
                    d.cantidadRealIngresada = Convert.ToDouble(dr["cantidadRealIngresada"]);
                    d.ordenCompra = o;

                    detalles.Add(d);

                }

            }
            catch (InvalidOperationException ex)
            {
                throw new ApplicationException(ex.Message);
            }
            catch (SqlException ex)
            {
                throw new ApplicationException("Error en BD: " + ex.Message);
            }
            finally
            {
                conexion.Close();
            }

            return detalles;
        }
        public static void UpdateCantidadIngresadaReal(DetalleOrdenCompra  det, int idOrden, SqlConnection con, SqlTransaction tran)
        {
            Acceso ac = new Acceso();

            string sql =("UPDATE [Luiggi].[dbo].[DetalleOrdenCompra] SET [cantidadRealIngresada] = @cantidadRealIngresada, [subtotal] = @cantidadRealIngresada * @precio   WHERE idProducto = @idProducto and idOrdenCompra = @idOrdenCompra");
            SqlCommand cmd = new SqlCommand(sql, con, tran);

            cmd.Parameters.AddWithValue("@idProducto", det.producto.idProducto);
            cmd.Parameters.AddWithValue("@cantidadRealIngresada", det.cantidadRealIngresada );
            cmd.Parameters.AddWithValue("@idOrdenCompra", idOrden);
            cmd.Parameters.AddWithValue("@precio", det.precio);

            try
            {

                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();

                ProductoDAO.UpdateStockActualYDisponibleInsumosYMPIngresadas(det, con,tran);

            }
            catch (ArgumentException ex)
            {
                throw new ApplicationException(ex.Message);
            }
            catch (SqlException ex)
            {
                throw new ApplicationException("Error en BD: " + ex.Message);
            }
            finally
            {

            }
        }