Imports System.IO
Imports IntraSell_DLL
Imports IntraSell_Net_Base

Public Class Artikel
    Inherits AbstractForm
    Implements InterfacePrintable, IArtikelEditor
    Dim ARTIKEL_BILDER_VERZEICHNIS As String
    Dim ArtikeNotizChanged As Boolean = False

    Private Property EditingEnabled As Boolean = False

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

    'Die Datensätze filtern
    Public Sub FilterBy(Expression As String)
        Try
            WriteLog("Artikel.FilterBy=" & Expression)
            GrartikelBindingSource.Filter = Expression
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Sub Sort(Sort As String)
        Try
            GrartikelBindingSource.Sort = "EAN"
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub SetEditingActive(active As Boolean)
        TableLayoutPanel2.Enabled = active
        TableLayoutPanel5.Enabled = active
        PanelArtikel.Enabled = True
    End Sub
    Private Sub Edit_Click(sender As Object, e As System.EventArgs)
        Try
            EditingEnabled = Not EditingEnabled
            SetEditingActive(EditingEnabled)
            'PanelArtikel.Enabled = Not PanelArtikel.Enabled
        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
        If Not HasRecht(Rechte.Artikel, True) Then
            Exit Sub
        End If

        Try
            If ArtikelSave.Save(Me) Then
                'ErrorProvider1.Clear()
                Validate()
                FKgrartikelbuchsetartikelBindingSource.EndEdit()
                GrartikelgrartikelverwandteartikelBindingSource.EndEdit()
                GrartikelBindingSource.EndEdit()
                Grartikel_vkpreisperselectionTableAdapter.Update(DsArtikel)
                Grartikel_staffelpreiseTableAdapter.Update(DsArtikel)
                Grartikel_verwandteartikelTableAdapter.Update(DsArtikel)
                Grartikel_lagerbestandTableAdapter.Update(DsLager)
                BuchsetartikelTableAdapter.Update(DsArtikel)
                ArtikelBild(GrartikelBindingSource.Current.Item("ArtNr"), PictureBoxProduktBild)
                StatistikAustria1.Save()
            End If

            If ArtikeNotizChanged Then
                ArtikeNotizSave
            End If

        Catch ex As Exception

            If ex.Message.Contains("EAN") Then
                ErrorProvider1.SetError(EANTextBox, ex.Message)
                Exit Sub
            End If
            If ex.Message.Contains("ArtKatNr") Then
                ErrorProvider1.SetError(ArtikelKategorieControl1, ex.Message)
                Exit Sub
            End If
            If ex.Message.Contains("PreisATS") Then
                ErrorProvider1.SetError(PreisATSTextBox, ex.Message)
                Exit Sub
            End If
            If ex.Message.Contains("PreisATS_Brutto") Then
                ErrorProvider1.SetError(PreisATS_BruttoTextBox, ex.Message)
                Exit Sub
            End If
            If ex.Message.Contains("MWST") Then
                ErrorProvider1.SetError(MWSTTextBox, ex.Message)
                Exit Sub
            End If
            If ex.Message.Contains("Bezeichnung") Then
                ErrorProvider1.SetError(BezeichnungTextBox, ex.Message)
                Exit Sub
            End If

            HandleAppError(ex)
        End Try
    End Sub


    Private Sub GrartikelBindingNavigatorDeleteItem_Click(sender As Object, e As System.EventArgs) Handles MyBase.Delete
        Try
            Dim artikel As dsArtikel.grartikelRow = GrartikelBindingSource.Current.Row
            If DeleteArtikel(artikel.ArtNr) Then
                Close()
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


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

        Try
            EditingEnabled = False
            SetEditingActive(EditingEnabled)
            ToolStripButtonEdit.Visible = True
            ds = DsArtikel
            AddHandler Me.ToolStripButtonEdit.Click, AddressOf Edit_Click

            Dim ph = New ArtikelNettoBruttoHandler
            ph.HaendlerInitialisieren(PreisATSTextBox, PreisATS_BruttoTextBox, MWSTTextBox)

            ARTIKEL_BILDER_VERZEICHNIS = VarValue_Default(Variablen.ARTIKEL_BILDER_VERZEICHNIS, ClassSettings.GetDataPath & "produktbilder")
            Try
                'Fill grid combos first 
                FillComboBoxInDG(IDNRDataGridViewTextBoxColumn, AdressenControl.SQL_PREISLISTEN, "Adr", "IDNR")
                FillComboBoxInDG(ArtNrDataGridViewTextBoxColumn, ArtikelControl.SQL, "Art", "ArtNr")
                FillComboBoxInDG(ArtKatNrDataGridViewTextBoxColumn, "SELECT artkatnr, name from `grArtikel-Kategorien` order by name asc", "Name", "ArtKatNr")
                FillComboBoxInDG(PreislisteNameDataGridViewTextBoxColumn, SQL_PREISLISTEN, "PreislisteName")
                FillComboBoxInDG(ArtNrDataGridViewTextBoxColumn4, ArtikelControl.SQL, "Art", "ArtNr")
                FillComboBoxInDG(UnterArtNrDataGridViewTextBoxColumn, ArtikelControl.SQL, "Art", "ArtNr")
                FillComboBoxInDG(UnterArtNrDataGridViewTextBoxColumn1, ArtikelControl.SQL, "Art", "ArtNr")

                'Me.GrArtikellisteTableAdapter.Fill(Me.DsArtikel.grArtikelliste)
            Catch ex As Exception
                HandleAppError(ex)
            End Try

            Try
                Grartikel_kategorienTableAdapter.Fill(DsArtikel._grartikel_kategorien)
                GrartikelTableAdapter.Fill(DsArtikel.grartikel)
                Grartikel_vkpreisperselectionTableAdapter.Fill(DsArtikel._grartikel_vkpreisperselection)
                Grartikel_staffelpreiseTableAdapter.Fill(DsArtikel._grartikel_staffelpreise)
                Grartikel_verwandteartikelTableAdapter.Fill(DsArtikel._grartikel_verwandteartikel)
                BuchsetartikelTableAdapter.Fill(DsArtikel.buchsetartikel)
            Catch ex As Exception
                IgnoreAppError(ex)
            End Try

            FillComboBox(EinheitComboBox, "SELECT Einheit FROM `grArtikel-Einheiten` group by Einheit", "Einheit", "Einheit")
            FillComboBox(LieferantNRComboBox, "SELECT IDNR, Firma FROM lieferantenAdressen order by Firma", "Firma", "IDNR")
            FillComboBox(HerstellerNrComboBox, "SELECT IDNR, Firma FROM lieferantenAdressen order by Firma", "Firma", "IDNR")
            FillComboBox(Bezeichnung1ComboBox, "SELECT DISTINCT bezeichnung1 FROM grArtikel", "bezeichnung1", "bezeichnung1")

            ParentBindingNavigator.BindingSource = GrartikelBindingSource

            If BeginNewFlag Then
                BeginNew()
            End If

            MakeVergroesserbar(BezeichnungTextBox)
            MakeVergroesserbar(BeschreibungTextBox)
            MakeVergroesserbar(ModifikationenTextBox)
            MakeVergroesserbar(KurzBeschreibungTextBox)

            'Felder Verstecken 
            'Das Feld „Modifikationen“ benötigen wir nicht – das wird in Magento verwaltet
            'Setartikel und Seriennummer erforderlich benötigen wir auch nicht
            SetArtikelCheckBox.Visible = VarValue_Default("ARTIKEL_SETARTIKEL_SICHTBAR", True)
            SeriennummerCheckBox.Visible = VarValue_Default("ARTIKEL_SERIENNUMMER_SICHTBAR", True)
            ModifikationenTextBox.Visible = VarValue_Default("ARTIKEL_MODIFIKATIONEN_SICHTBAR", True)
            ModifikationenLabel.Visible = VarValue_Default("ARTIKEL_MODIFIKATIONEN_SICHTBAR", True)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Sub Print(sender As Object) Implements InterfacePrintable.Print
        EtikettenToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

