Imports System.Reflection
Imports System.Runtime.Remoting.Lifetime
Imports System.Threading
Imports IntraSell_DLL

Public Class ModuleReports
    Shared PATH As String = "IntraSell_Net_Reports.exe"
    Dim objForm As Form = Nothing
    Public Shared Report_Kassabeleg80mm_Standard = "Kassabeleg80mm_Standard"
    Public Shared Report_Kassabeleg57mm_Standard = "Kassabeleg57mm_Standard"
    Public Shared Report_KassabelegA4_Standard = "KassabelegA4_Standard"
    Public Shared _Standard = "_Standard"
    Dim printOpts1 As New PrintOpts

    Public Shared Sub ShowReport(DatumVon As Date, DatumBis As Date, reportName As String, Optional reportMethod As String = "ShowReport")
        Try
            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            Dim objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
            objForm.MdiParent = Main
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod(reportMethod)
            mi.Invoke(objForm, {DatumVon, DatumBis, My.Settings.intrasell_daten_2_ConnectionString, reportName})
            objForm.Show()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="DatumVon"></param>
    ''' <param name="DatumBis"></param>
    ''' <param name="filter"></param>
    ''' <param name="reportName"></param>
    ''' <param name="basisMonatlich">wenn true wird eine Abfrage benutzt die bereits die Daten auf Monatsbasis gruppiert hat</param>
    ''' <remarks></remarks>
    Public Shared Function ShowVerkaufsstatistik(DatumVon As Date, DatumBis As Date, filter As String,
                                            Optional reportName As String = "ReportVorgangStatistik.rdlc",
                                            Optional basisMonatlich As Boolean = False,
                                            Optional vorgangTyp As String = "AR",
                                            Optional exportAsPDF As Boolean = False)
        Try
            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            Dim objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
            objForm.MdiParent = Main
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod("ShowReportVerkaufsstatistik")
            mi.Invoke(objForm, {DatumVon, DatumBis, My.Settings.intrasell_daten_2_ConnectionString, filter, reportName, basisMonatlich, vorgangTyp})
            objForm.Show()

            If exportAsPDF Then

                Thread.Sleep(2000)
                Dim miExport As MethodInfo = type.GetMethod("SaveReportAsPDF")
                miExport.Invoke(objForm, {})
                objForm.Close()
                Dim cnt = 0
                While Not IO.File.Exists("exportreport.pdf") AndAlso cnt < 10
                    Thread.Sleep(1000)
                    cnt += 1
                End While
                Dim timestamp = Format(Now, "yyyyMMdd_HHmm")
                Dim exportPDFName = reportName.Replace(".rdlc", timestamp & ".pdf")
                If IO.File.Exists(exportPDFName) Then
                    IO.File.Delete(exportPDFName)
                End If
                IO.File.Move("exportreport.pdf", exportPDFName)
                Return exportPDFName
            Else
                objForm.TopMost = True
            End If

        Catch ex As Exception
            HandleAppError(ex)
        End Try
        Return Nothing
    End Function

    Public Shared Sub ShowReportVorgangSubartikelVerbrauch(DatumVon As Date, DatumBis As Date, filter As String, Optional reportName As String = "ReportVorgangStatistik.rdlc")
        Try
            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            Dim objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
            objForm.MdiParent = Main
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod("ShowReportVerkaufsstatistikVerbrauch")
            mi.Invoke(objForm, {DatumVon, DatumBis, My.Settings.intrasell_daten_2_ConnectionString, filter, reportName})
            objForm.Show()
            objForm.TopMost = True
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Shared Sub ShowReportStatistikAustria(DatumVon As Date, DatumBis As Date, filter As String)
        Try
            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            Dim objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
            objForm.MdiParent = Main
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod("ShowReportVerkaufsstatistikAustria")
            mi.Invoke(objForm, {DatumVon, DatumBis, My.Settings.intrasell_daten_2_ConnectionString, filter})
            objForm.Show()
            objForm.TopMost = True
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Shared Sub ShowReportLagerInventurliste(DatumVon As Date, DatumBis As Date, filter As String)
        Try

            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            Dim objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
            objForm.MdiParent = Main
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod("ShowReportLagerInventurliste")
            mi.Invoke(objForm, {My.Settings.intrasell_daten_2_ConnectionString, filter, DatumVon, DatumBis})
            objForm.Show()
            objForm.TopMost = True
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Sub ShowKassabeleg(vorgangTyp As String, vorgangNummer As Integer, filename As String, qrCodeFile As String)
        Try
            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            If objForm Is Nothing Then
                objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
                objForm.MdiParent = Main
                objForm.WindowState = FormWindowState.Normal
            End If
            AddHandler objForm.FormClosing, AddressOf ReportClosing
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod("ShowKassabeleg")
            mi.Invoke(objForm, {filename, qrCodeFile, "Kassabeleg.rdlc"})
            objForm.Show()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Sub ShowKassabeleg(vorgangTyp As String, vorgangNummer As Integer, filename As String, qrCodeFile As String, templateName As String)
        Try
            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            If objForm Is Nothing Then
                objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
                objForm.MdiParent = Main
                objForm.WindowState = FormWindowState.Normal
            End If
            AddHandler objForm.FormClosing, AddressOf ReportClosing
            Dim type As Type = objForm.GetType()
            If templateName.Contains(Report_Kassabeleg80mm_Standard) _
                OrElse templateName.Contains(Report_Kassabeleg57mm_Standard) _
                OrElse templateName.Contains(Report_KassabelegA4_Standard) _
                OrElse templateName.Contains(_Standard) Then
                Dim mi As MethodInfo = type.GetMethod("ShowKassabelegStandard")
                mi.Invoke(objForm, {vorgangTyp, vorgangNummer, filename, qrCodeFile, templateName})
            Else
                Dim mi As MethodInfo = type.GetMethod("ShowKassabeleg2")
                mi.Invoke(objForm, {filename, qrCodeFile, templateName})
            End If
            objForm.Show()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Class PrintOpts
        Public VorgangTyp As String
        Public VorgangNummer As Integer
        Public filename As String
        Public qrCodeFile As String
        Public qrCodeFileNavigation As String

        Public qrCodeFilenameFeedback As String
        Public feedbackText As String

        Public templateName As String
        Public deviceInfo As String
        Public printToDefaultPrinter As Boolean
        Public closeFormAfterPrinting As Boolean
    End Class


    ''' <summary>
    ''' Druckt Grafik auf NICHT POS Drucker
    ''' </summary>
    ''' <param name="filename"></param>
    ''' <param name="qrCodeFile"></param>
    ''' <param name="templateName"></param>
    ''' <remarks></remarks>
    Public Sub PrintKassabeleg(vorgangTyp As String,
                               vorgangNummer As Integer,
                               filename As String,
                               qrCodeFile As String,
                               templateName As String,
                               showPreview As Boolean,
                               qrCodeFileNavigation As String,
                               Optional qrCodeFileFeedback As String = Nothing)

        printOpts1.VorgangTyp = vorgangTyp
        printOpts1.VorgangNummer = vorgangNummer
        printOpts1.filename = filename
        printOpts1.qrCodeFile = qrCodeFile
        printOpts1.qrCodeFileNavigation = qrCodeFileNavigation
        printOpts1.qrCodeFilenameFeedback = qrCodeFileFeedback
        printOpts1.templateName = templateName
        printOpts1.printToDefaultPrinter = True
        printOpts1.closeFormAfterPrinting = Not showPreview
        Dim pageWidth = VarValue_Default(DRUCKER_PAPIER_BREITE_MM, "80")
        Dim pageHeight = VarValue_Default(DRUCKER_PAPIER_LAENGE_MM, "297")
        Dim deviceInfo As String = "<DeviceInfo>" &
                                        "<OutputFormat>EMF</OutputFormat>" &
                                        "<PageWidth>" & pageWidth & "mm</PageWidth>" &
                                        "<PageHeight>" & pageHeight & "mm</PageHeight>" &
                                        "<MarginTop>0.0cm</MarginTop>" &
                                        "<MarginLeft>0.0cm</MarginLeft>" &
                                        "<MarginRight>0.0cm</MarginRight>" &
                                        "<MarginBottom>0.0cm</MarginBottom>" &
                                        "</DeviceInfo>"
        printOpts1.deviceInfo = deviceInfo
        If showPreview Then
            PrintKassabelegThread() 'Direkt im UI Thread rufen damit der Report stehen bleibt 
        Else
            Dim t As New Thread(AddressOf PrintKassabelegThread)
            t.Start()
        End If
    End Sub

    Sub PrintKassabelegThread()
        Try

            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            If objForm Is Nothing Then
                objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
                objForm.MdiParent = Main
                objForm.WindowState = FormWindowState.Normal
            End If
            AddHandler objForm.FormClosing, AddressOf ReportClosing
            Dim type As Type = objForm.GetType()

            objForm.Show()

            WriteLog("Print Kassabeleg " & printOpts1.filename)

            If printOpts1.templateName.Contains(Report_Kassabeleg80mm_Standard) _
                OrElse printOpts1.templateName.Contains(Report_Kassabeleg57mm_Standard) _
                OrElse printOpts1.templateName.Contains(Report_KassabelegA4_Standard) _
                OrElse printOpts1.templateName.Contains(_Standard) Then

                If Not printOpts1.closeFormAfterPrinting Then
                    Dim mi As MethodInfo = type.GetMethod("ShowKassabelegStandard")
                    mi.Invoke(objForm, {
                              printOpts1.VorgangTyp,
                              printOpts1.VorgangNummer,
                              printOpts1.filename,
                              printOpts1.qrCodeFile,
                              printOpts1.templateName,
                              printOpts1.closeFormAfterPrinting,
                              printOpts1.printToDefaultPrinter,
                              printOpts1.deviceInfo,
                              printOpts1.qrCodeFileNavigation,
                              printOpts1.qrCodeFilenameFeedback})
                Else
                    'Faster
                    Dim mi As MethodInfo = type.GetMethod("PrintKassabelegStandard")
                    mi.Invoke(objForm, {
                              printOpts1.VorgangTyp,
                              printOpts1.VorgangNummer,
                              printOpts1.filename,
                              printOpts1.qrCodeFile,
                              printOpts1.templateName,
                              printOpts1.deviceInfo,
                              printOpts1.qrCodeFileNavigation,
                              printOpts1.qrCodeFilenameFeedback})
                End If

            Else
                Dim mi As MethodInfo = type.GetMethod("ShowKassabeleg")
                mi.Invoke(objForm, {
                          printOpts1.VorgangTyp,
                          printOpts1.VorgangNummer,
                          printOpts1.filename,
                          printOpts1.qrCodeFile,
                          printOpts1.templateName,
                          printOpts1.closeFormAfterPrinting,
                          printOpts1.printToDefaultPrinter,
                          printOpts1.deviceInfo,
                          printOpts1.qrCodeFileNavigation,
                          printOpts1.qrCodeFilenameFeedback})
            End If

            If printOpts1.closeFormAfterPrinting Then
                objForm.Close()
            End If

            objForm = Nothing
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub ReportClosing(sender As Object, e As FormClosingEventArgs)
        objForm = Nothing
    End Sub

    ''' <summary>
    ''' Druckt Artikeletikette
    ''' </summary>
    ''' <param name="ArtNr"></param>
    ''' <param name="Language_Code"></param>
    ''' <param name="reportName"></param>
    ''' <param name="reportMethod"></param>
    ''' <remarks></remarks>
    Public Shared Sub ShowReportEtikette(ArtNr As Integer, Language_Code As String, Optional reportName As String = "ArtikelEtikette.rdlc", Optional reportMethod As String = "ShowReportArtikelEtikette")
        Try
            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            Dim objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
            objForm.MdiParent = Main
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod(reportMethod)
            mi.Invoke(objForm, {CType(ArtNr, String), Language_Code, My.Settings.intrasell_daten_2_ConnectionString, reportName})
            objForm.Show()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Shared Sub ShowReportBarcodes(ArtNr As Integer,
                                         Zeilen As Integer,
                                         Spalten As Integer,
                                         Language_Code As String, Optional reportName As String = "ArtikelBarcodes.rdlc",
                                         Optional reportMethod As String = "ShowReportArtikelBarcodes")
        Try
            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            Dim objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
            objForm.MdiParent = Main
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod(reportMethod)
            '  Public Sub ShowReportArtikelBarcodes(Barcode As String, rows As Int16, cols As Int16, ConnString As String, ReportName As String)
            Dim artikel = OpenRecordsetInMemory("select barcode, Bezeichnung, Beschreibung, PreisATS_Brutto from grArtikel where artnr=" & ArtNr)
            Dim barcode = artikel.Rows(0)("barcode")
            Dim Bezeichnung = artikel.Rows(0)("Bezeichnung")
            Dim Beschreibung = artikel.Rows(0)("Beschreibung")
            Dim PreisATS_Brutto = artikel.Rows(0)("PreisATS_Brutto")
            mi.Invoke(objForm, {CType(barcode, String), CType(Bezeichnung, String), CType(Beschreibung, String), CDec(PreisATS_Brutto), Zeilen, Spalten, My.Settings.intrasell_daten_2_ConnectionString, reportName})
            objForm.Show()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub


    Public Shared Sub ShowZustellungen(DatumVon As Date, DatumBis As Date,
                                       Optional filter As String = "",
                                       Optional reportName As String = "ReportZustellung.rdlc",
                                       Optional exportAsPDF As Boolean = False)
        Try

            Dim ass As Assembly = Assembly.LoadFrom(PATH)
            Dim FormInstanceType = ass.GetType("IntraSell_Net_Reports.ReportViewer")
            Dim objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
            objForm.MdiParent = Main
            Dim type As Type = objForm.GetType()
            Dim mi As MethodInfo = type.GetMethod("ShowReportZustellung")
            mi.Invoke(objForm, {DatumVon, DatumBis, My.Settings.intrasell_daten_2_ConnectionString, filter, reportName})
            objForm.Show()

            If exportAsPDF Then
                Thread.Sleep(2000)
                Dim miExport As MethodInfo = type.GetMethod("SaveReportAsPDF")
                miExport.Invoke(objForm, {})
                objForm.Close()
            Else
                objForm.TopMost = True
            End If

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

    ''' <summary>
    ''' Wird für Reporting benötigt damit weniger RAM verbraucht wird
    ''' </summary>
    Public Shared Sub ConfigureLeaseTime()
        LifetimeServices.LeaseTime = TimeSpan.FromSeconds(5)
        LifetimeServices.LeaseManagerPollTime = TimeSpan.FromSeconds(5)
        LifetimeServices.RenewOnCallTime = TimeSpan.FromSeconds(1)
        LifetimeServices.SponsorshipTimeout = TimeSpan.FromSeconds(5)
    End Sub

End Class
