
Imports System.Data.SqlClient
Imports System.Reflection
Imports VERAG_PROG_ALLGEMEIN.UIDPruefung
'Imports SDL.eu.europa.ec

Public Class cUIDPruefung

    Property uid_id As Integer = -1
    Property uid_KundenNr As Integer
    Property uid_UstIdKz As String
    Property uid_UstIdNr As String
    Property uid_Datum As Date = Now
    Property uid_valid As Boolean
    Property uid_MaId As Object = Nothing
    Property uid_Sachbearbeiter As String
    Property uid_firma As Object = Nothing


    Property uid_stufe As Integer = 1
    Property Firma As String = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
    Property uid_abfrageUid As Object = Nothing
    Property uid_sessionId As Object = Nothing



    Property uid_adr1 As Object = Nothing
    Property uid_adr2 As Object = Nothing
    Property uid_adr3 As Object = Nothing
    Property uid_adr4 As Object = Nothing
    Property uid_adr5 As Object = Nothing
    Property uid_adr6 As Object = Nothing


    Shared SQL As New SQL

    Sub New()
    End Sub

    Sub New(uid_id)
        Me.uid_id = uid_id
        LOAD()
    End Sub

    Public 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("uid_id", uid_id, , True, True))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_KundenNr", uid_KundenNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_UstIdKz", uid_UstIdKz))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_UstIdNr", uid_UstIdNr))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_Datum", uid_Datum))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_valid", uid_valid))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_MaId", uid_MaId))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_Sachbearbeiter", uid_Sachbearbeiter))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_firma", uid_firma))


        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_stufe", uid_stufe))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Firma", Firma))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_abfrageUid", uid_abfrageUid))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_sessionId", uid_sessionId))

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_adr1", uid_adr1))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_adr2", uid_adr2))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_adr3", uid_adr3))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_adr4", uid_adr4))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_adr5", uid_adr5))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uid_adr6", uid_adr6))
        Return list
    End Function



    Public Function SAVE() As Boolean
        Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

        Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblUIDPruefung WITH(updlock,serializable) WHERE uid_id=@uid_id) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "

        uid_id = SQL.doSQLVarListID(uid_id, sqlstr, "FMZOLL", , list)
        Return uid_id > 0
    End Function

    Public Shared Function LOADByKdNrDate(ba_KundenNr As Integer, ba_Datum As Date) As cUIDPruefung
        Try
            Dim UID As New cUIDPruefung
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
                Using cmd As New SqlCommand("SELECT * FROM tblUIDPruefung WHERE ba_KundenNr=@ba_KundenNr AND  cast(ba_Datum as date)=@ba_Datum ", conn)
                    cmd.Parameters.AddWithValue("@ba_KundenNr", ba_KundenNr)
                    cmd.Parameters.AddWithValue("@ba_Datum", ba_Datum.ToShortDateString)
                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each li In UID.getParameterList()
                            Dim propInfo As PropertyInfo = UID.GetType.GetProperty(li.Scalarvariable)

                            If dr.Item(li.Text) Is DBNull.Value Then
                                propInfo.SetValue(UID, Nothing)
                            Else
                                propInfo.SetValue(UID, dr.Item(li.Text))
                            End If

                        Next
                        dr.Close()
                        Return UID
                    End If
                    dr.Close()
                End Using
            End Using
        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 Nothing
    End Function


    Public Shared Function doUIDPruefungALL(Optional datum As Object = Nothing, Optional SaveErgInAdressen As Boolean = True, Optional Sciherheitsabfrage As Boolean = True, Optional MaxEintraege As Integer = -1, Optional showErr As Boolean = True) As DataTable
        Dim dt As DataTable = Nothing
        If datum = Nothing Then datum = CDate("01." & Now.ToString("MM.yyyy")).AddMonths(-1)

        Dim where = ""
        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "AMBAR" : where = " And Filialen.FilialenNr  IN (5701)"
            Case "IMEX" : where = " And Filialen.FilialenNr  IN (5501)"
            Case "ATILLA" : where = " And Filialen.FilialenNr IN (4801)"
            Case "UNISPED" : where = " AND Filialen.firma='UNISPED' "
            Case Else : where = " AND Filialen.firma='VERAG' " '" And isnull(FilialenNr,'')  Not IN (5501,5701)"
        End Select
        Dim Top = ""
        If MaxEintraege > 0 Then
            Top = " TOP " & MaxEintraege
        End If

        dt = SQL.loadDgvBySql("SELECT " & Top & " [AdressenNr] as KdNr,[Ordnungsbegriff] as Firma,UstIdGeprüft as [letzte Prüfung],Adressen.UstIdKz,Adressen.UstIdnr " &
          "  From [Adressen] inner Join kunden On KundenNr=AdressenNr  inner join Filialen on Filialen.FilialenNr=Kunden.FilialenNr " &
          "  where (UstIdGeprüft <= '" & datum.ToShortDateString & "' OR UstIdGeprüft is null) and (Adressen.UstIdKz is not null and Adressen.UstIdNr is not null) " &
          "  And Auswahl='A' " & where & " ORDER BY Ordnungsbegriff", "FMZOLL")

        If dt IsNot Nothing Then
            If dt.Rows.Count = 0 Then Return Nothing
            If Sciherheitsabfrage Then
                If vbYes <> MsgBox("Es werden " & dt.Rows.Count & " Datensätze abgefragt, möchten Sie fortfahren?", vbYesNoCancel) Then
                    Return Nothing
                End If
            End If
            Dim c As New DataColumn
            c.ColumnName = "Ergebnis"
            dt.Columns.Add(c)

            Dim d As New DataColumn
            d.ColumnName = "Error-Code"
            dt.Columns.Add(d)


            '------------------------------------------------
            'ENTWEDER ÜBER EU-KOMISSION ODER FINANZONLINE::::
            Dim ART = "FINANZONLINE"
            '------------------------------------------------
            Select Case ART
                Case "EUROPE"

                    For Each r As DataRow In dt.Rows
                        Dim UID_TMP = doUIDPruefung(r("KdNr"),, SaveErgInAdressen, showErr)
                        If UID_TMP IsNot Nothing Then
                            If UID_TMP.uid_valid Then
                                r("Ergebnis") = "OK"
                            Else
                                r("Ergebnis") = "UNGÜLTIG"
                            End If
                        Else
                            r("Ergebnis") = "ERROR"

                        End If
                    Next


                Case "FINANZONLINE"
                    Dim FO As New VERAG_PROG_ALLGEMEIN.cFinanzOnlineWebService
                    VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERAG"
                    FO.initValues()
                    Dim counter = 0
                    If FO.Call_Web_Service_MethodUID_Login_NEU2020() = 0 Then

                        For Each r As DataRow In dt.Rows

                            counter += 1

                            Dim errorCode = -99
                            Dim UID_TMP = FO.Call_Web_Service_MethodUID_Abfrage_NEU2020(r("KdNr"),, SaveErgInAdressen, showErr,, errorCode)
                            If UID_TMP IsNot Nothing Then
                                If UID_TMP.uid_valid Then
                                    r("Ergebnis") = "OK"
                                Else
                                    r("Ergebnis") = "UNGÜLTIG"
                                End If
                            Else
                                r("Ergebnis") = "ERROR"
                                r("Error-Code") = errorCode.ToString()
                            End If

                            If counter Mod 100 = 0 Then
                                FO.Call_Web_Service_MethodUID_Logout_NEU2020()
                                FO.Call_Web_Service_MethodUID_Login_NEU2020()
                            End If

                        Next

                        FO.Call_Web_Service_MethodUID_Logout_NEU2020()

                    End If

            End Select
            '------------------------------------------------


        End If

        Return dt
    End Function


    Public Shared Function doUIDPruefung(ba_KundenNr, Optional AskIfDouble = False, Optional SaveErgInAdressen = True, Optional showErr = True) As cUIDPruefung

        Dim AD As New cAdressen(ba_KundenNr)
        If AD IsNot Nothing Then
            If AD.UstIdKz IsNot Nothing AndAlso AD.UstIdNr IsNot Nothing Then

                Try
                    If AskIfDouble Then
                        If IsDate(AD.UstIdGeprüft) AndAlso CDate(AD.UstIdGeprüft).ToShortDateString = Now.ToShortDateString Then
                            If vbYes <> MsgBox("Die UID-Nummer wurde heute bereits geprüft. Soll die Prüfung nochmal durchgeführt werden?", vbYesNoCancel) Then
                                Return Nothing
                            End If
                        End If
                    End If

                    Dim vat As New UIDPruefung.checkVatService

                    ' 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 valid As Boolean = False
                    'Dim name As String = ""
                    'Dim adress As String = ""

                    Dim countryCode As String = AD.UstIdKz
                    Dim vatNumber As String = AD.UstIdNr
                    Dim traderName As String
                    Dim traderCompanyType As String
                    Dim traderStreet As String
                    Dim traderPostcode As String
                    Dim traderCity As String

                    Dim requesterCountryCode As String = "AT"
                    Dim requesterVatNumber As String = "U62663022"
                    Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                        Case "IMEX"
                            requesterCountryCode = "AT"
                            requesterVatNumber = "U68490714"
                    End Select
                    Dim valid As Boolean = False
                    Dim traderAddress As String
                    Dim traderNameMatch As matchCode
                    Dim traderNameMatchSpecified As Boolean
                    Dim traderCompanyTypeMatch As matchCode
                    Dim traderCompanyTypeMatchSpecified As Boolean
                    Dim traderStreetMatch As matchCode
                    Dim traderStreetMatchSpecified As Boolean
                    Dim traderPostcodeMatch As matchCode
                    Dim traderPostcodeMatchSpecified As Boolean
                    Dim traderCityMatch As matchCode
                    Dim traderCityMatchSpecified As Boolean
                    Dim requestIdentifier As String



                    '   Dim ass As New EU_UID_Pruefung.checkVatPortTypeClient()

                    '  ass.checkVatPortTypeClient()

                    ' Dim s = EU3t.checkVat("AT", "U53187000", valid, name, adress)
                    'Dim s = vat.checkVat(ADRESSE.UstIdKz, ADRESSE.UstIdNr, valid, name, adress)
                    Dim s = vat.checkVatApprox(countryCode, vatNumber, traderName, traderCompanyType, traderStreet, traderPostcode, traderCity, requesterCountryCode, requesterVatNumber, valid, traderAddress, traderNameMatch, traderNameMatchSpecified, traderCompanyTypeMatch, traderCompanyTypeMatchSpecified, traderStreetMatch, traderStreetMatchSpecified, traderPostcodeMatch, traderPostcodeMatchSpecified, traderCityMatch, traderCityMatchSpecified, requestIdentifier)

                    If s >= Now.ToShortDateString Then 'If s IsNot Nothing Then
                        Dim UID_TMP As New cUIDPruefung
                        UID_TMP.uid_Datum = Now
                        UID_TMP.uid_Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME
                        If If(UID_TMP.uid_Sachbearbeiter, "") = "" Then UID_TMP.uid_Sachbearbeiter = "AUTO"
                        UID_TMP.uid_MaId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
                        UID_TMP.uid_valid = valid
                        UID_TMP.uid_KundenNr = ba_KundenNr

                        UID_TMP.uid_UstIdKz = AD.UstIdKz
                        UID_TMP.uid_UstIdNr = AD.UstIdNr
                        UID_TMP.uid_stufe = 1
                        UID_TMP.Firma = If(VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA, "VERAG")

                        UID_TMP.uid_abfrageUid = requesterCountryCode & requesterVatNumber
                        '  UID.uid_firma =
                        ' UID.uid_strasse))
                        'UID.uid_plz))
                        'UID.uid_ort))

                        UID_TMP.SAVE()
                        If valid Then
                            If SaveErgInAdressen Then
                                AD.UstIdGeprüft = Now.ToShortDateString
                                AD.SAVE()
                            End If
                        End If
                        Return UID_TMP
                    End If
                Catch ex As Exception
                    If showErr Then MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
                End Try
            End If
        End If

        Return Nothing
    End Function


    Public Sub LOAD()
        Try
            Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
                Using cmd As New SqlCommand("SELECT * FROM tblUIDPruefung WHERE uid_id=@uid_id  ", conn)
                    cmd.Parameters.AddWithValue("@uid_id", uid_id)
                    Dim dr = cmd.ExecuteReader()
                    If dr.Read Then
                        For Each li In getParameterList()
                            Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

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

                        Next

                    End If
                    dr.Close()
                End Using
            End Using
        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 Sub


    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 & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            Return (" UPDATE [tblUIDPruefung] SET " & str & " WHERE uid_id=@uid_id ")

        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 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.isPrimaryParam Then
                    str &= "[" & i.Text & "],"
                    values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                End If
            Next
            str = str.Substring(0, str.Length - 1) 'wg. ','
            values = values.Substring(0, values.Length - 1) 'wg. ','
            Return (" INSERT INTO tblUIDPruefung  (" & 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
