Option Strict Off
Option Explicit On
Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE
Imports VB = Microsoft.VisualBasic
Imports System.Collections.Generic
Imports CrystalDecisions
Imports BarcodeLib
Imports CrystalDecisions.CrystalReports.Engine
Imports System.IO
Imports System.Configuration
Imports System.Net.Mail
Public Class frmEmailEnvio

    Private dt, dt1, dt2, dt3, dt4 As DataTable
    Private objABD As New entidadeAtualizaBancoDados
    Private repABD As New repositorioAtualizaBancoDados
    Private objExecABD As New entidadeAtualizaBancoDados
    Private repExecABD As New repositorioAtualizaBancoDados
    Private bListaCarregada As Boolean
    Private istrTabela As String
    Private istrGrupo As String
    Private sCaminhoAnexo As String

    Private LImagem() As Byte
    Private sNomeEmpresa As String
    Private sEnderecoEmpresa As String
    Private sCepEmpresa As String
    Private sCidadeEmpresa As String
    Private sUFempresa As String
    Private sBairroEmpresa As String
    Private sFoneEmpresa As String
    Private sWebEmpresa As String
    Private bValidacao As Boolean

    Private Sub frmEmailEnvio_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Try

            Me.txtMesAno.Text = GetConfig("mes.ano.faturamento")
            Me.txtMesAno.Text = FormataData(Me.txtMesAno, 1)

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

    Private sTratamentoErro(30) As String
    Private sErroEnvio As Boolean
    Private ifrmimpFaturas As frmImpFaturas
    Private Sub cmdfechar_Click(sender As Object, e As EventArgs) Handles cmdfechar.Click
        Me.Close()
    End Sub

    Private Sub txtZona_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Enter

        Try

            With Me.txtZona
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            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 txtZona_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtZona.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try

            If KeyAscii <> 8 And (KeyAscii < 48 Or KeyAscii > 57) 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 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 txtZona_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtZona.Leave

        Try

            With Me.txtZona
                .Text = VB6.Format(.Text, "000")
            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 txtLivro_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Enter

        Try

            With Me.txtLivro
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            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 txtLivro_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtLivro.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try

            If KeyAscii <> 8 And (KeyAscii < 48 Or KeyAscii > 57) 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 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 cmdbuscar_Click(sender As Object, e As EventArgs) Handles cmdbuscar.Click
        sCarregaListView()
    End Sub

    Private Sub txtLivro_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtLivro.Leave

        Try
            With Me.txtLivro
                .Text = VB6.Format(.Text, "00")
            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 txtMesAno_Leave(sender As Object, e As EventArgs)
        Dim ldteAux As Date

        Try


            If Trim(Me.txtMesAno.Text) <> "" Then
                Me.txtMesAno.Text = FormataData(txtMesAno, 1)
                ldteAux = System.DateTime.FromOADate(CDate("01/" & Me.txtMesAno.Text).ToOADate - 1)
                ldteAux = System.DateTime.FromOADate(CDate("01/" & VB6.Format(ldteAux, "MM/YYYY")).ToOADate - 1)
                'Me.dtpMesAnoConsumo.Value = CDate("01/" & VB6.Format(ldteAux, "MM/YYYY"))
                'Monta_MesAno_Civil()

                'If Me.txtMesAno.Text = "" Then
                '    Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Date.Now), Year(Date.Now)) & "/" & VB6.Format(Date.Now, "MM/YYYY")).ToOADate)
                'Else
                '    Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Me.txtMesAno.Text), Year(Me.txtMesAno.Text)) & "/" & VB6.Format(Me.txtMesAno.Text, "MM/YYYY")).ToOADate)
                'End If

            Else
                MessageBox.Show("Mês e Ano inválido!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.txtMesAno.Focus()
            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 txtMesAno_Enter(sender As Object, e As EventArgs)
        Try

            txtMesAno.SelectionStart = 0
            txtMesAno.SelectionLength = Len(txtMesAno.Text)

            'If Me.txtMesAno.Text = "" Then
            '    Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Date.Now), Year(Date.Now)) & "/" & VB6.Format(Date.Now, "MM/YYYY")).ToOADate)
            'Else
            '    Me.txtDt_Leit_Atual.Text = System.DateTime.FromOADate(CDate(UltimoDiaMes(Month(Me.txtMesAno.Text), Year(Me.txtMesAno.Text)) & "/" & VB6.Format(Me.txtMesAno.Text, "MM/YYYY")).ToOADate)
            '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 cmdImprimir_Click(sender As Object, e As EventArgs) Handles cmdImprimir.Click
        Dim i As Int16
        Dim sNotas As String = ""

        Me.Cursor = Cursors.WaitCursor
        If Me.lstMail.Items.Count <> 0 Then
            For i = 0 To Me.lstMail.Items.Count - 1
                If lstMail.Items(i).Checked = True Then
                    sNotas += lstMail.Items(i).SubItems(3).Text + ","
                End If
            Next i
            If sNotas <> "" Then
                sNotas = sNotas.Substring(0, sNotas.Length - 1)
                Call sDadosEmpresa(LImagem, sNomeEmpresa, sEnderecoEmpresa, sCepEmpresa, sCidadeEmpresa, sUFempresa, sBairroEmpresa, sFoneEmpresa, sWebEmpresa)
                Me.Cursor = Cursors.WaitCursor
                lPrint("rptRelEnvioE", sNotas)
            Else
                MessageBox.Show("Selecione ao menos uma Fatura a ser impressa", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Else
            MessageBox.Show("Clique em Buscar para selecionar as faturas", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Sub
        End If
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub txtConta_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Enter

        Try

            With Me.txtConta
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            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 chkdata_CheckedChanged(sender As Object, e As EventArgs)
        Try
            If chkdata.Checked Then
                gpbData.Enabled = True
            Else
                gpbData.Enabled = False
            End If
        Catch ex As Exception
            MessageBox.Show("ocorreu o erro: " & Err.Description & " - rotina: chkref_CheckedChanged" & "", "aviso de erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub txtConta_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtConta.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try

            If KeyAscii <> 8 And (KeyAscii < 48 Or KeyAscii > 57) 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 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 txtConta_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtConta.Leave

        Try
            With Me.txtConta
                .Text = VB6.Format(.Text, "000000")
            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 sCarregaListView()

        Dim lsiItens As System.Windows.Forms.ListViewItem
        Dim clhColunas As System.Windows.Forms.ColumnHeader
        Dim strNome As String
        Dim strZona As String
        Dim lngTamanho As Integer
        Dim lintLinha As Integer
        Dim lstraux As String
        Dim lstrSqlRota As String
        Dim lstrSqlZLC As String
        Dim lstrMesAnoRef As String
        Dim lstrsqlGrupo As String
        Dim lstrsql As String

        Dim sZona As String
        Dim sLivro As String
        Dim sConta As String
        Dim szlc As String
        Dim sNome As String
        Dim sDataVenc As String
        Dim sValorTotal As String
        Dim SMail As String
        Dim sGrupo As String
        Dim sMesRef As String
        Dim sNumNf As String
        Dim sMailSplit
        Dim sMailEnviado As String

        Try


            If (Trim(txtZona.Text) <> "" And Trim(txtLivro.Text) <> "" And Trim(txtConta.Text) <> "") Or chkdata.Checked = True Then

                lstrsql = " SELECT c.nome, a.Zona, a.livro, a.conta, a.dataenvio, a.numnf, a.envioemail, a.email"
                lstrsql = lstrsql & " FROM envio_email_faturas A INNER JOIN uc_faturamento B on (a.zona = b.zona AND a.livro = b.livro AND a.conta = b.conta) "
                lstrsql = lstrsql & " INNER JOIN consum C on(c.consreg = b.cons_id)"
                lstrsql = lstrsql & "WHERE 1 = 1  AND a.ZONA  = '" & txtZona.Text & "' AND a.LIVRO = '" & txtLivro.Text & "' AND a.CONTA = '" & txtConta.Text & "'"

                If chkdata.Checked Then
                    lstrsql += " AND CONCAT(SUBSTRING(CONVERT( a.dataenvio, CHAR),6,2),'/', SUBSTRING(CONVERT( a.dataenvio, CHAR),1,4)) = '" & txtMesAno.Text & "'"
                End If

                objABD.QUERY_NAME = lstrsql
                dt = repABD.Consultar(objABD)

                ' ----- Limpa a List que carrega as cidades
                lstMail.Items.Clear()
                    lstMail.Columns.Clear()

                If lstMail.Columns.Count <= 1 Then
                    clhColunas = lstMail.Columns.Add("", "ZLC", CInt(VB6.TwipsToPixelsX(1900)))
                    clhColunas = lstMail.Columns.Add("", "Nome", CInt(VB6.TwipsToPixelsX(3000)))
                    clhColunas = lstMail.Columns.Add("", "Data de Envio", CInt(VB6.TwipsToPixelsX(2000)))
                    clhColunas = lstMail.Columns.Add("", "Fatura", CInt(VB6.TwipsToPixelsX(1200)))
                    clhColunas = lstMail.Columns.Add("", "Enviado", CInt(VB6.TwipsToPixelsX(800)))
                    clhColunas = lstMail.Columns.Add("", "Email", CInt(VB6.TwipsToPixelsX(3500)))

                    'clhColunas = lstMail.Columns.Add("", "Grupo", CInt(VB6.TwipsToPixelsX(1000)))
                    'clhColunas = lstMail.Columns.Add("", "NumNF", CInt(VB6.TwipsToPixelsX(1000)))
                End If


                If dt.Rows.Count > 0 Then
                    BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 0, dt.Rows.Count, "...carregando as informações na lista")
                    For Each row As DataRow In dt.Rows
                        sZona = IIf(IsDBNull(row("Zona")), "0", row("Zona"))
                        sLivro = IIf(IsDBNull(row("livro")), "0", row("livro"))
                        sConta = IIf(IsDBNull(row("conta")), "0", row("conta"))
                        sNome = IIf(IsDBNull(row("nome")), "", row("nome"))
                        sDataVenc = IIf(IsDBNull(row("dataenvio")), "", row("dataenvio"))
                        sNumNf = IIf(IsDBNull(row("numnf")), "", row("numnf"))
                        SMail = IIf(IsDBNull(row("email")), "", row("email"))
                        sMailEnviado = IIf(IsDBNull(row("envioemail")), "", row("envioemail"))

                        If sMailEnviado = "False" Then
                            sMailEnviado = "NÂO"
                        Else
                            sMailEnviado = "SIM"
                        End If

                        szlc = sZona & "." & sLivro & "." & sConta

                        With Me.lstMail

                            .Items.Add(szlc)
                            .Items.Item(.Items.Count - 1).SubItems.Add(sNome)
                            .Items.Item(.Items.Count - 1).SubItems.Add(sDataVenc)
                            .Items.Item(.Items.Count - 1).SubItems.Add(sNumNf)
                            .Items.Item(.Items.Count - 1).SubItems.Add(sMailEnviado)
                            .Items.Item(.Items.Count - 1).SubItems.Add(SMail)
                            '.Items.Item(.Items.Count - 1).SubItems.Add(sGrupo)
                            '.Items.Item(.Items.Count - 1).SubItems.Add(sNumNf)

                        End With

                        BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 1,, "...carregando as informações na lista")

                    Next
                Else
                    MsgBox("Não existe registro para a seleção", vbInformation + vbOKOnly, "Aviso")
                End If

                BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 0, 0, "...carregando as informações na lista")
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: sCarregaListView" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub
    Private Sub lPrint(ByVal vNomeRPT As String, sNotas As String)

        Dim dt As DataTable
        Dim dt_1 As DataTable
        Dim dt_2 As DataTable
        Dim dt_3 As DataTable
        Dim dc As DataColumn
        Dim ds As DataSet
        Dim lstrsql As String

        Dim bytBLOBData() As Byte

        Dim objEmpresa As New entidadeEmpresa
        Dim repositorioEmpresa As New repositorioEmpresa

        Dim vlist

        Try
            Dim rpt As New ReportDocument()

            'rptConsumidorAVencer
            If vNomeRPT = "rptRelEnvioE" Then

                dt_2 = New DataTable()
                dt_2.Columns.Add("NOME", GetType(String))
                dt_2.Columns.Add("DATAENVIO", GetType(String))
                dt_2.Columns.Add("FATURA", GetType(String))

                'CAMPOS NOVOS - Marcio Cesar - 10/01/2023
                dt_2.Columns.Add("EMAIL", GetType(String))
                dt_2.Columns.Add("ENVIO", GetType(Integer))

                ds = New DataSet

                lstrsql = " SELECT c.nome , a.dataenvio, CONVERT(a.numnf ,CHAR) as FATURA,CONVERT( a.envioemail , CHAR) as ENVIO, a.email , a.zona , a.livro , a.conta "
                lstrsql = lstrsql & " FROM envio_email_faturas A INNER JOIN uc_faturamento B on (a.zona = b.zona AND a.livro = b.livro AND a.conta = b.conta) "
                lstrsql = lstrsql & " INNER JOIN consum C on(c.consreg = b.cons_id)"
                lstrsql = lstrsql & "WHERE 1 = 1  AND a.ZONA  = '" & txtZona.Text & "' AND a.LIVRO = '" & txtLivro.Text & "' AND a.CONTA = '" & txtConta.Text & "'"

                'Seleção de faturas - Marcio Cesar - 10/01/2023
                lstrsql += " AND A.NUMNF IN ( " + sNotas + " )"


                objABD.QUERY_NAME = lstrsql
                dt = repABD.Consultar(objABD)

                If dt.Rows.Count > 0 Then
                    For Each dr_1 As DataRow In dt.Rows

                        dt_2.Rows.Add(dr_1("FATURA"),
                                          dr_1("NOME"),
                                          dr_1("DATAENVIO"), dr_1("EMAIL"), dr_1("ENVIO"))
                        'dr_1("FATURA"))
                        'dr_1("TENSAO"),
                        'dr_1("DSTIPO_MEDIDOR"),
                        'dr_1("MARCA"),
                        'dr_1("QTDE"),
                        'bytBLOBData)
                    Next dr_1
                End If

                ds.Tables.Add(dt)
                ds.Tables(0).TableName = "REL_ENVIO_E"


                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 rptRelEnvioE

                    rpt.SetDataSource(ds)
                    rpt.SetParameterValue("nomeempresa", sNomeEmpresa)
                    rpt.SetParameterValue("enderecoempresa", sEnderecoEmpresa)
                    rpt.SetParameterValue("cepempresa", sCepEmpresa)
                    rpt.SetParameterValue("ufempresa", sUFempresa)
                    rpt.SetParameterValue("cidadeempresa", sCidadeEmpresa)
                    rpt.SetParameterValue("bairroempresa", sBairroEmpresa)
                    rpt.SetParameterValue("foneempresa", sFoneEmpresa)
                    rpt.SetParameterValue("websiteempresa", sWebEmpresa)
                    'rpt.SetParameterValue("F_Titulo", "Listagem de medidores em: " & VB6.Format(Me.dtpBase.Value, "dd/mm/yyyy") & " da rota: " & VB6.GetItemString(Me.cmbRotaIni, Me.cmbRotaIni.SelectedIndex) & " até " & VB6.GetItemString(Me.cmbRotaFim, Me.cmbRotaFim.SelectedIndex))
                    'rpt.SetParameterValue("F_Subtitulo", lstrAuxiliar)


                    frmViewRelatorios.rpt = rpt

                    frmViewRelatorios.CRViewer.Zoom((100))
                    frmViewRelatorios.Text = "Relatório"
                    frmViewRelatorios.ShowDialog()
                    frmViewRelatorios.WindowState = WindowState.Maximized
                    Me.Cursor = Cursors.Default
                End If
            End If

            Me.Cursor = System.Windows.Forms.Cursors.Default

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

    End Sub


    Private Sub frmEmailEnvio_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try

            Select Case KeyAscii
                Case System.Windows.Forms.Keys.Return
                    TabEnter(KeyAscii, eventArgs)
                Case System.Windows.Forms.Keys.Escape
                    Me.Close()
            End Select
            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 Class