Imports IntraSell_DLL
Imports IntraSell_Net_Base

Public Class Artikelliste
    Implements InterfaceExportableGrid


    Dim filter As String = "1=1"
    Dim formLoaded As Boolean = False
    Dim countArtikel As Integer = 0

    Public Overloads Sub Export(sender As Object) Implements InterfaceExportableGrid.Export
        FunctionsDataGrid.ExportDGToCSV(OfArtikellisteDataGridView)
    End Sub

    Dim ErrorShownOnce As Boolean = False

    Private Sub Form_Verlassen() Handles MyBase.Verlassen
        Me.Close()
    End Sub

    Private Sub ArtikelListe_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        Try
            BindingNavigatorDeleteItem.Enabled = False
            'abstract form
            ds = DsArtikel
            ParentBindingNavigator.BindingSource = GrArtikellisteBindingSource
            'end abstract form 


            FillComboBox(ArtKatNrComboBox, "SELECT artkatnr, name from `grArtikel-Kategorien` order by name asc", "Name", "ArtKatNr")
            Grartikel_kategorienTableAdapter.Fill(DsArtikel._grartikel_kategorien)
            ArtKatNrComboBox.Text = ""

            SichbtbareSpaltenConfig()

            Dim fU = New FormUtility
            fU.MakeSplitterCustomizable(SplitContainer, "ARTIKELLISTE_SPLITTER_SIZE")
            Try
                countArtikel = FirstRow("select count(ArtNr) from grArtikel where produktAktiv=true")
            Catch ex As Exception
                countArtikel = 0
            End Try

            LoadData()
            FilterButton_Click(Nothing, Nothing)
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            formLoaded = True
        End Try
    End Sub

    Private Sub AddNewArtikel(sender As Object, e As System.EventArgs) Handles MyBase.AddNew
        Try
            BeginNewArtikel()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    ''' <summary>
    ''' Save Artikel
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub GrartikelBindingNavigatorSaveItem_Click(sender As Object, e As System.EventArgs) Handles MyBase.Save
        Try
            If Not HasRecht(Rechte.Artikel, True) Then
                Exit Sub
            End If

            Validate()
            GrArtikellisteBindingSource.EndEdit()
            GrArtikellisteTableAdapter.Update(DsArtikel)
            InvalidateCache()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Sub LoadData()
        Me.SuspendLayout()

        DsArtikel.EnforceConstraints = False
        Dim StatAustriaFelderZeigen = VarValue_Default(ARTIKEL_LISTE_STATAUSTRIA_URSRPUNGSLAND_SICHTBAR, False)
        If StatAustriaFelderZeigen Then
            GrArtikellisteTableAdapter.FillStatAustriaBy(DsArtikel.grArtikelliste)
        Else
            GrArtikellisteTableAdapter.FillForArtikelliste(DsArtikel.grArtikelliste)
        End If
        Me.ResumeLayout()
    End Sub

    'Filtern
    Private Sub FilterButton_Click(sender As Object, e As System.EventArgs) Handles FilterButton.Click
        Try
            If Not formLoaded Then
                Exit Sub
            End If
            LoadData()
            filter = Nothing

            'filter dataset 
            filter = "1=1"
            Try
                If ArtikelControl1.ArtNr > 0 Then
                    filter += " and ArtNr = " & ArtikelControl1.ArtNr
                End If
            Catch ex As Exception
            End Try

            If ArtNrTextBox.Text.Length > 0 And IsNumeric(ArtNrTextBox.Text) Then
                filter += " and ArtNr = " + ArtNrTextBox.Text
            End If

            If BezeichnungTextBox.Text.Length > 0 Then
                filter += " and (Barcode Like '%" + BezeichnungTextBox.Text + "%'  or EAN Like '%" + BezeichnungTextBox.Text + "%'  or Bezeichnung Like '%" + BezeichnungTextBox.Text + "%' or Bezeichnung1 Like '%" + BezeichnungTextBox.Text + "%' or Beschreibung Like '%" + BezeichnungTextBox.Text + "%') "
            End If

            If ArtKatNrComboBox.SelectedValue > 0 Then
                filter += " and ArtKatNr = " + CStr(ArtKatNrComboBox.SelectedValue)
            End If

            If PreisVonTextBox.Text.Length > 0 And IsNumeric(PreisVonTextBox.Text) Then
                filter += " and PreisATS >= " + PreisVonTextBox.Text + ""
            End If

            If PreisBisTextBox.Text.Length > 0 And IsNumeric(PreisBisTextBox.Text) Then
                filter += " and PreisATS <= " + PreisVonTextBox.Text + ""
            End If

            If LagerArtikelCheckBox.CheckState <> CheckState.Indeterminate Then
                filter += " and LagerArtikel = " + IIf(LagerArtikelCheckBox.CheckState = CheckState.Checked, "True", "False")
            End If

            If SeriennummerCheckBox.CheckState <> CheckState.Indeterminate Then
                filter += " and Seriennummer = " + IIf(SeriennummerCheckBox.CheckState = CheckState.Checked, "True", "False")
            End If

            If SetArtikelCheckBox.CheckState <> CheckState.Indeterminate Then
                filter += " and SetArtikel = " + IIf(SetArtikelCheckBox.CheckState = CheckState.Checked, "True", "False")
            End If

            If ProduktAktivCheckBox.CheckState <> CheckState.Indeterminate Then
                filter += " and ProduktAktiv = " + IIf(ProduktAktivCheckBox.CheckState = CheckState.Checked, "True", "False")
            End If

            If NichtBestellbarCheckBox.CheckState <> CheckState.Indeterminate Then
                filter += " and NichtBestellbar = " + IIf(NichtBestellbarCheckBox.CheckState = CheckState.Checked, "True", "False")
            End If

            If ProduktAktivOnlineCheckBox.CheckState <> CheckState.Indeterminate Then
                filter += " and ProduktAktivOnline = " + IIf(ProduktAktivOnlineCheckBox.CheckState = CheckState.Checked, "True", "False")
            End If

            'If Me.KundengruppeComboBox.Text.Length > 0 Then
            '    filter = "Kundengruppe Like '" + KundengruppeComboBox.Text + "%'"
            'End If

            'If Me.PreislisteComboBox.Text.Length > 0 Then
            '    filter = "Preisliste Like '" + PreislisteComboBox.Text + "%'"
            'End If

            If filter IsNot Nothing Then
                GrArtikellisteBindingSource.Filter = filter
            Else
                GrArtikellisteBindingSource.Filter = Nothing
            End If

        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    'KundenDetail öffnen 
    Private Sub OfAdressenlisteDataGridView_RowHeaderMouseDoubleClick(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles OfArtikellisteDataGridView.RowHeaderMouseDoubleClick
        Try
            OffneArtikelMaske(GetArtNr())
            ' OffneArtikelMaske("ArtNr=" & OfAdressenlisteDataGridView.SelectedRows(0).Cells(0).Value)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub PreisVonTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles PreisVonTextBox.TextChanged
        Try
            If CDec(PreisBisTextBox.Text) <= CDec(PreisVonTextBox.Text) Then
                PreisBisTextBox.Text = PreisVonTextBox.Text
            End If
        Catch ex As Exception
            PreisBisTextBox.Text = PreisVonTextBox.Text
        End Try
    End Sub

    ''' <summary>
    ''' Fehlermeldungen unterdrücken
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub OfAdressenlisteDataGridView_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles OfArtikellisteDataGridView.DataError
        If Not ErrorShownOnce Then
            HandleAppError(e.Exception, "Korrigieren Sie die Artikeldaten", True)
            ErrorShownOnce = True
        End If
    End Sub

    Private Sub BezeichnungTextBox_TextChanged(sender As Object, e As EventArgs) Handles BezeichnungTextBox.TextChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub ArtKatNrComboBox_SelectedValueChanged(sender As Object, e As EventArgs) Handles ArtKatNrComboBox.SelectedValueChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub ProduktAktivCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles ProduktAktivCheckBox.CheckedChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub LagerArtikelCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles LagerArtikelCheckBox.CheckedChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub SeriennummerCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles SeriennummerCheckBox.CheckedChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub SetArtikelCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles SetArtikelCheckBox.CheckedChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub NichtBestellbarCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles NichtBestellbarCheckBox.CheckedChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub ProduktAktivOnlineCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles ProduktAktivOnlineCheckBox.CheckedChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub ArtNrTextBox_TextChanged(sender As Object, e As EventArgs) Handles ArtNrTextBox.TextChanged
        FilterButton_Click(Nothing, Nothing)
    End Sub

    Private Sub ArtikelControl1_ArtNrChanged(ArtNr As Integer) Handles ArtikelControl1.ArtNrChanged
        ArtikelControl1.ArtNr = ArtNr
        FilterButton_Click(Nothing, Nothing)
    End Sub


#Region "Spalten"

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnSpalten_Click(sender As Object, e As EventArgs) Handles btnSpalten.Click
        AddHandler SichtbareSpalten.SpaltenGeaendert, AddressOf SichtbareSpalten_Geaendert
        SichtbareSpalten.ShowDialog()
        SichbtbareSpaltenConfig()
    End Sub

    Private Sub SichtbareSpalten_Geaendert()
        Try
            SichbtbareSpaltenConfig()
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub SichbtbareSpaltenConfig()
        Try
            Bezeichnung1.Visible = VarValue_Default(ARTIKEL_LISTE_BEZEICHNUNG1_SICHTBAR, False)
            BeschreibungDataGridViewTextBoxColumn.Visible = VarValue_Default(ARTIKEL_LISTE_BESCHREIBUNG_SICHTBAR, True)
            PreisATSDataGridViewTextBoxColumn.Visible = VarValue_Default(ARTIKEL_LISTE_PREIS_NETTO_SICHTBAR, False)
            PreisATSBruttoDataGridViewTextBoxColumn.Visible = VarValue_Default(ARTIKEL_LISTE_PREIS_BRUTTO_SICHTBAR, True)
            ZustellpreisColumn.Visible = VarValue_Default(ARTIKEL_LISTE_PREIS_ZUSTELLUNG_SICHTBAR, True)
            MWSTDataGridViewTextBoxColumn.Visible = VarValue_Default(ARTIKEL_LISTE_MWST_SICHTBAR, True)
            BarcodeDataGridViewTextBoxColumn.Visible = VarValue_Default(ARTIKEL_LISTE_BARCODE_SICHTBAR, True)
            SetArtikel.Visible = VarValue_Default(ARTIKEL_LISTE_SETARTIKEL_SICHTBAR, False)
            LagerArtikel.Visible = VarValue_Default(ARTIKEL_LISTE_LAGERARTIKEL_SICHTBAR, True)
            Modifikationen.Visible = VarValue_Default(ARTIKEL_LISTE_MODIFIKATIONEN_SICHTBAR, True)
            StatAustria_Ursprungsland.Visible = VarValue_Default(ARTIKEL_LISTE_STATAUSTRIA_URSRPUNGSLAND_SICHTBAR, False)
            StatAustria_Gewicht.Visible = StatAustria_Ursprungsland.Visible
            StatAustria_Warennr.Visible = StatAustria_Ursprungsland.Visible
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub
#End Region


    Private Function CheckArtNr() As Boolean
        If GrArtikellisteBindingSource.Current Is Nothing Then
            MsgBox("Artikelzeile zuerst wählen!", vbInformation)
            Return False
        End If
        Return True
    End Function

    Private Function GetArtNr() As Integer
        If CheckArtNr() Then
            Dim ds = GrArtikellisteBindingSource.Current.row
            Return ds.ArtNr()
        Else
            Throw New Exception("Artikel nicht ausgewählt.")
        End If
    End Function

    Private Sub OfArtikellisteDataGridView_RowHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles OfArtikellisteDataGridView.RowHeaderMouseClick
        'Private Sub OfArtikellisteDataGridView_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles OfArtikellisteDataGridView.CellClick
        Artikeloeffnen.ShowAuswahl(GetArtNr())
    End Sub

    Private Sub OfArtikellisteDataGridView_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles OfArtikellisteDataGridView.CellFormatting

        Try

            If Not formLoaded Or FormIsClosing Then
                Exit Sub
            End If

            If countArtikel > 500 Then
                Exit Sub
            End If

            If e.ColumnIndex = 0 Then
                Dim r As dsArtikel.grArtikellisteRow = OfArtikellisteDataGridView.Rows(e.RowIndex).DataBoundItem.row
                If IsNumeric(r.ArtNr) Then
                    'farbe setzen 
                    Dim af = FarbeVonStylesheet(r.Style)
                    If e.CellStyle.BackColor <> af Then
                        If af.ToArgb <> 0 Then
                            ' Debug.Print("Background to " & af.ToArgb)
                            e.CellStyle.BackColor = af
                        End If

                    End If
                End If
            End If

            ' If e.ColumnIndex = COLUMN_IN_VERWENDUNG_INDEX Then
            '     Dim r As dsArtikel.grArtikellisteRow = OfArtikellisteDataGridView.Rows(e.RowIndex).DataBoundItem.row
            '     e.Value = AnzahlVerwendung(r.ArtNr)
            ' End If

            If e.ColumnIndex = ZustellpreisColumn.Index Then
                Dim r As dsArtikel.grArtikellisteRow = OfArtikellisteDataGridView.Rows(e.RowIndex).DataBoundItem.row
                If IsDBNull(e.Value) Then
                    Dim Zustellpreis = ModulePreise.GetZustellpreisAT(r.ArtNr, "Zustellung")
                    e.Value = Zustellpreis
                End If
            End If


        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

#Region "Menu"

    Private Sub EtikettenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EtikettenToolStripMenuItem.Click
        Try
            If CheckArtNr() Then
                Dim ds = GrArtikellisteBindingSource.Current.row
                ArtikelEtikette.ArtNr = ds.ArtNr
                ArtikelEtikette.Show()
                ArtikelEtikette.Focus()
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub AlleArtikelinArtikelmaskeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AlleArtikelinArtikelmaskeToolStripMenuItem.Click
        Try
            If CheckArtNr() Then
                Dim artikelMaske = OffneArtikelMaskeByFilter(filter)
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub ArtikelmaskeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ArtikelmaskeToolStripMenuItem.Click
        Try
            If CheckArtNr() Then
                OffneArtikelMaske(GetArtNr())
            End If

        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub ArtikelQuickMaskeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ArtikelQuickMaskeToolStripMenuItem.Click
        Try
            If CheckArtNr() Then
                OffneArtikelMaskeQuick(GetArtNr)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub RezeptToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles RezeptToolStripMenuItem1.Click
        Try
            If CheckArtNr() Then
                ArtikelSet.Show()
                ArtikelSet.ShowArtNr(GetArtNr())
                ArtikelSet.BringToFront()
            End If

        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

#End Region

    Private Sub AlleArtikelAuf5MWSTUmstellenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AlleArtikelAuf5MWSTUmstellenToolStripMenuItem.Click
        Try
            If MsgBox(Messages.Artikelliste_es_werden_allle_Artikel_umgestellt, vbYesNo) = vbYes Then
                ArtikelUmstellenAuf5ProzentMWST()
                LoadData()
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=False)
        End Try
    End Sub

    Private Sub AlleArtikelAuf10Oder20MWSTZurückumstellenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AlleArtikelAuf10Oder20MWSTZurückumstellenToolStripMenuItem.Click
        Try
            If MsgBox(Messages.Artikelliste_es_werden_allle_Artikel_umgestellt, vbYesNo) = vbYes Then
                ArtikelUmstellenAuf10ProzentMWST()
                LoadData()
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=False)
        End Try
    End Sub

    Private Sub SplitContainer_SplitterMoved(sender As Object, e As SplitterEventArgs) Handles SplitContainer.SplitterMoved

    End Sub

    Private Sub GefilterteArtikelAktualisierungMassenUpdateToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GefilterteArtikelAktualisierungMassenUpdateToolStripMenuItem.Click
        Try
            Me.DsArtikel.grArtikelliste.DefaultView.RowFilter = GrArtikellisteBindingSource.Filter
            Dim destinationDataTable = Me.DsArtikel.grArtikelliste.DefaultView.ToTable
            ArtikelMassenUpdate.ArtikelListe = destinationDataTable
            ArtikelMassenUpdate.ShowDialog()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub OfArtikellisteDataGridView_CellValidated(sender As Object, e As DataGridViewCellEventArgs) Handles OfArtikellisteDataGridView.CellValidated
        Try
            If e.ColumnIndex = ZustellpreisColumn.Index Then
                Dim r As dsArtikel.grArtikellisteRow = OfArtikellisteDataGridView.Rows(e.RowIndex).DataBoundItem.row
                Dim zustellpreis = r.Zustellpreis
                ImportArtikel.ImportZustellpreis(r.ArtNr, zustellpreis, r.MWST)
                intrasell.preise.ResetCache()
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub
End Class