Imports IntraSell_DLL
Imports IntraSell_Net_Base
Public Class Kunden
    Implements InterfacePrintable

    Event KundenWizzardShown(ByRef form As KundenWizzard)
    Event AdresseWeitereButtonClicked(ByRef form As AdresseWeitere)

    Private IDNR As Integer = -999 'KundenNr
    'Die Datensätze filtern

    Public Sub FilterBy(Expression As String)
        Try
            ofAdressenBindingSource.Filter = Expression
        Catch ex As Exception
            HandleAppError(ex, , Silent:=True)
        End Try
    End Sub

    Private Sub Rebind()
        Try
            'try to bind comboboxes 
            FKofAdressenofadressensettingsBindingSource.ResetItem(0)
        Catch ex As Exception
            HandleAppError(ex)
        End Try

    End Sub

    Public Sub Print(sender As Object) Implements InterfacePrintable.Print
        'Start printing 
        'TODO IMPLEMENT OpenAusdruck_inWord_XML(Me.IDNRTextBox.Text, "Vorlagen/0. BRIEF.dot", "WORD", False, Nothing)
    End Sub

    Sub BeginNew()
        Try
            BindingNavigatorAddNewItem_Click(Nothing, Nothing)
            ofAdressenBindingSource.AddNew()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    ''' <summary>
    ''' Daten für Kunde mit IDNR Laden
    ''' </summary>
    ''' <param name="IDNR"></param>
    ''' <remarks></remarks>
    Sub LadeKunde(IDNR As Integer)
        Me.IDNR = IDNR
        TableAdapterManager.Connection = CurrentDB
        TableAdapterManager1.Connection = CurrentDB
        OfAdressenTableAdapter.Connection = CurrentDB
        KundengruppenTableAdapter.Connection = CurrentDB
        Ofadressen_weitereTableAdapter.Connection = CurrentDB
        PreislistenTableAdapter.Connection = CurrentDB
        Ofadressen_zahlungsmethodenTableAdapter.Connection = CurrentDB
        Ofadressen_zahlungsbedingungenTableAdapter.Connection = CurrentDB
        Ofadressen_transportmethodenTableAdapter.Connection = CurrentDB
        Ofadressen_settingsTableAdapter.Connection = CurrentDB
        ds = DataSetKunden

        'Me.AdressenDetailControl1.Init()
        GrbranchenTableAdapter.Fill(DsBranchen.grbranchen)
        BuchvorgangtypTableAdapter.Fill(DsVorgaenge.buchvorgangtyp)
        GrtransportmethodeTableAdapter.Fill(DsStammdaten.grtransportmethode)
        GrzahlungsbedingungTableAdapter.Fill(DsStammdaten.grzahlungsbedingung)
        GrzahlungsmethodeTableAdapter.Fill(DsStammdaten.grzahlungsmethode)

        'Satus 
        'FillComboBox(Me.StatusComboBox, "select Status from ofAdressen group by Status order by Status", "Status", "Status")

        GrlandTableAdapter.FillBy(DsPLZ.grland)
        'TODO - falls Land geändert wird dann auch hier Land ändern
        Dim KundeLand = ModuleKunden.KundeLand(IDNR)
        If Not IsDBNull(KundeLand) Then
            GrLandPlzTableAdapter.FillByLand(DsPLZ.grLandPlz, KundeLand)
        End If

        DataSetKunden.Clear()

        OfAdressenTableAdapter.Fill(DataSetKunden.ofadressen, IDNR:=IDNR)
        Ofadressen_settingsTableAdapter.Fill(DataSetKunden._ofadressen_settings, IDNR:=IDNR)
        Ofadressen_weitereTableAdapter.Fill(DataSetKunden._ofadressen_weitere, IDNR:=IDNR)

        Ofadressen_zahlungsmethodenTableAdapter.Fill(DataSetKunden._ofadressen_zahlungsmethoden, IDNR:=IDNR)
        Ofadressen_zahlungsbedingungenTableAdapter.Fill(DataSetKunden._ofadressen_zahlungsbedingungen, IDNR:=IDNR)
        Ofadressen_transportmethodenTableAdapter.Fill(DataSetKunden._ofadressen_transportmethoden, IDNR:=IDNR)


        PreislistenTableAdapter.Fill(DataSetKunden.Preislisten)
        KundengruppenTableAdapter.Fill(DataSetKunden.Kundengruppen)
        FillComboBox(MandantNrComboBox, "select IDNR, Firma FROM Mandant ORDER By Firma", "Firma", "IDNR")

        Try
            Dim adr = GetOfAdresse()
            If Not adr Is Nothing Then
                If adr.IsUIDGeprueftAmNull Then
                    TextBoxUIDGeprueftAm.Format = DateTimePickerFormat.Custom
                Else
                    TextBoxUIDGeprueftAm.Format = DateTimePickerFormat.Short
                End If
            End If
        Catch ex As Exception
        End Try
        AdressenVerknuepfungen1.IDNR = IDNR
        AdressenVerknuepfungen1.LoadData()
        Rebind()

        ParentBindingNavigator.BindingSource = ofAdressenBindingSource

        KundenUebersicht1.IDNR = IDNR 'Laden Intern 
        AdressenControlNextIDNR.ShowButtonDetails = True
    End Sub

#Region "Events "

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

            If BeginNewFlag Then
                LadeKunde(-999)
                BeginNew()
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

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

#Region "New"

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

    Function GetKunde() As dsAdressen.ofadressenRow
        Dim k As dsAdressen.ofadressenRow = ofAdressenBindingSource.Current.Row
        Return k
    End Function

    Private Sub BindingSource_CurrentChanged(sender As Object, _
                              e As System.EventArgs) _
                              Handles ofAdressenBindingSource.CurrentChanged
        Try

            If AddingNewFlag Then
                AddingNewFlag = False

                Dim HatKundenGruppen = FirstRow("select count(KGR) as cnt from [ofAdressen-Kundengruppen]")
                Dim neueIDNR
                If IsNumeric(HatKundenGruppen) Then
                    Dim kWizzard = New KundenWizzard
                    'kWizzard.MdiParent = Main
                    RaiseEvent KundenWizzardShown(kWizzard)
                    kWizzard.ShowDialog()
                    If kWizzard.DialogResult = Windows.Forms.DialogResult.OK AndAlso IsNumeric(kWizzard.NummerTextBox.Text) Then
                        neueIDNR = kWizzard.NummerTextBox.Text
                        Dim kundenGruppe = kWizzard.ComboBoxKundengruppe.SelectedValue


                        Dim kunde = GetKunde()
                        kunde.IDNR = neueIDNR
                        kunde.Status = "Kunde"
                        CreateNewSettingsCurrentRow(kundenGruppe)
                        ''   Me.IDNR = neueIDNR
                        ''   Me.AdressenDetailControl1.IDNRTextBox.Text = neueIDNR
                        ''   Me.AdressenDetailControl1.IDNR = neueIDNR
                        ''   Me.cbKundengruppe.SelectedValue = kundenGruppe

                    Else
                        neueIDNR = NextId("ofAdressen", "IDNR", , True)
                        Dim kunde = GetKunde()
                        kunde.IDNR = neueIDNR
                        AdressenDetailControl1.IDNR = neueIDNR 'Sonst kann Form nicht geschlossen werden
                        Return

                    End If
                Else
                    neueIDNR = NextId("ofAdressen", "IDNR", , True)
                    Dim kunde = GetKunde()
                    kunde.IDNR = neueIDNR
                    AdressenDetailControl1.IDNRTextBox.Text = neueIDNR
                End If
                IDNR = neueIDNR
                Return
            End If
            Try
                Dim curIDNR = GetKunde().IDNR
                IDNR = curIDNR
                If IsNumeric(curIDNR) Then KundenIDNR = curIDNR
            Catch ex As Exception
                'Ignore
            End Try
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub
#End Region


    ''' <summary>
    ''' Speichern
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Shadows Sub BindingNavigatorSaveItem_Click(sender As Object, e As System.EventArgs) Handles MyBase.Save

        Try
            Validate()

            Ofadressen_settingsBindingSource.EndEdit()
            ofAdressenBindingSource.EndEdit()
            FKofAdressenofadressensettingsBindingSource.EndEdit()
            Ofadressen_weitereBindingSource.EndEdit()
            Ofadressen_zahlungsbedingungenBindingSource.EndEdit()
            Ofadressen_zahlungsmethodenBindingSource.EndEdit()
            Ofadressen_transportmethodenBindingSource.EndEdit()

            OfAdressenTableAdapter.Update(DataSetKunden)
            Ofadressen_settingsTableAdapter.Update(DataSetKunden)
            Ofadressen_weitereTableAdapter.Update(DataSetKunden)
            Ofadressen_zahlungsbedingungenTableAdapter.Update(DataSetKunden)
            Ofadressen_zahlungsmethodenTableAdapter.Update(DataSetKunden)
            Ofadressen_transportmethodenTableAdapter.Update(DataSetKunden)

            NotizenControl1.Save()
        Catch ex As Exception
            HandleAppError(ex)
        End Try

    End Sub

#End Region

    Function GetOfAdresse() As dsAdressen.ofadressenRow
        If ofAdressenBindingSource.Current Is Nothing Then Return Nothing
        Return ofAdressenBindingSource.Current.row
    End Function

#Region "Vorgaenge"

    Private Sub AlteVorgängeToolStripMenuItem_Click(sender As Object, e As System.EventArgs) Handles AlteVorgängeToolStripMenuItem.Click
        Try

            OeffneVorgangListe(IDNR:=IDNR)

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

    Private Sub AlteVorgängeAnsehenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AlteVorgängeAnsehenToolStripMenuItem.Click
        Try
            OeffneVorgangMaske(IDNR)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


    Private Sub AngeboteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AngeboteToolStripMenuItem.Click
        OeffneVorgangMaske(IDNR, VorgangTypen.AN)
    End Sub

    Private Sub AufträgeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AufträgeToolStripMenuItem.Click
        OeffneVorgangMaske(IDNR, VorgangTypen.AU)
    End Sub

    Private Sub RechnungenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RechnungenToolStripMenuItem.Click
        OeffneVorgangMaske(IDNR, VorgangTypen.AR)
    End Sub

    Private Sub LieferscheinToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LieferscheinToolStripMenuItem.Click
        OeffneVorgangMaske(IDNR, VorgangTypen.LI)
    End Sub

    Private Sub NeuerVorgangToolStripMenuItem1_Click(sender As Object, e As System.EventArgs) Handles NeuerVorgangToolStripMenuItem1.Click
        BeginNewVorgangFuerKundenOhneTyp(IDNR)
    End Sub

    Private Sub AngebotToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AngebotToolStripMenuItem.Click
        BeginNewVorgangFuerKunden(IDNR, VorgangTypen.AN)
    End Sub

    Private Sub AuftragToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AuftragToolStripMenuItem.Click
        BeginNewVorgangFuerKunden(IDNR, VorgangTypen.AU)
    End Sub

    Private Sub RechnungToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RechnungToolStripMenuItem.Click
        BeginNewVorgangFuerKunden(IDNR, VorgangTypen.AR)
    End Sub

#End Region

#Region "Settings"
    Private Sub cbPreisliste_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles cbPreisliste.GotFocus
        CreateNewSettingsCurrentRow()
    End Sub

    Private Sub cbKundengruppe_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles cbKundengruppe.GotFocus
        CreateNewSettingsCurrentRow()
    End Sub

    Private Sub Language_codeComboBox_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles Language_codeComboBox.GotFocus
        CreateNewSettingsCurrentRow()
    End Sub

    Private Sub FirmenKontoIdTextBox_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles FirmenKontoIdTextBox.GotFocus
        CreateNewSettingsCurrentRow()
    End Sub


    Sub CreateNewSettingsCurrentRow(Optional Kundengruppe As String = Nothing)
        Try
            ofAdressenBindingSource.EndEdit()
            'create settings datarow 
            If FKofAdressenofadressensettingsBindingSource.Current Is Nothing Then
                DataSetKunden._ofadressen_settings.Add_ofadressen_settingsRow(ofAdressenBindingSource.Current.row, Kundengruppe, Nothing, Nothing, Nothing)
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub
#End Region

#Region "Weitere Adressen"


    Private Sub AdresseWeitereButton_Click(sender As Object, e As System.EventArgs) Handles AdresseWeitereButton.Click
        AdresseWeitereButton_Clicked()
    End Sub

    Public Sub AdresseWeitereButton_Clicked()
        Try
            If GetKunde() Is Nothing Then
                MsgBox(Messages.Kunden_zuerst_speichern, vbInformation)
                Exit Sub
            End If

            If GetKunde().IDNR < 0 Then
                MsgBox(Messages.Kunden_zuerst_speichern, vbInformation)
                Exit Sub
            End If

            Dim adresseWeitere As New AdresseWeitere
            adresseWeitere.StarteNeueAdresse(IDNR:=AdressenDetailControl1.IDNR, VorgangTyp:=VorgangTypen.LI)
            RaiseEvent AdresseWeitereButtonClicked(adresseWeitere)
            adresseWeitere.ShowDialog()
            'refresh data 
            Ofadressen_weitereTableAdapter.Fill(DataSetKunden._ofadressen_weitere, IDNR:=IDNR)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


    Private Sub ButtonAdressenEditieren_Click(sender As Object, e As EventArgs) Handles ButtonAdressenEditieren.Click

        Try
            Dim a As New AdresseWeitere
            a.LoadData(IDNR:=AdressenDetailControl1.IDNR)
            a.ShowDialog()
            'refresh data 
            Ofadressen_weitereTableAdapter.Fill(DataSetKunden._ofadressen_weitere, IDNR:=IDNR)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


    Private Sub Ofadressen_weitereDataGridView_RowHeaderMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles Ofadressen_weitereDataGridView.RowHeaderMouseDoubleClick
        'TODO Weitere Adresse Bearbeiten 
        Try
            Dim ID = Ofadressen_weitereDataGridView.SelectedRows(0).Cells(0).Value
            Dim a As New AdresseWeitere
            a.LoadDataByID(IDNR:=AdressenDetailControl1.IDNR, ID:=ID)
            a.ShowDialog()
            'refresh data 
            Ofadressen_weitereTableAdapter.Fill(DataSetKunden._ofadressen_weitere, IDNR:=IDNR)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    ''' <summary>
    ''' nicht löschen damit keine Datagid erros aufpoppen
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Ofadressen_weitereDataGridView_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles Ofadressen_weitereDataGridView.DataError

    End Sub
#End Region

    Private Sub UIDLabel_MouseClick(sender As Object, e As MouseEventArgs)
        Process.Start("http://ec.europa.eu/taxation_customs/vies/?locale=de")
    End Sub

    Private Sub UIDTextBox_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles UIDTextBox.MouseDoubleClick
        Process.Start("http://ec.europa.eu/taxation_customs/vies/?locale=de")
    End Sub

    Private Sub AdressenControl1_IDNRChanged(IDNR As Integer) Handles AdressenControlNextIDNR.IDNRChanged
        Try
            Dim current As dsAdressen.ofadressenRow = ofAdressenBindingSource.Current.row
            current.nextIDNR = IDNR
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Ofadressen_zahlungsmethodenDataGridView_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles Ofadressen_zahlungsmethodenDataGridView.DataError

    End Sub

    Private Sub Ofadressen_zahlungsbedingungenDataGridView_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles Ofadressen_zahlungsbedingungenDataGridView.DataError

    End Sub

    Private Sub Ofadressen_transportmethodenDataGridView_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles Ofadressen_transportmethodenDataGridView.DataError

    End Sub


    Private Sub TabControl1_Selected(sender As Object, e As TabControlEventArgs) Handles TabControl1.Selected
        Try
            If e.TabPage.Name = TabPageAnrufe.Name Then
                NotizenControl1.LadeNotizen()
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


    Private Sub NeuesAngebotToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NeuesAngebotToolStripMenuItem.Click
        BeginNewVorgangFuerKunden(IDNR, VorgangTypen.AN)
    End Sub

    Private Sub NeuenAuftragToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NeuenAuftragToolStripMenuItem.Click
        BeginNewVorgangFuerKunden(IDNR, VorgangTypen.AU)
    End Sub

    Private Sub NeueRechnungToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NEueRechnungToolStripMenuItem.Click
        BeginNewVorgangFuerKunden(IDNR, VorgangTypen.AR)
    End Sub

    Private Sub NeuenLieferscheinToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NeuenLieferscheinToolStripMenuItem.Click
        BeginNewVorgangFuerKunden(IDNR, VorgangTypen.LI)
    End Sub

    Private Sub NeueRetourwarenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NeueRetourwarenToolStripMenuItem.Click
        BeginNewVorgangFuerKunden(IDNR, VorgangTypen.RE)
    End Sub


    ''' <summary>
    ''' 
    ''' Öffne Kundenmaske (Arfaian) 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub nextIDNRLink_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles nextIDNRLink.LinkClicked
        If IsNumeric(nextIDNRLink.Text) Then
            OeffneKundenMaske(nextIDNRLink.Text, True)
        End If
    End Sub

    Private Sub TextBoxUIDGeprueftAm_Enter(sender As Object, e As EventArgs) Handles TextBoxUIDGeprueftAm.Enter
        Try
            'Sichbar machen
            TextBoxUIDGeprueftAm.Format = DateTimePickerFormat.Short
        Catch ex As Exception
        End Try
    End Sub

    Private Sub AdressenDetailControl_Resize(sender As Object, e As EventArgs) Handles MyBase.Resize
        Try
            MandantNrComboBox.SelectionLength = 0
            cbKundengruppe.SelectionLength = 0
            cbPreisliste.SelectionLength = 0
            AdressenControlNextIDNR.AdressenComboBox.SelectionLength = 0

        Catch ex As Exception

        End Try
    End Sub

    Private Sub KundenpreiseToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles KundenpreiseToolStripMenuItem.Click
        OeffneKundenMengenPreise(IDNR)
    End Sub

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