using System;
using System.Linq;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.ExpressApp.Utils;
using DevExpress.ExpressApp.Xpo;
using Nuvolar.Module.BusinessObjects.Popup;
using DevExpress.Xpo;
using DevExpress.Persistent.BaseImpl;
using System.Collections;
//using System.Windows.Forms;
namespace Nuvolar.Module.Controllers
{
    // For more typical usage scenarios, be sure to check out https://documentation.devexpress.com/eXpressAppFramework/clsDevExpressExpressAppViewControllertopic.aspx.
    public partial class OrderIn_VC : ViewController
    {
        public OrderIn_VC()
        {
            InitializeComponent();
            // Target required Views (via the TargetXXX properties) and create their Actions.
        }
        protected override void OnActivated()
        {
            base.OnActivated();
            // Perform various tasks depending on the target View.
        }
        protected override void OnViewControlsCreated()
        {
            base.OnViewControlsCreated();
            // Access and customize the target View control.
        }
        protected override void OnDeactivated()
        {
            // Unsubscribe from previously subscribed events and release other references and resources.
            base.OnDeactivated();
        }
        private void aMoveOrderIn_Execute(object sender, PopupWindowShowActionExecuteEventArgs e)
        {
            //XPObjectSpace _onew = (XPObjectSpace)Application.CreateObjectSpace();
            XPObjectSpace _onew = View.ObjectSpace as XPObjectSpace;
            OrderInMovePopup _OrderInMovePopup = (OrderInMovePopup)e.PopupWindow.View.SelectedObjects[0];
            Guid _GUID=Guid.Empty;
            if (_OrderInMovePopup.OrderInHeaderTo == null)
            {
                return;
            }

            foreach (StorageOutRowsInRows _StorageOutRowsInRows in _OrderInMovePopup.StorageOutRowsInRows)
            {
                if (_StorageOutRowsInRows.QTT_Will > 0 && _StorageOutRowsInRows.QTT_Will<=_StorageOutRowsInRows.QTT)
                {
                    if (_StorageOutRowsInRows.StorageOutRows.OrderInRows.DividedOriginal == 0)
                    {
                        _StorageOutRowsInRows.StorageOutRows.OrderInRows.DividedOriginal = 1;
                        _GUID = Guid.NewGuid();
                        _StorageOutRowsInRows.StorageOutRows.OrderInRows.DividedGUID = _GUID;
                    }
                    else
                    {
                        _GUID = _StorageOutRowsInRows.StorageOutRows.OrderInRows.DividedGUID;
                    }
                    _StorageOutRowsInRows.StorageOutRows.OrderInRows.QTT-= _StorageOutRowsInRows.QTT_Will;
                    _StorageOutRowsInRows.StorageOutRows.OrderInRows.QTT_DeliveryNoted-= _StorageOutRowsInRows.QTT_Will; 
                    _StorageOutRowsInRows.StorageOutRows.OrderInRows.QTT_Storaged-= _StorageOutRowsInRows.QTT_Will;
                    _StorageOutRowsInRows.QTT -= _StorageOutRowsInRows.QTT_Will;
                    _StorageOutRowsInRows.QTT_To_DeliveryOut -= _StorageOutRowsInRows.QTT_Will;

                    _StorageOutRowsInRows.DividedGUID = _GUID;
                    
                    if (_StorageOutRowsInRows.DividedOriginal==0) {_StorageOutRowsInRows.DividedOriginal = 1; _StorageOutRowsInRows.DividedGUID = _GUID; }
                    if (_StorageOutRowsInRows.StorageOutRows.DividedOriginal == 0) { _StorageOutRowsInRows.StorageOutRows.DividedOriginal = 1; _StorageOutRowsInRows.StorageOutRows.DividedGUID = _GUID; }
                    
                    OrderInRows _OrderInRows = _onew.GetObject(_StorageOutRowsInRows.StorageOutRows.OrderInRows);
                    OrderInRows _OrderInRowsNew = _onew.CreateObject<OrderInRows>();
                    _OrderInRowsNew.DividedOriginal = 2;
                    _OrderInRowsNew.DividedGUID = _GUID;
                    _OrderInRowsNew.APCSheetByProducts = _OrderInRows.APCSheetByProducts;
                    _OrderInRowsNew.Description = _OrderInRows.Description;
                    _OrderInRowsNew.DescriptionPrivate = _OrderInRows.DescriptionPrivate;
                    _OrderInRowsNew.DiscountPriceDEV = _OrderInRows.DiscountPriceDEV;
                    _OrderInRowsNew.DiscountPriceHUF = _OrderInRows.DiscountPriceHUF;
                    _OrderInRowsNew.ListPriceDEV = _OrderInRows.ListPriceDEV;
                    _OrderInRowsNew.ListPriceHUF = _OrderInRows.ListPriceHUF;
                    _OrderInRowsNew.ListPriceOriginalHUF = _OrderInRows.ListPriceOriginalHUF;
                    _OrderInRowsNew.OrderInHeader = _onew.GetObject(_OrderInMovePopup.OrderInHeaderTo);
                    _OrderInRowsNew.Products = _OrderInRows.Products;
                    _OrderInRowsNew.QTT = _StorageOutRowsInRows.QTT_Will;
                    _OrderInRowsNew.QTT_DeliveryNoted = _StorageOutRowsInRows.QTT_Will;
                    _OrderInRowsNew.QTT_Invoiced = 0;
                    _OrderInRowsNew.QTT_Process = 0;
                    _OrderInRowsNew.QTT_Storaged = _StorageOutRowsInRows.QTT_Will;
                    _OrderInRowsNew.QTT_To = 0;
                    _OrderInRowsNew.QualityOption = _OrderInRows.QualityOption;
                    _OrderInRowsNew.RowGroup1 = _OrderInRows.RowGroup1;
                    _OrderInRowsNew.RowGroup2 = _OrderInRows.RowGroup2;
                    _OrderInRowsNew.RowIndex = 0;
                    _OrderInRowsNew.VAT = _OrderInRows.VAT;

                    StorageOutRows _StorageOutRows = _onew.GetObject(_StorageOutRowsInRows.StorageOutRows);
                    StorageOutRows _StorageOutRowsNew = _onew.CreateObject<StorageOutRows>();
                    _StorageOutRowsNew.StorageOutHeader = _StorageOutRows.StorageOutHeader;
                    _StorageOutRowsNew.OrderInRows = _OrderInRowsNew;
                    _StorageOutRowsNew.Products = _StorageOutRows.Products;
                    _StorageOutRowsNew.QTT = _StorageOutRowsInRows.QTT_Will;
                    _StorageOutRowsNew.QTT_To_DeliveryOut = _StorageOutRowsInRows.QTT_Will;
                    _StorageOutRowsNew.QTT_Will = 0;
                    _StorageOutRowsNew.RowIndex = 0;
                    _StorageOutRowsNew.StorageComputed = _StorageOutRows.StorageComputed;
                    _StorageOutRowsNew.StorageOutHeader = _StorageOutRows.StorageOutHeader;
                    _StorageOutRowsNew.DividedGUID = _GUID;
                    _StorageOutRowsNew.DividedOriginal = 2;
                    
                    StorageOutRowsInRows _StorageOutRowsInRowsNew = _onew.CreateObject<StorageOutRowsInRows>();

                    _StorageOutRowsInRowsNew.StorageOutRows = _StorageOutRowsNew;
                    _StorageOutRowsInRowsNew.QTT = _StorageOutRowsInRows.QTT_Will;
                    _StorageOutRowsInRowsNew.QTT_To_DeliveryOut = _StorageOutRowsInRows.QTT_Will;
                    _StorageOutRowsInRowsNew.QTT_Will = 0;
                    _StorageOutRowsInRowsNew.RowIndex = 0;
                    _StorageOutRowsInRowsNew.StorageInRows = _onew.GetObject(_StorageOutRowsInRows.StorageInRows);
                    _StorageOutRowsInRowsNew.DividedGUID = _GUID;
                    _StorageOutRowsInRowsNew.DividedOriginal = 2;

                    DeliveryNoteOutRows _DeliveryNoteOutRows = _onew.FindObject<DeliveryNoteOutRows>(CriteriaOperator.Parse("StorageOutRowsInRows.Oid=?",_StorageOutRowsInRows.Oid));
                    if (_DeliveryNoteOutRows!=null)
                    {
                        if (_DeliveryNoteOutRows.DividedOriginal == 0) { _DeliveryNoteOutRows.DividedOriginal = 1; _DeliveryNoteOutRows.DividedGUID = _GUID; }
                        _DeliveryNoteOutRows.QTT -= _StorageOutRowsInRows.QTT_Will;

                        DeliveryNoteOutRows _DeliveryNoteOutRowsNew = _onew.CreateObject<DeliveryNoteOutRows>();

                        _DeliveryNoteOutRowsNew.DeliveryNoteOutHeader = _onew.GetObject(_DeliveryNoteOutRows.DeliveryNoteOutHeader);
                        _DeliveryNoteOutRowsNew.Note = "";
                        _DeliveryNoteOutRowsNew.QTT = _StorageOutRowsInRows.QTT_Will;
                        _DeliveryNoteOutRowsNew.QTT_Invoiced = 0;
                        _DeliveryNoteOutRowsNew.QTT_Will = 0;
                        _DeliveryNoteOutRowsNew.RowIndex = 0;
                        _DeliveryNoteOutRowsNew.StorageOutRowsInRows = _StorageOutRowsInRowsNew;
                        _DeliveryNoteOutRowsNew.DividedGUID = _GUID;
                        _DeliveryNoteOutRowsNew.DividedOriginal = 2;
                    }
                    _onew.CommitChanges();
                }
            }
            //Frame.GetController<RefreshController>().RefreshAction.DoExecute();
            //View.Refresh();
        }
        private void aMoveOrderIn_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            XPObjectSpace _ocur = (XPObjectSpace)View.ObjectSpace;
            XPObjectSpace _onew = (XPObjectSpace)Application.CreateObjectSpace();
            OrderInHeader _OrderInHeader = (OrderInHeader)View.SelectedObjects[0];
            OrderInMovePopup _OrderInMovePopup = _onew.CreateObject<OrderInMovePopup>();

