Imports System.Windows.Controls
Imports System.Windows.Documents
Imports DocumentFormat.OpenXml.Drawing.Charts
Imports GrapeCity.ActiveReports.SectionReportModel
Imports Microsoft.Office.Interop
Imports VERAG_PROG_ALLGEMEIN

Public Class frmdynMailvorlagen

    Dim txtkonserve As New cTextkonserve
    Dim editall As Boolean = False
    Dim h2t As New Chilkat.HtmlToText

    Sub New(permission As Boolean)
        InitializeComponent()
        editall = permission
        VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()
    End Sub

    Private Sub Mailvorlage_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        cboSprache.Items.Clear()
        cboSprache.fillWithSQL("SELECT distinct([txt_sprache]) FROM [tblTextkonserve] where txt_sprache is not null  ", False, "FMZOLL", True)

        cbxSpracheSelected.Items.AddRange(cboSprache.Items.Cast(Of VERAG_PROG_ALLGEMEIN.MyListItem).ToArray())
        cbxSpracheSelected.changeItem("DE")


        Dim listofFirmen = cFirmen.LOAD_LIST

        cboFirmensignatur.Items.Clear()
        For Each firma In listofFirmen
            cboFirmensignatur.Items.Add(New MyListItem(firma.Firma_Bez, firma.Firma_ID))
        Next

        cbxFirma.Items.Clear()
        cbxFirmaChange.Items.Clear()
        cbxFirma.fillWithSQL("SELECT distinct([Firmengruppe]) FROM [tblFirma] where Firmengruppe is not null  ", False, "FMZOLL", True)
        cbxFirmaChange.Items.AddRange(cbxFirma.Items.Cast(Of VERAG_PROG_ALLGEMEIN.MyListItem).ToArray())


        If Not IsDBNull(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_firmaFMZoll) AndAlso CInt(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_firmaFMZoll) = 19 Then

            Dim FIRMA As New VERAG_PROG_ALLGEMEIN.cFirmen(19)
            cbxFirma.changeItem(FIRMA.Firmengruppe)
        Else
            cbxFirma.changeItem(VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA)
        End If




        cbxSendungsvermerk.fillWithSQL("SELECT VermerkCodeId,Bezeichnung  FROM [VermerkeCodes]", True, "AVISO", True)

        cbxTyp.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        cbxTyp.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Sendung", "1"))
        cbxTyp.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Mahnung", "2"))
        cbxTyp.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("OP-Liste", "3"))
        cbxTyp.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("MDM-SR", "4"))
        cbxTyp.changeItem("")



        cbxFirma.Enabled = editall
        btnDelete.Enabled = editall

        initDGVMailvorlagen(cbxFirma._value,, cbxSpracheSelected._value)

    End Sub


    Private Sub initDGVMailvorlagen(Optional firma As String = "", Optional searchparam As String = "", Optional sprache As String = "")

        lblWarning.Text = ""

        Dim SQLString As String = "SELECT * FROM [tblTextkonserve] WHERE txt_kategorie = 'FRM_MNGR_MailText'"
        Dim SQLWHere = ""
        If firma <> "" Then
            SQLWHere &= " AND txt_FIRMA = '" & firma & "'"
        End If

        If searchparam <> "" Then
            SQLWHere &= " AND (txt_Bezeichnung like '%" & searchparam & "%' OR txt_Betreff like '%" & searchparam & "%')"
        End If

        If sprache <> "" Then
            SQLWHere &= " AND (txt_Sprache = '" & sprache & "')"
        End If


        dgvMailvorlagen.SET_SQL(SQLString & SQLWHere, "FMZOLL", ,)
        dgvMailvorlagen.LOAD()


        If dgvMailvorlagen.Columns.Count < 1 Then Exit Sub

        With dgvMailvorlagen
            If .RowCount = 0 Then Me.Cursor = Cursors.Default : Exit Sub
            .MultiSelect = False
            .RowHeadersVisible = False
            .ReadOnly = True
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .Columns("txt_Id").Visible = False
            .Columns("txt_kategorie").Visible = False
            .Columns("txt_bezeichnung").HeaderText = "Bezeichnung"
            .Columns("txt_bezeichnung").Width = 200
            .Columns("txt_text").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("txt_text").HeaderText = "Text"
            .Columns("txt_betreff").HeaderText = "Betreff"
            .Columns("txt_betreff").Width = 150
            .Columns("txt_sprache").HeaderText = "Sprache"
            .Columns("txt_sprache").Width = 50
            .Columns("txt_dynMailvorlage").HeaderText = "Mailvorlage"
            .Columns("txt_firmaSig").Visible = False
            .Columns("txt_FIRMA").HeaderText = "Firma"
            .Columns("txt_FIRMA").Width = 150
            .Columns("txt_letzteAenderung").HeaderText = "letzte Änderung"
            .Columns("txt_letzteAenderung").Width = 100
            .Columns("txt_letzteAenderungUser").HeaderText = "letzte Änderung durch"
            .Columns("txt_letzteAenderungUser").Width = 75
            .Columns("txt_sendungsvermerk").HeaderText = "Sendungsvermerk"
            .Columns("txt_sendungsvermerkId").Visible = False
            .Columns("txt_sendungsvermerkText").Visible = False
            .Columns("txt_fixerEmpfaengerEmail").Visible = False
            .Columns("txt_typ").Visible = False
        End With


        For Each row As DataGridViewRow In dgvMailvorlagen.Rows


            If row.Cells("txt_firmaSig").Value IsNot DBNull.Value AndAlso IsNumeric(row.Cells("txt_firmaSig").Value) Then
                If CInt(row.Cells("txt_firmaSig").Value) > 0 Then

                    Dim tmpFirma = New VERAG_PROG_ALLGEMEIN.cFirmen(row.Cells("txt_firmaSig").Value)
                    'row.Cells("txt_firmaSig").Value = tmpFirma.Firma_Bez.ToString
                End If
            End If

        Next



    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click

        If checkIfFirmaIsFilled(True) = False Then Exit Sub

        Dim input = InputBox("Bitte geben Sie die Bezeichnung der neuen Mailvorlage ein:", "Mailvorlage anlegen")
        If input <> "" Then
            If checkNameIsValid(input) Then
                Dim txtkonserve As New cTextkonserve()
                txtkonserve.txt_bezeichnung = input
                txtkonserve.txt_kategorie = "FRM_MNGR_MailText"
                txtkonserve.txt_dynMailvorlage = True
                txtkonserve.txt_sprache = cbxSpracheSelected._value
                txtkonserve.txt_text = " "
                txtkonserve.txt_betreff = " "
                txtkonserve.txt_FIRMA = cbxFirma.Text
                txtkonserve.txt_firmaSig = 1
                txtkonserve.txt_letzteAenderung = DateTime.Now
                txtkonserve.txt_letzteAenderungUser = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME

                If txtkonserve.SAVE() Then
                    initDGVMailvorlagen(cbxFirma._value)
                End If

            Else
                MsgBox("Es existiert bereits ein Mailvorlage " & input & " für die Firma " & cbxFirma._value & "in der Sprache " & cbxSpracheSelected._value)
            End If

        Else
            MsgBox("Keine Bezeichnung angegeben!")
        End If
    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        If dgvMailvorlagen.SelectedRows.Count > 0 Then

            Dim txtKonserve As New cTextkonserve(dgvMailvorlagen.SelectedRows(0).Cells("txt_id").Value)

            If vbYes = MsgBox("Möchten Sie diesen Mailvorlage " & txtKonserve.txt_bezeichnung & " (" & txtKonserve.txt_sprache & ")" & " in " & txtKonserve.txt_FIRMA & " wirklich löschen?", vbYesNo) Then
                txtKonserve.DELETE(txtKonserve.txt_Id) ' delete funktion implementierten
                initDGVMailvorlagen(cbxFirma._value)
            End If

        End If

    End Sub

    Private Function checkNameIsValid(name As String) As Boolean

        If dgvMailvorlagen.Rows.Count = 0 Then Return True
        If checkIfFirmaIsFilled(False) = False Then Return False


        For Each row As DataGridViewRow In dgvMailvorlagen.Rows
            If Not IsDBNull(row.Cells("txt_bezeichnung").Value) AndAlso Not IsDBNull(row.Cells("txt_FIRMA").Value) Then
                If row.Cells("txt_bezeichnung").Value.ToLower = name.ToLower AndAlso row.Cells("txt_FIRMA").Value = cbxFirma._value Then
                    Return False
                End If
            End If

        Next

        Return True

    End Function


    Private Sub dgvMailvorlagen_SelectionChanged(sender As Object, e As EventArgs) Handles dgvMailvorlagen.SelectionChanged
        Try


            If dgvMailvorlagen.SelectedRows.Count < 1 Then
                mainPanel.Enabled = False
                Exit Sub

            Else
                mainPanel.Enabled = True

            End If

            txtkonserve = New cTextkonserve(dgvMailvorlagen.SelectedRows(0).Cells("txt_id").Value)

            rtb_Emailtext.Text = txtkonserve.txt_text
            txtBezeichnung.Text = txtkonserve.txt_bezeichnung
            txtBetreff.Text = txtkonserve.txt_betreff
            cbxAktiv.Checked = txtkonserve.txt_dynMailvorlage
            cboSprache._value = txtkonserve.txt_sprache
            rtb_Emailtext.Text = h2t.ToText(txtkonserve.txt_text)
            rtb_txthtml.Text = txtkonserve.txt_text
            cboFirmensignatur.changeItem(txtkonserve.txt_firmaSig)
            cbxFirmaChange.changeItem(txtkonserve.txt_FIRMA)
            cbSendungsvermerk.Checked = txtkonserve.txt_sendungsvermerk
            cbxSendungsvermerk.changeItem(txtkonserve.txt_sendungsvermerkId)
            txtSendungsvermerk.Text = txtkonserve.txt_sendungsvermerkText
            txtfixeEmail.Text = txtkonserve.txt_fixerEmpfaengerEmail
            If txtkonserve.txt_typ IsNot Nothing Then
                cbxTyp.changeItem(txtkonserve.txt_typ, True)
            Else
                cbxTyp.changeItem("")
            End If


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


    End Sub

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

            Dim txtKS As New cTextkonserve(dgvMailvorlagen.SelectedRows(0).Cells("txt_id").Value)

            If checkFields() = False Then Exit Sub

            txtKS.txt_bezeichnung = txtBezeichnung.Text
            txtKS.txt_betreff = txtBetreff.Text
            txtKS.txt_dynMailvorlage = cbxAktiv.Checked
            txtKS.txt_sprache = cboSprache._value
            txtKS.txt_text = insertlinebreaks(rtb_Emailtext.Text)
            txtKS.txt_FIRMA = cbxFirmaChange._value
            txtKS.txt_firmaSig = cboFirmensignatur._value
            txtKS.txt_letzteAenderung = DateTime.Now
            txtKS.txt_letzteAenderungUser = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME
            txtKS.txt_fixerEmpfaengerEmail = txtfixeEmail.Text
            txtKS.txt_sendungsvermerk = cbSendungsvermerk.Checked
            txtKS.txt_typ = cbxTyp._value

            If cbSendungsvermerk.Checked AndAlso cbxSendungsvermerk._value = "" Then MsgBox("SendungsvermerksID hinterlegen!") : Exit Sub
            If cbSendungsvermerk.Checked AndAlso txtSendungsvermerk.Text = "" Then MsgBox("Sendungsvermerk hinterlegen!") : Exit Sub


            If cbSendungsvermerk.Checked Then
                txtKS.txt_sendungsvermerkId = cbxSendungsvermerk._value
                txtKS.txt_sendungsvermerkText = txtSendungsvermerk.Text
            End If



            txtKS.SAVE()

            dgvMailvorlagen.GetOrder()
            initDGVMailvorlagen(cbxFirma._value)
            dgvMailvorlagen.SetOrder()

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

    End Sub

    Private Sub cbxFirma_SelectedValueChanged(sender As Object, e As EventArgs) Handles cbxFirma.SelectedValueChanged, cbxSpracheSelected.SelectedValueChanged
        Try

            dgvMailvorlagen.GetOrder()
            initDGVMailvorlagen(cbxFirma._value, txtSuche.Text, cbxSpracheSelected._value)
            dgvMailvorlagen.SetOrder()

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


    End Sub

    Private Function checkIfFirmaIsFilled(initialSave As Boolean, Optional setWarning As Boolean = True)

        If cbxFirma._value = "" Then
            If ((dgvMailvorlagen.SelectedRows(0).Cells("txt_FIRMA").Value Is DBNull.Value Or dgvMailvorlagen.SelectedRows(0).Cells("txt_FIRMA").Value Is Nothing Or dgvMailvorlagen.SelectedRows(0).Cells("txt_FIRMA").Value = "") Or initialSave = True) Then 'And initialSave = False ???

                If setWarning Then
                    lblWarning.Text = "Bitte Firma auswählen!"
                Else
                    lblWarning.Text = ""
                End If

                Return False
            End If
            lblWarning.Text = ""
            Return True

        ElseIf cbxSpracheSelected._value = "" Then
            If ((dgvMailvorlagen.SelectedRows(0).Cells("txt_sprache").Value Is DBNull.Value Or dgvMailvorlagen.SelectedRows(0).Cells("txt_sprache").Value Is Nothing Or dgvMailvorlagen.SelectedRows(0).Cells("txt_sprache").Value = "") Or initialSave = True) Then 'And initialSave = False ???

                If setWarning Then
                    lblWarning.Text = "Bitte Sprache auswählen!"
                Else
                    lblWarning.Text = ""
                End If
                Return False
            End If
            lblWarning.Text = ""
            Return True


        End If

        Return True
    End Function

    Private Function checkFields() As Boolean

        lblWarning.Text = ""
        Return True


    End Function

    Private Sub txtSuche_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSuche.KeyDown
        If e.KeyCode = Keys.Enter Then

            initDGVMailvorlagen(cbxFirma._value, txtSuche.Text, cboSprache._value)
            e.Handled = True

        End If
    End Sub

    Private Sub rtb_Emailtext_TextChanged(sender As Object, e As EventArgs) Handles rtb_Emailtext.TextChanged
        Dim wordcount = rtb_Emailtext.TextLength
        lblWordcount.Text = "(" & wordcount & "/65500)"

    End Sub

    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click

        Try

            Dim outl As New Outlook.Application
            Dim Mail As Microsoft.Office.Interop.Outlook.MailItem
            Mail = outl.CreateItem(0)

            If txtfixeEmail.Text <> "" Then Mail.To = txtfixeEmail.Text

            If rtb_Emailtext.Text <> "" AndAlso cboSprache._value <> "" Then

                Dim TextHTML = ""
                TextHTML &= rtb_txthtml.Text
                TextHTML &= "<br>"
                TextHTML &= "<br>"
                TextHTML &= "Mit freundlichen Grüßen<br>"
                TextHTML &= VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME & "<br>"
                TextHTML &= "<br>"
                TextHTML &= cFakturierung.getSignature(cboSprache._value, cboFirmensignatur._value, True, True)

                Mail.HTMLBody = "<div style=""font-family:Calibri, Arial"">" & TextHTML & "</div>"

                Mail.Subject = txtBetreff.Text

            End If

            Mail.Display()

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


    End Sub

    Private Function insertlinebreaks(text As String) As String

        Return text.ToString.Replace(vbLf, "<br>" & vbLf)

    End Function

    Private Sub cbSendungsvermerk_CheckedChanged(sender As Object, e As EventArgs) Handles cbSendungsvermerk.CheckedChanged

        txtSendungsvermerk.Visible = cbSendungsvermerk.Checked
        cbxSendungsvermerk.Visible = cbSendungsvermerk.Checked
        Label10.Visible = cbSendungsvermerk.Checked
        Label9.Visible = cbSendungsvermerk.Checked

    End Sub

    Private Sub cbxTyp_SelectedValueChanged(sender As Object, e As EventArgs) Handles cbxTyp.SelectedValueChanged
        If cbxTyp.SelectedItem Is Nothing Then
            txtVariablen.Text = "-"
            Exit Sub

        End If
        Dim oItem As VERAG_PROG_ALLGEMEIN.MyListItem = CType(cbxTyp.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem)

        Select Case oItem.Value
            Case 1
                'Sendungsvariable
                txtVariablen.Text = "%VAR-GRENZE%, %LKW%, %LKWKennzeichen%, %Empfaenger%, %voraus-Eintreffen%, %FilialenNr%, %AbfertigungsNr%, %Absender%, %Gewicht%, %ImEx%, %Zollstelle%"
            Case Else
                'Mahnvariable
                txtVariablen.Text = " %Mahntext%, %KdNr%, %email_mahnung%"

        End Select


    End Sub
End Class