#Region "New"

    Private Sub BindingNavigatorAddNewItem_Click(sender As Object, e As System.EventArgs) Handles MyBase.AddNew
        Try
            SetEditingActive(True)
            PanelArtikel.Enabled = True
            AddingNewFlag = True
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub BindingSource_CurrentChanged(sender As Object, _
                              e As System.EventArgs) _
                              Handles GrartikelBindingSource.CurrentChanged
        Try
            If AddingNewFlag = True Then
                AddingNewFlag = False
                ArtNrTextBox.Text = NextId("grArtikel", "ArtNr", , True)
                MWSTTextBox.Text = VarValue_Default(ARTIKEL_ANLAGE_MWST, "20")
                LagerArtikelCheckBox.Checked = VarValue_Default("Lager_autostart", False)
            Else
                Dim ArtNr = GrartikelBindingSource.Current.Item("ArtNr")
                BindLager()
                If GrartikelBindingSource.Current IsNot Nothing Then
                    ArtikelBild(artnr, PictureBoxProduktBild)
                End If
                BackColor = ArtikelFarbe(ArtNr)
                TextBoxLagerstand.Text = GetLagerBestandArtikel(ArtNr:=ArtNr)
                'Interne Notiz
                LabelNotiz.Text = LetzteArtikelDescription(ArtNr)
                Me.RichTextBoxNotiz.Text = LabelNotiz.Text
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Sub BeginNew()
        Try
            BindingNavigatorAddNewItem_Click(Nothing, Nothing)
            GrartikelBindingSource.AddNew()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub
