username@email.com
2024-09-09 cc170291673472d3cda8d7ea77f6bd3a3b5dbb83
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/***********************************************************************
 *            Project: baifenBinfa
 *        ProjectName: 百分兵法管理系统                               
 *                Web: http://chuanyin.com                     
 *             Author:                                        
 *              Email:                               
 *         CreateTime: 202403/02   
 *        Description: 暂无
 ***********************************************************************/
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Utility.Helper;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
 
namespace CoreCms.Net.Services
{
    /// <summary>
    ///     代理商订单记录表 接口实现
    /// </summary>
    public class CoreCmsAgentOrderServices : BaseServices<CoreCmsAgentOrder>, ICoreCmsAgentOrderServices
    {
        private readonly ICoreCmsAgentGoodsServices _agentGoodsServices;
        private readonly ICoreCmsAgentProductsServices _agentProductsServices;
        private readonly ICoreCmsUserBalanceServices _balanceServices;
        private readonly ICoreCmsAgentOrderRepository _dal;
        private readonly ICoreCmsGoodsServices _goodsServices;
        private readonly ICoreCmsOrderItemServices _orderItemServices;
        private readonly ICoreCmsOrderServices _orderServices;
        private readonly ICoreCmsProductsServices _productsServices;
        private readonly ICoreCmsAgentOrderDetailsServices _agentOrderDetailsServices;
 
 
        private readonly IServiceProvider _serviceProvider;
        private readonly ICoreCmsSettingServices _settingServices;
        private readonly IUnitOfWork _unitOfWork;
 
        private readonly ICoreCmsUserServices _userServices;
 
 
        public CoreCmsAgentOrderServices(IUnitOfWork unitOfWork, ICoreCmsAgentOrderRepository dal,
            ICoreCmsUserServices userServices, ICoreCmsOrderItemServices orderItemServices,
            ICoreCmsProductsServices productsServices, ICoreCmsGoodsServices goodsServices,
            ICoreCmsAgentProductsServices agentProductsServices, ICoreCmsSettingServices settingServices,
            ICoreCmsAgentGoodsServices agentGoodsServices, IServiceProvider serviceProvider,
            ICoreCmsOrderServices orderServices, ICoreCmsUserBalanceServices balanceServices, ICoreCmsAgentOrderDetailsServices agentOrderDetailsServices)
        {
            _dal = dal;
            BaseDal = dal;
            _unitOfWork = unitOfWork;
            _userServices = userServices;
            _orderItemServices = orderItemServices;
            _productsServices = productsServices;
            _goodsServices = goodsServices;
            _agentProductsServices = agentProductsServices;
            _settingServices = settingServices;
            _agentGoodsServices = agentGoodsServices;
            _serviceProvider = serviceProvider;
            _orderServices = orderServices;
            _balanceServices = balanceServices;
            _agentOrderDetailsServices = agentOrderDetailsServices;
        }
 
        #region 重写根据条件查询分页数据
 
        /// <summary>
        ///     重写根据条件查询分页数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <param name="blUseNoLock">是否使用WITH(NOLOCK)</param>
        /// <returns></returns>
        public async Task<IPageList<CoreCmsAgentOrder>> QueryPageAsync(
            Expression<Func<CoreCmsAgentOrder, bool>> predicate,
            Expression<Func<CoreCmsAgentOrder, object>> orderByExpression, OrderByType orderByType, int pageIndex = 1,
            int pageSize = 20, bool blUseNoLock = false)
        {
            return await _dal.QueryPageAsync(predicate, orderByExpression, orderByType, pageIndex, pageSize,
                blUseNoLock);
        }
 
        #endregion
 
        #region 添加代理订单关联记录
 
