Imports System.Data.SqlClient
Imports System.Runtime.InteropServices
Public Class FrmInvoices
#Region "Mov. Pantalla"
    <DllImport("user32.Dll", EntryPoint:="ReleaseCapture")>
    Private Shared Sub ReleaseCapture()
    End Sub

    <DllImport("user32.Dll", EntryPoint:="SendMessage")>
    Private Shared Sub SendMessage(hWnd As IntPtr, wMsg As Integer, wParam As Integer, lParam As Integer)
    End Sub

    Private Sub PanelBarraTitulo_MouseMove(sender As Object, e As MouseEventArgs) Handles PanelBarraTitulo.MouseMove
        ReleaseCapture()
        SendMessage(Me.Handle, &H112&, &HF012&, 0)
    End Sub
    Private Sub lblEmpresa_MouseMove(sender As Object, e As MouseEventArgs) Handles lblEmpresa.MouseMove
        ReleaseCapture()
        SendMessage(Me.Handle, &H112&, &HF012&, 0)
    End Sub

#End Region

    Dim EditoDetalle As Boolean
    Dim varMensaje, BuzonCompleto As String
    Dim Ds As DataSet
    Dim CantLetra As String

    Private Sub btnCerrar_Click(sender As Object, e As EventArgs) Handles btnCerrar.Click
        If GlobalVariables.EditoInvoice = True Then
            MsgBox("Atención! Captura de Invoice/Remisión en proceso... Guardar o Cancelar el registro para continuar.", MsgBoxStyle.Information, "Mensaje del Sistema")
            Exit Sub
        End If

        Me.Close()
        CerrarFormulario()
    End Sub

    Private Sub FrmInvoices_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Inicializar()
    End Sub
    Sub Inicializar()
        LlenarCombo(Cliente, "Clientes", "RazonSoc", "RazonSoc")

        If GlobalVariables.VarFromHistoInv = False Then
            VaciarGrid()
            LimpiarCampos(Me)
            LockCampos(Me)
            Fecha.Format = DateTimePickerFormat.Custom
            Fecha.CustomFormat = " "
            FechaPag.Format = DateTimePickerFormat.Custom
            FechaPag.CustomFormat = " "
            FechaVenc.Format = DateTimePickerFormat.Custom
            FechaVenc.CustomFormat = " "
        ElseIf GlobalVariables.VarFromHistoInv = True Then
            VaciarGrid()
            LimpiarCampos(Me)
            CargaDatosMaster()
            CargarDGV()
            VerificaEstatus()
        End If
    End Sub
    Sub VerificaEstatus()
        If Estatus.Text = "POR PAGAR" Or Estatus.Text = "POR PAGAR-ENV. MAIL" Then
            btnGrabar.Enabled = True
            btnAddReg.Enabled = True
            btnDelReg.Enabled = True
            BtnPagar.Enabled = True
            btnImprimir.Enabled = True
            btnCancelar.Enabled = True
            btnMail.Enabled = True
            UnlockCampos(Me)
        ElseIf Estatus.Text = "PAGADA" Or Estatus.Text = "CANCELADA" Then
            btnGrabar.Enabled = False
            btnAddReg.Enabled = False
            btnDelReg.Enabled = False
            BtnPagar.Enabled = False
            btnImprimir.Enabled = True
            btnCancelar.Enabled = False
            btnMail.Enabled = True
            LockCampos(Me)
        End If
    End Sub
    Sub CargaDatosMaster()
        Dim cn As SqlConnection = New SqlConnection(GlobalVariables.cstring)
        Dim cmd As SqlCommand = New SqlCommand
        cmd.CommandType = CommandType.Text
        cmd.Connection = cn
        cmd.CommandText = "Select * from Invoices where Id=" & GlobalVariables.VarIDReg
        Try
            cn.Open()
            Dim LeeDatos As SqlDataReader = cmd.ExecuteReader
            If LeeDatos.HasRows = True Then
                LeeDatos.Read()
                Id.Text = LeeDatos.Item("Id")
                Capturo.Text = LeeDatos.Item("Capturo")
                Consecutivo.Text = LeeDatos.Item("Consecutivo")
                Folio.Text = LeeDatos.Item("Folio")
                TipoReg.Text = LeeDatos.Item("TipoReg")
                Fecha.Value = LeeDatos.Item("Fecha")
                Cliente.Text = LeeDatos.Item("Cliente")
                Direccion.Text = LeeDatos.Item("Direccion")
                Estatus.Text = LeeDatos.Item("Estatus")
                If IsDBNull(LeeDatos.Item("Pagado")) Then
                    Pagado.Checked = False
                Else
                    Pagado.Checked = LeeDatos.Item("Pagado")
                End If

                If IsDBNull(LeeDatos.Item("FechaPag")) Then
                    FechaPag.Format = DateTimePickerFormat.Custom
                    FechaPag.CustomFormat = " "
                Else
                    FechaPag.Value = LeeDatos.Item("FechaPag")
                End If

                If IsDBNull(LeeDatos.Item("FechaVenc")) Then
                    FechaVenc.Format = DateTimePickerFormat.Custom
                    FechaVenc.CustomFormat = " "
                Else
                    FechaVenc.Value = LeeDatos.Item("FechaVenc")
                End If

                If IsDBNull(LeeDatos.Item("RefPago")) Then
                    RefPago.Text = ""
                Else
                    RefPago.Text = LeeDatos.Item("RefPago")
                End If
                Moneda.Text = LeeDatos.Item("Moneda")
                Obs.Text = LeeDatos.Item("Obs")
                Total.Text = Convert.ToDouble(LeeDatos.Item("Total")).ToString("C2")
                Obs.Text = LeeDatos.Item("Obs")
                TotalLetra.Text = LeeDatos.Item("TotalLetra")
            End If
            cn.Close()
        Catch ex As Exception
            MsgBox("Problema al cargar los datos Master, verifique su conexion de red." & vbCrLf & ex.Message)
        End Try
    End Sub

    Sub CargarDGV()
        Dim sql As String
        Dim cn As SqlConnection
        Dim cm As SqlCommand
        Dim da As SqlDataAdapter
        Dim ds As DataSet
        sql = "Select Id, IdReg, Folio, Linea, Descripcion, Pedimento, Caja, Invo, FecInvo, Cantidad, Precio, Importe from InvoicesDet where IdReg=" & Me.Id.Text & " order by Linea"
        cn = New SqlConnection(GlobalVariables.cstring)
        Try
            cn.Open()

            cm = New SqlCommand()
            cm.CommandText = sql
            cm.CommandType = CommandType.Text
            cm.Connection = cn
            da = New SqlDataAdapter(cm)
            ds = New DataSet()
            da.Fill(ds)

            Me.BindingSource1.DataSource = ds.Tables(0).DefaultView
            Me.DGVPartidas.DataSource = Me.BindingSource1
            'ocultar columna y formatear una columna
            DGVPartidas.Columns(0).Visible = False
            DGVPartidas.Columns(1).Visible = False
            DGVPartidas.Columns(2).Visible = False

            DGVPartidas.Columns.Item("Linea").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            DGVPartidas.Columns.Item("Cantidad").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            DGVPartidas.Columns.Item("Precio").DefaultCellStyle.Format = "C2"
            DGVPartidas.Columns.Item("Precio").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            DGVPartidas.Columns.Item("Importe").DefaultCellStyle.Format = "C2"
            DGVPartidas.Columns.Item("Importe").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

            FormatoFilas()
            cn.Close()
            cm = Nothing
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Information)
        End Try
    End Sub

    Sub FormatoFilas()
        DGVPartidas.Columns("Linea").Width = 20
        DGVPartidas.Columns("Descripcion").Width = 360
        DGVPartidas.Columns("Cantidad").Width = 40
        DGVPartidas.Columns("Precio").Width = 75
        DGVPartidas.Columns("Importe").Width = 75

        With DGVPartidas
            'CAMBIA LOS TITULOS DE LAS COLUMNAS a ingles
            .Columns(3).HeaderText = "LINEA"
            .Columns(4).HeaderText = "DESCRIPCION"
            .Columns(5).HeaderText = "PEDIMENTO"
            .Columns(6).HeaderText = "CAJA"
            .Columns(7).HeaderText = "INVO."
            .Columns(8).HeaderText = "FECHA MOV."
            .Columns(9).HeaderText = "CANT."
            .Columns(10).HeaderText = "PRECIO"
            .Columns(11).HeaderText = "TOTAL"
        End With
    End Sub

    Sub VaciarGrid()
        DGVPartidas.DataSource = Nothing
        DGVPartidas.Rows.Clear()
        DGVPartidas.Refresh()
    End Sub

    Private Sub btnNuevo_Click(sender As Object, e As EventArgs) Handles btnNuevo.Click
        UnlockCampos(Me)
        BloquearPago()
        GlobalVariables.EditoInvoice = True
        LimpiarCampos(Me)
        VaciarGrid()

        FechaPag.Format = DateTimePickerFormat.Custom
        FechaPag.CustomFormat = " "

        Me.Fecha.Format = DateTimePickerFormat.Short
        Me.Fecha.Value = Date.Today

        Me.FechaVenc.Format = DateTimePickerFormat.Short
        Me.FechaVenc.Value = Fecha.Value.AddDays(30)

        Me.Estatus.Text = "POR PAGAR"
        Me.Capturo.Text = GlobalVariables.VarUsuario
        Me.Moneda.Text = "Dollar USD"

        btnMail.Enabled = True
        btnGrabar.Enabled = True
        btnCancelar.Enabled = True
        btnAddReg.Enabled = True
        btnDelReg.Enabled = True
        btnImprimir.Enabled = False
        btnMail.Enabled = True
        TipoReg.Focus()

    End Sub

    Sub BloquearPago()
        Estatus.ReadOnly = True
        Pagado.Enabled = False
        FechaPag.Enabled = False
        RefPago.ReadOnly = True
        BtnPagar.Enabled = False
    End Sub

    Sub DesBloquearPago()
        Estatus.ReadOnly = False
        Pagado.Enabled = True
        FechaPag.Enabled = True
        RefPago.ReadOnly = False
        BtnPagar.Enabled = True
    End Sub

    Private Sub Cliente_KeyDown(sender As Object, e As KeyEventArgs) Handles Cliente.KeyDown
        If e.KeyCode = Keys.Enter Then
            If Me.Cliente.Text Is Nothing Or IsDBNull(Me.Cliente.Text) Or Me.Cliente.Text = "" Then
                Exit Sub
            Else
                If Me.TipoReg.Text Is Nothing Or IsDBNull(Me.TipoReg.Text) Or Me.TipoReg.Text = "" Then
                    MsgBox("Atención!, primero seleccione el Tipo de Registro.", vbInformation, "Mensaje del Sistema")
                    Cliente.Text = ""
                    Exit Sub
                End If

                If Id.Text = "" Then
                    GrabaNoInvoice()
                    Id.Text = DLookup("Id", "Invoices", "Folio='" & Folio.Text & "'")
                    ArmaDireccion()
                Else
                    Exit Sub
                End If
            End If
        End If
    End Sub

    Private Sub Cliente_Validated(sender As Object, e As EventArgs) Handles Cliente.Validated
        If Me.Cliente.Text Is Nothing Or IsDBNull(Me.Cliente.Text) Or Me.Cliente.Text = "" Then
            Exit Sub
        Else
            If Me.TipoReg.Text Is Nothing Or IsDBNull(Me.TipoReg.Text) Or Me.TipoReg.Text = "" Then
                MsgBox("Atención!, primero seleccione el Tipo de Registro.", vbInformation, "Mensaje del Sistema")
                Cliente.Text = ""
                Exit Sub
            End If

            If Id.Text = "" Then
                GrabaNoInvoice()
                Id.Text = DLookup("Id", "Invoices", "Folio='" & Folio.Text & "'")
                ArmaDireccion()
            Else
                ArmaDireccion()
                Exit Sub
            End If
        End If
    End Sub

    Sub GrabaNoInvoice()
        Dim sql As String = ""
        Consecutivo.Text = DMaxCriterio("Consecutivo", "Invoices", "TipoReg='" & TipoReg.Text & "'") + 1
        Folio.Text = TipoReg.Text & " - " & Consecutivo.Text

        sql = "INSERT INTO Invoices (Capturo, Consecutivo, Folio, TipoReg) VALUES (@Capturo, @Consecutivo, @Folio, @TipoReg)"

        Try
            Dim cn As New SqlConnection(GlobalVariables.cstring)
            Dim cmd As New SqlCommand(sql, cn)
            cn.Open()
            cmd.Parameters.AddWithValue("@Capturo", GlobalVariables.VarUsuario)
            cmd.Parameters.AddWithValue("@Consecutivo", Consecutivo.Text)
            cmd.Parameters.AddWithValue("@Folio", Folio.Text)
            cmd.Parameters.AddWithValue("@TipoReg", TipoReg.Text)
            cmd.ExecuteNonQuery()
            cn.Close()
            cmd = Nothing

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Sub ArmaDireccion()
        If DLookup("Pais", "Clientes", "RazonSoc='" & Cliente.Text & "'") = "EEUU" Then
            Dim VarNum As String = DLookup("Numero", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarCalle As String = DLookup("Calle", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarCiudad As String = DLookup("Estado", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarCP As String = DLookup("CodPos", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarTel As String = DLookup("TelUno", "Clientes", "RazonSoc='" & Cliente.Text & "'")

            Direccion.Text = VarNum & " " & VarCalle & vbCrLf _
                         & VarCiudad & " " & VarCP & vbCrLf _
                         & VarTel

            Descripcion.Focus()
        Else
            Dim VarNum As String = DLookup("Numero", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarCalle As String = DLookup("Calle", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarCiudad As String = DLookup("Estado", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarCP As String = DLookup("CodPos", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarTel As String = DLookup("TelUno", "Clientes", "RazonSoc='" & Cliente.Text & "'")
            Dim VarCol As String = DLookup("Colonia", "Clientes", "RazonSoc='" & Cliente.Text & "'")


            Direccion.Text = VarCalle & " " & VarNum & " COL. " & VarCol & vbCrLf _
                             & VarCiudad & ", " & " CP " & VarCP & vbCrLf _
                             & VarTel

            Descripcion.Focus()
        End If
    End Sub

    Private Sub TipoReg_Validated(sender As Object, e As EventArgs) Handles TipoReg.Validated
        If Id.Text = "" Then
            Exit Sub
        Else
            Consecutivo.Text = DMaxCriterio("Consecutivo", "Invoices", "TipoReg='" & TipoReg.Text & "'") + 1
            Folio.Text = TipoReg.Text & " - " & Consecutivo.Text

            QryInsUpDel("UPDATE Invoices SET Consecutivo =" & CInt(Consecutivo.Text) & ", Folio='" & Folio.Text & "' WHERE Id=" & Id.Text & "")
            QryInsUpDel("UPDATE InvoicesDet SET Folio='" & Folio.Text & "' WHERE IdReg=" & Id.Text & "")
        End If
    End Sub

    Private Sub Descripcion_KeyDown(sender As Object, e As KeyEventArgs) Handles Descripcion.KeyDown
        If e.KeyCode = Keys.Enter Then
            If Me.Folio.Text Is Nothing Or IsDBNull(Me.Folio.Text) Or Me.Folio.Text = "" Then
                MsgBox("Atención!, No Existe NO. DE INVOCE/REMISION, debe capturar un Cliente.", MsgBoxStyle.Critical, "Mensaje del Sistema")
                Descripcion.Text = ""
                Exit Sub
            Else
                If EditoDetalle = False Then
                    Linea.Text = DMaxCriterio("Linea", "InvoicesDet", "IdReg=" & Id.Text & "") + 1
                End If
                Cantidad.Text = 1
                Pedimento.Focus()
            End If
        End If
    End Sub

    Private Sub Descripcion_Validated(sender As Object, e As EventArgs) Handles Descripcion.Validated
        If Me.Folio.Text Is Nothing Or IsDBNull(Me.Folio.Text) Or Me.Folio.Text = "" Then
            MsgBox("Atención!, No Existe NO. DE INVOCE/REMISION, debe capturar un Cliente.", MsgBoxStyle.Critical, "Mensaje del Sistema")
            Descripcion.Text = ""
            Exit Sub
        Else
            If EditoDetalle = False Then
                Linea.Text = DMaxCriterio("Linea", "InvoicesDet", "IdReg=" & Id.Text & "") + 1
            End If
            Cantidad.Text = 1
            Pedimento.Focus()
        End If
    End Sub

    Private Sub Cantidad_Validated(sender As Object, e As EventArgs) Handles Cantidad.Validated
        If Me.Cantidad.Text Is Nothing Or IsDBNull(Me.Cantidad.Text) Or Me.Cantidad.Text = "" Then
            Exit Sub
        Else
            If Me.Precio.Text Is Nothing Or IsDBNull(Me.Precio.Text) Or Me.Precio.Text = "" Then
                Exit Sub
            Else
                Dim VarImporte As Double = (CDbl(Cantidad.Text) * CDbl(Precio.Text))
                Me.Importe.Text = VarImporte.ToString("C2")
                Precio.Focus()
            End If
        End If
    End Sub

    Private Sub Cantidad_KeyDown(sender As Object, e As KeyEventArgs) Handles Cantidad.KeyDown
        If e.KeyCode = Keys.Enter Then
            If Me.Cantidad.Text Is Nothing Or IsDBNull(Me.Cantidad.Text) Or Me.Cantidad.Text = "" Then
                Exit Sub
            Else
                If Me.Precio.Text Is Nothing Or IsDBNull(Me.Precio.Text) Or Me.Precio.Text = "" Then
                    Exit Sub
                Else
                    Dim VarImporte As Double = (CDbl(Cantidad.Text) * CDbl(Precio.Text))
                    Me.Importe.Text = VarImporte.ToString("C2")
                    Precio.Focus()
                End If
            End If
        End If
    End Sub

    Private Sub Precio_Validated(sender As Object, e As EventArgs) Handles Precio.Validated
        If Me.Precio.Text Is Nothing Or IsDBNull(Me.Precio.Text) Or Me.Precio.Text = "" Then
            Exit Sub
        Else
            If Me.Cantidad.Text Is Nothing Or IsDBNull(Me.Cantidad.Text) Or Me.Cantidad.Text = "" Then
                Exit Sub
            Else
                Dim VarImporte As Double = (CDbl(Cantidad.Text) * CDbl(Precio.Text))
                Me.Importe.Text = VarImporte.ToString("C2")
                btnAddReg.Focus()
            End If
        End If
    End Sub

    Private Sub Precio_KeyDown(sender As Object, e As KeyEventArgs) Handles Precio.KeyDown
        If e.KeyCode = Keys.Enter Then
            If Me.Precio.Text Is Nothing Or IsDBNull(Me.Precio.Text) Or Me.Precio.Text = "" Then
                Exit Sub
            Else
                If Me.Cantidad.Text Is Nothing Or IsDBNull(Me.Cantidad.Text) Or Me.Cantidad.Text = "" Then
                    Exit Sub
                Else
                    Dim VarImporte As Double = (CDbl(Cantidad.Text) * CDbl(Precio.Text))
                    Me.Importe.Text = VarImporte.ToString("C2")
                    btnAddReg.Focus()
                End If
            End If
        End If
    End Sub

    Private Sub DGVPartidas_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVPartidas.CellContentDoubleClick
        Me.Linea.Text = Me.DGVPartidas.CurrentRow.Cells("Linea").Value
        Me.Descripcion.Text = Me.DGVPartidas.CurrentRow.Cells("Descripcion").Value
        Me.Cantidad.Text = Me.DGVPartidas.CurrentRow.Cells("Cantidad").Value
        Dim VPrecio As Double = Me.DGVPartidas.CurrentRow.Cells("Precio").Value
        Me.Precio.Text = VPrecio.ToString("c2")
        Dim VImporte As Double = Me.DGVPartidas.CurrentRow.Cells("Importe").Value
        Me.Importe.Text = VImporte.ToString("c2")

        Me.Pedimento.Text = Me.DGVPartidas.CurrentRow.Cells("Pedimento").Value
        Me.Caja.Text = Me.DGVPartidas.CurrentRow.Cells("Caja").Value
        Me.Invo.Text = Me.DGVPartidas.CurrentRow.Cells("Invo").Value
        Me.FecInvo.Text = Me.DGVPartidas.CurrentRow.Cells("FecInvo").Value

        EditoDetalle = True
    End Sub

    Private Sub btnDelReg_Click(sender As Object, e As EventArgs) Handles btnDelReg.Click
        EliminaDetalle()
        LimpiaDetalle()
        TotalizaInvoice()
        EditoDetalle = False
    End Sub
    Sub EliminaDetalle()
        If Me.Linea.Text = "" Then
            MsgBox("Atención!, no existe linea cargada para Eliminar.", MsgBoxStyle.Information, "Mensaje del Sistema")
            Exit Sub
        Else
            Dim sql As String = ""
            sql = " DELETE FROM  InvoicesDet WHERE idreg =" & Id.Text & " and Linea = " & Me.Linea.Text
            If MsgBox("Seguro(a) de eliminar la partida actual?", MsgBoxStyle.YesNo, "Mensaje del Sistema") = vbYes Then
                Try
                    Dim cn As New SqlConnection(GlobalVariables.cstring)
                    Dim cmd As New SqlCommand(sql, cn)
                    cn.Open()
                    cmd.ExecuteNonQuery()
                    cn.Close()
                    cmd = Nothing
                    CargarDGV()
                    ReEnumeraLineas()
                Catch ex As Exception
                    MsgBox(ex.ToString)
                End Try
            End If
        End If
    End Sub
    Sub ReEnumeraLineas()
        Dim NoLinea As Integer = 0
        Dim VarNoCoti As Integer = CInt(Id.Text)
        Dim VarIDReg As Integer = 0
        For Each row As DataGridViewRow In Me.DGVPartidas.Rows
            NoLinea += 1
            VarIDReg = CInt(row.Cells("id").Value)
            ActualizaLineadetalle(NoLinea, VarNoCoti, VarIDReg)
        Next
    End Sub
    Sub ActualizaLineadetalle(NoLin As Int32, IDCotizacion As Int32, IDRegistro As Int32)
        Try
            Using cnn As SqlConnection = New SqlConnection(GlobalVariables.cstring)

                Dim sql As String = "UPDATE InvoicesDet SET Linea = @Linea WHERE IdReg = " & IDCotizacion & " and id = " & IDRegistro

                Dim cmd As SqlCommand = New SqlCommand(sql, cnn)
                cnn.Open()
                cmd.Parameters.AddWithValue("@Linea", NoLin)
                cmd.ExecuteNonQuery()
                cnn.Close()
            End Using

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Sub LimpiaDetalle()
        Linea.Text = ""
        Descripcion.Text = ""
        Cantidad.Text = ""
        Precio.Text = ""
        Importe.Text = ""
        Pedimento.Text = ""
        Caja.Text = ""
        Invo.Text = ""
        FecInvo.Text = ""
    End Sub

    Sub TotalizaInvoice()
        Dim ValorSubTotal As Double = 0
        For Each row As DataGridViewRow In Me.DGVPartidas.Rows
            ValorSubTotal += Val(row.Cells("Importe").Value)
        Next
        Total.Text = ValorSubTotal.ToString("C2")
    End Sub

    Private Sub btnAddReg_Click(sender As Object, e As EventArgs) Handles btnAddReg.Click
        If Me.Folio.Text Is Nothing Or IsDBNull(Me.Folio.Text) Or Me.Folio.Text = "" Then
            MsgBox("Atención!, No Existe NO. DE INVOICE/REMISION, debe capturar un Cliente.", MsgBoxStyle.Critical, "Mensaje del Sistema")
            Exit Sub
        End If

        If Me.Descripcion.Text Is Nothing Or IsDBNull(Me.Descripcion.Text) Or Me.Descripcion.Text = "" Then
            MsgBox("Atención!, debe capturar DESCRIPCION del Producto o Servicio.", MsgBoxStyle.Critical, "Mensaje del Sistema")
            Exit Sub
        End If
        If Me.Cantidad.Text Is Nothing Or IsDBNull(Me.Cantidad.Text) Or Me.Cantidad.Text = "" Then
            MsgBox("Atención!, debe capturar CANTIDAD del Producto o Servicio.", MsgBoxStyle.Critical, "Mensaje del Sistema")
            Exit Sub
        End If
        If Me.Precio.Text Is Nothing Or IsDBNull(Me.Precio.Text) Or Me.Precio.Text = "" Then
            MsgBox("Atención!, debe capturar PRECIO del Producto o Servicio.", MsgBoxStyle.Critical, "Mensaje del Sistema")
            Exit Sub
        End If

        If Me.Pedimento.Text Is Nothing Or IsDBNull(Me.Pedimento.Text) Or Me.Pedimento.Text = "" Then
            Pedimento.Text = ""
        End If
        If Me.Caja.Text Is Nothing Or IsDBNull(Me.Caja.Text) Or Me.Caja.Text = "" Then
            Caja.Text = ""
        End If
        If Me.Invo.Text Is Nothing Or IsDBNull(Me.Invo.Text) Or Me.Invo.Text = "" Then
            Invo.Text = ""
        End If
        If Me.FecInvo.Text Is Nothing Or IsDBNull(Me.FecInvo.Text) Or Me.FecInvo.Text = "" Then
            FecInvo.Text = ""
        End If

        GuardaDetalle()
        TotalizaInvoice()
        LimpiaDetalle()
    End Sub
    Sub GuardaDetalle()
        Dim sql As String = ""
        If EditoDetalle = False Then
            sql = "INSERT INTO InvoicesDet (IdReg, Folio, Linea, Descripcion, Cantidad, Precio, Importe, Pedimento, Caja, Invo, FecInvo) VALUES (@IdReg, @Folio, " &
                "@Linea, @Descripcion, @Cantidad, @Precio, @Importe, @Pedimento, @Caja, @Invo, @FecInvo)"
        ElseIf EditoDetalle = True Then
            sql = "UPDATE InvoicesDet SET IdReg=@IdReg, Folio=@Folio, Linea=@Linea, Descripcion=@Descripcion, Cantidad=@Cantidad, Precio=@Precio, Importe=@Importe, " &
            "Pedimento=@Pedimento, Caja=@Caja, Invo=@Invo, FecInvo=@FecInvo WHERE IdReg =" & Id.Text & " AND Linea=" & Linea.Text
        End If
        Try
            Dim cn As New SqlConnection(GlobalVariables.cstring)
            Dim cmd As New SqlCommand(sql, cn)
            cn.Open()
            cmd.Parameters.AddWithValue("@IdReg", Me.Id.Text)
            cmd.Parameters.AddWithValue("@Folio", Me.Folio.Text)
            cmd.Parameters.AddWithValue("@Linea", Me.Linea.Text)
            cmd.Parameters.AddWithValue("@Descripcion", Me.Descripcion.Text)
            cmd.Parameters.AddWithValue("@Cantidad", CDbl(Me.Cantidad.Text))
            cmd.Parameters.AddWithValue("@Precio", CDbl(Me.Precio.Text))
            cmd.Parameters.AddWithValue("@Importe", CDbl(Me.Importe.Text))
            cmd.Parameters.AddWithValue("@Pedimento", Me.Pedimento.Text)
            cmd.Parameters.AddWithValue("@Caja", Me.Caja.Text)
            cmd.Parameters.AddWithValue("@Invo", Me.Invo.Text)
            cmd.Parameters.AddWithValue("@FecInvo", Me.FecInvo.Text)
            cmd.ExecuteNonQuery()
            cn.Close()
            cmd = Nothing
            CargarDGV()
            EditoDetalle = False
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles btnGrabar.Click
        Dim ExistLineas As Integer = DCount("IdReg", "InvoicesDet", "Folio='" & Me.Folio.Text & "'")
        If ExistLineas <= 0 Then
            MsgBox("Atención!, No existen LINEAS CAPTURADAS. Proceda a agregar LINEAS o CANCELAR este registro.", MsgBoxStyle.Critical, "Mensaje del Sistema")
            GlobalVariables.EditoInvoice = True
            Exit Sub
        End If

        If Me.Moneda.Text Is Nothing Or IsDBNull(Me.Moneda.Text) Or Me.Moneda.Text = "" Then
            MsgBox("Atención!, debe capturar MONEDA de Compra.", MsgBoxStyle.Critical, "Mensaje del Sistema")
            Exit Sub
        End If
        If Me.Total.Text Is Nothing Or IsDBNull(Me.Total.Text) Or Me.Total.Text = "" Then
            MsgBox("Atención!, esta Invoce/Remision no ha sido totalizada.", MsgBoxStyle.Critical, "Mensaje del Sistema")
            Exit Sub
        End If
        If Me.Obs.Text Is Nothing Or IsDBNull(Me.Obs.Text) Or Me.Obs.Text = "" Then
            Obs.Text = ""
        End If

        If Moneda.Text = "Dollar USD" Then
            CantLetra = Num2TextDolarEsp(CDbl(Total.Text))
        ElseIf Moneda.Text = "Pesos MXN" Then
            CantLetra = Num2TextD(CDbl(Total.Text))
        End If

        varMensaje = "Guardar"

        GuardarRegistro()
        GlobalVariables.EditoInvoice = False
        LimpiaDetalle()
        BtnPagar.Enabled = True
        btnImprimir.Enabled = True
        btnMail.Enabled = True
    End Sub
    Sub GuardarRegistro()
        Me.Capturo.Text = GlobalVariables.VarUsuario
        Dim sql As String = ""

        sql = "UPDATE Invoices SET Capturo=@Capturo, Consecutivo=@Consecutivo, Folio=@Folio, TipoReg=@TipoReg, Fecha=@Fecha, FechaVenc=@FechaVenc, Cliente=@Cliente, Direccion=@Direccion, Estatus=@Estatus, " &
                "Moneda=@Moneda, Total=@Total, Obs=@Obs, TotalLetra=@TotalLetra WHERE id =" & Id.Text
        Try
            Dim cn As New SqlConnection(GlobalVariables.cstring)
            Dim cmd As New SqlCommand(sql, cn)
            cn.Open()
            cmd.Parameters.AddWithValue("@Capturo", Capturo.Text)
            cmd.Parameters.AddWithValue("@Consecutivo", CInt(Consecutivo.Text))
            cmd.Parameters.AddWithValue("@Folio", Me.Folio.Text)
            cmd.Parameters.AddWithValue("@TipoReg", Me.TipoReg.Text)
            cmd.Parameters.AddWithValue("@Fecha", Me.Fecha.Value)
            cmd.Parameters.AddWithValue("@FechaVenc", Me.FechaVenc.Value)
            cmd.Parameters.AddWithValue("@Cliente", Me.Cliente.Text)
            cmd.Parameters.AddWithValue("@Direccion", Me.Direccion.Text)
            cmd.Parameters.AddWithValue("@Estatus", Me.Estatus.Text)
            cmd.Parameters.AddWithValue("@Moneda", Me.Moneda.Text)
            cmd.Parameters.AddWithValue("@Total", CDbl(Me.Total.Text))
            cmd.Parameters.AddWithValue("@Obs", Me.Obs.Text)
            cmd.Parameters.AddWithValue("@TotalLetra", CantLetra)
            cmd.ExecuteNonQuery()
            cn.Close()
            cmd = Nothing

            CargarDGV()
            If varMensaje = "Guardar" Then
                MsgBox("Atención!, Registro guardado con éxito.", MsgBoxStyle.Information, "Mensaje del Sistema")
            ElseIf varMensaje = "Cancelada" Then
                MsgBox("Operación cancelada con éxito.", MsgBoxStyle.Information, "Mensaje del Sistema")
            End If

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
    Private Sub btnCancelar_Click(sender As Object, e As EventArgs) Handles btnCancelar.Click
        If Me.Folio.Text Is Nothing Or IsDBNull(Me.Folio.Text) Or Me.Folio.Text = "" Then
            LimpiarCampos(Me)
            LimpiaDetalle()
            VaciarGrid()
            btnGrabar.Enabled = False
            btnAddReg.Enabled = False
            btnDelReg.Enabled = False
            BtnPagar.Enabled = False
            btnImprimir.Enabled = False
            btnMail.Enabled = False
            GlobalVariables.EditoInvoice = False
            LockCampos(Me)
            Exit Sub
        Else
            If Estatus.Text = "PAGADA" Or Estatus.Text = "CANCELADA" Then
                MsgBox("Atención!, Imposible cancelar esta Invoice/Remisión... tiene estatus de PAGADA/CANCELADA.", MsgBoxStyle.Information, "Mensaje del Sistema")
            Else
                If MsgBox("Esta seguro(a) de Eliminar el registro actual?", vbYesNo, "Mensaje del Sistema") = vbYes Then
                    QryInsUpDel("DELETE FROM  InvoicesDet WHERE IdReg =" & Me.Id.Text & "")
                    QryInsUpDel("DELETE FROM  Invoices WHERE Id =" & Me.Id.Text & "")
                    GlobalVariables.EditoInvoice = False
                    LimpiarCampos(Me)
                    LimpiaDetalle()
                    VaciarGrid()
                    btnGrabar.Enabled = False
                    btnAddReg.Enabled = False
                    btnDelReg.Enabled = False
                    BtnPagar.Enabled = False
                    btnImprimir.Enabled = False
                    btnMail.Enabled = False
                    MsgBox("Atención!, Registro Eliminado con éxito!", vbInformation, "Mensaje del Sistema")
                    LockCampos(Me)
                Else
                    MsgBox("Eliminación abortada!", vbInformation, "Mensaje del Sistema")
                End If
            End If
        End If
    End Sub

    Private Sub btnImprimir_Click(sender As Object, e As EventArgs) Handles btnImprimir.Click
        If Folio.Text Is Nothing Or IsDBNull(Folio.Text) Or Folio.Text = "" Then
            Exit Sub
        Else
            GlobalVariables.VarIDReg = Id.Text

            If (Application.OpenForms("FrmRptInvoice") Is Nothing) Then
                FrmRptInvoice.lblEncabezado.Text = "Reporte: " & Folio.Text
                FrmRptInvoice.Text = "Reporte: " & Folio.Text
                FrmRptInvoice.ShowDialog()
            Else
                FrmRptInvoice.Close()
                FrmRptInvoice.lblEncabezado.Text = "Reporte: " & Folio.Text
                FrmRptInvoice.Text = "Reporte: " & Folio.Text
                FrmRptInvoice.ShowDialog()
            End If
        End If
    End Sub
    Private Sub Cantidad_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Cantidad.KeyPress
        NumConFrac(Cantidad, e)
    End Sub

    Private Sub Precio_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Precio.KeyPress
        NumConFrac(Precio, e)
    End Sub

    Private Sub Pedimento_KeyDown(sender As Object, e As KeyEventArgs) Handles Pedimento.KeyDown
        If e.KeyCode = Keys.Enter Then
            Caja.Focus()
        End If
    End Sub

    Private Sub Caja_KeyDown(sender As Object, e As KeyEventArgs) Handles Caja.KeyDown
        If e.KeyCode = Keys.Enter Then
            Invo.Focus()
        End If
    End Sub

    Private Sub Invo_KeyDown(sender As Object, e As KeyEventArgs) Handles Invo.KeyDown
        If e.KeyCode = Keys.Enter Then
            FecInvo.Focus()
        End If
    End Sub

    Private Sub FecInvo_KeyDown(sender As Object, e As KeyEventArgs) Handles FecInvo.KeyDown
        If e.KeyCode = Keys.Enter Then
            Precio.Focus()
        End If
    End Sub

    Private Sub BtnPagar_Click(sender As Object, e As EventArgs) Handles BtnPagar.Click
        AbrirFormDatos()
    End Sub
    Sub AbrirFormDatos()
        GlobalVariables.VarIDReg = Me.Id.Text

        FrmAppPago.Folio.Text = Me.Folio.Text
        FrmAppPago.Cliente.Text = Me.Cliente.Text
        FrmAppPago.Total.Text = Total.Text

        FrmAppPago.FechaPag.Format = DateTimePickerFormat.Custom
        FrmAppPago.FechaPag.CustomFormat = " "
        FrmAppPago.Pagado.Checked = False
        FrmAppPago.RefPago.Text = ""
        GlobalVariables.VarOrigenPago = True

        FrmAppPago.ShowDialog()
    End Sub

    Private Sub FechaVenc_MouseDown(sender As Object, e As MouseEventArgs) Handles FechaVenc.MouseDown
        Select Case e.Button
            Case Windows.Forms.MouseButtons.Left
                FechaVenc.Format = DateTimePickerFormat.Short
                FechaVenc.Value = Date.Today
            Case Windows.Forms.MouseButtons.Right
                FechaVenc.Format = DateTimePickerFormat.Custom
                FechaVenc.CustomFormat = " "
        End Select
    End Sub

    Private Sub btnMail_Click(sender As Object, e As EventArgs) Handles btnMail.Click
        FrmRptInvoice.Show()
        FrmRptInvoice.Hide()
        FrmRptInvoice.CreaPDF()
        FrmRptInvoice.Close()

        frmMail.Show()
        frmMail.Hide()

        frmMail.Para.Text = ""
        frmMail.Asunto.Text = ""
        frmMail.Adjunto1.Text = ""
        frmMail.Adjunto2.Text = ""
        frmMail.Mensaje.Text = ""

        frmMail.Para.Text = DLookup("Email1", "Clientes", "RazonSoc='" & Me.Cliente.Text & "'")

        Dim NombreProv As String = Cliente.Text
        Dim ParteNombre() As String = NombreProv.Split(" ")

        frmMail.Asunto.Text = Folio.Text & ParteNombre(0)
        frmMail.Adjunto1.Text = "C:\IRGodam\PDFS\" & Folio.Text & ParteNombre(0) & ".pdf"
        frmMail.Adjunto2.Text = "C:\IRGodam\PDFS\nodata.txt"

        frmMail.Mensaje.Text = "Estimado cliente a continuación encontrara anexa " & TipoReg.Text & " correspondinete a nuestros servicios y/o productos. " & vbNewLine & vbNewLine &
                         "Agradecemos de antemano su atención y preferencia, quedamos muy atentos a sus apreciables comentarios." & vbNewLine & vbNewLine &
                         "Muchas gracias y saludos cordiales. " & vbNewLine & vbNewLine &
                         "Depto. de Facturación - GODAMEXPRESS " & vbNewLine & vbNewLine &
                         "AutoMail - ProcSmart - Invoices & Remisiones 2.0"

        frmMail.ShowDialog()
    End Sub
End Class