Imports System.Diagnostics
Imports System.Windows.Forms
Imports AVISO

Public Class frmAvisoAnfuegen

    Public AvisoId = -1
    Public SendungsId = -1
    Public Bezeichnung = ""
    Public PDF_MAIL As cANHANGSART_ADDIN
    Public Art = ""
    Dim VSQL As New VERAG_PROG_ALLGEMEIN.SQL

    Public ATT As List(Of String)
    Public INFO As String = ""

    Sub New(Bezeichnung, Art)

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        Me.Bezeichnung = Bezeichnung
        Me.Art = Art
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub
    Private Sub frmAvisoAnfügen_Load(sender As Object, e As EventArgs) Handles Me.Load
        txtBezeichnung.Text = Bezeichnung
        txtSrchDat.Text = Now.AddMonths(-1).ToShortDateString
        Label4.Visible = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM
        cboFiliale.fillWithSQL("SELECT FilialenNr, Grenzstelle FROM Filialen WHERE Fil_Status='A'  ORDER BY FilialenNr ", True, "FMZOLL", True)
        txtLKWNr.Focus()

        cboArt.Items.Clear()
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("", ""))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ATR-EUR1", "ATR-EUR1"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Rechnung", "Rechnung"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("CMR", "CMR"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Ausfuhr", "Ausfuhr"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Vorpapier", "Vorpapier"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Packliste", "Packliste"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Auftrag", "Auftrag"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Auftrag", "Auftrag"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Dispoliste", "Dispoliste"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Vorkasse", "Vorkasse"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Überweisungsbeleg", "Überweisungsbeleg"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Vollmacht", "Vollmacht"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ATB-Nr", "ATB"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("ATA-Nr", "ATA"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Sonstiges", "Sonstiges"))
        cboArt.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Bordro", "Bordro"))

        If Art <> "" Then cboArt.changeItem(Art)

        initAttachment()
    End Sub

    Sub initAttachment()
        dgvAnhaenge.Rows.Clear()
        If ATT.Count = 0 Then
            btnSaveAttachments.Enabled = False
        Else
            btnSaveAttachments.Enabled = cbxAnhaengeSpeichern.Checked
            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
        End If
        dgvAnhaenge.ClearSelection()

    End Sub

    Private Sub txtLKWNr_TextChanged(sender As Object, e As KeyEventArgs) Handles txtLKWNr.KeyDown, txtAbfertigungsnummer.KeyDown, cboFiliale.KeyDown
        If e.KeyCode = Keys.Return Then initSrch()
    End Sub
    Private Sub cboFiliale_TextChanged(sender As Object, e As EventArgs) Handles cboFiliale.SelectedIndexChanged
        initSrch()
    End Sub
    Sub initSrch()
        Try
            lblInfo.Text = ""
            UseWaitCursor = True

            With dgvAviso
                .Columns.Clear()
                Dim firma = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                If firma = "" Then firma = "VERAG"

                If VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER <> "" Then
                    firma = " AND ( FIRMA='" & firma & "' OR CLUSTER='" & VERAG_PROG_ALLGEMEIN.cAllgemein.CLUSTER & "' ) "
                Else
                    firma = " AND FIRMA='" & firma & "'  "
                End If

                Dim sql = "SELECT TOP 10 AvisoID, Grenzstelle as Grenze, Datum, LKW_Nr,Auftraggeber,Frächter,Firma FROM Aviso left join tblSendungen on tblSnd_AvisoID=AvisoID WHERE  status <>2  " & firma & " "
                If IsDate(txtSrchDat.Text) Then sql &= " AND Datum > '" & CDate(txtSrchDat.Text).ToShortDateString & "'"
                If txtLKWNr.Text <> "" Then sql &= " AND (LKW_Nr LIKE '%" & txtLKWNr.Text & "%'" & IIf(IsNumeric(txtLKWNr.Text), " OR AvisoID ='" & txtLKWNr.Text & "')", ")")



                If cboFiliale._value <> "" Then sql &= " AND FilialenNr LIKE '%" & cboFiliale._value & "%'"
                If txtAbfertigungsnummer.Text <> "" Then sql &= " AND AbfertigungsNr LIKE '" & txtAbfertigungsnummer.Text.Replace("*", "%") & "'"
                sql &= " group by AvisoID, Grenzstelle, Datum, LKW_Nr,Auftraggeber,Frächter,Firma "
                sql &= " order by datum desc"
                .SET_SQL(sql, "AVISO")
                .LOAD()

                '.Columns("AvisoId").Visible = False
                .Columns("AvisoID").HeaderText = "LKW-ID"
                .Columns("AvisoID").Width = 60
                .AutoSizeColumnsMode = Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill
                .Columns("Grenze").Width = 40
                .Columns("Datum").Width = 80

                If .RowCount = 0 Then lblInfo.Text = "keine Sendungen gefunden!"

                If .Rows.Count = 1 Then
                    .Rows(0).Selected = True
                    txtBezeichnung.Focus()
                End If
            End With

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

        UseWaitCursor = False
    End Sub

    Sub initSrchSnd(AvisoId)
        Try
            UseWaitCursor = True

            With dgvSendungen
                .Columns.Clear()
                If AvisoId <= 0 Then Exit Sub
                Dim firma = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                If firma = "" Then firma = "VERAG"
                Dim sql = "SELECT [tblSnd_SendungID],[FilialenNr],[AbfertigungsNr],[tblSnd_Absender] as Absender,[tblSnd_Empfaenger] as Empfänger,[tblSnd_Auftraggeber] as Auftraggeber,[tblSnd_Colli] as Colli,[tblSnd_Gewicht] as Gewicht,[tblSnd_FremdspeditionText] as Fremd,tblSnd_AvisoID "
                sql &= " FROM [tblSendungen] where tblSnd_AvisoID=" & AvisoId

                .SET_SQL(sql, "AVISO")
                .LOAD()

                .Columns("tblSnd_AvisoID").Visible = False
                .Columns("tblSnd_SendungID").Visible = False
                .AutoSizeColumnsMode = Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill

                .Columns("FilialenNr").Width = 35
                .Columns("AbfertigungsNr").Width = 55
                .Columns("Colli").Width = 40
                .Columns("Gewicht").Width = 55
                .Columns("Empfänger").Width = 100
                .Columns("Fremd").Width = 45


                '.Columns("Grenze").Width = 40
                ' .Columns("Datum").Width = 80

                'If .Rows.Count = 1 Then
                '    .Rows(0).Selected = True
                '    txtBezeichnung.Focus()
                'End If
                .ClearSelection()

                If cboFiliale._value <> "" AndAlso txtAbfertigungsnummer.Text <> "" Then
                    For Each r As DataGridViewRow In .Rows
                        If r.Cells("FilialenNr").Value = cboFiliale._value And r.Cells("AbfertigungsNr").Value = txtAbfertigungsnummer.Text Then
                            r.Selected = True
                        End If
                    Next
                End If
            End With
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        UseWaitCursor = False
    End Sub


    Private Sub btn_Click(sender As Object, e As EventArgs) Handles btnSaveAttachments.Click, btnSaveMail.Click
        lblErr_Bezeichnung.Visible = False
        lblErr_Aviso.Visible = False
        If dgvAviso.SelectedRows.Count > 0 Then
            If txtBezeichnung.Text.Trim = "" Then
                lblErr_Bezeichnung.Visible = True
                Me.DialogResult = Windows.Forms.DialogResult.None : Exit Sub
            End If
            Me.AvisoId = dgvAviso.SelectedRows(0).Cells("AvisoId").Value
            If dgvSendungen.SelectedRows.Count > 0 Then
                Me.SendungsId = dgvSendungen.SelectedRows(0).Cells("tblSnd_SendungID").Value
            Else
                Me.SendungsId = -1
            End If
            If sender Is btnSaveAttachments Then
                PDF_MAIL = cANHANGSART_ADDIN.PDF
            End If
            If sender Is btnSaveMail Then
                If cbxAnhaengeSpeichern.Checked Then
                    If cbxAnhaengeZusaetzlichSpeichern.Checked Then
                        PDF_MAIL = cANHANGSART_ADDIN.PDFANDMAIL
                    Else
                        PDF_MAIL = cANHANGSART_ADDIN.YMAIL
                    End If
                Else
                    PDF_MAIL = cANHANGSART_ADDIN.YMAIL
                End If

            End If
            Bezeichnung = txtBezeichnung.Text
            Me.DialogResult = Windows.Forms.DialogResult.OK
        Else
            lblErr_Aviso.Visible = True
            Me.DialogResult = Windows.Forms.DialogResult.None
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        initSrch()
    End Sub

    Private Sub dgvAviso_DoubleClick(sender As Object, e As EventArgs) Handles dgvAviso.DoubleClick
        If dgvAviso.SelectedRows.Count > 0 Then
            txtBezeichnung.Focus()
        End If
    End Sub

    Private Sub dgvAviso_Click(sender As Object, e As EventArgs) Handles dgvAviso.Click
        dgvSendungen.ClearSelection()
    End Sub

    Private Sub dgvAviso_CellContentClick(sender As Object, e As EventArgs) Handles dgvAviso.SelectionChanged
        Dim avisoId = -1
        If dgvAviso.SelectedRows.Count > 0 Then avisoId = dgvAviso.SelectedRows(0).Cells("AvisoId").Value
        initSrchSnd(avisoId)
    End Sub

    Private Sub dgvAnhaenge_KeyDown(sender As Object, e As KeyEventArgs) Handles dgvAnhaenge.KeyDown
        If e.KeyCode = Keys.Delete Then

            If dgvAnhaenge.SelectedRows.Count > 0 Then
                For Each row In dgvAnhaenge.SelectedRows.Cast(Of DataGridViewRow)().OrderByDescending(Function(dgvr) dgvr.Index)
                    ATT.RemoveAt(row.Index)
                Next
                ' ATT.RemoveAt(dgvAnhaenge.SelectedRows(0).Index) 'Inex-Rows = Index-Att
                initAttachment()
            End If
        End If
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles cbxAnhaengeSpeichern.CheckedChanged
        dgvAnhaenge.Enabled = cbxAnhaengeSpeichern.Checked
        cbxAnhaengeZusaetzlichSpeichern.Enabled = cbxAnhaengeSpeichern.Checked

        If cbxAnhaengeSpeichern.Checked Then
            btnSaveAttachments.Enabled = dgvAnhaenge.Rows.Count > 0
        Else
            btnSaveAttachments.Enabled = False
        End If
    End Sub

    Private Sub dgvAnhaenge_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvAnhaenge.CellContentDoubleClick, dgvAnhaenge.CellDoubleClick

        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

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnVermerke.Click
        If dgvSendungen.SelectedRows.Count > 0 Then
            If Me.SendungsId >= 0 Then

                Dim frmGrayOut = VERAG_PROG_ALLGEMEIN.cMeineFunktionenAVISO.grayoutForm()
                Dim sv As New AVISO.frmAddSendungsvermerkShort(dgvSendungen.SelectedRows(0).Cells("tblSnd_AvisoID").Value, Me.SendungsId) ', dgvSendungen.SelectedRows(0).Cells("tblSnd_SendungID").Value)

                If INFO <> "" Then
                    sv.txtDetail.Text = INFO
                End If

                sv.Location = Me.PointToClient(Cursor.Position)
                sv.ShowDialog(frmGrayOut)
                frmGrayOut.Close()
                sv.Close()

                initVermerke()

            End If
        End If
    End Sub

    Sub initVermerke()
        If dgvSendungen.SelectedRows.Count > 0 Then
            btnVermerke.Enabled = True
            Me.SendungsId = dgvSendungen.SelectedRows(0).Cells("tblSnd_SendungID").Value
            Dim SENDUNG_TMP = New VERAG_PROG_ALLGEMEIN.cSendungen(SendungsId)
            Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(dgvSendungen.SelectedRows(0).Cells("tblSnd_AvisoID").Value)
            If AVISO IsNot Nothing Then
                usrcntrVermerke.init(AVISO, SendungsId)

                If SENDUNG_TMP IsNot Nothing Then

                    CheckBox3.Checked = IIf(SENDUNG_TMP.tblSnd_Vorgeschrieben = Nothing, False, True)
                    CheckBox2.Checked = IIf(SENDUNG_TMP.tblSnd_Vorbereitet = Nothing, False, True)
                    CheckBox3.Enabled = True
                    CheckBox2.Enabled = True
                End If

            Else
                btnVermerke.Enabled = False
                CheckBox3.Enabled = False
                CheckBox2.Enabled = False
                usrcntrVermerke.init(Nothing, -1)
            End If
        End If


    End Sub
    Private Sub dgvSendungen_SelectionChanged(sender As Object, e As EventArgs) Handles dgvSendungen.SelectionChanged
        initVermerke()
    End Sub

    Private Sub CheckBox3_Click(sender As Object, e As EventArgs) Handles CheckBox3.Click, CheckBox2.Click
        If dgvSendungen.SelectedRows.Count > 0 Then
            Me.SendungsId = dgvSendungen.SelectedRows(0).Cells("tblSnd_SendungID").Value
            Dim AVISO = VERAG_PROG_ALLGEMEIN.cAviso.getAvisoById(dgvSendungen.SelectedRows(0).Cells("tblSnd_AvisoID").Value)
            If AVISO IsNot Nothing Then
                Dim FUNC As New AvisoStatusFunctions

                Select Case sender.Name
                    Case "CheckBox3" : FUNC.setSendungVorgeschrieben(SendungsId, AVISO.AvisoID) : initVermerke()
                    Case "CheckBox2" : FUNC.setSendungVorbereitetQS(SendungsId, AVISO.AvisoID) : initVermerke()
                End Select

            End If
        End If


    End Sub
End Class