Imports System.Data.SqlClient
Imports VERAG_PROG_ALLGEMEIN
Public Class cImporter_DakosyToVERAG

    Private SQL As New VERAG_PROG_ALLGEMEIN.SQL

    ' ========================================================================
    '  MAIN ENTRY
    ' ========================================================================
    Public Function ImportDakosyEZA(MRN As String, Optional overwrite As Boolean = True, Optional freshInsert As Boolean = False) As Boolean
        If MRN Is Nothing Then Return False
        If MRN = "" Then Return False

        Dim EZA = cDakosyEZA.LOADByMRN(MRN, True)
        If EZA IsNot Nothing Then Return ImportDakosyEZA(EZA, overwrite, freshInsert)
        Return False
    End Function
    Public Function ImportDakosyEZA(eza As cDakosyEZA, Optional overwrite As Boolean = True, Optional freshInsert As Boolean = False) As Boolean
        Try
            If eza Is Nothing Then Return False
            If String.IsNullOrWhiteSpace(eza.eza_MRN) AndAlso String.IsNullOrWhiteSpace(eza.eza_ANR) Then Return False

            If If(eza.eza_MRN, "") = "" AndAlso eza.eza_ANR.ToString.StartsWith("ATA") Then ' Keine finale Anmeldung!
                Return False
            End If

            ' ================================================================
            ' DUPLIKATSPRÜFUNG
            ' ================================================================
            If Not overwrite Then
                If ExistsInVERAG(eza) Then Return False
            End If

            ' ================================================================
            ' HEADER
            ' ================================================================
            Dim ZA As cVERAG_CustomsDeclarations
            If If(eza.eza_MRN, If(eza.eza_ANR, "")) = "" Then
                ZA = New cVERAG_CustomsDeclarations
            Else
                ZA = cVERAG_CustomsDeclarations.loadByMRN(If(eza.eza_MRN, If(eza.eza_ANR, "")), False)
            End If

            ZA.za_System = "DAKOSY"
            ZA.za_CustomsSystem = "ATLAS"
            ZA.za_REGIME = "IMPORT"
            ZA.za_CustomsSystemCountry = "DE"
            ZA.za_IsExternalSystem = False
            ZA.za_IsFinalDeclaration = True

            ZA.za_Firma = eza.eza_firma
            ZA.za_Niederlassung = eza.eza_niederlassung


            ZA.za_MRN = If(eza.eza_MRN, eza.eza_ANR)
            ZA.za_LRN = eza.eza_ObjectName

            VERAG_PROG_ALLGEMEIN.cProgramFunctions.tryGetFirmaNiederlassung(ZA.za_Firma, ZA.za_Niederlassung, "", ZA.za_LRN)
            VERAG_PROG_ALLGEMEIN.cProgramFunctions.tryGetAvisoId_SndId_ByLRN(ZA.za_LRN, ZA.za_AvisoId, ZA.za_SendungsId)

            Dim DY = cDakosy_Zollanmeldungen.LOADById(eza.eza_dyaAnmID)
            If DY IsNot Nothing Then
                If ZA.za_AvisoId Is Nothing AndAlso DY.dy_AvisoId IsNot Nothing Then ZA.za_AvisoId = DY.dy_AvisoId
                If ZA.za_SendungsId Is Nothing AndAlso DY.dy_SendungsId IsNot Nothing Then ZA.za_SendungsId = DY.dy_SendungsId
            End If


            If eza.eza_Anmeldedatum IsNot Nothing AndAlso eza.eza_Anmeldedatum.ToString <> "" Then
                ZA.za_DeclarationDate = CDate(eza.eza_Anmeldedatum)
                ZA.za_ReleaseDate = CDate(eza.eza_Anmeldedatum)
            Else

                Dim dateumRelease As String = (New VERAG_PROG_ALLGEMEIN.SQL).DLookup("isnull(dySt_DakosyTransaktionsDatum,'')", "[tblDakosy_Statusmeldungen]", " dySt_status = 60 And dySt_dyId = '" & eza.eza_dyaAnmID & "' Order By [dySt_DakosyTransaktionsDatum] desc", "FMZOLL",)
                If dateumRelease <> "" AndAlso IsDate(dateumRelease) Then
                    ZA.za_DeclarationDate = CDate(dateumRelease)
                    ZA.za_ReleaseDate = CDate(dateumRelease)
                Else
                    ZA.za_DeclarationDate = ToNullableDate(If(eza.eza_Anmeldedatum, eza.eza_LetzteBearbeitung))
                    ZA.za_ReleaseDate = ToNullableDate(If(eza.eza_Anmeldedatum, eza.eza_LetzteBearbeitung))
                End If
            End If

            ZA.za_MainProcedure = eza.eza_VerfahrenBeantragtCode
            ZA.za_RepresentationCode = eza.eza_VertretungsVerhaeltnisCode
            ZA.za_FiscalRepFlag = ToNullableBool(eza.eza_FiskalvertretungKz)
            ZA.za_ApplicantVATNo = ToStringSafe(eza.eza_UstIdAnmelder)
            ZA.za_ApplicantTaxOffice = ToStringSafe(eza.eza_FinanzamtAnmelder)
            ZA.za_TaxDeduction = ToNullableBool(eza.eza_Vorsteuerabzug)

            ZA.za_CountryDispatch = eza.eza_VersendungsLandCode
            ZA.za_CountryDestination = eza.eza_Bestimmungsland
            ZA.za_CountryDestinationState = eza.eza_Bestimmungsbundesland

            ZA.za_ContainerNr1 = eza.eza_ContainerNr1
            ZA.za_ContainerNr2 = eza.eza_ContainerNr2
            ZA.za_ContainerNr3 = eza.eza_ContainerNr3
            ZA.za_ContainerNr4 = eza.eza_ContainerNr4
            ZA.za_ContainerNr5 = eza.eza_ContainerNr5
            ZA.za_ContainerNr6 = eza.eza_ContainerNr6
            ZA.za_ContainerNr7 = eza.eza_ContainerNr7
            ZA.za_ContainerNr8 = eza.eza_ContainerNr8
            ZA.za_ContainerNr9 = eza.eza_ContainerNr9

            ZA.za_MeansOfTransport_Vehicle = eza.eza_KennzeichenNameBefoerderungsmittelAnkunft
            ZA.za_MeansOfTransport_Nationality = eza.eza_BeförderungsmittelGrenzeStaatszugehörigkeitCode
            ZA.za_MeansOfTransport_Type = eza.eza_BeförderungsmittelGrenzeArt
            ZA.za_CountryImport = "DE"
            ZA.za_WarehouseCode = eza.eza_Warenort
            ZA.za_InvoiceAmount = eza.eza_Rechnungspreis
            ZA.za_InvoiceCurrency = eza.eza_Rechnungswaehrung
            ZA.za_DV1Flag = ToNullableBool(eza.eza_DV1Kz)
            ZA.za_PrevDocument_No = eza.eza_VorpapierNr
            ZA.za_PrevDocument_Type = eza.eza_VorpapierArtCode

            ZA.za_Incoterms = eza.eza_LieferbedingungCode
            ZA.za_IncotermsPlace = eza.eza_LieferbedingungOrt

            ZA.za_Sachbearbeiter = eza.eza_AnmeldenderBearbeiterName
            ZA.za_TotGrossMass = ToNullableDecimal(eza.eza_GesamtRohmasse)


            ZA.za_TransportModeBorder = ToStringSafe(eza.eza_VerkehrszweigGrenze)

            ' ================================================================
            ' ADRESSEN 
            ' ================================================================
            If eza.eza_ADRESSEN IsNot Nothing Then
                For Each p In eza.eza_ADRESSEN

                    Dim party As New cVERAG_CustomsDeclarations_Parties

                    party.zaParty_Role = p.ezaAd_AdressTyp
                    party.zaParty_EORI = p.ezaAd_TeilnehmerEORI
                    party.zaParty_EORI_NL = p.ezaAd_TeilnehmerNLNR
                    party.zaParty_Name = p.ezaAd_NameFirma1
                    party.zaParty_Street = p.ezaAd_StrasseHausNr1
                    party.zaParty_PostalCode = p.ezaAd_PLZ
                    party.zaParty_City = p.ezaAd_Ort
                    party.zaParty_Country = p.ezaAd_LandCode
                    'party.zaParty_TIN = p.
                    party.zaParty_VATNumber = p.ezaAd_UStIDAnmelder
                    party.zaParty_TaxOffice = p.ezaAd_FinanzamtIDAnmelder


                    If If(party.zaParty_EORI, "") <> "" Then

                        Dim AD As VERAG_PROG_ALLGEMEIN.cAdressen = cZOLL_IMPORT.getAdresseFromEORI(party.zaParty_EORI, "", "", True)

                        If AD IsNot Nothing Then
                            party.zaParty_Name = (If(AD.Name_1, "") & " " & If(AD.Name_2, "")).trim
                            party.zaParty_Country = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getISO2Land(AD.LandKz)
                            party.zaParty_City = AD.Ort
                            party.zaParty_Street = AD.Straße
                            'party.ImporterAddressNumber = ""
                            party.zaParty_PostalCode = AD.PLZ
                            'party.ImporterEmail = AD.E_Mail
                            'party.ImporterPhone = AD.Telefon
                        End If

                    End If


                    ZA.Parties.Add(party)
                Next
            End If

            ' ================================================================
            ' ABGABEN 
            ' ================================================================

            If eza.eza_AUFSCHUB IsNot Nothing Then
                For Each d In eza.eza_AUFSCHUB
                    If d.ezaAfb_PositionsNummer Is Nothing Then

                        Dim duty As New cVERAG_CustomsDeclarations_Duty

                        duty.zaDuty_ApplicationType = d.ezaAfb_ArtAufschubantrag
                        duty.zaDuty_AccountType = d.ezaAfb_Aufschubart
                        duty.zaDuty_AccountHeadCustoms = d.ezaAfb_HZA
                        duty.zaDuty_AccountNo = d.ezaAfb_KontoNr
                        duty.zaDuty_AccountEORI = d.ezaAfb_AufschubnehmerEORI
                        duty.zaDuty_AccountHolderName = d.AufschubnehmerName
                        duty.zaDuty_DutyType = d.ezaAfb_AbgabeArt
                        duty.zaDuty_BIN = d.ezaAfb_AufschuBIN
                        duty.zaDuty_AmountEUR = ToNullableDecimal(d.ezaAfb_Abgabenbetrag)
                        duty.zaDuty_AmountForeign = ToNullableDecimal(d.ezaAfb_Abgabenbetrag)
                        duty.zaDuty_Currency = "EUR"
                        duty.zaDuty_LimitDate = ToNullableDate(d.ezaAfb_Faelligkeit)

                        ZA.Duties.Add(duty)
                    End If
                Next
            End If

            ' ================================================================
            ' HEADER-UNTERLAGEN (ItemId = NULL)
            ' ================================================================
            If eza.eza_UNTERLAGEN IsNot Nothing Then
                For Each ul In eza.eza_UNTERLAGEN

                    Dim doc As New cVERAG_CustomsDeclarations_Document
                    doc.zaDoc_Section = ul.ezaUl_Bereich
                    doc.zaDoc_ItemId = Nothing
                    doc.zaDoc_Code = ul.ezaUl_Art
                    doc.zaDoc_Reference = ul.ezaUl_Nummer

                    doc.zaDoc_Date = ul.ezaUl_DatumAusstellung



                    ZA.Documents.Add(doc)
                Next
            End If

            ' ================================================================
            ' POSITIONEN + POSITIONS-UNTERLAGEN
            ' ================================================================
            If eza.eza_WARENPOS IsNot Nothing Then
                For Each wp In eza.eza_WARENPOS

                    Dim item As New cVERAG_CustomsDeclarations_Item

                    item.zaItem_PosNo = ToInt(wp.ezaWP_PositionsNummer)
                    item.zaItem_ArticleCode = wp.ezaWP_Artikelnummer

                    item.zaItem_HSCode = wp.ezaWP_WarennummerEZT
                    item.zaItem_HSAddition1 = wp.ezaWP_Warennummerzusatz1
                    item.zaItem_HSAddition2 = wp.ezaWP_Warennummerzusatz2
                    item.zaItem_HSAddCodes1 = wp.ezaWP_WarennummerZusatzCode1
                    item.zaItem_HSAddCodes2 = wp.ezaWP_WarennummerZusatzCode2
                    item.zaItem_HSAddCodes3 = wp.ezaWP_WarennummerZusatzCode3
                    item.zaItem_HSAddCodes4 = wp.ezaWP_WarennummerZusatzCode4
                    item.zaItem_HSAddCodes5 = wp.ezaWP_WarennummerZusatzCode5
                    item.zaItem_HSAddCodes6 = wp.ezaWP_WarennummerZusatzCode6
                    item.zaItem_HSAddCodes7 = wp.ezaWP_WarennummerZusatzCode7
                    item.zaItem_HSAddCodes8 = wp.ezaWP_WarennummerZusatzCode8
                    item.zaItem_HSAddCodes9 = wp.ezaWP_WarennummerZusatzCode9
                    item.zaItem_HSAddCodes10 = wp.ezaWP_WarennummerZusatzCode10

                    item.zaItem_Description = wp.ezaWP_Warenbezeichnung
                    item.zaItem_PrevProcedure = wp.ezaWP_VerfahrensCodeVorangegangenesVerfahren
                    item.zaItem_PreferentialCountry = wp.ezaWP_Praeferenzursprungsland
                    item.zaItem_MainProcedure = wp.ezaWP_AnmeldeVErfahren


                    item.zaItem_PackageColli = (wp.ezaWP_PackstueckAnzahl)
                    item.zaItem_PackageType = wp.ezaWP_PackstueckArt

                    item.zaItem_GrossMass = ToNullableDecimal(wp.ezaWP_Rohmasse)
                    item.zaItem_NetMass = ToNullableDecimal(wp.ezaWP_Eigenmasse)


                    item.zaItem_InvoiceValueForeign = ToNullableDecimal(wp.ezaWP_Artikelpreis)
                    item.zaItem_InvoiceCurrency = wp.ezaWP_ArtikelpreisWaehrung
                    If If(wp.ezaWP_ArtikelpreisWaehrung, "") = "EUR" Then
                        item.zaItem_InvoiceValueEUR = ToNullableDecimal(wp.ezaWP_Artikelpreis)
                    End If

                    item.zaItem_CustomsValueEUR = ToNullableDecimal(wp.ezaWP_Zollwert)
                    item.zaItem_StatisticalValueEUR = ToNullableDecimal(wp.ezaWP_AHStatWert)

                    item.zaItem_OriginCountry = wp.ezaWP_UrsprungslandCode
                    item.zaItem_PreferenceCode = wp.ezaWP_BeguenstigungBenatragtCode
                    item.zaItem_PosAddition = If(wp.ezaWP_PositionsZusatz, "")

                    ' -------------------------------
                    ' POSITIONS-UNTERLAGEN
                    ' -------------------------------
                    If wp.ezaWP_UNTERLAGEN IsNot Nothing Then
                        For Each ul In wp.ezaWP_UNTERLAGEN

                            Dim doc As New cVERAG_CustomsDeclarations_Document
                            doc.zaDoc_Section = ul.ezaWpUl_Bereich
                            doc.zaDoc_Code = ul.ezaWpUl_Art
                            doc.zaDoc_Reference = ul.ezaWpUl_Nummer

                            doc.zaDoc_Date = ToNullableDate(ul.ezaWpUl_DatumAusstellung)

                            doc.zaDoc_Presentation = ul.ezaWpUl_VorlageKz

                            doc.zaDoc_DepreciationAmount = (ul.ezaWpUl_AbschreibungsMenge)
                            doc.zaDoc_DepreciationUnitmeasurement = ul.ezaWpUl_AbschreibungsMengeMasseinheit
                            doc.zaDoc_DepreciationUnitmeasurementQualifier = ul.ezaWpUl_AbschreibungsMengeMasseinheitQualifier



                            item.Documents.Add(doc)
                        Next
                    End If

                    ' ================================================================
                    ' ABGABEN  POS
                    ' ================================================================

                    If eza.eza_AUFSCHUB IsNot Nothing Then
                        For Each d In eza.eza_AUFSCHUB
                            If d.ezaAfb_PositionsNummer IsNot Nothing AndAlso CInt(d.ezaAfb_PositionsNummer) = item.zaItem_PosNo Then

                                Dim duty As New cVERAG_CustomsDeclarations_Duty

                                duty.zaDuty_ApplicationType = d.ezaAfb_ArtAufschubantrag
                                duty.zaDuty_AccountType = d.ezaAfb_Aufschubart
                                duty.zaDuty_AccountHeadCustoms = d.ezaAfb_HZA
                                duty.zaDuty_AccountNo = d.ezaAfb_KontoNr
                                duty.zaDuty_AccountEORI = d.ezaAfb_AufschubnehmerEORI
                                duty.zaDuty_AccountHolderName = d.AufschubnehmerName
                                duty.zaDuty_DutyType = d.ezaAfb_AbgabeArt
                                duty.zaDuty_BIN = d.ezaAfb_AufschuBIN
                                duty.zaDuty_AmountEUR = ToNullableDecimal(d.ezaAfb_Abgabenbetrag)
                                duty.zaDuty_AmountForeign = ToNullableDecimal(d.ezaAfb_Abgabenbetrag)
                                duty.zaDuty_Currency = "EUR"
                                duty.zaDuty_LimitDate = ToNullableDate(d.ezaAfb_Faelligkeit)
                                duty.zaDuty_Prozentsatz = ToNullableDecimal(d.ezaAfb_Prozentsatz)

                                item.Duties.Add(duty)
                            End If
                        Next
                    End If

                    ZA.Items.Add(item)
                Next
            End If

            ' ================================================================
            'CBAM WARNING
            ' ================================================================
            If freshInsert Then
                ZA.checkfreshCBAMWarning()
            End If
            ' ================================================================

            ' SAVE
            Dim saved = ZA.SAVE()
            ' ======KAFKA==========================================================
            If freshInsert Then cDakosyEZA_Greenpulse.INSERT_KAFKA(ZA)
            ' ================================================================
            Return saved


        Catch ex As Exception
            cErrorHandler.ERR(ex.Message, ex.StackTrace, Reflection.MethodInfo.GetCurrentMethod.Name)
            Return False
        End Try
    End Function

    ' =====================================================================
    ' DUPLIKATSPRÜFUNG
    ' =====================================================================
    Private Function ExistsInVERAG(eza As cDakosyEZA) As Boolean

        Dim sql As String =
        "SELECT TOP 1 1 FROM tblVERAG_CustomsDeclarations " &
        "WHERE za_System='DAKOSY' " &
        "AND (za_MRN=@mrn OR za_MRN=@anr)"

        Dim p As New List(Of SQLVariable) From {
        New SQLVariable("mrn", eza.eza_MRN),
        New SQLVariable("anr", eza.eza_ANR)
    }

        Dim dt = New SQL().loadDgvBySql_Param(sql, "VERAG", , p)
        Return dt IsNot Nothing AndAlso dt.Rows.Count > 0
    End Function
    ' =========================================================================
    '  Small helpers (falls du sie schon hast, kannst du diese entfernen)
    ' =========================================================================
    Private Function ToStringSafe(v As Object) As String
        If v Is Nothing Then Return Nothing
        Dim s As String = TryCast(v, String)
        If s IsNot Nothing Then Return s
        Return Convert.ToString(v, Globalization.CultureInfo.InvariantCulture)
    End Function

    Private Function ToInt(v As Object) As Integer
        If v Is Nothing Then Return 0
        Dim s = Convert.ToString(v, Globalization.CultureInfo.InvariantCulture)
        Dim i As Integer
        If Integer.TryParse(s, Globalization.NumberStyles.Any, Globalization.CultureInfo.InvariantCulture, i) Then Return i
        Return 0
    End Function

    Private Function ToNullableDecimal(v As Object) As Decimal?
        If v Is Nothing Then Return Nothing
        Dim s = Convert.ToString(v, Globalization.CultureInfo.InvariantCulture)
        Dim d As Decimal
        If Decimal.TryParse(s, Globalization.NumberStyles.Any, Globalization.CultureInfo.InvariantCulture, d) Then Return d
        Return Nothing
    End Function

    Private Function ToNullableDate(v As Object) As Date?
        If v Is Nothing Then Return Nothing
        If TypeOf v Is Date Then Return CType(v, Date)

        Dim s = Convert.ToString(v, Globalization.CultureInfo.InvariantCulture)
        Dim dt As Date
        If Date.TryParse(s, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dt) Then Return dt
        Return Nothing
    End Function

    Private Function ToNullableBool(v As Object) As Boolean?
        If v Is Nothing Then Return Nothing
        If TypeOf v Is Boolean Then Return CType(v, Boolean)

        Dim s = Convert.ToString(v, Globalization.CultureInfo.InvariantCulture).Trim().ToLowerInvariant()
        If s = "J" OrElse s = "1" OrElse s = "true" OrElse s = "y" OrElse s = "yes" Then Return True
        If s = "N" OrElse s = "0" OrElse s = "false" OrElse s = "n" OrElse s = "no" Then Return False
        Return Nothing
    End Function
End Class