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 { /// /// 供应商发货单处理服务 /// public class DistributorDeliveryServices : BaseServices, 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(); 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 totl = 0; var list = await _unitOfWork.GetDbClient().Queryable() .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().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(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 GetNoAcceptedDeliveryCount() { var lista= await _unitOfWork.GetDbClient().Queryable().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 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 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().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().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 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().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; // } } } }