username@email.com
2024-10-29 3f91a6737fc06b45461ce11eae5660cbbf766f7e
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
using CoreCms.Net.Caching.AutoMate.RedisCache;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IRepository;
using CoreCms.Net.IServices;
using CoreCms.Net.IServices.baifenbingfa;
using CoreCms.Net.Model.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.Auth.HttpContextUser;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.ViewModels.Basics;
using COSXML.Model.Tag;
using NPOI.SS.Formula.Functions;
using CoreCms.Net.Model.ViewModels.UI;
using SqlSugar;
using CoreCms.Net.Configuration;
using Newtonsoft.Json;
using CoreCms.Net.DTO;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinExpressDeliveryOpenMessageGetDeliveryListResponse.Types;
 
using CoreCms.Net.Loging;
using CoreCms.Net.Model.Entities.baifenbingfa.DistributionSendOder;
using StackExchange.Redis;
using Microsoft.Extensions.Logging;
 
namespace CoreCms.Net.Services.baifenbingfa
{
    /// <summary>
    /// 供应商发货单处理服务
    /// </summary>
    public class DistributorDeliveryServices : BaseServices<CoreCmsBillDelivery>, IDistributorDeliveryServices
    {
 
        private readonly ICoreCmsBillDeliveryRepository _dal;
        private readonly ICoreCmsStoreServices _storeServices;
        private readonly ICoreCmsBillDeliveryItemServices _billDeliveryItemServices;
        private readonly ICoreCmsOrderLogServices _orderLogServices;
        private readonly ICoreCmsSettingServices _settingServices;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IServiceProvider _serviceProvider;
        private readonly IRedisOperationRepository _redisOperationRepository;
       private readonly  IHttpContextUser _user;
 
 
        public readonly ICoreCmsDistributionServices _coreCmsDistributionServices;
        private readonly ICoreCmsOrderServices _orderServices;
 
        public DistributorDeliveryServices(
            IUnitOfWork unitOfWork,
            IServiceProvider serviceProvider
            , ICoreCmsBillDeliveryRepository dal
            , ICoreCmsStoreServices storeServices
            , ICoreCmsBillDeliveryItemServices billDeliveryItemServices
            , ICoreCmsOrderLogServices orderLogServices
            , ICoreCmsSettingServices settingServices
            , IRedisOperationRepository redisOperationRepository
            , IHttpContextUser user
            ,ICoreCmsDistributionServices coreCmsDistributionServices
            ,ICoreCmsOrderServices orderServices)
        {
            this._dal = dal;
            base.BaseDal = dal;
            _unitOfWork = unitOfWork;
            _serviceProvider = serviceProvider;
            _storeServices = storeServices;
            _billDeliveryItemServices = billDeliveryItemServices;
            _orderLogServices = orderLogServices;
            _settingServices = settingServices;
            _redisOperationRepository = redisOperationRepository;
            _user = user;
            _coreCmsDistributionServices = coreCmsDistributionServices;
            _orderServices = orderServices;
        }
 
