Option Explicit On

Imports GriTon.XML2Word
Imports IntraSell_DLL
Imports IntraSell_Net_Base
Module ModuleBuchVorgangXML

    Public Const VIEWER_WORD = "WORD"
    Public Const VIEWER_XML As String = "XML"
    Public Const VIEWER_OUTLOOK As String = "OUTLOOK"
    Public Const VIEWER_PDF As String = "PDF"
    Public Const VIEWER_HTML As String = "HTML"
    Public Const MAIL_GRITON As String = "MAIL_GRITON"


    Function XML2WORD() As String
        Return DbFolder() & "..\components\XML2WordGT\TestXML2Word.exe"
    End Function


    ''' <summary>
    ''' Generates new MS Word File using XML2WORD
    ''' </summary>
    ''' <param name="VorgangTyp"></param>
    ''' <param name="VorgangNummer"></param>
    ''' <param name="VorlageFilename"></param>
    ''' <param name="Viewer">Viewer = WORD, XML, OUTLOOK or PDF</param>
    ''' <param name="Silent"></param>
    ''' <returns> Returns the filename of the MS Word File</returns>
    ''' <remarks></remarks>
    Function OpenAusdruck_inWord_XML(
                                VorgangTyp As String,
                                VorgangNummer As Long,
                                VorlageFilename As String,
                                Viewer As String,
                                Silent As Boolean) As String
        Try
            Application.UseWaitCursor = True
            Dim Data As String = VorgangXML(VorgangNummer, VorgangTyp)

            Dim ArchiveFilename As String = Nothing

            'jetzt XML erstellen

            Dim xml As String
            xml = "<DOCUMENT>" & vbCrLf
            xml = xml & Data & vbCrLf
            xml &= "</DOCUMENT>"

            'Create TMP Folder 
            'Create Archive Folde if not et exiting 
            If Dir(GetAppPath() & "tmp", vbDirectory) = "" Then
                MkDir(GetAppPath() & "tmp")
            End If

            Dim FileNameXMLDoc As String = DbFolder() & "tmp\Vorgang_" & VorgangTyp & VorgangNummer & ".xml"

            SaveXML(xml, FileNameXMLDoc)

            If VorlageFilename IsNot Nothing Then
                Dim ResultFilenamePrefix As String = "Vorgang_" & VorgangTyp & VorgangNummer
                Dim ResultFilename As String = DbFolder() & "tmp\" & ResultFilenamePrefix & "1.doc"


                'merge with word template
                Dim Vorlage As String = DbFolder() & VorlageFilename

                Dim ExportPath As String = SelektiereExportPath(VorgangTyp)
                CallXML2WORD(FileNameXMLDoc, Vorlage, ExportPath, ResultFilenamePrefix)

                'rename file to remove the 1 at the end
                ArchiveFilename = Replace(ResultFilename, DbFolder() & "tmp\", ExportPath)
                ArchiveFilename = Replace(ArchiveFilename, "1.doc", ".doc")
                'nur wenn die datei nicht vorher existiert 
                If Not FileIO.FileSystem.FileExists(ArchiveFilename) Then
                    RenameFile(ResultFilename, ArchiveFilename)
                Else
                    If Environment.GetEnvironmentVariable("UITest") = "True" Then
                        RenameFile(ResultFilename, ArchiveFilename)
                    Else
                        If Silent Then
                            RenameFile(ResultFilename, ArchiveFilename)
                        Else
                            If MsgBox("Die Datei " & ArchiveFilename & " wurde bereits angelegt! Wollen Sie diese Datei ersetzen?", vbYesNo, "Ersetzen?") = vbYes Then
                                RenameFile(ResultFilename, ArchiveFilename)
                            End If
                        End If
                    End If
                End If
            End If

            If Viewer IsNot Nothing Then
                DokumentOeffnen(Viewer, ArchiveFilename, Nothing)
            End If
            'DokumentOeffnen(VIEWER_XML, FileNameXMLDoc, VorgangTyp, VorgangNummer, SofortSenden, MailText)
            Application.UseWaitCursor = False

            Return ArchiveFilename
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Application.UseWaitCursor = False
        End Try
        Return Nothing
    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="VorgangTyp"></param>
    ''' <returns></returns>
    Public Function SelektiereExportPath(VorgangTyp As String) As String
        Dim ExportPath As String = DbFolder() & "archiv\" & VorgangTyp & "\"

        ExportPath = VarValue_Default("SPEICHERPLATZ_VORGANG_" & VorgangTyp, ExportPath) 'hier kann der Administrator den Speicherplatz bestimmen

        If Not IO.Directory.Exists(ExportPath) Then 'Fallback to tmp folder
            If Not silent Then
                MsgBox("Verzeichnis " & ExportPath & " wurde nicht gefunden. Bitte die Einstellung " & "SPEICHERPLATZ_VORGANG_" & VorgangTyp & " prüfen!", vbOK)

                Dim folderBrowserDialog1 As New FolderBrowserDialog
                If (folderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
                    SetVarValue("SPEICHERPLATZ_VORGANG_" & VorgangTyp, folderBrowserDialog1.SelectedPath & "\")
                    Return folderBrowserDialog1.SelectedPath & "\"
                End If
            End If
            ExportPath = DbFolder() & "archiv\" & VorgangTyp & "\"
        End If
        Return ExportPath
    End Function

    ''' <summary>
    ''' Erstellt XML für einen Vorgang
    ''' </summary>
    ''' <param name="VorgangNummer"></param>
    ''' <param name="VorgangTyp"></param>
    ''' <returns>Vorgng Daten als XML</returns>
    ''' <remarks></remarks>
    Public Function VorgangXML(VorgangNummer As Long, VorgangTyp As String) As String
        Try
            Application.UseWaitCursor = True

            Dim xml As String = ""

            xml &= "<Vorgang>"
            xml += QueryToXML("select vt.*, v.*, date(datum) as DatumOhneUhrzeit, " &
                             " (select MAX(mwstsatz) from `buchVorgang-Artikel` where Nummer=" & VorgangNummer & " and Typ = '" & VorgangTyp & "') AS MWSTProzent, " &
                             " ROUND(100*(v.SummeBrutto/ v.Summe -1),0) AS MWSTProzentNichtGenau " &
                             " from buchVorgang " &
                             " v, buchVorgangTyp vt where vt.Typ = v.Typ and v.Nummer=" & VorgangNummer & " and v.Typ = '" & VorgangTyp & "'")

            xml += QueryToXML(GetRecSource_Address("ofAdressen", "idnr in (select KundNr from buchVorgang where Nummer=" & VorgangNummer &
                                                        " and Typ = '" & VorgangTyp & "')"), "Kunde")
            'Kundeneinstellungen
            xml += QueryToXML("select k.* from buchVorgang a, `ofadressen-settings` ks, buchfirmenkonto k " &
                        " where a.KundNr = ks.IDNR and ks.Firmenkontoid = k.KontoId and a.Nummer=" & VorgangNummer & " and Typ = '" & VorgangTyp & "'", "UnsereBankVerbindung")

            'Kundengruppe
            xml += QueryToXML("select k.*, ks.* from buchVorgang a, `ofadressen-settings` ks, `ofadressen-kundengruppen` k " &
                        " where a.KundNr = ks.IDNR and ks.Kundengruppe = k.Gruppe and a.Nummer=" & VorgangNummer & " and Typ = '" & VorgangTyp & "'", "Kundengruppe")

            'Lieferadresse
            'Erste / Rechnung Adresse abweichend von der ersten
            xml += QueryToXML(GetRecSource_Address("`ofAdressen-Weitere`", "ID in (select KundNr1 from buchVorgang where Nummer=" & VorgangNummer & " and Typ = '" & VorgangTyp & "')"), "Rechnungadresse")
            'Zweite / Lieferadresse 
            xml += QueryToXML(GetRecSource_Address("`ofAdressen-Weitere`", "ID in (select KundNr2 from buchVorgang where Nummer=" & VorgangNummer & " and Typ = '" & VorgangTyp & "')"), "Lieferadresse")

            xml += QueryToXML(GetRecSource_Address("lieferantenAdressen", "IDNR in (select LieferantNr from buchVorgang where Nummer=" & VorgangNummer & " and Typ = '" & VorgangTyp & "')"), "Lieferant")


            xml += QueryToXML("select adr.* from buchVorgang a, ofMitarbeiter adr " &
                        " where a.MitarbeiterNr = adr.IDNR and a.Nummer=" & VorgangNummer & " and a.Typ = '" & VorgangTyp & "'", "Mitarbeiter")

            xml += QueryToXML("SELECT Name, Value FROM buchvorgaengeeigenschaften b where b.VorgangTyp='" & VorgangTyp & "' and b.Nummer=" & VorgangNummer, "Eigenschaften")

            xml &= "<Positionen>"

            xml += QueryToXML("select p.*, round(p.Preis_Netto,2) AS Preis_NettoGerundet, round(p.Preis_Brutto,2) AS Preis_BruttoGerundet, " &
                                   " round(p.Preis_Netto*p.Stk,2) as PreisSummeNetto, round(p.Preis_Brutto*p.Stk,2) as PreisSummeBrutto, " &
                                   " round(p.Preis_Brutto*p.Stk,2) - round(p.Preis_Netto*p.Stk,2) as PreisSummeMWST, a.*, a.Bezeichnung as ArtikelBezeichnung, " &
                                   " concat(a.EAN,  ' ' , ifnull( p.ArtikelIdentifikation,'')) as EANArtikelIdentifikation," &
                                   " concat(p.Bezeichnung,  ' ' , ifnull( p.ArtikelIdentifikation,'')) as BezeichnungArtikelIdentifikation," &
                                   " k.Name as Kategorie " &
                                   " from `buchVorgang-Artikel` p, grArtikel a,  `grArtikel-Kategorien` k " &
                                   " where p.ArtNr=a.ArtNr and a.ArtKatNr=k.ArtKatNr and p.Nummer=" & VorgangNummer & " and p.Typ = '" & VorgangTyp & "'" &
                                   " ORDER BY a.EAN, p.Id, k.Name, p.Bezeichnung, p.ArtNr", "Position")

            xml &= "</Positionen>"

            xml &= "</Vorgang>"

            Application.UseWaitCursor = False
            Return xml
        Catch ex As Exception
            HandleAppError(ex)
            Application.UseWaitCursor = False
            Return Nothing
        End Try

    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="XMLFilename"></param>
    ''' <param name="WordTemplateFilename"></param>
    ''' <param name="GenerationPath"></param>
    ''' <param name="ResultPraefix"></param>
    ''' <remarks></remarks>
    Private Sub CallXML2WORD(XMLFilename As String, WordTemplateFilename As String, GenerationPath As String, ResultPraefix As String)
        Try
            Application.UseWaitCursor = True
            Dim xml2Word As New XML2WORD With {
                .XMLFile = XMLFilename,
                .WordTemplate = WordTemplateFilename,
                .Path = GetAppPath() & "\tmp\", 'where to generate the files 
                .DocumentPrefix = ResultPraefix
            }
            xml2Word.Execute(FilenamePrefix:=Nothing, showAppWindow:=False, closeAppWindowAtEnd:=True) 'Word is invisible and closed at the end  
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Application.UseWaitCursor = False
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="Dateiname"></param>
    ''' <param name="read_only"></param>
    ''' <remarks></remarks>
    Public Sub DokumentInWordZeigen(Dateiname As String, Optional read_only As Boolean = False)
        Try
            WriteLog("DokumentInWordZeigen " & Dateiname)
            Dim App 'As Application
            App = CreateObject("Word.Application")
            App.Visible = True
            App.Documents.Open(fileName:=Dateiname, ConfirmConversions:=False, readonly:=False, AddToRecentFiles:=False, Format:=0)
            If read_only Then
                App.ActiveDocument.Protect(Password:="xxxqwe", NoReset:=False, Type:=
                1, UseIRM:=False, EnforceStyleLock:=False)
            End If
            App.Activate()
            WriteLog("DokumentInWordZeigen nach Activate " & Dateiname) 'Word ist Focused
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="Viewer">WORD/PDF/OUTLOOK</param>
    ''' <param name="ArchiveFilename"></param>
    ''' <param name="Mail"></param> 
    Public Sub DokumentOeffnen(Viewer As String,
                               ArchiveFilename As String,
                               Optional Mail As Email = Nothing)

        If ArchiveFilename Is Nothing Then
            Return
        End If

        'print or send per email
        If Viewer = VIEWER_WORD Then
            DokumentInWordZeigen(ArchiveFilename)

        ElseIf Viewer = VIEWER_PDF Then
            SaveWordAsPDF(ArchiveFilename)

        ElseIf Viewer = VIEWER_OUTLOOK Then
            If Mail Is Nothing Then
                Mail = New Email
            End If
            Mail.FilePath = ArchiveFilename
            MailWithOutlook(Mail.Subject, Mail.EmailTo, ArchiveFilename, Mail.Mailtext, "", Mail.SofortSenden)

        ElseIf Viewer = MAIL_GRITON Then
            If Mail Is Nothing Then
                Mail = New Email
            End If
            Mail.FilePath = ArchiveFilename
            ModuleMailGriton.MailAnKundeMitDatei(Mail)

        ElseIf Viewer = VIEWER_HTML Then
            Process.Start("file://" & ArchiveFilename)

        ElseIf Viewer = VIEWER_XML Then
            Shell(VarValue_Default("XMLVIEWER", "notepad.exe") & " " & ArchiveFilename)

        End If
    End Sub

    Function KundenEmailVorbereiten(VorgangTyp As String,
                         VorgangNummer As String) As Email
        Dim leereEmail As New Email
        leereEmail.EmailTo = GetKundenEmail(VorgangTyp, VorgangNummer)
        leereEmail.Subject = intrasell.vorgang.GetDruckForType(VorgangTyp) & " #" & VorgangNummer
        Return leereEmail
    End Function

End Module
