Imports DocumentFormat.OpenXml.Drawing.Charts
Imports System.IO
Imports System.Windows.Controls.Primitives
Imports VERAG_PROG_ALLGEMEIN





'DATENSERVER!!!!!!!!!!!!!!!!!!

Public Class frmBerufung

    Dim ATR As VERAG_PROG_ALLGEMEIN.cOrigianlATR = Nothing
    Dim loadedDSID As Integer = -1
    Dim DSID As Integer = -1

    Sub New()
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
    End Sub
    Sub New(atr_id)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu. 
        ATR = New VERAG_PROG_ALLGEMEIN.cOrigianlATR(atr_id)
        loadedDSID = ATR.atr_dsId
    End Sub

    Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint

    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'If ATR IsNot Nothing Then
        '    If vbYes = MsgBox("Möchten Sie den Eintrag wirklich löchen?", vbYesNoCancel) Then
        '        If ATR.delete Then
        '            Me.Close()
        '        End If
        '    End If
        'End If
        Me.Close()
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

        If doValidation() Then
            If ATR Is Nothing Then
                ATR = New cOrigianlATR()
                ATR.atr_erfassungsdatum = Now
                ATR.atr_Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME
                ATR.atr_mitId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID

            End If

            getValues()

            'Falls keine Sendung gewählt, aber FilialeNr/AbfertigungsNr eingegeben:


            If ATR.atr_SendungsId <= 0 And ATR.atr_FilialenNr > 0 And ATR.atr_AbfertigungsNr > 0 Then
                'Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
                Dim SND = VERAG_PROG_ALLGEMEIN.cSendungen.LOADByFilialenNrAbfertigungsNr(ATR.atr_FilialenNr, ATR.atr_AbfertigungsNr)
                If SND IsNot Nothing Then
                    ATR.atr_SendungsId = SND.tblSnd_SendungID
                    ATR.atr_AvisoId = SND.tblSnd_AvisoID
                End If
            End If

            If (ATR.atr_SendungsId > 0 AndAlso ATR.atr_dsId > 0) And ((loadedDSID <> DSID Or loadedDSID <= 0) Or (loadedDSID > 0 And ATR.atr_anhID <= 0)) Then
                If vbYes = MsgBox("ATR in Anhang speichern?", vbYesNoCancel) Then
                    If ATR.atr_dsId < 0 Then
                        MsgBox("Kein PDF-Anhang!")
                    Else
                        Dim ANH = New VERAG_PROG_ALLGEMEIN.cAvisoAnhaenge(ATR.atr_anhID)
                        ANH.anh_SendungsId = ATR.atr_SendungsId
                        ANH.anh_AvisoId = ATR.atr_AvisoId
                        ANH.anh_docId = DSID
                        ANH.anh_Name = "ATR_ARCHIV"
                        ANH.anh_Typ = VERAG_PROG_ALLGEMEIN.cProgramFunctions.getFilePathTypeValid(VERAG_PROG_ALLGEMEIN.cDATENSERVER.GET_PDFPath_BY_DocID(DSID))
                        ANH.anh_Art = "ATR"
                        ANH.SAVE() 'Eintrag wird überschreiben 
                        ATR.atr_anhID = ANH.anh_id
                        insertVermerkATR(ATR)

                    End If
                End If
            End If

            If ATR.SAVE Then
                Me.Close()
                Exit Sub
            End If

        End If
        Me.DialogResult = DialogResult.None
    End Sub

    Shared Sub insertVermerkATR(ATR As VERAG_PROG_ALLGEMEIN.cOrigianlATR)

        Dim VermerkeCodeID = 110
        VERAG_PROG_ALLGEMEIN.cVermerkeDAL.DeleteSNDVermerkCode(ATR.atr_SendungsId, VermerkeCodeID) 'Alte löschen!
        Dim vermerkId = VERAG_PROG_ALLGEMEIN.cVermerkeDAL.insertSendungsVermerk(ATR.atr_SendungsId, ATR.atr_AvisoId, "ATR-Archiv", VermerkeCodeID)
        If vermerkId > 0 Then VERAG_PROG_ALLGEMEIN.cVermerkeDAL.toggleHervorheben(vermerkId) 'Hervorheben!

    End Sub

    Function doValidation() As Boolean
        lblErr_Ausstellungsdatum.Visible = False
        lblErr_DocNr.Visible = False
        lblErr_Aufbewarungsort.Visible = False
        lblErr_ErhaltenDatum.Visible = False

        If txtDocNumber.Text.Trim = "" Then lblErr_Ausstellungsdatum.Visible = True : Return False
        If txtDocDatum._value = "" Then lblErr_DocNr.Visible = True : Return False
        If txtErhaltenDatum._value = "" Then lblErr_ErhaltenDatum.Visible = True : Return False
        If txtLocation._value = "" Then lblErr_Aufbewarungsort.Visible = True : Return False

        Return True
    End Function




    Sub loadValues()

        If ATR.atr_empfaengerkdnr > -1 Then
            txtEmpfaenger.KdNr = ATR.atr_empfaengerkdnr
        Else
            txtEmpfaenger.KdNr_value = -1
            txtEmpfaenger.Text = ATR.atr_empfaenger
        End If

        If ATR.atr_absenderkdnr > -1 Then
            txtAbsender.KdNr = ATR.atr_absenderkdnr
        Else
            txtAbsender.KdNr_value = -1
            txtAbsender.Text = ATR.atr_absender
        End If

        txtLocation.Text = If(ATR.atr_location, "")
        txtInfo.Text = If(ATR.atr_info, "")

        DSID = ATR.atr_dsId
        togglePDFPic()
        txtDocNumber.Text = If(ATR.atr_documentNr, "")
        txtDocDatum._value = If(ATR.atr_austellungsdatum, "")
        txtKennzeichen.Text = If(ATR.atr_LKW, "")
        txtFiliale._value = If(ATR.atr_FilialenNr > 0, ATR.atr_FilialenNr, "")
        txtAbfNr._value = If(ATR.atr_AbfertigungsNr > 0, ATR.atr_AbfertigungsNr, "")

        sbAvisoSuche.SET_VALUE(ATR.atr_SendungsId)

        If ATR.atr_erhalenDatum IsNot Nothing Then
            txtErhaltenDatum._value = CDate(ATR.atr_erhalenDatum).ToShortDateString
            txtErhaltenUhrzeit._value = CDate(ATR.atr_erhalenDatum).ToShortTimeString
        End If

        txtErhaltenReferenz.Text = If(ATR.atr_DHL_ReferenzNr, "")
        Select Case If(ATR.atr_erhalten_Art, "")
            Case "PAKETDIENST" : cbxKurierPaketdienst.Checked = True
            Case "MOTORRAD" : cbxKurierMotorrad.Checked = True
        End Select
    End Sub
    Sub getValues()

        ATR.atr_documentNr = txtDocNumber.Text
        ATR.atr_austellungsdatum = txtDocDatum._value
        'ATR.atr_erfassungsdatum = Now
        ATR.atr_absender = If(txtAbsender.KdNr > 0, txtAbsender.KdName, txtAbsender.Text)
        ATR.atr_absenderkdnr = txtAbsender.KdNr
        ATR.atr_empfaenger = If(txtEmpfaenger.KdNr > 0, txtEmpfaenger.KdName, txtEmpfaenger.Text)
        ATR.atr_empfaengerkdnr = txtEmpfaenger.KdNr
        ATR.atr_location = txtLocation.Text
        ATR.atr_info = txtInfo.Text
        ATR.atr_dsId = DSID
        If txtFiliale._value <> "" Then ATR.atr_FilialenNr = txtFiliale._value
        If txtAbfNr._value <> "" Then ATR.atr_AbfertigungsNr = txtAbfNr._value
        ATR.atr_LKW = txtKennzeichen.Text

        ATR.atr_SendungsId = If(sbAvisoSuche._value <> "", sbAvisoSuche._value, -1)
        If sbAvisoSuche._value <> "" Then
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            ATR.atr_AvisoId = SQL.DLookup("tblSnd_AvisoId", "tblSendungen", " tblSnd_SendungID='" & sbAvisoSuche._value & "'", "AVISO", -1)
        End If



        If txtErhaltenDatum._value <> "" Then
            If txtErhaltenUhrzeit._value <> "" Then
                ATR.atr_erhalenDatum = CDate(txtErhaltenDatum._value & " " & txtErhaltenUhrzeit._value)
            Else
                ATR.atr_erhalenDatum = CDate(txtErhaltenDatum._value)
            End If
        End If
        ATR.atr_DHL_ReferenzNr = txtErhaltenReferenz.Text

        If cbxKurierPaketdienst.Checked Then ATR.atr_erhalten_Art = "PAKETDIENST"
        If cbxKurierMotorrad.Checked Then ATR.atr_erhalten_Art = "MOTORRAD"


    End Sub
    Private Sub frmATR_Load(sender As Object, e As EventArgs) Handles Me.Load
        txtAbsender.initKdBox(Me)

        txtEmpfaenger.initKdBox(Me)

        'sbAvisoSuche.initSearchBox(Me.FindForm, " [tblSnd_SendungID],LKW_Nr,[tblSnd_Empfaenger],[tblSnd_Absender],[tblSnd_Colli],[tblSnd_Gewicht],FilialenNr,AbfertigungsNr,[Code]+' - ' +[Description] as display   FROM tbl_DY_ZollDE_C0008_LaenderFull", {"Code", "Description"}, " (StartDate is null OR StartDate< GETDATE()) AND (EndDate is null OR EndDate> GETDATE()) ", "Code", "Code", "display", "FMZOLL", , 400, 200)
        ' sbAvisoSuche.initSearchBox(Me.FindForm, " [tblSnd_SendungID] ,Datum as Erfasst,LKW_Nr,[tblSnd_Empfaenger],[tblSnd_Absender],[tblSnd_Colli],[tblSnd_Gewicht],FilialenNr,AbfertigungsNr    FROM tblSendungen inner join Aviso on AvisoID=tblSnd_AvisoID ", {"LKW_Nr", "tblSnd_Empfaenger", "tblSnd_Absender"}, " (Datum >= '" & Now.AddDays(-30).ToShortDateString & "') ", "Datum DESC", "tblSnd_SendungID", "Datum as Erfasst,LKW_Nr,[tblSnd_Empfaenger],[tblSnd_Absender],[tblSnd_Colli],[tblSnd_Gewicht],FilialenNr,AbfertigungsNr", "AVISO", False, 600, 300)
        sbAvisoSuche.initSearchBox(Me.FindForm, " [tblSnd_SendungID] ,Datum as Erfasst,LKW_Nr,[tblSnd_Empfaenger],[tblSnd_Absender],[tblSnd_Colli],[tblSnd_Gewicht],FilialenNr,AbfertigungsNr,LKW_Nr + ' ' +cast(FilialenNr as varchar(4)) +'/'+cast(AbfertigungsNr as varchar(8))as display    FROM tblSendungen inner join Aviso on AvisoID=tblSnd_AvisoID ", {"LKW_Nr", "tblSnd_Empfaenger", "tblSnd_Absender"}, " Cluster='" & VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER & "'  /*AND (Datum >= '" & Now.AddDays(-40).ToShortDateString & "') */ ", " Datum DESC", "tblSnd_SendungID", "display", "AVISO", False, 600, 300)


        If ATR IsNot Nothing Then
            loadValues()
        Else
            If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERIMEX" Then
                txtLocation.Text = "VERIMEX"
            End If
            If VERAG_PROG_ALLGEMEIN.cAllgemein.ABTEILUNG = "VRR" Then
                txtLocation.Text = "VERRECHNUNG"
            End If

        End If


        AddHandler txtAbsender.PropertyChanged, Sub()
                                                    FlatButton4.BackgroundImage = IIf(txtAbsender.KdNr > 0, My.Resources.person, My.Resources.personInaktiv)
                                                    ' ATR.atr_absender = txtAbsender.Text
                                                    '  ATR.atr_absenderKdNr = txtAbsender.KdNr

                                                End Sub


        AddHandler txtEmpfaenger.PropertyChanged, Sub()
                                                      FlatButton4.BackgroundImage = IIf(txtEmpfaenger.KdNr > 0, My.Resources.person, My.Resources.personInaktiv)
                                                      'ATR.atr_empfaenger = txtEmpfaenger.Text
                                                      'ATR.atr_empfaengerKdNr = txtEmpfaenger.KdNr

                                                  End Sub


        togglePDFPic()
    End Sub

    Sub togglePDFPic()
        If DSID > 0 Then
            PictureBox1.BackgroundImage = My.Resources.pdf
        Else
            PictureBox1.BackgroundImage = My.Resources.pdf_gray
        End If
    End Sub
    Private Sub FlatButton4_Click(sender As Object, e As EventArgs) Handles FlatButton4.Click
        If txtAbsender.KdNr > 0 Then
            Me.Cursor = Cursors.WaitCursor

            Dim zoll As New SDL.frmKundenUebersichtZOLL(txtAbsender.KdNr)
            If zoll IsNot Nothing Then zoll.Show()

            Me.Cursor = Cursors.Default
        End If
    End Sub
    Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click
        If txtEmpfaenger.KdNr > 0 Then
            Me.Cursor = Cursors.WaitCursor

            Dim zoll As New SDL.frmKundenUebersichtZOLL(txtEmpfaenger.KdNr)
            If zoll IsNot Nothing Then zoll.Show()

            Me.Cursor = Cursors.Default
        End If
    End Sub

    Private Sub sbAvisoSuche_TextChanged() Handles sbAvisoSuche.VALUE_CHANGED
        txtFiliale.Text = ""
        txtAbfNr.Text = ""
        If sbAvisoSuche._value <> "" Then

            Dim SND As New VERAG_PROG_ALLGEMEIN.cSendungen(sbAvisoSuche._value)
            If SND IsNot Nothing Then
                Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(SND.tblSnd_AvisoID)
                txtFiliale._value = SND.FilialenNr
                txtAbfNr._value = SND.AbfertigungsNr
                lblLKWId.Text = SND.tblSnd_AvisoID
                If AVISO IsNot Nothing Then
                    txtKennzeichen.Text = AVISO.LKW_Nr
                End If
                ' lblKennzeichen.Visible = True
                lblLKWId.Visible = True
            End If
        End If
    End Sub

    Private Sub btnScan_Click(sender As Object, e As EventArgs) Handles btnScan.Click
        quickScan()
        togglePDFPic()
    End Sub

    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
        If DSID > 0 Then
            Dim path = VERAG_PROG_ALLGEMEIN.cDATENSERVER.GET_PDFPath_BY_DocID(DSID)
            If path <> "" Then Process.Start(path)
            'VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.OPEN_PATH(DSID)

        End If
    End Sub

    Private Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
        addData_AnhangFD()
        togglePDFPic()
    End Sub

    Public Sub addData_AnhangFD()
        Dim fd As New OpenFileDialog
        fd.Multiselect = False

        If fd.ShowDialog = vbOK Then
            '   For Each F_listItem In fd.FileNames

            Dim fi As New FileInfo(fd.FileName)
            Dim filename = fi.Name
            If filename = "" Then
                MsgBox("Dateiname konnte nicht ermittelt werden." & vbNewLine & fd.FileName)
            Else

                '   Dim TMP_Path = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getTMPPath(filename, fi.Extension,, False, "SendungsAnhaenge")
                ' MsgBox(TMP_Path)
                '  File.Copy(F_listItem, TMP_Path)
                Dim anhId = -1
                Dim destPath = ""

                Dim Typ = ""
                If getFileTypeValid(fi.Extension.Replace(".", ""), Typ) Then
                    If saveToDS(filename, fd.FileName, "ATR", Typ, DSID, anhId, destPath) Then

                    End If

                End If
            End If
            'Next
            '  If flpnlAviso.Controls.Count > 0 Then DirectCast(flpnlAviso.Controls(0), usrCntlSendungAnhangElement).CLICK_Me()
        End If
    End Sub

    Public Shared Function getFileTypeValid(extension, ByRef Typ) As Boolean
        Select Case extension.ToString.Replace(".", "").ToUpper
            Case "PDF" : Typ = "PDF"
            Case "XLS", "XLM", "XLSM", "XLSX", "CSV" : Typ = "EXCEL"
            Case "DOC", "DOCX" : Typ = "WORD"
            Case "TXT" : Typ = "TEXT"
            Case "JPEG", "JPG", "GIF", "TFF" : Typ = "BILD"
            Case "EXE" : MsgBox("Aviso-Anhänge: Ungültiges Datei-Format!") : Return False
            Case Else : Typ = "SONSTIGES"
        End Select
        Return True
    End Function

    Public Shared Function saveToDS(ByRef fileName, sourcePath, Art, Typ, Optional ByRef da_id = -1, Optional ByRef anhId = -1, Optional ByRef destPath = "", Optional SendungsId = Nothing) As Boolean
        fileName = VERAG_PROG_ALLGEMEIN.cDATENSERVER.replaceInvalidCahr(fileName)

        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "ORIGINAL_ATR_ARCHIV", Now.Year, Now.ToString("ddMMyy"), "", Now.ToString("ddMMyyHHmmss") & fileName, -1, False)
        If Not DS.uploadDataToDATENSERVER(sourcePath) Then MsgBox("Fehler beim Speichern: Datenserver!") : Return False
        If DS.da_id <= 0 Then MsgBox("Keine DocId!") : Return False

        da_id = DS.da_id
        destPath = DS.GET_TOP1_PATH
        Dim fi As New FileInfo(sourcePath)
        Return True
    End Function

    Public Function quickScan(Optional SendungsId = Nothing) As Boolean
        Try
            'If KdNr < 0 Then Exit Sub
            Dim frmScan As New VERAG_PROG_ALLGEMEIN.frmScan("QuickScan")
            frmScan.DefaultFileName = "ScanATR" & Now.ToString("ddMMyyyy_HHmmss") ' Me._TEXT_PDF

            If frmScan.ShowDialog() = DialogResult.OK Then
                If frmScan.ReturnValue IsNot Nothing Then
                    Dim Filename = frmScan.fileName
                    Dim TMP_Path = VERAG_PROG_ALLGEMEIN.DATENVERVER_OPTIONS.getTMPPath(Filename, ".pdf",, False, "SendungsAnhaenge")
                    File.WriteAllBytes(TMP_Path, frmScan.ReturnValue)

                    Dim anhId = -1
                    Dim destPath = ""
                    If saveToDS(Filename, TMP_Path, "ATR", "PDF", DSID, anhId, destPath, SendungsId) Then
                        Return True
                    End If
                    'addUsrcnlToPnl(TMP_Path)
                End If
            End If

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

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim data As IDataObject = Clipboard.GetDataObject
        If True Then 'data.GetDataPresent(DataFormats.FileDrop) Then
            For Each s As String In My.Computer.Clipboard.GetFileDropList() 'GetData(DataFormats.) 'data.GetData(DataFormats.FileDrop) 'DataFormats.FileDrop)
                ' Dim F_listItem As String = Path.Combine("c:\mynewpath", Path.GetFileName(s))
                ' File.Copy(s, newFile)
                '  MsgBox(s)
                If System.IO.File.Exists(s) Then

                    Dim fi As New FileInfo(s)
                    Dim filename = fi.Name
                    If filename = "" Then
                        MsgBox("Dateiname konnte nicht ermittelt werden." & vbNewLine & s)
                    Else

                        Dim anhId = -1
                        Dim destPath = ""

                        Dim Typ = ""
                        If getFileTypeValid(fi.Extension.Replace(".", ""), Typ) Then
                            If saveToDS(filename, s, "ATR", Typ, DSID, anhId, destPath) Then
                                MsgBox("Dokument wurde hochgeladen.")
                            End If
                        End If
                    End If
                End If
            Next

        End If
        togglePDFPic()
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        txtLocation.Text = "VERIMEX"
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        txtLocation.Text = "VERRECHNUNG"
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        txtLocation.Text = "FRONT-OFFICE"
    End Sub

    Private Sub Panel1_DragDrop(sender As Object, e As DragEventArgs) Handles Panel1.DragDrop, PictureBox1.DragDrop

        Try
            Dim added = False

            If e.Data.GetDataPresent(DataFormats.FileDrop) Then
                Dim files() As String = e.Data.GetData(DataFormats.FileDrop)

                If files.Count > 1 Then
                    MsgBox("Nur eine Datei möglich!")
                ElseIf files.Count > 0 Then
                    If files(0) <> "" Then
                        Dim fio As New System.IO.FileInfo(files(0))
                        If saveToDS(fio.Name, files(0), "ATR", "", DSID) Then
                            MsgBox("Dokument wurde hochgeladen.")
                        End If
                    End If
                End If

            ElseIf e.Data.GetDataPresent("FileGroupDescriptor") Then
                Dim FilePath = VERAG_PROG_ALLGEMEIN.cProgramFunctions.EmAilAttach(e)
                If FilePath <> "" Then
                    Dim fio As New System.IO.FileInfo(FilePath)
                    If saveToDS(fio.Name, FilePath, "ATR", "", DSID) Then
                        MsgBox("Dokument wurde hochgeladen.")
                    End If
                End If
            End If



            togglePDFPic()
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Sub

    Private Sub PictureBox6_Click(sender As Object, e As EventArgs) Handles PictureBox6.Click
        Dim webAddress As String = "https://wiki.verag.ag/de/software/aviso/howtos/ATRArchiv"
        Process.Start(webAddress)
    End Sub

End Class