Imports System.Diagnostics
Imports System.Drawing
Imports System.Windows.Forms
Imports Microsoft.Office.Tools.Ribbon
Imports SDL
Imports VERAG_PROG_ALLGEMEIN


Public Class frmAvisoFormularAnfuegen

    Public KdNr As Integer = -1
    Public AvisoId As Integer = -1
    Dim vollmachtartId As Integer = -1
    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
    Public SendungsId = -1
    Public Bezeichnung = ""
    Public PDF_MAIL As cANHANGSART_ADDIN
    Public enableOverwritting As Boolean = False
    Public ATTTemp As List(Of String)
    Public ATT As List(Of String)
    Public hasAnhaenge As Boolean = False
    Public button As RibbonButton
    Dim UsrCntlKundenZollVollmachten1 As usrCntlKundenZollVollmachten
    Dim UsrCntlVertraege1 As usrcntlVertraege
    Dim UsrCntlGestellungsgarantien1 As usrcntlGestellungsgarantien
    Dim frmDefaultSize As Size = New Size(535, 750)
    Dim dgvAnhaengeSize As Size = New Size(495, 30)
    Dim avisoIdSet As Boolean = False



    Sub New()

        InitializeComponent()

    End Sub

    Sub New(Bezeichnung, sender)

        InitializeComponent()
        Me.Bezeichnung = Bezeichnung
        button = sender
        initForm()


    End Sub
    Sub initForm()

        Me.pnlDetails.AutoSizeMode = AutoSizeMode.GrowAndShrink
        Me.pnlDetails.AutoSize = True


        Select Case button.Name

            Case "btnVollmachten"

                UsrCntlKundenZollVollmachten1 = New usrCntlKundenZollVollmachten()
                UsrCntlKundenZollVollmachten1.AutoSize = False
                Me.pnlDetails.Controls.Add(UsrCntlKundenZollVollmachten1)
                Me.Text = "Vollmachten einfügen"


            Case "btnVertraege"
                UsrCntlVertraege1 = New usrcntlVertraege()
                AddHandler UsrCntlVertraege1.clickOK, AddressOf btnOK_Click
                Me.pnlDetails.Controls.Add(UsrCntlVertraege1)
                Me.Text = "Verträge einfügen"


            Case "btnGestellungsgarantien"
                UsrCntlGestellungsgarantien1 = New usrcntlGestellungsgarantien()
                AddHandler UsrCntlGestellungsgarantien1.clickOK, AddressOf btnOK_Click
                Me.Text = "Gestellungsgarantien einfügen"
                Me.pnlDetails.Controls.Add(UsrCntlGestellungsgarantien1)


            Case Else
                MsgBox("Funktion nicht unterstützt!")
                Me.DialogResult = DialogResult.Cancel
                Me.Close()

        End Select


    End Sub


    Private Sub frmAvisoFormularAnfuegen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        initAttachment()
        KdSearchBox.initKdBox(Me)
        If hasAnhaenge Then pbAnhaenge.Image = My.Resources.pdf

    End Sub


    Private Sub KdSearchBox_TextChanged(sender As Object, e As EventArgs) Handles KdSearchBox.TextChanged

        If KdSearchBox.KdNr_value > 0 AndAlso KdSearchBox.KdNr IsNot Nothing Then
            KdNr = KdSearchBox.KdNr_value
            Dim AD = KdSearchBox.KdData_ADRESSEN
            Dim KD = KdSearchBox.KdData_KUNDE
            init()
        End If

    End Sub

    Sub init()
        If KdNr > 0 Then
            Select Case button.Name

                Case "btnVollmachten"

                    initVollmachtarten(KdNr)

                Case "btnVertraege"

                    UsrCntlVertraege1.initDGVVertraege(KdNr)

                Case "btnGestellungsgarantien"

                    UsrCntlGestellungsgarantien1.initDGVGestGarantie(KdNr)

            End Select
            Show()
        End If
    End Sub

    Sub initVollmachtarten(kdNr As Integer)
        cbVMTypen.fillWithSQL("SELECT DISTINCT(art.kdvma_Id), art.kdvma_Bezeichnung FROM [tblKundenVollmachtenArt] as art LEFT JOIN (select * from [tblKundenVollmachten] where [kdvm_KundenNr]='" & kdNr & "' ) as abf on art.[kdvma_Id]=abf.[kdvm_kdvmaId] WHERE art.kdvma_visible=1 AND art.kdvma_Firma='" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA & "'", False, "FMZOLL", True)
    End Sub


    Sub initUsrCntrlKundenvollmachten(vollmachtartId)

        UsrCntlKundenZollVollmachten1.init(KdNr, vollmachtartId)


    End Sub

    Private Sub KdSearchBox_PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Handles KdSearchBox.PropertyChanged
        If KdSearchBox.KdNr_value > 0 AndAlso KdSearchBox.KdData_KUNDE IsNot Nothing AndAlso KdSearchBox.KdData_ADRESSEN IsNot Nothing Then
            KdNr = KdSearchBox.KdNr
            Dim AD = KdSearchBox.KdData_ADRESSEN
            Dim KD = KdSearchBox.KdData_KUNDE
            init()

        End If
    End Sub

    Private Sub cbVMTypen_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbVMTypen.SelectedValueChanged
        If cbVMTypen._value <> "" Then
            vollmachtartId = cbVMTypen._value
            initUsrCntrlKundenvollmachten(vollmachtartId)
        End If
    End Sub

    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click

        If Not checkMandatoryFields() Then
            DialogResult = DialogResult.None
            Exit Sub
        End If

        If avisoIdSet And Not button.Name = "btnVollmachten" Then
            DialogResult = DialogResult.OK
            Exit Sub
        End If

        Select Case button.Name

            Case "btnVertraege"

                If UsrCntlVertraege1.dgvVertraegeNew.SelectedRows.Count < 1 Then
                    MsgBox("Bitte einen Vertrag markieren")
                    DialogResult = DialogResult.None
                    Exit Sub
                End If

                UsrCntlVertraege1.dgvVertraegeNew.GetOrder()
                UsrCntlVertraege1.initDGVVertraege(KdNr)
                UsrCntlVertraege1.dgvVertraegeNew.SetOrder()

            Case "btnGestellungsgarantien"

                If UsrCntlGestellungsgarantien1.dgvGestGarantieNew.SelectedRows.Count < 1 Then
                    MsgBox("Bitte eine Gestellung markieren")
                    DialogResult = DialogResult.None
                    Exit Sub
                End If

                UsrCntlGestellungsgarantien1.dgvGestGarantieNew.GetOrder()
                UsrCntlGestellungsgarantien1.initDGVGestGarantie(KdNr)
                UsrCntlGestellungsgarantien1.dgvGestGarantieNew.SetOrder()


        End Select


        If Not hasAnhaenge Then

            'If Not vbYes = MsgBox("Diese Email besitzt keinen Anhang!" & vbCrLf & "Soll die Email als Anhang gespeichert werden?", vbYesNoCancel) Then
            '    Close()
            '    DialogResult = DialogResult.None
        Else

            If ATT IsNot Nothing Then
                If ATT.Count > 1 Then
                    ATT = ATTTemp
                    If dgvAnhaenge.SelectedRows.Count = 0 Then
                        MsgBox("Bitte Anhang markieren!")
                        DialogResult = DialogResult.None
                        Exit Sub
                    Else
                        Dim listOfSelectedAttachmendIndex As New List(Of Integer)
                        For Each indexOfAttachment As DataGridViewRow In dgvAnhaenge.SelectedRows
                            listOfSelectedAttachmendIndex.Add(indexOfAttachment.Index)
                        Next

                        RemoveNotUsedAttachmentOnList(ATT, listOfSelectedAttachmendIndex)

                    End If
                End If
            End If
        End If



        Select Case button.Name

            Case "btnVollmachten"

                UsrCntlKundenZollVollmachten1.btnNeu_Click(sender, e)
                AvisoId = UsrCntlKundenZollVollmachten1.vmId

                Close()

            Case "btnVertraege"

                If sender.Text = "Hinzufügen" Then

                    setAvisoIdForVertrage()

                ElseIf UsrCntlVertraege1.dgvVertraegeNew.SelectedRows.Count = 1 Then

                    Dim hasExistingEmail As Boolean = False
                    Dim hasExistingAttachment As Boolean = False

                    For Each row As DataGridViewRow In UsrCntlVertraege1.dgvVertraegeNew.SelectedRows

                        If (row.Cells("kv_datenarchivId_mail").Value IsNot Nothing AndAlso IsNumeric(row.Cells("kv_datenarchivId_mail").Value) AndAlso CInt(row.Cells("kv_datenarchivId_mail").Value) > 0) Then hasExistingEmail = True

                        If (row.Cells("kv_datenarchivId").Value IsNot Nothing AndAlso IsNumeric(row.Cells("kv_datenarchivId").Value) AndAlso CInt(row.Cells("kv_datenarchivId").Value) > 0) Then hasExistingAttachment = True

                        setAvisoIdForVertrage()

                        If hasAnhaenge AndAlso hasExistingAttachment Then
                            Dim response = MsgBox("Der markierte Vertrag besitzt bereits einen Anhang!" & vbCrLf & "Soll der Anhang ersetzt werden?", vbYesNoCancel)
                            If response = vbYes Then
                                'setAvisoIdForVertrage()
                                enableOverwritting = True
                            ElseIf response = vbCancel Then
                                DialogResult = DialogResult.None
                                Exit Sub
                            Else
                                Close()
                            End If
                        End If



                    Next

                    Dim ASKMailSpeichern As String = ""

                    If hasAnhaenge Then
                        ASKMailSpeichern = "Soll die Mail auch gespeichert werden!" & IIf(hasExistingEmail, vbNewLine & "Die aktuell hinterlegte Mail wird dadurch überschrieben!", "")
                    Else
                        ASKMailSpeichern = "Soll die Mail als Anhang gepeichert werden!" & IIf(hasExistingEmail, vbNewLine & "Die aktuell hinterlegte Mail wird dadurch überschrieben!", "")
                    End If

                    If vbYes = MsgBox(ASKMailSpeichern, vbYesNoCancel) Then
                        If hasExistingEmail Then enableOverwritting = True
                        If ATT.Count = 0 Then
                            PDF_MAIL = cANHANGSART_ADDIN.MAIL_DATENSERVER '"ONLYMAIL_DATENSERVER"
                        Else
                            PDF_MAIL = cANHANGSART_ADDIN.PDFANDMAIL_DATENSERVER '"PDFMAIL_DATENSERVER"
                        End If
                    Else
                        If ATT.Count = 0 Then
                            DialogResult = DialogResult.None
                            Exit Sub
                        End If

                    End If

                    Me.DialogResult = DialogResult.OK
                        Close()
                    Else
                        Close()
                End If



                Close()

            Case "btnGestellungsgarantien"

                If sender.Text = "Hinzufügen" Then

                    setAvisoIdForGestellungen()
                    Me.DialogResult = DialogResult.OK

                ElseIf UsrCntlGestellungsgarantien1.dgvGestGarantieNew.SelectedRows.Count = 1 Then

                    For Each row As DataGridViewRow In UsrCntlGestellungsgarantien1.dgvGestGarantieNew.SelectedRows

                        If row.Cells("gg_datenarchivId").Value Is DBNull.Value Or row.Cells("gg_datenarchivId").Value Is Nothing Then
                            setAvisoIdForGestellungen()
                        Else
                            Dim response = MsgBox("Die markierte Gestellungsgarantie besitzt bereit einen Anhang!" & vbCrLf & "Soll der Anhang ersetzt werden?", vbYesNoCancel)
                            If response = vbYes Then
                                setAvisoIdForGestellungen()
                                enableOverwritting = True
                            ElseIf response = vbCancel Then
                                DialogResult = DialogResult.None
                                Exit Sub
                            Else
                                Close()
                            End If
                        End If

                    Next
                    Me.DialogResult = DialogResult.OK
                    Close()
                Else

                    Close()
                End If



        End Select

    End Sub


    Private Sub setAvisoIdForGestellungen()
        If UsrCntlGestellungsgarantien1.Gid > 0 Then
            AvisoId = UsrCntlGestellungsgarantien1.Gid
        ElseIf UsrCntlGestellungsgarantien1.dgvGestGarantieNew.SelectedRows.Count = 1 Then
            AvisoId = UsrCntlGestellungsgarantien1.dgvGestGarantieNew.SelectedRows(0).Cells("gg_id").Value
        End If

    End Sub

    Private Sub setAvisoIdForVertrage()
        If UsrCntlVertraege1.Vid > 0 Then
            AvisoId = UsrCntlVertraege1.Vid
        ElseIf UsrCntlVertraege1.dgvVertraegeNew.SelectedRows.Count = 1 Then
            AvisoId = UsrCntlVertraege1.dgvVertraegeNew.SelectedRows(0).Cells("kv_id").Value
        End If
        If AvisoId > 0 Then
            avisoIdSet = True
        End If

    End Sub

    Private Sub RemoveNotUsedAttachmentOnList(ByRef a As List(Of String), tmpIndex As List(Of Integer))
        If (a IsNot Nothing) AndAlso (a.Count > 1) Then
            Dim list As New List(Of String)
            For Each r In tmpIndex
                Dim selectedItem As Object = a.Item(CInt(r))
                list.Add(selectedItem)
            Next
            a = list
        End If
    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Close()
    End Sub

    Sub initAttachment()
        dgvAnhaenge.Rows.Clear()

        If ATT Is Nothing Then
            Exit Sub
        End If

        If ATT.Count = 0 Then
            hasAnhaenge = False
            PDF_MAIL = cANHANGSART_ADDIN.MAIL_DATENSERVER '"ONLYMAIL_DATENSERVER"
        Else
            hasAnhaenge = True
            If button.Name = "btnVollmachten" Then
                PDF_MAIL = cANHANGSART_ADDIN.PDFANDMAIL_DATENSERVER '"PDFANDMAIL_DATENSERVER"
            Else
                PDF_MAIL = cANHANGSART_ADDIN.PDF_DATENSERVER '"ONLYPDF_DATENSERVER"
            End If


            For Each a In ATT
                Dim display = a
                If a.Contains("\") Then
                    Dim sp = a.Split("\")
                    display = sp(sp.Count - 1)
                End If
                dgvAnhaenge.Rows.Add({display, a})
            Next
            ATTTemp = ATT
        End If

        Dim addHeightfrm = 180
        Dim addHeightdgv = 50
        If dgvAnhaenge.Rows.Count > 1 Then

            dgvAnhaenge.Visible = True
            lblMultiAttachements.Visible = True


            Select Case button.Name

                Case "btnVollmachten"

                    Me.Size = New Size(frmDefaultSize.Width, frmDefaultSize.Height + addHeightdgv)
                    pnlDetails.Size = New Size(pnlDetails.Width, pnlDetails.Height + addHeightdgv)
                    dgvAnhaenge.Size = New Size(dgvAnhaengeSize.Width, dgvAnhaengeSize.Height + addHeightdgv)

                Case "btnVertraege"
                    Me.Size = New Size(frmDefaultSize.Width, frmDefaultSize.Height - addHeightfrm)
                    pnlDetails.Size = New Size(pnlDetails.Width, pnlDetails.Height - addHeightfrm)
                    dgvAnhaenge.Size = New Size(dgvAnhaengeSize.Width, dgvAnhaengeSize.Height + addHeightdgv)

                Case "btnGestellungsgarantien"
                    Me.Size = New Size(frmDefaultSize.Width, frmDefaultSize.Height - addHeightfrm)
                    pnlDetails.Size = New Size(pnlDetails.Width, pnlDetails.Height - addHeightfrm)
                    dgvAnhaenge.Size = New Size(dgvAnhaengeSize.Width, dgvAnhaengeSize.Height + addHeightdgv)
            End Select


        Else
            dgvAnhaenge.Visible = False
            lblMultiAttachements.Visible = False
            Select Case button.Name

                Case "btnVollmachten"

                    Me.Size = frmDefaultSize
                    dgvAnhaenge.Size = dgvAnhaengeSize
                Case "btnVertraege"
                    pnlDetails.Size = New Size(pnlDetails.Width, pnlDetails.Height - addHeightfrm - addHeightdgv)
                    Me.Size = New Size(frmDefaultSize.Width, frmDefaultSize.Height - addHeightfrm)
                    dgvAnhaenge.Size = dgvAnhaengeSize

                Case "btnGestellungsgarantien"
                    pnlDetails.Size = New Size(pnlDetails.Width, pnlDetails.Height - addHeightfrm - addHeightdgv)
                    Me.Size = New Size(frmDefaultSize.Width, frmDefaultSize.Height - addHeightfrm)
                    dgvAnhaenge.Size = dgvAnhaengeSize
            End Select
        End If

        dgvAnhaenge.ClearSelection()
    End Sub

    Private Function checkMandatoryFields() As Boolean



        Dim valid = False

        If KdSearchBox.KdNr_value = -1 Then
            lblWarning.Text = "Kunde auswählen!"
            Return valid
        End If


        Select Case button.Name

            Case "btnVollmachten"

                If cbVMTypen._value = "" Then
                    lblWarning.Text = "Vollmachttyp auswählen"
                    Return valid
                End If

                If UsrCntlKundenZollVollmachten1.txtGueltigVon.Text = "" Then
                    lblWarning.Text = "Gültig von-Datum hinterlegen!"
                    Return valid
                End If


            Case Else
        End Select


        lblWarning.Text = ""
        valid = True
        Return valid

    End Function

    Private Sub frmAvisoFormularAnfuegen_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        KdSearchBox.Focus()
        Label1.Visible = cAllgemein.TESTSYSTEM
        If button.Name = "btnVollmachten" Then
            lblVMId.Visible = True
            cbVMTypen.Visible = True
        Else
            lblVMId.Visible = False
            cbVMTypen.Visible = False
        End If

    End Sub

    Private Sub pnlDetails_ControlAdded(sender As Object, e As ControlEventArgs)
        For Each control As Control In Controls
            pnlDetails.Size = control.Size
        Next
    End Sub

    Private Sub dgvAnhaenge_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvAnhaenge.CellDoubleClick, dgvAnhaenge.CellContentDoubleClick
        Try
            If dgvAnhaenge.SelectedRows.Count > 0 Then
                If dgvAnhaenge.SelectedRows(0).Cells(1).Value <> "" Then

                    Process.Start(dgvAnhaenge.SelectedRows(0).Cells(1).Value)

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