Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms

'Imports System.Threading

Public Class KdSearchBox
    Inherits System.Windows.Forms.TextBox
    Implements INotifyPropertyChanged

    ' Dim sql As New SDL.SQL
    ' Dim KUNDENSQL As New SDL.kundenSQL
    Dim form As Form = Me.FindForm
    'Public KdData As SDL.cKundenFMZOLL
    Public KdData_KUNDE As cKunde = Nothing
    Public KdData_ADRESSEN As cAdressen = Nothing
    Public KdData_KUNDE_ERW As cKundenErweitert = Nothing

    Public Property searchActive As Boolean = True
    Public Property _AllowSetValue As Boolean = False
    Public Property _displayFullName As Boolean = False ' nur wenn _loadKdData
    Public Property _display_Name1 As Boolean = False ' nur wenn _loadKdData

    Public Property _ValueKdAndName As Boolean = True
    Public Property _loadKdData As Boolean = False

    Public Property _hideIfListEmpty As Boolean = True
    Public Property _displayWoelflKd As Boolean = False
    Public Property _displayAVISO_Email As Boolean = False
    Public Property nurAktive As Boolean = True
    Public Property kdNrField As Control = Nothing
    Public Property dgvpos As String = "LEFT"
    Public Property _autoSizeGross As Boolean = False
    Public Property _AlleFirmenCLUSTER As Boolean = False
    Public Property _UseFIRMA As String = ""

    Dim last_search As DateTime = Now
    Dim last_eingabe As DateTime = Now
    Public Property TIMER_SEARCH As Boolean = True
    Dim Eingabe_verarbeitet = True
    Dim WithEvents tmr_Search As New Timer


    Public usrcntlWIDTH = 600
    Public usrcntlHEIGHT = 380

    Public WithEvents usrcntl As usrcntlKdSearch '= DirectCast(Me.FindForm.Controls.Find("dgvFindKD", False)(0), DataGridView)

    '    Public WithEvents dgv As DataGridView
    ' Public WithEvents dgvInaktiv As DataGridView

    Dim SQL As New SQL

    Public Sub FireReturn()
        dgvFindKD_Click(Me, New KeyEventArgs(Keys.Return))
    End Sub

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        Try
            MyBase.OnPaint(e)
        Catch ex As Exception
            Me.Invalidate()
        End Try
    End Sub

    Private Sub KdSearchBox_GotFocus(sender As Object, e As EventArgs) Handles Me.GotFocus
        Try
            Me.SelectionLength = 0
            Me.HideSelection = False
            Me.SelectAll()
            Me.Select()
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_01")
        End Try
    End Sub

    Public Sub RESARCH()
        KdSearchBox_KeyUp(Me, New KeyEventArgs(Keys.Space))
    End Sub

    Private Sub KdSearchBox_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
        Try
            'Console.WriteLine(String.Format("TEEST 01"))
            If Not searchActive Then Exit Sub

            ' If dgv Is Nothing Then dgv = usrcntl.dgvKundenAktiv
            ' If dgvInaktiv Is Nothing Then dgvInaktiv = usrcntl.dgvKundenInAktiv


            If e.KeyCode = Keys.Tab Then
                If usrcntl IsNot Nothing Then usrcntl.Visible = False
                e.Handled = True
                Exit Sub
            End If

            If e.KeyCode = Keys.ShiftKey Or e.KeyCode = Keys.Shift Or e.KeyCode = Keys.Alt Or e.KeyCode = Keys.Control Or e.KeyCode = Keys.Left Or e.KeyCode = Keys.Right Or e.KeyCode = Keys.End Or e.KeyCode = Keys.Home Or e.KeyCode = Keys.CapsLock Then 'Bei Shift Tab..
                If usrcntl IsNot Nothing Then usrcntl.Visible = False
                e.Handled = True
                Exit Sub
            End If


            If e.KeyCode = Keys.Return Then

                e.Handled = True
                Exit Sub
            End If

            If e.KeyCode = Keys.Up Then
                If usrcntl IsNot Nothing Then prevLKW(usrcntl.dgvKundenAktiv)
                e.Handled = True
                Exit Sub
            End If
            If e.KeyCode = Keys.Down Then
                If usrcntl IsNot Nothing Then nextLKW(usrcntl.dgvKundenAktiv)
                e.Handled = True
                Exit Sub
            End If
            If e.KeyCode = Keys.Escape Then
                hideDgv(usrcntl)
                e.Handled = True
                Exit Sub
            End If




            If kdNrField IsNot Nothing Then kdNrField.Text = ""

            KdNr_value = -1
            KdData_KUNDE = Nothing
            KdData_ADRESSEN = Nothing
            KdData_KUNDE_ERW = Nothing

            If Me.Text.Trim = "" Then
                KdNr = -1
                KdName = ""
                ' KdData = Nothing
                KdData_KUNDE = Nothing
                KdData_ADRESSEN = Nothing
                KdData_KUNDE_ERW = Nothing
                setMeValue()
                hideDgv(usrcntl)
                Exit Sub
            End If

            If usrcntl Is Nothing Then
                Exit Sub
            End If

            Eingabe_verarbeitet = False
            last_eingabe = Now

            doKeyDown(Now)

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_02")
        End Try
    End Sub

    Sub doKeyDown(srchdate As DateTime)
        Try
            If usrcntl Is Nothing Then Exit Sub
            If Eingabe_verarbeitet Then Exit Sub ' Bereits abgearbetiet -> Timer

            Dim span_last_search = CInt(DirectCast((srchdate - last_search), TimeSpan).TotalMilliseconds)
            Dim span_last_eingabe = CInt(DirectCast((srchdate - last_eingabe), TimeSpan).TotalMilliseconds)

            'TIMER_SEARCH
            If TIMER_SEARCH Then
                If span_last_search < 500 And span_last_eingabe < 500 Then
                    Exit Sub
                End If
            End If


            If usrcntl.Visible = False Then
                usrcntl.Width = usrcntlWIDTH
                usrcntl.Height = usrcntlHEIGHT

                Dim locationOnForm As Point = Nothing
                If Me.FindForm IsNot Nothing Then
                    If dgvpos = "LEFT" Or dgvpos = "" Then
                        locationOnForm = Me.FindForm().PointToClient(Me.Parent.PointToScreen(Me.Location))
                    ElseIf dgvpos = "RIGHT" Then
                        locationOnForm = Me.FindForm().PointToClient(Me.Parent.PointToScreen(Me.Location))
                        locationOnForm.X = locationOnForm.X - (usrcntl.Width - Me.Width)
                    End If
                End If


                If locationOnForm.Y + usrcntl.Height + Me.Height > form.ClientRectangle.Height Then
                    usrcntl.Height = form.ClientRectangle.Height - locationOnForm.Y - Me.Height
                End If

                usrcntl.Location = locationOnForm
                usrcntl.Top += Me.Height
            End If

            If usrcntl IsNot Nothing AndAlso usrcntl.dgvKundenAktiv IsNot Nothing Then

                With usrcntl.dgvKundenAktiv

                    If usrcntl.Visible = False Then
                        .AllowUserToAddRows = False
                        .AllowUserToDeleteRows = False
                        .AllowUserToOrderColumns = False
                        .AllowUserToResizeColumns = False
                        .AllowUserToResizeRows = False
                        .ReadOnly = True
                        .MultiSelect = False
                        .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                        .BackgroundColor = Color.White
                        .ForeColor = Color.Black
                        Try
                            .GridColor = Color.White
                        Catch ex As Exception
                            'Keine Ahnung warum hier ein Fehler kommt
                        End Try

                    End If


                    'THREADING AKTIV
                    Me.ThreadInitAKTIV()
                    ' Dim ThreadInitAKTIV = New System.Threading.Thread(AddressOf Me.ThreadInitAKTIV)
                    ' ThreadInitAKTIV.IsBackground = True
                    ' ThreadInitAKTIV.Start()

                End With
            End If

            If nurAktive Then
            usrcntl.dgvKundenInAktiv.Visible = False
            usrcntl.Panel1.Visible = False
        Else
                If usrcntl IsNot Nothing AndAlso usrcntl.dgvKundenInAktiv IsNot Nothing Then

                    With usrcntl.dgvKundenInAktiv
                        If usrcntl.Visible = False Then
                            .AllowUserToAddRows = False
                            .AllowUserToDeleteRows = False
                            .AllowUserToOrderColumns = False
                            .AllowUserToResizeColumns = False
                            .AllowUserToResizeRows = False
                            .ReadOnly = True
                            .MultiSelect = False
                            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                            .BackgroundColor = Color.White
                            .ForeColor = Color.Black
                            Try
                                .GridColor = Color.White
                            Catch ex As Exception
                                'Keine Ahnung warum hier ein Fehler kommt
                            End Try
                            .DefaultCellStyle.ForeColor = Color.Gray
                        End If


                        Me.ThreadInitINAKTIV()
                        'THREADING INAKTIV
                        'Dim ThreadInitINAKTIV = New System.Threading.Thread(AddressOf Me.ThreadInitINAKTIV)
                        'ThreadInitINAKTIV.IsBackground = True
                        'ThreadInitINAKTIV.Start()

                    End With

                End If
            End If

            If _hideIfListEmpty Then

            If usrcntl.dgvKundenAktiv.RowCount = 0 And usrcntl.dgvKundenInAktiv.RowCount = 0 Then
                setObjectVisible(usrcntl, False)
            Else
                setObjectVisible(usrcntl, True)
            End If
            If False Then

                'THREADING ThreadWaitAndSee
                Dim ThreadWaitAndSee = New System.Threading.Thread(Sub()
                                                                       Threading.Thread.Sleep(200)
                                                                       If usrcntl.dgvKundenAktiv.RowCount = 0 And usrcntl.dgvKundenInAktiv.RowCount = 0 Then
                                                                           setObjectVisible(usrcntl, False)
                                                                       Else
                                                                           setObjectVisible(usrcntl, True)
                                                                       End If
                                                                   End Sub)
                ThreadWaitAndSee.IsBackground = True
                ThreadWaitAndSee.Start()
            End If
        Else
            usrcntl.Visible = True
            usrcntl.Show()
            usrcntl.BringToFront()
        End If
        Eingabe_verarbeitet = True
        last_search = Now

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
    End Sub

    Public Sub hideDgv(o) '(sender As Object, e As EventArgs)
        If o IsNot Nothing Then
            Me.searchActive = False
            o.visible = False
            Me.searchActive = True
        End If
    End Sub


    Sub ThreadInitAKTIV()
        Try
            If usrcntl Is Nothing Then Exit Sub
            If usrcntl.dgvKundenAktiv Is Nothing Then Exit Sub
            With usrcntl.dgvKundenAktiv

                Dim srch As String = Me.Text.Replace("'", "").ToString.Trim
                If srch.StartsWith("*") Then srch = Replace(srch, "*", "%", , 1) ' Suche mit beginnenden *

                Dim srch2 As String = ""
                If srch.Contains(",") Then
                    Dim spitter() = srch.Split(",")
                    srch = spitter(0).ToString.Trim
                    srch2 = spitter(1).ToString.Trim
                End If
                If srch2.StartsWith("*") Then srch2 = Replace(srch2, "*", "%", , 1) ' Suche mit beginnenden *

                Dim topAnz = 10
                If nurAktive Then topAnz = 16
                Dim AvisoEmail = ""
                If _displayAVISO_Email Then
                    AvisoEmail = ", (SELECT CASE WHEN Count(*)>0 Then 'JA' ELSE '' END [Adressen] FROM [tblEmailBenachrichtigung] WHERE [eb_KundenNr]=AdressenNr) as [E-Mail] "
                End If
                Dim SQLstr As String = " SELECT top " & topAnz & " Ordnungsbegriff as Firma, AdressenNr as KdNr,Adressen.[LandKz] + ' ' + Adressen.[PLZ] + ' - ' + Adressen.[Ort] + ' ' + Adressen.[Straße] as Adresse " & AvisoEmail & "    "
                If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "FRONTOFFICE" Or VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERIMEX" Or _AlleFirmenCLUSTER Or _UseFIRMA <> "" Or VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AVISO_IMEX", "AVISO") Or VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_VERAGIMEX", "SDL") Then SQLstr &= ",  Filialen.Firma as Firma_Intern "
                SQLstr &= " FROM [Adressen] "
                SQLstr &= "  INNER JOIN Kunden on KundenNr=AdressenNr  "
                SQLstr &= "  INNER JOIN Filialen on Filialen.FilialenNr=isnull(Kunden.FilialenNr,4803) "
                SQLstr &= "  WHERE 1=1 "
                SQLstr &= " AND (  "
                SQLstr &= "   Ordnungsbegriff LIKE '" & srch & "%'   " : If IsNumeric(srch) Then SQLstr &= "  OR AdressenNr LIKE '" & srch & "%'   "
                SQLstr &= "   ) "
                If srch2 <> "" Then SQLstr &= " AND (Filialen.Firma LIKE '" & srch2 & "%' OR ( Adressen.PLZ LIKE '" & srch2 & "%' OR Adressen.Ort LIKE '" & srch2 & "%' OR Adressen.LandKz LIKE '" & srch2 & "%' OR Adressen.Straße LIKE '" & srch2 & "%' )) "
                SQLstr &= "  AND [Auswahl]='A' "

                'If VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER <> "" Then
                '    SQLstr &= "  AND (Filialen.Firma='" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA & "' OR Filialen.CLUSTER='" & VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER & "')  "
                'Else
                '    SQLstr &= "  AND Filialen.Firma='" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA & "'  "
                'End If

                If _AlleFirmenCLUSTER Then
                    SQLstr &= "  AND '" & VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER & "' IN (Filialen.Firma,Filialen.Cluster) " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                ElseIf _UseFIRMA <> "" Then
                    SQLstr &= "  AND '" & _UseFIRMA & "' IN (Filialen.Firma,Filialen.Cluster) " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                Else
                    SQLstr &= "  AND ( '" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA.Replace("ATILLA", "VERAG") & "' IN (Filialen.Firma,Filialen.Cluster) " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                    If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AVISO_IMEX", "AVISO") Then
                        SQLstr &= "  OR  Filialen.Firma IN ('IMEX') " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                    End If
                    If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_VERAGIMEX", "SDL") Then
                        SQLstr &= "  OR  Filialen.Firma IN ('IMEX','VERAG') " ' Wenn die OFFERTE_FREMD_VERAGIMEX --> Beide
                    End If
                    If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_UNISPED_BREXIT", "SDL") Then
                        SQLstr &= "  OR  (Filialen.Firma IN ('UNISPED') AND Kunden.[FilialenNr]=7002) " ' Wenn die OFFERTE_FREMD_VERAGIMEX --> Beide
                    End If
                    If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("FAKTURIERUNG_FRONTOFFICE", "SDL") Then
                        SQLstr &= "  OR  Filialen.Firma IN ('FRONTOFFICE') " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                    End If
                    SQLstr &= "  ) "
                End If

                'AUSNAHME BIS BESSERE LÖSUNG:
                If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "FRONTOFFICE" Then
                    SQLstr &= "  and Filialen.Firma NOT IN ('AMBAR') "
                End If


                'If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "FRONTOFFICE" Then 'Keine
                '    SQLstr &= "  AND isnull(Kunden.[FilialenNr],0) NOT IN ('5701') "
                'ElseIf VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA <> "VERAG" And VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA <> "ATILLA" Then
                '    SQLstr &= "  AND Kunden.[FilialenNr]='" & VERAG_PROG_ALLGEMEIN.cAllgemein.STAMMFILIALE & "' "
                'Else
                '    'SQLstr &= "  AND isnull(Kunden.[FilialenNr],0)<>'5501' "
                '    SQLstr &= "  AND isnull(Kunden.[FilialenNr],0) NOT IN ('5501','5601','5701','5801') "
                'End If
                If Not _displayWoelflKd Then SQLstr &= "  AND AdressenNr NOT LIKE '15%'"
                SQLstr &= " order by Ordnungsbegriff "

                setDS(usrcntl.dgvKundenAktiv, SQL.loadDgvBySql(SQLstr, "FMZOLL"))

            End With

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_03")
        End Try
    End Sub

    Sub ThreadInitINAKTIV()
        Try
            If usrcntl Is Nothing Then Exit Sub
            If usrcntl.dgvKundenInAktiv Is Nothing Then Exit Sub
            With usrcntl.dgvKundenInAktiv

                Dim srch As String = Me.Text.Replace("'", "").ToString.Trim
                If srch.StartsWith("*") Then srch = Replace(srch, "*", "%", , 1) ' Suche mit beginnenden *

                Dim srch2 As String = ""
                If srch.Contains(",") Then
                    Dim spitter() = srch.Split(",")
                    srch = spitter(0).ToString.Trim
                    srch2 = spitter(1).ToString.Trim
                End If
                If srch2.StartsWith("*") Then srch2 = Replace(srch2, "*", "%", , 1) ' Suche mit beginnenden *

                Dim SQLstr As String = " SELECT top 4 Ordnungsbegriff as Firma, AdressenNr as KdNr,Adressen.[LandKz] + ' ' + Adressen.[PLZ] + ' - ' + Adressen.[Ort] + ' ' + Adressen.[Straße] as Adresse   "
                If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "FRONTOFFICE" Or VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERIMEX" Or _AlleFirmenCLUSTER Or _UseFIRMA <> "" Or VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AVISO_IMEX", "AVISO") Or VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_VERAGIMEX", "SDL") Then SQLstr &= ",  Filialen.Firma as Firma_Intern  "
                SQLstr &= " FROM [Adressen] "
                SQLstr &= "  INNER JOIN Kunden on KundenNr=AdressenNr  "
                SQLstr &= "  INNER JOIN Filialen on Filialen.FilialenNr=isnull(Kunden.FilialenNr,4803) "
                SQLstr &= "  WHERE 1=1 "
                SQLstr &= " AND (  "
                SQLstr &= "   Ordnungsbegriff LIKE '" & srch & "%'   " : If IsNumeric(srch) Then SQLstr &= "  OR AdressenNr LIKE '" & srch & "%'   "
                SQLstr &= "   ) "
                If srch2 <> "" Then SQLstr &= " AND (Filialen.Firma LIKE '" & srch2 & "%' OR ( Adressen.PLZ LIKE '" & srch2 & "%' OR Adressen.Ort LIKE '" & srch2 & "%' OR Adressen.LandKz LIKE '" & srch2 & "%' OR Adressen.Straße LIKE '" & srch2 & "%' )) "
                SQLstr &= "  AND [Auswahl]='I' "
                'If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "FRONTOFFICE" Then 'Keine
                '    SQLstr &= "  AND isnull(Kunden.[FilialenNr],0) NOT IN ('5701') "
                'ElseIf VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA <> "VERAG" And VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA <> "ATILLA" Then
                '    SQLstr &= "  AND Kunden.[FilialenNr]='" & VERAG_PROG_ALLGEMEIN.cAllgemein.STAMMFILIALE & "' "
                'Else
                '    'SQLstr &= "  AND isnull([FilialenNr],0)<>'5501' "
                '    SQLstr &= "  AND isnull(Kunden.[FilialenNr],0) NOT IN ('5501','5601','5701','5801') "
                'End If

                'If VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER <> "" Then
                '    SQLstr &= "  AND (Filialen.Firma='" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA & "' OR Filialen.CLUSTER='" & VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER & "')  "
                'Else
                '    SQLstr &= "  AND Filialen.Firma='" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA & "'  "
                'End If

                If _AlleFirmenCLUSTER Then
                    SQLstr &= "  AND '" & VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER & "' IN (Filialen.Firma,Filialen.Cluster) " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                ElseIf _UseFIRMA <> "" Then
                    SQLstr &= "  AND '" & _UseFIRMA & "' IN (Filialen.Firma,Filialen.Cluster) " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                Else
                    SQLstr &= "  AND ( '" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA.Replace("ATILLA", "VERAG") & "' IN (Filialen.Firma,Filialen.Cluster) " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                    If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AVISO_IMEX", "AVISO") Then
                        SQLstr &= "  OR  Filialen.Firma IN ('IMEX') " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                    End If
                    If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_VERAGIMEX", "SDL") Then
                        SQLstr &= "  OR  Filialen.Firma IN ('IMEX','VERAG') " ' Wenn die OFFERTE_FREMD_VERAGIMEX --> Beide
                    End If
                    If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_UNISPED_BREXIT", "SDL") Then
                        SQLstr &= "  OR  (Filialen.Firma IN ('UNISPED') AND Kunden.[FilialenNr]=7002) " ' Wenn die OFFERTE_FREMD_VERAGIMEX --> Beide
                    End If
                    If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("FAKTURIERUNG_FRONTOFFICE", "SDL") Then
                        SQLstr &= "  OR  Filialen.Firma IN ('FRONTOFFICE') " ' Wenn die Firmenbezeichnung im CLUSter vorkommt .--> Frontoffice
                    End If
                    SQLstr &= "  ) "
                End If


                'AUSNAHME BIS BESSERE LÖSUNG:
                If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "FRONTOFFICE" Then
                    SQLstr &= "  and Filialen.Firma NOT IN ('AMBAR') "
                End If

                If Not _displayWoelflKd Then SQLstr &= "  AND AdressenNr NOT LIKE '15%'"
                SQLstr &= " order by Ordnungsbegriff "

                setDS(usrcntl.dgvKundenInAktiv, SQL.loadDgvBySql(SQLstr, "FMZOLL"))

            End With

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_04")
        End Try
    End Sub

    'threadsicherer Aufruf
    '   Delegate Sub setLabelCallback(l As DataGridView, t As DataTable)
    Private Sub setDS(l As DataGridView, t As DataTable)
        Try
            If l Is Nothing Then Exit Sub
            If t Is Nothing Then Exit Sub
            ''  If Me.InvokeRequired Then
            'Dim d As New setLabelCallback(AddressOf setDS)
            ' Me.Invoke(d, New Object() {l, t})
            ' Else
            With l
                .Columns.Clear()
                .DataSource = t
                If .ColumnCount = 0 Then Exit Sub

                .RowHeadersVisible = False

                If .Columns("KdNr") IsNot Nothing AndAlso .Columns("KdNr") IsNot DBNull.Value Then .Columns("KdNr").Width = 60 : .Columns("KdNr").HeaderText = "KundenNr"
                If .Columns("Firma") IsNot Nothing AndAlso .Columns("Firma") IsNot DBNull.Value Then .Columns("Firma").Width = 250
                If .Columns("Adresse") IsNot Nothing AndAlso .Columns("Adresse") IsNot DBNull.Value Then .Columns("Adresse").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                If .Columns("E-Mail") IsNot Nothing AndAlso .Columns("E-Mail") IsNot DBNull.Value Then .Columns("E-Mail").Width = 50 : .Columns("E-Mail").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
                If .Columns("Firma_Intern") IsNot Nothing AndAlso .Columns("Firma_Intern") IsNot DBNull.Value Then .Columns("Firma_Intern").Width = 60 : .Columns("Firma_Intern").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter : .Columns("Firma_Intern").HeaderText = ""

                .ClearSelection()
            End With
            '  End If

        Catch ex As Exception
            ' Try
            '       MsgBox("Es ist ein Fehler beim Kunden-Such-Feld aufgetreten 05: " & vbNewLine & vbNewLine & ex.Message)
            'Catch ex2 As Exception
            '    MsgBox("ERR", vbCritical)
            'End Try
        End Try

    End Sub

    'threadsicherer Aufruf
    'Delegate Sub setObjectVisibleCallback(l As Object, v As Boolean)
    Private Sub setObjectVisible(l As Object, v As Boolean)
        Try
            If l Is Nothing Then Exit Sub
            '    If Me.InvokeRequired Then
            '       Dim d As New setObjectVisibleCallback(AddressOf setObjectVisible)
            'Me.Invoke(d, New Object() {l, v})
            '   Else
            l.visible = v
            If v = True Then
                l.Show()
                l.BringToFront()
            End If
            ' End If
        Catch ex As Exception
            '   MsgBox("Es ist ein Fehler beim Kunden-Such-Feld aufgetreten 06: " & vbNewLine & vbNewLine & ex.Message)
        End Try
    End Sub


    Public Sub nextLKW(dgv As DataGridView) '(sender As Object, e As EventArgs)
        Try
            If dgv.SelectedRows.Count > 0 Then
                Dim i As Integer = dgv.SelectedRows(0).Index
                If (i + 1 < dgv.RowCount) Then
                    'dgv.CurrentCell = dgv.Item(2, i + 1)
                    dgv.ClearSelection()
                    dgv.Rows(i + 1).Selected = True
                End If
            Else
                If dgv.Rows.Count > 0 Then ' dgv.CurrentCell = dgv.Item(2, 0)
                    dgv.ClearSelection()
                    dgv.Rows(0).Selected = True
                End If
            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_03_1")
        End Try
    End Sub
    Public Sub prevLKW(dgv As DataGridView) '(sender As Object, e As EventArgs)
        Try
            If dgv.SelectedRows.Count > 0 Then
                Dim i As Integer = dgv.SelectedRows(0).Index
                If (i > 0) Then
                    'dgv.CurrentCell = dgv.Item(2, i - 1)
                    dgv.ClearSelection()
                    dgv.Rows(i - 1).Selected = True
                End If
            Else
                If dgv.Rows.Count > 0 Then 'dgv.CurrentCell = dgv.Item(2, dgv.Rows.Count - 1)
                    dgv.ClearSelection()
                    dgv.Rows(dgv.Rows.Count - 1).Selected = True
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_06")
        End Try
    End Sub


    Private Sub usrcntl_CLOSE(sender As Object, e As EventArgs) Handles usrcntl.CLOSE
        hideDgv(usrcntl)
    End Sub


    Private Sub dgvFindKD_Click(sender As Object, e As EventArgs) Handles usrcntl.DGV_Click
        Try
            If usrcntl IsNot Nothing AndAlso usrcntl.dgvKundenAktiv IsNot Nothing Then
                With usrcntl.dgvKundenAktiv
                    If .SelectedRows.Count > 0 Then
                        If IsNumeric(.SelectedRows(0).Cells("KdNr").Value) Then
                            KdNr = .SelectedRows(0).Cells("KdNr").Value
                            KdName = .SelectedRows(0).Cells("Firma").Value
                            setMeValue()
                            hideDgv(usrcntl)
                        End If
                    End If
                End With
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_07")
        End Try
    End Sub

    Private Sub dgvFindKD_Click2(sender As Object, e As EventArgs) Handles usrcntl.DGV_INAKTIV_Click
        Try
            If usrcntl IsNot Nothing AndAlso usrcntl.dgvKundenInAktiv IsNot Nothing Then
                With usrcntl.dgvKundenInAktiv
                    If .SelectedRows.Count > 0 Then
                        If IsNumeric(.SelectedRows(0).Cells("KdNr").Value) Then
                            KdNr = .SelectedRows(0).Cells("KdNr").Value
                            KdName = .SelectedRows(0).Cells("Firma").Value
                            setMeValue()
                            hideDgv(usrcntl)
                        End If
                    End If
                End With
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_08")
        End Try
    End Sub
    Private Sub TextBox1_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles Me.PreviewKeyDown
        Try

            If usrcntl IsNot Nothing AndAlso usrcntl.dgvKundenAktiv IsNot Nothing Then
                If e.KeyData = Keys.Tab And usrcntl.Visible Then ' wenn usrcntl eingeblendet, soll der TABULATOR als InputKey gesehen werden.
                    If usrcntl.dgvKundenAktiv.SelectedRows.Count > 0 Then e.IsInputKey = True Else usrcntl.Visible = False
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_09")
        End Try
    End Sub
    Private Sub dgvFindKD_Click(sender As Object, e As KeyEventArgs) Handles Me.KeyDown, usrcntl.DGV_KeyDown
        Try
            If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Tab Then
                last_search = Now.AddSeconds(-10)
                doKeyDown(Now) ' Damit Suche-Timer sicherausgelöst wurde
                ' System.Threading.Thread.Sleep(5000)
            End If


            If usrcntl IsNot Nothing AndAlso usrcntl.dgvKundenAktiv IsNot Nothing Then
                With usrcntl.dgvKundenAktiv
                    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Tab Then
                        If e.KeyCode = Keys.Return And .RowCount > 0 And .SelectedRows.Count = 0 Then .Rows(0).Selected = True
                        If .SelectedRows.Count > 0 Then
                            If IsNumeric(.SelectedRows(0).Cells("KdNr").Value) Then
                                KdNr = .SelectedRows(0).Cells("KdNr").Value
                                KdName = .SelectedRows(0).Cells("Firma").Value
                                setMeValue()
                                hideDgv(usrcntl)
                            End If
                        Else
                            usrcntl.Visible = False
                        End If
                        e.Handled = True
                        e.SuppressKeyPress = True

                    End If
                End With
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_10")
        End Try
    End Sub

    Private Sub dgvFindKD_Click2(sender As Object, e As KeyEventArgs) Handles usrcntl.DGV_KeyDown
        Try
            If usrcntl IsNot Nothing AndAlso usrcntl.dgvKundenInAktiv IsNot Nothing Then
                With usrcntl.dgvKundenInAktiv
                    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Tab Then
                        If .SelectedRows.Count > 0 Then
                            If IsNumeric(.SelectedRows(0).Cells("KdNr").Value) Then
                                KdNr = .SelectedRows(0).Cells("KdNr").Value
                                KdName = .SelectedRows(0).Cells("Firma").Value
                                setMeValue()
                                hideDgv(usrcntl)
                            End If
                        Else
                            usrcntl.Visible = False
                        End If

                        e.Handled = True
                        e.SuppressKeyPress = True

                    End If
                End With
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_11")
        End Try
    End Sub

    Sub reloadKdData()
        Me.KdData_KUNDE = New cKunde(KdNr_value)
        Me.KdData_ADRESSEN = New cAdressen(KdNr_value)
        Me.KdData_KUNDE_ERW = New cKundenErweitert(KdNr_value)

    End Sub

    Sub setMeValue()
        Try
            If Me.kdNrField IsNot Nothing Then Me.kdNrField.Text = IIf(Me.KdNr_value > 0, Me.KdNr_value, "")
            If _AllowSetValue Then
                If _loadKdData Then 'Kundendaten sollen mitgeladen werden...
                    '  Me.KdData = KUNDENSQL.getKundeFMZOLLByKdNr(KdNr_value)
                    Me.KdData_KUNDE = New cKunde(KdNr_value)
                    Me.KdData_ADRESSEN = New cAdressen(KdNr_value)
                    Me.KdData_KUNDE_ERW = New cKundenErweitert(KdNr_value)

                    If Me.KdData_ADRESSEN Is Nothing Then
                        KdName = ""
                        Me.Text = ""

                    Else
                        KdName = KdData_ADRESSEN.Ordnungsbegriff
                        If _ValueKdAndName Then
                            If KdNr_value > 0 Then

                                If _displayFullName Then
                                    Me.Text = KdNr_value & " - " & (Me.KdData_ADRESSEN.Name_1 & " " & Me.KdData_ADRESSEN.Name_2).Trim
                                ElseIf _display_Name1 Then
                                    Me.Text = KdNr_value & " - " & Me.KdData_ADRESSEN.Name_1
                                Else
                                    Me.Text = KdNr_value & " - " & KdName
                                End If
                            Else
                                KdName = ""
                                Me.Text = ""
                            End If
                            ' -1 |-| 
                            'If Me.Text.Trim = "-" Then Me.Text = ""
                            '    Me.Text = KdNr_value & " - " & IIf(_displayFullName, (Me.KdData_ADRESSEN.Name_1 & " " & Me.KdData_ADRESSEN.Name_2).Trim, KdName)
                        Else
                            If _displayFullName Then
                                Me.Text = (Me.KdData_ADRESSEN.Name_1 & " " & Me.KdData_ADRESSEN.Name_2).Trim
                            ElseIf _display_Name1 Then
                                Me.Text = Me.KdData_ADRESSEN.Name_1
                            Else
                                Me.Text = KdName
                            End If

                            ' Me.Text = IIf(_displayFullName, (Me.KdData_ADRESSEN.Name_1 & " " & Me.KdData_ADRESSEN.Name_2).Trim, KdName)
                        End If
                    End If
                Else '... wenn nicht sollte beim Binding auch KdName gesetzt sein, sonst wird dieser nicht geladen
                    If KdNr_value > 0 Then
                        ' If KdName = "" Then
                        KdName = SQL.getValueTxtBySql("SELECT Ordnungsbegriff FROM Adressen WHERE AdressenNr =" & KdNr_value, "FMZOLL")
                        If _ValueKdAndName Then
                            Me.Text = KdNr_value & " - " & KdName
                        Else
                            Me.Text = KdName
                        End If
                    Else
                        KdName = ""
                        Me.Text = ""
                    End If
                End If
                ' searchActive = False

            End If
            If Me.Text.Length > Me.MaxLength Then Me.Text = Me.Text.Substring(0, Me.MaxLength)
            Eingabe_verarbeitet = True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_12")
        End Try

    End Sub

    Public KdNr_value As Integer = -1 'Hier ist der richtige Wert drin...
    Public Property KdName As String 'Muss vom Typ String sein, sonst geht es nicht... (BINDING NULL VALUE)

    Public Property KdNr As String
        Get
            Return KdNr_value
        End Get
        Set(v As String)
            Try
                KdNr_value = IIf(IsNumeric(v), v, -1)
                OnPropertyChanged("KdNr")
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_14")
            End Try
        End Set
    End Property

    Public Sub setKdNrKeepName()
        Dim nameTmp = KdName
        KdNr = -1
        KdName = nameTmp
        Me.Text = nameTmp
    End Sub


    Public Function getFirma() As String
        If Me.KdData_KUNDE IsNot Nothing And KdNr_value > 0 Then
            Return VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(Me.KdData_KUNDE.FilialenNr,, "")
        End If
        Return ""
    End Function


    Public Function checkFirma(FirmaPruef As String) As Boolean
        Dim KdFirma = getFirma()
        If KdFirma <> "" And FirmaPruef <> "" And KdNr_value > 0 Then
            If KdFirma <> FirmaPruef Then
                Return False
            End If
        End If
        Return True
    End Function



    Public Property KdNrNullInt As Object
        Get
            If KdNr_value > 0 Then
                Return KdNr_value
            Else
                Return Nothing
            End If
            '    Return CObj(If(KdNr_value > 0, KdNr_value, Nothing))
        End Get
        Set(v As Object)
            'NIX...
        End Set
    End Property



    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Protected Sub OnPropertyChanged(ByVal name As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub


    Private Sub KdSearchBox_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Handles Me.PropertyChanged
        setMeValue()
    End Sub

    Sub initKdBox(control As Control, Optional kdNrBox As Control = Nothing)
        Try
            If control Is Nothing Then Exit Sub
            Me.form = control
            Me.usrcntl = New usrcntlKdSearch
            control.Controls.Add(usrcntl)

            If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERIMEX" Then
                _AlleFirmenCLUSTER = True
            End If

            'Me.usrcntl = usrcntl
            hideDgv(Me.usrcntl)
            If kdNrBox IsNot Nothing Then Me.kdNrField = kdNrBox


            tmr_Search.Interval = 200
            tmr_Search.Enabled = True
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_13")
        End Try
    End Sub



    Private Sub KdSearchBox_LostFocus(sender As Object, e As EventArgs) Handles Me.LostFocus
        'THREADING ThreadWaitAndSee
        Dim ThreadWaitAndSee = New System.Threading.Thread(Sub()
                                                               Try
                                                                   Threading.Thread.Sleep(300)
                                                                   ' MsgBox(Me.form.ActiveControl.Name)
                                                                   If Me.form Is Nothing Then Exit Sub
                                                                   If Me.form.ActiveControl Is Nothing Then Exit Sub
                                                                   If Me.form.ActiveControl IsNot Me Then
                                                                       setObjectVisible(usrcntl, False)
                                                                   End If
                                                               Catch ex As Exception

                                                               End Try
                                                           End Sub)
        ThreadWaitAndSee.IsBackground = True
        ThreadWaitAndSee.Start()

        Try
            If usrcntl IsNot Nothing AndAlso usrcntl.dgvKundenAktiv IsNot Nothing AndAlso usrcntl.dgvKundenInAktiv IsNot Nothing Then
                If usrcntl.dgvKundenAktiv.SelectedCells.Count = 0 And usrcntl.dgvKundenInAktiv.SelectedCells.Count = 0 Then
                    Me.SelectionLength = 0
                End If
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Kunden-Such-Feld aufgetreten!",,,, "ERR_KDS_LF")
        End Try
    End Sub



    Private Sub KdSearchBox_Layout(sender As Object, e As LayoutEventArgs) Handles Me.Layout
        If _autoSizeGross Then
            Me.CharacterCasing = Windows.Forms.CharacterCasing.Upper
            ' If Me.Text <> "" Then Me.Text = Me.Text.ToUpper
        End If
    End Sub

    Private Sub KdSearchBox_TextChanged(sender As Object, e As EventArgs) Handles Me.TextChanged
        If Me.Text.Length > Me.MaxLength Then Me.Text = Me.Text.Substring(0, Me.MaxLength)
    End Sub

    Private Sub tmr_Search_Tick(sender As Object, e As EventArgs) Handles tmr_Search.Tick
        If TIMER_SEARCH Then doKeyDown(Now)
    End Sub

End Class
