Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE
Imports CrystalDecisions.CrystalReports.Engine


Friend Class frmRelOcorrencias
    Inherits System.Windows.Forms.Form

#Region "Propriedades"

    Private Sub frmRelOcorrencias_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load

        Dim objTempOcorrencias As New entidadeTempOcorrencias
        Dim repositorioTempOcorrencias As New repositorioTempOcorrencias

        Try

            lPreencherList()
            Me.lblInfo.Text = String.Empty
            Me.lblInfo.Refresh()
            Me.dtpMesAno.Value = CDate("01/" & GetConfig("mes.ano.faturamento"))
            Me.dtpIni.Value = Me.dtpMesAno.Value
            Me.dtpFim.Value = Me.dtpMesAno.Value

            objTempOcorrencias.NM_USUARIO = vUsuario.LOGIN

            repositorioTempOcorrencias.Execute(objTempOcorrencias)
            lDelete(objTempOcorrencias)

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lsvRotas_Click(sender As Object, e As EventArgs) Handles lsvRotas.Click


        Try

            If lsvRotas.Items.Count > 0 Then

                If lsvRotas.FocusedItem.[Text].ToString() = "Todas as rotas" Then

                    If lsvRotas.FocusedItem.Checked = True Then
                        CheckAllListView(lsvRotas, False)
                    ElseIf lsvRotas.FocusedItem.Checked = False Then
                        CheckAllListView(lsvRotas, True)
                    End If

                Else
                    If lsvRotas.FocusedItem.Checked = False Then
                        lsvRotas.Items.Item(0).Checked = False
                        lsvRotas.FocusedItem.Checked = True
                    Else
                        lsvRotas.Items.Item(0).Checked = False
                        lsvRotas.FocusedItem.Checked = False
                    End If
                End If

            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try


    End Sub

    Private Sub lsvOcorrencias_Click(sender As Object, e As EventArgs) Handles lsvOcorrencias.Click

        Try


            If lsvOcorrencias.Items.Count > 0 Then

                If lsvOcorrencias.FocusedItem.[Text].ToString() = "Todas as ocorrências" Then

                    If lsvOcorrencias.FocusedItem.Checked = True Then
                        CheckAllListView(lsvOcorrencias, False)
                    ElseIf lsvOcorrencias.FocusedItem.Checked = False Then
                        CheckAllListView(lsvOcorrencias, True)
                        lsvOcorrencias.Items.Item(1).Checked = False
                        lsvOcorrencias.Items.Item(2).Checked = False
                    End If

                ElseIf lsvOcorrencias.FocusedItem.[Text].ToString() = "Somente com média" Then

                    If lsvOcorrencias.FocusedItem.Checked = True Then
                        CheckAllListView(lsvOcorrencias, False, "S")
                    ElseIf lsvOcorrencias.FocusedItem.Checked = False Then
                        CheckAllListView(lsvOcorrencias, True, "S")
                        lsvOcorrencias.Items.Item(0).Checked = False
                        lsvOcorrencias.Items.Item(2).Checked = False
                    End If


                ElseIf lsvOcorrencias.FocusedItem.[Text].ToString() = "Somente sem média" Then

                    If lsvOcorrencias.FocusedItem.Checked = True Then
                        CheckAllListView(lsvOcorrencias, False, "N")
                    ElseIf lsvOcorrencias.FocusedItem.Checked = False Then
                        CheckAllListView(lsvOcorrencias, True, "N")
                        lsvOcorrencias.Items.Item(0).Checked = False
                        lsvOcorrencias.Items.Item(1).Checked = False
                    End If

                Else
                    If lsvOcorrencias.FocusedItem.Checked = False Then
                        lsvOcorrencias.Items.Item(0).Checked = False
                        lsvOcorrencias.FocusedItem.Checked = True
                    Else
                        lsvOcorrencias.Items.Item(0).Checked = False
                        lsvOcorrencias.FocusedItem.Checked = False
                    End If
                End If

            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub opbArrec_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbArrec.CheckedChanged


        Try

            If eventSender.Checked Then
                Me._lblAux_0.Enabled = (Me.opbLeit.Checked Or Me.opbTran.Checked)
                Me._lblAux_1.Enabled = Me.opbArrec.Checked
                Me._lblAux_2.Enabled = Me.opbArrec.Checked
                Me.dtpMesAno.Enabled = (Me.opbLeit.Checked Or Me.opbTran.Checked)
                Me.dtpIni.Enabled = Me.opbArrec.Checked
                Me.dtpFim.Enabled = Me.opbArrec.Checked
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try



    End Sub

    Private Sub opbLeit_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbLeit.CheckedChanged


        Try

            If eventSender.Checked Then
                Me._lblAux_0.Enabled = (Me.opbLeit.Checked Or Me.opbTran.Checked)
                Me._lblAux_1.Enabled = Me.opbArrec.Checked
                Me._lblAux_2.Enabled = Me.opbArrec.Checked
                Me.dtpMesAno.Enabled = (Me.opbLeit.Checked Or Me.opbTran.Checked)
                Me.dtpIni.Enabled = Me.opbArrec.Checked
                Me.dtpFim.Enabled = Me.opbArrec.Checked
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try



    End Sub

    Private Sub opbTran_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles opbTran.CheckedChanged


        Try


            If eventSender.Checked Then
                Me._lblAux_0.Enabled = (Me.opbLeit.Checked Or Me.opbTran.Checked)
                Me._lblAux_1.Enabled = Me.opbArrec.Checked
                Me._lblAux_2.Enabled = Me.opbArrec.Checked
                Me.dtpMesAno.Enabled = (Me.opbLeit.Checked Or Me.opbTran.Checked)
                Me.dtpIni.Enabled = Me.opbArrec.Checked
                Me.dtpFim.Enabled = Me.opbArrec.Checked
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub dtpFim_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles dtpFim.Leave


        Try

            If CInt(VB6.Format(Me.dtpFim.Value, "yyyymm")) < CInt(VB6.Format(Me.dtpIni.Value, "yyyymm")) Then
                Me.dtpFim.Value = CDate(UltimoDiaMes((Me.dtpIni.Value.Month), (Me.dtpIni.Value.Year)) & "/" & Me.dtpIni.Value.Month & "/" & Me.dtpIni.Value.Year)
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub dtpIni_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles dtpIni.Leave

        Try

            Me.dtpFim.Value = CDate(UltimoDiaMes((Me.dtpIni.Value.Month), (Me.dtpIni.Value.Year)) & "/" & Me.dtpIni.Value.Month & "/" & Me.dtpIni.Value.Year)

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdExportar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdExportar.Click

        Try


            If Trim(Me.txtArq.Text) <> "" Then
                Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
                LigDes(False)
                ExportarArquivo()
                LigDes(True)
                Me.Cursor = System.Windows.Forms.Cursors.Default
            Else
                MessageBox.Show("Você precisa selecionar o caminho e o arquivo para exportação!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdFechar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdFechar.Click

        Try



            lClose()


        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdProcessar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdProcessar.Click

        Try

            Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
            LigDes(False)
            ProcessarDados()
            LigDes(True)
            Me.Cursor = System.Windows.Forms.Cursors.Default

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdProcura_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdProcura.Click

        Dim lstrAux As String
        Dim lstrArq As String

        lstrArq = "List_Oc_." & VB6.Format(Date.Now, "yyyymmddHHMMSS")

        Try

            With Me.dialArqOpen
                .DefaultExt = "CSV"
                .Filter = .DefaultExt & "(*." & .DefaultExt & ")" & "|*." & .DefaultExt
                If Trim(Me.txtArq.Text) <> "" Then
                    .FileName = StrReverse(Mid(StrReverse(Me.txtArq.Text), CInt(InStr(StrReverse(Me.txtArq.Text), "\")))) & lstrArq & "." & .DefaultExt
                Else
                    .FileName = My.Application.Info.DirectoryPath & "\" & lstrArq & "." & .DefaultExt
                End If
                .Title = "Arquivo de exportação de Ocorrências"
                .ShowDialog()
                lstrAux = StrReverse(.FileName)
                Me.txtArq.Text = StrReverse(Mid(lstrAux, CInt(InStr(lstrAux, "\")))) & lstrArq & "." & .DefaultExt
            End With

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdImprimir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdImprimir.Click

        Try

            lPrint()

        Catch ex As Exception
            MessageBox.Show("Ocorreu um Erro Inesperado. Favor, Contate o Administrador do Sistema ou a Equipe de Suporte de sua localidade! ", "Fatal - Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

#End Region

#Region "Métodos"

    Private Sub lClose()

        Try
            Me.Close()
        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub LigDes(ByVal ablnModo As Boolean)


        Try

            Me.cmdProcessar.Enabled = ablnModo
            Me.cmdExportar.Enabled = ablnModo
            Me.cmdImprimir.Enabled = ablnModo
            Me.fmeAux(0).Enabled = ablnModo
            Me.fmeAux(1).Enabled = ablnModo
            Me.fmeAux(2).Enabled = ablnModo
            Me.fmeAux(3).Enabled = ablnModo
            Me.cmdFechar.Enabled = ablnModo

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CheckAllListView(ByRef vlist As System.Windows.Forms.ListView, ByVal vCheck As Boolean)

        Dim i As Integer

        Try
            For i = 0 To vlist.Items.Count - 1
                vlist.Items.Item(i).Checked = vCheck
            Next i
        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub CheckAllListView(ByRef vlist As System.Windows.Forms.ListView, ByVal vCheck As Boolean, ByVal vCheckValue As String)

        Dim i As Integer

        Try

            For i = 0 To vlist.Items.Count - 1

                If vlist.Items.Item(i).SubItems(2).Text = vCheckValue Then
                    vlist.Items.Item(i).Checked = vCheck
                End If

            Next i

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub lPreencherList()

        Try
            PreencherListRotas()
            PreencherListOcorrencias()
        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub lPrint()

        Dim dt As DataTable
        Dim dc As DataColumn
        Dim ds As DataSet

        Dim bytBLOBData() As Byte

        Dim rpt As New ReportDocument()

        Dim vlist

        Dim objTempOcorrencias As New entidadeTempOcorrencias
        Dim repositorioTempOcorrencias As New repositorioTempOcorrencias


        Dim objEmpresa As New entidadeEmpresa
        Dim repositorioEmpresa As New repositorioEmpresa


        Try



            vlist = repositorioEmpresa.Select(objEmpresa)

            If vlist.Count <> 0 Then

                For Each objEmpresaFor As entidadeEmpresa In vlist

                    bytBLOBData = objEmpresaFor.LOGOTIPO

                Next

            End If

            objTempOcorrencias.NM_USUARIO = vUsuario.LOGIN

            dt = repositorioTempOcorrencias.Select_2(objTempOcorrencias)

            If dt.Rows.Count > 0 Then

                dc = New DataColumn("IMAGE", GetType(Byte()))
                dc.DefaultValue = bytBLOBData
                dt.Columns.Add(dc)

            End If

            ds = New DataSet
            ds.Tables.Add(dt)
            ds.Tables(0).TableName = "REL_TEMP_OCORRENCIAS"

            If ds.Tables(0).Rows.Count = 0 Then
                MessageBox.Show("Não há registros para o relatório escolhido! ", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            Else

                rpt = New rptRelOcorrencias

                rpt.SetDataSource(ds)

                frmViewRelatorios.rpt = rpt

                frmViewRelatorios.CRViewer.Zoom((100))
                frmViewRelatorios.Text = "Relatório de Declaração Debito"
                frmViewRelatorios.ShowDialog()

            End If

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub PreencherListRotas()

        Dim lstrRot As String

        Dim vlist

        Dim objLeitmensal As New entidadeLeitmensal
        Dim repositorioLeitmensal As New repositorioLeitmensal

        Try

            With Me.lsvRotas
                .Items.Clear()
                .Columns.Clear()
                If .Columns.Count <= 1 Then
                    .Columns.Add("", "Rota", CInt(VB6.TwipsToPixelsX(1800)))
                End If
                .Items.Add("Todas as rotas")
                .Items.Item(.Items.Count - 1).SubItems.Add("T")
            End With

            vlist = repositorioLeitmensal.Select_4(objLeitmensal)

            If vlist.Count <> 0 Then

                BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, vlist.Count)

                For Each objLeitmensalFor As entidadeLeitmensal In vlist

                    lstrRot = IIf(IsDBNull(objLeitmensalFor.ROTA), "0", objLeitmensalFor.ROTA)

                    With Me.lsvRotas
                        .Items.Add(lstrRot)
                    End With

                    BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1,  , " rotas")


                Next

            End If


        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Private Sub PreencherListOcorrencias()

        Dim lstrCod As String
        Dim lstrDes As String
        Dim lintMed As Short

        Dim vlist

        Dim objOcorrencia As New entidadeOcorrencia
        Dim repositorioOcorrencia As New repositorioOcorrencia

        Try


            With Me.lsvOcorrencias
                .Items.Clear()
                .Columns.Clear()
                If .Columns.Count <= 1 Then
                    .Columns.Add("", "Descrição", CInt(VB6.TwipsToPixelsX(2800)))
                    .Columns.Add("Cód.", CInt(VB6.TwipsToPixelsX(650)), System.Windows.Forms.HorizontalAlignment.Center)
                    .Columns.Add("Média", CInt(VB6.TwipsToPixelsX(650)), System.Windows.Forms.HorizontalAlignment.Center)
                End If
                .Items.Add("Todas as ocorrências")
                .Items.Item(.Items.Count - 1).SubItems.Add("T")
                .Items.Item(.Items.Count - 1).SubItems.Add("")
            End With

            objOcorrencia.COD = "'00'"

            vlist = repositorioOcorrencia.Select_3(objOcorrencia)

            If vlist.Count <> 0 Then

                With Me.lsvOcorrencias
                    .Items.Add("Somente com média")
                    .Items.Item(.Items.Count - 1).SubItems.Add("S")
                    .Items.Item(.Items.Count - 1).SubItems.Add("")
                    .Items.Add("Somente sem média")
                    .Items.Item(.Items.Count - 1).SubItems.Add("N")
                    .Items.Item(.Items.Count - 1).SubItems.Add("")
                End With

                BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, vlist.Count)

                For Each objOcorrenciaFor As entidadeOcorrencia In vlist

                    lstrDes = Trim(IIf(IsDBNull(objOcorrenciaFor.DESCRICAO), "", objOcorrenciaFor.DESCRICAO))
                    lstrCod = VB6.Format(Trim(IIf(IsDBNull(objOcorrenciaFor.COD), "", objOcorrenciaFor.COD)), "00")
                    lintMed = IIf(IsDBNull(objOcorrenciaFor.MEDIA), "", objOcorrenciaFor.MEDIA)

                    With Me.lsvOcorrencias
                        .Items.Add(lstrDes)
                        .Items.Item(.Items.Count - 1).SubItems.Add(lstrCod)
                        .Items.Item(.Items.Count - 1).SubItems.Add(IIf(lintMed = 1, "S", "N"))
                    End With

                    BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1,  , " ocorrência")

                Next

            End If

        Catch ex As Exception
            Exit Sub
        End Try
    End Sub

    Private Sub ExportarArquivo()

        Dim lstrLin As String
        Dim lintARQ As Short

        Dim vlist

        Dim objTempOcorrencias As New entidadeTempOcorrencias
        Dim repositorioTempOcorrencias As New repositorioTempOcorrencias

        Try

            objTempOcorrencias.NM_USUARIO = vUsuario.LOGIN

            vlist = repositorioTempOcorrencias.Select(objTempOcorrencias)


            If vlist.Count <> 0 Then

                'Export para CSV
                If Trim(Me.txtArq.Text) <> String.Empty Then

                    lintARQ = FreeFile()
                    FileOpen(lintARQ, Me.txtArq.Text, OpenMode.Output)
                    PrintLine(lintARQ, "Mesano_Ref;Zona;Livro;Conta;Rota;Sequencia;Nome;Codocor;Desocor;")

                    BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, vlist.Count)

                    For Each objTempOcorrenciasFor As entidadeTempOcorrencias In vlist

                        lstrLin = String.Empty
                        lstrLin = lstrLin & Trim(IIf(IsDBNull(objTempOcorrenciasFor.MESANO_REF), "", objTempOcorrenciasFor.MESANO_REF)) & ";" & Trim(IIf(IsDBNull(objTempOcorrenciasFor.ZONA), "", objTempOcorrenciasFor.ZONA)) & ";" & Trim(IIf(IsDBNull(objTempOcorrenciasFor.LIVRO), "", objTempOcorrenciasFor.LIVRO)) & ";" & Trim(IIf(IsDBNull(objTempOcorrenciasFor.CONTA), "", objTempOcorrenciasFor.CONTA)) & ";" & Trim(IIf(IsDBNull(Microsoft.VisualBasic.Right(Microsoft.VisualBasic.Left(objTempOcorrenciasFor.ROTA, 4), 2)), "", Microsoft.VisualBasic.Right(Microsoft.VisualBasic.Left(objTempOcorrenciasFor.ROTA, 4), 2))) & ";" & Trim(IIf(IsDBNull(Microsoft.VisualBasic.Right(objTempOcorrenciasFor.ROTA, 4)), "", Microsoft.VisualBasic.Right(objTempOcorrenciasFor.ROTA, 4))) & ";" & Trim(IIf(IsDBNull(objTempOcorrenciasFor.CODOCOR), "", objTempOcorrenciasFor.CODOCOR)) & ";" & Trim(IIf(IsDBNull(objTempOcorrenciasFor.DESOCOR), "", objTempOcorrenciasFor.DESOCOR)) & ";"

                        PrintLine(lintARQ, lstrLin)

                        BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1)

                    Next

                    FileClose(lintARQ)

                    MessageBox.Show("Arquivo gerado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)

                End If

            End If

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub ProcessarDados()


        Dim llngIdx As Integer 'Indices das listviews
        Dim lstrAux As String 'Auxiliar
        Dim lstrFRt As String 'Filtro de rotas
        Dim lstrFOc As String 'Filtro de ocorrencias
        Dim lstrTab As String 'Tabela
        Dim lstrMAn As String 'Mês/Ano
        Dim llngMAn As Integer 'Mês/Ano ref
        Dim lstrZon As String 'Zona
        Dim lstrLiv As String 'Livro
        Dim lstrCon As String 'Conta
        Dim lstrNom As String 'Nome
        Dim lstrRot As String 'Rota
        Dim lstrCOc As String 'Codigo da ocorrencia
        Dim lstrDOc As String 'Descricao da ocorrencia


        Dim vlist

        Dim objTempOcorrencias As New entidadeTempOcorrencias
        Dim repositorioTempOcorrencias As New repositorioTempOcorrencias

        Try

            Me.lblInfo.Text = " Buscando as ocorrências..."
            Me.lblInfo.Refresh()

            lstrMAn = GetConfig("mes.ano.faturamento")

            objTempOcorrencias.NM_USUARIO = vUsuario.LOGIN

            lDelete(objTempOcorrencias)

            If Me.opbTran.Checked Then
                lstrTab = "nftransicao"
            ElseIf Me.opbArrec.Checked Then
                lstrTab = "nf"
            ElseIf Me.opbLeit.Checked Then
                lstrTab = "leitmensal"
                If VB6.Format(Me.dtpMesAno.Value, "mm/yyyy") <> lstrMAn Then
                    lstrTab = lstrTab & "bkp" & VB6.Format(Me.dtpMesAno.Value, "mmyy")
                End If
                lstrTab = lstrTab & ""
            End If

            'Filtro de Rotas
            lstrAux = ""
            lstrFRt = ""

            With Me.lsvRotas
                If .Items.Count > 0 Then
                    If .Items.Item(0).Checked = False Then
                        For llngIdx = 2 To .Items.Count - 1
                            If .Items.Item(llngIdx).Checked = True Then
                                lstrAux = lstrAux & "'" & .Items.Item(llngIdx).Text & "',"
                            End If
                        Next llngIdx
                    End If
                End If
            End With

            If Len(Trim(lstrAux)) > 0 Then
                lstrFRt = vbCrLf & "      AND MID(" & lstrTab & ".`rota`,1,4) IN ( " & Microsoft.VisualBasic.Left(lstrAux, Len(lstrAux) - 1) & ") "
            End If

            'Filtro das ocorrencias
            lstrAux = ""
            lstrFOc = ""

            With Me.lsvOcorrencias
                If .Items.Count > 0 Then
                    If .Items.Item(0).Checked = False Then
                        For llngIdx = 4 To .Items.Count - 1
                            If .Items.Item(llngIdx).Checked = True Then
                                lstrAux = lstrAux & "'" & .Items.Item(llngIdx).SubItems(1).Text & "',"
                            End If
                        Next llngIdx
                    End If
                End If
            End With

            If Len(Trim(lstrAux)) > 0 Then
                If Microsoft.VisualBasic.Left(lstrTab, 11) = "`leitmensal" Then
                    lstrFOc = vbCrLf & "      AND LPAD(" & lstrTab & ".`ocorrenc`, 2, ""0"") IN ( " & Microsoft.VisualBasic.Left(lstrAux, Len(lstrAux) - 1) & ") "
                Else
                    lstrFOc = vbCrLf & "    AND MID(" & lstrTab & ".`itensserv`, INSTR(itensserv,'90410000')+8, 2) IN ( " & Microsoft.VisualBasic.Left(lstrAux, Len(lstrAux) - 1) & ") "
                End If
            Else
                If Microsoft.VisualBasic.Left(lstrTab, 11) = "`leitmensal" Then
                    lstrFOc = vbCrLf & "      AND LPAD(" & lstrTab & ".`ocorrenc`, 2, ""0"") NOT IN ( ""00"") "
                Else
                    lstrFOc = vbCrLf & "    AND MID(" & lstrTab & ".`itensserv`, INSTR(itensserv,'90410000')+8, 2) NOT IN ( ""00"") "
                End If
            End If

            objTempOcorrencias.NOME = lstrTab.ToUpper()

            If opbArrec.Checked = True Then
                objTempOcorrencias.CODOCOR = "01/" & VB6.Format(Me.dtpIni.Value, "MM/yyyy")
                objTempOcorrencias.DESOCOR = UltimoDiaMes((Me.dtpFim.Value.Month), (Me.dtpFim.Value.Year)) & "/" & VB6.Format(Me.dtpFim.Value, "MM/yyyy")
            Else
                objTempOcorrencias.CODOCOR = "01/" & VB6.Format(Me.dtpMesAno.Value, "MM/yyyy")
                objTempOcorrencias.DESOCOR = UltimoDiaMes((Me.dtpMesAno.Value.Month), (Me.dtpMesAno.Value.Year)) & "/" & VB6.Format(Me.dtpMesAno.Value, "MM/yyyy")
            End If
            objTempOcorrencias.NM_USUARIO = lstrFRt & lstrFOc

            vlist = repositorioTempOcorrencias.Select_1(objTempOcorrencias)

            If vlist.Count <> 0 Then

                BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, vlist.Count)

                For Each objTempOcorrenciasFor As entidadeTempOcorrencias In vlist


                    llngMAn = CInt(IIf(IsDBNull(objTempOcorrenciasFor.MESANO_REF), 0, objTempOcorrenciasFor.MESANO_REF))
                    lstrZon = Trim(IIf(IsDBNull(objTempOcorrenciasFor.ZONA), "", objTempOcorrenciasFor.ZONA))
                    lstrLiv = Trim(IIf(IsDBNull(objTempOcorrenciasFor.LIVRO), "", objTempOcorrenciasFor.LIVRO))
                    lstrCon = Trim(IIf(IsDBNull(objTempOcorrenciasFor.CONTA), "", objTempOcorrenciasFor.CONTA))
                    lstrRot = Trim(IIf(IsDBNull(objTempOcorrenciasFor.ROTA), "", objTempOcorrenciasFor.ROTA))
                    lstrNom = Trim(IIf(IsDBNull(objTempOcorrenciasFor.NOME), "", objTempOcorrenciasFor.NOME))
                    lstrCOc = Trim(IIf(IsDBNull(objTempOcorrenciasFor.CODOCOR), "00", objTempOcorrenciasFor.CODOCOR))
                    lstrDOc = Trim(IIf(IsDBNull(objTempOcorrenciasFor.DESOCOR), "", objTempOcorrenciasFor.DESOCOR))

                    objTempOcorrencias.NM_USUARIO = vUsuario.LOGIN
                    objTempOcorrencias.MESANO_REF = llngMAn
                    objTempOcorrencias.ZONA = lstrZon
                    objTempOcorrencias.LIVRO = lstrLiv
                    objTempOcorrencias.CONTA = lstrCon
                    objTempOcorrencias.ROTA = lstrRot
                    objTempOcorrencias.NOME = lstrNom
                    objTempOcorrencias.CODOCOR = lstrCOc
                    objTempOcorrencias.DESOCOR = lstrDOc

                    lInsert(objTempOcorrencias)

                    BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 1,  , " ocorrências")

                Next

            End If

        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Function lInsert(ByRef objTempOcorrencias As entidadeTempOcorrencias) As Boolean
        Dim repositorioTempOcorrencias As New repositorioTempOcorrencias
        Try

            repositorioTempOcorrencias.Insert(objTempOcorrencias)

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Function lDelete(ByRef objTempOcorrencias As entidadeTempOcorrencias) As Boolean
        Dim repositorioTempOcorrencias As New repositorioTempOcorrencias
        Try

            repositorioTempOcorrencias.Delete(objTempOcorrencias)

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

#End Region


End Class