Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Net.Http
Imports System.Text
Imports System.Threading.Tasks
Imports com.sun.tools.doclets.internal.toolkit.util
Imports sun.net.www.http



Public Class frmZollBrgBuchungenFremd

    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

    Public Sub EnrichDgvWithMrnData(dgv As DataGridView)
        If dgv Is Nothing OrElse dgv.Columns.Count = 0 Then Exit Sub

        ' 1) Zielspalten in der DGV sicherstellen
        EnsureDgvColumn(dgv, "Datum", GetType(Date))
        EnsureDgvColumn(dgv, "CustomsOfficeOfDestination", GetType(String))
        EnsureDgvColumn(dgv, "PlateNumber", GetType(String))
        EnsureDgvColumn(dgv, "Customer", GetType(String))
        EnsureDgvColumn(dgv, "Agent", GetType(String))
        EnsureDgvColumn(dgv, "Comment", GetType(String))
        dgv.Columns("Datum").DefaultCellStyle.Format = "dd.MM.yyyy"

        ' 2) MRNs aus der ersten Spalte einsammeln (Distinct, nicht leer)
        Dim mrns As List(Of String) =
                (From r As DataGridViewRow In dgv.Rows
                 Where Not r.IsNewRow
                 Let v = If(r.Cells(0).Value, "").ToString().Trim()
                 Where v <> ""
                 Select v).Distinct(StringComparer.OrdinalIgnoreCase).ToList()

        If mrns.Count = 0 Then Exit Sub

        ' 3) Daten aus DB laden (beide Quellen)
        Dim results As Dictionary(Of String, MrnRow) = LoadMrnData(mrns)

        ' 4) Ergebnisse in die DGV zurückschreiben
        For Each row As DataGridViewRow In dgv.Rows
            If row.IsNewRow Then Continue For
            Dim key As String = If(row.Cells(0).Value, "").ToString().Trim()
            If key = "" Then Continue For

            Dim hit As MrnRow = Nothing
            If results.TryGetValue(key, hit) Then
                row.Cells("Datum").Value = If(hit.Datum.HasValue, hit.Datum.Value, CType(Nothing, Date?))
                row.Cells("CustomsOfficeOfDestination").Value = hit.CustomsOfficeOfDestination
                row.Cells("PlateNumber").Value = hit.PlateNumber
                row.Cells("Customer").Value = hit.Customer
                row.Cells("Agent").Value = hit.Firma
                row.Cells("Comment").Value = ""
            Else

                Dim result As Boolean = NctsChecker.HasNoInfo(key)

                If result Then
                    ' Falls nicht gefunden, optional leeren:
                    row.Cells("Datum").Value = Nothing
                    row.Cells("CustomsOfficeOfDestination").Value = Nothing
                    row.Cells("PlateNumber").Value = Nothing
                    row.Cells("Customer").Value = Nothing
                    row.Cells("Agent").Value = Nothing
                    row.Cells("Comment").Value = "Not found"
                Else
                    ' Falls nicht gefunden, optional leeren:
                    row.Cells("Datum").Value = Nothing
                    row.Cells("CustomsOfficeOfDestination").Value = Nothing
                    row.Cells("PlateNumber").Value = Nothing
                    row.Cells("Customer").Value = Nothing
                    row.Cells("Agent").Value = Nothing
                    row.Cells("Comment").Value = "?????"
                End If

            End If
        Next
    End Sub

    Private Sub EnsureDgvColumn(dgv As DataGridView, colName As String, t As Type)
        If Not dgv.Columns.Contains(colName) Then
            Dim c As New DataGridViewTextBoxColumn()
            c.Name = colName
            c.HeaderText = colName
            dgv.Columns.Add(c)
        End If
    End Sub

    Private Class MrnRow
        Public Property MRN As String
        Public Property Datum As Date?
        Public Property CustomsOfficeOfDestination As String
        Public Property PlateNumber As String
        Public Property Customer As String
        Public Property Firma As String
        Public Property Source As String ' "NCTS" oder "TELOTEC"
    End Class

    Private Function LoadMrnData(mrns As List(Of String)) As Dictionary(Of String, MrnRow)
        Dim res As New Dictionary(Of String, MrnRow)(StringComparer.OrdinalIgnoreCase)

        Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL()
            ' ---------- DAKOSY / NCTS ----------
            Dim nctsParam = mrns.Select(Function(val, i) "@pN" & i).ToArray()
            Dim nctsSql As String =
                "SELECT 
                ncts_MRN AS MRN,
                CAST(ncts_Trans_DatumZeit AS date) AS Datum,
                ncts_CustomsOfficeOfDestinationDeclared AS CustomsOfficeOfDestination,
                ISNULL(ncts_DepartureTransportMeans_1_IdentificationNumber, ncts_ActiveBorderTransportMeans_1_IdentificationNumber) AS PlateNumber,
                [Aviso].Auftraggeber AS Customer,
                CASE 
                    WHEN LEFT(ncts_ObjectName,4) IN ('4801','4802') THEN 'ATILLA'
                    WHEN LEFT(ncts_ObjectName,4) = '5601' THEN 'UNISPED'
                    ELSE 'VERAG'
                END AS Firma
            FROM [VERAG].[dbo].[tblDakosy_NCTSOut004]
            INNER JOIN tblDakosy_Zollanmeldungen ON ncts_dyaAnmID = dy_Id
            LEFT JOIN [AVISO].[dbo].[Aviso] ON dy_AvisoId = Avisoid
            WHERE ncts_MRN IN (" & String.Join(",", nctsParam) & ");"

            Using cmd As New SqlCommand(nctsSql, conn)
                For i = 0 To mrns.Count - 1 : cmd.Parameters.AddWithValue(nctsParam(i), mrns(i)) : Next
                Using rd = cmd.ExecuteReader()
                    While rd.Read()
                        Dim m As New MrnRow With {
                            .MRN = rd("MRN").ToString(),
                            .Datum = If(IsDBNull(rd("Datum")), CType(Nothing, Date?), CType(rd("Datum"), Date)),
                            .CustomsOfficeOfDestination = If(rd("CustomsOfficeOfDestination") Is DBNull.Value, Nothing, rd("CustomsOfficeOfDestination").ToString()),
                            .PlateNumber = If(rd("PlateNumber") Is DBNull.Value, Nothing, rd("PlateNumber").ToString()),
                            .Customer = If(rd("Customer") Is DBNull.Value, Nothing, rd("Customer").ToString()),
                            .Firma = If(rd("Firma") Is DBNull.Value, Nothing, rd("Firma").ToString()),
                            .Source = "DAKOSY/NCTS"
                        }
                        res(m.MRN) = m ' NCTS hat Vorrang
                    End While
                End Using
            End Using

            ' ---------- TELOTEC ----------
            Dim telParam = mrns.Select(Function(val, i) "@pT" & i).ToArray()
            Dim teloSql As String =
                "SELECT
                telanm_CRN AS MRN,
                CAST(Hea_DecDT AS date) AS Datum,
                DestCO_Ref AS CustomsOfficeOfDestination,
                Transp_CrossIdnt AS PlateNumber,
                CAST(Mandant_ID AS nvarchar(50)) AS Customer,
                '' AS Firma
            FROM [VERAG].[dbo].[tblTelotec_Anmeldung]
            WHERE telanm_CRN IN (" & String.Join(",", telParam) & ")
              AND [telnam_aktuellsteNachricht] = 1;"

            Using cmd As New SqlCommand(teloSql, conn)
                For i = 0 To mrns.Count - 1 : cmd.Parameters.AddWithValue(telParam(i), mrns(i)) : Next
                Using rd = cmd.ExecuteReader()
                    While rd.Read()
                        Dim mrn As String = rd("MRN").ToString()
                        If Not res.ContainsKey(mrn) Then
                            Dim m As New MrnRow With {
                                .MRN = mrn,
                                .Datum = If(IsDBNull(rd("Datum")), CType(Nothing, Date?), CType(rd("Datum"), Date)),
                                .CustomsOfficeOfDestination = If(rd("CustomsOfficeOfDestination") Is DBNull.Value, Nothing, rd("CustomsOfficeOfDestination").ToString()),
                                .PlateNumber = If(rd("PlateNumber") Is DBNull.Value, Nothing, rd("PlateNumber").ToString()),
                                .Customer = If(rd("Customer") Is DBNull.Value, Nothing, rd("Customer").ToString()),
                                .Firma = "",
                                .Source = "TELOTEC"
                            }
                            res.Add(mrn, m)
                        End If
                    End While
                End Using
            End Using


        End Using
        If cbxEZollDaten.Checked Then

            Using conn As SqlConnection = SQL.GetNewOpenConnectionEZOLL()
                ' ---------- EZOLL ----------
                ' Hinweis: Falls die View in einer anderen DB/Connection liegt, ggf. eigene Connection öffnen (z. B. SQL.GetNewOpenConnectionEZOLL()).
                Dim ezParam = mrns.Select(Function(val, i) "@pE" & i).ToArray()
                Dim ezSql As String =
                    "SELECT
                    ISNULL(v.CRN,'') AS MRN,
                    CAST(v.AnmeldungsDatum AS date) AS Datum,
                    ISNULL(v.Bestimmungszollstelle,'') AS CustomsOfficeOfDestination,
                    (SELECT TOP 1 t.CrossIdnt FROM ezoll.dbo.zsAnmTransp t WHERE t.AnmID = v.AnmID) AS PlateNumber,
                    (SELECT TOP 1 c.Na FROM ezoll.dbo.zsAnmCarrTra c WHERE c.AnmID = v.AnmID) AS Firma,
                    (SELECT TOP 1 c.Na FROM ezoll.dbo.zsAnmCarrTra c WHERE c.AnmID = v.AnmID) AS Customer
                FROM vwVERAG_Zolaris_EZoll_NCTS_Datenübernahme_Eroeffnung v
                WHERE v.CRN IN (" & String.Join(",", ezParam) & ");"

                Using cmd As New SqlCommand(ezSql, conn)
                    For i = 0 To mrns.Count - 1 : cmd.Parameters.AddWithValue(ezParam(i), mrns(i)) : Next
                    Using rd = cmd.ExecuteReader()
                        While rd.Read()
                            Dim mrn As String = rd("MRN").ToString()
                            If mrn = "" Then Continue While
                            If Not res.ContainsKey(mrn) Then
                                Dim m As New MrnRow With {
                                    .MRN = mrn,
                                    .Datum = If(IsDBNull(rd("Datum")), CType(Nothing, Date?), CType(rd("Datum"), Date)),
                                    .CustomsOfficeOfDestination = If(rd("CustomsOfficeOfDestination") Is DBNull.Value, Nothing, rd("CustomsOfficeOfDestination").ToString()),
                                    .PlateNumber = If(rd("PlateNumber") Is DBNull.Value, Nothing, rd("PlateNumber").ToString()),
                                    .Customer = If(rd("Customer") Is DBNull.Value, Nothing, rd("Customer").ToString()),
                                    .Firma = If(rd("Firma") Is DBNull.Value, Nothing, rd("Firma").ToString()),
                                    .Source = "EZOLL"
                                }
                                res.Add(mrn, m)
                            End If
                        End While
                    End Using
                End Using

            End Using

        End If
        Return res
    End Function

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        EnrichDgvWithMrnData(MyDatagridview1)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Cursor = Cursors.WaitCursor
        cProgramFunctions.genExcelFromDGV_NEW(MyDatagridview1, False)
        Me.Cursor = Cursors.Default
    End Sub

    Public Sub ClearDgvKeepMrn(dgv As DataGridView)
        If dgv Is Nothing Then Exit Sub

        ' --- Spalten löschen (alle außer der ersten) ---
        For i As Integer = dgv.Columns.Count - 1 To 1 Step -1
            dgv.Columns.RemoveAt(i)
        Next

        ' --- Zeilen löschen ---
        dgv.Rows.Clear()
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        ClearDgvKeepMrn(MyDatagridview1)
    End Sub


