Imports System.Reflection
Imports java.lang
Imports TELOTEC_Worker
Imports VERAG_PROG_ALLGEMEIN

Public Class cImporter_TelotecToVERAG

    Private SQL As New VERAG_PROG_ALLGEMEIN.SQL

    ' =====================================================================
    ' MAIN ENTRY
    ' =====================================================================
    Public Function ImportTelotec(CRN As String, Optional overwrite As Boolean = True, Optional freshInsert As Boolean = False) As Boolean

        If CRN Is Nothing Then Return False
        If CRN = "" Then Return False

        Dim cTelotec_Anmeldung = TELOTEC_Worker.cTelotec_Anmeldung.LOADByCRN(CRN, True)

        If cTelotec_Anmeldung IsNot Nothing Then Return ImportTelotec(cTelotec_Anmeldung, overwrite, freshInsert)
        Return False
    End Function

    Public Function ImportTelotec(tel As cTelotec_Anmeldung, Optional overwrite As Boolean = True, Optional freshinsert As Boolean = False) As Boolean
        Try
            If tel Is Nothing Then Return False
            If String.IsNullOrWhiteSpace(ToStringSafe(tel.Refs_LRN)) AndAlso
               String.IsNullOrWhiteSpace(ToStringSafe(tel.Refs_CRN)) Then Return False

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

            ' ================================================================
            ' HEADER
            ' ================================================================
            'Dim mrnOrLrn As String = If(ToStringSafe(tel.Refs_CRN)
            Dim ZA As cVERAG_CustomsDeclarations = cVERAG_CustomsDeclarations.loadByMRN(tel.Refs_CRN, False)

            ZA.za_System = "TELOTEC"
            ZA.za_CustomsSystem = "ACCS"
            ZA.za_CustomsSystemCountry = "AT"
            ZA.za_REGIME = "IMPORT"
            ZA.za_IsExternalSystem = False
            ZA.za_IsFinalDeclaration = True

            ZA.za_Firma = ToStringSafe(tel.telanm_firma)
            ZA.za_Niederlassung = ToStringSafe(tel.telanm_niederlassung)


            ZA.za_MRN = ToStringSafe(tel.Refs_CRN)
            ZA.za_LRN = ToStringSafe(tel.Refs_LRN)

            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)

            If ZA.za_AvisoId Is Nothing AndAlso tel.telanm_AvisoId IsNot Nothing Then ZA.za_AvisoId = tel.telanm_AvisoId
            If ZA.za_SendungsId Is Nothing AndAlso tel.telanm_SendungsId IsNot Nothing Then ZA.za_SendungsId = tel.telanm_SendungsId


            ZA.za_RepresentationCode = ToStringSafe(tel.Declarant_DecRep)


            ZA.za_CustomsOffice = ToStringSafe(tel.Locs_CustPlc)
            ZA.za_EntryCustomsOffice = ToStringSafe(tel.EntryCO_Ref)

            ZA.za_DeclarationDate = ToNullableDate(tel.Hea_DecDT)
            ZA.za_AcceptanceDate = ToNullableDate(tel.Hea_AccDT)
            ZA.za_ReleaseDate = ToNullableDate(tel.Hea_DecDT)

            ZA.za_MainProcedure = ToStringSafe(tel.Hea_DecTy)

            ZA.za_MeansOfTransport_Vehicle = ToStringSafe(tel.Transp_DepIdnt)
            ZA.za_MeansOfTransport_Nationality = ToStringSafe(tel.Transp_DepNat)
            ZA.za_MeansOfTransport_Type = ToStringSafe(tel.Transp_DepTy)

            ZA.za_TransportModeBorder = ToStringSafe(tel.Transp_BordMo)
            ZA.za_TransportModeInland = ToStringSafe(tel.Transp_InMo)

            ZA.za_CountryDispatch = ToStringSafe(tel.Locs_Disp)
            ZA.za_CountryDestination = ToStringSafe(tel.Locs_Dest)
            ZA.za_CountryImport = "AT"

            ZA.za_WarehouseCode = ToStringSafe(tel.Locs_ArrLocAuth)

            ZA.za_InvoiceAmount = ToNullableDecimal(tel.ValData_InvVal)
            ZA.za_InvoiceCurrency = ToStringSafe(tel.ValData_InvCurr)

            ZA.za_Incoterms = ToStringSafe(tel.ValData_TermDelCd)
            ZA.za_IncotermsPlace = ToStringSafe(tel.ValData_TermDelPlc)


            ZA.za_Sachbearbeiter = tel.telanm_LetzteBearbeitung_SB

            ' ================================================================
            ' PARTIES (direkt aus Header-Feldern)
            ' ================================================================
            AddParty(ZA, "CONSIGNOR", tel.ConorTra_TIN, tel.ConorTra_Na, tel.ConorTra_Strt, tel.ConorTra_Pst, tel.ConorTra_Cty, tel.ConorTra_Ctry, tel.ConorTra_UID)
            AddParty(ZA, "CONSIGNEE", tel.ConeeTra_TIN, tel.ConeeTra_Na, tel.ConeeTra_Strt, tel.ConeeTra_Pst, tel.ConeeTra_Cty, tel.ConeeTra_Ctry, tel.ConeeTra_UID)
            AddParty(ZA, "EXPORTER", tel.ExpTra_TIN, tel.ExpTra_Na, tel.ExpTra_Strt, tel.ExpTra_Pst, tel.ExpTra_Cty, tel.ExpTra_Ctry, tel.ExpTra_UID)
            AddParty(ZA, "DECLARANT", tel.Declarant_TIN, tel.Declarant_Na, tel.Declarant_Strt, tel.Declarant_Pst, tel.Declarant_Cty, tel.Declarant_Ctry, tel.Declarant_UID)

            ' ================================================================
            ' ABGABEN (HEADER)
            ' ================================================================
            For Each a In tel.ABGABEN
                Dim d As New cVERAG_CustomsDeclarations_Duty With {
                    .zaDuty_DutyType = ToStringSafe(a.Ty),
                    .zaDuty_AmountEUR = ToNullableDecimal(a.Amnt),
                    .zaDuty_Currency = "EUR"
                }
                ZA.Duties.Add(d)
            Next

            ' ================================================================
            ' POSITIONEN
            ' ================================================================
            For Each p In tel.POSITIONSDATEN
                Dim it As New cVERAG_CustomsDeclarations_Item

                it.zaItem_PosNo = p.Pos_ID
                it.zaItem_HSCode = ToStringSafe(p.Item_ComCd)
                it.zaItem_Description = ToStringSafe(p.Item_GdsDes)
                it.zaItem_GrossMass = ToNullableDecimal(p.Item_Gross)
                it.zaItem_NetMass = ToNullableDecimal(p.Item_Net)
                it.zaItem_OriginCountry = ToStringSafe(p.Item_Orig)
                it.zaItem_MainProcedure = ToStringSafe(p.Item_ProcCd)
                it.zaItem_AdditionalProc = ToStringSafe(p.Item_ProcAddCd)

                Dim colli = 0
                Dim cnt = 0
                For Each pk In p.PACKSTUECKE
                    colli += pk.Pack_Nr
                    If cnt = 0 Then
                        it.zaItem_PackageMark = ToStringSafe(pk.Pack_Mark)
                        it.zaItem_PackageType = ToStringSafe(pk.Pack_Kind)
                    End If
                    cnt += 1
                Next

                it.zaItem_PackageColli = ToNullableDecimal(colli)


                it.zaItem_PreferenceCode = ToStringSafe(p.Item_Pref)
                it.zaItem_InvoiceValueEUR = ToNullableDecimal(p.Item_ItVal)
                it.zaItem_StatisticalValueEUR = ToNullableDecimal(p.Item_StatVal)

                '' ------------------------------------------------------------
                '' POSITIONS-ABGABEN
                '' ------------------------------------------------------------
                'For Each pa In p.ABGABEN
                '    Dim d As New cVERAG_CustomsDeclarations_Duty With {
                '        .zaDuty_DutyType = ToStringSafe(pa.Ty),
                '        .zaDuty_AmountEUR = ToNullableDecimal(pa.Amnt),
                '        .zaDuty_Currency = ToStringSafe(pa.Curr)
                '    }
                '    ZA.Duties.Add(d)
                'Next

                ' ------------------------------------------------------------
                ' DOKUMENTE
                ' ------------------------------------------------------------

                If p.DOC_CERTS IsNot Nothing Then

                    For Each doc In p.DOC_CERTS

                        Dim ItemId = Nothing
                        Dim Doc_Code As String = ToStringSafe(doc.DocCerts_DocCd)
                        Dim Doc_Reference As String = ToStringSafe(doc.DocCerts_DRef)
                        Dim Doc_Date As String = ToStringSafe(doc.DocCerts_IssD)

                        Try
                            Dim dd As New cVERAG_CustomsDeclarations_Document With {
                                .zaDoc_ItemId = ItemId,
                                .zaDoc_Code = Doc_Code,
                                .zaDoc_Reference = Doc_Reference,
                                .zaDoc_Date = Doc_Date
                            }
                            it.Documents.Add(dd)
                        Catch ex As Exception
                            cErrorHandler.ERR(ex.Message, ex.StackTrace, MethodInfo.GetCurrentMethod.Name)
                        End Try
                    Next

                End If

                ZA.Items.Add(it)
            Next


            ' ================================================================
            'CBAM WARNING
            ' ================================================================
            If freshinsert Then
                ZA.checkfreshCBAMWarning()
            End If
            ' ================================================================
            ' ================================================================
            ' SAVE
            Dim saved = ZA.SAVE()
            ' ======KAFKA==========================================================
            cDakosyEZA_Greenpulse.INSERT_KAFKA(ZA)
            ' ================================================================
            Return saved

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

    ' =====================================================================
    ' DUPLIKATSPRÜFUNG
    ' =====================================================================
    Private Function ExistsInVERAG(tel As cTelotec_Anmeldung) As Boolean
        Dim sql As String =
            "SELECT TOP 1 1 FROM tblVERAG_CustomsDeclarations " &
            "WHERE za_System='TELOTEC' AND (za_MRN=@mrn OR za_LRN=@lrn)"

        Dim p As New List(Of SQLVariable) From {
            New SQLVariable("mrn", tel.Refs_CRN),
            New SQLVariable("lrn", tel.Refs_LRN)
        }

        Dim dt = New SQL().loadDgvBySql_Param(sql, "VERAG", , p)
        Return dt IsNot Nothing AndAlso dt.Rows.Count > 0
    End Function

    ' =====================================================================
    ' PARTY HELPER
    ' =====================================================================
    Private Sub AddParty(za As cVERAG_CustomsDeclarations,
                               role As String,
                             eori As String,
                           name As Object,
                             street As Object,
                             plz As Object,
                             city As Object,
                             country As Object,
                             uid As Object)

        If String.IsNullOrWhiteSpace(ToStringSafe(name)) Then Exit Sub

        Dim p As New cVERAG_CustomsDeclarations_Parties With {
            .zaParty_EORI = eori,
            .zaParty_Role = role,
            .zaParty_Name = ToStringSafe(name),
            .zaParty_Street = ToStringSafe(street),
            .zaParty_PostalCode = ToStringSafe(plz),
            .zaParty_City = ToStringSafe(city),
            .zaParty_Country = ToStringSafe(country),
            .zaParty_VATNumber = ToStringSafe(uid)
        }

        za.Parties.Add(p)
    End Sub













    ' =========================================================================
    '  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 ""
        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