Imports IntraSell_DLL
Imports IntraSell_Net_Base

Public Class Dashboard

    Dim plugInsLoader As ClassPlugIns = Nothing
    Dim DashboardIsVisible As Boolean = True
    Dim DashboardIsVisibleAt As New Date

    Private Sub Dashboard_ClientSizeChanged(sender As Object, e As EventArgs) Handles Me.ClientSizeChanged
        Try
            'For some reason sometimes its minimized 
            'this is not allowed

            Dim current_Size = WindowState
            'Debug.Print("Dashboard size " & CStr(current_Size))
            If current_Size = FormWindowState.Minimized Then
                WindowState = FormWindowState.Maximized
            End If
        Catch ex As Exception
            HandleAppError(ex, "Dashboard_ClientSizeChanged", Silent:=True)
        End Try
    End Sub

    Private Sub Dashboard_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
        Try
            ApplyStyle()
            UpdateData()
            RechteSetzen()
            TimerStartmaske.Enabled = True
            AddHandler ModuleGlobals.MitarbeiterIDChanged, AddressOf ModuleGlobals_MitarbeiterIDChanged
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub ModuleGlobals_MitarbeiterIDChanged(MitarbeiterId As Integer)
        RechteSetzen()
    End Sub

    Private Sub LadeStartmaske()
        If ExistsVarValue(AUTOSTART_FORM) Then
            If "EasyKassa".Equals(VarValue(AUTOSTART_FORM)) Then
                ShowRestaurantKassa()
            End If
        End If
    End Sub

    Sub ApplyStyle()
        ModuleStyle.StyleForm(Me)
        ModuleStyle.Style(TableLayoutPanel1)
        ModuleStyle.StyleButton(AuftragButton)
        ModuleStyle.StyleButton(AuftragButton1)
        ModuleStyle.StyleButton(AngebotButton)
        ModuleStyle.StyleButton(RechnungButton)
        ModuleStyle.StyleButton(BestellungenButton)
        ModuleStyle.StyleButton(ButtonOffeneBestellungenListe)
        ModuleStyle.StyleButton(BarrechnungEasyButton)
        ModuleStyle.StyleButton(ButtonOnlineSicherung)
        ModuleStyle.StyleButton(BarrechnungButton)
        ModuleStyle.StyleButton(AnrufenButton)
        ModuleStyle.StyleButton(ButtonNachrichtEinstellungen)
        ModuleStyle.StyleButton(ButtonKundenliste)
        ModuleStyle.StyleButton(KundenButton)
        ModuleStyle.StyleButton(ButtonArtikelListe)
        ModuleStyle.StyleButton(ArtikelMaskeButton)
        ModuleStyle.StyleButton(ArtikelAnlegenButton)
        ModuleStyle.StyleButton(LagerButton)
        ModuleStyle.StyleButton(ButtonOnlineSicherung)
        ModuleStyle.StyleButton(ZustellerDashboardButton)
        ModuleStyle.StyleButton(ButtonOnlineSicherung)
        ModuleStyle.StyleButton(ButtonKassabuch)
        ModuleStyle.StyleButton(ButtonVorgangliste)
        ModuleStyle.StyleButton(ButtonVorgangstatistik)
        ModuleStyle.StyleButton(ButtonRefresh)
        ModuleStyle.StyleButton(ButtonLanguage)
        ModuleStyle.StyleButton(ButtonAbmelden)
        ModuleStyle.StyleButton(ButtonNeues)
    End Sub

    Public Sub LoadPlugins()
        Try
            If plugInsLoader Is Nothing Then
                plugInsLoader = New ClassPlugIns
                plugInsLoader.LadePlugins(Me, Main)

                Dim TAPIListener As New TAPIListener
                TAPIListener.Init()
            End If
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Me.WindowState = FormWindowState.Normal
            Me.WindowState = FormWindowState.Maximized
        End Try
    End Sub

    Private Sub KundenButton_Click(sender As Object, e As System.EventArgs) Handles KundenButton.Click
        Main.NeuerKundeToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub ButtonKundenliste_Click(sender As Object, e As EventArgs) Handles ButtonKundenliste.Click
        Main.KundenlisteToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub ButtonArtikelListe_Click(sender As Object, e As EventArgs) Handles ButtonArtikelListe.Click
        Main.ArtikellisteToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub AngebotButton_Click(sender As Object, e As System.EventArgs) Handles AngebotButton.Click
        BeginNewVorgang(VorgangTypen.AN)
    End Sub

    Private Sub RechnungButton_Click(sender As Object, e As System.EventArgs) Handles RechnungButton.Click
        BeginNewVorgang(VorgangTypen.AR)
    End Sub

    Private Sub ButtonAngebot_Click(sender As Object, e As EventArgs) Handles AuftragButton1.Click
        BeginNewVorgang(VorgangTypen.AU)
    End Sub

    Private Sub MahnungenButton_Click(sender As Object, e As System.EventArgs)
        Main.MahnungenToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub AnrufenButton_Click(sender As Object, e As System.EventArgs) Handles AnrufenButton.Click
        'Main.NeuerAnrufToolStripMenuItem_Click(Nothing, Nothing)
        FormManager.OeffneAnrufliste(-1)
    End Sub

    Private Sub ArtikelMaskeButton_Click(sender As Object, e As EventArgs) Handles ArtikelMaskeButton.Click
        OffneArtikelMaskeByFilter("1=1")
    End Sub

    Shared Sub ArtikelAnlegenButton_Click(sender As Object, e As System.EventArgs) Handles ArtikelAnlegenButton.Click
        BeginNewArtikel()
    End Sub

    Private Sub AnzahlAngeboteLabel_Click(sender As Object, e As System.EventArgs) Handles AnzahlAngeboteLabel.Click
        Main.VorganglisteToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub AnzahlRechnungenLabel_Click(sender As Object, e As System.EventArgs) Handles AnzahlRechnungenLabel.Click
        Main.VorganglisteToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub AnzahlAnrufeLabel_Click(sender As Object, e As System.EventArgs) Handles AnzahlAnrufeLabel.Click
        Main.ListeToolStripMenuItem1_Click(Nothing, Nothing)
    End Sub

    Private Sub AnzahlKundenLabel_Click(sender As Object, e As System.EventArgs) Handles AnzahlKundenLabel.Click
        Main.KundenlisteToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub ArtikelAnlegenLabel_Click(sender As Object, e As System.EventArgs) Handles ArtikelAnlegenLabel.Click
        Main.ArtikellisteToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub BarrechnungButton_Click(sender As Object, e As System.EventArgs) Handles BarrechnungButton.Click
        Main.VorgangBarToolStripMenuItem_Click(Nothing, Nothing)
    End Sub

    Private Sub BarrechnungEasyButton_Click(sender As Object, e As EventArgs) Handles BarrechnungEasyButton.Click
        ShowRestaurantKassa()
    End Sub

    Shared Function ShowRestaurantKassa() As AbstractVorgangBar
        Dashboard.Cursor = Cursors.WaitCursor
        Dim form = FormManager.ShowRestaurantKassa()
        Dashboard.Cursor = Cursors.Default
        Return form
    End Function

    Private Sub LagerButton_Click(sender As Object, e As EventArgs) Handles LagerButton.Click
        Try
            Cursor = Cursors.WaitCursor
            Dim lagerPlugin = GetAppPath().ToLower & "IntraSell_Lager.Plugin"
            plugInsLoader.OnTag(lagerPlugin, False)
            'Lagerbuchung.MdiParent = Main
            'Lagerbuchung.Show()
            'Lagerbuchung.WindowState = FormWindowState.Maximized
            'Lagerbuchung.BringToFront()
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub BestellungenButton_Click(sender As Object, e As EventArgs) Handles BestellungenButton.Click
        Try
            Cursor = Cursors.WaitCursor
            TouchBestellung.MdiParent = Main
            TouchBestellung.Show()
            TouchBestellung.WindowState = FormWindowState.Maximized
            TouchBestellung.ZeigeListe(False)
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub ButtonOffeneBestellungenListe_Click(sender As Object, e As EventArgs) Handles ButtonOffeneBestellungenListe.Click
        OffeneBestellungenListe()
    End Sub

    Private Sub ButtonKassabuch_Click(sender As Object, e As EventArgs) Handles ButtonKassabuch.Click
        Try
            If Not HasRecht(MitarbeiterID, Rechte.Kassabuch, True) Then
                Exit Sub
            End If

            KassaListe.MdiParent = Main
            KassaListe.Show()
            KassaListe.BringToFront()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub ButtonAbmelden_Click(sender As Object, e As EventArgs) Handles ButtonAbmelden.Click
        Try
            'ignoriere wenn zu schnell geklickt wird 
            Dim diff = Date.Now - DashboardIsVisibleAt
            If diff.Seconds < 2 Then
                Exit Sub
            End If
            Login.Logout()
            UpdateData()
            RechteSetzen()
            Login.ShowDialog()
            UpdateData()
            RechteSetzen()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub ButtonVorgangliste_Click(sender As Object, e As EventArgs) Handles ButtonVorgangliste.Click
        OeffneVorgangListe()
    End Sub

    Private Sub ButtonVorgangstatistik_Click(sender As Object, e As EventArgs) Handles ButtonVorgangstatistik.Click
        Try
            VorgangStat.MdiParent = Main
            VorgangStat.Show()
            VorgangStat.BringToFront()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Sub AddPlugin(button As Button, row As Integer, col As Integer)
        button.Dock = DockStyle.Fill
        TableLayoutPlugIns.Controls.Add(button)
    End Sub

