Option Strict Off
Option Explicit On

Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE

Friend Class frmCadPrecoMedioLivre
    Inherits System.Windows.Forms.Form

    Dim ilngUnidId As Integer
    Dim ilngConsId As Integer


#Region "Propriedades"

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


        Try

            Me.dtpMesAno.Value = BuscaDataBD()
            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 mfgDados_ClickEvent(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles mfgDados.ClickEvent

        Try


            With Me.mfgDados
                Me.dtpMesAno.Value = "01/" & .get_TextMatrix(.RowSel, 0)
                Me.txtValor.Text = VB6.Format(CDbl(IIf(IsNumeric(.get_TextMatrix(.RowSel, 3)), .get_TextMatrix(.RowSel, 3), 0)), "#,##0.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 txtValor_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtValor.Enter

        Try


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

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)


        Try


            If KeyAscii = System.Windows.Forms.Keys.Return Then
                TabEnter(KeyAscii, eventArgs)
            ElseIf KeyAscii <> System.Windows.Forms.Keys.Back And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9) Then
                If KeyAscii = System.Windows.Forms.Keys.Delete Then
                    KeyAscii = System.Windows.Forms.Keys.Snapshot
                End If
                If KeyAscii <> System.Windows.Forms.Keys.Snapshot Then
                    KeyAscii = 0
                Else
                    If InStr(1, Me.txtValor.Text, ",") > 0 Then
                        KeyAscii = 0
                    End If
                End If
            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 txtValor_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtValor.Leave


        Try



            With Me.txtValor
                .Text = VB6.Format(CDbl(IIf(IsNumeric(.Text), .Text, 0)), "#,##0.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 cmdLocalizar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdLocalizar.Click



        Try

            frmLocalizaUnidade.Show()
            frmLocalizaUnidade.SetaLocalizaUnidade("U", Me)



        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 cmdNovo_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdNovo.Click


        Try


            Me.dtpMesAno.Value = BuscaDataBD()
            Me.txtValor.Text = "0,00"
            Me.dtpMesAno.Focus()



        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 cmdSalvar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdSalvar.Click

        Dim llngRef As Integer
        Dim lstrCpj As String
        Dim lstrNom As String
        Dim ldblVlr As Double
        Dim llngCId As Integer
        Dim llngUId As Integer
        Dim lblnExi As Boolean
        Dim lstrSql As String


        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            With Me.mfgDados
                llngRef = CInt(Microsoft.VisualBasic.Right(.get_TextMatrix(.RowSel, 0), 4) & Microsoft.VisualBasic.Left(.get_TextMatrix(.RowSel, 0), 2))
                lstrCpj = .get_TextMatrix(.RowSel, 1)
                lstrNom = .get_TextMatrix(.RowSel, 2)
                ldblVlr = CDbl(IIf(IsNumeric(.get_TextMatrix(.RowSel, 3)), .get_TextMatrix(.RowSel, 3), 0))
                llngCId = CInt(IIf(IsNumeric(.get_TextMatrix(.RowSel, 4)), .get_TextMatrix(.RowSel, 4), 0))
                llngUId = CInt(IIf(IsNumeric(.get_TextMatrix(.RowSel, 5)), .get_TextMatrix(.RowSel, 5), 0))
            End With

            lblnExi = False

            lstrSql = ""
            lstrSql = lstrSql & "SELECT * "
            lstrSql = lstrSql & "  FROM `precomediolivre` "
            lstrSql = lstrSql & " WHERE `referencia` = " & CInt(VB6.Format(Me.dtpMesAno.Value, "YYYYMM")) & " "
            lstrSql = lstrSql & "   AND `cons_id` = " & llngCId
            lstrSql = lstrSql & "   AND `unid_id` = " & llngUId



            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                lblnExi = True

            End If


            lstrSql = ""

            If lblnExi Then
                lstrSql = lstrSql & "UPDATE "
            Else
                lstrSql = lstrSql & "INSERT INTO "
            End If
            lstrSql = lstrSql & " `precomediolivre` SET "
            lstrSql = lstrSql & " `referencia` = " & CInt(VB6.Format(Me.dtpMesAno.Value, "YYYYMM")) & ", "
            lstrSql = lstrSql & " `cnpj` = '" & lstrCpj & "', "
            lstrSql = lstrSql & " `nome` = '" & lstrNom & "', "
            lstrSql = lstrSql & " `preco_medio_mwh` = " & Replace(Replace(Me.txtValor.Text, ".", ""), ",", ".") & ", "
            lstrSql = lstrSql & " `cons_id` = " & llngCId & ", "
            lstrSql = lstrSql & " `unid_id` = " & llngUId & " "
            If lblnExi Then
                lstrSql = lstrSql & " WHERE `referencia` = " & CInt(VB6.Format(Me.dtpMesAno.Value, "YYYYMM")) & " "
                lstrSql = lstrSql & "   AND `cons_id` = " & llngCId
                lstrSql = lstrSql & "   AND `unid_id` = " & llngUId
            End If

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            PreencherGrid()




        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 frmCadPrecoMedioLivre_FormClosed(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed

        Try

            If Not vfrmOld Is Nothing Then
                vfrmOld.Enabled = True
            End If

            vfrmOld = Nothing

        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

            Close()

        Catch ex As Exception
            Exit Sub
        End Try

    End Sub

    Public Sub SetaParametros(ByRef afrmQuemChama As System.Windows.Forms.Form, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal alngUnidId As Integer, ByVal astrGrupo As String)


        Try


            If Not vfrmOld Is Nothing Then

                vfrmOld = afrmQuemChama

                SetaCodigo(alngUnidId, astrZona, astrLivro, astrConta, astrGrupo)

                vfrmOld.Enabled = False

                Me.cmdLocalizar.Enabled = False

            End If


        Catch ex As Exception
            Exit Sub
        End Try



    End Sub

    Public Sub SetaCodigo(ByVal alngUnidId As Integer, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal astrGrupo As String)

        Dim lstrSql As String

        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            Me.txtNome.Text = ""

            lstrSql = ""
            lstrSql = lstrSql & "SELECT `cons_id`, `unid_id`, `nome`, `ta` " & vbCrLf
            lstrSql = lstrSql & "  FROM `uc_faturamento` " & vbCrLf
            lstrSql = lstrSql & " WHERE `zona`  = '" & astrZona & "' " & vbCrLf
            lstrSql = lstrSql & "   AND `livro` = '" & astrLivro & "' " & vbCrLf
            lstrSql = lstrSql & "   AND `conta` = '" & astrConta & "' "
            lstrSql = lstrSql & "   AND `ta` = '01AL00' "

            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    Me.txtNome.Text = IIf(IsDBNull(row("nome")), "", row("nome"))
                    ilngUnidId = IIf(IsDBNull(row("unid_id")), 0, row("unid_id"))
                    ilngConsId = IIf(IsDBNull(row("cons_id")), 0, row("cons_id"))

                    Me.txtZona.Text = astrZona
                    Me.txtLivro.Text = astrLivro
                    Me.txtConta.Text = astrConta

                    Me.txtTa.Text = IIf(IsDBNull(row("ta")), "01AL00", row("ta"))

                Next

            Else
                MessageBox.Show("Este consumidor não é Livre.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)


            End If


            MontaGrid()
            PreencherGrid()


        Catch ex As Exception
            Exit Sub
        End Try


    End Sub

    Private Sub MontaGrid()


        Try

            With Me.mfgDados
                .Rows = 1
                .Cols = 6
                Call .Clear()
                .set_TextMatrix(0, 0, "Referência")
                .set_TextMatrix(0, 1, "CNPJ")
                .set_TextMatrix(0, 2, "Nome")
                .set_TextMatrix(0, 3, "Valor MWh")
                .set_TextMatrix(0, 4, "cons_id")
                .set_TextMatrix(0, 5, "unid_id")
                .set_ColWidth(0, 1000)
                .set_ColWidth(1, 0)
                .set_ColWidth(2, 0)
                .set_ColWidth(3, 1000)
                .set_ColWidth(4, 0)
                .set_ColWidth(5, 0)
            End With


        Catch ex As Exception
            Exit Sub
        End Try



    End Sub

    Private Sub PreencherGrid()

        Dim llngRef As Integer
        Dim lstrCpj As String
        Dim lstrNom As String
        Dim ldblVlr As Double
        Dim llngCId As Integer
        Dim llngUId As Integer
        Dim lstrSql As String




        Dim dt As DataTable


        Dim objAtualizaBancoDados As New entidadeAtualizaBancoDados
        Dim repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados


        Try

            MontaGrid()

            lstrSql = ""
            lstrSql = lstrSql & "SELECT CONVERT(IFNULL(`precomediolivre`.`cnpj`,`unida`.`cpf_cnpj`) USING Latin1) `cnpj`, "
            lstrSql = lstrSql & "       IFNULL(`precomediolivre`.`referencia`," & VB6.Format(Me.dtpMesAno.Value, "yyyyMM") & ") `referencia`, "
            lstrSql = lstrSql & "       `precomediolivre`.`preco_medio_mwh`, "
            lstrSql = lstrSql & "       `unida`.`nome`, "
            lstrSql = lstrSql & "       `unida`.`cons_id`, "
            lstrSql = lstrSql & "       `unida`.`unid_id` "
            lstrSql = lstrSql & "  FROM `unida` "
            lstrSql = lstrSql & " LEFT JOIN `precomediolivre` ON(`precomediolivre`.`unid_id` = `unida`.`unid_id` AND "
            lstrSql = lstrSql & "                                `precomediolivre`.`cons_id` = `unida`.`cons_id`) "
            lstrSql = lstrSql & " WHERE `unida`.`zona` = '" & Me.txtZona.Text & "' "
            lstrSql = lstrSql & "   AND `unida`.`livro` = '" & Me.txtLivro.Text & "' "
            lstrSql = lstrSql & "   AND `unida`.`conta` = '" & Me.txtConta.Text & "' "
            lstrSql = lstrSql & "   AND `unida`.`cons_id` = " & ilngConsId & " "
            lstrSql = lstrSql & "   AND `unida`.`unid_id` = " & ilngUnidId & " "
            lstrSql = lstrSql & " ORDER BY `referencia` DESC "


            objAtualizaBancoDados.QUERY_NAME = lstrSql
            dt = repositorioAtualizaBancoDados.Consultar(objAtualizaBancoDados)


            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    llngRef = CInt(IIf(IsDBNull(row("referencia")), "0", row("referencia")))

                    lstrCpj = Trim(IIf(IsDBNull(row("cnpj")), "", row("cnpj")))

                    lstrNom = Trim(IIf(IsDBNull(row("nome")), "", row("nome")))

                    ldblVlr = CDbl(IIf(IsDBNull(row("preco_medio_mwh")), "0", row("preco_medio_mwh")))

                    llngCId = CInt(IIf(IsDBNull(row("cons_id")), "0", row("cons_id")))

                    llngUId = CInt(IIf(IsDBNull(row("unid_id")), "0", row("unid_id")))

                    With Me.mfgDados
                        .Rows = .Rows + 1
                        .set_TextMatrix(.Rows - 1, 0, Microsoft.VisualBasic.Right(CStr(llngRef), 2) & "/" & Microsoft.VisualBasic.Left(CStr(llngRef), 4))
                        .set_TextMatrix(.Rows - 1, 1, lstrCpj)
                        .set_TextMatrix(.Rows - 1, 2, lstrNom)
                        .set_TextMatrix(.Rows - 1, 3, VB6.Format(ldblVlr, "#,##0.00"))
                        .set_TextMatrix(.Rows - 1, 4, llngCId)
                        .set_TextMatrix(.Rows - 1, 5, llngUId)
                    End With

                Next

            End If



        Catch ex As Exception
            Exit Sub
        End Try

    End Sub



#End Region


End Class