#End Region


    Private Sub TabControl1_Click(sender As Object, e As EventArgs) Handles TabControl1.Click
        BindLager()
    End Sub

    Private Sub BindLager()
        Try
            'If IsNumeric(Me.ArtNrTextBox.Text) Then
            Dim artikelRow As DataRowView = GrartikelBindingSource.Current
            If artikelRow IsNot Nothing Then
                Dim artnr As Integer = artikelRow.Item("ArtNr")
                Grartikel_lagerbewegungTableAdapter.FillBy(DsLager._grartikel_lagerbewegung, artnr, Now.AddDays(-365 * 3))
                Grartikel_lagerbestandTableAdapter.FillBy(DsLager._grartikel_lagerbestand, artnr)
                ' End If
            End If

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

#Region "Bilder"
    Private Sub ButtonBildLaden_Click(sender As Object, e As EventArgs) Handles ButtonBildLaden.Click
        BildLadenDialog(GrartikelBindingSource.Current.Row, PictureBoxProduktBild)
    End Sub

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        AllowDrop = True
    End Sub

    Private Sub Form1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
        Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
        For Each path In files
            Dim artikel As dsArtikel.grartikelRow = GrartikelBindingSource.Current.Row
            artikel.Picture = BildLaden(artikel.ArtNr, path, PictureBoxProduktBild)
        Next
    End Sub

    Private Sub Form1_DragEnter(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Copy
        End If
    End Sub
#End Region

    Private Sub GrartikelBindingSource_DataError(sender As Object, e As BindingManagerDataErrorEventArgs) Handles GrartikelBindingSource.DataError

    End Sub

    Private Sub DataGridView1_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles DataGridViewPreise.DataError

    End Sub

    Private Sub DataGridView5_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles DataGridView5.DataError

    End Sub

    Private Sub ArtikelControlSuche_ArtNrChanged(ArtNr As Integer) Handles ArtikelControlSuche.ArtNrChanged
        Try
            If ArtNr > 0 Then
                'FilterBy("ArtNr=" & ArtNr)
                Dim found = GrartikelBindingSource.Find("ArtNr", ArtNr)
                GrartikelBindingSource.Position = found
            Else
                'FilterBy("")
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub ArtikelControlAddVerwandt_ArtNrChanged(ArtNr As Integer) Handles ArtikelControlAddVerwandt.ArtNrChanged
        Try
            GrartikelgrartikelverwandteartikelBindingSource.AddNew()
            Dim newVerw As dsArtikel._grartikel_verwandteartikelRow = GrartikelgrartikelverwandteartikelBindingSource.Current.row()
            newVerw.ArtNr = GrartikelBindingSource.Current.row.artnr
            newVerw.UnterArtNr = ArtNr
            newVerw.Bezeichnung = "Verwandt"
            'Grartikel_verwandteartikelTableAdapter.Insert(Me.GrartikelBindingSource.Current.row.artnr, ArtNr, "Verwandt")
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub ArtikelControlAddVerwandt_Load(sender As Object, e As EventArgs) Handles ArtikelControlAddVerwandt.Load

    End Sub



    Private Sub DataGridView2_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles DataGridView2.DataError

    End Sub

    Private Sub DataGridView3_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles DataGridView3.DataError

    End Sub

    Private Sub DataGridView4_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles DataGridView4.DataError

    End Sub

    Private Sub EtikettenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EtikettenToolStripMenuItem.Click
        Try
            ArtikelEtikette.ArtNr = GrartikelBindingSource.Current.row.artnr
            ArtikelEtikette.Show()
            ArtikelEtikette.Focus()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub ArtikelKategorieControl1_ArtKatNrAdded(newArtKatNR As Integer) Handles ArtikelKategorieControl1.ArtKatNrAdded
        Try
            DsArtikel.EnforceConstraints = False
            Grartikel_kategorienTableAdapter.Fill(DsArtikel._grartikel_kategorien)
            DsArtikel.EnforceConstraints = True
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


    Private Sub CheckBoxDifferenzbesteuerung_Click(sender As Object, e As EventArgs) Handles CheckBoxDifferenzbesteuerung.Click
        Try
            If CheckBoxDifferenzbesteuerung.Checked Then
                'Validierungen 
                Dim art As dsArtikel.grartikelRow = GrartikelBindingSource.Current.Row
                art.MWST = 0
                'If Not art.IsPreisATSNull Then
                art.PreisATS_Brutto = art.PreisATS
                'End If

                'If Not art.IsPreisATS_BruttoNull Then
                art.PreisATS = art.PreisATS_Brutto
                'End If

                art.Differenzbesteuerung = True
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


    Private Sub UcTranslate2_Load(sender As Object, e As EventArgs) Handles UcTranslate2.Load

    End Sub

    Private Sub UcTranslate1_Load(sender As Object, e As EventArgs) Handles UcTranslate1.Load

    End Sub

    Private Sub UcTranslate3_Load(sender As Object, e As EventArgs) Handles UcTranslate3.Load

    End Sub

    Private Sub MakeVergroesserbar(textBox As TextBox)
        AddHandler textBox.Enter, AddressOf TextBox_OnEnter
        AddHandler textBox.Leave, AddressOf TextBox_OnLeave
    End Sub

    Sub TextBox_OnEnter(sender As Object, e As EventArgs)
        Dim tb As TextBox = sender
        tb.Height *= 4
    End Sub

    Sub TextBox_OnLeave(sender As Object, e As EventArgs)
        Dim tb As TextBox = sender
        tb.Height /= 4
    End Sub


#Region "IArtikelEditor"
    Function ErrorProvider() As ErrorProvider Implements IArtikelEditor.ErrorProvider
        Return ErrorProvider1
    End Function

    Function BindingSource() As System.Windows.Forms.BindingSource Implements IArtikelEditor.BindingSource
        Return GrartikelBindingSource
    End Function

    Function GetBezeichnungTextBox() As Control Implements IArtikelEditor.GetBezeichnungTextBox
        Return BezeichnungTextBox
    End Function

    Function GetPreisATSTextBox() As Control Implements IArtikelEditor.GetPreisATSTextBox
        Return PreisATSTextBox
    End Function

    Function GetPreisATS_BruttoTextBox() As Control Implements IArtikelEditor.GetPreisATS_BruttoTextBox
        Return PreisATS_BruttoTextBox
    End Function

    Function GetArtikelKategorieControl() As Control Implements IArtikelEditor.GetArtikelKategorieControl
        Return ArtikelKategorieControl1
    End Function

    Function GetMWSTTextBox() As Control Implements IArtikelEditor.GetMWSTTextBox
        Return MWSTTextBox
    End Function

    Function GetEANTextBox() As Control Implements IArtikelEditor.GetEANTextBox
        Return EANTextBox
    End Function

    Function GetGrartikelTableAdapter() As IntraSell_Net_Base.dsArtikelTableAdapters.grartikelTableAdapter Implements IArtikelEditor.GetGrartikelTableAdapter
        Return GrartikelTableAdapter
    End Function

    Function GetDsArtikel() As IntraSell_Net_Base.dsArtikel Implements IArtikelEditor.GetDsArtikel
        Return DsArtikel
    End Function

    Function ValidateFrom() As Boolean Implements IArtikelEditor.ValidateFrom
        Return Validate()
    End Function


    Private Sub LabelNotiz_Click(sender As Object, e As EventArgs) Handles LabelNotiz.Click, LabelNotiz4.Click
        Try
            TabControlArtikel1.SelectedIndex = 1 'Springe zu Notiz
        Catch ex As Exception
        End Try
    End Sub
    Private Sub LabelNotiz_MouseClick(sender As Object, e As MouseEventArgs) Handles LabelNotiz.MouseClick, LabelNotiz4.MouseClick
        Try
            TabControlArtikel1.SelectedIndex = 1 'Springe zu Notiz
        Catch ex As Exception
        End Try
    End Sub

    Private Sub RichTextBoxNotiz_Validated(sender As Object, e As EventArgs) Handles RichTextBoxNotiz.Validated
        ArtikeNotizSave()
    End Sub

    Sub ArtikeNotizSave()
        Try
            Dim ArtNr = GrartikelBindingSource.Current.Item("ArtNr")
            InsertArtikelDescription(ArtNr, RichTextBoxNotiz.Text, ModuleGlobals.Username)
            LabelNotiz.Text = RichTextBoxNotiz.Text
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub RichTextBoxNotiz_TextChanged(sender As Object, e As EventArgs) Handles RichTextBoxNotiz.TextChanged
        ArtikeNotizChanged = True
    End Sub


#End Region

    Private Sub TabPageDokumente_Enter(sender As Object, e As EventArgs) Handles TabPageDokumente.Enter
        Try
            UcDokumente1.TabelleName = "grArtikel"
            UcDokumente1.FilterString = Me.ArtNrTextBox.Text
            UcDokumente1.LadeDaten()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub
End Class