Imports System.Data.SqlClient

Public Class usrCntlLkwListe


    Dim kundenSQL As New kundenSQL
    Private bindingSDL As New BindingSource
    Private dataAdapterLKW As New SqlDataAdapter
    Dim SQL As New SQL
    Dim FUNC As New cProgramFunctions
    Dim bindingString As String
    Dim aktbtn As String = ""
    Dim dgvInitWait As Boolean = False


    Sub init()
        pnlFilter.AutoScroll = False
        Me.dgvLkw.DataSource = Me.bindingSDL
        newBinding("SELECT KundenNr, KfzKennzeichen, Nationalität, Baujahr, Verkauft,KZAenderung, Abgemeldet, KzMiete , KzLeasing,[KzFinanzierungBank] , Vermerk, Erfassungsdatum, Änderungsdatum, Sachbearbeiter FROM LKW WHERE 1=1 ")

    End Sub

    Private Sub usrCntlVERAGCard_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' btnFilter.Left = Panel4.Width - btnFilter.Width
       
        init()

        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", Me.FindForm) Then
            FlatButton1.Enabled = False
            FlatButton2.Enabled = False
            Button14.Enabled = False
        End If
        '   Panel3.Height = Me.Height / 2 + 300
    End Sub

    Private Sub dgvLkw_KeyDown(sender As Object, e As KeyEventArgs) Handles dgvLkw.KeyDown
        If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then
            dgvLKW_SelectionChanged(dgvLkw, New EventArgs)
        End If
    End Sub

    Private Sub dgvLKW_SelectionChanged(sender As Object, e As EventArgs) Handles dgvLkw.SelectionChanged ', dgvLKW.CellContentClick
        If dgvLkw.SelectedCells.Count > 0 AndAlso Not dgvLkw.selectedrowS(0).Cells(1).Value Is DBNull.Value Then

            Dim kd As cKunden = kundenSQL.getKundeByKdNr(dgvLkw.selectedrowS(0).Cells(0).Value)
            lblFirma.Text = kd.Kurzname
            '    Panel3.Controls.Clear()

            Dim usrCntlLKW As usrCntlLKW
            If Panel3.Controls.Count > 0 Then
                usrCntlLKW = Panel3.Controls(0)
            Else
                usrCntlLKW = New usrCntlLKW

                AddHandler usrCntlLKW.LKWChanged, Sub(kdNr, newKfz, SDLNr, History)
                                                      dgvLKW_SelectionChanged(dgvLkw, New EventArgs)
                                                      Exit Sub
                                                      MsgBox("!!")
                                                      init()
                                                      dgvLkw.ClearSelection()
                                                      For Each r As DataGridViewRow In dgvLkw.Rows
                                                          If r.Cells("KfzKennzeichen").Value = newKfz Then
                                                              r.Selected = True
                                                              Exit For
                                                          End If
                                                      Next
                                                  End Sub


                AddHandler usrCntlLKW.btnPrevLKW.Click, AddressOf prevLKW
                AddHandler usrCntlLKW.btnNextLKW.Click, AddressOf nextLKW
                Panel3.Controls.Add(usrCntlLKW)
                usrCntlLKW.Dock = DockStyle.Fill
            End If
            Dim nat = ""
            Try : nat = dgvLkw.selectedrowS(0).Cells(2).Value
            Catch : End Try
            usrCntlLKW.init(dgvLkw.SelectedRows(0).Cells(0).Value, dgvLkw.SelectedRows(0).Cells(1).Value, nat, FUNC.checkDbNullStr(dgvLkw.SelectedRows(0).Cells(7).Value), FUNC.checkDbNullStr(dgvLkw.SelectedRows(0).Cells(8).Value), FUNC.checkDbNullStr(dgvLkw.SelectedRows(0).Cells(9).Value))


        End If
    End Sub
    Sub nextLKW(sender As Object, e As EventArgs)
        Dim i As Integer = dgvLkw.selectedrowS(0).Index
        '  MsgBox(i)
        If (i + 1 < dgvLkw.RowCount) Then
            'dgvLKW.ClearSelection() 'dgvLKW.Rows(i + 1).Selected = True
            '  dgvLKW.Rows(i + 1).Selected = True
            dgvLkw.CurrentCell = dgvLkw.Item(1, i + 1)
            dgvLkw.Rows(i + 1).Selected = True
        End If

    End Sub
    Sub prevLKW(sender As Object, e As EventArgs)
        Dim i As Integer = dgvLkw.selectedrowS(0).Index
        ' MsgBox(i)
        If (i > 0) Then
            ' dgvLKW.Rows(i - 1).Selected = True
            'dgvLKW.Rows(i).Selected = False
            dgvLkw.CurrentCell = dgvLkw.Item(1, i - 1)
            dgvLkw.Rows(i - 1).Selected = True
        End If
    End Sub



    Sub newBinding(ByVal sql As String)
        dgvInitWait = True
        ' bindingSDL = Nothing
        dgvLkw.Columns.Clear()
        txtchanged = True
        clearFilter()
        setBindingstring(sql)
        initSDLBinding()
        initAllg()
        initFilter()
        txtchanged = False
        dgvInitWait = False
        If dgvLkw.RowCount > 0 Then dgvLkw.Rows(0).Cells(0).Selected = True
        dgvSDL_SelectionChanged(dgvLkw, New EventArgs)
    End Sub


    Private Sub initSDLBinding()
        dgvInitWait = True
        Dim sqlstr As String = bindingString
        ' dgvLKW.DataSource = bindingSDL
        Dim d As New SqlDataAdapter()
        Try
            Dim connectionString As String = cSqlDb.GetSDLConnectionString

            Dim filter As String = getFilter()
            If filter <> "" Then sqlstr &= " AND " & filter

            Me.dataAdapterLKW = New SqlDataAdapter(sqlstr, connectionString)
        Catch ex As SqlException
            MessageBox.Show("Der Connection-String kann nicht verarbeitet werden. Wenden Sie sich an den Programmbetreuer.")
        End Try
        Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapterLKW)
        Dim table As New DataTable()
        Me.dataAdapterLKW.Fill(table)
        '   table.Columns("KundenNr").DefaultValue = kdNr
        table.Locale = System.Globalization.CultureInfo.InvariantCulture
        'bindingSDL.Clear()
        dgvLkw.DataBindings.Clear()
        bindingSDL.DataSource = table
        dgvInitWait = False
    End Sub

    Sub initFilter()
        dgvInitWait = True
        Dim left_value As Integer = 40 - dgvLkw.HorizontalScrollingOffset
        pnlFilter.Controls.Clear()
        Dim l As New Label
        l.Left = left_value - 38 : l.Top = 12
        l.Width = 36 : l.Text = "Filter:"
        pnlFilter.Controls.Add(l)

        If dgvLkw.Rows.Count > 0 Then
            For i As Integer = 0 To dgvLkw.ColumnCount - 1 Step 1
                Dim c As DataGridViewColumn = dgvLkw.Columns(i)
                If c.Visible Then '
                    Try
                        If c.ValueType.Name = "Boolean" Then
                            Dim t As New CheckBox
                            t.Left = left_value
                            t.Top = 10
                            t.CheckAlign = ContentAlignment.MiddleCenter
                            t.ThreeState = True
                            t.CheckState = CheckState.Indeterminate
                            t.Name = "cbxSrch_" & c.Name
                            AddHandler t.CheckStateChanged, AddressOf initSearch
                            t.Width = c.Width
                            pnlFilter.Controls.Add(t)
                        End If
                        If c.ValueType.Name = "String" Or c.ValueType.Name = "Int32" Or c.ValueType.Name = "Decimal" Then
                            Dim t As New TextBox
                            t.Left = left_value
                            t.Top = 10
                            t.Name = "txtSrch_" & c.Name
                            '  AddHandler t.TextChanged, AddressOf initSearch
                            AddHandler t.KeyDown, Sub(send As Object, ev As KeyEventArgs)
                                                      If ev.KeyCode = Keys.Return Or ev.KeyCode = Keys.Tab Then ev.SuppressKeyPress = True : initSearch(send, New EventArgs)
                                                  End Sub

                            t.Width = c.Width
                            pnlFilter.Controls.Add(t)
                        End If
                        If c.ValueType.Name = "DateTime" Then
                            Dim t As New TextBox
                            t.Left = left_value
                            t.Top = 10
                            t.Name = "datSrch_" & c.Name
                            '  AddHandler t.TextChanged, AddressOf initSearch
                            AddHandler t.KeyDown, Sub(send As Object, ev As KeyEventArgs)
                                                      If ev.KeyCode = Keys.Return Or ev.KeyCode = Keys.Tab Then ev.SuppressKeyPress = True : initSearch(send, New EventArgs)
                                                  End Sub
                            t.Width = c.Width
                            pnlFilter.Controls.Add(t)
                        End If
                        left_value += c.Width

                    Catch ex As Exception

                    End Try
                End If
            Next
        End If
        dgvInitWait = False
    End Sub
    Dim txtchanged As Boolean = False
    Sub initSearch(sender As Object, e As EventArgs)
        txtchanged = True
        initSDLBinding()
        initAllg()
        txtchanged = False
        Try
            If dgvLkw.RowCount > 0 Then dgvLkw.Rows(0).Cells(0).Selected = True
            dgvSDL_SelectionChanged(dgvLkw, New EventArgs)
        Catch ex As Exception
        End Try

    End Sub

    Function getFilter() As String
        Dim filter As String = ""
        Dim andstr As String = ""
        If pnlFilter.HasChildren Then
            For Each c In pnlFilter.Controls
                If c.GetType.Name = "TextBox" Then
                    Try
                        Dim t As TextBox = DirectCast(c, TextBox)
                        If t.Text <> "" Then
                            If t.Name.Contains("txtSrch_") Then
                                filter &= andstr & " [" & t.Name.Replace("txtSrch_", "") & "] LIKE '%" & t.Text & "%' "
                                andstr = " AND "
                            End If
                            If t.Name.Contains("datSrch_") AndAlso t.Text.Length = 10 Then
                                filter &= andstr & " ( [" & t.Name.Replace("datSrch_", "") & "] BETWEEN '" & t.Text & "' AND '" & t.Text & "' ) "
                                andstr = " AND "
                            End If

                        End If
                    Catch ex As Exception
                    End Try
                ElseIf c.GetType.Name = "CheckBox" Then
                    Try
                        Dim t As CheckBox = DirectCast(c, CheckBox)
                        If Not t.CheckState = CheckState.Indeterminate Then
                            filter &= andstr & " [" & t.Name.Replace("cbxSrch_", "") & "] = '" & t.CheckState & "' "
                            andstr = " AND "
                        End If

                    Catch ex As Exception
                    End Try
                End If
            Next
            '  Me.bindingSDL = New BindingSource
            '   Me.dgvSDL.DataSource = Me.bindingSDL
        End If
        Return filter
    End Function

    Sub clearFilter()
        If pnlFilter.HasChildren Then
            pnlFilter.Controls.Clear()
        End If
    End Sub


    Private Sub dgvSDL_ColumnWidthChanged(sender As Object, e As DataGridViewColumnEventArgs) Handles dgvLkw.ColumnWidthChanged
        If Not txtchanged Then initFilter()
    End Sub

    Sub setBindingstring(ByVal b As String)
        bindingString = b
    End Sub

    Sub initAllg()
        With dgvLkw
            .RowTemplate.Height = 20
            .AllowUserToOrderColumns = False
            .AllowUserToResizeRows = False

            .Columns("Vermerk").MinimumWidth = 150
            .Columns("Erfassungsdatum").Width = 150
            .Columns("Änderungsdatum").Width = 150
            .Columns("Sachbearbeiter").Width = 150
            .Columns("KundenNr").Width = 150

            .Columns("Erfassungsdatum").ReadOnly = True
            .Columns("Änderungsdatum").ReadOnly = True
            .Columns("Sachbearbeiter").ReadOnly = True

            .Columns("Vermerk").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("KfzKennzeichen").AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
            .Columns("Vermerk").Width = 250
            .Columns("Verkauft").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns("KZAenderung").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter

            .Columns("KzMiete").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns("KzMiete").HeaderText = "Miete"

            .Columns("KzLeasing").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns("KzLeasing").HeaderText = "Leasing"

            .Columns("KzFinanzierungBank").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns("KzFinanzierungBank").HeaderText = "Finanz.Bank"

            .Columns("Abgemeldet").Visible = False
            '.Columns("Abgemeldet").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter

        End With

    End Sub

    Private Sub dgvLKW_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvLkw.CellValueChanged
        btnUpdate.Enabled = True
    End Sub
    Private Sub dgvSDL_SelectionChanged(sender As Object, e As EventArgs) Handles dgvLkw.SelectionChanged

    End Sub

    Private Sub btnUpdate2_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
        Try
            Me.dataAdapterLKW.Update(CType(Me.bindingSDL.DataSource, DataTable))
            sender.Enabled = False
        Catch ex As Exception
            MsgBox("Es ist ein Fehler aufgetreten: " & ex.Message)
        End Try
    End Sub

    Private Sub lblFirma_Click(sender As Object, e As EventArgs) Handles lblFirma.Click
        If dgvLkw.SelectedCells.Count > 0 Then
            If dgvLkw.selectedrowS(0).Cells(0).Value > 0 Then
                cProgramFunctions.openKundenblatt(dgvLkw.selectedrowS(0).Cells(0).Value, Me.FindForm, True)
                'Dim pf As New cProgramFunctions
                'pf.openKundenblatt(dgvLkw.selectedrowS(0).Cells(0).Value)
            End If
        End If
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        cProgramFunctions.genExcelFromDGV(dgvLkw, True)
    End Sub



    Private Sub dgvLKW_RowHeaderMouseDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvLkw.CellDoubleClick
        Dim frmGrayOut = cProgramFunctions.grayoutForm(Me)
        Dim l As New frmLKWDetails(dgvLkw.Rows(e.RowIndex).Cells("KundenNr").Value, dgvLkw.Rows(e.RowIndex).Cells("KfzKennzeichen").Value)
        If l.ShowDialog(frmGrayOut) = DialogResult.OK Then
            initSearch(New Object, New EventArgs)
        End If
        frmGrayOut.Close()
    End Sub

    Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", Me.FindForm) Then
            MsgBox("Keine Berechtigung!")
            Exit Sub
        End If

        Dim frmGrayOut = cProgramFunctions.grayoutForm(Me)
        Dim l As New frmLKWDetails(-1, "", True)
        If l.ShowDialog(frmGrayOut) = DialogResult.OK Then
            initSearch(New Object, New EventArgs)
        End If
        frmGrayOut.Close()
    End Sub

    Private Sub FlatButton2_Click_1(sender As Object, e As EventArgs) Handles FlatButton2.Click
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", Me.FindForm) Then
            MsgBox("Keine Berechtigung!")
            Exit Sub
        End If
        If dgvLkw.SelectedRows.Count > 20 Then MsgBox("Es können nicht mehr als 20 Zeilen gelöscht werden!") : Exit Sub
        If dgvLkw.SelectedRows.Count = 0 Then Exit Sub
        Dim txt As String = "Möchten Sie den Eintrag / die Einträge wirklich löschen?" & vbNewLine & vbNewLine
        For Each r As DataGridViewRow In dgvLkw.SelectedRows
            txt &= r.Cells("KfzKennzeichen").Value & vbNewLine
        Next
        If vbYes = MsgBox(txt, vbYesNoCancel) Then
            For Each r As DataGridViewRow In dgvLkw.SelectedRows
                Dim kdTMP = r.Cells("KundenNr").Value
                Dim kfzKzTMP = r.Cells("KfzKennzeichen").Value
                SQL.doSQL("DELETE TOP (1) FROM LKW WHERE KundenNr='" & kdTMP & "' AND  KfzKennzeichen='" & kfzKzTMP & "'", "SDL", True)
                SQL.doSQL("DELETE FROM SDL WHERE KundenNr='" & kdTMP & "' AND  KfzKennzeichen='" & kfzKzTMP & "' and SDLNr <> '501' ", "SDL", True)
                usrCntlSDLLeistungVERAGCard.clearAllVeragCard(kdTMP, kfzKzTMP)
                '  SQL.doSQL("UPDATE FROM SDL WHERE KundenNr='" & kdTMP & "' AND  KfzKennzeichen='" & kfzKzTMP & "' and SDLNr <> '501' ", "SDL", True)
                'SQL.doSQL("UPDATE [Kartenpool] SET [KundenNr]=NULL, [KfzKennzeichen]=NULL, [Fahrer]=NULL, [Datum]=NULL, [Kaution]=NULL, [BelegNr]=NULL, [Ersatzkarte]=NULL, [Gesperrt]=0, [Defekt]=0, [Verloren]=0, [Gestohlen]=0, [Vermerk]='', [Änderungsdatum]='" & Now & "', [Sachbearbeiter]='" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME & "' WHERE KundenNr='" & kdTMP & "' AND  KfzKennzeichen='" & kfzKzTMP & "'", "SDL", True)
            Next
            initSearch(New Object, New EventArgs)
        End If 'DEL
    End Sub

   

End Class