            _onew.Session.ExecuteNonQuery("UPDATE StorageOutRowsInRows set DividedOriginal=0 WHERE DividedOriginal IS NULL");
            _OrderInMovePopup.OrderInHeader = _onew.GetObject<OrderInHeader>(_OrderInHeader);
            e.View = Application.CreateDetailView(_onew, "OrderInMovePopup_DetailView", true, _OrderInMovePopup);
        }
        private void aOrderInStorageOut_Execute(object sender, PopupWindowShowActionExecuteEventArgs e)
        {
            XPObjectSpace _onew = (XPObjectSpace)Application.CreateObjectSpace();
            UnitOfWork _uow_lock = new UnitOfWork(_onew.Session.DataLayer);
            User _User = _onew.GetObject(SecuritySystem.CurrentUser as User);
            StorageComputed _StorageComputed;
           
            try
            {
                //--==Ellenőrzések==--
                //____________________________________________________________________________________________________________________
                OrderInHeader _OrderInHeader = _onew.GetObjectByKey<OrderInHeader>((View.SelectedObjects[0] as OrderInHeader).Oid);
                StorageSelectPopup _StorageSelectPopup = _onew.GetObject(e.PopupWindow.View.SelectedObjects[0] as StorageSelectPopup);
                if (_OrderInHeader.OrderInRows.Count <= 0)
                {
                    throw new Exception(string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions\\OrderInRows", "NoRowsInOrder"), 
                        string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions", "MsgBoxCheckItAgain"))));
                }
                ArrayList _OrderInRows_Collection = new ArrayList();

                foreach (OrderInRows _OrderInRows in _OrderInHeader.OrderInRows)
                {

                    if (_OrderInRows.QTT_Process > 0)
                    {
                        if (_OrderInRows.QTT_Process + _OrderInRows.QTT_Storaged + _OrderInRows.QTT_Storaged_Will > _OrderInRows.QTT)
                        {
                            //// Ha meghaladja a kitárolás a rendelteket
                            throw new Exception(string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions\\OrderInRows", "TooMutchQuantityInOrderIn"), 
                                _OrderInRows.RowIndex.ToString() + string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions", "MsgBoxCheckItAgain"))));
                        }
                        if (_OrderInRows.QTT_Process + _OrderInRows.QTT_DeliveryNoted > _OrderInRows.QTT)
                        {
                            //// Ha meghaladja a kiszállítás a rendelteket
                            throw new Exception(string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions\\OrderInRows", "TooMutchQuantityInOrderIn"), 
                                _OrderInRows.RowIndex.ToString() + string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions", "MsgBoxCheckItAgain"))));
                        }
                        //// Szabad készlet ellenőrzése
                        _StorageComputed = _onew.FindObject<StorageComputed>(CriteriaOperator.Parse("Storage.Oid=? AND Products.Oid=?", _StorageSelectPopup.Storage.Oid, 
                            _OrderInRows.Products.Oid));
                        if (_StorageComputed == null)
                        {
                            throw new Exception(string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions\\StorageComputed", "NoProductsInStorage"), 
                                _OrderInRows.RowIndex, _OrderInRows.Products.ShortName, _StorageSelectPopup.Storage.ShortName) + "\n" + 
                                string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions", "MsgBoxCheckItAgain")));
                        }
                        if ((_StorageComputed.QTTFree < _OrderInRows.QTT_Process))
                        {
                            throw new Exception(string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions\\StorageComputed", "NoProductsInStorage"), 
                                _OrderInRows.RowIndex, _OrderInRows.Products.ShortName, _StorageSelectPopup.Storage.ShortName) + "\n" + 
                                string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions", "MsgBoxCheckItAgain")));
                        }
                        if (_StorageComputed != null)
                        {
                            //// Mimimum ár ellenőrzés
                            if ((Application.Model.Options as IModelOptionsExtender).RequreMinimumPriceCheck)
                            {
                                if (_StorageComputed.MimumumPriceOutHUF < _OrderInRows.FinalPriceHUF)
                                {
                                    throw new Exception(string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions\\StorageComputed", "BadMinimumPrice"), 
                                        _OrderInRows.RowIndex, _OrderInRows.Products.ShortName, _StorageComputed.MimumumPriceOutHUF, _OrderInRows.FinalPriceHUF) + "\n" + 
                                        string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions", "MsgBoxCheckItAgain")));
                                }
                            }
                        }

                        _OrderInRows_Collection.Add(_onew.GetObjectByKey<OrderInRows>(_OrderInRows.Oid));
                    }
                }

                if (_OrderInRows_Collection.Count == 0)
                    throw new Exception(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions\\OrderInRows", "NoSelectionforStorageOutandDeliveryNoteOut") + "\n" + 
                        string.Format(CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions", "MsgBoxCheckItAgain")));

                //--==Zárolás==--
                //____________________________________________________________________________________________________________________
                if (!LockingModule.LockObject(_uow_lock, typeof(StorageComputed), "-", _User))
                {
                    LockingObject _LockingObject = _onew.FindObject<LockingObject>(CriteriaOperator.Parse("TableName=?", typeof(StorageComputed).Name + "-" + "-"));

                    string _Prompt = DevExpress.ExpressApp.Utils.CaptionHelper.GetLocalizedText("Exceptions\\NuvolarExceptions\\StorageComputed", "CanNotStorageInByLocking");
                    throw new Exception(string.Format(_Prompt, _LockingObject.User.FullName, _LockingObject.ObjectCreated));
                    
                    return;
                }
                else
                {
                    //--==Kitárolás==--
                    //____________________________________________________________________________________________________________________
                    StorageOutHeader _StorageOutHeader = new StorageOutHeader(_onew.Session);

                    _StorageOutHeader.Active = true;
                    _StorageOutHeader.CustomersFrom = _onew.GetObjectByKey<CustomersFrom>(_OrderInHeader.CustomersFrom.Oid);
                    _StorageOutHeader.Customers = _onew.GetObjectByKey<Customers>(_OrderInHeader.Customers.Oid);
                    _StorageOutHeader.StorageMoveType = _onew.GetObjectByKey<StorageMoveType>(_StorageSelectPopup.StorageMoveType.Oid);
                    _StorageOutHeader.Storage = _onew.GetObjectByKey<Storage>(_StorageSelectPopup.Storage.Oid);

                    foreach (OrderInRows _OrderInRows in _OrderInRows_Collection)
                    {
                        double _QTT_Mod = 0;
                        double _QTT_Free = 0;
                        double _QTT_ReservedOut = 0;
                        double _QTT_Will_Out = 0;

                        StorageOutRows _StorageOutRows = new StorageOutRows(_onew.Session);
                        _StorageOutRows.StorageOutHeader = _StorageOutHeader;
                        _StorageOutRows.Products = _onew.GetObjectByKey<Products>(_OrderInRows.Products.Oid);
                        _StorageOutRows.OrderInRows = _onew.GetObjectByKey<OrderInRows>(_OrderInRows.Oid);
                        XPCollection<StorageInRows> _StorageInRows_Collection = new XPCollection<StorageInRows>(PersistentCriteriaEvaluationBehavior.InTransaction, 
                            _onew.Session, CriteriaOperator.Parse("StorageInHeader.Storage=? and StorageInHeader.IsEditable=False and StorageInHeader.IsStorno=False and Products=?", 
                            _StorageOutHeader.Storage, _onew.GetObjectByKey<Products>(_OrderInRows.Products.Oid)));
                        _StorageInRows_Collection.Sorting.Add(new SortProperty("StorageInHeader.CreateDate", DevExpress.Xpo.DB.SortingDirection.Ascending));

                        _QTT_Mod = _OrderInRows.QTT_Process;
                        foreach (StorageInRows _StorageInRows in _StorageInRows_Collection)
                        {
                            _QTT_Free = _StorageInRows.QTT - _StorageInRows.QTT_Out - _StorageInRows.QTT_Out_Will;
                            if (_QTT_Free > 0)
                            {
                                if (_QTT_Free < _QTT_Mod)
                                {
                                    _StorageInRows.QTT_Out_Will += _QTT_Free;
                                    _StorageOutRows.QTT_Will += _QTT_Free;
                                    _QTT_Mod -= _QTT_Free;
                                    //------- FIFO sor beszúrása
                                    StorageOutRowsInRows _StorageOutRowsInRows = _onew.FindObject<StorageOutRowsInRows>(CriteriaOperator.Parse("StorageInRows=? and StorageOutRows=?", _StorageInRows, _StorageOutRows), true);
                                    if (_StorageOutRowsInRows != null)
                                    {
                                        _StorageOutRowsInRows.QTT += _QTT_Free;
                                    }
                                    else
                                    {
                                        _StorageOutRowsInRows = new StorageOutRowsInRows(_onew.Session);
                                        _StorageOutRowsInRows.StorageInRows = _StorageInRows;
                                        _StorageOutRowsInRows.StorageOutRows = _StorageOutRows;
                                        _StorageOutRowsInRows.QTT = _QTT_Free;
                                    }

                                }
                                else
                                {
                                    _StorageInRows.QTT_Out_Will += _QTT_Mod;
                                    _StorageOutRows.QTT_Will += _QTT_Mod;
                                    //------- FIFO sor beszúrása
                                    StorageOutRowsInRows _StorageOutRowsInRows = _onew.FindObject<StorageOutRowsInRows>(CriteriaOperator.Parse("StorageInRows=? and StorageOutRows=?", _StorageInRows, _StorageOutRows), true);
                                    if (_StorageOutRowsInRows != null)
                                    {
                                        _StorageOutRowsInRows.QTT += _QTT_Mod;
                                    }
                                    else
                                    {
                                        _StorageOutRowsInRows = new StorageOutRowsInRows(_onew.Session);
                                        _StorageOutRowsInRows.StorageInRows = _StorageInRows;
                                        _StorageOutRowsInRows.StorageOutRows = _StorageOutRows;
                                        _StorageOutRowsInRows.QTT = _QTT_Mod;
                                    }

                                    break; // TODO: might not be correct. Was : Exit For
                                }
                            }
                        }

                        _StorageOutRows.RowIndex = _StorageOutHeader.StorageOutRows.Count;

                        _StorageComputed = _onew.FindObject<StorageComputed>(CriteriaOperator.Parse("Storage=? and Products=?", _StorageOutHeader.Storage, 
                            _onew.GetObjectByKey<Products>(_OrderInRows.Products.Oid)), true);
                        _QTT_ReservedOut = _StorageComputed.QTTReservedOut;
                        XPCollection<StorageOutRows> _StorageOutRows_Collection_R = new XPCollection<StorageOutRows>(PersistentCriteriaEvaluationBehavior.InTransaction, 
                            _onew.Session, CriteriaOperator.Parse("QTT_Will>0 and StorageOutHeader.Storage=? and Products=?", _StorageOutHeader.Storage, 
                            _onew.GetObjectByKey<Products>(_OrderInRows.Products.Oid)));
                        foreach (StorageOutRows _StorageOutRows_R in _StorageOutRows_Collection_R)
                        {
                            _QTT_Will_Out += _StorageOutRows_R.QTT_Will;
                        }

                        _StorageComputed.QTTFree = _StorageComputed.QTTFree - (_QTT_Will_Out - _QTT_ReservedOut);
                        _StorageComputed.QTTReservedOut = _QTT_Will_Out;
                    }

                    //--Kitárolás véglegesítése--
                    //____________________________________________________________________________________________________________________

                    foreach (StorageOutRows _StorageOutRows in _StorageOutHeader.StorageOutRows)
                    {
                        XPCollection<StorageOutRowsInRows> _StorageOutRowsInRows_Collection = new XPCollection<StorageOutRowsInRows>(PersistentCriteriaEvaluationBehavior.InTransaction, _onew.Session, CriteriaOperator.Parse("StorageOutRows=?", _StorageOutRows));

                        foreach (StorageOutRowsInRows _StorageOutRowsInRows in _StorageOutRowsInRows_Collection)
                        {
                            if (_StorageOutRowsInRows.QTT > 0)
                            {
                                XPCollection<StorageMoveEvents> _StorageMoveEvents_Collection = new XPCollection<StorageMoveEvents>(PersistentCriteriaEvaluationBehavior.InTransaction, _onew.Session, CriteriaOperator.Parse("StorageInRows=?", _StorageOutRowsInRows.StorageInRows));
                                _StorageMoveEvents_Collection.Sorting.Add(new SortProperty("ObjectCreated", DevExpress.Xpo.DB.SortingDirection.Descending));

                                _StorageOutRowsInRows.StorageInRows.QTT_Out += _StorageOutRowsInRows.QTT;
                                _StorageOutRowsInRows.StorageInRows.QTT_Out_Will -= _StorageOutRowsInRows.QTT;

                                StorageMoveEvents _StorageMoveEvents = new StorageMoveEvents(_onew.Session);
                                _StorageMoveEvents.StorageInRows = _StorageOutRowsInRows.StorageInRows;
                                _StorageMoveEvents.StorageOutRows = _StorageOutRowsInRows.StorageOutRows;
                                if (_StorageMoveEvents_Collection.Count > 0)
                                {
                                    _StorageMoveEvents.QTT_Free_Before = _StorageMoveEvents_Collection[0].QTT_Free_After;
                                }
                                else
                                {
                                    _StorageMoveEvents.QTT_Free_Before = 0;
                                }
                                _StorageMoveEvents.QTT = (-1) * _StorageOutRowsInRows.QTT;
                                _StorageMoveEvents.QTT_Free_After = _StorageMoveEvents.QTT_Free_Before + _StorageMoveEvents.QTT;
                                _StorageMoveEvents.MoveEventsType = eMoveEventsType.StorageOutFinal;
                                _StorageMoveEvents.ExecutionDate = _StorageOutRowsInRows.StorageOutRows.StorageOutHeader.CreateDate;
                            }
                        }

                        _StorageOutRows.QTT += _StorageOutRows.QTT_Will;

                        if (_StorageOutRows.OrderInRows != null)
                        {
                            double _QTT_WillOrug = _StorageOutRows.QTT_Will;
                            OrderInRows _OrderInRows = _onew.GetObjectByKey<OrderInRows>(_StorageOutRows.OrderInRows.Oid);
                            _OrderInRows.QTT_Storaged += _StorageOutRows.QTT_Will;
                            _OrderInRows.QTT_Process = 0;
                        }
                        _StorageComputed = _onew.FindObject<StorageComputed>(CriteriaOperator.Parse("Products=? and Storage=?", _StorageOutRows.Products, _StorageOutRows.StorageOutHeader.Storage), true);
                        _StorageComputed.QTTReservedOut -= _StorageOutRows.QTT_Will;
                        _StorageOutRows.QTT_Will = 0;
                    }

                    _StorageOutHeader.IsEditable = false;
                    _StorageOutHeader.IsFinalized = true;
                    
                    _onew.CommitChanges();
                    Frame.GetController<RefreshController>().RefreshAction.DoExecute();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                LockingModule.UnLockObject(_uow_lock, typeof(StorageComputed), "-", _User);
            }
        }
        private void aOrderInStorageOut_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            XPObjectSpace _onew = (XPObjectSpace)Application.CreateObjectSpace();
            OrderInHeader _OrderInHeader = View.SelectedObjects[0] as OrderInHeader;
            StorageSelectPopup _StorageSelectPopup = _onew.CreateObject<StorageSelectPopup>();
                        
            e.View = Application.CreateDetailView(_onew, "StorageSelectPopup_DetailView", false, _StorageSelectPopup);
        }

        private void aMoveOrderInBack_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            XPObjectSpace _onew = (XPObjectSpace)Application.CreateObjectSpace();
            OrderInRows _OrderInRows = View.SelectedObjects[0] as OrderInRows;
            UnitOfWork _uow = new UnitOfWork(_onew.Session.DataLayer);
            if (_OrderInRows!=null && _OrderInRows.DividedOriginal==1)
            {
                Guid _GUID = _OrderInRows.DividedGUID;
                double _QTT = _OrderInRows.QTT;
                string _SQL = "";
                // s.ExecuteNonQuery("UPDATE Products SET ProductName='a_'+ProductName WHERE UnitPrice>@price AND ProductName LIKE 'A%'", new string[] { "@price" }, new object[] { 10 });
                // StorageOutRowsInRows

                try
                {
                    string[] _stringparam = null;
                    object[] _objectparam = null;

                    _uow.ExplicitBeginTransaction();

                    XPQuery<StorageOutRowsInRows> _StorageOutRowsInRows_Q = new XPQuery<StorageOutRowsInRows>(_uow, true);
                    var query = from q in _StorageOutRowsInRows_Q
                                where q.DividedGUID == _GUID
                                group q by q.StorageInRows into g
                                select new { a = g.Key.Oid, s = g.Sum(x => x.QTT) };
                    foreach (var item in query)
                    {
                        _SQL = "UPDATE StorageOutRowsInRows set QTT=@QTT,QTT_To_DeliveryOut=@QTT WHERE StorageInRows=@StorageInRows AND DividedGUID=@DividedGUID AND DividedOriginal=1";
                        _stringparam = new string[] { "@QTT", "@StorageInRows", "@DividedGUID" };
                        _objectparam = new object[] { item.s, item.a, _GUID };
                        _uow.ExecuteNonQuery(_SQL, _stringparam, _objectparam);
                    }

                    XPQuery<StorageOutRows> _StorageOutRows_Q = new XPQuery<StorageOutRows>(_uow, true);
                    var query2 = from q in _StorageOutRows_Q
                                 where q.DividedGUID == _GUID
                                 group q by q.DividedGUID into g
                                 select new { a = g.Key, s = g.Sum(x => x.QTT) };
                    foreach (var item in query2)
                    {
                        _SQL = "UPDATE StorageOutRows set QTT=@QTT WHERE DividedGUID=@DividedGUID AND DividedOriginal=1";
                        _stringparam = new string[] { "@QTT", "@DividedGUID" };
                        _objectparam = new object[] { item.s, _GUID };
                        _uow.ExecuteNonQuery(_SQL, _stringparam, _objectparam);
                    }

                    XPQuery<StorageOutRowsInRows> _StorageOutRowsInRows_QD = new XPQuery<StorageOutRowsInRows>(_uow, true);
                    var query3 = from q in _StorageOutRowsInRows_QD
                                 where q.DividedGUID == _GUID && q.DividedOriginal == 1
                                 group q by q.Oid into g
                                 select new { a = g.Key, s = g.Sum(x => x.QTT) };
                    foreach (var item in query3)
                    {
                        _SQL = "UPDATE DeliveryNoteOutRows set QTT=@QTT WHERE StorageOutRowsInRows=@StorageOutRowsInRows AND DividedGUID=@DividedGUID AND DividedOriginal=1";
                        _stringparam = new string[] { "@QTT", "@StorageOutRowsInRows", "@DividedGUID" };
                        _objectparam = new object[] { item.s, item.a, _GUID };
                        _uow.ExecuteNonQuery(_SQL, _stringparam, _objectparam);
                    }
                    XPQuery<OrderInRows> _OrderInRows_Q = new XPQuery<OrderInRows>(_uow, true);
                    var query4 = from q in _OrderInRows_Q
                                 where q.DividedGUID == _GUID
                                 group q by q.DividedGUID into g
                                 select new { a = g.Key, s = g.Sum(x => x.QTT) };
                    foreach (var item in query4)
                    {
                        _SQL = "UPDATE OrderInRows set QTT=@QTT,QTT_DeliveryNoted=@QTT,QTT_Storaged=@QTT WHERE DividedGUID=@DividedGUID AND DividedOriginal=1";
                        _stringparam = new string[] { "@QTT", "@DividedGUID" };
                        _objectparam = new object[] { item.s, _GUID };
                        _uow.ExecuteNonQuery(_SQL, _stringparam, _objectparam);
                    }
                    // -------========= Törlések ==========-------------
                    _SQL = "DELETE FROM DeliveryNoteOutRows WHERE DividedGUID=@DividedGUID AND DividedOriginal=2";
                    _stringparam = new string[] { "@DividedGUID" };
                    _objectparam = new object[] { _GUID };
                    _uow.ExecuteNonQuery(_SQL, _stringparam, _objectparam);

                    _SQL = "DELETE FROM StorageOutRowsInRows WHERE DividedGUID=@DividedGUID AND DividedOriginal=2";
                    _stringparam = new string[] { "@DividedGUID" };
                    _objectparam = new object[] { _GUID };
                    _uow.ExecuteNonQuery(_SQL, _stringparam, _objectparam);

                    _SQL = "DELETE FROM StorageOutRows WHERE DividedGUID=@DividedGUID AND DividedOriginal=2";
                    _stringparam = new string[] { "@DividedGUID" };
                    _objectparam = new object[] { _GUID };
                    _uow.ExecuteNonQuery(_SQL, _stringparam, _objectparam);

                    _SQL = "DELETE FROM OrderInRows WHERE DividedGUID=@DividedGUID AND DividedOriginal=2";
                    _stringparam = new string[] { "@DividedGUID" };
                    _objectparam = new object[] { _GUID };
                    _uow.ExecuteNonQuery(_SQL, _stringparam, _objectparam);

                    _uow.ExplicitCommitTransaction();

                }
                catch (Exception _Exception)
                {
                    _uow.ExplicitRollbackTransaction();
                    throw _Exception;
                }
                finally
                {
                    _uow.ExplicitRollbackTransaction();
                }
            }
            NestedFrame nestedFrame = Frame as NestedFrame;
            if (nestedFrame != null)
            {
                View parentView = nestedFrame.View as View;
                if (parentView != null)
                    parentView.ObjectSpace.Refresh();
            }
        }

        private void aDeliveryNoteOutPrint_Divided_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            XPObjectSpace _ocur = View.ObjectSpace as XPObjectSpace;
            DeliveryNoteOutRows _DeliveryNoteOutRows = View.SelectedObjects[0] as DeliveryNoteOutRows;

            if (_DeliveryNoteOutRows !=null)
            {
                XAFPrintHelper _XAFPrintHelper = new XAFPrintHelper(_ocur, Frame, _DeliveryNoteOutRows.DeliveryNoteOutHeader.DeliveryNoteOutType.ReportDataV2, CriteriaOperator.Parse("Oid=?",_DeliveryNoteOutRows.Oid));
                _XAFPrintHelper.ShowPreviewV2();
            }


        }
    }
}