#Region "UpdateData"

    Dim lastUpdate As Date = Now.AddDays(-1)
    Private DashboardData1 As New DashboardData


    Private Sub RechteSetzen()
        'Rechte für Buttons 
        BarrechnungButton.Visible = HasRecht(MitarbeiterID, Rechte.Handelskassa, False) And VarValue_Default(Variablen.HANDELSKASSA_AKTIVIERT, False)

        PanelBarrechnungEasy.Visible = HasRecht(MitarbeiterID, Rechte.EasyKassa, False)
        PanelAngebot.Visible = HasRecht(MitarbeiterID, Rechte.Angebot, False)
        AuftragButton.Visible = HasRecht(MitarbeiterID, Rechte.TelefonischeBestellung, False)
        PanelAuftrag.Visible = HasRecht(MitarbeiterID, Rechte.Auftrag, False)
        PanelRechnung.Visible = HasRecht(MitarbeiterID, Rechte.Rechnung, False)
        PanelRechnung.Visible = HasRecht(MitarbeiterID, Rechte.Rechnung, False)
        KundenButton.Visible = HasRecht(MitarbeiterID, Rechte.Kunden, False)
        PanelKundenliste.Visible = HasRecht(MitarbeiterID, Rechte.Kundenliste, False)
        PanelArtikelListe.Visible = HasRecht(MitarbeiterID, Rechte.Artikelliste, False)
        ArtikelAnlegenButton.Visible = HasRecht(MitarbeiterID, Rechte.Artikel, False)
        ArtikelMaskeButton.Visible = HasRecht(MitarbeiterID, Rechte.Artikel, False)
        LagerButton.Visible = HasRecht(MitarbeiterID, Rechte.Lager, False)
        ButtonOnlineSicherung.Visible = HasRecht(MitarbeiterID, Rechte.Online_Sicherung, False)
        ButtonKassabuch.Visible = HasRecht(MitarbeiterID, Rechte.Kassabuch, False)
        ButtonVorgangliste.Visible = HasRecht(MitarbeiterID, Rechte.Vorgangliste, False)
        ButtonVorgangstatistik.Visible = HasRecht(MitarbeiterID, Rechte.Vorgangliste, False)
        PanelOffeneBestellungen.Visible = HasRecht(MitarbeiterID, Rechte.OffeneBestellungen, False)
        UcSucheFrontEnd1.Visible = HasRecht(MitarbeiterID, Rechte.Kundenliste, False) _
            OrElse HasRecht(MitarbeiterID, Rechte.Vorgangliste, False) _
            OrElse HasRecht(MitarbeiterID, Rechte.Artikelliste, False)
        TableLayoutPlugIns.Visible = HasRecht(MitarbeiterID, Rechte.Plugins, False)

        Dim tische As Boolean = Not CType(VarValue_Default(BARRECHNUNG_KEINE_TISCHE, "False"), Boolean)
        PanelTische.Visible = tische AndAlso HasRecht(MitarbeiterID, Rechte.Tische, False)

        Dim zustellung As Boolean = Not CType(VarValue_Default(BARRECHNUNG_KEINE_ZUSTELLUNG, "False"), Boolean)
        PanelZustellungen.Visible = zustellung AndAlso HasRecht(MitarbeiterID, Rechte.Zustellungen, False)
        TableLayoutPanelAnrufe.Visible = HasRecht(MitarbeiterID, Rechte.Anrufe, False)
    End Sub

    Private Sub UpdateData()
        Try
            If Not DashboardIsVisible Then
                Exit Sub
            End If

            If Login.Visible Then
                Exit Sub
            End If

            Dim checkD = (Now - lastUpdate).TotalSeconds
            lastUpdate = Now
            'Tische
            Dim cnt As Short = DashboardData1.offeneTische
            If cnt > 3 Then
                LabelOffeneTische.ForeColor = Color.Red
            Else
                LabelOffeneTische.ForeColor = Color.Green
            End If
            LabelOffeneTische.Text = "offene Tische: " & cnt

            cnt = DashboardData1.offeneAuftraege7Tage
            If cnt > 3 Then
                LabelOffeneBestellungen.ForeColor = Color.Red
            Else
                LabelOffeneBestellungen.ForeColor = Color.Green
            End If

            LabelOffeneBestellungen.Text = "offene Bestellungen: " & cnt

            LabelOffeneZustellungen.Text = "offene Zustellungen: " & DashboardData1.offeneZustellungen
            If DashboardData1.offeneZustellungen > 1 Then
                LabelOffeneZustellungen.ForeColor = Color.Red
            Else
                LabelOffeneZustellungen.ForeColor = Color.Black
            End If

            If VarValue_Default("DASHBOARD_ZEIGE_UMSATZ", "false") And HasRecht(MitarbeiterID, Rechte.Kassabuch, False) Then
                If Not IsNull(DashboardData1.totalKassaTurnover) Then
                    LabelKassaStatistik.Text = "Umsatz: " & DashboardData1.totalKassaTurnover
                End If
            Else
                If Not IsNull(DashboardData1.totalKassaTurnoverAnzahlRechnungen) Then
                    LabelKassaStatistik.Text = "Rechnungen heute: " & DashboardData1.totalKassaTurnoverAnzahlRechnungen
                End If
            End If

            AnzahlAngeboteLabel.Text = "offene Angebote:" & DashboardData1.AnzahlOffeneAngebote
            AnzahlAufträgeLabel.Text = $"offene Aufträge: {DashboardData1.AnzahlOffeneAufträge} von {DashboardData1.AnzahlAufträge}"
            AnzahlRechnungenLabel.Text = $"offene Rechnungen: {DashboardData1.AnzahlOffeneRechnungen} von {DashboardData1.AnzahlRechnungen}"
            AnzahlAnrufeLabel.Text = "Anrufe:" & DashboardData1.AnzahlAnrufe
            AnzahlKundenLabel.Text = "Kunden:" & DashboardData1.AnzahlKunden
            ArtikelAnlegenLabel.Text = "Artikel:" & DashboardData1.ArtikelAnlegen

            If MitarbeiterID > 0 Then
                ButtonAbmelden.Text = "angemeldet als " & MitarbeiterName(MitarbeiterID) & vbNewLine & " A&bmelden"
                ButtonAbmelden.BackColor = MitarbeiterFarbe(MitarbeiterID)
            Else
                ButtonAbmelden.Text = "NICHT Angemeldet"
            End If

            UcFirma1.LoadDaten()

            BenoetigtSicherung(ButtonOnlineSicherung)

            'If DashboardData1.HatGemischteMWSTProKat <> "" Then
            '    WarningMsg("Achtung: In Artikel Kategorien " & DashboardData1.HatGemischteMWSTProKat & " sind die MWST Sätze gemischt. Bitte umgehend sicherstellen, dass je Kategorie nur die selbe MWST benutzt wird!")
            'End If

            If DashboardData1.CheckRegistrierkasse() <> "" Then
                ErrorMsg("Warnung: " & DashboardData1.CheckRegistrierkasse() & "!!!")
            End If

            LabelTasks.Text = "offene Tasks:" & DashboardData1.OffeneTasks

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

