Option Strict Off
Option Explicit On

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

Friend Class frmAnaliseLeituraMedia
    Inherits System.Windows.Forms.Form

#Region "Propriedades"

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


        Try

            Me.dtpMesAno.Value = Date.Now
            MontaGrid()

        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 cmdArquivo_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdArquivo.Click
        Dim lstrAux As String
        Dim lstrArq As String

        Try

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

            With Me.dialArqOpen

                .DefaultExt = "CSV"
                .Filter = .DefaultExt & "(*." & .DefaultExt & ")" & "|*." & .DefaultExt
                If Trim(Me.txtArquivo.Text) <> "" Then
                    .FileName = StrReverse(Mid(StrReverse(Me.txtArquivo.Text), CInt(InStr(StrReverse(Me.txtArquivo.Text), "\")))) & lstrArq & "." & .DefaultExt
                Else
                    .FileName = My.Application.Info.DirectoryPath & "\" & lstrArq & "." & .DefaultExt
                End If
                .Title = "Arquivo de exportação da análise de leitura e média "
                .ShowDialog()
                lstrAux = StrReverse(.FileName)
                Me.txtArquivo.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 cmdExporta_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdExporta.Click

        Dim lstrLin As String
        Dim lintARQ As Short
        Dim llngRow As Integer
        Dim llngCol As Integer


        Try

            LigDes(False)

            If Trim(Me.txtArquivo.Text) <> "" Then

                lintARQ = FreeFile()

                FileOpen(lintARQ, Me.txtArquivo.Text, OpenMode.Output)

                With Me.mshDados

                    For llngRow = 0 To .Rows - 1
                        lstrLin = ""
                        For llngCol = 0 To .Cols - 1
                            lstrLin = lstrLin & .get_TextMatrix(llngRow, llngCol) & ";"
                        Next llngCol
                        PrintLine(lintARQ, lstrLin)
                    Next llngRow

                End With

                FileClose(lintARQ)

                MessageBox.Show("Arquivo gerado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Você precisa selecionar o caminho e o arquivo para exportação!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            LigDes(True)




        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


            lProcess()



        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 frmAnaliseLeituraMedia_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
                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 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.cmdExporta.Enabled = ablnModo
            Me.cmdFechar.Enabled = ablnModo
            'Me.cmdImprimir.Enabled = ablnModo
            Me.cmdProcessar.Enabled = ablnModo
            Me.dtpMesAno.Enabled = ablnModo


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub MontaGrid()

        Dim llngCol As Integer
        Dim ldteAux As Date

        Try

            ldteAux = Me.dtpMesAno.Value
            With Me.mshDados
                .AllowUserResizing = MSFlexGridLib.AllowUserResizeSettings.flexResizeBoth
                .Cols = 24
                .Rows = 2
                .FixedRows = 1
                Call .Clear()
                .set_TextMatrix(0, 0, "Zona")
                .set_TextMatrix(0, 1, "Livro")
                .set_TextMatrix(0, 2, "Conta")
                .set_TextMatrix(0, 3, "Cod.Uc.")
                .set_TextMatrix(0, 4, "Cod.C.")
                .set_TextMatrix(0, 5, "Nome")
                .set_TextMatrix(0, 6, "Endereço")
                .set_TextMatrix(0, 7, "Numero")
                .set_TextMatrix(0, 8, "Bairro")
                .set_TextMatrix(0, 9, "Cep")
                .set_TextMatrix(0, 10, "Cidade")
                .set_TextMatrix(0, 11, "Uf")
                For llngCol = 1 To 12
                    .set_TextMatrix(0, 11 + llngCol, VB6.Format(CDate(DateAdd(Microsoft.VisualBasic.DateInterval.Month, (llngCol - 1) * -1, Me.dtpMesAno.Value)), "MM/YYYY"))
                Next llngCol

            End With


        Catch ex As Exception
            Exit Sub
        End Try



    End Sub

    Private Sub lProcess()

        Dim lstrZon As String
        Dim lstrLiv As String
        Dim lstrCon As String
        Dim llngUid As Integer
        Dim llngCId As Integer
        Dim lstrGru As String
        Dim lstrNom As String
        Dim lstrEnd As String
        Dim lstrNum As String
        Dim lstrBai As String
        Dim lstrCep As String
        Dim lstrCid As String
        Dim lstrUf As String

        Dim lstrMes As String
        Dim lintMes As Short

        Dim lblnOco As Boolean
        Dim lstrIte As String
        Dim lstrCod As String

        Dim lstrOco(12) As String
        Dim ldblMed(12) As Double
        Dim lstrRef(12) As String

        Dim llngRow As Integer
        Dim llngCol As Integer

        Dim vlist
        Dim vlist_1

        Dim objNf As New entidadeNf
        Dim repositorioNf As New repositorioNf

        Dim objConsum As New entidadeConsum
        Dim repositorioConsum As New repositorioConsum

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Try


            MontaGrid()

            With Me.mshDados
                .Redraw = False
            End With

            objNf.MESANO_REF = CInt(VB6.Format(Me.dtpMesAno.Value, "YYYYMM"))
            objNf.GRUPO = "B"

            vlist = repositorioNf.Select_13(objNf)

            If vlist.Count > 0 Then

                BarraProgresso((Me.ProgressBar), (Me.lblPerc), (Me.lblInfo), 0, vlist.Count)
                Me.lblLog.Text = " Registros encontrados " & vlist.Count

                For Each objNfFor As entidadeNf In vlist

                    If Me.chkComMedia.CheckState = System.Windows.Forms.CheckState.Checked Then
                        lblnOco = False
                    Else
                        lblnOco = True
                    End If


                    lstrZon = Trim(IIf(IsDBNull(objNfFor.ZONA), "", objNfFor.ZONA))

                    lstrLiv = Trim(IIf(IsDBNull(objNfFor.LIVRO), "", objNfFor.LIVRO))

                    lstrCon = Trim(IIf(IsDBNull(objNfFor.CONTA), "", objNfFor.CONTA))

                    lstrGru = Trim(IIf(IsDBNull(objNfFor.GRUPO), "B", objNfFor.GRUPO))

                    llngUid = CInt(IIf(IsDBNull(objNfFor.UNID_ID), 0, objNfFor.UNID_ID))

                    llngCId = CInt(IIf(IsDBNull(objNfFor.CONS_ID), 0, objNfFor.CONS_ID))

                    lintMes = 1

                    objNf.ZONA = lstrZon
                    objNf.LIVRO = lstrLiv
                    objNf.CONTA = lstrCon
                    objNf.GRUPO = lstrGru
                    objNf.UNID_ID = llngUid
                    objNf.MESANO_REF = CInt(VB6.Format(Me.dtpMesAno.Value, "YYYYMM"))

                    vlist_1 = repositorioNf.Select_14(objNf)

                    If vlist_1.Count > 0 Then

                        For Each objNfFor_1 As entidadeNf In vlist_1

                            lstrMes = Microsoft.VisualBasic.Left(Trim(IIf(IsDBNull(objNfFor_1.MESANO), "", objNfFor_1.MESANO)), 2)

                            lstrIte = Trim(IIf(IsDBNull(objNfFor_1.ITENSSERV), "", objNfFor_1.ITENSSERV))

                            If CInt(InStr(1, lstrIte, "90410000")) > 0 Then
                                lstrCod = Mid(lstrIte, CInt(InStr(1, lstrIte, "90410000")), 10)
                                lstrOco(lintMes) = lstrCod
                                ldblMed(lintMes) = BuscaValorItem(lstrIte, lstrCod)
                                lstrRef(lintMes) = BuscaRefItem(lstrIte, lstrCod)
                                lblnOco = True
                            Else
                                lstrOco(lintMes) = ""
                                ldblMed(lintMes) = 0
                                lstrRef(lintMes) = "LIDO"
                            End If

                            lintMes = lintMes + 1

                        Next

                    End If


                    If lblnOco Then

                        objConsum.CONSREG = llngCId

                        vlist_1 = repositorioConsum.Select(objConsum)

                        If vlist_1.Count > 0 Then

                            For Each objConsumFor As entidadeConsum In vlist_1
                                lstrNom = Trim(IIf(IsDBNull(objConsumFor.NOME), "", objConsumFor.NOME))
                            Next

                        Else
                            lstrNom = ""
                        End If

                        objUCFaturamento.ZONA = lstrZon
                        objUCFaturamento.LIVRO = lstrLiv
                        objUCFaturamento.CONTA = lstrCon
                        objUCFaturamento.GRUPO = LCase(lstrGru)
                        objUCFaturamento.UNID_ID = llngUid

                        vlist_1 = repositorioUCFaturamento.Select_12(objUCFaturamento)

                        If vlist_1.Count > 0 Then

                            For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist_1

                                If CInt(IIf(IsDBNull(objUCFaturamentoFor.CONS_ID), 0, objUCFaturamentoFor.CONS_ID)) = llngCId Then

                                    lstrNom = Trim(IIf(IsDBNull(objUCFaturamentoFor.NOME), "", objUCFaturamentoFor.NOME))
                                End If

                                lstrEnd = Trim(IIf(IsDBNull(objUCFaturamentoFor.END), "", objUCFaturamentoFor.END))

                                lstrNum = Trim(IIf(IsDBNull(objUCFaturamentoFor.NUMERO), "", objUCFaturamentoFor.NUMERO))

                                lstrBai = Trim(IIf(IsDBNull(objUCFaturamentoFor.BAIRRO), "", objUCFaturamentoFor.BAIRRO))

                                lstrCep = Trim(IIf(IsDBNull(objUCFaturamentoFor.CEP), "", objUCFaturamentoFor.CEP))

                                lstrCid = Trim(IIf(IsDBNull(objUCFaturamentoFor.CIDADE), "", objUCFaturamentoFor.CIDADE))

                                lstrUf = Trim(IIf(IsDBNull(objUCFaturamentoFor.UF), "", objUCFaturamentoFor.UF))


                            Next

                        Else
                            lstrEnd = ""
                            lstrNum = ""
                            lstrBai = ""
                            lstrCep = ""
                            lstrCid = ""
                            lstrUf = ""
                        End If

                        '
                        With Me.mshDados
                            .set_TextMatrix(.Rows - 1, 0, lstrZon)
                            .set_TextMatrix(.Rows - 1, 1, lstrLiv)
                            .set_TextMatrix(.Rows - 1, 2, lstrCon)
                            .set_TextMatrix(.Rows - 1, 3, llngUid)
                            .set_TextMatrix(.Rows - 1, 4, llngCId)
                            .set_TextMatrix(.Rows - 1, 5, lstrNom)
                            .set_TextMatrix(.Rows - 1, 6, lstrEnd)
                            .set_TextMatrix(.Rows - 1, 7, lstrNum)
                            .set_TextMatrix(.Rows - 1, 8, lstrBai)
                            .set_TextMatrix(.Rows - 1, 9, lstrCep)
                            .set_TextMatrix(.Rows - 1, 10, lstrCid)
                            .set_TextMatrix(.Rows - 1, 11, lstrUf)

                            For llngCol = 1 To 12
                                If ldblMed(llngCol) = 1 Then
                                    'Muda cor de fundo
                                    .FillStyle = MSFlexGridLib.FillStyleSettings.flexFillRepeat
                                    .Col = 11 + llngCol
                                    .Row = .Rows - 1
                                    .ColSel = 11 + llngCol
                                    .CellBackColor = System.Drawing.Color.Red
                                Else
                                    .Col = 0
                                    .ColSel = .Cols - 1
                                    .Row = .Rows - 1
                                    .CellBackColor = System.Drawing.Color.White
                                End If
                                .set_TextMatrix(.Rows - 1, 11 + llngCol, lstrRef(llngCol))
                                .FillStyle = MSFlexGridLib.FillStyleSettings.flexFillSingle
                            Next llngCol
                            .Rows = .Rows + 1
                        End With
                    End If

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

                Next

                If Me.mshDados.Rows > 2 Then Me.mshDados.Rows = Me.mshDados.Rows - 1

            End If


            With Me.mshDados
                .Redraw = False
                For llngCol = 0 To .Cols - 1
                    .set_ColWidth(llngCol, 95)
                Next llngCol
                For llngRow = 0 To .Rows - 1
                    For llngCol = 0 To .Cols - 1
                        If (95 * CInt(Len(.get_TextMatrix(llngRow, llngCol)))) > .get_ColWidth(llngCol) Then
                            .set_ColWidth(llngCol, 95 * (CInt(Len(.get_TextMatrix(llngRow, llngCol))) + 2))
                            If IsDate(.get_TextMatrix(llngRow, llngCol)) Then
                                If llngRow > 0 Then
                                    .set_TextMatrix(llngRow, llngCol, VB6.Format(.get_TextMatrix(llngRow, llngCol), "DD/MM/YYYY" & IIf(CInt(Len(Trim(.get_TextMatrix(llngRow, llngCol)))) > 10, " HH:NN:SS", "")))
                                End If
                            End If
                        End If
                    Next llngCol
                Next llngRow
                .Redraw = True
            End With

            With Me.mshDados
                .Redraw = True
            End With

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub


#End Region


End Class