using RFrameGenerate.BLL;
using RFrameGenerate.DAL.Enums;
using RFrameGenerate.Model;
using RFramework.SQLServer;
using RFramework.SQLServer.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace jiouosdptask.BLL
{
    public class Order
    {
        /// <summary>
        /// 买家下单后，超过过期时间而未付款，订单自动变为过期。过期订单，不能继续交易。 
        /// </summary>
        public static void orderCloseTime()
        {
            using (var tran = new SqlRTransaction())
            {
                var queryOrder = Factory.CreateT_BAS_Orders(tran);
                var query = Factory.CreateProcedure(tran);
                var query_sku = Factory.CreateT_BAS_ProductSKU(tran);
                GridModel gridModel = new GridModel() { page = 1, rows = 10000, };
                while (true)
                {
                    var orderList = queryOrder.GetPageList(gridModel, a => a.OrderState == DictionaryConst.OrderState.Unpaid, false, b => b.OrderTime, OrderMethods.ASC, LockType.Default, false);
                    orderList.ForEach(o =>
                    {
                        var param = ParameterManage.GetParameter(ParameterName.Order.AutoExpirationTime, o.MerchantGuid.Value);
                        if (param != null)
                        {
                            var minute = Convert.ToDouble(param.ParameterValue);
                            if (minute > 0)
                            {
                                if (o.OrderTime.AddMinutes(minute) < DateTime.Now)
                                {//超过过期时间而未付款,关闭
                                    queryOrder.Update(a => new object[] { a.OrderState == DictionaryConst.OrderState.BeCancel, a.OrderInnerState == DictionaryConst.OrderInnerState.BeCancel }, b => b.OrderGuid == o.OrderGuid, false);
                                    //自动关闭订单
                                    var listDetail = query.GetOrderDetails(o.OrderGuid);
                                    foreach (var v in listDetail)
                                    {
                                        var product = query.GetProduct(v.ProductGuid.Value);
                                        if (product.InventoryWay == DictionaryConst.InventoryWay.LessStockBySingle)
                                        {

                                            //无规格
                                            if (v.GroupGuid == null)
                                            {
                                                //付款减库存,未并发处理
                                                decimal inventory = product.Inventory + v.Quantity.Value;
                                                decimal saleVolume = product.SalesVolume - v.Quantity.Value;
                                                query.UpdateProduct(inventory, saleVolume, product.ProductGuid);
                                            }//有规格
                                            else
                                            {
                                                //付款减库存,未并发处理
                                                decimal inventory = product.Inventory + v.Quantity.Value;
                                                decimal saleVolume = product.SalesVolume - v.Quantity.Value;
                                                query.UpdateProduct(inventory, saleVolume, product.ProductGuid);

                                                var listSKU = query_sku.GetList(a => a.ProductGuid == product.ProductGuid && a.ProductSKUGroupGuid == v.GroupGuid);
                                                if (listSKU != null && listSKU.Count > 0)
                                                {
                                                    foreach (var item in listSKU)
                                                    {
                                                        item.Invenotory = item.Invenotory + v.Quantity;
                                                        item.EntityState = EntityStates.ToBeUpdated;
                                                    }
                                                    query_sku.UpdateList(listSKU);
                                                }
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    });

                    if (orderList.Count < gridModel.rows)
                    {
                        GC.Collect();
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 商家确认订单发货后，系统自动开始倒计时，达到指定的时间后，用户而未确认收货，系统会自动将订单标示为已收货。 
        /// </summary>
        public static void orderCompleteTime()
        {
            using (var tran = new SqlRTransaction())
            {
                var queryOrder = Factory.CreateT_BAS_Orders(tran);
                var queryDistOrder = Factory.CreateT_BAS_Distribute(tran);
                var queryOrderDetails = Factory.CreateT_BAS_OrderDetails(tran);
                GridModel gridModel = new GridModel() { page = 1, rows = 10000, };
                while (true)
                {
                    var orderList = queryOrder.GetPageList(gridModel, a => a.OrderState == DictionaryConst.OrderState.WaitReceipt, false, b => b.DeliveryTime, OrderMethods.ASC, LockType.Default, false);
                    orderList.ForEach(o =>
                    {
                        if (o.DeliveryTime != null)
                        {
                            var param = ParameterManage.GetParameter(ParameterName.Order.AutomaticWrite, o.MerchantGuid.Value);
                            var day = Convert.ToDouble(param.ParameterValue);
                            if (day > 0)
                            {
                                if (o.DeliveryTime.Value.AddDays(day) < DateTime.Now)
                                {
                                    var listDetails = queryOrderDetails.GetList(a => a.OrderGuid == o.OrderGuid);
                                    if (o.IsExtendReceiving == true)
                                    {//延长了收货
                                        if (o.DeliveryTime.Value.AddDays(day + o.ExtendDay.Value) < DateTime.Now)
                                        {
                                            queryOrder.Update(a => new object[] { a.OrderState == DictionaryConst.OrderState.Completed, a.OrderInnerState == DictionaryConst.OrderInnerState.Completed, a.CompletedTime == DateTime.Now }, b => b.OrderGuid == o.OrderGuid, false);
                                            queryDistOrder.Update(a => new object[] { a.CompletionDate == DateTime.Now }, b => b.OrderGuid == o.OrderGuid, false);
                                            if (listDetails != null && listDetails.Count > 0)
                                            {
                                                foreach (var item in listDetails)
                                                {
                                                    item.State = DictionaryConst.OrderDetailState.Null;
                                                    item.EntityState = EntityStates.ToBeUpdated;
                                                }
                                                queryOrderDetails.UpdateList(listDetails);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        queryOrder.Update(a => new object[] { a.OrderState == DictionaryConst.OrderState.Completed, a.OrderInnerState == DictionaryConst.OrderInnerState.Completed, a.CompletedTime == DateTime.Now }, b => b.OrderGuid == o.OrderGuid, false);
                                        queryDistOrder.Update(a => new object[] { a.CompletionDate == DateTime.Now }, b => b.OrderGuid == o.OrderGuid, false);
                                        if (listDetails != null && listDetails.Count > 0)
                                        {
                                            foreach (var item in listDetails)
                                            {
                                                item.State = DictionaryConst.OrderDetailState.Null;
                                                item.EntityState = EntityStates.ToBeUpdated;
                                            }
                                            queryOrderDetails.UpdateList(listDetails);
                                        }
                                    }
                                }
                            }
                        }
                    });

                    if (orderList.Count < gridModel.rows)
                    {
                        GC.Collect();
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 一元购订单
        /// </summary>
        public static void corwdCompleteTime()
        {
            using (var tran = new SqlRTransaction())
            {
                var queryOrder = Factory.CreateT_CR_CrowdParticipate(tran);
                GridModel gridModel = new GridModel() { page = 1, rows = 10000, };
                while (true)
                {
                    var orderList = queryOrder.GetPageList(gridModel, a => a.CrowdState == DictionaryConst.CrowdState.DaiShou, false, b => b.CrowdDate, OrderMethods.ASC, LockType.Default, false);
                    orderList.ForEach(o =>
                    {
                        if (o.CrowdDate != null)
                        {
                            var param = ParameterManage.GetParameter(ParameterName.Order.AutomaticWrite, o.MerchantGuid.Value);
                            var day = Convert.ToDouble(param.ParameterValue);
                            if (day > 0)
                            {
                                if (o.CrowdDate.AddDays(day) < DateTime.Now)
                                {
                                    queryOrder.Update(a => new object[] { a.CrowdState == DictionaryConst.CrowdState.Complete }, b => b.CrowdParticipateGuid == o.CrowdParticipateGuid);
                                }
                            }
                        }
                    });

                    if (orderList.Count < gridModel.rows)
                    {
                        GC.Collect();
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 自动结算
        /// </summary>
        public static Result certainTask()
        {
            return RFrameGenerate.BLL.DistributionManage.GetAmount();
        }
    }
}
