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 System.Linq
Imports DevExpress.Persistent.BaseImpl
Imports System.Globalization

Public Class InvoiceRowsPivotVC
    Inherits DevExpress.ExpressApp.ViewController
    Public Event InitWork(ByVal _Minimum As Long, ByVal _Step As Long, ByVal _Maximum As Long)
    Public Event InitWork2(ByVal _Minimum2 As Long, ByVal _Step2 As Long, ByVal _Maximum2 As Long)
    Public Event DoWork()
    Public Event DoWork2()
    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()
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _User As User = _ocur.GetObjectByKey(Of User)(_ocur.GetKeyValue(SecuritySystem.CurrentUser))

        If View.Id = "InvoiceRowsPivot_ListView_UserEnable" Then
            Dim _ListView As ListView = TryCast(View, ListView)

            If _ListView IsNot Nothing Then
                Dim _InvoiceRowsPivot As InvoiceRowsPivot
                Dim _Criteria As String = ""
                For Each _InvoiceRowsPivot In _ListView.CollectionSource.List
                    Dim _InvoiceRowsPivotUser As InvoiceRowsPivotUser
                    For Each _InvoiceRowsPivotUser In _InvoiceRowsPivot.InvoiceRowsPivotUser
                        If _InvoiceRowsPivotUser.User.Oid.ToString = _User.Oid.ToString Then
                            If _Criteria = "" Then
                                _Criteria = "Oid in ('" & _InvoiceRowsPivot.Oid.ToString & "'"
                            Else
                                _Criteria += ", '" & _InvoiceRowsPivot.Oid.ToString & "'"
                            End If
                            Exit For
                        End If
                    Next
                Next
                If _Criteria = "" Then
                    _Criteria = "1=2"
                Else
                    _Criteria += ")"
                End If
                _ListView.CollectionSource.BeginUpdateCriteria()
                _ListView.CollectionSource.Criteria("ByEnabled") = CriteriaOperator.Parse(_Criteria)
                _ListView.CollectionSource.EndUpdateCriteria()
            End If
        End If

        If View.Id = "InvoiceRowsPivot_ListView_UserCreated" Then
            Dim _ListView As ListView = TryCast(View, ListView)

            If _ListView IsNot Nothing Then
                _ListView.CollectionSource.BeginUpdateCriteria()
                _ListView.CollectionSource.Criteria("ByUser") = CriteriaOperator.Parse("UserCreated=? ", _User)
                _ListView.CollectionSource.EndUpdateCriteria()
            End If
        End If

        
    End Sub

    Private Sub aRecalculateBallanceInvoiceRows_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aRecalculateBallanceInvoiceRows.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _InvoiceRows As InvoiceRows
        Dim _InvoiceRowsPivot As InvoiceRowsPivot = TryCast(View.SelectedObjects(0), InvoiceRowsPivot)
        Dim _Rate As Double = 0
        Dim _SumBallanceHUF As Double = 0
        Dim _SumBallanceDEV As Double = 0
        Dim _SQL As String = ""

        '// Mielőtt bármi történne !!!!!

        _SQL = "UPDATE InvoiceRows SET SumGrossMarginHUF=SumPriceHUF,SumGrossMarginDEV=SumPriceDEV  WHERE OrderInRowsOther Is Not NULL"

        Select Case GLOBAL_SQLType
            Case eSQLType.MSSQL
                _SQL = "UPDATE InvoiceRows SET SumGrossMarginHUF=SumPriceHUF,SumGrossMarginDEV=SumPriceDEV  WHERE OrderInRowsOther Is Not NULL"
                _uow.ExecuteNonQuery(_SQL)

                _SQL = " UPDATE InvoiceRows t1 JOIN InvoiceHeader t2 ON  t1.InvoiceHeader = t2.Oid "
                _SQL += " SET t1.SumAveragePriceDEV=t1.SumAveragePriceHUF/t2.CurrencyRate,"
                _SQL += " t1.SumGrossMarginDEV = t1.SumGrossMarginHUF / t2.CurrencyRate"
                _SQL += " WHERE t2.CurrencyRate > 0"
                _uow.ExecuteNonQuery(_SQL)
            Case eSQLType.MySQL
                _SQL = "UPDATE InvoiceRows SET SumGrossMarginHUF=SumPriceHUF,SumGrossMarginDEV=SumPriceDEV  WHERE OrderInRowsOther Is Not NULL"
                _uow.ExecuteNonQuery(_SQL)

                _SQL = " UPDATE InvoiceRows t1 JOIN InvoiceHeader t2 ON  t1.InvoiceHeader = t2.Oid "
                _SQL += " SET t1.SumAveragePriceDEV=t1.SumAveragePriceHUF/t2.CurrencyRate,"
                _SQL += " t1.SumGrossMarginDEV = t1.SumGrossMarginHUF / t2.CurrencyRate"
                _SQL += " WHERE t2.CurrencyRate > 0"
                _uow.ExecuteNonQuery(_SQL)

            Case eSQLType.PostgreSQL
                _SQL = "UPDATE ""InvoiceRows"" SET ""SumGrossMarginHUF""=""SumPriceHUF"",""SumGrossMarginDEV""=""SumPriceDEV""  WHERE ""OrderInRowsOther"" Is Not NULL"
                _uow.ExecuteNonQuery(_SQL)

                _SQL = " UPDATE ""InvoiceRows"" t1 JOIN ""InvoiceHeader"" t2 ON  ""t1"".""InvoiceHeader"" = ""t2"".""Oid"" "
                _SQL += " SET ""t1"".""SumAveragePriceDEV""=""t1"".""SumAveragePriceHUF""/""t2"".""CurrencyRate"","
                _SQL += " ""t1"".""SumGrossMarginDEV"" = ""t1"".""SumGrossMarginHUF"" / ""t2"".""CurrencyRate"""
                _SQL += " WHERE ""t2"".""CurrencyRate"" > 0"
                _uow.ExecuteNonQuery(_SQL)
        End Select


        RaiseEvent InitWork(1, 1, _InvoiceRowsPivot.InvoiceRows_Table.Count)
        For Each _InvoiceRows In _InvoiceRowsPivot.InvoiceRows_Table
            RaiseEvent DoWork()
            _Rate = 0
            _SumBallanceHUF = 0
            _SumBallanceDEV = 0

            Dim cultures() As CultureInfo = {New CultureInfo("en-US"), _
                                       New CultureInfo("fr-FR"), _
                                       New CultureInfo("it-IT"), _
                                       New CultureInfo("de-DE")}

            Dim _PCIGroup As PCIGroup = _ocur.FindObject(Of PCIGroup)(CriteriaOperator.Parse("CustomersFrom=? and Customers=? and PartnerType=0 and ConnectInfo=?", _
                                                                                             _InvoiceRows.InvoiceHeader.CustomersFrom, _InvoiceRows.InvoiceHeader.Customers, _InvoiceRows.InvoiceHeader.ConnectInfo))
            If _PCIGroup IsNot Nothing Then
                If _PCIGroup.CurrencyName_Account.ShortName = "HUF" Then
                    If _PCIGroup.AmountHUF_Account <> 0 Then
                        _Rate = _PCIGroup.BallanceHUF / _PCIGroup.AmountHUF_Account
                    End If
                Else
                    If _PCIGroup.AmountDEV_Account <> 0 Then
                        _Rate = _PCIGroup.BallanceDEV / _PCIGroup.AmountDEV_Account
                    End If
                End If
                _SumBallanceHUF = Math.Round((_Rate) * _InvoiceRows.SumPriceHUF, 0, MidpointRounding.AwayFromZero)
                _SumBallanceDEV = Math.Round((_Rate) * _InvoiceRows.SumPriceDEV, 2, MidpointRounding.AwayFromZero)
                _SQL = ""
                Select Case GLOBAL_SQLType
                    Case eSQLType.MSSQL
                        _SQL = "update InvoiceRows set SumBallanceHUF=" & _SumBallanceHUF.ToString(New CultureInfo("en-US")) & ",SumBallanceDEV=" & _SumBallanceDEV.ToString(New CultureInfo("en-US"))
                        _SQL += " Where Oid='" & _InvoiceRows.Oid.ToString & "'"
                    Case eSQLType.MySQL
                        _SQL = "update InvoiceRows set SumBallanceHUF=" & _SumBallanceHUF.ToString(New CultureInfo("en-US")) & ",SumBallanceDEV=" & _SumBallanceDEV.ToString(New CultureInfo("en-US"))
                        _SQL += " Where Oid='" & _InvoiceRows.Oid.ToString & "'"
                    Case eSQLType.PostgreSQL
                        _SQL = "update ""InvoiceRows"" set ""SumBallanceHUF""=" & _SumBallanceHUF.ToString(New CultureInfo("en-US")) & ",""SumBallanceDEV""=" & _SumBallanceDEV.ToString(New CultureInfo("en-US"))
                        _SQL += " Where ""Oid""='" & _InvoiceRows.Oid.ToString & "'"
                End Select
                _uow.ExecuteNonQuery(_SQL)
            End If
        Next
        RaiseEvent FinalWork
        View.Refresh()
    End Sub

    Private Sub aSelectUsers_InvoiceRowsPivot_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aSelectUsers_InvoiceRowsPivot.CustomizePopupWindowParams
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _CS As New CollectionSource(_onew, GetType(User))

        e.View = Application.CreateListView("User_ListView_Find", _CS, False)
    End Sub

    Private Sub aSelectUsers_InvoiceRowsPivot_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aSelectUsers_InvoiceRowsPivot.Execute
        Dim _InvoiceRowsPivot As InvoiceRowsPivot = TryCast(TryCast(View, ListView).CollectionSource, PropertyCollectionSource).MasterObject

        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _uow As New UnitOfWork(_ocur.Session.DataLayer)
        Dim _User As User
        Dim _InvoiceRowsPivotUser As InvoiceRowsPivotUser

        If _InvoiceRowsPivot Is Nothing Then Exit Sub

        If e.PopupWindow.View.SelectedObjects.Count > 0 Then

            For Each _User In e.PopupWindow.View.SelectedObjects
                _InvoiceRowsPivotUser = New InvoiceRowsPivotUser(_uow)
                _InvoiceRowsPivotUser.InvoiceRowsPivot = _uow.GetObjectByKey(Of InvoiceRowsPivot)(_InvoiceRowsPivot.Oid)
                _InvoiceRowsPivotUser.User = _uow.GetObjectByKey(Of User)(_User.Oid)
            Next
            _uow.CommitChanges()
        End If

        Dim nestedFrame As NestedFrame = TryCast(Frame, NestedFrame)
        If nestedFrame IsNot Nothing Then
            Dim parentView As View = nestedFrame.View
            parentView.ObjectSpace.Refresh()
        End If
    End Sub
End Class