        public async Task<(List< CoreCmsBillDelivery>,int )> GetDeliveryList(GetDeliveryListPost Param)
        {
 
 
            var where = PredicateBuilder.True<CoreCmsBillDelivery>();
             if(Param.Status != null )
            {
                where= where.And(x => x.status == (int)Param.Status);
            }
            if (Param.distributionAcceptStatus != null)
            {
                switch (Param.distributionAcceptStatus)
                {
                    case sendDistributionAcceptType.Accepted:
                        ///进行中,售后空
                        where = where.And(x => x.sendDistributionAccept == sendDistributionAcceptType.Accepted
                        && x.order.status == (int)GlobalEnumVars.OrderStatus.Normal && !x.order.aftersalesItem1.Any()&& x.order.confirmStatus != (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt);
                        //where = where.And(x => x.sendDistributionAccept == Param.distributionAcceptStatus);
                        break;
                    case sendDistributionAcceptType.NoAccted:
                        ///未确认接受的,不能售后空
                        where = where.And(x => x.sendDistributionAccept == sendDistributionAcceptType.NoAccted
                        && x.order.status == (int)GlobalEnumVars.OrderStatus.Normal && !x.order.aftersalesItem1.Any());
                        //where = where.And(x => x.sendDistributionAccept == Param.distributionAcceptStatus);
                        break;
                    
                    case sendDistributionAcceptType.OderFreeComplete:
 
                        where = where.And(x => x.sendDistributionAccept == sendDistributionAcceptType.Accepted
                      && x.order.status == (int)GlobalEnumVars.OrderStatus.Complete && !x.order.aftersalesItem1.Any());
                        //where = where.And(x => x.sendDistributionAccept == Param.distributionAcceptStatus);
                        break;
                    case sendDistributionAcceptType.Cancelled:
 
                        where = where.And(x =>( x.sendDistributionAccept == sendDistributionAcceptType.Cancelled
                 ||  x.order.status == (int)GlobalEnumVars.OrderStatus.Cancel || x.order.aftersalesItem1.Any()));
                        //where = where.And(x => x.sendDistributionAccept == Param.distributionAcceptStatus);
                        break;
                    case sendDistributionAcceptType.Delivered:
                        where = where.And(x => x.sendDistributionAccept == sendDistributionAcceptType.Delivered
                 || x.order.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt );
                        //where = where.And(x => x.sendDistributionAccept == Param.distributionAcceptStatus);
                        break;
                    default:
                        break;
                }
                //where= where.And(x => x.sendDistributionAccept == Param.distributionAcceptStatus);
            }
            where= where.And(x => x.sendDistributionUserID == _user.ID);
            //必须是出于发货状态
            //where= where.And(x => x.order.shipStatus ==(int ) GlobalEnumVars.OrderShipStatus.Yes);
            //必须是有效状态
            //where= where.And(x => x.order.status == (int)GlobalEnumVars.OrderStatus.Normal);
            RefAsync<int> totl = 0;
            var list = await _unitOfWork.GetDbClient().Queryable<CoreCmsBillDelivery>()
                .Includes(x => x.order, order => order.Orderitems, ite => ite.productInfo)
                .Includes(x => x.order, Order => Order.aftersalesItem1)
                .Where(where)
                .Select(x => new CoreCmsBillDelivery
                {
                    
                    order = x.order,
                }, true)
                 .MergeTable()
                //.Mapper(x => x.order.billAftersalesId = SqlFunc.Subqueryable<CoreCmsBillAftersales>().Where(core => core.orderId == x.orderId).Select(core => core.aftersalesId))
                .Mapper(
                x =>
                {
                    switch (x.sendDistributionAccept)
                    {
                        case sendDistributionAcceptType.Accepted:
                           
                             if (x.order.status == (int)GlobalEnumVars.OrderStatus.Cancel)
                                x.sendDistributionAccept = sendDistributionAcceptType.Cancelled;                          
                             else
                              if (x.order.status == (int)GlobalEnumVars.OrderStatus.Complete && !x.order.aftersalesItem1.Any())
                                x.sendDistributionAccept = sendDistributionAcceptType.OderFreeComplete;
                            if (x.order.status == (int)GlobalEnumVars.OrderStatus.Complete && x.order.aftersalesItem1.Any())
                                x.sendDistributionAccept = sendDistributionAcceptType.Cancelled;
 
                            else if (x.order.status == (int)GlobalEnumVars.OrderStatus.Normal && x.order.aftersalesItem1.Any())
                                x.sendDistributionAccept = sendDistributionAcceptType.Cancelled;
                            else
                             if (x.order.confirmStatus == (int)GlobalEnumVars.OrderConfirmStatus.ConfirmReceipt)
                                x.sendDistributionAccept = sendDistributionAcceptType.Delivered;
                            else
                                x.sendDistributionAccept = x.sendDistributionAccept;
                            break;
                        case sendDistributionAcceptType.NoAccted:
                            ///未确认接受的,不能售后空
                           if(x.order.status== (int)GlobalEnumVars.OrderStatus.Complete||x.order.status== (int)GlobalEnumVars.OrderStatus.Cancel|| x.order.aftersalesItem1.Any())
                                x.sendDistributionAccept= sendDistributionAcceptType.Cancelled;
                            else
                                x.sendDistributionAccept = x.sendDistributionAccept;
                            break;
 
                        case sendDistributionAcceptType.OderFreeComplete:
 
                          //永远不会到这
                            break;
                        case sendDistributionAcceptType.Cancelled:
                            //不需要处理
                       
                            break;
                        default:
                            break;
                    }
                }
                )
 
                .OrderByDescending(x => x.createTime)
                .ToPageListAsync(Param.page, Param.limit, totl);
             var listdata=  new PageList<CoreCmsBillDelivery>(list, Param.page, Param.limit, totl);
 
            return (listdata,totl);
            //return  await  _dal.QueryPageAsync(where, x => x.createTime, SqlSugar.OrderByType.Desc, Param.page, Param.page);
        }
 
        public async Task<int> GetNoAcceptedDeliveryCount()
        {
           var lista=  await _unitOfWork.GetDbClient().Queryable<CoreCmsBillDelivery>().Includes(x => x.order,ord=>ord.aftersalesItem1)             
               .Where(x => x.sendDistributionUserID == _user.ID && x.sendDistributionAccept == sendDistributionAcceptType.NoAccted
           && x.order.status != (int)GlobalEnumVars.OrderStatus.Complete ).ToListAsync();
 
            return lista.Where(x=>(x.order.aftersalesItem1==null|| x.order.aftersalesItem1.Count()==0)).Count();//删选出没有售后申请的订单
 
 
        }
 
        public async Task<bool> GetShowDelivery()
        {
            return (await _coreCmsDistributionServices.GetCountAsync(x => x.userId == _user.ID && x.verifyStatus == (int)GlobalEnumVars.DistributionVerifyStatus.VerifyYes&&x.profession=="校园代理", isDataCache: true, cacheTimes: 60)>0);
        }
        public async Task<WebApiCallBack> SetDeliveryAccepted(sendDistributionAcceptType acceptType,   string DeliveryID, string CancelledDec = null)
        {
 
            WebApiCallBack ret = new WebApiCallBack();
 
            if (acceptType == sendDistributionAcceptType.OderFreeComplete)
            {
                //只有在完成订单中设置该状态,该状态会对配售收益进行提取整合
                ret.status = false;
                ret.msg = "状态设置错误";
                return ret;
            }
            var data = await _dal.QueryByIdAsync(DeliveryID);
            if (data == null)
            {
                ret.status = false;
                ret.msg = " 没有找到发货单";
                return ret;
 
            }
            if (data.sendDistributionUserID != _user.ID)
            {
                ret.status = false;
                ret.msg = "该发货单不属于该该用户";
                return ret;
            }
 
            var oder = await _unitOfWork.GetDbClient().Queryable<CoreCmsOrder>().Where(x=>x.status== (int)GlobalEnumVars.OrderStatus.Normal).Includes(x => x.Orderitems).Where(x => x.orderId == data.orderId).FirstAsync();
            if(oder == null)
            {
                ret.status = false;
                ret.msg = "订单已经完结,不可操作";
                return ret;
            }
 
            var mQ = new ActiveDistributionSendOderMQ
            {
                Dec = CancelledDec,
                SendOderActive = acceptType,
                deliveryID = DeliveryID,
                userID = _user.ID
            };
            //记录操作记录
            await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.ActiveDistributionSendOderMQ, JsonConvert.SerializeObject(mQ));
            //用户不同意配送
            try
            {
 
           
            _unitOfWork.BeginTran();
            if (acceptType == sendDistributionAcceptType.Cancelled)
            {
                //如果是取消订单,需要把订单
                //不接受 需要将原订单设置为为分配状态,
 
               
                   
                if (oder.status != (int)GlobalEnumVars.OrderStatus.Complete 
                    && oder.status != (int)GlobalEnumVars.OrderStatus.Cancel
                    &&oder.shipStatus== (int)GlobalEnumVars.OrderShipStatus.Yes
                     )
                {
                        var Deliveryitem = await _unitOfWork.GetDbClient().Queryable<CoreCmsBillDeliveryItem>().Where(x => x.deliveryId == data.deliveryId).ToListAsync();
 
                        foreach (var item in oder.Orderitems)
                        {
                            //处理已发货数据
 
                            item.sendNums -= Deliveryitem.Where(x => x.productId == item.productId).Select(x => x.nums).FirstOrDefault();
                            if(item.sendNums<0)
                                item.sendNums = 0;
                            item.updateTime = DateTime.Now;
 
 
 
                        }
                        oder.shipStatus =(int ) GlobalEnumVars.OrderShipStatus.No;
 
                        oder.updateTime = DateTime.Now;
                   await  _unitOfWork.GetDbClient().UpdateNav( oder ).Include(x=>x.Orderitems).ExecuteCommandAsync() ;
                      
 
                }
 
 
            }
 
            data.sendDistributionAccept = acceptType;
            data.updateTime= DateTime.Now;
            ret.status = true;
            var r= await _dal.UpdateAsync(data);
                if(r==true)
                _unitOfWork.CommitTran();
                else
                {
                    _unitOfWork.RollbackTran();
                }
            ret.status = r;
            ret.msg = r ? "设置成功" : "设置失败";
           return ret;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackTran();
                throw;
            }
        }
 
        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 distributionSendOder =  await  _unitOfWork.GetDbClient().Queryable<DistributionSendOder>().Includes(x=>x.delivery)
                .Where(x=>x.delivery.orderId==order.orderId&&(x.sendDistributionAccept== sendDistributionAcceptType.Accepted|| x.sendDistributionAccept== sendDistributionAcceptType.Shipped||x.sendDistributionAccept== sendDistributionAcceptType.Delivered))
                .ToListAsync();
          if(  distributionSendOder.Count==1)
            {
                //满足所有条件开始分配逻辑
                var mQ = new ActiveDistributionSendOderMQ
                {
               
                    SendOderActive = sendDistributionAcceptType.OderFreeComplete,
                    deliveryID = distributionSendOder[0].deliveryID,
                    userID = order.userId
                };
 
                await _redisOperationRepository.ListLeftPushAsync(RedisMessageQueueKey.ActiveDistributionSendOderMQ, JsonConvert.SerializeObject(mQ));
                jm.status = true;
 
            }
          else if( distributionSendOder.Count>1)
            {
               jm.status= false;
                jm.msg = "发现多个配送订单,需要手动排查";
                NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.Order, "处理经销商配送收益时错误", $"订单ID{orderId} 发现多个满足经销商派送单,放弃处理,需排查");
             
            }
          jm.status = true;
          return jm;
 
             //if (order.shipStatus is (int)GlobalEnumVars.OrderShipStatus.No or (int)GlobalEnumVars.OrderShipStatus.PartialYes)
             //   {
             //       return jm;
             //   }
 
        }
    }
}