using BBWY.Common.Http; using BBWY.Common.Models; using BBWY.Server.Model; using BBWY.Server.Model.Dto; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Yitter.IdGenerator; using System.Linq; using BBWY.Server.Model.Db; using FreeSql; namespace BBWY.Server.Business.Sync { public class JDServiceOrderSyncBusiness : BaseSyncBusiness, IDenpendency { private IList jd_kd100_logisticsCompanyDictionary; public JDServiceOrderSyncBusiness(RestApiService restApiService, IOptions options, NLogManager nLogManager, IFreeSql fsql, IIdGenerator idGenerator, TaskSchedulerManager taskSchedulerManager, VenderBusiness venderBusiness, YunDingBusiness yunDingBusiness) : base(restApiService, options, nLogManager, fsql, idGenerator, taskSchedulerManager, venderBusiness, yunDingBusiness) { jd_kd100_logisticsCompanyDictionary = new List() { new LogisticsCompanyRelationship(){ SourceName="",TargetName="",SecondTargetName="" } }; } public void SyncServiceOrder() { var shopList = venderBusiness.GetShopList(platform: Enums.Platform.京东); //SyncAfterOrder(shopList.FirstOrDefault(s => s.ShopName == "布莱特玩具专营店"), string.Empty, isAuto: true); foreach (var shop in shopList) { Task.Factory.StartNew(() => SyncServiceOrder(shop, string.Empty, isAuto: true), System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.SyncServiceOrderTaskScheduler); } } public void SyncServiceOrder(long shopId, string serviceId) { var shopList = venderBusiness.GetShopList(shopId); Task.Factory.StartNew(() => SyncServiceOrder(shopList[0], serviceId, isAuto: true), System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.SyncServiceOrderTaskScheduler); } private void SyncServiceOrder(ShopResponse shop, long shopId, IList jtokenList, string relayAPIHost, string appKey, string appSecret, string token) { var serviceIdList = jtokenList.Select(j => j.Value("serviceId")).ToList(); var dbServiceOrderList = fsql.Select().Where(s => s.ShopId == shop.ShopId && serviceIdList.Contains(s.ServiceId)).ToList(); var dbServiceIdList = dbServiceOrderList.Select(s => s.ServiceId).ToList(); var exceptServiceIdList = serviceIdList.Except(dbServiceIdList); var apiOrderIdList = jtokenList.Where(j => exceptServiceIdList.Contains(j.Value("serviceId"))).Select(j => j.Value("orderId")).ToList(); var dbOrderSkuList = fsql.Select().InnerJoin((osku, o) => osku.OrderId == o.Id) .Where((osku, o) => osku.ShopId == shopId && apiOrderIdList.Contains(osku.OrderId)) .ToList((osku, o) => new { Id = osku.Id, ProductId = osku.ProductId, SkuId = osku.SkuId, OrderId = osku.OrderId, ItemTotal = osku.ItemTotal, StorageType = o.StorageType }); List insertServiceOrderList = new List(); List> updateServiceOrderList = new List>(); foreach (var serviceOrderJToken in jtokenList) { var serviceId = serviceOrderJToken.Value("serviceId"); var status = serviceOrderJToken.Value("sserviceOrderJToken"); var statusUpdateTime = serviceOrderJToken.Value("updateTime"); var dbServiceOrder = dbServiceOrderList.FirstOrDefault(s => s.ServiceId == serviceId); if (dbServiceOrder == null) { var serviceOrderId = serviceOrderJToken.Value("orderId"); var skuId = serviceOrderJToken.Value("skuId"); var dbOsku = dbOrderSkuList.FirstOrDefault(osku => osku.OrderId == serviceOrderId && osku.SkuId == skuId); if (dbOsku == null) continue; var isNeedSubscribeKuaiDi100 = false; #region 待收货服务单,检查是否需要订阅快递100 if (status == 10005) { if (dbOsku.StorageType == Enums.StorageType.代发) isNeedSubscribeKuaiDi100 = true; else { try { var serviceOrderDetailResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetServiceOrderDetail", new QueryServiceOrderDetailRequest() { AppKey = appKey, AppSecret = appSecret, AppToken = token, OrderId = serviceOrderId, ServiceId = serviceId, Platform = Enums.Platform.京东, VenderId = shop.VenderId }, GetYunDingRequestHeader(), HttpMethod.Post); if (serviceOrderDetailResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取服务单详情失败 {serviceOrderDetailResult.Content}"); var serviceOrderDetailResponse = JsonConvert.DeserializeObject>(serviceOrderDetailResult.Content); if (!serviceOrderDetailResponse.Success) throw new Exception($"获取服务单详情失败 {serviceOrderDetailResponse.Msg}"); //检查退货城市是否为泉州 isNeedSubscribeKuaiDi100 = serviceOrderDetailResponse.Data["returnWareAddress"].Value("cityCode") == 2812; } catch { } } } #endregion dbServiceOrder = new ServiceOrder() { Id = idGenerator.NewLong(), ServiceId = serviceId, OrderId = serviceOrderId, ShopId = shop.ShopId, ProductId = dbOsku.ProductId, SkuItemCount = dbOsku.ItemTotal, Status = status, CreateTime = DateTime.Now, SkuId = skuId, StatusUpdateTime = statusUpdateTime, IsSubscribeKuaiDi100 = false, IsNeedSubscribeKuaiDi100 = isNeedSubscribeKuaiDi100, WaybillNo = string.Empty, ExpressName = string.Empty, ApplyTime = serviceOrderJToken.Value("applyTime") }; insertServiceOrderList.Add(dbServiceOrder); } else if (dbServiceOrder.Status != status) { var update = fsql.Update(dbServiceOrder.Id).Set(s => s.Status, status) .Set(s => s.StatusUpdateTime, statusUpdateTime); updateServiceOrderList.Add(update); } } fsql.Transaction(() => { if (insertServiceOrderList.Count() > 0) fsql.Insert(insertServiceOrderList).ExecuteAffrows(); if (updateServiceOrderList.Count() > 0) foreach (var update in updateServiceOrderList) update.ExecuteAffrows(); }); } private void SyncServiceOrder(ShopResponse shop, string serviceId, DateTime? startTime = null, DateTime? endTime = null, bool isAuto = false) { /* 审核阶段: 待审核: 10001 待用户反馈: 10002 用户已反馈: 10012 【待收货: 10005】 【取消: 10011】 审核关闭: 10004 待用户确认: 10009 【完成: 10010】 处理阶段: 已收货,待处理 : 10007 原返取消,待处理:7060 换新取消,待处理:7023 线下换新取消,待处理:7090 商家催收: 13000 */ var loggerName = $"新服务单同步-{shop.ShopName}"; try { var shopId = long.Parse(shop.ShopId); var relayAPIHost = GetPlatformRelayAPIHost(shop.PlatformId); var serviceStatusList = new List() { 10005, 10011, 10010 }; var request = new QueryServiceOrderRequest() { UpdateTimeBegin = startTime ?? DateTime.Now.Date.AddHours(-1), UpdateTimeEnd = endTime ?? DateTime.Now, AppKey = shop.AppKey, AppSecret = shop.AppSecret, AppToken = shop.AppToken, PageIndex = 1, PageSize = 50, Platform = shop.PlatformId, SaveResponseLog = true, ServiceId = serviceId, VenderId = shop.VenderId }; List jtokenList = new List(); foreach (var serviceStatus in serviceStatusList) { if (string.IsNullOrEmpty(serviceId)) request.ServiceStatus = serviceStatus; var serviceOrderListApiResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetServiceOrderList", request, GetYunDingRequestHeader(), HttpMethod.Post); if (serviceOrderListApiResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取服务单失败 {serviceOrderListApiResult.Content}"); var serviceOrderListResponse = JsonConvert.DeserializeObject>(serviceOrderListApiResult.Content); if (!serviceOrderListResponse.Success) throw new Exception($"获取服务单失败 {serviceOrderListResponse.Msg}"); jtokenList.AddRange(serviceOrderListResponse.Data); if (!string.IsNullOrEmpty(serviceId)) break; } SyncServiceOrder(shop, shopId, jtokenList, relayAPIHost, request.AppKey, request.AppSecret, request.AppToken); } catch (Exception ex) { nLogManager.GetLogger(loggerName).Error(ex, $"SyncServiceOrder ShopName:{shop.ShopName} ShopId:{shop.ShopId}"); } } public void SubscribeKuaiDi100() { var shopList = venderBusiness.GetShopList(platform: Enums.Platform.京东); foreach (var shop in shopList) { Task.Factory.StartNew(() => SyncServiceOrder(shop, string.Empty, isAuto: true), System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.SyncServiceOrderTaskScheduler); } } public void SubscribeKuaiDi100(long shopId) { var shop = venderBusiness.GetShopList(shopId).FirstOrDefault(); Task.Factory.StartNew(() => SyncServiceOrder(shop, string.Empty, isAuto: true), System.Threading.CancellationToken.None, TaskCreationOptions.LongRunning, taskSchedulerManager.SyncServiceOrderTaskScheduler); } private void SubscribeKuaiDi100(ShopResponse shop) { var loggerName = $"订阅快递100-{shop.ShopName}"; try { var relayAPIHost = GetPlatformRelayAPIHost(shop.PlatformId); var serviceOrderList = fsql.Select().Where(s => s.ShopId == shop.Id && s.IsNeedSubscribeKuaiDi100 == true && s.IsSubscribeKuaiDi100 == false) .Page(1, 50) .ToList(); List> updateSerivceOrderList = new List>(); foreach (var serviceOrder in serviceOrderList) { bool isUpdateDelivery = false, isUpdateSubscribe = false; if (string.IsNullOrEmpty(serviceOrder.WaybillNo) || string.IsNullOrEmpty(serviceOrder.ExpressName)) { try { #region 查询服务单运单详情 var serviceOrderDeliveryResult = restApiService.SendRequest(relayAPIHost, "api/PlatformSDK/GetServiceOrderDeliveryDetail", new QueryServiceOrderDetailRequest() { AppKey = shop.AppKey, AppSecret = shop.AppSecret, AppToken = shop.AppToken, OrderId = serviceOrder.OrderId, ServiceId = serviceOrder.ServiceId, Platform = Enums.Platform.京东, VenderId = shop.VenderId }, GetYunDingRequestHeader(), HttpMethod.Post); if (serviceOrderDeliveryResult.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception($"获取服务单运单详情失败 {serviceOrderDeliveryResult.Content}"); var serviceOrderDeliveryResponse = JsonConvert.DeserializeObject>(serviceOrderDeliveryResult.Content); if (!serviceOrderDeliveryResponse.Success) throw new Exception($"获取服务单运单详情失败 {serviceOrderDeliveryResponse.Msg}"); if (serviceOrderDeliveryResponse.Data != null) { var wayBillNo = serviceOrderDeliveryResponse.Data.Value("expressCode"); var expressName = serviceOrderDeliveryResponse.Data.Value("expressCompany"); if (!string.IsNullOrEmpty(wayBillNo) && !string.IsNullOrEmpty(expressName)) { serviceOrder.WaybillNo = wayBillNo; serviceOrder.ExpressName = expressName; isUpdateDelivery = true; //var update = fsql.Update(serviceOrder.Id).Set(s => s.WaybillNo, wayBillNo) // .Set(s => s.ExpressName, expressName); } } #endregion } catch (Exception ex) { nLogManager.GetLogger(loggerName).Error(ex, $"SubscribeKuaiDi100 ShopName:{shop.ShopName} ShopId:{shop.ShopId} ServiceId:{serviceOrder.ServiceId}"); } } if (!string.IsNullOrEmpty(serviceOrder.WaybillNo) && !string.IsNullOrEmpty(serviceOrder.ExpressName)) { #region 订阅快递100 isUpdateSubscribe = true; #endregion } if (isUpdateDelivery || isUpdateSubscribe) { var update = fsql.Update(serviceOrder.Id).SetIf(isUpdateDelivery, s => s.WaybillNo, serviceOrder.WaybillNo) .SetIf(isUpdateDelivery, s => s.ExpressName, serviceOrder.ExpressName) .SetIf(isUpdateSubscribe, s => s.IsSubscribeKuaiDi100, true); updateSerivceOrderList.Add(update); } } if (updateSerivceOrderList.Count() > 0) { fsql.Transaction(() => { foreach (var update in updateSerivceOrderList) update.ExecuteAffrows(); }); } } catch (Exception ex) { nLogManager.GetLogger(loggerName).Error(ex, $"SubscribeKuaiDi100 ShopName:{shop.ShopName} ShopId:{shop.ShopId}"); } } } }