Imports IntraSell_DLL
Imports IntraSell_Net_Base
Imports MySql.Data.MySqlClient

Public Class TouchOrdersListe

    Event Selected(Vorgang As VorgangInBearbeitung)
    Event ZeileMarkiert(Vorgang As VorgangInBearbeitung)

    Dim TAG_BACK = 0
    Dim _CurrentMitarbeiterNr As Integer


    Dim COLUMN_STATUS = 10
    Dim COLUMN_ZUSTELLZEIT = 3
    Dim COLUMN_ZUSTELLER = 13
    Dim COLUMN_MITARBEITER = 14
    Dim COLUMN_MITARBEITER_NAME = 15

    Dim NeedUpdateUI As Boolean = False

    Property CurrentMitarbeiterNr As Integer
        Get
            Return _CurrentMitarbeiterNr
        End Get
        Set(value As Integer)
            _CurrentMitarbeiterNr = value
            VorgangAktionen1.MitarbeiterNr = value
        End Set
    End Property

    Private Sub TouchOrdersListe_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            ApplyStyle
            'LadeDaten()
            AddHandler VorgangAktionen1.HiddenFieldsShown, AddressOf HiddenFieldsShown
            AddHandler ModuleGlobal.CommandRequestEvent, AddressOf ModuleGlobal_CommandRequestEvent
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Sub ApplyStyle()
        ModuleStyle.Style(TableLayoutPanel1)
        ModuleStyle.StyleButton(ButtonBearbeiten)
        ModuleStyle.StyleButton(ButtonAnsehen)
        ModuleStyle.StyleButton(ButtonDruck)

        ModuleStyle.StyleButton(ButtonTagPlus)
        ModuleStyle.StyleButton(ButtonTagMinus)

        ModuleStyle.StyleDataGrid(DataGridViewVorgangListe)
    End Sub

    Private Sub ModuleGlobal_CommandRequestEvent(cmd As IntraSellCommand)
        Try
            If cmd.command = IntraSellCommands.Neu OrElse
               cmd.command = IntraSellCommands.Info OrElse
               cmd.command = IntraSellCommands.Importiert OrElse
               cmd.command = IntraSellCommands.Abschliessen OrElse
               cmd.command = IntraSellCommands.AbschliessenOhneRechnung OrElse
               cmd.command = IntraSellCommands.Status OrElse
               cmd.command = IntraSellCommands.Absagen Then
                NeedUpdateUI = True
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub LadeDaten()
        Try
            Cursor = Cursors.WaitCursor
            NeedUpdateUI = False
            Dim von = AdaptZeiten(AdaptToday().AddDays(TAG_BACK))
            Dim bis = AdaptZeiten(AdaptToday().AddDays(TAG_BACK + 1))
            BuchVorgangListeTableAdapter.Fill(DsVorgaenge.buchVorgangListe, von, bis)
            DataGridViewVorgangListe.Sort(DatumDataGridViewTextBoxColumn, ComponentModel.ListSortDirection.Descending)
            Dim BarrechnungKundNr = GetBarrechnungKundNr()
            BuchVorgangListeBindingSource.Filter = "Typ='AU' And KundNr<>" & BarrechnungKundNr

            Dim cmd = New MySqlCommand("select mitarbeiternr from `buchvorgang-status` s where (status ='ZUGESTELLT' or status ='WIRD ZUGESTELLT' ) and s.VorgangTyp = @VorgangTyp And s.VorgangNummer = @VorgangNummer order by datum desc limit 1")

            For Each r As dsVorgaenge.buchVorgangListeRow In DsVorgaenge.buchVorgangListe.Rows
                Try
                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("VorgangTyp", r.Typ)
                    cmd.Parameters.AddWithValue("VorgangNummer", r.Nummer)
                    r.ZustellerNr = FirstRow(cmd)
                    If IsNumeric(r.ZustellerNr) Then
                        r.ZustellerName = MitarbeiterName(r.ZustellerNr)
                    End If
                Catch ex As Exception
                    HandleAppError(ex, Silent:=True)
                End Try
            Next
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Sub FilterByKundNr(idnr As Integer)
        Try
            BuchVorgangListeTableAdapter.FillByKundNR(DsVorgaenge.buchVorgangListe, idnr, Now.AddDays(-366), Now)
            DataGridViewVorgangListe.Sort(DatumDataGridViewTextBoxColumn, ComponentModel.ListSortDirection.Descending)
            BuchVorgangListeBindingSource.Filter = "Typ='AU'"
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Friend Sub FilterBySystem(system As Object)
        Try
            If IsDBNull(system) Then
                BuchVorgangListeBindingSource.Filter = "System is null"
            Else
                BuchVorgangListeBindingSource.Filter = "System='" & system & "'"
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    ''' <summary>
    ''' Nicht löschen
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DataGridView1_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles DataGridViewVorgangListe.DataError
        'Ignore
    End Sub

    Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridViewVorgangListe.SelectionChanged
        If BuchVorgangListeBindingSource.Current Is Nothing Then
            Return
        End If
        Dim cur As dsVorgaenge.buchVorgangListeRow = BuchVorgangListeBindingSource.Current.row
        Dim Vorgang As New VorgangInBearbeitung(cur)
        VorgangAktionen1.Vorgang = Vorgang
    End Sub

    Private Sub ButtonBearbeiten_Click(sender As Object, e As EventArgs) Handles ButtonBearbeiten.Click
        Try
            Cursor = Cursors.WaitCursor
            Dim cur As dsVorgaenge.buchVorgangListeRow = BuchVorgangListeBindingSource.Current.row
            Dim Vorgang As New VorgangInBearbeitung(cur)
            RaiseEvent Selected(Vorgang)
            HiddenFieldsNotNeeded()
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridViewVorgangListe.CellMouseDoubleClick
        ButtonBearbeiten_Click(Nothing, Nothing)
    End Sub

    Private Sub DataGridView1_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridViewVorgangListe.CellMouseClick
        Try
            If BuchVorgangListeBindingSource.Current IsNot Nothing Then
                Dim cur As dsVorgaenge.buchVorgangListeRow = BuchVorgangListeBindingSource.Current.row
                Dim Vorgang As New VorgangInBearbeitung(cur)
                RaiseEvent ZeileMarkiert(Vorgang)
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub ButtonAnsehen_Click(sender As Object, e As EventArgs) Handles ButtonAnsehen.Click
        Dim vorgangInBearbeitung As dsVorgaenge.buchVorgangListeRow = BuchVorgangListeBindingSource.Current.row
        FormManager.OffneOrderPreview(vorgangInBearbeitung)
    End Sub


    'Format 
    Private Sub DataGridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridViewVorgangListe.CellFormatting
        Try


            Dim dr As DataGridViewRow = DataGridViewVorgangListe.Rows(e.RowIndex)
            Dim vorgang As dsVorgaenge.buchVorgangListeRow = DataGridViewVorgangListe.Rows(e.RowIndex).DataBoundItem.row

            If e.ColumnIndex = COLUMN_ZUSTELLER Then
                Dim newBcgColor As Color = Color.White
                If Not vorgang.IsZustellerNrNull Then
                    newBcgColor = MitarbeiterFarbe(vorgang.ZustellerNr)

                    If dr.Cells(COLUMN_ZUSTELLER).Style.BackColor <> newBcgColor Then
                        dr.Cells(COLUMN_ZUSTELLER).Style.BackColor = newBcgColor
                        dr.Cells(COLUMN_ZUSTELLER).Style.ForeColor = Color.Black
                    End If
                End If

            End If


            If e.ColumnIndex = COLUMN_MITARBEITER_NAME Then
                Dim newBcgColor As Color = Color.White
                If Not vorgang.IsMitarbeiterNrNull Then
                    newBcgColor = MitarbeiterFarbe(vorgang.MitarbeiterNr)

                    If dr.Cells(COLUMN_MITARBEITER_NAME).Style.BackColor <> newBcgColor Then
                        dr.Cells(COLUMN_MITARBEITER_NAME).Style.BackColor = newBcgColor
                        dr.Cells(COLUMN_MITARBEITER_NAME).Style.ForeColor = Color.Black
                    End If
                End If

            End If

            If e.ColumnIndex = COLUMN_STATUS AndAlso vorgang.Status IsNot Nothing Then
                Dim clr = GetVorgangStatusColor(vorgang.Typ, vorgang.Status)
                If clr <> Color.White Then
                    e.CellStyle.BackColor = clr
                End If
            End If

            If e.ColumnIndex = COLUMN_ZUSTELLZEIT Then
                Try
                    If Not IsDBNull(e.Value) Then
                        Dim zZ = e.Value  ' intrasell.vorgang.GetVorgangEigenschaft(vorgang.Typ, vorgang.Nummer, "Zustellzeit")
                        e.Value = zZ
                        Dim zzDate As Date
                        If Date.TryParse(zZ, zzDate) Then
                            e.Value = Format(zzDate, "HH:mm")
                        End If
                    End If
                Catch ex As Exception
                    'Ignore
                End Try
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Dim AktionenExpanded As Boolean = False

    Private Sub HiddenFieldsShown()
        TableLayoutPanelAll.RowStyles(1).Height = 300
        AktionenExpanded = True
    End Sub

    Private Sub HiddenFieldsNotNeeded()
        TableLayoutPanelAll.RowStyles(1).Height = 100
        AktionenExpanded = False
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub ButtonDruck_Click(sender As Object, e As EventArgs) Handles ButtonDruck.Click

        Try
            Cursor = Cursors.WaitCursor
            If BuchVorgangListeBindingSource.Current Is Nothing Then Return
            Dim cur As dsVorgaenge.buchVorgangListeRow = BuchVorgangListeBindingSource.Current.row
            Dim Vorgang As New VorgangInBearbeitung(cur)
            Dim vorgangInfo As String = OpenAusdruck_InWord_Filename_RTF(Vorgang.Typ,
                                                                         Vorgang.Nummer,
                                                                         "Vorlagen\Vorgang_Info.txt",
                                                                         True)
            'Print 
            PrintFile(vorgangInfo, VarValue_Default(PRINT_PORT, "/d:lpt3"))
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub BuchVorgangListeBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles BuchVorgangListeBindingSource.CurrentChanged
        Try
            Dim enabled = BuchVorgangListeBindingSource.Current IsNot Nothing
            Try
                If BuchVorgangListeBindingSource.Current IsNot Nothing Then
                    Dim cur As dsVorgaenge.buchVorgangListeRow = BuchVorgangListeBindingSource.Current.row
                    If cur.IsMitarbeiterNrNull Then
                        enabled = HasRecht(Rechte.Fremde_Tische_bedienen)
                    Else
                        enabled = HasRecht(Rechte.Fremde_Tische_bedienen) OrElse cur.MitarbeiterNr = MitarbeiterID
                    End If
                End If
            Catch ex As Exception
                'Ignore
            End Try
            ButtonAnsehen.Enabled = enabled
            ButtonBearbeiten.Enabled = enabled
            ButtonDruck.Enabled = enabled
        Catch ex As Exception
            'Ignore
        End Try
    End Sub

    Private Sub ButtonTagPlus_Click(sender As Object, e As EventArgs) Handles ButtonTagPlus.Click
        TAG_BACK = 0
        LadeDaten()
        ButtonTagMinus.Text = "Gestern"
    End Sub

    Private Sub ButtonTagMinus_Click(sender As Object, e As EventArgs) Handles ButtonTagMinus.Click
        TAG_BACK -= 1
        LadeDaten()
        ButtonTagMinus.Text = Today.AddDays(TAG_BACK)
    End Sub

    Private Sub TimerRefreshUI_Tick(sender As Object, e As EventArgs) Handles TimerRefreshUI.Tick
        Try
            If NeedUpdateUI Then
                LadeDaten()
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub
End Class
