Imports System.Data.SqlClient

Public Class usrCntlBesuchsberichte

    Public kdnr As Integer = -1
    Dim SQL As New SQL
    Dim dgvInitWait As Boolean = False
    Public kdNr_filter As Boolean = False
    Dim txtchanged As Boolean = False
    Dim fullyPainted = False

    Private Sub usrCntlBesuchsberichte_Load(sender As Object, e As EventArgs) Handles Me.Load

        initDGV()

    End Sub


    Sub initDGV(Optional doFilter = False)

        Dim SQLCmd = "SELECT TOP (200) [bb_Id],[bb_DatumBesuch],[bb_KundenNr],[bb_Kunde] ,[bb_Anpsprechpartner] ,[bb_Vermerk],[bb_Sachbearbeiter] FROM [VERAG].[dbo].[tblBesuchsberichte] WHERE bb_Firma='" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA & "' " & If(kdnr > 0, " AND bb_KundenNr='" & kdnr & "'", "")

        If doFilter Then
            newBinding(SQLCmd, doFilter)
        Else
            initFilter()
            With dgvBesuchsberichte

                .SET_SQL(SQLCmd, "FMZOLL")

                .LOAD()

            End With
        End If

        With dgvBesuchsberichte

            If .Columns.Count > 0 Then
                .Columns("bb_DatumBesuch").Width = 150
                .Columns("bb_DatumBesuch").HeaderText = "Datum"

                .Columns("bb_Sachbearbeiter").Width = 150
                .Columns("bb_Sachbearbeiter").HeaderText = "Sachbearbeiter"

                .Columns("bb_Kunde").Width = 200
                .Columns("bb_Kunde").HeaderText = "Firma"

                .Columns("bb_KundenNr").Width = 50
                .Columns("bb_KundenNr").HeaderText = "KdNr"

                .Columns("bb_Anpsprechpartner").Width = 150
                .Columns("bb_Anpsprechpartner").HeaderText = "Anpsprechpartner"

                .Columns("bb_Vermerk").MinimumWidth = 150
                .Columns("bb_Vermerk").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                .Columns("bb_Vermerk").HeaderText = "Vermerk"
                .Columns("bb_Id").Visible = False

            End If

        End With

        btnDelete.Enabled = False

        lblEinträge.Text = dgvBesuchsberichte.RowCount & " Einträge"

    End Sub

    Private Sub dgvBesuchsberichteDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBesuchsberichte.CellDoubleClick
        Try
            Dim bb_id = dgvBesuchsberichte.Rows(e.RowIndex).Cells("bb_id").Value
            Dim f As New frmBesuchsberichte(bb_id)
            f.ShowDialog(Me)
            initDGV()
        Catch ex As Exception
            MsgBox(ex.Message)
            'MsgBox(ex.StackTrace)
        End Try
    End Sub


    Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
        Dim f As New frmBesuchsberichte(-1, kdnr)
        f.ShowDialog(Me)
        initDGV()

    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        If dgvBesuchsberichte.SelectedRows.Count > 0 Then
            If vbYes = MsgBox("Möchten Sie den Eintrag wirklich löschen?", vbYesNoCancel) Then
                If VERAG_PROG_ALLGEMEIN.cBesuchsbericht.DELETE(dgvBesuchsberichte.SelectedRows(0).Cells("bb_id").Value) Then
                    initDGV()
                End If
            End If
        End If
    End Sub

    Private Sub dgvBesuchsberichte_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBesuchsberichte.CellClick
        If dgvBesuchsberichte.SelectedRows.Count > 0 Then
            btnDelete.Enabled = True
        End If

    End Sub


    Private Sub dgvBesuchsberichte_SelectionChanged(sender As Object, e As EventArgs) Handles dgvBesuchsberichte.SelectionChanged

    End Sub

    Private Sub dgvFILTER_SelectionChanged(sender As Object, e As EventArgs) Handles dgvFILTER.SelectionChanged
        dgvFILTER.ClearSelection()
    End Sub

    Private Sub dgvFILTER_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvFILTER.CellContentClick
        If dgvFILTER.Columns(e.ColumnIndex).GetType Is GetType(DataGridViewCheckBoxColumn) Then
            dgvBesuchsberichte.Focus()
        End If
    End Sub


    Private Sub dgvFILTER_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvFILTER.CellValueChanged
        initDGV(True)

    End Sub

    Sub initFilter()
        dgvInitWait = True

        dgvFILTER.RowTemplate.Height = dgvFILTER.Height
        If Not Me.fullyPainted Then Exit Sub ' nur wenn die usrcntl komplett gelden wurde...
        Try
            dgvFILTER.Columns.Clear()
        Catch ex As Exception

        End Try
        For Each c As DataGridViewColumn In dgvBesuchsberichte.Columns
            Dim cNew As DataGridViewColumn = c.Clone
            'MsgBox("Create Filter Column " & cNew.HeaderText)

            cNew.MinimumWidth = c.Width
            dgvFILTER.Columns.Add(cNew)
            If cNew.GetType Is GetType(DataGridViewCheckBoxColumn) Then
                DirectCast(cNew, DataGridViewCheckBoxColumn).ThreeState = True
                DirectCast(cNew, DataGridViewCheckBoxColumn).DefaultCellStyle.NullValue = CheckState.Indeterminate
            End If
        Next

        If dgvFILTER IsNot Nothing AndAlso dgvFILTER.ColumnCount > 0 Then
            dgvFILTER.Rows.Add()
            dgvFILTER.Width = dgvBesuchsberichte.Width
        End If

        dgvInitWait = False

    End Sub

    Function getSqlText(t) As String
        Try
            Return t.Replace("'", "")
        Catch ex As Exception
            Return ""
        End Try
    End Function


    Function getFilter() As String

        Dim filter As String = ""
        Dim andstr As String = ""

        If dgvFILTER.RowCount > 0 Then
            For Each c As DataGridViewCell In dgvFILTER.Rows(0).Cells
                If c.Value IsNot DBNull.Value Then
                    If c.GetType Is GetType(DataGridViewTextBoxCell) Then
                        If c.Value IsNot Nothing AndAlso c.Value <> "" Then
                            Dim srchstr = getSqlText(c.Value.ToString.Trim)
                            If c.OwningColumn.Name.Contains("SDLNr") Then
                                filter &= andstr & " SDL.[" & c.OwningColumn.Name & "] LIKE '%" & srchstr & "%' "
                            ElseIf c.OwningColumn.Name.Contains("IDS-KdNr") Then
                                filter &= andstr & " (SELECT TOP 1 [CustomerCode] FROM [VERAG].[dbo].[tbl_IDS_Kunden]  WHERE [KdNrVERAG]=KundenNr AND KdNrAlt =0  ORDER BY Zeitstempel DESC)  LIKE '%" & srchstr & "%'  "
                            ElseIf IsDate(srchstr) Then
                                If srchstr.ToLower = "ist null" Then
                                    filter &= andstr & "( [" & c.OwningColumn.Name & "] is null ) "
                                Else
                                    filter &= andstr & " convert(varchar,[" & c.OwningColumn.Name & "] ,104) LIKE '%" & srchstr & "%' "
                                End If
                            Else
                                If srchstr.ToLower = "ist null" Then
                                    filter &= andstr & "( [" & c.OwningColumn.Name & "] LIKE '' OR  [" & c.OwningColumn.Name & "] is null ) "
                                Else
                                    filter &= andstr & " [" & c.OwningColumn.Name & "] LIKE '%" & srchstr & "%' "
                                End If
                            End If
                            andstr = " AND "
                        End If
                    ElseIf c.GetType Is GetType(DataGridViewCheckBoxCell) Then
                        If c.Value IsNot Nothing AndAlso c.Value.ToString <> "" Then
                            If c.Value = CheckState.Checked Then
                                filter &= andstr & " SDL.[" & c.OwningColumn.Name & "] =1 "
                                andstr = " AND "
                            ElseIf c.Value = CheckState.Unchecked Then
                                filter &= andstr & " SDL.[" & c.OwningColumn.Name & "] =0 "
                                andstr = " AND "
                            End If
                        End If
                    End If

                End If
            Next
        End If

        Return filter
    End Function


    Protected Overrides Sub WndProc(ByRef m As Message)
        MyBase.WndProc(m)
        If m.Msg = 15 AndAlso Not fullyPainted Then
            fullyPainted = True

            initDGV()
            initFilter()
        End If
    End Sub

    Sub newBinding(ByVal sql As String, doFilter As Boolean)
        dgvInitWait = True
        ' bindingSDL = Nothing
        dgvBesuchsberichte.Columns.Clear()
        dgvBesuchsberichte.VirtualMode = True
        txtchanged = True
        dgvInitWait = True
        If doFilter Then
            Dim filter As String = getFilter()

            If filter <> "" Then sql &= " AND " & filter
            ' sql &= " ORDER BY sdl.[Erfassungsdatum] ASC"
        Else
            '  clearFilter()
        End If
        If kdNr_filter And kdnr > 0 Then sql &= " AND KundenNr=" & kdnr



        'Sortierung der tabl-DS
        'sql &= " ORDER BY sdl.[Bestelldatum] , sdl.[Erfassungsdatum] ASC ,sdl.ts"


        'dgvBesuchsberichte.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
        '  dgvSDL.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing '; //or even better .DisableResizing. Most time consumption enum is DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders

        'dgvBesuchsberichte.SET_SQL(sql, "SDL", , {"KundenNr", "KfzKennzeichen", "SDLNr", "History"})

        dgvBesuchsberichte.SET_SQL(sql, "FMZOLL")

        dgvBesuchsberichte.LOAD()

        dgvInitWait = False
        txtchanged = False
        dgvInitWait = False
        dgvBesuchsberichte.ClearSelection()


        If dgvBesuchsberichte.RowCount > 0 Then dgvBesuchsberichte.Rows(0).Cells(0).Selected = True

        dgvBesuchsberichte_SelectionChanged(Me, New EventArgs)

    End Sub

End Class
