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.ExpressApp.SystemModule
Imports DevExpress.Xpo

Imports System.Linq
Imports DevExpress.Data.Filtering

Public Class LiquidAssetsBallanceVC
    Inherits DevExpress.ExpressApp.ViewController
    Public Event InitWork(ByVal _Minimum As Long, ByVal _Step As Long, ByVal _Maximum As Long)
    Public Event DoWork()
    Public Event FinalWork
    Public Sub New()
        MyBase.New()

        'This call is required by the Component Designer.
        InitializeComponent()
        RegisterActions(components)

    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()

        Frame.GetController(Of LiquidAssetsBallanceVC).aGenerateCurrencyRateAverage.Active.SetItemValue("", False)
        Frame.GetController(Of LiquidAssetsBallanceVC).aGenerateCurrencyRateFIFO.Active.SetItemValue("", False)

        If View.Id = "LiquidAssetsBallanceHeader_LiquidAssetsBallanceRows_ListView_Cassa" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ListViewProcessCurrentObjectController)().Active.SetItemValue("", False)
        End If
        If View.Id = "LiquidAssetsBallanceHeader_DetailView_Cassa" Then
            Frame.GetController(Of NewObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of ModificationsController).SaveAndCloseAction.Active.SetItemValue("", False)
            Frame.GetController(Of ModificationsController).SaveAndCloseAction.Active.SetItemValue("", False)
            Frame.GetController(Of CloneObject.CloneObjectViewController).Active.SetItemValue("", False)
            Frame.GetController(Of DeleteObjectsViewController).Active.SetItemValue("", False)
            Dim _LiquidAssetsBallanceHeader As LiquidAssetsBallanceHeader
            Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
            _LiquidAssetsBallanceHeader = TryCast(View.SelectedObjects(0), LiquidAssetsBallanceHeader)
            If _LiquidAssetsBallanceHeader IsNot Nothing Then
                _LiquidAssetsBallanceHeader.DateExecution = GetSQLTime(_ocur.Session)
                _ocur.CommitChanges()
                Frame.GetController(Of LiquidAssetsBallanceVC).aGetBallanceCassa.DoExecute()
            End If
        End If
        If View.Id = "LiquidAssetsReturnHeader_LiquidAssetsReturnRows_ListView_Cassa" Then
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", False)
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ListViewProcessCurrentObjectController)().Active.SetItemValue("", False)
        End If
        If View.Id = "GLRows_ListView_Regenerate" Then
            Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", False)
        End If
    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()

        Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController)().Active.SetItemValue("", True)
        Frame.GetController(Of DevExpress.ExpressApp.SystemModule.NewObjectViewController)().Active.SetItemValue("", True)
        Frame.GetController(Of DevExpress.ExpressApp.SystemModule.LinkUnlinkController)().Active.SetItemValue("", True)
        Frame.GetController(Of DevExpress.ExpressApp.CloneObject.CloneObjectViewController)().Active.SetItemValue("", True)
        Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ListViewProcessCurrentObjectController)().Active.SetItemValue("", True)
        Frame.GetController(Of DevExpress.ExpressApp.SystemModule.ModificationsController).SaveAndCloseAction.Active.SetItemValue("", True)
    End Sub
    Private Sub aGetBallance_Execute(ByVal sender As System.Object, ByVal e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aGetBallanceCassa.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _LiquidAssetsBallanceHeader As LiquidAssetsBallanceHeader
        Dim _LiquidAssetsBallanceRows As LiquidAssetsBallanceRows
        _LiquidAssetsBallanceHeader = TryCast(View.SelectedObjects(0), LiquidAssetsBallanceHeader)
        If _LiquidAssetsBallanceHeader IsNot Nothing Then
            _ocur.Delete(_LiquidAssetsBallanceHeader.LiquidAssetsBallanceRows)

            Dim _GLRows_Collection As New XPQuery(Of GLRows)(_ocur.Session)

            Dim query = From _GLRows In _GLRows_Collection _
                        Where _GLRows.GLHeader.DateExecution <= DateAdd(DateInterval.Minute, 1439, _
                                           _LiquidAssetsBallanceHeader.DateExecution.Date) And _GLRows.LiquidAssets IsNot Nothing And _
                              _GLRows.GLHeader.DocumentNumber <> "" And
                              _GLRows.GLHeader.IsEditable = False And
                              _GLRows.GLHeader IsNot Nothing
                Group _GLRows By _GLRows.GLHeader.CustomersFrom, _
                                 _GLRows.LiquidAssets Into g = Group _
                Select New With {Key .CustomersFrom = CustomersFrom, _
                                 Key .LiquidAssets = LiquidAssets, _
                                 Key .InAmountHUF = g.Sum(Function(inv) inv.InAmountHUF), _
                                 Key .OutAmountHUF = g.Sum(Function(inv) inv.OutAmountHUF), _
                                 Key .InAmountDEV = g.Sum(Function(inv) inv.InAmountDEV), _
                                 Key .OutAmountDEV = g.Sum(Function(inv) inv.OutAmountDEV)}
            RaiseEvent InitWork(1, 1, query.Count)
            For Each item In query
                RaiseEvent DoWork()
                If item.LiquidAssets.LiquidAssetsType = eLiquidAssetsType.NormalCheckout Or _
                    item.LiquidAssets.LiquidAssetsType = eLiquidAssetsType.CurrencyCheckout Or _
                    item.LiquidAssets.LiquidAssetsType = eLiquidAssetsType.DepositCheckout Then
                    _LiquidAssetsBallanceRows = _ocur.CreateObject(Of LiquidAssetsBallanceRows)()
                    _LiquidAssetsBallanceRows.LiquidAssetsBallanceHeader = _LiquidAssetsBallanceHeader
                    _LiquidAssetsBallanceRows.CustomersFrom = item.CustomersFrom
                    _LiquidAssetsBallanceRows.LiquidAssets = item.LiquidAssets
                    _LiquidAssetsBallanceRows.BallanceHUF = item.InAmountHUF - item.OutAmountHUF
                    _LiquidAssetsBallanceRows.BallanceDEV = item.InAmountDEV - item.OutAmountDEV

                End If
            Next
            _ocur.CommitChanges()
            RaiseEvent FinalWork
            Frame.GetController(Of RefreshController).RefreshAction.DoExecute()
        End If
    End Sub

    Structure GLRowsToModify_Amount
        Dim Oid As Guid
        Dim OutAmountHUF As Double
        Dim AmountHUF As Double
        Dim DebitAmountHUF As Double
    End Structure

    Private Sub aGenerateCurrencyRateAverage_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aGenerateCurrencyRateAverage.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)


        Dim _GLRows As GLRows = TryCast(View.SelectedObjects(0), GLRows)
        Dim _GLRows_Collection As New XPCollection(Of GLRows)(PersistentCriteriaEvaluationBehavior.InTransaction, _uow, CriteriaOperator.Parse("LiquidAssets.Oid=? And OutAmountDEV>0 And GLHeader.IsEditable=False", _GLRows.LiquidAssets.Oid))
        Dim _Rate As Double
        Dim _GLRowsToModify_ArrayList As ArrayList = New ArrayList
        Dim _GLRowsToModify As GLRowsToModify_Amount = New GLRowsToModify_Amount

        _GLRows_Collection.Sorting.Add(New SortProperty("GLHeader.DateExecution", DB.SortingDirection.Ascending))

        RaiseEvent InitWork(1, 1, _GLRows_Collection.Count)
        For Each _GLRows_Element As GLRows In _GLRows_Collection
            RaiseEvent DoWork()

            _Rate = _GLRows_Element.LiquidAssets.GetCurrencyRateAverage(_uow, _GLRows_Element.LiquidAssets, _GLRows_Element.GLHeader.DateExecution)

            _GLRowsToModify.Oid = _GLRows_Element.Oid
            _GLRowsToModify.OutAmountHUF = Math.Round(_GLRows_Element.OutAmountDEV * _Rate, 2, MidpointRounding.AwayFromZero)
            _GLRowsToModify.AmountHUF = Math.Round(_GLRows_Element.AmountDEV * _Rate, 2, MidpointRounding.AwayFromZero)
            _GLRowsToModify.DebitAmountHUF = Math.Round(_GLRows_Element.DebitAmountDEV * _Rate, 2, MidpointRounding.AwayFromZero)
            _GLRowsToModify_ArrayList.Add(_GLRowsToModify)
        Next

        For Each _GLRowsToModify In _GLRowsToModify_ArrayList
            _GLRows = _uow.GetObjectByKey(Of GLRows)(_GLRowsToModify.Oid)
            _GLRows.OutAmountHUF = _GLRowsToModify.OutAmountHUF
            _GLRows.AmountHUF = _GLRowsToModify.AmountHUF
            _GLRows.DebitAmountHUF = _GLRowsToModify.DebitAmountHUF
            _GLRows.Save()
        Next

        RaiseEvent FinalWork

        _uow.CommitChanges()


    End Sub

    Private Sub aGenerateCurrencyRateFIFO_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aGenerateCurrencyRateFIFO.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)


        Dim _GLRows As GLRows = TryCast(View.SelectedObjects(0), GLRows)
        Dim _GLRows_Collection As New XPCollection(Of GLRows)(PersistentCriteriaEvaluationBehavior.InTransaction, _uow, CriteriaOperator.Parse("LiquidAssets.Oid=? And OutAmountDEV>0 And GLHeader.IsEditable=False", _GLRows.LiquidAssets.Oid))
        Dim _GLRows_CollectionToSetZero As New XPCollection(Of GLRows)(PersistentCriteriaEvaluationBehavior.InTransaction, _uow, CriteriaOperator.Parse("LiquidAssets.Oid=? And GLHeader.IsEditable=False", _GLRows.LiquidAssets.Oid))
        Dim _Rate As Double
        Dim _GLRowsToModify_ArrayList As ArrayList = New ArrayList
        Dim _GLRowsToModify As GLRowsToModify_Amount = New GLRowsToModify_Amount

        For Each _GLRows_Element As GLRows In _GLRows_CollectionToSetZero
            _GLRows_Element.AmountDEVFIFO = 0
            _GLRows_Element.Save()
        Next

        _GLRows_Collection.Sorting.Add(New SortProperty("GLHeader.DateExecution", DB.SortingDirection.Ascending))

        RaiseEvent InitWork(1, 1, _GLRows_Collection.Count)
        For Each _GLRows_Element As GLRows In _GLRows_Collection
            RaiseEvent DoWork()

            _Rate = _GLRows.LiquidAssets.GetCurrencyRateFIFO(_uow, _GLRows_Element.LiquidAssets, _GLRows_Element.OutAmountDEV, _GLRows_Element.GLHeader.DateExecution, _GLRows_Element.Oid)

            _GLRowsToModify.Oid = _GLRows_Element.Oid
            _GLRowsToModify.OutAmountHUF = Math.Round(_GLRows_Element.OutAmountDEV * _Rate, 2, MidpointRounding.AwayFromZero)
            _GLRowsToModify.AmountHUF = Math.Round(_GLRows_Element.AmountDEV * _Rate, 2, MidpointRounding.AwayFromZero)
            _GLRowsToModify.DebitAmountHUF = Math.Round(_GLRows_Element.DebitAmountDEV * _Rate, 2, MidpointRounding.AwayFromZero)
            _GLRowsToModify_ArrayList.Add(_GLRowsToModify)
        Next

        For Each _GLRowsToModify In _GLRowsToModify_ArrayList
            _GLRows = _uow.GetObjectByKey(Of GLRows)(_GLRowsToModify.Oid)
            _GLRows.OutAmountHUF = _GLRowsToModify.OutAmountHUF
            _GLRows.AmountHUF = _GLRowsToModify.AmountHUF
            _GLRows.DebitAmountHUF = _GLRowsToModify.DebitAmountHUF
            _GLRows.Save()
        Next
        RaiseEvent FinalWork

        _uow.CommitChanges()
    End Sub

    Private Sub aGenerateCurrencyRateAverageStart_CustomizePopupWindowParams(sender As Object, e As DevExpress.ExpressApp.Actions.CustomizePopupWindowParamsEventArgs) Handles aGenerateCurrencyRateAverageStart.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _LiquidAssetsRegenerateCurrency As LiquidAssetsRegenerateCurrency
        Dim _GLRows As GLRows = TryCast(View.SelectedObjects(0), GLRows)
        _LiquidAssetsRegenerateCurrency = _onew.CreateObject(Of LiquidAssetsRegenerateCurrency)()
        _LiquidAssetsRegenerateCurrency.DateFrom = New Date(Year(Now), 1, 1)
        _LiquidAssetsRegenerateCurrency.LiquidAssets = _onew.GetObject(_GLRows.LiquidAssets)

        e.View = Application.CreateDetailView(_onew, "LiquidAssetsRegenerateCurrency_DetailView", True, _LiquidAssetsRegenerateCurrency)
    End Sub

    Private Sub aGenerateCurrencyRateAverageStart_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.PopupWindowShowActionExecuteEventArgs) Handles aGenerateCurrencyRateAverageStart.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _LiquidAssetsRegenerateCurrency As LiquidAssetsRegenerateCurrency = TryCast(e.PopupWindow.View.SelectedObjects(0), LiquidAssetsRegenerateCurrency)

        Dim _GLRows_Collection As New XPCollection(Of GLRows) _
                    (PersistentCriteriaEvaluationBehavior.InTransaction, _uow, _
                    CriteriaOperator.Parse("LiquidAssets.Oid=? and GLHeader.IsEditable=False and GetDate(GLHeader.DateExecution)>=?", _
                    _LiquidAssetsRegenerateCurrency.LiquidAssets.Oid, _LiquidAssetsRegenerateCurrency.DateFrom.Date))

        Dim _GLRows As GLRows
        Dim _SumAmountDEV As Double = 0
        Dim _SumAmountHUF As Double = 0
        Dim _LiquidAssetsRate As LiquidAssetsRate = _uow.FindObject(Of LiquidAssetsRate)(CriteriaOperator.Parse("LiquidAssets.oid=? and GetYear(DateExecution)=?", _
                                                                                                                _LiquidAssetsRegenerateCurrency.LiquidAssets.Oid, _
                                                                                                                _LiquidAssetsRegenerateCurrency.DateFrom.Date.Year))
        If _LiquidAssetsRate IsNot Nothing Then
            _SumAmountDev = _LiquidAssetsRate.AmountDEV
            _SumAmountHUF = _LiquidAssetsRate.AmountHUF
        End If

        _GLRows_Collection.Sorting.Add(New SortProperty("GetDate(GLHeader.DateExecution)", DB.SortingDirection.Ascending))
        _GLRows_Collection.Sorting.Add(New SortProperty("InAmountDEV", DB.SortingDirection.Descending))

        RaiseEvent InitWork(1, 1, _GLRows_Collection.Count)
        For Each _GLRows In _GLRows_Collection
            '// A deviza a fix és az MNB árfolyammal újra kell számolni mindent
            RaiseEvent DoWork()
            If _GLRows.InAmountDEV > 0 Then
                Dim _CurrencyRate_MNB_Collection = New XPCollection(Of CurrencyRate) _
                    (_ocur.Session, CriteriaOperator.Parse("CurrencyName.ShortName=? and IsMNB=True and GetDate(DateValid)<=?", _
                    _LiquidAssetsRegenerateCurrency.LiquidAssets.CurrencyName.ShortName, _GLRows.GLHeader.DateExecution.Date))
                _CurrencyRate_MNB_Collection.Sorting.Add(New SortProperty("DateValid", DB.SortingDirection.Descending))
                If _CurrencyRate_MNB_Collection.Count > 0 Then
                    For Each _CurrencyRate_MNB In _CurrencyRate_MNB_Collection
                        If _CurrencyRate_MNB.DateValid.Date = _GLRows.GLHeader.DateExecution.Date Then
                            _GLRows.InAmountHUF = Math.Round(_CurrencyRate_MNB.RateAverage * _GLRows.InAmountDEV, 2, MidpointRounding.AwayFromZero)
                            _GLRows.AmountHUF = _GLRows.InAmountHUF
                            Exit For
                        End If
                    Next
                End If
            End If
        Next
        RaiseEvent FinalWork
        _uow.CommitChanges()

        _GLRows_Collection = New XPCollection(Of GLRows) _
                    (PersistentCriteriaEvaluationBehavior.InTransaction, _uow, _
                    CriteriaOperator.Parse("LiquidAssets.Oid=? and GLHeader.IsEditable=False and GetDate(GLHeader.DateExecution)>=?", _
                    _LiquidAssetsRegenerateCurrency.LiquidAssets.Oid, _LiquidAssetsRegenerateCurrency.DateFrom.Date))

        _GLRows_Collection.Sorting.Add(New SortProperty("GetDate(GLHeader.DateExecution)", DB.SortingDirection.Ascending))
        _GLRows_Collection.Sorting.Add(New SortProperty("InAmountDEV", DB.SortingDirection.Descending))
        _GLRows_Collection.Sorting.Add(New SortProperty("OutAmountDEV", DB.SortingDirection.Ascending))

        RaiseEvent InitWork(1, 1, _GLRows_Collection.Count)
        For Each _GLRows In _GLRows_Collection
            RaiseEvent DoWork()

            '// Árfolyamok helyrerakása
            If _GLRows.OutAmountDEV > 0 Then
                If _SumAmountDEV <> 0 Then
                    _GLRows.OutAmountHUF = Math.Round(_GLRows.OutAmountDEV * (_SumAmountHUF / _SumAmountDEV), 2, MidpointRounding.AwayFromZero)
                    _GLRows.AmountHUF = _GLRows.OutAmountHUF
                    _GLRows.Save()
                    _uow.CommitChanges()

                    If _GLRows.PartnerType <> ePartnerType.eNotSet Then
                        GLFunctions.ReconfigurePCI(_uow, _GLRows.GLHeader.CustomersFrom, _GLRows.Customer, _GLRows.PartnerType, _GLRows.ConnectInfo)
                        _uow.CommitChanges()
                    End If
                Else
                    Dim _CurrencyRate_MNB_Collection = New XPCollection(Of CurrencyRate) _
                                        (_ocur.Session, CriteriaOperator.Parse("CurrencyName.ShortName=? and IsMNB=True and GetDate(DateValid)<=?", _
                                        _LiquidAssetsRegenerateCurrency.LiquidAssets.CurrencyName.ShortName, _GLRows.GLHeader.DateExecution.Date))
                    _CurrencyRate_MNB_Collection.Sorting.Add(New SortProperty("DateValid", DB.SortingDirection.Descending))
                    If _CurrencyRate_MNB_Collection.Count > 0 Then
                        For Each _CurrencyRate_MNB In _CurrencyRate_MNB_Collection
                            If _CurrencyRate_MNB.DateValid.Date = _GLRows.GLHeader.DateExecution.Date Then
                                _GLRows.OutAmountHUF = Math.Round(_CurrencyRate_MNB.RateAverage * _GLRows.OutAmountDEV, 2, MidpointRounding.AwayFromZero)
                                _GLRows.AmountHUF = _GLRows.OutAmountHUF
                                _GLRows.Save()
                                _uow.CommitChanges()
                                If _GLRows.PartnerType <> ePartnerType.eNotSet Then
                                    GLFunctions.ReconfigurePCI(_uow, _GLRows.GLHeader.CustomersFrom, _GLRows.Customer, _GLRows.PartnerType, _GLRows.ConnectInfo)
                                    _uow.CommitChanges()
                                End If
                                Exit For
                            End If
                        Next
                    End If
                End If

                _SumAmountDEV -= Math.Round(_GLRows.OutAmountDEV, 2, MidpointRounding.AwayFromZero)
                _SumAmountHUF -= Math.Round(_GLRows.OutAmountHUF, 2, MidpointRounding.AwayFromZero)

                If _SumAmountDEV < 0 Then _SumAmountDEV = 0
                If _SumAmountHUF < 0 Then _SumAmountHUF = 0
            Else
                _SumAmountDEV += Math.Round(_GLRows.InAmountDEV, 2, MidpointRounding.AwayFromZero)
                _SumAmountHUF += Math.Round(_GLRows.InAmountHUF, 2, MidpointRounding.AwayFromZero)
            End If
        Next
        _uow.CommitChanges()

        RaiseEvent FinalWork

    End Sub
End Class
