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.Xpo
Imports DevExpress.Data.Filtering

Imports DevExpress.ExpressApp.SystemModule
Imports DevExpress.ExpressApp.CloneObject
Imports DevExpress.Persistent.BaseImpl

Public Class ContractReceivablesVC
    Inherits DevExpress.ExpressApp.ViewController
    Protected _selection As ArrayList
    Protected _InvoiceRowsSelection As ArrayList = New ArrayList
    Protected _InvoiceHeaderCreated As ArrayList = New ArrayList
    Protected _noselect As Boolean = False
    Public Sub New()
        MyBase.New()

        _selection = New ArrayList()
        'This call is required by the Component Designer.
        InitializeComponent()
        RegisterActions(components)

    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()
        Frame.GetController(Of ContractReceivablesVC).aCreateInvoicefromContractRowsReceivables.Active.SetItemValue("", False)

        If View.Id = "ContractRows_ListView_Invoice_Not_MileStone" Then
            AddHandler View.SelectionChanged, AddressOf view_SelectionChanged
            Frame.GetController(Of ContractReceivablesVC).aCreateInvoicefromContractRowsReceivables.Active.SetItemValue("", True)
        End If

        If View.Id = "ContractRows_ListView_Invoice_IsProforma" Or View.Id = "ContractRows_ListView_Invoice_Finalized" Then
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of ListViewProcessCurrentObjectController).Active.SetItemValue("", False)
            Frame.GetController(Of CloneObjectViewController).Active.SetItemValue("", False)

        End If

    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        If View.Id = "ContractRows_ListView_Invoice_Not_MileStone" Then
            RemoveHandler View.SelectionChanged, AddressOf view_SelectionChanged
            Frame.GetController(Of ContractReceivablesVC).aCreateInvoicefromContractRowsReceivables.Active.SetItemValue("", False)
        End If
    End Sub
    Private Sub view_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim i As Long = 0
        Dim _ContractRows As ContractRows

        If View Is Nothing Then Exit Sub

        If View.Id = "ContractRows_ListView_Invoice_Not_MileStone" Then
            If _noselect = False Then
                _selection.Clear()
                For Each _ContractRows In View.SelectedObjects
                    If i = 0 Then
                        _selection.Add(_ContractRows)
                        Frame.GetController(Of ContractReceivablesVC).aCreateInvoicefromContractRowsReceivables.Enabled.SetItemValue("", True)
                    Else
                        If _ContractRows.Contracts.CurrencyName_Invoice.Oid = TryCast(_selection(0), ContractRows).Contracts.CurrencyName_Invoice.Oid Then
                            _selection.Add(_ContractRows)
                            i += 1
                        Else
                            _selection.Clear()
                            Frame.GetController(Of ContractReceivablesVC).aCreateInvoicefromContractRowsReceivables.Enabled.SetItemValue("", False)
                        End If
                    End If
                Next
            End If
        End If
    End Sub

    Private Sub aCreateInvoicefromContractRowsReceivables_Cancel(sender As Object, e As System.EventArgs) Handles aCreateInvoicefromContractRowsReceivables.Cancel
        _noselect = False
    End Sub

    Private Sub aCreateInvoicefromContractRowsReceivables_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aCreateInvoicefromContractRowsReceivables.CustomizePopupWindowParams
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)

        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ContractsRowsToInvoice As ContractsRowsToInvoice = _ocur.CreateObject(Of ContractsRowsToInvoice)()
        Dim _ContractsRowsToInvoice_New As ContractsRowsToInvoice

        _ContractsRowsToInvoice.Description = ""
        _ContractsRowsToInvoice.CurrencyRate = 1
        _ContractsRowsToInvoice.DateExecution = GetSQLTime(_ocur.Session)
        _ContractsRowsToInvoice.BankInformation = Nothing
        _ContractsRowsToInvoice.ContractRows = _selection(0)

        _noselect = True
        _ContractsRowsToInvoice.Save()
        _ocur.CommitChanges()

        _ContractsRowsToInvoice_New = _onew.GetObject(_ContractsRowsToInvoice)

        e.View = Application.CreateDetailView(_onew, "ContractsRowsToInvoice_DetailView_Receivables", False, _ContractsRowsToInvoice_New)
    End Sub
    Private Sub aCreateInvoicefromContractRowsReceivables_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aCreateInvoicefromContractRowsReceivables.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _ContractRowsCollection As New XPCollection(Of ContractRows)(_ocur.Session, CriteriaOperator.Parse("1=2"))

        Dim _ContractsRowsToInvoice As ContractsRowsToInvoice = TryCast(e.PopupWindow.View.SelectedObjects(0), ContractsRowsToInvoice)

        Dim _ContractRows As ContractRows
        Dim _ContractRows_Selection As ContractRows
        Dim _InvoiceRows_new As InvoiceRows
        Dim _InvoiceRows_Array As New ArrayList()

        Dim i As Long = 0
        Dim _IsHeaderCreated As Boolean = False
        Dim _IsNextWhile As Boolean = True
        Dim _NG As NumberGenerator

        On Error GoTo CheckError

        Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController)().Active.SetItemValue("", False)
        ' -- létrehozunk egy kollekciót a kiválasztott elemek tömbjébol
        _InvoiceHeaderCreated.Clear()

        For Each _ContractRows_Selection In _selection
            _ContractRows = _ocur.GetObject(_ContractRows_Selection)
            _ContractRowsCollection.Add(_ContractRows)
        Next
        _InvoiceRows_Array.Clear()

        _noselect = False
        ' -- rendezési feltételeket adunk a létrehozott kollekciónak
        Dim sortCollection As SortingCollection = New SortingCollection()
        sortCollection.Add(New SortProperty("Contracts.CustomersFrom.Name", DB.SortingDirection.Ascending))
        sortCollection.Add(New SortProperty("Contracts.Customers.Name", DB.SortingDirection.Ascending))
        sortCollection.Add(New SortProperty("Contracts.BankInformation", DB.SortingDirection.Ascending))
        sortCollection.Add(New SortProperty("Contracts.CurrencyName_Invoice.ShortName", DB.SortingDirection.Ascending))
        sortCollection.Add(New SortProperty("DateExecution", DB.SortingDirection.Ascending))
        sortCollection.Add(New SortProperty("PaymentOption.ShortName", DB.SortingDirection.Ascending))

        _ContractRowsCollection.Sorting = sortCollection

        Do While _IsNextWhile
            Dim _InvoiceHeader As InvoiceHeader
            Dim _InvoiceRows As InvoiceRows = _ocur.CreateObject(Of InvoiceRows)()
            _InvoiceHeader = _ocur.CreateObject(GetType(InvoiceHeader))

            _InvoiceHeader.PaymentOption = _ContractRowsCollection(i).PaymentOption
            _InvoiceHeader.ShipmentOption = _ContractRowsCollection(i).ShipmentOption

            'Ha a sor típusa előleg akkor az előleg számla típusát kell vennünk a szerz.sablonnak egyébként a rendeset
            If _ContractRowsCollection(i).ContractRowsType = eContractRowsType.eAdvance Then
                _InvoiceHeader.InvoiceType = _ContractRowsCollection(i).Contracts.ContractTemplate.InvoiceTypeAdvanced
            Else
                _InvoiceHeader.InvoiceType = _ContractRowsCollection(i).Contracts.ContractTemplate.InvoiceType
            End If
            If _InvoiceHeader.InvoiceType.NumberGeneratorProforma IsNot Nothing Then
                _NG = _InvoiceHeader.InvoiceType.NumberGeneratorProforma
                _InvoiceHeader.DocumentNumberProforma = _NG.GetNewNumber(_NG)
            End If


            _InvoiceHeader.IsProforma = _ContractsRowsToInvoice.IsProforma
            _InvoiceHeader.IsEditable = False
            _InvoiceHeader.CustomersFrom = _ContractRowsCollection(i).Contracts.CustomersFrom
            _InvoiceHeader.Customers = _ContractRowsCollection(i).Contracts.Customers
            _InvoiceHeader.Description = _ocur.GetObject(_ContractsRowsToInvoice.Description)
            _InvoiceHeader.CurrencyName = _ContractRowsCollection(i).Contracts.CurrencyName_Invoice
            _InvoiceHeader.CurrencyRate = _ContractsRowsToInvoice.CurrencyRate
            _InvoiceHeader.BankInformation = _ContractRowsCollection(i).Contracts.BankInformation

            '-- Próbaszámla miatt el kell menteni a tényleges adatokat --------------------------------------------------------
            _InvoiceHeader.Saved_Customers_Name = _ContractRowsCollection(i).Contracts.Customers.Name.ToString
            _InvoiceHeader.Saved_Customers_Address_Country = _ContractRowsCollection(i).Contracts.Customers.Address1.Country.ToString
            _InvoiceHeader.Saved_Customers_Address_ZipPostal = _ContractRowsCollection(i).Contracts.Customers.Address1.ZipPostal.ToString
            _InvoiceHeader.Saved_Customers_Address_Street = _ContractRowsCollection(i).Contracts.Customers.Address1.Street.ToString
            _InvoiceHeader.Saved_Customers_Address_City = _ContractRowsCollection(i).Contracts.Customers.Address1.City.ToString
            _InvoiceHeader.Saved_Customers_Address_StateProvince = _ContractRowsCollection(i).Contracts.Customers.Address1.StateProvince.ToString
            _InvoiceHeader.Saved_Customers_VATNumber = _ContractRowsCollection(i).Contracts.Customers.VATNumber.ToString
            _InvoiceHeader.Saved_Customers_VATNumberEU = _ContractRowsCollection(i).Contracts.Customers.VATNumberEU.ToString

            _InvoiceHeader.Saved_CustomersFrom_Name = _ContractRowsCollection(i).Contracts.CustomersFrom.Name.ToString
            _InvoiceHeader.Saved_CustomersFrom_Address_ZipPostal = _ContractRowsCollection(i).Contracts.CustomersFrom.Address1.ZipPostal.ToString
            _InvoiceHeader.Saved_CustomersFrom_Address_Street = _ContractRowsCollection(i).Contracts.CustomersFrom.Address1.Street.ToString
            _InvoiceHeader.Saved_CustomersFrom_Address_City = _ContractRowsCollection(i).Contracts.CustomersFrom.Address1.City.ToString
            _InvoiceHeader.Saved_CustomersFrom_Address_StateProvince = _ContractRowsCollection(i).Contracts.CustomersFrom.Address1.StateProvince.ToString
            _InvoiceHeader.Saved_CustomersFrom_VATNumber = _ContractRowsCollection(i).Contracts.CustomersFrom.VATNumber.ToString
            _InvoiceHeader.Saved_CustomersFrom_VATNumberEU = _ContractRowsCollection(i).Contracts.CustomersFrom.VATNumberEU.ToString

            _InvoiceHeader.Saved_CustomersFrom_Bank_ShortName = _InvoiceHeader.BankInformation.FullBankAccount.ToString
            _InvoiceHeader.Saved_CustomersFrom_Bank_IBAN = _InvoiceHeader.BankInformation.IBAN.ToString
            _InvoiceHeader.Saved_CustomersFrom_Bank_SWIFT = _InvoiceHeader.BankInformation.SWIFT.ToString
            _InvoiceHeader.Saved_CustomersFrom_Bank_AccountNumber = _InvoiceHeader.BankInformation.AccountNumber.ToString
            '------------------------------------------------------------------------------------------------------------------
            If _ContractRowsCollection(i).ContractRowsType = eContractRowsType.eMileStone Then
                _InvoiceHeader.DateExecution = TryCast(e.PopupWindow.View.SelectedObjects(0), ContractsRowsToInvoice).DateExecution
            Else
                _InvoiceHeader.DateExecution = _ContractRowsCollection(i).DateExecution
            End If
            If _InvoiceHeader.PaymentOption.PayMode = ePayMode.InContinuous Then
                _InvoiceHeader.DatePayment = _InvoiceHeader.DateExecution
            Else
                _InvoiceHeader.DatePayment = _InvoiceHeader.DateCreated.AddDays(_InvoiceHeader.PaymentOption.PayDay)
            End If
            _InvoiceHeader.CurrencyName = _ContractRowsCollection(i).Contracts.CurrencyName_Invoice

            If _InvoiceHeader.IsProforma = False Then
                _InvoiceHeader.ConnectInfo = _InvoiceHeader.InvoiceType.NumberGenerator.GetNewNumber(_InvoiceHeader.InvoiceType.NumberGenerator)
            End If

            _InvoiceHeader.DocumentNumber = _InvoiceHeader.ConnectInfo
            _InvoiceHeader.DateCreated = GetSQLTime(TryCast(View.ObjectSpace, Xpo.XPObjectSpace).Session)

            ' -- Ha folyamatos teljesítésű számla akkor a fizetési határidő megegyezik a teljesítés dátumával
            If _InvoiceHeader.PaymentOption.PayMode = ePayMode.InContinuous Then
                _InvoiceHeader.DatePayment = _InvoiceHeader.DateExecution
            Else
                ' -- Egyébként számolja ki a fizetési opcióból, hogy hány nap van a kiállítás dátuma és a fizetési határidő között
                _InvoiceHeader.DatePayment = _InvoiceHeader.DateCreated.AddDays(_InvoiceHeader.PaymentOption.PayDay)
            End If

            '-- A következő sorok vizsgálata és hozzáadása a fenti fejléchez amíg az ezt engedélyezo feltételek teljesülnek
            Do
                _InvoiceRows_new = _ocur.CreateObject(Of InvoiceRows)()
                _InvoiceRows_new.InvoiceHeader = _InvoiceHeader
                _InvoiceHeader.InvoicePeriod = _ContractRowsCollection(i).InvoicePeriod
                _InvoiceRows_new.InvoicePeriod = _ContractRowsCollection(i).InvoicePeriod

                _InvoiceRows_new.CustomsTariffs = _ContractRowsCollection(i).CustomsTariffs
                _InvoiceRows_new.Description = _ContractRowsCollection(i).Description
                _InvoiceRows_new.QTT = _ContractRowsCollection(i).QTT
                _InvoiceRows_new.QualityOption = _ContractRowsCollection(i).QualityOption
                _InvoiceRows_new.VAT = _ContractRowsCollection(i).VAT
                _InvoiceRows_new.Units = _ContractRowsCollection(i).Units
                _InvoiceRows_new.ShortName = _ContractRowsCollection(i).ShortName

                If _ContractRowsCollection(i).Contracts.CurrencyName.ShortName <> "HUF" Then
                    _InvoiceRows_new.ListPriceHUF = Math.Round(_ContractRowsCollection(i).NettoPriceDEV * _ContractsRowsToInvoice.CurrencyRate, 0, MidpointRounding.AwayFromZero)
                Else
                    _InvoiceRows_new.ListPriceHUF = _ContractRowsCollection(i).NettoPriceHUF
                End If
                _InvoiceRows_new.ListPriceDEV = _ContractRowsCollection(i).NettoPriceDEV
                _InvoiceRows_new.ContractRows = _ContractRowsCollection(i)

                _InvoiceRows_new.Save()
                _InvoiceRows_Array.Add(_InvoiceRows_new)
                If i = _ContractRowsCollection.Count - 1 Then
                    _IsNextWhile = False
                    Exit Do
                End If
                i += 1
            Loop While _ContractRowsCollection(i - 1).Contracts.CustomersFrom Is _ContractRowsCollection(i).Contracts.CustomersFrom And _
                    _ContractRowsCollection(i - 1).Contracts.Customers Is _ContractRowsCollection(i).Contracts.Customers And _
                    _ContractRowsCollection(i - 1).Contracts.BankInformation Is _ContractRowsCollection(i).Contracts.BankInformation And _
                    _ContractRowsCollection(i - 1).DateExecution = _ContractRowsCollection(i).DateExecution And _
                    _ContractRowsCollection(i - 1).CurrencyName Is _ContractRowsCollection(i).CurrencyName And _
                    _ContractRowsCollection(i - 1).PaymentOption Is _ContractRowsCollection(i).PaymentOption

            _InvoiceHeader.Save()
            _ocur.CommitChanges()
            _InvoiceHeader.RecalculateInvoice(_InvoiceHeader, _ocur)
            _ocur.CommitChanges()

            _InvoiceHeaderCreated.Add(_InvoiceHeader)
        Loop

        For Each _InvoiceRows_new In _InvoiceRows_Array
            _ContractRows = _InvoiceRows_new.ContractRows
            _ContractRows.InvoiceRows = _InvoiceRows_new
            If _ContractRows.Contracts.CurrencyName.ShortName <> "HUF" Then
                _ContractRows.NettoPriceHUF = Math.Round(_ContractRows.NettoPriceDEV * _ContractsRowsToInvoice.CurrencyRate, 0, MidpointRounding.AwayFromZero)
                _ContractRows.CurrencyRate = _ContractsRowsToInvoice.CurrencyRate
            End If

            _ContractRows.Save()
        Next
        _ocur.CommitChanges()
        _noselect = False

        Me.PrintSelectedInvoices()

        Frame.GetController(Of DevExpress.ExpressApp.Validation.PersistenceValidationController)().Active.SetItemValue("", True)
        Exit Sub
CheckError:
        If Err.Number = 91 Then Resume Next
        If Err.Number = 13 Then Resume Next

    End Sub

    Sub PrintSelectedInvoices()
        'Meg kell állapítani, hogy a vevő belföldi vagy külföldi.

        Dim _InvoiceHeader As InvoiceHeader
        Dim _CurrencyName As CurrencyName
        If _InvoiceHeaderCreated.Count > 0 Then
            _InvoiceHeader = TryCast(_InvoiceHeaderCreated(0), InvoiceHeader)

            _CurrencyName = _InvoiceHeader.CurrencyName
            If _InvoiceHeader IsNot Nothing Then
                Dim _XAFPrintHelper As New XAFPrintHelper(Nothing, Frame, _InvoiceHeader.InvoiceType.ReportDataV2, CriteriaOperator.Parse("InvoiceHeader.Oid=?", _InvoiceHeader.Oid))
                _XAFPrintHelper.ShowPreviewV2()
            End If
        End If
    End Sub
End Class