        /// <summary>
        ///     添加代理订单关联记录
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task<WebApiCallBack> AddData(CoreCmsOrder order)
        {
            var jm = new WebApiCallBack();
 
            using var container = _serviceProvider.CreateScope();
 
            var agentServices = container.ServiceProvider.GetService<ICoreCmsAgentServices>();
 
 
            var allConfigs = await _settingServices.GetConfigDictionaries();
            var isAllowProcurementService = CommonHelper
                .GetConfigDictionary(allConfigs, SystemSettingConstVars.IsAllowProcurementService).ObjectToInt(0);
            CoreCmsUser user = null;
            CoreCmsAgent agentModel = null;
            //判断是否支持代理代购,支持的话就直接判断当前订单用户是否是代理商,是的话传代理商数据
            if (isAllowProcurementService == 1)
            {
                agentModel = await agentServices.QueryByClauseAsync(p =>
                    p.userId == order.userId && p.verifyStatus == (int)GlobalEnumVars.AgentVerifyStatus.VerifyYes);
                if (agentModel != null) user = await _userServices.QueryByClauseAsync(p => p.id == order.userId);
            }
 
            //如果当前用户不是代理,则找上级
            if (user == null)
            {
                var userChild = await _userServices.QueryByClauseAsync(p => p.id == order.userId);
                if (userChild.parentId > 0)
                {
                    agentModel = await agentServices.QueryByClauseAsync(p =>
                        p.userId == userChild.parentId &&
                        p.verifyStatus == (int)GlobalEnumVars.AgentVerifyStatus.VerifyYes);
                    if (agentModel != null)
                        user = await _userServices.QueryByClauseAsync(p => p.id == userChild.parentId);
                }
            }
 
            //查询获取几级返利
 
            if (user != null)
            {
                //获取购物明细
                var orderItems = await _orderItemServices.QueryListByClauseAsync(p => p.orderId == order.orderId);
                var goodIds = orderItems.Select(p => p.goodsId).ToList();
                var productIds = orderItems.Select(p => p.productId).ToList();
                //获取商品数据
                var goods = await _goodsServices.QueryListByClauseAsync(p => goodIds.Contains(p.id));
                //获取货品数据
                var products = await _productsServices.QueryListByClauseAsync(p => productIds.Contains(p.id));
                //获取当前订单包含的商品在代理商货品池启用商品数据
                var agentGoods =
                    await _agentGoodsServices.QueryListByClauseAsync(p => goodIds.Contains(p.goodId) && p.isEnable);
                //获取货品关联的分销数据
                var agentProducts = await _agentProductsServices.QueryListByClauseAsync(p =>
                    productIds.Contains(p.productId) && p.agentGradeId == agentModel.gradeId);
 
                if (agentGoods.Any() && agentProducts.Any())
                    await AddOther(order, orderItems, goods, products, agentGoods, agentProducts, agentModel, user);
                else
                    jm.msg = "代理商商品池或货品池为空";
                jm.status = true;
            }
            else
            {
                jm.status = false;
            }
 
            return jm;
        }
 
        #endregion
 
        #region 订单结算处理事件
 
        /// <summary>
        ///     订单结算处理事件
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public async Task<WebApiCallBack> FinishOrder(string orderId)
        {
            var jm = new WebApiCallBack();
 
            var order = await _orderServices.QueryByClauseAsync(p =>
                p.orderId == orderId && p.status == (int)GlobalEnumVars.OrderStatus.Complete);
            if (order == null)
            {
                jm.msg = "订单查询失败";
                return jm;
            }
 
            //更新
            var list = await _dal.QueryListByClauseAsync(p =>
                p.orderId == orderId && p.isSettlement == (int)GlobalEnumVars.AgentOrderSettlementStatus.SettlementNo);
            if (list != null && list.Any())
            {
                foreach (var item in list)
                {
                    //钱挪到会员余额里面
                    var result = await _balanceServices.Change(item.userId,
                        (int)GlobalEnumVars.UserBalanceSourceTypes.Agent,
                        item.amount, item.orderId);
                    if (!result.status)
                    {
                    }
                }
 
                await _dal.UpdateAsync(
                    p => new CoreCmsAgentOrder
                    {
                        isSettlement = (int)GlobalEnumVars.AgentOrderSettlementStatus.SettlementYes,
                        updateTime = DateTime.Now
                    },
                    p => p.orderId == orderId &&
                         p.isSettlement == (int)GlobalEnumVars.AgentOrderSettlementStatus.SettlementNo);
            }
 
            return jm;
        }
 
        #endregion
 
        #region 作废订单
 
        /// <summary>
        ///     作废订单
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> CancelOrderByOrderId(string orderId)
        {
            var jm = new WebApiCallBack();
 
            var res = await _dal.UpdateAsync(
                p => new CoreCmsAgentOrder
                { isSettlement = (int)GlobalEnumVars.AgentOrderSettlementStatus.SettlementCancel },
                p => p.orderId == orderId &&
                     p.isSettlement == (int)GlobalEnumVars.AgentOrderSettlementStatus.SettlementNo);
            if (res == false)
            {
                jm.msg = "该未结算的订单不存在";
                return jm;
            }
 
            jm.msg = "操作成功";
            jm.status = true;
 
 
            return jm;
        }
 
        #endregion
 
        #region 循环插入上级
 
