Imports System.Data.SqlClient
Imports System.Reflection

Public Class cAdressen
    Property Auswahl As Object = Nothing
    Property AdressenNr As Object = Nothing
    Property Ordnungsbegriff As Object = Nothing
    Property Name_1 As Object = Nothing
    Property Name_2 As Object = Nothing
    Property Postfach As Object = Nothing
    Property PLZPF As Object = Nothing
    Property Straße As Object = Nothing
    Property LandKz As Object = Nothing
    Property PLZ As Object = Nothing
    Property Ort As Object = Nothing
    Property Telefon As Object = Nothing
    Property Telefax As Object = Nothing
    Property Mobiltelefon As Object = Nothing
    Property E_Mail As Object = Nothing
    Property E_Mail2 As Object = Nothing
    Property Anrede As Object = Nothing
    Property Ansprechpartner As Object = Nothing
    Property UstIdKz As Object = Nothing
    Property UstIdNr As Object = Nothing
    Property UstIdGeprüft As Object = Nothing
    Property BLZ As Object = Nothing
    Property KTO As Object = Nothing
    Property Eingegeben_am As Object = Nothing
    Property Geändert_am As Object = Nothing
    Property Sachbearbeiter As Object = Nothing
    Property Rechnungsdruck As Object = Nothing
    Property Steuernummer As Object = Nothing
    Property IDSKundenNr As Object = Nothing
    Property WölflKundenNr As Object = Nothing
    Property MSEKundenNr As Object = Nothing
    Property MSEExportCSV As Object = Nothing
    Property TELEPASS_Kd_Nr As Object = Nothing
    Property ASFINAGExportCSV As Object = Nothing
    Property UStV_GVAnfDat As Object = Nothing
    Property UStV_GVAusDat As Object = Nothing
    Property ExportMautberichtCSV As Object = Nothing
    Property UTAKundenNr As Object = Nothing
    Property UTAExportCSV As Object = Nothing
    'Property SSMA_TimeStamp As Object = Nothing
    Property MWSTVorauszahlung As Object = Nothing
    Property PLOSEKundenNr As Object = Nothing

    Property weitereWölflKundenNr As Object = Nothing


    Public hasEntry = False
    Shared SQL As New SQL

    Sub New(AdressenNr)
        Me.AdressenNr = AdressenNr
        If AdressenNr <= 0 Then
            INIT_NEWKD_DATA()
        Else
            LOAD()
        End If
    End Sub

    Sub New(UIDNr As String, woellKdNr As Integer, isWoelflKundenNr As Boolean)
        LOADUIDNr(UIDNr, woellKdNr, isWoelflKundenNr)
    End Sub
    Public Function FullName() As String
        Return (If(Name_1, "") & " " & If(Name_2, "")).ToString.Replace("  ", " ")
    End Function

    Public Shared Function getHoechsteKdNr(NrKr_von As Integer, NrKr_bis As Integer, Optional checkAbweichendeDebitorenNr As Boolean = False) As Integer
        Try
            Dim optionalSQLString = ""

            If checkAbweichendeDebitorenNr Then
                optionalSQLString = "AND not exists ( select * from [Adressen] b INNER JOIN Kunden k2 ON k2.Kundennr=b.adressennr where AdressenNr between '" & NrKr_von & "' AND '" & NrKr_bis & "' and a.[AdressenNr] +1 = k2.KundenNrZentrale) AND KundenNrZentrale NOT IN (([AdressenNr]) +1)"
            End If

            Using conn As SqlConnection = cSqlDb.GetNewOpenConnectionFMZOLL(False)
                Using cmd As New SqlCommand("select isnull(min([AdressenNr]) +1," & NrKr_von & ")  as AdressenNr from [Adressen] a INNER JOIN Kunden ON Kundennr=adressennr where  AdressenNr between '" & NrKr_von & "' AND '" & NrKr_bis & "' AND not exists ( select * from [Adressen] b INNER JOIN Kunden k2 ON k2.Kundennr=b.adressennr where AdressenNr between '" & NrKr_von & "' AND '" & NrKr_bis & "' and a.[AdressenNr] +1 = b.[AdressenNr]) AND KundenNr NOT IN (([AdressenNr]) +1) " & optionalSQLString, conn)
                    'Using cmd As New SqlCommand("SELECT isnull(max([AdressenNr])," & NrKr_von & ") as AdressenNr FROM Adressen WHERE AdressenNr BETWEEN '" & NrKr_von & "' AND '" & NrKr_bis & "' ", conn)
                    Dim dr = cmd.ExecuteReader()
                    If dr.HasRows Then
                        dr.Read()
                        If IsNumeric(dr.Item("AdressenNr")) Then Return (CInt(dr.Item("AdressenNr")))
                    End If
                    dr.Close()
                End Using
            End Using

        Catch ex As Exception

            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            '   MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message)
        End Try
        Return -1
    End Function

    Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        '  list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Mandant", Mandant))

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Auswahl", Auswahl))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("AdressenNr", AdressenNr, , True))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Ordnungsbegriff", Ordnungsbegriff))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Name 1", Name_1, "Name_1"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Name 2", Name_2, "Name_2"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Postfach", Postfach))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PLZPF", PLZPF))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Straße", Straße))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("LandKz", LandKz))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PLZ", PLZ))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Ort", Ort))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Telefon", Telefon))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Telefax", Telefax))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Mobiltelefon", Mobiltelefon))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("E-Mail", E_Mail, "E_Mail"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("E-Mail2", E_Mail2, "E_Mail2"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Anrede", Anrede))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Ansprechpartner", Ansprechpartner))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UstIdKz", UstIdKz))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UstIdNr", UstIdNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UstIdGeprüft", UstIdGeprüft))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("BLZ", BLZ))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("KTO", KTO))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Eingegeben am", Eingegeben_am, "Eingegeben_am"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Geändert am", Geändert_am, "Geändert_am"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Sachbearbeiter", Sachbearbeiter))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Rechnungsdruck", Rechnungsdruck))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Steuernummer", Steuernummer))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("IDSKundenNr", IDSKundenNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("WölflKundenNr", WölflKundenNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("MSEKundenNr", MSEKundenNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("MSEExportCSV", MSEExportCSV))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("TELEPASS-Kd-Nr", TELEPASS_Kd_Nr, "TELEPASS_Kd_Nr"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ASFINAGExportCSV", ASFINAGExportCSV))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UStV_GVAnfDat", UStV_GVAnfDat))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UStV_GVAusDat", UStV_GVAusDat))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ExportMautberichtCSV", ExportMautberichtCSV))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UTAKundenNr", UTAKundenNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UTAExportCSV", UTAExportCSV))
        '  list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("SSMA_TimeStamp", SSMA_TimeStamp))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("MWSTVorauszahlung", MWSTVorauszahlung))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PLOSEKundenNr", PLOSEKundenNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("weitereWölflKundenNr", weitereWölflKundenNr))

        Return list
    End Function

    Sub INIT_NEWKD_DATA()
        If Me.Sachbearbeiter Is Nothing Then Me.Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME
        Me.Eingegeben_am = Now.ToShortDateString
        Me.Auswahl = "A"
        Me.Rechnungsdruck = 0
    End Sub


    Dim kundenNameUID = ""
    Function VALID(ByRef ERROR_TXT As String, KD As cKunde, Optional ByVal UIDMehfachverwendung As Boolean = False) As Boolean
        If If(Ordnungsbegriff, "") = "" Then ERROR_TXT = "Bitte geben Sie einen Ordnungsbegriff ein!" : Return False
        If If(Name_1, "") = "" Then ERROR_TXT = "Bitte geben Sie den Firmenwortlaut ein!" : Return False
        If If(LandKz, "") = "" Then ERROR_TXT = "Bitte geben Sie das Land an!" : Return False
        If If(Ort, "") = "" Then ERROR_TXT = "Bitte geben Sie den Ort an!" : Return False
        If If(PLZ, "") = "" Then ERROR_TXT = "Bitte geben Sie die PLZ an!" : Return False
        If If(Straße, "") = "" Then ERROR_TXT = "Bitte geben Sie die Straße an!" : Return False
        If Not hasEntry Then
            'Prüfung Neuanlage: Nur Hinweismeldung! -> speichern soll trotzdem möglich sein!
            If checkUID(KD, kundenNameUID, UIDMehfachverwendung) Then ERROR_TXT = "Die UID Nummer existiert bereits " & kundenNameUID & "!" & vbNewLine & "Bitte prüfen, damit es zu keiner doppelten Erfassung des Kunden kommt." : Return False
        Else
                Try
                Dim kunde = DirectCast(KD, cKunde)
                Dim addresseTemp = New cAdressen(kunde.KundenNr)
                If Not (addresseTemp.UstIdKz = UstIdKz And addresseTemp.UstIdNr = UstIdNr) Then
                    'Nur Hinweismeldung! -> speichern soll trotzdem möglich sein!
                    If checkUID(KD, kundenNameUID, UIDMehfachverwendung) Then ERROR_TXT = "Die UID Nummer existiert bereits " & kundenNameUID & "!" & vbNewLine & "Bitte prüfen, damit es zu keiner doppelten Erfassung des Kunden kommt." : Return False
                End If

            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try


        End If
        Return True
    End Function

    Function checkUID(KD As cKunde, ByRef kundenNameUID As String, UIDMehfachverwendung As Boolean) As Boolean
        If If(UstIdKz, String.Empty) <> String.Empty And If(UstIdNr, String.Empty) <> String.Empty And Not UIDMehfachverwendung Then
            kundenNameUID = SQL.getValueTxtBySql("SELECT TOP(1) '(' + Cast([AdressenNr] AS NVARCHAR) +' - '+ Cast([Name 1] AS NVARCHAR) + ')'  FROM [Adressen] INNER JOIN Kunden ON KundenNr=AdressenNr  WHERE [UstIdKz]='" & UstIdKz & "' AND [UstIdNr]='" & UstIdNr & "' and  kunden.FilialenNr='" & KD.FilialenNr & "'", "FMZOLL")
            If kundenNameUID IsNot "" Then
                Return True
            End If
        End If
        Return False
    End Function

    Function getUIDMehrfachverwendung() As Boolean

        If If(UstIdKz, String.Empty) <> String.Empty And If(UstIdNr, String.Empty) <> String.Empty Then
            Dim count As Integer = SQL.getValueTxtBySql("SELECT count(*)  FROM [Adressen] INNER JOIN Kunden ON KundenNr=AdressenNr WHERE [UstIdKz]='" & UstIdKz & "' AND [UstIdNr]='" & UstIdNr & "'", "FMZOLL")
            If count > 0 Then
                Return True
            End If
        End If
        Return False

    End Function

    Function getDTUIDMehrfachverwendung(adressenNr) As DataTable
        Dim dt_UID As New DataTable
        If If(UstIdKz, String.Empty) <> String.Empty And If(UstIdNr, String.Empty) <> String.Empty Then

            dt_UID = SQL.loadDgvBySql_Param("SELECT KundenNr FROM [Adressen] INNER JOIN Kunden ON KundenNr=AdressenNr WHERE [UstIdKz]='" & UstIdKz & "' AND [UstIdNr]='" & UstIdNr & "' and not KundenNr='" & adressenNr & "'", "FMZOLL")
        End If

        Return dt_UID

    End Function

    Public Function SAVE(Optional newFlag = False) As Boolean 'obj As Object, tablename As String, where As String) As Boolean
        If newFlag Then INIT_NEWKD_DATA()
        If AdressenNr <= 0 Then
            MsgBox("Fehler: KundenNr <= 0!")
            Return False
        End If
        Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
        Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM Adressen  WHERE AdressenNr=@AdressenNr) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "
        'MsgBox(sqlstr)

        Dim id = SQL.doSQLVarListID(AdressenNr, sqlstr, "FMZOLL", , list,,, False, 2)
        If id = -2 Then id = SQL.doSQLVarListID(AdressenNr, sqlstr, "FMZOLL", , list,,, False, 10) '2.Versuch --> Oft Timeout wg.Fmzoll
        If id = -2 Then id = SQL.doSQLVarListID(AdressenNr, sqlstr, "FMZOLL", , list) '3.Versuch --> Oft Timeout wg.Fmzoll

        '  Dim id = SQL.doSQLVarListID(, sqlstr, "FMZOLL", , list)
        If id > 0 Then AdressenNr = id 'Sonst wird beim Speichern mit Fehler -1 in die AdressenNr übergeben
        Return id > 0
    End Function

    Public Function UpdateSpecialField(field, value) As Boolean
        If field = "" Then Return False

        Dim itemFound = False
        For Each s In getParameterList()
            If s.Scalarvariable = field AndAlso value IsNot Nothing Then
                itemFound = True
                Exit For
            End If
        Next

        If Not itemFound Then Return False

        Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM Adressen  WHERE AdressenNr= " & AdressenNr & ") " &
                       " BEGIN UPDATE [Adressen] SET " & field & " = '" & value & "' WHERE AdressenNr=" & AdressenNr & " End " &
                       " commit tran "

        Return SQL.doSQL(sqlstr, "FMZOLL")

    End Function

    Public Sub LOAD()
        Dim test = ""
        Try
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL(False)
                Using cmd As New SqlCommand("Select * FROM Adressen WHERE AdressenNr=@AdressenNr  ", conn)
                    cmd.Parameters.AddWithValue("@AdressenNr", AdressenNr)

                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each li In getParameterList()
                            '  Me.GetType.GetProperty(l.Scalarvariable) = dr.Item(l.Text)
                            Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)
                            ' MsgBox(l.Text)
                            ' MsgBox(propInfo.PropertyType.ToString)
                            '  propInfo.SetValue(GetType(Object), l.Text)

                            'propInfo.SetValue(Me, l.Text)

                            ' Try
                            test = li.Text
                            If dr.Item(li.Text) Is DBNull.Value Then
                                propInfo.SetValue(Me, Nothing)
                            Else
                                propInfo.SetValue(Me, dr.Item(li.Text))
                            End If

                            '  Catch ex As Exception

                            '  End Try

                            ' Me.GetType.GetProperty(l.Scalarvariable).setSetValue(GetType(Object), l.Text)
                            'If propInfo IsNot Nothing Then
                            'propInfo.SetValue(l.Scalarvariable, l.Text)
                            '  End If
                        Next
                        Me.hasEntry = True
                    End If
                    dr.Close()
                End Using
            End Using
            'Return Nothing
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            '   MsgBox(test & "Fehler In der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
        '  Return Nothing
    End Sub

    Public Sub LOADUIDNr(UIDNr As String, woelflKdNr As Integer, isWoelfKdNr As Boolean)

        Dim test = ""

        Try
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL(False)
                Using cmd As New SqlCommand("Select TOP(1) * FROM Adressen WHERE (UstIdKz + UstIdNr='" & UIDNr & "' or Steuernummer ='" & UIDNr & "') AND (WölflKundenNr = " & woelflKdNr & " OR weitereWölflKundenNr = " & woelflKdNr & ") " & IIf(isWoelfKdNr, " AND (AdressenNr LIKE '15%' or AdressenNr LIKE '18%')", ""), conn)

                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each li In getParameterList()

                            Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)


                            ' Try
                            test = li.Text
                            If dr.Item(li.Text) Is DBNull.Value Then
                                propInfo.SetValue(Me, Nothing)
                            Else
                                propInfo.SetValue(Me, dr.Item(li.Text))
                            End If

                        Next
                        Me.hasEntry = True
                    End If
                    dr.Close()
                End Using
            End Using
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)

        End Try

    End Sub




    Public Function getAdressFromatted()
        getAdressFromatted = Name_1 & " " & If(Name_2, "") & vbNewLine
        If If(Straße, "") <> "" Then getAdressFromatted &= Straße & vbNewLine
        getAdressFromatted &= If(LandKz, "") & " " & If(PLZ, "") & " " & If(Ort, "") & vbNewLine

    End Function



    Public Function doesOrdnungsbegriffExist() As Boolean
        Try
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL(False)
                Using cmd As New SqlCommand("SELECT count(*) FROM Adressen WHERE Ordnungsbegriff=@Ordnungsbegriff  ", conn)
                    cmd.Parameters.AddWithValue("@Ordnungsbegriff", Ordnungsbegriff)

                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        Return dr.Item(0) > 0
                    End If
                    dr.Close()
                End Using
            End Using
            'Return Nothing
        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
        Return False
    End Function


    Public Function getUpdateCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim str As String = ""
            For Each i In list
                If Not i.isPrimaryParam Then
                    str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," 'Text.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            Return (" UPDATE [Adressen] SET " & str & " WHERE AdressenNr=@AdressenNr ")

        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
        Return ""
    End Function

    Public Shared Function getNewAdressenNr752000() As Integer
        Return (New SQL).getValueTxtBySql("SELECT isnull(MAX (Adressennr),752000)+1  FROM [Adressen] where [AdressenNr]>752000 and [AdressenNr]<800000", "FMZOLL")
    End Function

    Public Function getInsertCmd() As String
        Try
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim str As String = ""
            Dim values As String = ""
            For Each i In list
                If Not i.isonlyForLoad Then 'And (Not i.isPrimaryParam OrElse i.Value > 0) Then
                    str &= "[" & i.Text & "],"
                    values &= "@" & i.Scalarvariable & "," 'Text.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            values = values.Substring(0, values.Length - 1) 'wg. ','
            Return (" INSERT INTO Adressen  (" & str & ") VALUES(" & values & ")  ")
        Catch ex As Exception
            MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
        End Try
        Return ""
    End Function


End Class
