Imports System.Data.SqlClient

Public Class usrCntlKunden
    Dim SQL As New SQL
    Dim dtSource As DataTable
    Public dgvkundenisReady As Boolean = False

    Dim dgvInitWait As Boolean

    Dim kundenSQL As New kundenSQL
    Private bindingSDL As New BindingSource
    Private dataAdapterLKW As New SqlDataAdapter

    Dim aktuelleSeite As Integer = 1
    Dim zeilenProSeite As Integer = 50

    Dim BERECHTIGUNEN As List(Of cBerechtigungen) = cBerechtignungenFunctions.loadBerechtigungen(VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)

    Private Sub usrCntlKunden_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim usrCntl As New usrCntlKundeDetails
        Panel1.Controls.Add(usrCntl)
        usrCntl.Dock = System.Windows.Forms.DockStyle.Fill

        initDGV()
        initDGVButtons()
        dgvkundenisReady = True
        txtSearch.Focus()

    End Sub
    Public Sub setenable()
        'dgvkundenisReady = True
    End Sub
    Sub initDGVButtons()
        'Dim b = New Button : b.Text = "A"
        'Dim b2 = New Button : b2.Text = "B"
        'Panel3.Controls.Add(b)
        'Panel3.Controls.Add(b2)
        Dim left As Integer = 0
        Dim b As VERAG_PROG_ALLGEMEIN.FlatButton

        For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜ".ToCharArray()
            b = New VERAG_PROG_ALLGEMEIN.FlatButton : b.Text = c : b.Width = 20
            '  b.ForeColor = Color.White
            b.Left = left : left += 25
            Panel3.Controls.Add(b)
            AddHandler b.Click, AddressOf buttonClick
        Next
        b = New VERAG_PROG_ALLGEMEIN.FlatButton : b.Text = "123" : b.Width = 35
        '  b.ForeColor = Color.White
        b.Left = left : left += 25
        Panel3.Controls.Add(b)
        AddHandler b.Click, AddressOf buttonClick
    End Sub

    Sub buttonClick(sender As Object, e As EventArgs)
        ' MsgBox(sender.text)
        txtSearch.Text = ""
        initDGV(sender.text)
    End Sub
    Sub initDGV(Optional alphabet As String = "")
        If dgvkundenisReady Then
            Dim start As Long = CLng((DateTime.Now - New DateTime(1970, 1, 1)).TotalMilliseconds)

            showDGV(alphabet)

            Dim ende As Long = CLng((DateTime.Now - New DateTime(1970, 1, 1)).TotalMilliseconds)
            frmMain.setLoadingTime("Ladezeit: " & (ende - start) & " ms")
        End If
        dgvKunden_SelectionChanged(dgvKunden, New System.EventArgs)
    End Sub

    Sub showDGV(Optional alphabet As String = "")
        Dim sqlstr As String
        sqlstr = "SELECT  Auswahl,Abfertigungsverbot,Ordnungsbegriff,KundenNr,LandKz, Ort FROM Kunden  INNER JOIN Adressen ON Adressen.AdressenNr=Kunden.KundenNr "
        Dim andstr As String = ""
        Dim where As String = ""
        If txtSearch.Text <> "" Then
            where &= andstr & " ( [Name 1] LIKE @search OR [Name 2] LIKE @search OR Ordnungsbegriff LIKE @search OR Ort LIKE @search  OR KundenNr LIKE @search  ) "
            andstr = " AND "
        End If

        If alphabet = "123" Then
            where &= andstr & " Ordnungsbegriff LIKE '[0-9]%' "
            andstr = " AND "
        ElseIf alphabet <> "" Then
            where &= andstr & " Ordnungsbegriff LIKE '" & alphabet & "%' "
            andstr = " AND "
        End If
        If Not cbxAbfVerbot.CheckState = CheckState.Indeterminate Then
            where &= andstr & " Abfertigungsverbot = '" & cbxAbfVerbot.Checked & "' "
            andstr = " AND "
        End If

        If cbxOnlyAkt.Checked Then
            where &= andstr & " Auswahl = 'A' "
            andstr = " AND "
        End If


        If where <> "" Then sqlstr += " WHERE ( " & where & ") "
        sqlstr += " ORDER BY Ordnungsbegriff ASC"
        Dim sqlCmd As New SqlCommand(sqlstr)
        sqlCmd.Parameters.AddWithValue("@search", "%" & txtSearch.Text & "%")
        initSDLBinding(sqlCmd)
        dtSource = dtSource
        aktuelleSeite = 1
        initSeiten()
        LoadPage()
    End Sub

    Private Sub initSDLBinding(bindingString As SqlCommand)
        dgvkundenisReady = False
        Dim d As New SqlDataAdapter()
        Try
            bindingString.Connection = cSqlDb.GetNewOpenConnectionFMZOLL 'REAL 'New SqlConnection(cSqlDb.GetSDLConnectionString)
            Me.dataAdapterLKW = New SqlDataAdapter(bindingString)
        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)
        dtSource = New DataTable()
        Me.dataAdapterLKW.Fill(dtSource)
        dtSource.Locale = System.Globalization.CultureInfo.InvariantCulture
        dgvKunden.DataBindings.Clear()
        bindingSDL.DataSource = dtSource
        dgvkundenisReady = True

    End Sub
    Sub initSeiten()
        Panel4.Controls.Clear()
        Dim seiten As Integer = Math.Ceiling(dtSource.Rows.Count / zeilenProSeite)
        ' MsgBox(dtSource.Rows.Count & " / " & zeilenProSeite & "= " & seiten)
        Dim lblSeite As New Label
        lblSeite.Text = "Seite: "
        lblSeite.Width = 45
        lblSeite.Name = "lblSeite"
        lblSeite.Top = 5 : lblSeite.Left = 2
        Panel4.Controls.Add(lblSeite)

        Dim left As Integer = 50
        Dim top As Integer = lblSeite.Top


        If seiten > 50 Then
            seiten = 50
            Dim lblEtc As New Label
            lblEtc.Text = "..."
            lblEtc.Width = 20
            lblEtc.Top = 5 : lblEtc.Left = (50 * 20) + left
            Panel4.Controls.Add(lblEtc)
        End If


        Dim l As LinkLabel
        For i = 0 To seiten - 1 Step 1
            l = New LinkLabel
            l.Left = left
            l.Top = top
            l.ForeColor = Color.FromArgb(0, 54, 128)
            l.Width = 20
            l.Text = (i + 1)
            AddHandler l.Click, AddressOf SeiteWechseln
            Panel4.Controls.Add(l)
            left += 20
        Next

    End Sub
 
    Private Sub LoadPage()

        Dim von As Integer = (aktuelleSeite - 1) * zeilenProSeite
        Dim bis As Integer = von + zeilenProSeite
        Dim startRec As Integer = 0

        Dim dtTemp As DataTable
        dtTemp = dtSource.Clone()
       
        If dtSource.Rows.Count > 0 Then
            If dtSource.Rows.Count < bis Then bis = dtSource.Rows.Count
            For cnt As Integer = von To bis - 1
                dtTemp.ImportRow(dtSource.Rows(cnt))
            Next
        End If

        dgvKunden.DataSource = dtTemp

    End Sub


    Sub setColumns()
        With dgvKunden
            '.RowTemplate.Height = 20
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .RowTemplate.ReadOnly = True
            .RowHeadersVisible = False
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect

            .AllowUserToOrderColumns = True

            .Columns("Abfertigungsverbot").Width = 70
            .Columns("Abfertigungsverbot").HeaderText = "Abf.-Verbot"
            .Columns("Abfertigungsverbot").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("Auswahl").Width = 40
            .Columns("Auswahl").HeaderText = "Aktiv"
            .Columns("Auswahl").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("Ordnungsbegriff").MinimumWidth = 250
            .Columns("Ordnungsbegriff").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("Ordnungsbegriff").HeaderText = "Firmenname"

            .Columns("KundenNr").Width = 100
            .Columns("KundenNr").HeaderText = "Kunden-Nr"
            
            .Columns("LandKz").Width = 40
            .Columns("LandKz").HeaderText = "Land"

            .Columns("Ort").Width = 200
            .Columns("Ort").HeaderText = "Ort"

        End With
    End Sub

    'Eigenschaften für einzelne Felder
    Private Sub setCoustomProperties()
        With dgvKunden
            For Each r As DataGridViewRow In .Rows
                If Not r.Cells("Abfertigungsverbot").Value Is DBNull.Value AndAlso CBool(r.Cells("Abfertigungsverbot").Value) Then
                    r.DefaultCellStyle.ForeColor = Color.Red
                End If
            Next
            Exit Sub
            For i As Integer = 0 To .RowCount - 1
                If (Not .Rows(i).Cells("Abfertigungsverbot").Value Is DBNull.Value) Then
                    If CBool(.Rows(i).Cells("Abfertigungsverbot").Value) = True Then
                        ' .Item(0, i).Style.BackColor = Color.IndianRed ' deaktive Firmen werden mit einem roten Hintergrund in der Spalte 'deakt' angezeigt

                        .Item(0, i).Style.BackColor = Color.Red
                        .Item(0, i).Style.ForeColor = Color.Red
                        .Item(1, i).Style.ForeColor = Color.Red
                        .Item(2, i).Style.ForeColor = Color.Red
                        .Item(3, i).Style.ForeColor = Color.Red
                    End If
                End If
            Next
        End With
    End Sub



    Private WithEvents timShow As New Timer With {.Interval = 500}
    Private Sub txtSearch_KeyUp(sender As Object, e As EventArgs) Handles txtSearch.TextChanged, txtSearch.KeyDown
        '  timShow.Stop()
        ' timShow.Start()
    End Sub
    Private Sub txtSearch_KeyDown(sender As Object, e As EventArgs) Handles txtSearch.Enter, txtSearch.Leave
        '  initDGV()
        '   timShow.Stop()
    End Sub
    Private Sub txtSearch_KeyUp(sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown
        If e.KeyData = Keys.Enter Then
            e.SuppressKeyPress = True
            initDGV()
            timShow.Stop()
        End If
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timShow.Tick
        timShow.Stop()
        initDGV()
    End Sub



    Private Sub usrCntlKunden_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        '  Panel1.Width = frmMain.Width() - 900

    End Sub

    Private Sub btnSuche2_Click(sender As Object, e As EventArgs) Handles btnSuche2.Click, cbxOnlyAkt.CheckedChanged, cbxAbfVerbot.CheckedChanged
        initDGV()
    End Sub

    Private Sub btnAlle_Click(sender As Object, e As EventArgs) Handles btnAlle.Click
        txtSearch.Text = ""
        initDGV() : timShow.Stop()
    End Sub

    Private Sub DataGridView1_RowPostPaint(sender As Object, e As DataGridViewRowPostPaintEventArgs) Handles dgvKunden.RowPostPaint
        setColumns()
        setCoustomProperties()
    End Sub


    Private Sub dgvKunden_SelectionChanged(sender As Object, e As System.EventArgs) Handles dgvKunden.Click
        'AndAlso Not dgvKunden.SelectedRows Is Nothing
        Try
            If dgvkundenisReady AndAlso dgvKunden.SelectedRows.Count > 0 Then
                clrPnlMain()
                Dim usrCntl As New usrCntlKundeDetails
                usrCntl.kdNr = dgvKunden.SelectedRows(0).Cells("KundenNr").Value
                Panel1.Controls.Add(usrCntl)
                usrCntl.Dock = System.Windows.Forms.DockStyle.Fill
                usrCntl.initSDLListeRed()
            End If

        Catch ex As Exception

        End Try
    End Sub

    Private Sub clrPnlMain()
        While Panel1.HasChildren
            Panel1.Controls.RemoveAt(0)
        End While
    End Sub

    Private Sub cbxAbfVerbot_CheckedChanged(sender As Object, e As EventArgs) Handles cbxAbfVerbot.CheckStateChanged
        initDGV()
    End Sub

    Private Sub dgvKunden_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvKunden.CellDoubleClick

        If dgvKunden.SelectedRows.Count > 0 Then
            If Not IsNumeric(dgvKunden.SelectedRows(0).Cells("KundenNr").Value) Then
                frmMain.setInfo("info", "Bitte wählen Sie einen Kunden aus der Liste.", 3)
            Else
                '  pic.Visible = True
                cProgramFunctions.openKundenblatt(dgvKunden.SelectedRows(0).Cells("KundenNr").Value, Me.FindForm, True)
                ' pic.Visible = False
                ' Dim pf As New cProgramFunctions
                'pf.openKundenblatt(dgvKunden.SelectedRows(0).Cells(2).Value, True)
            End If
        End If
    End Sub

    Private Sub SeiteWechseln(sender As Object, e As EventArgs)
        aktuelleSeite = sender.text
        LoadPage()
    End Sub

    Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click

        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kundendaten_bearbeiten", "SDL") Then
            Dim frmKundenblatt As New SDL.frmKundenblatt
            frmKundenblatt.showEdit = True
            frmKundenblatt.kdNr = -1
            'frmKundenblatt.BERECHTIGUNEN = BERECHTIGUNEN
            frmKundenblatt.ShowDialog(Me)
            initDGV()
        Else
            Dim frmKd As New SDL.frmNeuerKunde
            frmKd.openKd = False
            frmKd.timerIntervall = 500
            frmKd.username = VERAG_PROG_ALLGEMEIN.cGlobal.AktiverMitarbeiter.mit_username
            If frmKd.username.Length > 15 Then frmKd.username = frmKd.username.Substring(0, 15)
            '    frmKd.tmpFiliale = VERAG_PROG_ALLGEMEIN.cGlobal.AktiverMitarbeiter.StandartFiliale
            '  frmKd.tmpKdNrKreis = 9
            frmKd.ShowDialog()

            'OPEN!
            If frmKd.kdnr > 0 Then
                initDGV()
            End If
        End If


    End Sub

    Private Sub FlatButton3_Click(sender As Object, e As EventArgs) Handles FlatButton3.Click
        Dim kdsrch As New SDL.frmKundenSuche
        kdsrch.erweitern = True
        If kdsrch.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
            cProgramFunctions.openKundenblatt(kdsrch.kundenNrSearch.Text, Me.FindForm, True)
        Else
            frmMain.setInfo("info", "Sie haben keine Berichtigung für diese Funktion.", 3)
        End If
    End Sub
End Class