End Class

Public Class NctsChecker
    ' WICHTIG: direkt mrn_list.jsp, nicht mrn_home.jsp
    Private Shared ReadOnly baseUrl As String = "https://ec.europa.eu/taxation_customs/dds2/mrn/mrn_list.jsp?Lang=en&MRN="

    ''' <summary>
    ''' True  = Seite meldet "No information found that satisfies the request."
    ''' False = Daten vorhanden ODER Fehler beim Abruf
    ''' </summary>
    Public Shared Function HasNoInfo(mrn As String) As Boolean
        Dim url As String = baseUrl & mrn.Trim()

        Try
            Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
            request.Method = "GET"
            request.UserAgent = "Mozilla/5.0"

            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
                Using reader As New StreamReader(response.GetResponseStream(), Encoding.UTF8)
                    Dim html As String = reader.ReadToEnd()

                    ' Debug: HTML ansehen
                    ' File.WriteAllText("C:\temp\ncts_" & mrn & ".html", html)

                    ' Hier auf den bekannten Text prüfen
                    If html.Contains("No information found that satisfies the request.") Then
                        Return True      ' -> keine Information
                    Else
                        Return False     ' -> irgendwas gefunden
                    End If
                End Using
            End Using

        Catch ex As Exception
            ' Im Fehlerfall: wie gewünscht behandeln
            ' Wenn du bei Fehler lieber auch "keine Info" zurückgeben willst, hier True setzen.
            Return False
        End Try
    End Function

End Class