Imports System
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text

Imports DevExpress.ExpressApp
Imports DevExpress.ExpressApp.Actions
Imports DevExpress.Persistent.Base
Imports DevExpress.Data.Filtering
Imports DevExpress.XtraReports.UI
Imports DevExpress.XtraReports.Parameters
Imports DevExpress.ExpressApp.Reports
Imports DevExpress.Persistent.BaseImpl
Imports System.IO
Imports DevExpress.ExpressApp.Editors
Imports Gnostice.PDFOne
Imports DevExpress.ExpressApp.Utils

Public Class OffersOutPrintVC
    Inherits Nuvolar.Module.OffersOutPrintVC
    Private _ReportServiceController As ReportServiceController
    Private _RichEditControl As RichEditControl

    Public Sub New()
        MyBase.New()
        InitializeComponent()
        RegisterActions(components)
    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()
        Frame.GetController(Of OffersOutPrintVC).aOfferOutSendMailDeatil.Active.SetItemValue("", False)
        If View.Id = "OfferOutHeader_DetailView" Then
            Frame.GetController(Of OffersOutPrintVC).aOfferOutSendMailDeatil.Active.SetItemValue("", True)
        End If
        If View.Id = "CRM_Opportunities_OfferOutHeader_ListView" Then
            Frame.GetController(Of OffersOutPrintVC).aOfferOutSendMailDeatil.Active.SetItemValue("", True)
        End If
    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        If View.Id = "OfferOutHeader_DetailView" Then
            Frame.GetController(Of OffersOutPrintVC).aOfferOutSendMailDeatil.Active.SetItemValue("", False)
        End If
        If View.Id = "CRM_Opportunities_OfferOutHeader_ListView" Then
            Frame.GetController(Of OffersOutPrintVC).aOfferOutSendMailDeatil.Active.SetItemValue("", True)
        End If
    End Sub
    Protected Overrides Sub OnViewControlsCreated()
        MyBase.OnViewControlsCreated()
        If View.Id = "OfferOutHeader_DetailView" Then
            Dim _DetailView As DetailView = TryCast(View, DetailView)
            Dim _RichEditContolViewItem As ViewItem = _DetailView.FindItem("DocumentBody")
            If _RichEditContolViewItem IsNot Nothing Then
                AddHandler _RichEditContolViewItem.ControlCreated, AddressOf RichEditContolViewItem_ControlCreated
            End If
        End If
    End Sub

    Private Sub RichEditContolViewItem_ControlCreated(sender As Object, e As EventArgs)
        Dim _ItemControl As Object = TryCast(sender, ViewItem).Control
        Dim _RichEditUserControl As RichEditUserControl = TryCast(_ItemControl, RichEditUserControl)
        _RichEditControl = TryCast(_ItemControl, RichEditUserControl).RichEditControl
    End Sub

    Private Sub aOfferOutSendMailDeatil_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aOfferOutSendMailDeatil.Execute
        Try
            Dim _ObjectSpace As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            If View.SelectedObjects.Count = 0 Then Throw New Exception("*Nincs kiválasztva egyetlen ajánlat sem!")
            Dim _OfferOutHeader As OfferOutHeader = TryCast(View.SelectedObjects(0), OfferOutHeader)
            If _OfferOutHeader.IsEditable = False Then
                Dim _ReportData As ReportData

                If Frame.GetController(Of OffersOutPrintVC).aOfferOutPrintChoice.SelectedItem Is Nothing Then
                    Throw New Exception("*Nincs nyomtatvány típus kiválasztva!")
                End If
                Select Case Frame.GetController(Of OffersOutPrintVC).aOfferOutPrintChoice.SelectedItem.Data
                    Case "0" : _ReportData = _OfferOutHeader.OfferOutParameters.ReportData
                    Case "1" : _ReportData = _OfferOutHeader.OfferOutParameters.ReportData1
                    Case Else : Throw New Exception("*Nincs nyomtatvány típus kiválasztva!")
                        Exit Sub
                End Select

                If _ReportData IsNot Nothing Then
                    Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
                    Dim _FileName As String = Path.GetTempPath & CorrectFileName(_OfferOutHeader.DocumentNumber & ".pdf")
                    Dim _XafReport As XafReport = _ReportData.LoadReport(_ocur)
                    Dim _FF As String = "[OfferOutHeader.Oid]='" & _OfferOutHeader.Oid.ToString & "'"
                    _XafReport.FilterString = _FF
                    Dim _StreamFile As New FileStream(_FileName, FileMode.Create)
                    _XafReport.ExportToPdf(_StreamFile)

                    _StreamFile.Close()

                    Dim _OutlookEMail As OutlookEMail = _ocur.CreateObject(Of OutlookEMail)()
                    Dim _OutlookEMailAttachments As OutlookEMailAttachments = _ocur.CreateObject(Of OutlookEMailAttachments)()
                    Dim _DocumentFileData As DocumentFileData = _ocur.CreateObject(Of DocumentFileData)()

                    _StreamFile = New FileStream(_FileName, FileMode.Open)
                    If _OfferOutHeader.CRM_Opportunities IsNot Nothing Then
                        _OutlookEMail.CRM_Leads = _OfferOutHeader.CRM_Opportunities.CRM_Leads
                        _OutlookEMail.CRM_Opportunities = _OfferOutHeader.CRM_Opportunities
                    End If
                    _OutlookEMail.Recipients = _OfferOutHeader.Contact.Email
                    If _OutlookEMail.Recipients = "" Then
                        _OutlookEMail.Recipients = "A kapcsolattartónak nincs e-mail címe."
                    End If
                    _OutlookEMail.Subject = "Árajánlat"
                    Dim _s As String = _OfferOutHeader.DocumentNumber & ".pdf"

                    _DocumentFileData.File = New FileData(_ocur.Session)
                    _DocumentFileData.File.LoadFromStream(_s, _StreamFile) '_FileData
                    _DocumentFileData.File.FileName = CorrectFileName(_OfferOutHeader.DocumentNumber & ".pdf")
                    _OutlookEMailAttachments.DocumentFileData = _DocumentFileData
                    _OutlookEMail.OutlookEMailAttachments.Add(_OutlookEMailAttachments)

                    _StreamFile.Close()

                    If System.IO.File.Exists(_FileName) Then
                        System.IO.File.Delete(_FileName)
                    End If

                    e.ShowViewParameters.CreatedView = Application.CreateDetailView(_ocur, "OutlookEMail_DetailView", False, _OutlookEMail)
                    View.Refresh()
                Else
                    '____________________________ TESZT MIATT ________________________________________
                    Throw New UserFriendlyException("Üres a ReportData1 property!")
                End If
            Else
                '____________________________ TESZT MIATT ________________________________________
                Throw New UserFriendlyException("Csak végleges kimenő árajánlatot lehet e-mailben pdf-ként elküldeni.")
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly)
        End Try

    End Sub

    Private Sub aOffersOutPrintPDF2_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aOffersOutPrintPDF2.Execute
        Try
            If Frame.GetController(Of OffersOutPrintVC).aOfferOutPrintChoice.SelectedItem Is Nothing Then Throw New Exception("*Nincs nyomtatvány típus kiválasztva!")
            If _RichEditControl Is Nothing Then Throw New Exception("*A PDF elkészítéséhez aktiválni kell a ""Dokumentum"" fület a részletes nézetben!")

            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            Dim _OfferOutHeader As OfferOutHeader = TryCast(View.SelectedObjects(0), OfferOutHeader)
            If _OfferOutHeader.IsEditable = True Then
                _OfferOutHeader.RecalculateOfferOut(_OfferOutHeader, _ocur)
                _ocur.CommitChanges()
            End If
            Dim _FileName As String = CorrectFileName(_OfferOutHeader.DocumentNumber) & ".pdf"

            Dim _FileName_Report As String = Path.GetTempPath & "Report.pdf"
            Dim _FileName_RTF As String = Path.GetTempPath & "RTF.pdf"
            Dim _FileName_Full As String = Path.GetTempPath & _FileName

            Dim _ReportData As ReportData
            Dim _StreamFile As FileStream
            Dim DOCReport As New PDFDocument("2962-F2F8-23B1-5FD8-F4A3-55DB-7D94-28E9")
            Dim DOCRTF As New PDFDocument("2962-F2F8-23B1-5FD8-F4A3-55DB-7D94-28E9")
            Dim mergeDOC As New PDFDocument("2962-F2F8-23B1-5FD8-F4A3-55DB-7D94-28E9")

            Select Case Frame.GetController(Of OffersOutPrintVC).aOfferOutPrintChoice.SelectedItem.Data
                Case "0" : _ReportData = _OfferOutHeader.OfferOutParameters.ReportData
                Case "1" : _ReportData = _OfferOutHeader.OfferOutParameters.ReportData1
                Case Else : Throw New Exception("*Nincs nyomtatvány típus kiválasztva!")
                    Exit Sub
            End Select

            If _ReportData IsNot Nothing Then
                Dim _XafReport As XafReport = _ReportData.LoadReport(_ocur)
                Dim _FF As String = "[OfferOutHeader.Oid]='" & _OfferOutHeader.Oid.ToString & "'"
                _StreamFile = New FileStream(_FileName_Report, FileMode.Create)
                _XafReport.FilterString = _FF
                _XafReport.ExportToPdf(_StreamFile)
                _StreamFile.Close()
                DOCReport.Load(_FileName_Report)
            End If

            If _RichEditControl IsNot Nothing Then
                _StreamFile = New FileStream(_FileName_RTF, FileMode.Create)
                _RichEditControl.ExportToPdf(_StreamFile)
                _StreamFile.Close()
                DOCRTF.Load(_FileName_RTF)
            End If

            '// Két PDF összefűzése
            mergeDOC.Merge(DOCRTF)
            mergeDOC.Merge(DOCReport)

            mergeDOC.Save(_FileName_Full)
            mergeDOC.Close()

            _StreamFile = New FileStream(_FileName_Full, FileMode.Open)
            Dim _FileData As New FileData(_ocur.Session)
            _FileData.LoadFromStream(_FileName_Full, _StreamFile)
            _OfferOutHeader.PDF_Original = _FileData
            _StreamFile.Close()
            _ocur.CommitChanges()

            Process.Start(_FileName_Full)

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, String.Format(CaptionHelper.GetLocalizedText("Exceptions\NuvolarExceptions", "MsgBoxCheckItAgain")))
        End Try
    End Sub

    
End Class
