Imports VERAG_PROG_ALLGEMEIN
Public Class usrCntlModaltrans_NCTS

    Property ALLG As usrCntlModaltrans_EXIM_Allg
    Property ADRESSEN As usrCntlModaltrans_NCTS_Adressen
    'Property SICHERHEIT As usrCntlATLAS_NCTS_Sicherheit
    Property POSITIONEN As usrCntlModaltrans_NCTS_Positionen
    'Property VERSCHLUESSE As usrCntlATLAS_NCTS_Verschluesse
    Property Jahr2Stellig As Integer
    Property zusatz As String
    Property BezugsNr As String = ""
    Property AVISO As VERAG_PROG_ALLGEMEIN.cAviso
    Property SENDUNG As VERAG_PROG_ALLGEMEIN.cSendungen
    Property sendToModaltrans = False
    Property isSTAMMREF As Boolean = False ' Wenn das Formular als Stammreferenz bearbeitet wird
    Property STAMMREF As String = "" ' Wenn eine Stammrefereenz als Grundlage dient

    Dim FIRMA_DY = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

    Dim cDy_ART As String = If(FIRMA_DY = "ATILLA", "T2", "T1")

    Dim ncts_OUT As VERAG_PROG_ALLGEMEIN.cOregonNCTs_DeclarationData = Nothing
    'Dim DY_ANM As cDakosy_Zollanmeldungen = Nothing

    Sub New(AVISO As VERAG_PROG_ALLGEMEIN.cAviso, SENDUNG As VERAG_PROG_ALLGEMEIN.cSendungen, Jahr2Stellig As Integer, Optional zusatz As String = "", Optional isSTAMMREF As Boolean = False, Optional STAMMREF As String = "")
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()


        Me.Jahr2Stellig = Jahr2Stellig
        Me.zusatz = zusatz

        Me.AVISO = AVISO
        Me.SENDUNG = SENDUNG
        Me.isSTAMMREF = isSTAMMREF
        Me.STAMMREF = STAMMREF

        'DY_ANM = New cDakosy_Zollanmeldungen(ncts_OUT.ncts_dyaAnmID)

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
    End Sub



    Sub New(ART As String, Aviso As VERAG_PROG_ALLGEMEIN.cAviso, SENDUNG As VERAG_PROG_ALLGEMEIN.cSendungen, Jahr2Stellig As Integer, Optional zusatz As String = "", Optional isSTAMMREF As Boolean = False, Optional STAMMREF As String = "", Optional FIRMA_DY As String = "")
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        Me.cDy_ART = ART

        Me.AVISO = Aviso
        Me.SENDUNG = SENDUNG
        Me.isSTAMMREF = isSTAMMREF
        Me.STAMMREF = STAMMREF

        Me.Jahr2Stellig = Jahr2Stellig
        Me.zusatz = zusatz
        If FIRMA_DY <> "" Then Me.FIRMA_DY = FIRMA_DY
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
    End Sub

    Function getBezugsnr(ByRef BezugsNr)
        Dim BezugsNrTmp = ""
        Select Case FIRMA_DY
            Case "UNISPED"
                If If(SENDUNG.tblSnd_DakosyRef, "") <> "" Then
                    BezugsNrTmp = SENDUNG.tblSnd_DakosyRef
                Else
                    BezugsNrTmp = SENDUNG.FilialenNr & "/" & SENDUNG.AbfertigungsNr
                End If
            Case Else
                BezugsNrTmp = SENDUNG.FilialenNr & "/" & SENDUNG.AbfertigungsNr '& If(zusatz <> "", "/" & zusatz, "") 'zusatz ' & "/" & Jahr2Stellig
        End Select
        BezugsNr = BezugsNrTmp
        zusatz = "A"
        'Soloagne bis die Bezugsnummer noch nicht existiert
        While DAKOSY_Worker.cDakosy_Zollanmeldungen.ExistsBezugsNr(BezugsNr) 'IsNot Nothing
            BezugsNr = BezugsNrTmp & "/" & zusatz

            If zusatz.Length = 1 Then
                zusatz = Chr(Asc(zusatz.ToString) + 1)
            Else
                zusatz = zusatz.Substring(0, 1) & Chr(Asc(zusatz.Substring(0, 2).ToString) + 1)
            End If

            If zusatz = "Z" Then zusatz = "AA"
        End While
        lblBezugsnummer.Text = BezugsNr
        Return BezugsNr
    End Function

    Private Sub usrCntlModaltrans_Load(sender As Object, e As EventArgs) Handles Me.Load
        'MsgBox("LOAD")

        cboDakosyAction.Items.Clear()
        cboDakosyAction.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Neuen Datensatz erstellen", DY_ObjektAktion.OBJ_CREATE))
        cboDakosyAction.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Vohr. DS ändern", DY_ObjektAktion.OBJ_CHANGE))
        cboDakosyAction.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Vorh. DS stornieren", DY_ObjektAktion.OBJ_CANCEL))
        cboDakosyAction.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Datensatz an ZOLL senden", DY_ObjektAktion.OBJ_SEND))
        cboDakosyAction.changeItem(DY_ObjektAktion.OBJ_CREATE)

        Select Case FIRMA_DY
            Case "VERAG" : txtDyMandant.Text = "VERG"
                txtDyNiederlassung.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.NIEDERLASSUNG
            Case "ATILLA" : txtDyMandant.Text = "ATIL" : txtDyNiederlassung.Text = "SUW"
            Case "UNISPED" : txtDyMandant.Text = "UNAT" : txtDyNiederlassung.Text = "ATSPED"
            Case "IMEX" : txtDyMandant.Text = "IMEX" : txtDyNiederlassung.Text = "IME"
            Case "AMBAR" : txtDyMandant.Text = "ATIL" : txtDyNiederlassung.Text = "AMBWO"
        End Select


        cboStammreferenz.fillWithSQL("SELECT [reference],[descr] FROM [tblOregonNCTS_ReferenceTemplate] WHERE country='UK' AND declaration='import'  and mandant='" & txtDyMandant.Text & "'  and niederlassung IN ('','" & txtDyNiederlassung.Text & "')  and visible=1", False, "FMZOLL", True)
        cboStammreferenz.changeItem("")

        'SICHERHEIT = New usrCntlATLAS_NCTS_Sicherheit(ncts_OUT, FIRMA_DY)
        'VERSCHLUESSE = New usrCntlATLAS_NCTS_Verschluesse() 'ncts_OUT)
        ADRESSEN = New usrCntlModaltrans_NCTS_Adressen() ')
        ALLG = New usrCntlModaltrans_EXIM_Allg(ncts_OUT)
        POSITIONEN = New usrCntlModaltrans_NCTS_Positionen(ncts_OUT)

        If isSTAMMREF Then
            Me.BezugsNr = "STAMMREFERENZ"
            If ncts_OUT Is Nothing Then ncts_OUT = New VERAG_PROG_ALLGEMEIN.cOregonNCTs_DeclarationData()
            ncts_OUT.commercial_ref = BezugsNr
        Else
            If ncts_OUT Is Nothing Then ' NEUE ZOLLANMELDUNG
                Dim f As New frmModaltransStammreferenz("UK", "T1", True,,, FIRMA_DY)
                Dim Stammreferenz = Nothing
                If f.ShowDialog(Me) Then
                    Stammreferenz = f.STAMMREF
                End If
                Try

                    BezugsNr = getBezugsnr(BezugsNr)

                Catch ex As Exception
                    MsgBox(ex.Message & ex.StackTrace)
                End Try
                ncts_OUT = VERAG_PROG_ALLGEMEIN.cOregonNCTs_DeclarationData.LOADByBezugsNr(BezugsNr, True)
                If ncts_OUT Is Nothing Then
                    'Falls zur BezugsNr schon ein Eintrag in der DB vorhanden ist
                    'ncts_OUT = VERAG_PROG_ALLGEMEIN.cNCTS_TR.LOADByAnmIDFull(f.STAMMREF_DYID, True) ' DyID --> Falls bei der Stammreferenz eine Vorlage hinterlegt ist!


                    If ncts_OUT IsNot Nothing Then
                        'Stmmreferenz - Werte zurücksetzen, damit nicht falsch übergeben
                        ncts_OUT.status = -1
                        ncts_OUT.aviso_id = AVISO.AvisoID
                    Else
                        ncts_OUT = New VERAG_PROG_ALLGEMEIN.cOregonNCTs_DeclarationData()
                    End If


                    loaddataFromAVISO(ncts_OUT)
                    cboStammreferenz.changeItem(Stammreferenz)


                End If
                'ncts_OUT

            Else
                ' ncts_OUT is  ot nothing
                Me.BezugsNr = ncts_OUT.commercial_ref

                'MsgBox(ncts_OUT.ncts_Hauptverpflichteter_Name)

            End If
        End If

        Me.SplitContainer.Panel2.Controls.Add(ALLG)
        Me.SplitContainer.Panel2.Controls.Add(POSITIONEN)
        Me.SplitContainer.Panel2.Controls.Add(ADRESSEN)

        ADRESSEN.setValues_TR(ncts_OUT)
        ALLG.setValues(ncts_OUT)
        POSITIONEN.setValues_TR(ncts_OUT)

        Me.SplitContainer.Panel2.Controls.Clear()

        For Each c In MyFlowLayoutPanel1.Controls
            If c.GetType.ToString = GetType(System.Windows.Forms.Button).ToString Then
                AddHandler DirectCast(c, System.Windows.Forms.Button).Click, AddressOf buttonClick
            End If
        Next

        SplitContainer.Panel2.Controls.Add(ALLG)
        lblBezugsnummer.Text = BezugsNr




        ALLG.Dock = DockStyle.Fill
        ADRESSEN.Dock = DockStyle.Fill
        POSITIONEN.Dock = DockStyle.Fill

        AddHandler POSITIONEN.RohmasseChanged, Sub(rohmasse, packstuecke)
                                                   Label5.Text = packstuecke.ToString("N0") & " Pk"
                                                   Label7.Text = rohmasse.ToString("N2") & " kg"

                                               End Sub
        AddHandler POSITIONEN.PosAnzChanged, Sub(anz)
                                                 Label3.Text = anz
                                             End Sub

        If isSTAMMREF Then
            Button1.Visible = False
            cboDakosyAction.Visible = False
            lblBezugsnummer.Text = "STAMMREFERENZ"
            lblBezugsnummer.ForeColor = Color.Red
        End If


        If sendToModaltrans Then

            Try
                Me.Button1.PerformClick()
                Me.FindForm.Close()
            Catch
            End Try
        End If
        Try
            'If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("ZOLL_Modaltrans_AVISO_Edit", "AVISO") Then
            '    Me.FindForm.Close()
            'End If
        Catch
        End Try
    End Sub

    Sub buttonClick(sender As Object, e As EventArgs) 'HANDLED
        Dim btn As System.Windows.Forms.Button = DirectCast(sender, System.Windows.Forms.Button)

        For Each c In MyFlowLayoutPanel1.Controls
            If c.GetType.ToString = GetType(System.Windows.Forms.Button).ToString Then
                DirectCast(c, System.Windows.Forms.Button).BackColor = Drawing.Color.White
                DirectCast(c, System.Windows.Forms.Button).ForeColor = Drawing.Color.Black
            End If
        Next

        btn.BackColor = Drawing.Color.SteelBlue 'Drawing.Color.FromArgb(0, 54, 128)
        btn.ForeColor = Drawing.Color.White


        SplitContainer.Panel2.Controls.Clear()

        If btn Is btnAllgemein Then
            SplitContainer.Panel2.Controls.Add(ALLG)
        ElseIf btn Is btnAdressen Then
            SplitContainer.Panel2.Controls.Add(ADRESSEN)

        ElseIf btn Is btnPositionen Then
            SplitContainer.Panel2.Controls.Add(POSITIONEN)
        End If
    End Sub


    Sub loaddataFromAVISO(ByRef cdy As VERAG_PROG_ALLGEMEIN.cOregonNCTs_DeclarationData)
        Try

            '==> VORBLENDUNG:

            cdy.auto_send = False 'If the declaration is created correctly, and if it is desired to be sent directly to the customs system after this process, it should be set as "true".

            cdy.service_code = "cds" 'Options:  - "chief"  - "cds"
            cdy.doc_type = "" 'EXA, EXD, IMA, IMD declaration type code
            cdy.declaration_type = cDy_ART
            cdy.commercial_ref = BezugsNr
            cdy.ducr = ""
            cdy.mucr = ""
            cdy.ducr_part = ""





            cdy.export_country_id = ""

            cdy.multiple_consignor = False

            cdy.invoice_amount = ""
            cdy.invoice_curr = ""
            cdy.goods_location = ""
            cdy.border_transport_type = ""
            cdy.border_vehicle_code = ""
            cdy.border_vehicle_coun = ""
            cdy.inland_transport_type = ""
            cdy.container_no = ""
            cdy.gvms_interested = False
            cdy.freight_amount = ""
            cdy.freight_curr = ""
            cdy.payment_method = ""
            cdy.total_packages = 0
            cdy.nature_of_transaction = ""
            cdy.premises_code = ""
            cdy.first_dan_no = ""
            cdy.second_dan_no = ""
            cdy.insurance_amount = ""
            cdy.insurance_curr = ""
            cdy.other_amounts = ""
            cdy.other_amounts_curr = ""
            cdy.apportment_indicator = ""
            cdy.total_gross_weight = ""
            cdy.total_net_weight = ""
            cdy.airfreight_cost = ""
            cdy.vat_adjustment = ""
            cdy.vat_adjustment_curr = ""
            cdy.discount_amount = ""
            cdy.discount_curr = ""
            cdy.discount_rate = ""
            cdy.incoterm = ""
            cdy.incoterm_location = ""
            cdy.trader_ref = ""
            cdy.arrival_transport_type = ""
            cdy.guarantee_code = 0
            cdy.guarantee_reference = ""


            If AVISO IsNot Nothing Then


            End If

            cdy.consignee_eori = cProgramFunctions.isLeerNothing(SENDUNG.NCTS_Verzollungsadresse_EORI)
            cdy.consignee_name = cProgramFunctions.isLeerNothing(SENDUNG.tblSnd_NCTSVerzollungsadresse)
            cdy.consignee_address = cProgramFunctions.isLeerNothing(SENDUNG.NCTS_Verzollungsadresse_Strasse)
            cdy.consignee_postcode = cProgramFunctions.isLeerNothing(SENDUNG.NCTS_Verzollungsadresse_PLZ)
            cdy.consignee_city_name = cProgramFunctions.isLeerNothing(SENDUNG.NCTS_Verzollungsadresse_Ort)
            cdy.consignee_country_id = cProgramFunctions.isLeerNothing(SENDUNG.NCTS_Verzollungsadresse_Land)

            If AVISO.Frächter_KdNr IsNot Nothing AndAlso IsNumeric(AVISO.Frächter_KdNr) AndAlso AVISO.Frächter_KdNr > 0 Then
                Dim AD_Befoerderer As New VERAG_PROG_ALLGEMEIN.cAdressen(AVISO.Frächter_KdNr) ' Befoerderer
                Dim KD_Befoerderer As New VERAG_PROG_ALLGEMEIN.cKunde(AVISO.Frächter_KdNr) ' Befoerderer
                cdy.carrier_eori = KD_Befoerderer.EORITIN
                If KD_Befoerderer.EORITIN IsNot Nothing Then
                    'cdy.ncts_SumA_Befoerderer_NLNR = KD_Befoerderer.EORITIN_NL
                End If
                cdy.carrier_name = (If(AD_Befoerderer.Name_1, "") & " " & If(AD_Befoerderer.Name_2, "")).Trim
                cdy.carrier_address = AD_Befoerderer.Straße
                cdy.carrier_postcode = AD_Befoerderer.PLZ
                cdy.carrier_city_name = AD_Befoerderer.Ordnungsbegriff
                cdy.carrier_country_id = cProgramFunctions.getISO2Land(AD_Befoerderer.LandKz)
            Else
                cdy.carrier_name = If(AVISO.Frächter, "")
            End If





            If SENDUNG IsNot Nothing Then

                Dim FilialeAktFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale2(SENDUNG.FilialenNr,, "")


                cdy.declarant_eori = FilialeAktFirma
                cdy.declarant_name = FilialeAktFirma
                cdy.declarant_address = ""
                cdy.declarant_city_name = ""
                cdy.declarant_country_id = ""
                cdy.declarant_postcode = ""
                cdy.declarant_rep = ""


                If SENDUNG IsNot Nothing Then

                    Dim p As VERAG_PROG_ALLGEMEIN.cOregonNCTs_GoodsAttribute = Nothing
                    If cdy.goods.Count > 0 Then
                        p = cdy.goods(0)
                    Else
                        p = New VERAG_PROG_ALLGEMEIN.cOregonNCTs_GoodsAttribute
                        cdy.goods.Add(p) ' schon wieder...'nciht mehr anfügen
                    End If
                    p.commodity = SENDUNG.tblSnd_Warenbezeichnung

                    If SENDUNG.tblSnd_Colli IsNot Nothing AndAlso IsNumeric(SENDUNG.tblSnd_Colli) Then
                        Dim pk As New VERAG_PROG_ALLGEMEIN.cOregonNCTs_PacksAttribute
                        pk.pack_count = SENDUNG.tblSnd_Colli
                        pk.pack_type = "PK"
                        pk.goods_attribute_id = p.id
                        p.decl_PAckattributes.Add(pk)
                        'pk.SAVE()
                    End If
                    p.net_wg = IIf(IsNumeric(SENDUNG.tblSnd_Gewicht), CDbl(SENDUNG.tblSnd_Gewicht), 0)
                    p.invoice_amount = SENDUNG.tblSnd_Warenwert
                    p.invoice_curr = SENDUNG.tblSnd_WarenwertWaehrung


                    If SENDUNG.tblSnd_AbsenderKdNr > 0 Then
                        Dim adVERSENDER As New VERAG_PROG_ALLGEMEIN.cAdressen(SENDUNG.tblSnd_AbsenderKdNr)
                        Dim kdVERSENDER As New VERAG_PROG_ALLGEMEIN.cKunde(SENDUNG.tblSnd_AbsenderKdNr)
                        p.sender_eori_code = kdVERSENDER.EORITIN
                        p.sender_name = If(adVERSENDER.Name_1, "") & If(adVERSENDER.Name_2, "")
                        p.sender_address = adVERSENDER.Straße
                        p.sender_postcode = adVERSENDER.PLZ
                        p.sender_city_name = adVERSENDER.Ort
                        If adVERSENDER.LandKz IsNot Nothing Then
                            p.sender_country_id = cProgramFunctions.getISO2Land(adVERSENDER.LandKz)
                        End If

                    End If

                    If SENDUNG.tblSnd_EmpfaengerKdNr > 0 Then
                        Dim adEMPFAENGER As New VERAG_PROG_ALLGEMEIN.cAdressen(SENDUNG.tblSnd_EmpfaengerKdNr)
                        Dim kdEMPFAENGER As New VERAG_PROG_ALLGEMEIN.cKunde(SENDUNG.tblSnd_EmpfaengerKdNr)
                        p.consignee_eori_code = kdEMPFAENGER.EORITIN
                        p.consignee_name = If(adEMPFAENGER.Name_1, "") & If(adEMPFAENGER.Name_2, "")
                        p.consignee_address = adEMPFAENGER.Straße
                        p.consignee_postcode = adEMPFAENGER.PLZ
                        p.consignee_city_name = adEMPFAENGER.Ort
                        If adEMPFAENGER.LandKz IsNot Nothing Then
                            p.consignee_country_id = cProgramFunctions.getISO2Land(adEMPFAENGER.LandKz)
                        End If

                    End If

                End If
            End If


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


    Sub setValue(ncts_OUT)
        BezugsNr = ncts_OUT.commercial_ref

    End Sub


    Private Sub pnl_Paint(sender As Object, e As PaintEventArgs)

    End Sub

    Sub loadDYZollanmeldungen(Optional Status As String = "") ' + Speichern
        'If DY_ANM Is Nothing Then
        '    DY_ANM = New cDakosy_Zollanmeldungen(ncts_OUT.ncts_dyaAnmID)
        'End If
        'DY_ANM.dy_ART = ALLG.NCTS_ART 'cDy_ART
        'DY_ANM.dy_BezugsNr = BezugsNr
        'DY_ANM.dy_AvisoId = If(AVISO Is Nothing, Nothing, AVISO.AvisoID)
        'DY_ANM.dy_SendungsId = If(SENDUNG Is Nothing, Nothing, SENDUNG.tblSnd_SendungID)
        'DY_ANM.SAVE() 'Speichern, ID wird erzeugt  

    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Me.Refresh()
        Me.Cursor = Cursors.WaitCursor
        If False Then 'sentToDakosy OrElse vbYes = MsgBox("Sollen die Daten abgeschickt werden?" & vbNewLine & "Eine Änderung ist nur noch in der MIC Software möglich.", vbYesNoCancel) Then
            '  Dim cDyAnm As New cDakosy_Zollanmeldungen(cDy_ART, BezugsNr, AVISO.AvisoID, SENDUNG.tblSnd_SendungID)
            loadDYZollanmeldungen()

            If ncts_OUT IsNot Nothing Then


                loadInClass_VersandanmeldungNCTS(ncts_OUT, Me, FIRMA_DY)


                If Not ncts_OUT.SAVE_ALL() Then Exit Sub '---> DANN SCHON

            End If


        End If

            'DY_ANM.UPDATE_DATA()
            Me.FindForm.Close()

        Me.Cursor = Cursors.Default
    End Sub


    Private Sub SpeichernToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SpeichernToolStripMenuItem.Click

        Me.Refresh()
        loadDYZollanmeldungen()

        If ncts_OUT IsNot Nothing Then

            loadInClass_VersandanmeldungNCTS(ncts_OUT, Me, FIRMA_DY)

            If Not ncts_OUT.SAVE_ALL() Then
                'gespeichert
            End If


        End If
        'DY_ANM.UPDATE_DATA()

    End Sub

    Private Sub NeueBezugsnummerVergebenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NeueBezugsnummerVergebenToolStripMenuItem.Click
        BezugsNr = getBezugsnr(BezugsNr)
    End Sub

    Function loadInClass_VersandanmeldungNCTS(ByRef NCTS As VERAG_PROG_ALLGEMEIN.cOregonNCTs_DeclarationData, USRCNTL As usrCntlModaltrans_NCTS, FIRMA_DY As String) As VERAG_PROG_ALLGEMEIN.cOregonNCTs_DeclarationData
        Try



            NCTS.status = "00"
            NCTS.created = DateTime.Now()
            NCTS.aviso_id = If(USRCNTL.AVISO IsNot Nothing, USRCNTL.AVISO.AvisoID, Nothing)

            NCTS.commercial_ref = USRCNTL.BezugsNr
            USRCNTL.ALLG.getValues(NCTS)
            USRCNTL.ADRESSEN.getValues_TR(NCTS)
            USRCNTL.POSITIONEN.getValues_TR(NCTS)

            'NCTS.ncts_WARENPOS=USRCNTL.POSITIONEN.getValues()
            '--------------------------------



            Return NCTS

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

End Class