#End Region

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        Try
            ArtikelSet.MdiParent = MdiParent
            ArtikelSet.Show()
            ArtikelSet.BringToFront()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub AuftragButton_Click(sender As Object, e As EventArgs) Handles AuftragButton.Click
        Try
            Main.AuftragErfassenToolStripMenuItem_Click(sender, e)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub UcLanguage1_SpracheGewechelt(neueSprache As String)
        Try
            Main.DashboardToolStripMenuItem_Click(Nothing, Nothing)
        Catch
        End Try
    End Sub


    Private Sub Dashboard_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        Main.ToolTipDashboard(True)
    End Sub


    Private Sub Dashboard_Activated(sender As Object, e As EventArgs) Handles Me.Activated
        DashboardIsVisible = True
        DashboardIsVisibleAt = Date.Now
        Main.ToolTipDashboard(False)
    End Sub

    Private Sub Dashboard_LostFocus(sender As Object, e As EventArgs) Handles Me.Deactivate
        DashboardIsVisible = False
        Main.ToolTipDashboard(True)
    End Sub

    Private Sub Dashboard_VisibleChanged(sender As Object, e As EventArgs) Handles Me.VisibleChanged
        DashboardIsVisible = Visible
        If DashboardIsVisible Then
            DashboardIsVisibleAt = Date.Now
        End If
        Main.ToolTipDashboard(Not Visible)
    End Sub

    Private Sub TimerRefresh_Tick(sender As Object, e As EventArgs) Handles TimerRefresh.Tick
        Try
            TimerRefresh.Interval = 60000
            BackgroundWorker1.RunWorkerAsync()
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Public Sub WarningMsg(warnText As String)
        LabelMessage.Text = warnText & vbNewLine & LabelMessage.Text
        LabelMessage.BackColor = Color.Orange
    End Sub

    Public Sub ErrorMsg(warnText As String)
        LabelMessage.Text = warnText & vbNewLine & LabelMessage.Text
        LabelMessage.BackColor = Color.Red
    End Sub

    Private Sub ZustellerDashboardButton_Click(sender As Object, e As EventArgs) Handles ZustellerDashboardButton.Click
        OeffneZustellerPanel()
    End Sub

    Private Sub Dashboard_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If MessageBox.Show("Möchten Sie die Applikation beenden?", "Beenden?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
        Else
            e.Cancel = True 'schliessen ist nicht erlaubt
        End If
    End Sub

    Shared Function GetArtikelQuick2() As ArtikelQuick2
        Return ArtikelQuick2
    End Function

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Try
            Debug.Print("BackgroundWorker1_DoWork")
            Debug.Print("Dashboard DashboardIsVisible " & DashboardIsVisible)
            If DashboardIsVisible Then
                DashboardData1.Berechne()
            End If
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        Try
            Debug.Print("BackgroundWorker1_RunWorkerCompleted")
            UpdateData()
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        Try
            Debug.Print("BackgroundWorker1_ProgressChanged")
            UpdateData()
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Public Sub OnLanguageChange()
        Try
            Controls.Clear()
            InitializeComponent()
            WindowState = FormWindowState.Minimized
            WindowState = FormWindowState.Maximized
            UpdateData()
            RechteSetzen()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub ButtonLanguage_Click(sender As Object, e As EventArgs) Handles ButtonLanguage.Click
        Try
            Main.SpracheToolStripMenuItem_Click(Nothing, Nothing)
        Catch ex As Exception

        End Try
    End Sub

    Private Sub ButtonRefresh_Click(sender As Object, e As EventArgs) Handles ButtonRefresh.Click
        Try
            DashboardData1.Berechne()
            UpdateData()
        Catch ex As Exception
            HandleAppError(ex, "ButtonRefresh_Click", Silent:=True)
        End Try
    End Sub

    Public Function GetPlugInsLoader() As ClassPlugIns
        Return plugInsLoader
    End Function

    Private Sub ButtonNeues_Click(sender As Object, e As EventArgs) Handles ButtonNeues.Click
        Process.Start("http://www.griton.net/index.php/produkte/intrasell-features")
    End Sub

    Private Sub ButtonNachrichtEinstellungen_Click(sender As Object, e As EventArgs) Handles ButtonNachrichtEinstellungen.Click
        FormManager.OpenNachrichtEinstellungen()
    End Sub

    Private Sub TimerStartmaske_Tick(sender As Object, e As EventArgs) Handles TimerStartmaske.Tick
        Try
            TimerStartmaske.Enabled = False
            LadeStartmaske()
        Catch ex As Exception
        End Try
    End Sub

End Class