Imports System.Data.SqlClient

Imports SDL.EORI
'Imports Gemeinsames

Public Class frmKundenUebersichtZOLL
    'Implements INotifyPropertyChanged
    Public superuser As Boolean = False
    Dim KUNDE As VERAG_PROG_ALLGEMEIN.cKunde = Nothing
    Public KUNDE_ERW As VERAG_PROG_ALLGEMEIN.cKundenErweitert = Nothing
    Dim ADRESSE As VERAG_PROG_ALLGEMEIN.cAdressen = Nothing
    Dim AUFSCHUB As List(Of VERAG_PROG_ALLGEMEIN.cKundenAufschubkonten) = Nothing

    Public kdNr As Integer = -1
    Private dataAdapterFirma As New SqlDataAdapter
    ' Private dataFirma As New DataTable
    Private bindingFirma As New BindingSource
    Dim FISKAL As cFiskal_Daten = Nothing

    Private abfertigungsverbotText As String = ""
    Private gespraechsberichtText As String = ""
    Private korrAdresseText As String = ""
    Private firmenwortlautFiskal As String = ""
    Dim trennungBesonderheiten = False

    Dim f_bold = New Font(Me.Font.FontFamily, 8, FontStyle.Bold)
    Dim f_norm = New Font(Me.Font.FontFamily, 8, FontStyle.Regular)

    Dim WithEvents timerOP As New Timer

    Private loaded As Boolean = False
    Dim RG_MONAT As Date = CDate("01." & Now.Month & "." & Now.Year) '.AddMonths(-1)

    ' Dim cDATENSERVER As New VERAG_PROG_ALLGEMEIN.cDATENSERVER
    Dim cFormularManager As New VERAG_PROG_ALLGEMEIN.cFormularManager
    '  Dim BERECHTIGUNEN As List(Of cBerechtigungen)
    Dim WithEvents timer_EORI As New Timer()
    Dim f_EORI As Form

    Dim SQL As New SQL
    Dim cSqlDb As New cSqlDb
    Dim FUNC As New cProgramFunctions
    '  Public USRID As Integer = -1
    ' Public userfullname As String = ""
    'Public username As String = ""
    Dim db As New DataSet
    Dim WHEREStatistik = ""
    Public selectedTAB = ""
    Property BER_STUFE = 99

    Public Sub New()
        Try
            ' initialize added component on form1, which is menu strip;
            'note: if you have added any second component alongside menu
            'strip, such as context menu strip just add additional code 
            'line under InitializeComponent(), and it will work;
            InitializeComponent()
            ' MenuStripKunden.Renderer = New MyRenderer()

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


    Public Sub New(KdNr As Integer)
        Try
            InitializeComponent()
            Me.kdNr = KdNr
            'MenuStripKunden.Renderer = New MyRenderer()

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

    End Sub
    Private Sub initCboKd()

        Dim connetionString As String = Nothing
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim adapter As New SqlDataAdapter()
        Dim ds As New DataSet()
        Dim i As Integer = 0
        Dim sql As String = Nothing
        sql = "SELECT KundenNr,Kurzname FROM Kunden where order by kurzname"
        connection = cSqlDb.GetNewOpenConnection()
        Try
            ' connection.Open()
            command = New SqlCommand(sql, connection)
            adapter.SelectCommand = command
            adapter.Fill(db)
            adapter.Dispose()
            command.Dispose()
            connection.Close()

        Catch ex As Exception
            MessageBox.Show("Err ! ")
        End Try
    End Sub



    Private Sub frmKundenUebersichtZOLL_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("WARENORT", "AVISO") Then Exit Sub


        Me.BER_STUFE = VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("KUNDEN", "SDL")
        timerOP.Interval = 500
        timerOP.Enabled = False

        System.Console.WriteLine("QQQQQQQ2")
        lblTESTSystem.Visible = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM

        'If Not VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME = "COBAN" Then

        Select Case BER_STUFE
            Case 99 : Me.Close() : Exit Sub
        End Select

        cboKundenblattFirma.Items.Clear()
        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "IMEX"
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("IMEX", "20"))
                cboKundenblattFirma.SelectedIndex = 0
            Case "UNISPED"
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("UNISPED", "21,22,23"))
                cboKundenblattFirma.SelectedIndex = 0
            Case "ATILLA"
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ATILLA", "7"))
                cboKundenblattFirma.SelectedIndex = 0
            Case "AMBAR"
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("AMBAR", "24"))
                cboKundenblattFirma.SelectedIndex = 0
            Case "VERAG"
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG (alle)", "1,11,15"))
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG (AG)", "1"))
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG (CS)", "11"))
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ATILLA", "7"))
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("VERAG + ATILLA", "1,11,15,7"))
                cboKundenblattFirma.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("IMEX", "20"))
                cboKundenblattFirma.SelectedIndex = 0
            Case Else
                '
        End Select

        KdSearchBox1.initKdBox(Me) ', lblKdNr)

        If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige IsNot Nothing AndAlso VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige <> "" Then
            Dim where = If(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige.contains("A"), "", " AND Firma_ID IN (" & VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige & ") ")
            '  cboFirmaFMZOLL.fillWithSQL("SELECT cast([Firma_ID] as varchar(3)) as Firma_ID,[Firma_Bez]  FROM [tblFirma] WHERE 1=1 " & where, True, "FMZOLL", True)
        End If


        'If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERIMEX" Then
        '    cbx.Checked = True
        'End If

        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("VERIMEX", "AVISO") Then
            mnueRechnungen.Visible = False
            mnueSpeditionsbuch.Visible = False
            mnueStatistik.Visible = False
            toolOptionen.Visible = False
            mneBearbeiten.Visible = False
            mnueOfferte.Visible = False
            mneFormulare.Visible = False
            mnueFiskal.Visible = False
            toolNeuerKunde.Visible = False
            ' cbx.Checked = True
        End If



        '   BERECHTIGUNEN = cBerechtignungenFunctions.loadBerechtigungen(USRID)
        AddHandler KdSearchBox1.PropertyChanged, Sub()
                                                     Try
                                                         setKD(KdSearchBox1.KdNr_value)
                                                     Catch ex As Exception
                                                         MsgBox(ex.Message & vbNewLine & ex.StackTrace)
                                                     End Try
                                                 End Sub

        Me.tbcntrKundenDaten.Visible = False
        tbcntrKundenDaten.Appearance = TabAppearance.FlatButtons
        tbcntrKundenDaten.ItemSize = New Size(0, 1)
        tbcntrKundenDaten.SizeMode = TabSizeMode.Fixed

        If kdNr > 0 Then KdSearchBox1.KdNr = kdNr 'setKD(kdNr)

        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "ATILLA"
                mnueZoll.Visible = False
                'btncheckliste.Visible = False
                'tbcntrAllg.Visible = False
            Case "IMEX"
                'FlatButton8.Visible = False
                'FlatButton7.Visible = False

        End Select

        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("KUNDEN_Fiskaldaten", Me) Then
            mnueFiskal.Visible = True
        End If



        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("ZOLL_Auswertungen", Me) Then
            btnUbersicht.Visible = True
        End If

        VERAG_PROG_ALLGEMEIN.cAllgemein._TRANSLATE(Me)


    End Sub

    Private Sub frmKundenUebersichtZOLL_Shown(sender As Object, e As EventArgs) Handles Me.Shown

        KdSearchBox1.Focus()
        Select Case selectedTAB
            Case "Kunde"
                tbcntrKundenDaten.SelectedIndex = 0
            Case "Zolltarif"
                tbcntrKundenDaten.SelectedIndex = 1
            Case "Offerte"
                tbcntrKundenDaten.SelectedIndex = 2
        End Select
        loaded = True

    End Sub
    Sub initKD()
        Dim kdsrch As New SDL.frmKundenSuche
        kdsrch.erweitern = True
        Panel1.Enabled = False
        If kdsrch.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then

            setKD(kdsrch.kundenNrSearch.Text)
        Else
            Me.BringToFront()
            If kdNr <= 0 Then
                '  Me.Close()
            End If
        End If


        Panel1.Enabled = True

    End Sub

    Public Sub setKD(kdnr)
        Me.kdNr = kdnr
        loaded = False
        If Not (New kundenSQL).existByKdNr(kdnr) Then
            Me.tbcntrKundenDaten.Visible = False
            For Each m As ToolStripItem In MenuStripKunden.Items
                m.Enabled = False
            Next
            'initAbfVerb(False)
            rtbInfo.Visible = False
            Exit Sub
            'MsgBox("Keine Kundennummer ausgewählt!", vbCritical)
            'Me.Close() : Exit Sub
        End If
        'MsgBox(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM & " - " & VERAG_PROG_ALLGEMEIN.cAllgemein.USR_NNAME)

        initAllgemein()


        Me.tbcntrKundenDaten.Visible = True
        usrcntlKundenuebersicht.setKD(kdnr)
        'initDGVUmsatz()
        'initDGVOffenePosten()
        'initDGVVollmachten()
        'initDGVGestGarantie()
        ''initDGVOfferte()
        'initDGVAnhaenge()
        'initDGVOffertenSperrliste()
        'initSperre()
        UsrCntlOfferte1.init(kdnr)

        RG_MONAT = CDate("01." & Now.Month & "." & Now.Year) '.AddMonths(-1)

        tbcntrKundenDaten_TabIndexChanged(tbcntrKundenDaten, New EventArgs)
        '   tbKontakt_TabIndexChanged(tbKontakt, New EventArgs)

        'If tbcntrKundenDaten.SelectedIndex = 1 Then initZollTarife() ' nur wenn der Tab aktiv, sonst dauert das Laden länger
        'If tbcntrKundenDaten.SelectedIndex = 3 Then initStatistik() ' nur wenn der Tab aktiv, sonst dauert das Laden länger


        mnueKunden.Enabled = True
        mnueZoll.Enabled = True
        mneFormulare.Enabled = True
        mnueOfferte.Enabled = True
        mnueStatistik.Enabled = True
        mnueRechnungen.Enabled = True
        mnueSpeditionsbuch.Enabled = True
        toolOptionen.Enabled = True
        mneBearbeiten.Enabled = True
        'SchließenToolStripMenuItem.Enabled = True
        mnueFiskal.Enabled = True


        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("VERIMEX", "AVISO") Then
            mnueRechnungen.Visible = False
            mnueSpeditionsbuch.Visible = False
            mnueStatistik.Visible = False
            mnueOfferte.Visible = False
            If usrcntlKundenuebersicht.ADRESSE IsNot Nothing AndAlso usrcntlKundenuebersicht.ADRESSE.LandKz = "TR" Then
                mnueRechnungen.Visible = True
                mnueSpeditionsbuch.Visible = True
                mnueStatistik.Visible = True
                mnueOfferte.Visible = True
            End If
        End If


        Dim KdFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale(KUNDE.FilialenNr)
        If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "ATILLA" Then KdFirma = KdFirma.Replace("VERAG", "ATILLA")
        If (KdFirma <> VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA And Not VERAG_PROG_ALLGEMEIN.cAllgemein.isCLUSTER) And
            Not (KdFirma = "IMEX" And VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AVISO_IMEX", "AVISO")) Then

            If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_CLUSTER", "SDL") And
                Not ((KdFirma = "IMEX" Or KdFirma = "VERAG") And VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_VERAGIMEX", "SDL")) And
                Not ((KdFirma = "AMBAR") And VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_AMBAR", "SDL")) And
                Not ((KdFirma = "FRONTOFFICE") And VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("FAKTURIERUNG_FRONTOFFICE", "SDL")) And
                Not ((KdFirma = "AMBAR") And VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("FAKTURIERUNG_AMBAR", "SDL")) Then
                mnueOfferte.Enabled = False
                mnueRechnungen.Enabled = False
                mnueSpeditionsbuch.Enabled = False
                mnueStatistik.Enabled = False
                mneFormulare.Enabled = False
                mnueFiskal.Enabled = False
                mneBearbeiten.Enabled = False
                toolOptionen.Enabled = False
                UsrCntlOfferte1.init(-1)
            End If
        Else
        End If
        Try
            Dim cntZoll = SQL.getValueTxtBySql("SELECT COUNT(*) FROM tblZollArtikel WHERE KundenNr='" & kdnr & "'", "FMZOLL")

            mnueZoll.Text = "Kunden-Zolltarife "
            If cntZoll > 0 Then
                mnueZoll.Text &= vbNewLine & "(" & cntZoll & ")"
            End If
        Catch : End Try
        ' btncheckliste.Focus()
        loaded = True
    End Sub

    Private Sub pnlAbfVerb_MouseHover(sender As Object, e As EventArgs) Handles lblAbfertigungsverbot.MouseHover, rtbInfo.MouseHover
        Dim p As New UserControl
        '  rtbInfo.Width = 450
        rtbInfo.Height = 300
        ' rtbInfo.Text = abfertigungsverbotText
        rtbInfo.Visible = True
    End Sub

    Private Sub lblAbfertigungsverbot_MouseLeave(sender As Object, e As EventArgs) Handles lblAbfertigungsverbot.MouseLeave, rtbInfo.MouseLeave

        ' rtbInfo.Visible = False
        rtbInfo.Height = 32
    End Sub

    Private Sub lblAbfertigungsverbot_Click(sender As Object, e As EventArgs) Handles lblAbfertigungsverbot.Click
        showForm(abfertigungsverbotText, "Abfertigungsverbot")
    End Sub


    Sub initAllgemein()
        Try
            lblAbfertigungsverbot.Visible = False
            rtbInfo.Visible = False
            trennungBesonderheiten = False

            abfertigungsverbotText = ""
            gespraechsberichtText = ""
            korrAdresseText = ""
            firmenwortlautFiskal = ""
            'Me.dataAdapterFirma = Nothing
            ' Me.dataFirma.Clear()
            'SDL!

            Dim conn As SqlConnection = cSqlDb.GetNewOpenConnectionFMZOLL()
            '    MsgBox(conn.ConnectionString)
            ' Me.dataAdapterFirma = New SqlDataAdapter("SELECT TOP 1 * FROM Kunden INNER JOIN Adressen ON Kunden.KundenNr= Adressen.AdressenNr where  KundenNr=" & kdNr & " AND [Auswahl]='A' ", conn)
            KUNDE = New VERAG_PROG_ALLGEMEIN.cKunde(kdNr)
            ADRESSE = New VERAG_PROG_ALLGEMEIN.cAdressen(kdNr)
            KUNDE_ERW = New VERAG_PROG_ALLGEMEIN.cKundenErweitert(kdNr)
            AUFSCHUB = VERAG_PROG_ALLGEMEIN.cKundenAufschubkonten.LOAD_ListAufschubKTOByKdNr(kdNr)
            '  Me.dataAdapterFirma.Fill(Me.dataFirma)
            conn.Close()

            ' Me.dataFirma.AcceptChanges()
            ' Me.dataFirma.Locale = System.Globalization.CultureInfo.InvariantCulture


            '     Button4.Visible = False
            '  Button5.Visible = False
        Catch ex As Exception
            MsgBox("Es ist ein Fehler beim Laden der Firmendaten - Allgemein aufgetreten!" & vbNewLine & vbNewLine & ex.Message & ex.StackTrace)
        End Try
    End Sub



    Sub showForm(t As String, Optional h As String = "")
        Dim f As New Form
        Dim p As New Panel
        Dim rtb As New RichTextBox
        f.StartPosition = FormStartPosition.CenterScreen
        f.Width = 700
        f.Height = 400
        f.Text = h
        f.Icon = My.Resources.sdl_ico
        rtb.Dock = DockStyle.Fill
        p.Dock = DockStyle.Fill
        f.Controls.Add(p)
        p.Controls.Add(rtb)
        rtb.Text = t
        f.ShowDialog()
    End Sub


    Function checkNullStr(o As Object) As String
        If Not IsDBNull(o) Then
            Return o
        End If
        Return ""
    End Function


    Function checkNullNbr(o As Object) As Double
        If Not IsDBNull(o) AndAlso IsNumeric(o) Then
            Return o
        End If
        Return 0
    End Function
    Function checkNullBool(o As Object) As Boolean
        Try
            Return DirectCast(o, Boolean)
        Catch ex As Exception
            Return False
        End Try
    End Function



    Private Sub lklGanzerText_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs)
        showForm(gespraechsberichtText, "Gesprächsbericht")
    End Sub

    Private Sub lblEmail_Click(sender As Object, e As EventArgs)

        If sender.text <> "" Then
            If MsgBox("Möchten Sie eine E-Mail an '" & sender.text & "' senden?", vbQuestion + vbYesNo) = vbYes Then
                Try : Process.Start(String.Format("mailto:{0}", sender.text)) : Catch : End Try
            End If
        End If
    End Sub


    Dim tmprowindex As Integer = -1
    Private Sub DgvDelays_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs)
        Exit Sub
        Try
            If e.Button = Windows.Forms.MouseButtons.Right Then
                tmprowindex = e.RowIndex
                '  cntxtVollmachten.Show(dgvVollmachten, dgvVollmachten.PointToClient(Cursor.Position))
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    '



    Private Sub dgvUmsatzbericht_SelectionChanged(sender As Object, e As EventArgs)  ', dgvOffertenSperrliste.SelectionChanged
        sender.ClearSelection()
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs)
        showForm(korrAdresseText, "Korrespondenz - Postadresse ")
    End Sub

    Sub initZollTarife()
        pnlZollTarife.Controls.Clear()
        If kdNr <= 0 Then Exit Sub
        Dim usrcntl As New usrCntlZollArtikel

        usrcntl.displayFilter = True
        usrcntl.Dock = DockStyle.Fill
        usrcntl.kdnr = CInt(kdNr)
        usrcntl.parentKundenblatt = True
        pnlZollTarife.Controls.Add(usrcntl)
    End Sub

    Private Sub tbcntrKundenDaten_TabIndexChanged(sender As Object, e As EventArgs) Handles tbcntrKundenDaten.SelectedIndexChanged
        tbSpeditionsbuch.Controls.Clear()
        If tbcntrKundenDaten.SelectedIndex = 1 Then
            initZollTarife()
        ElseIf tbcntrKundenDaten.SelectedIndex = 3 Then
            initStatistik()
        ElseIf tbcntrKundenDaten.SelectedIndex = 4 Then
            initFiskal()
        ElseIf tbcntrKundenDaten.SelectedIndex = 5 Then
            initBtns("Monat")
            initRechnungen()
        ElseIf tbcntrKundenDaten.SelectedIndex = 6 Then
            ' initBtns("Monat")
            initSpeditinsbuch()
        End If
    End Sub

    Sub initFiskal()
        pnlFiskal.Controls.Clear()
        Dim u As New SDL.usrCntlKundeFiskaldaten(kdNr)
        pnlFiskal.Controls.Add(u)
    End Sub
    Sub initRechnungen()
        With dgvRg
            Dim sqlStr = ""
            sqlStr &= "  SELECT TOP 1000 RK_ID,[RechnungsNr],[RechnungsDatum],"
            sqlStr &= " ( SELECT SUM(isnull([SteuerpflichtigerBetrag],0)+isnull([SteuerfreierBetrag],0))  FROM [RechnungsausgangPositionen] where [RechnungsausgangPositionen].RK_ID=[Rechnungsausgang].RK_ID ) as Rechnungsbetrag,"
            sqlStr &= " Sammelrechnung, [FilialenNr],[AbfertigungsNr],[UnterNr],[Abfertigungsdatum],  isnull(cast(RechnungsKundenNr as nvarchar(7)) + ' ','') + [RechnungsName 1] as [RechnungAn], "
            sqlStr &= " isnull(cast([VermittlerKundenNr] as nvarchar(7)) + ' ','') + [VermittlerName 1] as Vermittler, [LKW Kennzeichen],Sachbearbeiter "
            sqlStr &= " FROM [Rechnungsausgang] WHERE RechnungsKundenNr=@KundenNr AND RechnungsDatum BETWEEN @RechnungsDatum_Von AND @RechnungsDatum_Bis "

            Dim SQL_PARAM As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            SQL_PARAM.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("KundenNr", kdNr))
            SQL_PARAM.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("RechnungsDatum_Von", RG_MONAT))
            SQL_PARAM.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("RechnungsDatum_Bis", RG_MONAT.AddMonths(1).AddDays(-1)))
            .SET_SQL(sqlStr & " ORDER BY RechnungsDatum DESC", "FMZOLL", SQL_PARAM)
            .LOAD()

            '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            .Columns("RK_ID").Visible = False

            .Columns("RechnungsNr").Width = 70
            .Columns("RechnungsNr").HeaderText = "Rechnugs-Nr"
            .Columns("RechnungsNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("RechnungsNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("RechnungsDatum").Width = 100
            .Columns("RechnungsDatum").HeaderText = "Rg-Dat."
            .Columns("RechnungsDatum").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("RechnungsDatum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("Sammelrechnung").Width = 45
            .Columns("Sammelrechnung").HeaderText = "SR"

            .Columns("Rechnungsbetrag").Width = 100
            .Columns("Rechnungsbetrag").HeaderText = "Rechnungsbetrag"
            .Columns("Rechnungsbetrag").DefaultCellStyle.Format = "C"
            .Columns("Rechnungsbetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight

            .Columns("FilialenNr").Width = 45
            .Columns("FilialenNr").HeaderText = "Filiale"
            .Columns("FilialenNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("FilialenNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("AbfertigungsNr").Width = 70
            .Columns("AbfertigungsNr").HeaderText = "Abf-Nr"
            .Columns("AbfertigungsNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("AbfertigungsNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("UnterNr").Width = 45
            .Columns("UnterNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("UnterNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("Abfertigungsdatum").Width = 100
            .Columns("Abfertigungsdatum").HeaderText = "Abf-Dat."
            .Columns("Abfertigungsdatum").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("Abfertigungsdatum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("RechnungAn").MinimumWidth = 150
            .Columns("RechnungAn").HeaderText = "Rechnung an"
            .Columns("RechnungAn").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            '.Columns("Absender").MinimumWidth = 150
            '.Columns("Absender").HeaderText = "Absender"
            '.Columns("Absender").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns("Vermittler").MinimumWidth = 150
            .Columns("Vermittler").HeaderText = "Auftraggeber"
            .Columns("Vermittler").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            '.Columns("Empfänger").MinimumWidth = 150
            '.Columns("Empfänger").HeaderText = "Empfänger"
            '.Columns("Empfänger").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns("LKW Kennzeichen").Width = 120
            .Columns("LKW Kennzeichen").HeaderText = "LKW Kennzeichen"

            .Columns("Sachbearbeiter").MinimumWidth = 100
            .Columns("Sachbearbeiter").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

        End With
    End Sub

    Sub initSpeditinsbuch()
        '        tbSpeditionsbuch.Controls.Clear
        Dim s As New SDL.usrCntlSpeditionsBuchSuche(kdNr, Now.AddDays(-10), Now)
        s.Dock = DockStyle.Fill
        tbSpeditionsbuch.Controls.Add(s)
        s.initSearch()
    End Sub



    Private Sub DataGridView_CellContentClick(sender As Object, e As EventArgs) Handles dgvRg.DoubleClick
        If dgvRg.SelectedRows.Count = 0 Then Exit Sub

        Dim f As New frmKundenUebersichtZollRgDetails(dgvRg.SelectedRows(0).Cells("RK_ID").Value)
        f.ShowDialog()

        dgvRg.RELOAD()

        '   frmNacherfassung.showAll()
    End Sub


    Private Sub lblTARIFE_Click(sender As Object, e As EventArgs)
        'tbcntrKundenDaten.SelectedIndex = 1
        mnueZoll.PerformClick()
    End Sub




    Private Sub SchließenToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Me.Close()
    End Sub



    Sub changeTab(index As Integer, tsi As ToolStripItem)
        tbcntrKundenDaten.SelectedIndex = index
        For Each i As ToolStripItem In MenuStripKunden.Items
            i.Font = New Font(MenuStripKunden.Font.FontFamily, MenuStripKunden.Font.Size, FontStyle.Regular)
        Next
        tsi.Font = New Font(tsi.Font.FontFamily, tsi.Font.Size, FontStyle.Underline Or FontStyle.Bold)
    End Sub


    Private Sub VerzollungspreiseToolStripMenuItem1_Click(sender As Object, e As EventArgs)
        'cDATENSERVER.openDataTMP(cDATENSERVER.getTOP1Path("DOKUMENTE", "VORLAGEN", , "Verzollungspreise.pdf"))
        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "VORLAGEN", "", "", "", "Verzollungspreise.pdf")
        DS.OPEN_SINGLE()
    End Sub

    Private Sub VerzollungspreiseEVToolStripMenuItem1_Click(sender As Object, e As EventArgs)
        ' cDATENSERVER.openDataTMP(cDATENSERVER.getTOP1Path("DOKUMENTE", "VORLAGEN", , "Verzollungspreise EV.pdf"))
        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "VORLAGEN", "", "", "", "Verzollungspreise EV.pdf")
        DS.OPEN_SINGLE()
    End Sub
    Private Sub VerzollungspreiseBEARBEITBARToolStripMenuItem_Click(sender As Object, e As EventArgs)
        cFormularManager.fillVerzollungspreise()
    End Sub
    Private Sub VUBToolStripMenuItem_Click(sender As Object, e As EventArgs)
        ' cDATENSERVER.openDataTMP(cDATENSERVER.getTOP1Path("DOKUMENTE", "VORLAGEN", , "VUB.pdf"))
        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "VORLAGEN", "", "", "", "VUB.pdf")
        DS.OPEN_SINGLE()
    End Sub

    Private Sub toolVPCreditreformTRToolStripMenuItem_Click(sender As Object, e As EventArgs)
        cFormularManager.fillCreditreform(kdNr)
    End Sub

    Private Sub btnKundeWechseln_Click(sender As Object, e As EventArgs)
        initKD()
    End Sub



    Private Sub mnueZoll_Click(sender As Object, e As EventArgs) Handles mnueZoll.Click
        changeTab(1, mnueZoll)
    End Sub

    Private Sub mnueBerichte_Click(sender As Object, e As EventArgs) Handles mnueOfferte.Click
        changeTab(2, mnueOfferte)
    End Sub

    Private Sub mnueStatistik_Click(sender As Object, e As EventArgs) Handles mnueStatistik.Click
        changeTab(3, mnueStatistik)
    End Sub

    Private Sub mnueKunden_Click_1(sender As Object, e As EventArgs) Handles mnueKunden.Click
        changeTab(0, mnueKunden)
    End Sub

    Private Sub lblTARIFE_Click_1(sender As Object, e As EventArgs)

    End Sub

    Private Sub lblTARIFE_Click_2(sender As Object, e As EventArgs)
        changeTab(2, mnueOfferte)
    End Sub


    Private Sub SchließenToolStripMenuItem_Click_1(sender As Object, e As EventArgs)
        Me.Close()
    End Sub




    Private Sub lblEmail_TextChanged(sender As Object, e As EventArgs)
        sender.cursor = IIf(sender.text <> "", Cursors.Hand, Cursors.Default)
    End Sub

    Sub initStatistik()
        datVon.Value = Now.AddYears(-1)
        MyListBox1.fillWithSQL(" SELECT [Abfertigungsart],[Abfertigungsbezeichnung] FROM [Abfertigungsarten] ORDER BY Abfertigungsart ", , "FMZOLL")

        doStatistik()
    End Sub
    Function getValues() As String
        Dim s As String = ""
        For Each i In MyListBox1.SelectedItems
            s += DirectCast(i, VERAG_PROG_ALLGEMEIN.MyListItem).Value & ", "
        Next
        If s.EndsWith(", ") Then
            s = s.Substring(0, s.Length - 2)
        End If
        Return s
    End Function


    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        For i = 0 To MyListBox1.Items.Count - 1
            MyListBox1.SetSelected(i, False)
        Next
    End Sub

    Sub doStatistik()
        Dim von As Date = datVon.Value
        Dim bis As Date = datBis.Value
        Dim abfertigungsarten = getValues()

        WHEREStatistik = ""
        WHEREStatistik &= " Abfertigungsdatum between '" & von.ToShortDateString & "' AND '" & bis.ToShortDateString & "' AND "
        If abfertigungsarten <> "" Then WHEREStatistik &= " Abfertigungsart IN (" & getValues() & ") AND "

        txtAnzAbs.Text = SQL.getValueTxtBySql("SELECT  COUNT(*) FROM [Speditionsbuch]  WHERE " & WHEREStatistik & " [AbsenderKundenNr]=" & kdNr & " ", "FMZOLL")
        txtAnzAtrEmpf.Text = SQL.getValueTxtBySql("SELECT  COUNT(*) FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  [EmpfängerKundenNr]=" & kdNr & " ", "FMZOLL")
        txtAnzFrachtf.Text = SQL.getValueTxtBySql("SELECT  COUNT(*) FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  [FrachtführerKundenNr]=" & kdNr & " ", "FMZOLL")
        txtAnzAtr.Text = SQL.getValueTxtBySql("SELECT  COUNT(*) FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  [VermittlerKundenNr]=" & kdNr & " ", "FMZOLL")
        'txtAnzAtr.Text = SQL.getValueTxtBySql("SELECT  COUNT(*) FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  [AbsenderKundenNr]=" & kdNr & " ", "FMZOLL")


        dgvStat_Abs.DataSource = SQL.loadDgvBySql("SELECT [AbsenderKundenNr] as KdNr, CASE WHEN [AbsenderKundenNr] IS NULL THEN '-' ELSE MAX(Absender) END as Firma, COUNT(*) as Anzahl FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  " & kdNr & " IN([AbsenderKundenNr],[EmpfängerKundenNr],[FrachtführerKundenNr],[VermittlerKundenNr],[EndempfängerKundenNr]) GROUP BY AbsenderKundenNr ORDER BY Anzahl DESC ", "FMZOLL")
        dgvStat_Empf.DataSource = SQL.loadDgvBySql("SELECT [EmpfängerKundenNr] as KdNr, CASE WHEN [EmpfängerKundenNr] IS NULL THEN '-' ELSE MAX(Empfänger) END as Firma, COUNT(*) as Anzahl FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  " & kdNr & " IN([AbsenderKundenNr],[EmpfängerKundenNr],[FrachtführerKundenNr],[VermittlerKundenNr],[EndempfängerKundenNr]) GROUP BY EmpfängerKundenNr ORDER BY Anzahl DESC ", "FMZOLL")
        dgvStat_Frachtf.DataSource = SQL.loadDgvBySql("SELECT [FrachtführerKundenNr] as KdNr, CASE WHEN [FrachtführerKundenNr] IS NULL THEN '-' ELSE MAX(Frachtführer) END as Firma, COUNT(*) as Anzahl FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  " & kdNr & " IN([AbsenderKundenNr],[EmpfängerKundenNr],[FrachtführerKundenNr],[VermittlerKundenNr],[EndempfängerKundenNr]) GROUP BY FrachtführerKundenNr ORDER BY Anzahl DESC ", "FMZOLL")
        dgvStat_Atr.DataSource = SQL.loadDgvBySql("SELECT [VermittlerKundenNr] as KdNr, CASE WHEN [VermittlerKundenNr] IS NULL THEN '-' ELSE MAX(Vermittler) END as Firma, COUNT(*) as Anzahl FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  " & kdNr & " IN([AbsenderKundenNr],[EmpfängerKundenNr],[FrachtführerKundenNr],[VermittlerKundenNr],[EndempfängerKundenNr]) GROUP BY VermittlerKundenNr ORDER BY Anzahl DESC ", "FMZOLL")


        dgvFilialen.DataSource = SQL.loadDgvBySql("SELECT FilialenNr,(SELECT Grenzstelle FROM Filialen WHERE Filialen.FilialenNr=Speditionsbuch.FilialenNr  ) as Bezeichnung,COUNT(*) as Anzahl  FROM [Speditionsbuch]  WHERE " & WHEREStatistik & "  " & kdNr & " IN([AbsenderKundenNr],[EmpfängerKundenNr],[FrachtführerKundenNr],[VermittlerKundenNr],[EndempfängerKundenNr]) GROUP BY Filialennr ORDER BY Anzahl DESC  ", "FMZOLL")


        With dgvStat_Abs
            .Columns("KdNr").Width = 50
            .Columns("Firma").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("Anzahl").Width = 40
        End With
        With dgvStat_Empf
            .Columns("KdNr").Width = 50
            .Columns("Firma").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("Anzahl").Width = 40
        End With
        With dgvStat_Frachtf
            .Columns("KdNr").Width = 50
            .Columns("Firma").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("Anzahl").Width = 40
        End With
        With dgvStat_Atr
            .Columns("KdNr").Width = 50
            .Columns("Firma").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("Anzahl").Width = 40
        End With
        With dgvFilialen
            .Columns("FilialenNr").Width = 50
            .Columns("Bezeichnung").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("Anzahl").Width = 40
        End With
    End Sub

    Private Sub datVon_ValueChanged(sender As Object, e As EventArgs) Handles datVon.ValueChanged, datBis.ValueChanged, btn.Click, MyListBox1.SelectedValueChanged
        doStatistik()
    End Sub

    Private Sub dgvStat_Abs_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvStat_Abs.CellDoubleClick, dgvStat_Empf.CellDoubleClick, dgvStat_Frachtf.CellDoubleClick, dgvStat_Atr.CellDoubleClick
        If e.RowIndex < 0 Then Exit Sub

        Dim frm As New frmKundenUebersichtZOLLStatDetails

        If sender Is dgvStat_Abs Then frm.kdBez = "AbsenderKundenNr"
        If sender Is dgvStat_Empf Then frm.kdBez = "EmpfängerKundenNr"
        If sender Is dgvStat_Frachtf Then frm.kdBez = "FrachtführerKundenNr"
        If sender Is dgvStat_Atr Then frm.kdBez = "VermittlerKundenNr"
        frm.WHEREStatistik = WHEREStatistik
        frm.kdNrTMP = sender.Rows(e.RowIndex).Cells("KdNr").Value
        frm.kdNr = kdNr
        frm.Show()

    End Sub


    Private Sub dgvStat_Atr_SelectionChanged(sender As Object, e As EventArgs) Handles dgvStat_Abs.SelectionChanged, dgvStat_Empf.SelectionChanged, dgvStat_Frachtf.SelectionChanged, dgvStat_Atr.SelectionChanged
        sender.ClearSelection()
    End Sub






    Private Sub pic_Click(sender As Object, e As EventArgs) Handles pic.Click
        initKD()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        If ADRESSE.UstIdNr Is Nothing Then Exit Sub
        If ADRESSE.UstIdKz Is Nothing Then Exit Sub
        If ADRESSE.UstIdKz = "" Then Exit Sub
        If ADRESSE.UstIdNr = "" Then Exit Sub

        sender.BackgroundImage = My.Resources.wait
        ' Button5.Visible = False

        '  If cProgramFunctions.validUID(ADRESSE.UstIdKz, ADRESSE.UstIdNr) Then
        Dim UID = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefung(ADRESSE.AdressenNr, True)
        If UID IsNot Nothing Then
            If UID.uid_valid Then
                setKD(kdNr)
                sender.BackgroundImage = My.Resources.ok
            Else
                sender.BackgroundImage = My.Resources.del
            End If
        Else
            sender.BackgroundImage = My.Resources.fragezeichen
        End If


    End Sub

    Private Sub btnPruf_Click(sender As Object, e As EventArgs)
        'Create an object that calls the name for the 
        'Web service used in the added Web Reference. 




        sender.BackgroundImage = My.Resources.wait
        ' Button4.Visible = False
        Dim sGetValu2e As New validation
        ' sGetValu2e.Url = "http://eori.ws.eos.dds.s/"
        sGetValu2e.RequestEncoding = System.Text.UTF8Encoding.Default
        'sGetValu2e.RequestEncoding = System.Text.Encoding.Default
        '  sGetValu2e.UserAgent = "Mozilla/4.0"
        Try
            '   sGetValu2e.Url = "http://ec.europa.eu/taxation_customs/dds2/eos/validation/services/validation?wsdl"
            Dim result As eoriValidationResult = sGetValu2e.validateEORI({KUNDE.EORITIN})

            MsgBox("ASDSADSA")
            If False Then

                Dim CallWebService As New EORI.validation
                '(Substitute the names of your own Server and Web 
                ' service for ServerName.WebServiceName above.) 
                ' CallWebService.validateEORI = txtEori
                ' Dim eori As New UID.eu.europa.ec.eoriResponse
                Dim arrEori As String() = {KUNDE.EORITIN}
                CallWebService.Timeout = 32768
                ' CallWebService.SoapVersion
                'MsgBox(CallWebService.validateEORI(arrEori))
                'CallWebService.validateEORIAsync(arrEori)
                'CallWebService.UserAgent = "MSIE 6.0"

                Dim sGetValue As EORI.eoriValidationResult = CallWebService.validateEORI(arrEori)
                Dim f As EORI.eoriResponse
                MsgBox(sGetValue.requestDate)
                MsgBox(sGetValue.errorDescription.ToString)

                MsgBox("OK")
                MsgBox(sGetValue.result)


                If f.status = 100 Then
                    sender.BackgroundImage = My.Resources.ok
                    'Button4.Visible = True
                    Exit Sub
                End If

            End If

        Catch ex2 As InvalidOperationException
            'Server.GetLastError()
            MsgBox(ex2.Message & ex2.StackTrace)
        Catch ex As Exception
            'Server.GetLastError()
            MsgBox(ex.Message & ex.StackTrace)

        End Try
        sender.BackgroundImage = My.Resources.del

        Exit Sub
        Dim vat As New SDL.EORI.validation

        ' Dim EU3t As New SDL.eu.europa.ec.checkVatService("checkVatPort", "http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl") '"urn:ec.europa.eu:taxud:vies:services:checkVat:types")
        '   Dim EU4 As New EU_Uid_Pruefung.checkVatPortTyp
        ' EU3.checkVatPortType()
        '  "EU_Uid_Pruefung.checkVatPortType" 



        '   Dim ass As New EU_UID_Pruefung.checkVatPortTypeClient()

        '  ass.checkVatPortTypeClient()

        ' Dim s = EU3t.checkVat("AT", "U53187000", valid, name, adress)
        Dim str(1) As String  ' = {KUNDE.EORITIN}
        str(0) = "DE22372020005"
        '  MsgBox("")
        Dim s As EORI.eoriValidationResult = vat.validateEORI(str)
        MsgBox(s.result(0))
        Dim v As New EORI.validation()

        'Dim resp As eu.europa.ec1.eoriResponse
        'resp



        ' FINANZONLINE:::::::::::::::::::::::::::
        '_________________________________
        '  frmUidLink.link = uidlink
        '   frmUidLink.Show()

        '_________________________________
        Me.Cursor = Cursors.WaitCursor
        If cFinanzOnlineWebService.Call_Web_Service_MethodUID_Login() = 0 Then
            MsgBox("HURRA")
        End If

        '  If session <> "" Then
        '  Dim s As String
        '  Try
        's = Call_Web_Service_MethodUID_Abfrage(session)
        ' Call_Web_Service_MethodUID_Logout(session)
        ' uid_message = getmessage(s)
        ' If s = "0" Then
        'uid_message_report = "Die UID-Nummer " & txtUid.Text & " wurde geprüft und ist gültig."
        ' ElseIf s = "4" Then
        '  uid_message_report = "Die UID-Nummer " & txtUid.Text & " wurde geprüft und ist NICHT gültig."
        '  Else
        'uid_message_report = "Probleme bei der Abfrage - UID-Nummer: " & txtUid.Text
        '  End If
        '
        ' Catch ex As Exception
        '    MsgBox("Fehler beim Prüfen der UID-Nummer" & vbNewLine & vbNewLine & ex.Message) : End Try
        ' End If
        '  Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel2_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs)
        showForm(firmenwortlautFiskal, "Firmenwortlaut - Fiskal")
    End Sub



    Private Sub mnueFiskal_Click(sender As Object, e As EventArgs) Handles mnueFiskal.Click
        changeTab(4, mnueFiskal)
    End Sub

    Private Sub ToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles mnueSpeditionsbuch.Click
        changeTab(6, mnueSpeditionsbuch)
    End Sub

    Private Sub ToolStripMenuItem2_Click_1(sender As Object, e As EventArgs) Handles mnueRechnungen.Click
        changeTab(5, mnueRechnungen)
    End Sub





    Private Sub Button5_Click(sender As Object, e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        printUID("AT", "U53187000", ADRESSE.UstIdKz, ADRESSE.UstIdNr)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        printEORI(KUNDE.EORITIN)
        Me.Cursor = Cursors.Default
    End Sub

    Sub printUID(uidKz_antragsteller, uid_antragsteller, uidKz, uid)
        If uidKz Is Nothing Then Exit Sub
        If uid Is Nothing Then Exit Sub
        If uidKz = "" Then Exit Sub
        If uid = "" Then Exit Sub
        printURL("http://ec.europa.eu/taxation_customs/vies/vatResponse.html?memberStateCode=" & uidKz & "&number=" & uid & "&requesterMemberStateCode=" & uidKz_antragsteller & "&requesterNumber=" & uid_antragsteller)
    End Sub


    Sub printEORI(eoriNr)

        timer_EORI.Interval = 2000
        If eoriNr Is Nothing Then Exit Sub
        eoriNr = eoriNr.Replace(" ", "").Trim
        '   printURL("http://ec.europa.eu/taxation_customs/dds2/eos/eori_validation.jsp?Lang=de&EoriNumb=" & eoriNr & "&Expand=true")

        Dim f As New frmInfo
        f.Controls.Clear()
        Dim WebBrowser As New VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx
        f.Controls.Add(WebBrowser)
        f.Visible = False
        f.WindowState = FormWindowState.Minimized
        f.Show()
        f_EORI = f
        WebBrowser.Dock = DockStyle.Fill
        WebBrowser.Navigate(New Uri("http://ec.europa.eu/taxation_customs/dds2/eos/eori_validation.jsp?Lang=de&EoriNumb=" & eoriNr & "&Expand=true"))
        AddHandler WebBrowser.DocumentCompleted, Sub()
                                                     ' Print the document now that it is fully loaded.
                                                     If WebBrowser.ReadyState = WebBrowserReadyState.Complete Then
                                                         '   System.Threading.Thread.Sleep(1000)
                                                         '   WebBrowser.Print()
                                                         ' Dispose the WebBrowser now that the task is complete. 
                                                         ' WebBrowser.Dispose()
                                                         timer_EORI.Enabled = True
                                                     End If

                                                 End Sub


    End Sub

    Sub printURL(url)
        Dim WebBrowser As New VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx
        WebBrowser.Navigate(New Uri(url))
        WebBrowser.AllowNavigation = True
        'WebBrowser.Print()
        AddHandler WebBrowser.DocumentCompleted, Sub()
                                                     ' Print the document now that it is fully loaded.
                                                     System.Threading.Thread.Sleep(1000)
                                                     WebBrowser.Print()
                                                     ' Dispose the WebBrowser now that the task is complete. 
                                                     WebBrowser.Dispose()
                                                 End Sub

    End Sub



    Private Sub FlatButton5_Click(sender As Object, e As EventArgs)

        Dim f1 As New frmBonitaet(kdNr)
        f1.ShowDialog(Me)

        setKD(kdNr) 'aktualisieren
        Exit Sub


        Dim f As New frmFormulare(kdNr)
        f.Show()
        f.addForm("Boniteatsauskunft")

        Exit Sub
        If kdNr <= 0 Then Exit Sub
        Dim frmBonitaetBearbeiten As New frmBonitaetBearbeiten
        If frmBonitaetBearbeiten.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            SQL.doSQL("UPDATE Kunden SET Bonität='" & frmBonitaetBearbeiten.lblBonitaet.Text & "', Bonitätsdatum='" & frmBonitaetBearbeiten.lblBonitaetsdatum._value & "' WHERE KundenNr=" & kdNr, "FMZOLL")
            setKD(kdNr)
        End If
    End Sub





    Private Sub ToolStripMenuItem7_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem9.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.Gestellungsgarantie, kdNr, {})
    End Sub

    Private Sub ZollvollmachtDEToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles toolStrVM_de.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.DE_Vollmacht, kdNr, {})
        'cFormularManager.fillVollmacht(-1, "ZVM_DE")
    End Sub

    Private Sub ToolStripMenuItem10_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem10.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.Importaviso_VK, kdNr, {})

    End Sub

    Private Sub MANAGERToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MANAGERToolStripMenuItem.Click
        Dim f As New frmFormulare(kdNr)
        f.Show()
    End Sub

    Private Sub ZollvollmachtDEFiskalToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ZollvollmachtDEFiskalToolStripMenuItem.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.DE_Fiskal, kdNr, {})
    End Sub

    Private Sub ToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem6.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.AT_Vollmacht, kdNr, {})
    End Sub

    Private Sub ToolStripMenuItem8_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem8.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.AT_Fiskal, kdNr, {})
    End Sub

    Private Sub ZollvollmachtATEVToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ZollvollmachtATEVToolStripMenuItem.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.AT_Vollmacht_EV, kdNr, {})
    End Sub

    Private Sub ToolStripMenuItem11_Click(sender As Object, e As EventArgs)
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.Importaviso_VK, kdNr, {})
    End Sub

    Private Sub ToolStripMenuItem13_Click(sender As Object, e As EventArgs)
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.Importaviso_VK, kdNr, {})
    End Sub

    Private Sub ToolStripMenuItem14_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem14.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.DispoListe, kdNr, {})
    End Sub

    Private Sub ToolStripMenuItem16_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem16.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.Verzollungspreise, kdNr, {})
    End Sub

    Private Sub VUBVERAGSpeditionAGToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VUBVERAGSpeditionAGToolStripMenuItem.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.VUB_AG, kdNr, {})
    End Sub

    Private Sub VeragCustomsServiceToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VeragCustomsServiceToolStripMenuItem.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.VUB_CS, kdNr, {})
    End Sub

    Private Sub ToolStripMenuItem19_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem19.Click
        SDL.FormularManagerNEU.OPEN_FORM(SDL.FormularManagerArten.Boniteatsauskunft, kdNr, {})
    End Sub




    Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
        RG_MONAT = RG_MONAT.AddMonths(1)
        initBtns("Monat")
    End Sub

    Sub initBtns(MonatJahr)
        Try
            'MsgBox(RG_MONAT.ToString("MMMM yy"))
            btnMonat.Text = RG_MONAT.ToString("MMMM yy")
            Select Case MonatJahr
                Case "Monat"
                Case "Jahr", "Tag"
            End Select
            initRechnungen()
        Catch ex As Exception

        End Try

    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        RG_MONAT = RG_MONAT.AddMonths(-1)
        initBtns("Monat")
    End Sub




    Private Sub btnSpeichern_Click(sender As Object, e As EventArgs) Handles btnSpeichern.Click
        Dim u As SDL.usrCntlKundeFiskaldaten = pnlFiskal.Controls(0)
        If u.SAVE Then
            lblFiskGespeichert.Visible = True
            tmrFiskal.Enabled = True
        End If
    End Sub

    Private Sub tmrFiskal_Tick(sender As Object, e As EventArgs) Handles tmrFiskal.Tick
        lblFiskGespeichert.Visible = False
        tmrFiskal.Enabled = False
    End Sub

    Private Sub btnUbersicht_Click(sender As Object, e As EventArgs) Handles btnUbersicht.Click
        Dim Firma = "VERAG"
        Select Case cboKundenblattFirma._value
            Case "7" : Firma = "ATILLA"
            Case "20" : Firma = "IMEX"
            Case "21,22,23" : Firma = "UNISPED"
        End Select


        Dim rptKundeUebersicht As New SDL.rptKundeUebersicht(kdNr, cboKundenblattFirma._value, Firma)
        Dim rpt As New frmPrintLayout
        rpt.Text = ""

        rpt.Viewer.LoadDocument(rptKundeUebersicht)

        rpt.Viewer.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
        rpt.Show()
    End Sub

    Private Sub FlatButton7_Click(sender As Object, e As EventArgs)
        Dim f As New frmKundeTeamZuordnung(KUNDE_ERW.kde_qsTeamId, KUNDE_ERW.kde_qsTeamMAId)

        If f.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            If f.SEL_TEAM IsNot Nothing Then
                KUNDE_ERW.kde_qsTeamId = f.SEL_TEAM.qstm_Id
                KUNDE_ERW.kde_qsTeamMAId = f.SEL_TEAM.qstm_Id
                KUNDE_ERW.kde_qsTeamId = If(f.SEL_MA Is Nothing, Nothing, f.SEL_MA.qtma_MaId)
                KUNDE_ERW.kde_qsTeamMAName = If(f.SEL_MA Is Nothing, Nothing, f.SEL_MA.qtma_name)
                KUNDE_ERW.kde_qsTeamName = f.SEL_TEAM.qstm_bezeichnung
                KUNDE_ERW.SAVE()
                '   SQL.doSQL("UPDATE tblKundenErweitert SET kde_qsTeamId='" & f.SEL_TEAM.qstm_Id & "', [kde_qsTeamMAId] = " & If(f.SEL_MA Is Nothing, "null", "'" & f.SEL_MA.qtma_MaId & "'") & " , [kde_qsTeamMAName] = " & If(f.SEL_MA Is Nothing, "null", "'" & f.SEL_MA.qtma_name & "'") & " , [kde_qsTeamName] = '" & f.SEL_TEAM.qstm_bezeichnung & "' WHERE kde_KundenNr=" & kdNr, "FMZOLL")
            Else
                KUNDE_ERW.kde_qsTeamId = Nothing
                KUNDE_ERW.kde_qsTeamMAId = Nothing
                KUNDE_ERW.kde_qsTeamId = Nothing
                KUNDE_ERW.kde_qsTeamMAName = Nothing
                KUNDE_ERW.kde_qsTeamName = Nothing
                KUNDE_ERW.SAVE()
                '  SQL.doSQL("UPDATE tblKundenErweitert SET kde_qsTeamId=null, [kde_qsTeamMAId] = null, [kde_qsTeamMAName] =null , [kde_qsTeamName] =null WHERE kde_KundenNr=" & kdNr, "FMZOLL")
            End If
            setKD(kdNr)
        End If
    End Sub



    Private Sub BearbeitenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BearbeitenToolStripMenuItem.Click
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("Kundendaten_bearbeiten", "SDL") = 0 Then
            If kdNr > 0 Then
                Dim frmKundenblatt As New frmKundenblatt
                frmKundenblatt.showEdit = True
                frmKundenblatt.kdNr = kdNr
                'frmKundenblatt.BERECHTIGUNEN = BERECHTIGUNEN
                frmKundenblatt.ShowDialog(Me)
                setKD(kdNr)
            End If
        End If
    End Sub

    Private Sub AnDakosyÜbertragenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AnDakosyÜbertragenToolStripMenuItem.Click
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("DAKOSY_KD_Uebertragen", "SDL") Then
            MsgBox("Keine Berechtigung!")
        Else

            If If(KUNDE.EORITIN, "") = "" Then
                MsgBox("Bitte EORI-Nr. eintragen!")
                Exit Sub
            End If
            If DAKOSY_Worker.cDakosyFunftions.sendDataByKdNr(KUNDE.KundenNr) Then ' Application.StartupPath & "\Dakosy_SEND\")
                '    init(KUNDE.KundenNr)
                MsgBox("Daten gesendet!")
            End If
        End If
    End Sub

    Private Sub AufschubEORIBearbeitenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AufschubEORIBearbeitenToolStripMenuItem.Click
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("KUNDEN_AufschubBearbeiten", "SDL") Then
            MsgBox("Keine Berechtigung!")
        Else
            Dim f As New frmKundenAufschubdatenBearbeiten(kdNr)
            f.ShowDialog(Me)
            setKD(kdNr)
        End If
    End Sub
    Private Sub timer_EORI_Tick(sender As Object, e As EventArgs) Handles timer_EORI.Tick
        Try

            DirectCast(f_EORI.Controls(0), VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx).Print()
            f_EORI.Close()


        Catch ex As Exception

        End Try

        timer_EORI.Enabled = False
    End Sub



    Private Sub FlatButton8_Click(sender As Object, e As EventArgs)
        cProgramFunctions.openThereforeNavigatorTarifnummern(kdNr)
    End Sub

    Private Sub FlatButton7_Click_1(sender As Object, e As EventArgs)
        cProgramFunctions.openThereforeNavigatorKudnenInfo(kdNr)
    End Sub



    Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles mneBearbeiten.Click
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("Kundendaten_bearbeiten", "SDL") = 0 Then
            If kdNr > 0 Then
                Dim frmKundenblatt As New frmKundenblatt
                frmKundenblatt.showEdit = True
                frmKundenblatt.kdNr = kdNr
                'frmKundenblatt.BERECHTIGUNEN = BERECHTIGUNEN
                frmKundenblatt.ShowDialog(Me)
                setKD(kdNr)
            End If
        End If
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        Dim f As New frmKundenDatenblatt(kdNr)
        f.Show()
    End Sub

    Private Sub cbx_CheckedChanged(sender As Object, e As EventArgs) Handles cbx.CheckedChanged
        KdSearchBox1._AlleFirmenCLUSTER = cbx.Checked
        KdSearchBox1.RESARCH()
    End Sub

    Private Sub toolNeuerKunde_Click(sender As Object, e As EventArgs) Handles toolNeuerKunde.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
            If frmKundenblatt.ShowDialog(Me) Then
                If frmKundenblatt.kdNr > 0 Then
                    setKD(frmKundenblatt.kdNr)
                End If
            End If
        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.ShowDialog()
            If frmKd.kdnr > 0 Then
                setKD(frmKd.kdnr)
            End If
        End If

    End Sub

    Private Sub SYSKAÜbertragToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SYSKAÜbertragToolStripMenuItem.Click
        If KUNDE Is Nothing Then Exit Sub
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("SYSKA_UPDATE", "SDL") Then
            Dim f As New frmKundenSyska_DatenÜbertragen(KUNDE.KundenNrZentrale)
            f.ShowDialog(Me)
        End If
    End Sub

    Function getList_RK_ID() As List(Of Integer)
        Dim listRgNr As New List(Of Integer)
        Dim list As New List(Of Integer)
        If dgvRg.SelectedRows.Count > 0 Then
            For Each r As DataGridViewRow In dgvRg.SelectedRows
                If listRgNr.FindIndex((Function(x) x.ToString = r.Cells("RechnungsNr").Value)) < 0 Then
                    list.Add(r.Cells("RK_ID").Value)
                    listRgNr.Add(r.Cells("RechnungsNr").Value)
                End If
            Next
        End If
        Return list
    End Function


    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles btnRgPdf.Click
        Me.Cursor = Cursors.WaitCursor
        Try
            For Each RK_ID In getList_RK_ID()
                Dim RG_PATH = ""
                cFakturierung.doRechnungsDruck_SRorER(RK_ID,, False, 4, RG_PATH,,, True)
                Process.Start(RG_PATH)
            Next
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub DateiHochladenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DateiHochladenToolStripMenuItem.Click
        Me.Cursor = Cursors.WaitCursor
        Try

            Dim list As New List(Of String)

            For Each RK_ID In getList_RK_ID()
                Dim RG_PATH = ""
                cFakturierung.doRechnungsDruck_SRorER(RK_ID,, False, 4, RG_PATH,,, True)
                list.Add(RG_PATH)
            Next

            'Zwischenablage
            Clipboard.Clear()
            Dim d As New DataObject(DataFormats.FileDrop, list.ToArray)
            Clipboard.SetDataObject(d, True)
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub dgvrg_SelectionChanged(sender As Object, e As EventArgs) Handles dgvRg.SelectionChanged
        btnRgPdf.Enabled = (dgvRg.SelectedRows.Count > 0)
    End Sub

End Class