        /// <summary>
        ///     循环插入上级
        /// </summary>
        /// <param name="order">订单信息</param>
        /// <param name="orderItems"></param>
        /// <param name="goods"></param>
        /// <param name="products">订单货品</param>
        /// <param name="agentProducts">商品池货品价格体系数据</param>
        /// <param name="agentGoods">商品池数据</param>
        /// <param name="agent">代理商数据</param>
        /// <param name="user">用户数据</param>
        /// <returns></returns>
        private async Task AddOther(CoreCmsOrder order, List<CoreCmsOrderItem> orderItems, List<CoreCmsGoods> goods,
            List<CoreCmsProducts> products, List<CoreCmsAgentGoods> agentGoods,
            List<CoreCmsAgentProducts> agentProducts, CoreCmsAgent agent, CoreCmsUser user)
        {
            //直返本级
            decimal amount = 0;
            var agentOrderDetails = new List<CoreCmsAgentOrderDetails>();
 
            foreach (var item in orderItems)
            {
                var orderDetails = new CoreCmsAgentOrderDetails();
                orderDetails.agentOrderId = 0;
                orderDetails.orderId = order.orderId;
                orderDetails.orderId = order.orderId;
                orderDetails.productPrice = item.price;
                orderDetails.amount = 0;
                orderDetails.goodId = item.goodsId;
                orderDetails.name = item.name;
                orderDetails.addon = item.addon;
                orderDetails.productId = item.productId;
                orderDetails.productNums = item.nums;
                orderDetails.promotionAmount = item.promotionAmount;
                orderDetails.imageUrl = item.imageUrl;
                orderDetails.remark = "";
                orderDetails.createTime = DateTime.Now;
 
                //判断是否存在商品内
                var good = goods.Find(p => p.id == item.goodsId);
                if (good == null)
                {
                    agentOrderDetails.Add(orderDetails);
                    continue;
                };
                //判断是否存在货品类
                var product = products.Find(p => p.id == item.productId);
                if (product == null)
                {
                    agentOrderDetails.Add(orderDetails);
                    continue;
                }
                //判断代理商代理池是否包含此商品数据
                var agentGood = agentGoods.Find(p => p.goodId == item.goodsId);
                if (agentGood == null)
                {
                    agentOrderDetails.Add(orderDetails);
                    continue;
                }
 
                //判断代理商代理池是否包含此货品数据
                var agentProduct = agentProducts.Find(p => p.productId == item.productId);
                if (agentProduct == null)
                {
                    agentOrderDetails.Add(orderDetails);
                    continue;
                }
 
                //获取实际当前单个商品应获得利润
                var price = item.price - agentProduct.agentGradePrice;
                //如果销售价减去代理商价格负了,就不计算了。
                if (price < 0)
                {
                    agentOrderDetails.Add(orderDetails);
                    continue;
                }
 
                //如果利润减去优惠负了,就不计算了。
                var mathMoney = Math.Round(price * item.nums - item.promotionAmount, 2);
                if (mathMoney < 0) mathMoney = 0;
 
                //单个商品利润*数量,再减去优惠金额
                amount += mathMoney;
 
                orderDetails.amount = mathMoney;
                agentOrderDetails.Add(orderDetails);
            }
 
            if (amount > 0)
            {
                var iData = new CoreCmsAgentOrder();
                iData.userId = user.id;
                iData.buyUserId = order.userId;
                iData.orderId = order.orderId;
                iData.amount = amount;
                iData.isSettlement = (int)GlobalEnumVars.AgentOrderSettlementStatus.SettlementNo; //默认未结算
                iData.isDelete = false;
                //判断是否返利过,有历史记录直接更新
                var agentOrder = await _dal.QueryByClauseAsync(p => p.userId == user.id && p.orderId == order.orderId);
                if (agentOrder != null)
                {
                    agentOrder.updateTime = DateTime.Now;
                    agentOrder.userId = iData.userId;
                    agentOrder.buyUserId = iData.buyUserId;
                    agentOrder.orderId = iData.orderId;
                    agentOrder.amount = iData.amount;
                    agentOrder.isSettlement = iData.isSettlement;
                    agentOrder.isDelete = iData.isDelete;
                    await _dal.UpdateAsync(agentOrder);
                }
                else
                {
                    iData.createTime = DateTime.Now;
                    iData.updateTime = DateTime.Now;
                    var id = await _dal.InsertAsync(iData);
                    if (id > 0 && agentOrderDetails.Any())
                    {
                        agentOrderDetails.ForEach(p =>
                        {
                            p.agentOrderId = id;
                        });
                        await _agentOrderDetailsServices.InsertAsync(agentOrderDetails);
                    }
                }
            }
        }
        #endregion
    }
}