Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE

Friend Class frmDesFaturamento
	Inherits System.Windows.Forms.Form
    'Private ifrmBarraProgresso As frmBarraProgresso

    Dim dt, dt2, dt3, dt4 As DataTable
    Private objAtualizaBancoDados As New entidadeAtualizaBancoDados
    Private repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

    Private objExecAtualizaBancoDados As New entidadeAtualizaBancoDados
    Private repositorioExecAtualizaBancoDados As New repositorioAtualizaBancoDados

    Private Sub cmdBuscaIndi_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdBuscaIndi.Click
        Dim lstrZon As String
        Dim lstrLiv As String
        Dim lstrCon As String
        Dim llngUid As Integer
        Dim lstrTar As String
        Dim lstrGru As String
        Dim lstrNom As String
        Dim ldtePag As Date
        Dim ldblNNf As Double
        Dim llngMAn As Integer
        Dim lblnCor As Boolean
        Dim lstrSql As String
        Dim lstrPag As String

        Try

            Me.txtZona.Text = ""
            Me.txtLivro.Text = ""
            Me.txtConta.Text = ""
            Me.txtNome.Text = ""
            Me.txtTa.Text = ""

            If IsNumeric(Me.txtNumNf.Text) Then
                ldblNNf = CDbl(Me.txtNumNf.Text)
                llngMAn = CInt(VB.Right(Me.txtMesAno.Text, 4) & VB.Left(Me.txtMesAno.Text, 2))
                llngUid = 0
                lstrTar = ""
                lstrGru = ""
                lstrZon = ""
                lstrLiv = ""
                lstrCon = ""
                ldtePag = CDate("01/01/1951")
                lstrSql = ""
                lstrSql = lstrSql & "SELECT `nf`.`unid_id`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`ta`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`grupo`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`zona`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`livro`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`conta`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`datapag`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`flgst`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`mesano_ref`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`mesano`, " & vbCrLf
                lstrSql = lstrSql & "       `nf`.`numnf` " & vbCrLf
                lstrSql = lstrSql & "  FROM `nf` " & vbCrLf
                lstrSql = lstrSql & " WHERE `nf`.`mesano_ref` = " & llngMAn & vbCrLf
                lstrSql = lstrSql & "   AND `nf`.`numnf`      = " & ldblNNf
                lstrSql = lstrSql & " LIMIT 0, 1"
                objAtualizaBancoDados.QUERY_NAME = lstrSql
                dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                '  With lrstAux
                If dt.Rows.Count > 0 Then
                    For Each row As DataRow In dt.Rows
                        llngUid = CInt(IIf(IsDBNull(row.Item("unid_id")), 0, row.Item("unid_id")))
                        lstrTar = Mid(Trim(IIf(IsDBNull(row.Item("ta")), "01B1", row.Item("ta"))), 3, 2)
                        lstrGru = Trim(IIf(IsDBNull(row.Item("grupo")), "B", row.Item("grupo")))
                        lstrZon = VB6.Format(Trim(IIf(IsDBNull(row.Item("zona")), "0", row.Item("zona"))), "000")
                        lstrLiv = VB6.Format(Trim(IIf(IsDBNull(row.Item("livro")), "0", row.Item("livro"))), "00")
                        lstrCon = VB6.Format(Trim(IIf(IsDBNull(row.Item("conta")), "0", row.Item("conta"))), "000000")
                        lstrPag = CStr(VB6.Format(Trim(IIf(IsDBNull(row.Item("datapag")), "0000-00-00", row.Item("datapag"))), "0000-00-00"))
                        'ldtePag = CDate(IIf(IsDBNull(row.Item("datapag")) Or row.Item("datapag") = "00/00/0000", "01/01/1951", row.Item("datapag")))
                    Next
                End If

                If Len(Trim(lstrGru)) > 0 Then
                    lstrSql = ""
                    lstrSql = lstrSql & "SELECT `nome` "
                    'lstrSql = lstrSql & "  FROM `unid" & LCase(lstrGru) & "` "
                    lstrSql = lstrSql & "  FROM uc_faturamento "
                    lstrSql = lstrSql & " WHERE `id` = " & llngUid
                    objAtualizaBancoDados.QUERY_NAME = lstrSql
                    dt2 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                    If dt2.Rows.Count > 0 Then
                        For Each row2 As DataRow In dt2.Rows
                            lstrNom = IIf(IsDBNull(row2.Item("nome")), "", row2.Item("nome"))
                        Next
                    Else
                        lstrNom = ""
                    End If

                Else
                    lstrNom = ""
                End If

                If llngUid = 0 Then
                    Call MsgBox("Esta fatura não existe na arrecadação!", MsgBoxStyle.Information, gstrTituloMensagem)
                    Exit Sub
                End If
                Me.txtZona.Text = lstrZon
                Me.txtLivro.Text = lstrLiv
                Me.txtConta.Text = lstrCon
                Me.txtNome.Text = lstrNom
                Me.txtTa.Text = lstrTar
                'If ldtePag <> CDate("01/01/1951") Then
                If lstrPag <> "0000-00-00" Then
                    Call MsgBox("Esta Fatura já foi paga, não pode ser faturada!", MsgBoxStyle.Information, gstrTituloMensagem)
                    Me.cmdProcessar.Enabled = False
                Else
                    lblnCor = VerExisteCorte()

                    If Not lblnCor Then
                        Call MsgBox("Esta fatura já foi Cortada/Paga e não pode ser processada!", MsgBoxStyle.Information, gstrTituloMensagem)
                        Me.cmdProcessar.Enabled = False
                    Else
                        Me.cmdProcessar.Enabled = True
                    End If
                End If
                ' End With
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdBuscaIndi_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub
    Private Sub cmdBuscaRota_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdBuscaRota.Click
        Call CarregaRotas()
    End Sub

    Private Sub cmdProcessar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdProcessar.Click
        Dim lstrSql As String
        Dim lstrAux As String
        Dim lintIdx As Short
        Dim ldblNNf As Double
        Dim llngMAn As Integer
        Dim lblnAux As Boolean
        'Dim lrstAux As ADODB.Recordset
        'lrstAux = New ADODB.Recordset

        Try
            lblnAux = False
            If Me.opbIndividual.Checked Then
                If IsNumeric(Me.txtNumNf.Text) Then
                    ldblNNf = CDbl(Me.txtNumNf.Text)
                    llngMAn = CInt(VB.Right(Me.txtMesAno.Text, 4) & VB.Left(Me.txtMesAno.Text, 2))
                    If TransfereFatura(ldblNNf, llngMAn) Then
                        Call MsgBox("Fatura " & Me.txtNumNf.Text & " do mês e ano " & Me.txtMesAno.Text & " transferida para faturamento com sucesso!", MsgBoxStyle.Information, gstrTituloMensagem)
                    End If
                Else
                    Call MsgBox("Por favor, informar um númeração de fatura válida!", MsgBoxStyle.Information, gstrTituloMensagem)
                    Call Me.txtNumNf.Focus()
                End If
            ElseIf Me.opbRota.Checked Then
                llngMAn = CInt(VB6.Format(Me.dtpMesAno.Value, "yyyymm"))
                lstrAux = ""
                With Me.lsvRotas
                    If .Items.Count > 0 Then
                        If .Items.Item(1).Checked = False Then
                            For lintIdx = 2 To .Items.Count - 1
                                If .Items.Item(lintIdx).Checked = True Then
                                    lstrAux = lstrAux & "'" & .Items.Item(lintIdx).Text & "',"
                                End If
                            Next lintIdx
                        End If
                    End If
                End With
                If Len(Trim(lstrAux)) > 0 Then
                    lstrAux = " AND MID(`nf`.`rota`, 1, 4) IN ( " & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
                End If
                'Call ifrmBarraProgresso.SetaBarraProgresso(Me)
                'ifrmBarraProgresso.Show()
                'ifrmBarraProgresso.lblInfo.Text = " Aguarde buscando as faturas!"
                'Call ifrmBarraProgresso.lblInfo.Refresh()
                lstrSql = ""
                lstrSql = lstrSql & "SELECT `nf`.`numnf`,`nf`.`anomes_fat`,`nf`.`mesano` "
                lstrSql = lstrSql & "  FROM `nf` "
                lstrSql = lstrSql & " WHERE `nf`.`anomes_fat` = " & VB6.Format(Me.dtpMesAno.Value, "yyyymm")
                lstrSql = lstrSql & "   AND `nf`.`flgst` = '' "
                lstrSql = lstrSql & lstrAux
                If Me.chkSomenteMicroGeracao.CheckState = System.Windows.Forms.CheckState.Checked Then
                    lstrSql = lstrSql & "   AND (`nf`.`micro_geracao` = 1 OR `nf`.`micro_geracao_distribuida` = 1) "
                End If
                If Me.chkSomenteBaixaRenda.CheckState = System.Windows.Forms.CheckState.Checked Then
                    lstrSql = lstrSql & "   AND (`nf`.`codclas` BETWEEN '9102' AND '9106') "
                End If
                ' Call Conectar(lstrSql, lrstAux)
                objAtualizaBancoDados.QUERY_NAME = lstrSql
                dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                If dt.Rows.Count > 0 Then
                    'Call BarraProgresso((ifrmBarraProgresso.ProgressBar), (ifrmBarraProgresso.lblPerc), (ifrmBarraProgresso.lblInfo), 0, .RecordCount)
                    For Each row As DataRow In dt.Rows
                        ldblNNf = CDbl(IIf(IsDBNull(row.Item("numnf")), 0, row.Item("numnf")))
                        lblnAux = TransfereFatura(ldblNNf, llngMAn)

                        If lblnAux = False Then
                            'Exit For
                        End If

                        'Call .MoveNext()
                        'Call BarraProgresso((ifrmBarraProgresso.ProgressBar), (ifrmBarraProgresso.lblPerc), (ifrmBarraProgresso.lblInfo), 1)
                    Next
                    ' Call ifrmBarraProgresso.Close()
                Else
                    Call MsgBox("Não foi encontrado nenhuma fatura para transferência, favor mude os filtros!", MsgBoxStyle.Information, gstrTituloMensagem)
                    Exit Sub
                End If


                Call MsgBox("Transferência para em faturamento realizada com sucesso!", MsgBoxStyle.Information, gstrTituloMensagem)

            ElseIf Me.opbAgrupa.Checked Then
                llngMAn = CInt(VB6.Format(Me.dtpMesAno.Value, "yyyymm"))
                lstrAux = ""
                lstrAux = MontaFiltroAgrupa()
                'Call ifrmBarraProgresso.SetaBarraProgresso(Me)
                'ifrmBarraProgresso.Show()
                'ifrmBarraProgresso.lblInfo.Text = " Aguarde buscando as faturas!"
                'Call ifrmBarraProgresso.lblInfo.Refresh()
                lstrSql = ""
                lstrSql = lstrSql & "SELECT `nf`.`numnf`,`nf`.`anomes_fat`,`nf`.`mesano` "
                lstrSql = lstrSql & "  FROM `nf` "
                lstrSql = lstrSql & " WHERE `nf`.`anomes_fat` = " & VB6.Format(Me.dtpMesAnoAgru.Value, "yyyymm")
                lstrSql = lstrSql & "   AND `nf`.`flgst` = '' "
                lstrSql = lstrSql & lstrAux
                objAtualizaBancoDados.QUERY_NAME = lstrSql
                dt2 = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

                If dt2.Rows.Count > 0 Then
                    ' Call BarraProgresso((ifrmBarraProgresso.ProgressBar), (ifrmBarraProgresso.lblPerc), (ifrmBarraProgresso.lblInfo), 0, .RecordCount)
                    For Each row2 As DataRow In dt2.Rows
                        ldblNNf = CDbl(IIf(IsDBNull(row2.Item("numnf")), 0, row2.Item("numnf")))
                        lblnAux = TransfereFatura(ldblNNf, llngMAn)
                        If lblnAux = False Then
                            Exit For
                        End If
                        'Call .MoveNext()
                        ' Call BarraProgresso((ifrmBarraProgresso.ProgressBar), (ifrmBarraProgresso.lblPerc), (ifrmBarraProgresso.lblInfo), 1)
                    Next
                    ' Call ifrmBarraProgresso.Close()
                Else
                    Call MsgBox("Não foi encontrado nenhuma fatura para transferência, favor mude os filtros!", MsgBoxStyle.Information, gstrTituloMensagem)
                End If


                If lblnAux Then
                    Call MsgBox("Transferência para em faturamento realizada com sucesso!", MsgBoxStyle.Information, gstrTituloMensagem)
                End If
            End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdProcessar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Function TransfereFatura(ByVal adblNumNf As Double, ByVal alngMesAno As Integer) As Boolean
        Dim lblnAux As Boolean
        Dim lstrSql As String

        lblnAux = False

        Try

            If VerExisteFatura("nftransicao", adblNumNf, alngMesAno) Then
                If VerExisteFatura("nf", adblNumNf, alngMesAno) Then
                    lstrSql = "DELETE FROM nftransicao WHERE mesano_ref = " & alngMesAno & " AND numnf = " & adblNumNf
                    objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

                    lstrSql = "INSERT INTO nftransicao (SELECT * FROM nf WHERE mesano_ref = " & alngMesAno & " AND numnf = " & adblNumNf & ")"
                    objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

                    lstrSql = "UPDATE nftransicao SET site = 0 where mesano_ref = " & alngMesAno & " AND numnf = " & adblNumNf & ""
                    objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

                    lstrSql = "DELETE FROM nf WHERE mesano_ref = " & alngMesAno & " AND numnf = " & adblNumNf
                    objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

                    If gstrEmpresa_Sigla = "CERCI" Then
                        lstrSql = "DELETE FROM site_cerci.nss_faturasnet WHERE id_ano_mes = " & alngMesAno & " AND id_numero_fiscal = " & adblNumNf
                        objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                        repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)
                    ElseIf gstrEmpresa_Sigla = "CERES" Then
                        lstrSql = "DELETE FROM site_ceres.nss_faturasnet WHERE id_ano_mes = " & alngMesAno & " AND id_numero_fiscal = " & adblNumNf
                        objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                        repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)
                    End If

                    lblnAux = True
                End If
            Else
                If VerExisteFatura("nf", adblNumNf, alngMesAno) Then
                    lstrSql = "INSERT INTO nftransicao (SELECT * FROM nf WHERE mesano_ref = " & alngMesAno & " AND numnf = " & adblNumNf & ")"
                    objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

                    lstrSql = "UPDATE nftransicao SET site = 0 where mesano_ref = " & alngMesAno & " AND numnf = " & adblNumNf & ""
                    objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

                    lstrSql = "DELETE FROM nf WHERE mesano_ref = " & alngMesAno & " AND numnf = " & adblNumNf
                    objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

                    If gstrEmpresa_Sigla = "CERCI" Then
                        lstrSql = "DELETE FROM site_cerci.nss_faturasnet WHERE id_ano_mes = " & alngMesAno & " AND id_numero_fiscal = " & adblNumNf
                        objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                        repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)
                    ElseIf gstrEmpresa_Sigla = "CERES" Then
                        lstrSql = "DELETE FROM site_ceres.nss_faturasnet WHERE id_ano_mes = " & alngMesAno & " AND id_numero_fiscal = " & adblNumNf
                        objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                        repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)
                    End If

                    lblnAux = True
                End If
            End If

            TransfereFatura = lblnAux

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: TransfereFatura" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            TransfereFatura = lblnAux
            Exit Function
        End Try

    End Function

    Private Function VerExisteFatura(ByVal astrTabela As String, ByVal adblNumNf As Double, ByVal alngMesAno As Integer) As Boolean
        Dim lblnAux As Boolean
        Dim lstrSql As String

        Try

            lblnAux = False
            lstrSql = ""
            lstrSql = lstrSql & "SELECT * "
            lstrSql = lstrSql & "  FROM `" & astrTabela & "` "
            lstrSql = lstrSql & " WHERE `numnf`      = " & adblNumNf
            lstrSql = lstrSql & "   AND `mesano_ref` = " & alngMesAno
            lstrSql = lstrSql & "   AND `flgst` = '' "
            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            If dt.Rows.Count > 0 Then
                lblnAux = True
            End If

            VerExisteFatura = lblnAux

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: VerExisteFatura" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function


    Private Sub frmDesFaturamento_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try
            If KeyAscii = System.Windows.Forms.Keys.Escape Then
                Call cmdFechar_Click(cmdFechar, New System.EventArgs())
            ElseIf KeyAscii = System.Windows.Forms.Keys.Return Then
                TabEnter(KeyAscii, eventArgs)
            End If
            eventArgs.KeyChar = Chr(KeyAscii)
            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmDesFaturamento_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub frmDesFaturamento_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
        Dim lstrMesAno As String

        Try
            ' Call CenterForm(Me)
            lstrMesAno = Trim(GetConfig("mes.ano.faturamento"))
            If lstrMesAno = "" Or lstrMesAno = "-1" Then
                Call MsgBox("Não foi definido o mês e ano de faturamento!", MsgBoxStyle.Information, gstrTituloMensagem)
                Call Me.Close()
            End If
            Me.txtMesAno.Text = lstrMesAno
            Me.dtpMesAno.Value = Date.Now()
            Me.dtpMesAnoAgru.Value = Me.dtpMesAno.Value
            Call LigDesCampos(Me.opbIndividual.Checked, Me.opbRota.Checked, Me.opbAgrupa.Checked)
            Me.cmdProcessar.Enabled = False
            'ifrmBarraProgresso = New frmBarraProgresso
            Call CarregaAgrupamento()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmDesFaturamento_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub cmdFechar_Click(sender As Object, e As EventArgs) Handles cmdFechar.Click
        Call Me.Close()
    End Sub

    'Private Sub lsvRotas_ItemCheck(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.ItemCheckEventArgs) Handles lsvRotas.ItemCheck
    '    Dim aListItem As System.Windows.Forms.ListViewItem = lsvRotas.Items(eventArgs.Index)
    '    Dim lintIdx As Short

    '    Try
    '        With Me.lsvRotas
    '            If aListItem.Text = "Todas as rotas" Then
    '                If .Items.Item(1).Checked = True Then
    '                    For lintIdx = 1 To .Items.Count - 1
    '                        .Items.Item(lintIdx).Checked = True
    '                    Next lintIdx
    '                ElseIf .Items.Item(1).Checked = False Then
    '                    For lintIdx = 1 To .Items.Count - 1
    '                        .Items.Item(lintIdx).Checked = False
    '                    Next lintIdx
    '                End If
    '            Else
    '                If aListItem.Checked = False Then
    '                    .Items.Item(1).Checked = False
    '                End If
    '            End If
    '        End With

    '    Catch ex As Exception
    '        MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lsvRotas_ItemCheck" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
    '        Exit Sub
    '    End Try

    'End Sub

    'UPGRADE_WARNING: Event opbAgrupa.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub opbAgrupa_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbAgrupa.CheckedChanged
        If eventSender.Checked Then
            Call LigDesCampos(Me.opbIndividual.Checked, Me.opbRota.Checked, Me.opbAgrupa.Checked)
        End If
    End Sub

    ''	'UPGRADE_WARNING: Event opbIndividual.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub opbIndividual_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbIndividual.CheckedChanged
        If eventSender.Checked Then
            Call LigDesCampos(Me.opbIndividual.Checked, Me.opbRota.Checked, Me.opbAgrupa.Checked)
        End If
    End Sub

    ''	'UPGRADE_WARNING: Event opbRota.CheckedChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
    Private Sub opbRota_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbRota.CheckedChanged
        If eventSender.Checked Then
            Call LigDesCampos(Me.opbIndividual.Checked, Me.opbRota.Checked, Me.opbAgrupa.Checked)
        End If
    End Sub

    Private Sub CarregaRotas()
        Dim lstrRota As String
        Dim lstrGrupo As String
        Dim lstrSql As String

        Try
            ' ----- Monta as colunas na ListView de rotas
            With Me.lsvRotas
                Call .Items.Clear()
                Call .Columns.Clear()
                If .Columns.Count <= 1 Then
                    Call .Columns.Add("", "Rota", CInt(VB6.TwipsToPixelsX(1800)))
                    Call .Columns.Add("Grupo", CInt(VB6.TwipsToPixelsX(650)), System.Windows.Forms.HorizontalAlignment.Center)
                End If
                'Call .Items.Add("Todas as rotas")

                'Call .Items.Item(.Items.Count - 1).SubItems.Add("T")
            End With
            'Call ifrmBarraProgresso.SetaBarraProgresso(Me)
            'ifrmBarraProgresso.Show()
            'ifrmBarraProgresso.lblInfo.Text = " Aguarde buscando as rotas!"
            'Call ifrmBarraProgresso.lblInfo.Refresh()
            ' ----- Busca as rotas
            lstrSql = ""
            lstrSql = lstrSql & "SELECT DISTINCT  cast(LEFT(`nf`.`rota`,4) as decimal) AS `rotaaux`, `grupo` "
            lstrSql = lstrSql & "  FROM `" & gstrDataBase & "`.`nf` USE INDEX(`keyrota`) "
            lstrSql = lstrSql & " WHERE `nf`.`mesano_ref` = " & VB6.Format(Me.dtpMesAno.Value, "yyyymm")
            lstrSql = lstrSql & "   AND `nf`.`flgst` = '' "
            lstrSql = lstrSql & " ORDER BY 2 ASC, 1 ASC"
            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            ' ----- Fim do Busca as rotas
            ' ----- Se Retornou alguma coisa, monta as rotas!
            If dt.Rows.Count > 0 Then
                'Call BarraProgresso((ifrmBarraProgresso.ProgressBar), (ifrmBarraProgresso.lblPerc), (ifrmBarraProgresso.lblInfo), 0, .RecordCount)
                For Each row As DataRow In dt.Rows
                    lstrRota = IIf(IsDBNull(row.Item("rotaaux")), "0", row.Item("rotaaux"))
                    lstrGrupo = IIf(IsDBNull(row.Item("grupo")), "B", row.Item("grupo"))
                    With Me.lsvRotas
                        Call .Items.Add(lstrRota)
                        Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrGrupo)
                    End With
                    ' Call BarraProgresso((ifrmBarraProgresso.ProgressBar), (ifrmBarraProgresso.lblPerc), (ifrmBarraProgresso.lblInfo), 1)
                Next
                'Call ifrmBarraProgresso.Close()
                Me.cmdProcessar.Enabled = True
            Else
                Call MsgBox("Não existem faturas na arrecadação para a(s) rota(s) selecionada(s)!", MsgBoxStyle.Information, gstrTituloMensagem)
                Me.cmdProcessar.Enabled = False
            End If

            System.Windows.Forms.Application.DoEvents()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CarregaRotas" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub LigDesCampos(ByVal ablnModoIndi As Boolean, ByVal ablnModoRota As Boolean, ByVal ablnModoAgru As Boolean)
        Try
            Me._fmeAux_0.Enabled = ablnModoIndi
            Me.txtNumNf.Enabled = ablnModoIndi
            Me.cmdBuscaIndi.Enabled = ablnModoIndi
            Me._fmeAux_1.Enabled = ablnModoRota
            Me.dtpMesAno.Enabled = ablnModoRota
            Me.lsvRotas.Enabled = ablnModoRota
            Me.cmdBuscaRota.Enabled = ablnModoRota
            Me.txtNumNf.BackColor = System.Drawing.ColorTranslator.FromOle(IIf(ablnModoIndi, System.Drawing.ColorTranslator.ToOle(System.Drawing.SystemColors.Window), System.Drawing.ColorTranslator.ToOle(System.Drawing.SystemColors.Control)))
            Me.lsvRotas.BackColor = System.Drawing.ColorTranslator.FromOle(IIf(ablnModoRota, System.Drawing.ColorTranslator.ToOle(System.Drawing.SystemColors.Window), System.Drawing.ColorTranslator.ToOle(System.Drawing.SystemColors.Control)))
            Me.chkSomenteMicroGeracao.Enabled = ablnModoRota
            Me.chkSomenteBaixaRenda.Enabled = ablnModoRota
            Me._fmeAux_2.Enabled = ablnModoAgru
            Me.lsvAgrupa.Enabled = ablnModoAgru
            Me.dtpMesAnoAgru.Enabled = ablnModoAgru

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: LigDesCampos" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub txtNumNf_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtNumNf.KeyPress
        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
        Try
            If KeyAscii <> System.Windows.Forms.Keys.Back And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9) Then
                KeyAscii = 0
            End If
            eventArgs.KeyChar = Chr(KeyAscii)
            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtNumNf_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Function VerExisteCorte() As Boolean
        Dim lblnRet As Boolean
        Dim lstrSql As String
        Dim lstrSit As String

        Try

            lblnRet = True
            lstrSql = ""
            lstrSql = lstrSql & "SELECT * "
            lstrSql = lstrSql & "  FROM concorte "
            lstrSql = lstrSql & " WHERE numnf = " & CDbl(IIf(IsNumeric(Me.txtNumNf.Text), Me.txtNumNf.Text, 0)) & " "
            lstrSql = lstrSql & "   AND mesano = """ & Me.txtMesAno.Text & """ "
            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            If dt.Rows.Count > 0 Then
                For Each row As DataRow In dt.Rows
                    lstrSit = IIf(IsDBNull(row.Item("sit")), "R", row.Item("sit"))
                Next
                If lstrSit = "R" Or lstrSit = "E" Then
                    lstrSql = ""
                    lstrSql = "DELETE FROM concorte WHERE mesano = """ & Me.txtMesAno.Text & """ AND numnf = " & CDbl(IIf(IsNumeric(Me.txtNumNf.Text), Me.txtNumNf.Text, 0)) & " "
                    objExecAtualizaBancoDados.QUERY_NAME = lstrSql
                    repositorioExecAtualizaBancoDados.Execute(objExecAtualizaBancoDados)

                    lblnRet = True
                Else
                    lblnRet = False
                End If
            Else
                lblnRet = True
            End If

            VerExisteCorte = lblnRet

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: VerExisteCorte" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Sub chktodasrotas_CheckedChanged(sender As Object, e As EventArgs) Handles chktodasrotas.CheckedChanged
        Try
            'Dim Item As System.Windows.Forms.ListViewItem = LVRota.Items(EventArgs.Index)
            Dim intConta As Short

            'If Item.Text = "Todas as rotas" Then

            If chktodasrotas.Checked = True Then
                For intConta = 0 To lsvRotas.Items.Count - 1

                    lsvRotas.Items.Item(intConta).Checked = True
                Next

            ElseIf chktodasrotas.Checked = False Then
                For intConta = 0 To lsvRotas.Items.Count - 1

                    lsvRotas.Items.Item(intConta).Checked = False
                Next intConta
            End If
            'Else
            'If Item.Checked = False Then
            '	'	
            '	LVRota.Items.Item(0).Checked = False
            'End If
            'End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chktodas_CheckedChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub lsvAgrupa_ItemCheck(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.ItemCheckEventArgs) Handles lsvAgrupa.ItemCheck
        Dim aItem As System.Windows.Forms.ListViewItem = lsvAgrupa.Items(eventArgs.Index)
        Dim lintIdx As Short
        Try
            With Me.lsvAgrupa
                For lintIdx = 1 To .Items.Count - 1
                    If .Items.Item(lintIdx).Checked Then
                        Me.cmdProcessar.Enabled = True
                        lintIdx = .Items.Count - 1
                    Else
                        Me.cmdProcessar.Enabled = False
                    End If
                Next lintIdx
            End With

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CarregaRotas" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub CarregaAgrupamento()
        Dim lstrCod As String
        Dim lstrDes As String
        Dim lstrSql As String

        Try
            ' ----- Monta as colunas na ListView de rotas
            With Me.lsvAgrupa
                Call .Items.Clear()
                Call .Columns.Clear()
                If .Columns.Count <= 1 Then
                    Call .Columns.Add("", "Agrupa", CInt(VB6.TwipsToPixelsX(4790)))
                    Call .Columns.Add("Código", CInt(VB6.TwipsToPixelsX(700)), System.Windows.Forms.HorizontalAlignment.Right)
                End If
            End With
            ' ----- Busca as rotas
            lstrSql = ""
            lstrSql = lstrSql & "SELECT `codigo`, " & vbCrLf
            lstrSql = lstrSql & "       `descricao`"
            lstrSql = lstrSql & "  FROM `agrupa` " & vbCrLf
            lstrSql = lstrSql & " ORDER BY 1 ASC"
            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)

            ' ----- Insere os dados na ListView de rotas
            If dt.Rows.Count > 0 Then
                For Each row As DataRow In dt.Rows
                    lstrCod = VB6.Format(IIf(IsDBNull(row.Item("codigo")), "0", row.Item("codigo")), "000")
                    lstrDes = Trim(IIf(IsDBNull(row.Item("descricao")), "", row.Item("descricao")))
                    With Me.lsvAgrupa
                        Call .Items.Add(lstrDes)
                        Call .Items.Item(.Items.Count - 1).SubItems.Add(lstrCod)
                    End With
                Next
            End If
            System.Windows.Forms.Application.DoEvents()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CarregaAgrupamento" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Function MontaFiltroAgrupa() As String
        Dim lstrAux As String
        Dim lintIdx As Short

        Try

            lstrAux = ""
            With Me.lsvAgrupa
                For lintIdx = 0 To .Items.Count - 1
                    If .Items.Item(lintIdx).Checked = True Then
                        lstrAux = lstrAux & """" & .Items.Item(lintIdx).SubItems(1).Text & ""","
                    End If
                Next lintIdx
                If Len(Trim(lstrAux)) > 0 Then
                    lstrAux = " (" & VB.Left(lstrAux, Len(lstrAux) - 1) & ") "
                End If
                If Len(Trim(lstrAux)) > 0 Then
                    lstrAux = " AND agrupa IN " & lstrAux & " "
                End If
            End With
            MontaFiltroAgrupa = lstrAux

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: MontaFiltroAgrupa" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function
End Class