Imports Microsoft.Office.Interop
Imports System.Drawing.Printing

Public Class frmSDLBestellungEintrag

    
    Dim TMP_KdNr As Integer
    Dim TMP_SDLNr As Integer
    Dim saveInProgress = False
    Sub New()

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

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

    End Sub

   

    Sub New(KdNr As Integer, SDLNr As Integer)
        InitializeComponent()
        TMP_KdNr = KdNr
        TMP_SDLNr = SDLNr
    End Sub

    


    Private Sub frmSDLAbholungEintrag_Load(sender As Object, e As EventArgs) Handles Me.Load
        KdFirma.initKdBox(Me)
        cboSDLNr.fillWithSQL("SELECT [SDLNr],cast([SDLNr] as varchar(3)) + '  ' + [SDLBez] FROM [Speditionsdienstleistungen] WHERE SDLTypNr<=2 and SDLNr IN(500) ORDER BY SDLBez", False, "SDL", True)

        initDrucker()

        lblSBErfassung.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME
      


        If TMP_KdNr > 0 Then KdFirma.KdNr = TMP_KdNr
        If TMP_SDLNr > 0 Then cboSDLNr.changeItem(TMP_SDLNr) : btnSDLLaden.PerformClick()

        cboSprache.Items.Clear()
        cboSprache.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("DEUTSCH", "DE"))
        cboSprache.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("SERBISCH", "YU"))
        cboSprache.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("TÜRKISCH", "TR"))
        cboSprache.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("RUMÄNISCH", "RO"))

        If KdFirma.KdNr <> "" Then
            Select Case KdFirma.KdNr.ToString.Substring(0, 1)
                Case "1" : cboSprache.changeItem("TR")
                Case "2" : cboSprache.changeItem("RO")
                Case "3" : cboSprache.changeItem("YU")
                Case "4" : cboSprache.changeItem("YU")
                Case Else : cboSprache.changeItem("DE")
            End Select
        End If

     
    End Sub



    Sub initDrucker()
        ' alle installierten Drucker ermitteln und 
        ' in in ein ArrayList-Objekt speichern
        Dim sPrinters As New ArrayList
        For Each sPrinter As String In PrinterSettings.InstalledPrinters
            sPrinters.Add(sPrinter)
        Next

        ' Array sortieren
        sPrinters.Sort()

        ' jetzt alle Drucker in sortierter Reihenfolge in einer
        ' ComboBox zur Auswahl anbieten
        Dim oPS As New System.Drawing.Printing.PrinterSettings
        For i As Integer = 0 To sPrinters.Count - 1
            cboPrinter.Items.Add(sPrinters(i))
        Next

        If sPrinters.Count > 0 Then
            cboPrinter.SelectedIndex = 0
            For Each i In cboPrinter.Items
                If i.ToString = oPS.PrinterName Then
                    cboPrinter.SelectedItem = i
                    Exit For
                End If
            Next
        End If
    End Sub
     
     
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles btnSDLLaden.Click
        initdgv()
    End Sub



    Sub initdgv()
        Dim kundenSQL As New kundenSQL
        Dim sqlStr As String = ""

        Dim sdlnr As Integer = If(IsNumeric(cboSDLNr._value), cboSDLNr._value, -1)

        sqlStr = " SELECT  [KfzKennzeichen] ,SDLNr, " &
                             "  cast(CASE [SDLNr] " &
                                 "       WHEN '207'      THEN 'FREJUS'   " &
                                 "       WHEN '100'      THEN 'IDS'" &
                                 "       WHEN '101'      THEN 'WÖLFL'" &
                                 "       WHEN '202'      THEN 'IT'  " &
                                 "       WHEN '208'      THEN 'MSE' " &
                                 "       WHEN '211'      THEN 'MULTI-BOX' " &
                                 "       WHEN '210'      THEN 'SI' " &
                                 "       WHEN '212'      THEN 'UTA' " &
                                 "       WHEN '213'      THEN 'HUGO' " &
                                 "       WHEN '203'      THEN 'CZ' " &
                                 "       WHEN '209'      THEN 'PL' " &
                                 "       WHEN '500'      THEN 'ABGASPLAKETTE' " &
                                 "       Else '-' " &
                             "   END as VARCHAR(30)) AS KARTEBOX, " &
                             "  cast(CASE [SDLNr] " &
                                 "       WHEN '207'      THEN cast([FREJUS-CARD-Nr] as VARCHAR(200))  " &
                                 "       WHEN '100'      THEN cast(KartenNr as VARCHAR(200))" &
                                 "       WHEN '101'      THEN cast([KartenSchlüsselNr] as VARCHAR(200))" &
                                 "       WHEN '202'      THEN cast([TELEPASS-Nr] as VARCHAR(200)) " &
                                 "       WHEN '208'      THEN cast(KartenNr as VARCHAR(200)) " &
                                 "       WHEN '211'      THEN cast([PAN-Nr] as VARCHAR(200)) " &
                                 "       WHEN '210'      THEN cast([SERIE-Nr] as VARCHAR(200)) " &
                                 "       WHEN '212'      THEN cast(KartenNr as VARCHAR(200)) " &
                                 "       WHEN '213'      THEN cast(OBUID as VARCHAR(200)) " &
                                 "       WHEN '203'      THEN cast(KartenNr as VARCHAR(200)) " &
                                 "       WHEN '209'      THEN cast([MSE-Kd-Nr] as VARCHAR(200)) " &
                                 "       WHEN '500'      THEN '-' " &
                                 "       Else '-' " &
                             "   END as VARCHAR(200)) AS KARTEBOX_NR, " &
                                 "       [PIN] " &
                             " FROM [SDL] " &
                             " WHERE KundenNr = " & KdFirma.KdNr_value
        If sdlnr > 0 Then : sqlStr &= " AND SDLNr=" & sdlnr
        Else : sqlStr &= " AND SDLNr IN (500)"
        End If
        sqlStr &= " AND Bestelldatum between '" & datVon.Value.ToShortDateString & "' and '" & datBis.Value.ToShortDateString & "' "



        Dim order As String = " ORDER BY KfzKennzeichen,SDLNr, Bestelldatum, BestellNr,Ausstellungsdatum,KartenNr,OBUID"

        Dim dt = kundenSQL.loadSQLDataAdapterBySqlWithoutReadonlyProblem(sqlStr & order, "SDL")
        If Not cboAnTabelleAnfuegen.Checked Then dgvPositionen.Rows.Clear()

        If dt IsNot Nothing Then
            For Each r In dt.Rows
                dgvPositionen.Rows.Add(r("KfzKennzeichen"), r("SDLNr"), r("KARTEBOX"), r("KARTEBOX_NR"), r("PIN"))
            Next
        End If
        FilterKZ()

        Exit Sub

        With dgvPositionen

            .DataSource = kundenSQL.loadSQLDataAdapterBySqlWithoutReadonlyProblem(sqlStr & order, "SDL")
            .Columns("KfzKennzeichen").HeaderText = "KENNZEICHEN"
            .Columns("KfzKennzeichen").Width = 200
            .Columns("KfzKennzeichen").ReadOnly = True
            .Columns("SDLNr").ReadOnly = True
            .Columns("SDLNr").Visible = False
            '.Columns("MSE-Kd-Nr").Visible = False
            '.Columns("MSE-Kd-Nr").HeaderText = "MSE-Kd-Nr"
            '.Columns("MSE-Kd-Nr").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns("PIN").Visible = False
            '.Columns("KartenNr").Visible = False
            ' .Columns("KartenNr").Visible = False
            .Columns("KARTEBOX_NR").Width = 300
            .Columns("KARTEBOX_NR").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("PIN").HeaderText = "PIN"
            .Columns("PIN").Width = 200

            Select Case sdlnr
                Case -1, 100
                    .Columns("PIN").Visible = True
                Case 203, 209
                    .Columns("MSE-Kd-Nr").Visible = True
                Case Else
                    .Columns("PIN").Visible = True
                    .Columns("PIN").Visible = True
            End Select

            .Sort(.Columns("KfzKennzeichen"), System.ComponentModel.ListSortDirection.Ascending)

        End With

        'CreateTableForGridView()
    End Sub


    Sub FilterKZ()
        'FahrerAbholAuftrag
        dgvPositionen.Sort(dgvPositionen.Columns("KfzKennzeichen"), System.ComponentModel.ListSortDirection.Ascending)
    End Sub

    Function genFormular(sender As Button, Optional ByRef WordPath As String = "") As Microsoft.Office.Interop.Word.Document
        Me.Cursor = Cursors.WaitCursor
        FilterKZ()
        Dim SDLNr As Integer = -1 ' If(IsNumeric(cboSDLNr._value), cboSDLNr._value, -1)

        If dgvPositionen.Rows.Count > 0 Then
            SDLNr = 999 'PL+CZ
            For Each r As DataGridViewRow In dgvPositionen.Rows
                If r.Cells("SDLNr").Value IsNot DBNull.Value Then
                    If r.Cells("SDLNr").Value <> 209 And r.Cells("SDLNr").Value <> 203 Then
                        SDLNr = -1 : Exit For
                    End If
                End If
            Next
        End If

        If SDLNr < 0 Then
            For Each r As DataGridViewRow In dgvPositionen.Rows
                If r.Cells("SDLNr").Value IsNot DBNull.Value Then
                    If SDLNr <= 0 Then
                        SDLNr = r.Cells("SDLNr").Value
                    Else
                        If SDLNr <> r.Cells("SDLNr").Value Then
                            SDLNr = -1
                            Exit For
                            'Verschiedene Leistungen --> SDLNR=-1 --> richtige .docx
                        End If
                    End If
                End If
            Next
        End If

        Dim KdNr As Integer = KdFirma.KdNr_value

         Dim TMPvisible = True
        If sender Is Button3 Then TMPvisible = False

        Dim print = False
        Dim printername = cboPrinter.Text
       
        lblErrSprache.Visible = False

        Dim cGenWord As New cGenWord
         Dim sprache = cboSprache._value ' DirectCast(cboSprache.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem).Value

        If SDLNr = 500 Then 'Spezialfall PL+CZ
            genFormular = cGenWord.genBestellung_MAN(cProgramFunctions.dgridViewTods(dgvPositionen), KdNr, VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME, cboSprache._value, print, printername, WordPath, TMPvisible)
        End If


        Me.Cursor = Cursors.Default
    End Function

  



    Private Sub btnFax_Click(sender As Object, e As EventArgs) Handles btnFax.Click
        genFormular(sender)
    End Sub

    Private Sub btnFaxDrucken_Click(sender As Object, e As EventArgs) Handles btnFaxDrucken.Click
        genFormular(sender)
    End Sub
 

    Private Sub MyComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSprache.SelectedIndexChanged
          lblErrSprache.Visible = False
    End Sub

    Private Sub KdFirma_PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Handles KdFirma.PropertyChanged
        If KdFirma.KdNr_value > 0 Then
            lbl_ErrKunde.Visible = False
        End If
        If Not saveInProgress Then

            If KdFirma.KdNr <> "" Then
                Select Case KdFirma.KdNr.ToString.Substring(0, 1)
                    Case "1" : cboSprache.changeItem("TR")
                    Case "2" : cboSprache.changeItem("RO")
                    Case "3" : cboSprache.changeItem("YU")
                    Case "4" : cboSprache.changeItem("YU")
                    Case Else : cboSprache.changeItem("DE")
                End Select
            End If
        End If
    End Sub

    Private Sub KdFirma_TextChanged(sender As Object, e As EventArgs) Handles KdFirma.TextChanged

    End Sub

    Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
        Dim WordPath = ""
        Dim oWORD As Microsoft.Office.Interop.Word.Document = genFormular(sender, WordPath)
        If oWORD IsNot Nothing AndAlso WordPath <> "" Then

            oWORD.SaveAs(WordPath.Replace(".docx", "") & ".pdf", Word.WdSaveFormat.wdFormatPDF)
            openMail(WordPath.Replace(".docx", "") & ".pdf")
            oWORD.Close()
        End If
    End Sub

    Sub openMail(dest_path)
        Try



            Dim outl As New Outlook.Application
            Dim Mail As Object 'Microsoft.Office.Interop.Outlook.MailItem
            Mail = outl.CreateItem(0)
            ' Mail.To = If(KdFirma.KdData_ADRESSEN IsNot Nothing, KdFirma.KdData_ADRESSEN.E_Mail, "")

            Mail.Display()
            Dim signature = Mail.HTMLBody

            Select Case If(IsNumeric(cboSDLNr._value), cboSDLNr._value, -1)
                Case 500
                    Mail.To = If(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "al@verag.ag", "office@mtruck.at")

                    Mail.HTMLBody = "<span style='font-size:11.0pt;font-family:""Arial""'>"
                    Mail.HTMLBody &= "Sehr geehrte Damen und Herren,"
                    Mail.HTMLBody &= "<br/>"
                    Mail.HTMLBody &= "<br/>"
                    Mail.HTMLBody &= "bitte um Bestellung von Abgasplaketten lt. angefügter Liste."
                    Mail.HTMLBody &= "<br/>"
                    ' Mail.Body &= vbNewLine
                    '  Mail.Body &= "Mit freundlichen Grüßen"
                    '  Mail.Body &= vbNewLine
                    ' Mail.Body &= VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME
                    ' Mail.Body &= vbNewLine 
                    ' Mail.Body &= "ABTEILUNG Maut u. Diesel"
                    Mail.HTMLBody &= signature
                    Mail.HTMLBody &= "</span>"

                    Mail.Subject &= "Abgasplakette"
                Case Else
                    Select Case KdFirma.KdNr.ToString.Substring(0, 1)
                        Case "1" : Mail.To = "maut.tr@verag.ag"
                        Case "2" : Mail.To = "ma@verag.ag" : Mail.CC = "maut.ro@verag.ag"
                        Case "3" : Mail.To = "z.batinic@verag.ag"
                        Case "4" : Mail.To = "z.batinic@verag.ag"
                        Case Else
                    End Select
            End Select
            Mail.Attachments.Add(dest_path, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, , "VERAG_Formular.pdf")
           
        Catch ex As Exception
            MsgBox("Fehler beim erstellen der E-Mail:" & vbNewLine & ex.Message)
        End Try
    End Sub
End Class