using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Net;
|
using System.Text;
|
using System.Threading.Tasks;
|
using AlibabaSDK.Api;
|
using AlibabaSDK.Domain;
|
using AlibabaSDK.Request;
|
using BaiDuSdk;
|
using CommonUtil;
|
using CommonUtil.RabbitMQ;
|
using HtmlAgilityPack;
|
using Operater.DAL;
|
using Operater.DbModel;
|
using Operater.DTO.System;
|
using YouZanSDKStandard.Api;
|
using YouZanSDKStandard.Api.Domain;
|
using YouZanSDKStandard.Api.Request;
|
using YouZanSDKStandard.Api.Response;
|
|
namespace Operater.Service.System
|
{
|
public class ItemDistributionService : IItemDistributionService
|
{
|
|
/// <summary>
|
/// 精选货源铺货
|
/// </summary>
|
/// <param name="sourcePid"></param>
|
public async Task<bool> RunDistribution(DistributionHistory taskInfo, string aliToken, string yzToken, List<ProductFilter> filter)
|
{
|
DistributionHistory finalHis = new DistributionHistory();
|
try
|
{
|
//任务状态改成执行中
|
DistributionHistory distributionHistory = new DistributionHistory()
|
{
|
DisStatus = 1,
|
RunTime = DateTime.Now
|
};
|
new DistributionHistoryDAL().Update(distributionHistory, t => new { t.DisStatus, t.RunTime }, t => t.Id == taskInfo.Id);
|
//获取1688商品详情
|
List<string> ls = new List<string>();
|
ls.Add(taskInfo.ProductId);
|
PFTProductDetailRequest request = new PFTProductDetailRequest()
|
{
|
offerIds = ls
|
};
|
var response = AliabaClient.Execute(request, aliToken);
|
if (response.IsNull() || !response.result.success || response.result.result.Count == 0)
|
{//获取商品详情失败
|
LogUtil.Info($"获取商品详情失败:{taskInfo.Id}", "铺货错误");
|
finalHis.DisStatus = 3;
|
finalHis.Memo = "获取商品详情失败:" + (response.IsNull() ? "null" : response.ErrorMsg);
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
//判断1688商品状态
|
if (response.result.result[0].productInfo.status != "published")
|
{//不可铺货
|
LogUtil.Info($"商品状态不对:{response.result.result[0].productInfo.status}", "铺货错误");
|
finalHis.DisStatus = 3;
|
finalHis.Memo = "商品状态不对:" + (response.result.result[0].productInfo.status);
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
if (!response.result.result[0].productInfo.saleInfo.supportOnlineTrade)
|
{
|
LogUtil.Info($"不支持网上交易:{response.result.result[0].productInfo.saleInfo.supportOnlineTrade}", "铺货错误");
|
finalHis.DisStatus = 3;
|
finalHis.Memo = "商品不支持网上交易";
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
StringBuilder imgError = new StringBuilder();
|
//商品图片
|
finalHis.ProImg = "https://cbu01.alicdn.com/img/" + response.result.result[0].productInfo.image.images[0];
|
//string imgMsg = FilterImg(filter, finalHis.ProImg);
|
//if (!imgMsg.IsNullOrEmpty())
|
//{
|
// imgError.Append($"主图:[{imgMsg}]");
|
//}
|
//商品title
|
finalHis.ProTitle = response.result.result[0].productInfo.subject;
|
|
//根据规则调整字段
|
var aliPro = response.result.result[0].productInfo;
|
//是否包邮 精选货源默认包邮
|
finalHis.IsFreeShipping = 1;
|
//调用有赞新增商品接口 youzan.item.add.1.0.1
|
YouZanItemAddRequest yzReq = new YouZanItemAddRequest();
|
yzReq.param = GetAliInfoToYz(aliPro, yzToken, filter, ref imgError);
|
var yzRsp = YouZanClient.Execute(yzReq, yzToken);
|
if (yzRsp.IsNull() || !yzRsp.success)
|
{//新增失败
|
finalHis.DisStatus = 3;
|
finalHis.Memo = yzRsp.IsNull() ? "有赞接口错误" : yzRsp.message;
|
LogUtil.Info($"有赞错误:{finalHis.Memo}--request:" + JSONUtil.ObjectToJson(yzReq), "铺货错误");
|
}
|
else
|
{
|
//有赞返回商品id
|
string yzProductId = yzRsp.data.item_id;
|
//修改任务状态
|
finalHis.DisStatus = 2;
|
finalHis.YzItemId = yzProductId;
|
finalHis.YzAlias = yzRsp.data.alias;
|
string yzskuInfo = UpdateYzSku(yzProductId, yzToken);
|
if (!imgError.IsNull() && imgError.Length > 0)
|
{
|
finalHis.Memo = imgError.ToString();
|
}
|
yzskuInfo = yzskuInfo.IsNullOrEmpty() ? JSONUtil.ObjectToJson(yzReq.param.sku_list) : yzskuInfo;
|
//记录1688id与有赞id的关系
|
DistributionRelation distributionRelation = new DistributionRelation()
|
{
|
Id = TopUtil.GetId().ToString(),
|
SourceProduct = taskInfo.ProductId,
|
YzProduct = yzProductId,
|
YzAlias = yzRsp.data.alias,
|
ReStatus = 1,
|
InstanceCode = response.result.result[0].instanceCode,
|
CreateTime = DateTime.Now,
|
AliskuInfo = JSONUtil.ObjectToJson(response.result.result[0].productInfo.skuInfos),
|
YzskuInfo = yzskuInfo,
|
ProSource = 0
|
};
|
new DistributionRelationDAL().Insert(distributionRelation);
|
//关注商品
|
AlibabaProductFollowRequest followReq = new AlibabaProductFollowRequest()
|
{
|
productId = long.Parse(taskInfo.ProductId)
|
};
|
var followRsp = AliabaClient.Execute(followReq, aliToken);
|
if (followRsp.IsNull() || followRsp.message != "success")
|
{
|
LogUtil.Info($"关注商品{taskInfo.ProductId}失败,错误:" + (followRsp.IsNull() ? "null" : followRsp.message), "铺货错误");
|
}
|
}
|
}
|
catch (Exception e)
|
{
|
finalHis.DisStatus = 3;
|
finalHis.Memo = e.Message;
|
LogUtil.Info($"错误:{e.ToString()}", "铺货错误");
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo, t.ProImg, t.ProTitle, t.YzAlias, t.YzItemId, t.IsFreeShipping }, t => t.Id == taskInfo.Id);
|
return true;
|
}
|
|
/// <summary>
|
/// 精品货源商品属性赋值给有赞
|
/// </summary>
|
/// <param name="aliPro"></param>
|
/// <returns></returns>
|
public static YouZanItemAddDomain GetAliInfoToYz(PFTProductDetailDomainProInfo aliPro, string yzToken, List<ProductFilter> filter, ref StringBuilder imgError)
|
{
|
|
YouZanItemAddDomain yzPara = new YouZanItemAddDomain();
|
yzPara.item_no = aliPro.productID.ToString();
|
string desc = FilterMsg(filter, aliPro.description);
|
// desc = FilterDesc(filter, desc);
|
yzPara.desc = desc;
|
|
//yzPara.start_sale_num = aliPro.saleInfo.minOrderQuantity;
|
yzPara.start_sale_num = 1;
|
DeliverySetting deliverySetting = new DeliverySetting()
|
{
|
express = true
|
};
|
//售后信息
|
PostSaleParam postSaleParam = new PostSaleParam()
|
{ is_support_barter = 0 };
|
postSaleParam.support_unconditional_return = aliPro.sevenDaysRefunds;
|
yzPara.post_sale_param = postSaleParam;
|
//获取默认运费模板
|
var appset = new AppsetDAL().ListGet(t => t.Id != null);
|
ItemDeliveryParam itemDeliveryParam = new ItemDeliveryParam
|
{
|
delivery_setting = deliverySetting,
|
delivery_template_id = long.Parse(appset[0].YzPostMould)
|
};
|
yzPara.item_delivery_param = itemDeliveryParam;
|
switch (aliPro.saleInfo.invReduceType)
|
{
|
case "1"://下单减库存
|
yzPara.stock_deduct_mode = 0;
|
break;
|
case "2"://付款减库存
|
yzPara.stock_deduct_mode = 1;
|
break;
|
}
|
yzPara.title = FilterMsg(filter, aliPro.subject);
|
yzPara.is_display = 0;
|
//商品库存, 无sku情况下库存必填,如果有sku则无效
|
yzPara.quantity = long.Parse(aliPro.saleInfo.amountOnSale.ToString());
|
List<SkuList> skuLists = new List<SkuList>();
|
List<SkuValueProps> skuValues = new List<SkuValueProps>();
|
Dictionary<string, long> imgDic = new Dictionary<string, long>();
|
bool isImgShow = false;
|
long replaceImgId = 0;
|
foreach (var aliSkuItem in aliPro.skuInfos)
|
{
|
if (aliSkuItem.retailPrice <= 0)
|
{
|
continue;
|
}
|
List<SkuProps> skuPropsList = new List<SkuProps>();
|
aliSkuItem.attributes = aliSkuItem.attributes.OrderBy(t => t.skuImageUrl.IsNullOrEmpty()).ToList();
|
int index = 0;
|
foreach (var attr in aliSkuItem.attributes)
|
{//属性信息
|
index++;
|
SkuProps skuProps = new SkuProps()
|
{
|
prop_value_name = attr.attributeValue,
|
prop_name = attr.attributeName,
|
prop_name_id = attr.attValueID,
|
prop_value_id = attr.attributeID
|
};
|
skuPropsList.Add(skuProps);
|
if (index == 1 && !attr.skuImageUrl.IsNullOrEmpty())
|
{
|
isImgShow = true;
|
//处理有赞sku图片信息
|
long imgId = 0;
|
if (imgDic.ContainsKey(attr.skuImageUrl))
|
{
|
imgId = imgDic[attr.skuImageUrl];
|
}
|
else
|
{
|
imgId = UploadImg(yzToken, attr.skuImageUrl);
|
//string imgstr = ImgCheck(filter, attr.skuImageUrl);
|
//if (!imgstr.IsNullOrEmpty())
|
//{
|
// imgError.Append($"sku:[{imgstr}]");
|
//}
|
imgDic.Add(attr.skuImageUrl, imgId);
|
}
|
SkuValueProps skuValueProps = new SkuValueProps()
|
{
|
name = attr.attributeValue,
|
id = attr.attributeID
|
};
|
if (imgId > 0)
|
{
|
replaceImgId = replaceImgId == 0 ? imgId : replaceImgId;
|
skuValueProps.img_id = imgId;
|
}
|
skuValues.Add(skuValueProps);
|
}
|
}
|
//价格计算。上涨50%
|
long price = long.Parse(Math.Ceiling(aliSkuItem.retailPrice * 100 + aliSkuItem.retailPrice * 100 * 0.5).ToString());
|
SkuList skuitem = new SkuList()
|
{
|
//price = long.Parse((Math.Round(aliSkuItem.price * 100, 2)).ToString()),
|
price = price,
|
sku_no = aliSkuItem.skuId.ToString(),
|
stock_num = aliSkuItem.amountOnSale,
|
sku_props = skuPropsList
|
};
|
skuLists.Add(skuitem);
|
}
|
if (!skuValues.IsNull() && skuValues.Count > 0)
|
{
|
yzPara.sku_value_props = skuValues;
|
yzPara.sku_picture_display_config = isImgShow;
|
}
|
//sku信息
|
yzPara.sku_list = skuLists;
|
ItemPriceParam itemPriceParam = new ItemPriceParam()
|
{
|
price = long.Parse(Math.Round(aliPro.saleInfo.priceRanges[0].price * 100, 2).ToString())
|
};
|
yzPara.item_price_param = itemPriceParam;
|
//处理商品图片
|
|
int currentIndex = 0;
|
List<long> imageIds = new List<long>();
|
foreach (var img in aliPro.image.images)
|
{
|
currentIndex++;
|
long imgId = 0;
|
if (currentIndex==1)
|
{
|
//检测第一张主图
|
string imgstr = ImgCheck(filter, aliPro.image.images[0]);
|
if (!imgstr.IsNullOrEmpty())
|
{
|
imgError.Append($"主图:[{imgstr}]");
|
imgId = replaceImgId;
|
imageIds.Add(imgId);
|
continue;
|
}
|
}
|
if (imgDic.ContainsKey(img))
|
{
|
imgId = imgDic[img];
|
}
|
else
|
{
|
imgId = UploadImg(yzToken, img);
|
|
imgDic.Add(img, imgId);
|
}
|
if (imgId == 0)
|
{//上传失败
|
continue;
|
}
|
imageIds.Add(imgId);
|
}
|
yzPara.image_ids = imageIds;
|
return yzPara;
|
}
|
|
/// <summary>
|
/// 代发方案铺货
|
/// </summary>
|
/// <param name="taskInfo"></param>
|
/// <param name="aliToken"></param>
|
/// <param name="yzToken"></param>
|
/// <param name="filter"></param>
|
/// <returns></returns>
|
public async Task<bool> DaiFaRunDistribution(DistributionHistory taskInfo, string aliToken, string yzToken, string yzShopId, List<ProductFilter> filter)
|
{
|
DistributionHistory finalHis = new DistributionHistory();
|
try
|
{
|
//任务状态改成执行中
|
DistributionHistory distributionHistory = new DistributionHistory()
|
{
|
DisStatus = 1,
|
RunTime = DateTime.Now
|
};
|
new DistributionHistoryDAL().Update(distributionHistory, t => new { t.DisStatus, t.RunTime }, t => t.Id == taskInfo.Id);
|
//获取1688商品详情
|
FenXiaoProductInfoGetRequest request = new FenXiaoProductInfoGetRequest()
|
{
|
offerId = long.Parse(taskInfo.ProductId)
|
};
|
var response = AliabaClient.Execute(request, aliToken);
|
if (response.IsNull() || !response.Success)
|
{//获取商品详情失败
|
LogUtil.Info($"获取商品详情失败:{taskInfo.Id}", "铺货错误");
|
finalHis.DisStatus = 3;
|
finalHis.Memo = "获取商品详情失败:" + (response.IsNull() ? "null" : response.ErrorMsg);
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
//判断1688商品状态
|
if (response.productInfo.status != "published")
|
{//不可铺货
|
LogUtil.Info($"商品状态不对:{response.productInfo.status}", "铺货错误");
|
finalHis.DisStatus = 3;
|
finalHis.Memo = "商品状态不对:" + (response.productInfo.status);
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
if (!response.productInfo.productSaleInfo.supportOnlineTrade)
|
{
|
LogUtil.Info($"不支持网上交易:{response.productInfo.productSaleInfo.supportOnlineTrade}", "铺货错误");
|
finalHis.DisStatus = 3;
|
finalHis.Memo = "商品不支持网上交易";
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
StringBuilder imgError = new StringBuilder();
|
//商品图片
|
finalHis.ProImg = response.productInfo.productImage.images[0];
|
//string imgMsg = FilterImg(filter, finalHis.ProImg);
|
//if (!imgMsg.IsNullOrEmpty())
|
//{
|
// imgError.Append($"主图:[{imgMsg}]");
|
//}
|
//商品title
|
finalHis.ProTitle = response.productInfo.subject;
|
|
//根据规则调整字段
|
var aliPro = response.productInfo;
|
|
//是否包邮
|
bool isPost = IsPost(aliPro);
|
finalHis.IsFreeShipping = isPost ? 1 : 0;
|
//调用有赞新增商品接口 youzan.item.add.1.0.1
|
YouZanItemAddRequest yzReq = new YouZanItemAddRequest();
|
yzReq.param = DaiFaGetAliInfoToYz(aliPro, yzToken, filter, ref imgError);
|
var yzRsp = YouZanClient.Execute(yzReq, yzToken);
|
if (yzRsp.IsNull() || !yzRsp.success)
|
{//新增失败
|
finalHis.DisStatus = 3;
|
finalHis.Memo = yzRsp.IsNull() ? "有赞接口错误" : yzRsp.message;
|
LogUtil.Info($"有赞错误:{finalHis.Memo}--request:" + JSONUtil.ObjectToJson(yzReq), "铺货错误");
|
}
|
else
|
{
|
//有赞返回商品id
|
string yzProductId = yzRsp.data.item_id;
|
|
//添加分销商品关系
|
FenXiaoOutproductRelationAddRequest relaReq = new FenXiaoOutproductRelationAddRequest()
|
{
|
channel = "youzan",
|
offerId = long.Parse(taskInfo.ProductId),
|
outItemCode = yzProductId,
|
outShopCode = yzShopId
|
};
|
var relaRsp = AliabaClient.Execute(relaReq, aliToken);
|
if (relaRsp.IsNull() || !relaRsp.Success)
|
{
|
finalHis.DisStatus = 3;
|
finalHis.Memo = "添加分销商品关系失败:" + (relaRsp.IsNull() ? "null" : relaRsp.ErrorMsg);
|
LogUtil.Info($"添加分销商品关系失败:{JSONUtil.ObjectToJson(relaReq)}--返回:" + (relaRsp.IsNull() ? "null" : relaRsp.ErrorMsg), "铺货错误");
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
//修改任务状态
|
finalHis.DisStatus = 2;
|
finalHis.YzItemId = yzProductId;
|
finalHis.YzAlias = yzRsp.data.alias;
|
string yzskuInfo = UpdateYzSku(yzProductId, yzToken);
|
|
if (!imgError.IsNull() && imgError.Length > 0)
|
{
|
finalHis.Memo = imgError.ToString();
|
}
|
yzskuInfo = yzskuInfo.IsNullOrEmpty() ? JSONUtil.ObjectToJson(yzReq.param.sku_list) : yzskuInfo;
|
//记录1688id与有赞id的关系
|
DistributionRelation distributionRelation = new DistributionRelation()
|
{
|
Id = TopUtil.GetId().ToString(),
|
SourceProduct = taskInfo.ProductId,
|
YzProduct = yzProductId,
|
YzAlias = yzRsp.data.alias,
|
ReStatus = 1,
|
InstanceCode = response.productInfo.sellerId.ToString(),
|
CreateTime = DateTime.Now,
|
AliskuInfo = JSONUtil.ObjectToJson(response.productInfo.productSkuInfos),
|
YzskuInfo = yzskuInfo,
|
ProSource = 1
|
};
|
new DistributionRelationDAL().Insert(distributionRelation);
|
//关注商品
|
AlibabaProductFollowRequest followReq = new AlibabaProductFollowRequest()
|
{
|
productId = long.Parse(taskInfo.ProductId)
|
};
|
var followRsp = AliabaClient.Execute(followReq, aliToken);
|
if (followRsp.IsNull() || followRsp.message != "success")
|
{
|
LogUtil.Info($"关注商品{taskInfo.ProductId}失败,错误:" + (followRsp.IsNull() ? "null" : followRsp.message), "铺货错误");
|
}
|
//修改代发商品表铺货状态
|
DaifaProduct daifaProduct = new DaifaProduct()
|
{
|
IsDistribute = 1
|
};
|
new DaifaProductDAL().Update(daifaProduct, i => new { i.IsDistribute }, t => t.Id == taskInfo.ProductId);
|
}
|
}
|
catch (Exception e)
|
{
|
finalHis.DisStatus = 3;
|
finalHis.Memo = e.Message;
|
LogUtil.Info($"错误:{e.ToString()}", "铺货错误");
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo }, t => t.Id == taskInfo.Id);
|
return false;
|
}
|
|
//修改任务状态
|
new DistributionHistoryDAL().Update(finalHis, t => new { t.DisStatus, t.Memo, t.ProImg, t.ProTitle, t.YzAlias, t.YzItemId, t.IsFreeShipping }, t => t.Id == taskInfo.Id);
|
return true;
|
}
|
|
#region 是否包邮
|
public bool IsPost(FenXiaoProductInfoGetDomain productInfo)
|
{
|
if (productInfo.productShippingInfo.freightTemplateID == 1)
|
{
|
return true;
|
}
|
double PfMinPrice = productInfo.productSaleInfo.priceRanges.Max(t => t.price);
|
double FxMinPrice = productInfo.productSkuInfos.Min(t => t.consignPrice);
|
if (FxMinPrice > PfMinPrice && FxMinPrice - PfMinPrice > 2)
|
{
|
return true;
|
}
|
return false;
|
}
|
|
#endregion
|
|
|
public static YouZanItemAddDomain DaiFaGetAliInfoToYz(FenXiaoProductInfoGetDomain aliPro, string yzToken, List<ProductFilter> filter, ref StringBuilder imgError)
|
{
|
YouZanItemAddDomain yzPara = new YouZanItemAddDomain();
|
yzPara.item_no = aliPro.productID.ToString();
|
yzPara.desc = FilterMsg(filter, aliPro.description);
|
//yzPara.start_sale_num = aliPro.saleInfo.minOrderQuantity;
|
yzPara.start_sale_num = 1;
|
DeliverySetting deliverySetting = new DeliverySetting()
|
{
|
express = true
|
};
|
//售后信息
|
PostSaleParam postSaleParam = new PostSaleParam()
|
{ is_support_barter = 0 };
|
//是否支持7天无理由退货
|
//postSaleParam.support_unconditional_return = aliPro.sevenDaysRefunds;
|
bool support_unconditional_return = false;
|
foreach (var m in aliPro.productExtendInfos)
|
{
|
if (!"buyerProtection,buyerProtectionDistribution".Contains(m.key) || m.value.IsNullOrEmpty())
|
{
|
continue;
|
}
|
List<string> arr = JSONUtil.JsonToObject<List<string>>(m.value);
|
foreach (var a in arr)
|
{
|
if (a.Contains("wlybt"))
|
{
|
support_unconditional_return = true;
|
break;
|
}
|
}
|
if (support_unconditional_return) break;
|
}
|
postSaleParam.support_unconditional_return = support_unconditional_return;
|
yzPara.post_sale_param = postSaleParam;
|
//获取默认运费模板
|
var appset = new AppsetDAL().ListGet(t => t.Id != null);
|
ItemDeliveryParam itemDeliveryParam = new ItemDeliveryParam
|
{
|
delivery_setting = deliverySetting,
|
delivery_template_id = long.Parse(appset[0].YzPostMould)
|
};
|
yzPara.item_delivery_param = itemDeliveryParam;
|
//默认付款减库存
|
yzPara.stock_deduct_mode = 1;
|
yzPara.title = FilterMsg(filter, aliPro.subject);
|
yzPara.is_display = 0;
|
//商品库存, 无sku情况下库存必填,如果有sku则无效
|
yzPara.quantity = long.Parse(aliPro.productSkuInfos.Min(t => t.amountOnSale).ToString());
|
List<SkuList> skuLists = new List<SkuList>();
|
List<SkuValueProps> skuValues = new List<SkuValueProps>();
|
Dictionary<string, long> imgDic = new Dictionary<string, long>();
|
bool isImgShow = false;
|
long replaceImgId = 0;
|
foreach (var aliSkuItem in aliPro.productSkuInfos)
|
{
|
if (aliSkuItem.consignPrice <= 0)
|
{
|
continue;
|
}
|
List<SkuProps> skuPropsList = new List<SkuProps>();
|
aliSkuItem.attributes = aliSkuItem.attributes.OrderBy(t => t.skuImageUrl.IsNullOrEmpty()).ToList();
|
int index = 0;
|
foreach (var attr in aliSkuItem.attributes)
|
{//属性信息
|
index++;
|
SkuProps skuProps = new SkuProps()
|
{
|
prop_value_name = attr.attributeValue,
|
prop_name = attr.attributeName,
|
prop_name_id = 0,
|
prop_value_id = attr.attributeID
|
};
|
skuPropsList.Add(skuProps);
|
if (index == 1 && !attr.skuImageUrl.IsNullOrEmpty())
|
{
|
isImgShow = true;
|
//处理有赞sku图片信息
|
long imgId = 0;
|
if (imgDic.ContainsKey(attr.skuImageUrl))
|
{
|
imgId = imgDic[attr.skuImageUrl];
|
}
|
else
|
{
|
imgId = UploadImg(yzToken, attr.skuImageUrl);
|
//string imgstr = ImgCheck(filter, attr.skuImageUrl);
|
//if (!imgstr.IsNullOrEmpty())
|
//{
|
// imgError.Append($"sku:[{imgstr}]");
|
//}
|
imgDic.Add(attr.skuImageUrl, imgId);
|
}
|
SkuValueProps skuValueProps = new SkuValueProps()
|
{
|
name = attr.attributeValue,
|
id = attr.attributeID
|
};
|
if (imgId > 0)
|
{
|
replaceImgId = replaceImgId == 0 ? imgId : replaceImgId;
|
skuValueProps.img_id = imgId;
|
}
|
skuValues.Add(skuValueProps);
|
}
|
}
|
//价格计算。上涨50%
|
long price = long.Parse(Math.Ceiling(aliSkuItem.consignPrice * 100 + aliSkuItem.consignPrice * 100 * 0.5).ToString());
|
SkuList skuitem = new SkuList()
|
{
|
//price = long.Parse((Math.Round(aliSkuItem.price * 100, 2)).ToString()),
|
price = price,
|
sku_no = aliSkuItem.skuId.ToString(),
|
stock_num = aliSkuItem.amountOnSale,
|
sku_props = skuPropsList
|
};
|
skuLists.Add(skuitem);
|
}
|
if (!skuValues.IsNull() && skuValues.Count > 0)
|
{
|
yzPara.sku_value_props = skuValues;
|
yzPara.sku_picture_display_config = isImgShow;
|
}
|
//sku信息
|
yzPara.sku_list = skuLists;
|
|
ItemPriceParam itemPriceParam = new ItemPriceParam()
|
{
|
price = long.Parse(Math.Round(aliPro.productSaleInfo.priceRanges[0].price * 100, 2).ToString())
|
};
|
yzPara.item_price_param = itemPriceParam;
|
//处理商品图片
|
List<long> imageIds = new List<long>();
|
int currentIndex = 0;
|
foreach (var img in aliPro.productImage.images)
|
{
|
currentIndex++;
|
long imgId = 0;
|
if (currentIndex == 1)
|
{
|
//检测第一张主图
|
string imgstr = ImgCheck(filter, aliPro.productImage.images[0]);
|
if (!imgstr.IsNullOrEmpty())
|
{
|
imgError.Append($"主图:[{imgstr}]");
|
imgId = replaceImgId;
|
imageIds.Add(imgId);
|
continue;
|
}
|
}
|
if (imgDic.ContainsKey(img))
|
{
|
imgId = imgDic[img];
|
}
|
else
|
{
|
imgId = UploadImg(yzToken, img);
|
//string imgstr = ImgCheck(filter, img);
|
//if (!imgstr.IsNullOrEmpty())
|
//{
|
// imgError.Append($"主图:[{imgstr}]");
|
//}
|
imgDic.Add(img, imgId);
|
}
|
if (imgId == 0)
|
{//上传失败
|
continue;
|
}
|
imageIds.Add(imgId);
|
}
|
yzPara.image_ids = imageIds;
|
return yzPara;
|
}
|
|
|
#region 更新有赞信息
|
private string UpdateYzSku(string yzItemId, string yzToken)
|
{
|
////获取有赞商品详情
|
YouZanProductDetailGetRequest detailReq = new YouZanProductDetailGetRequest()
|
{
|
item_id = long.Parse(yzItemId)
|
};
|
var detailRs = YouZanClient.Execute(detailReq, yzToken);
|
if (detailRs.IsNull() || !detailRs.success)
|
{
|
return null;
|
}
|
else
|
{
|
return JSONUtil.ObjectToJson(detailRs.data.sku_list);
|
}
|
}
|
|
#endregion
|
|
/// <summary>
|
/// 图片上传有赞
|
/// </summary>
|
/// <param name="urls"></param>
|
/// <returns></returns>
|
private static long UploadImg(string yzToken, string url)
|
{
|
if (url.IsNullOrEmpty())
|
{
|
return 0;
|
}
|
string[] urlArr = url.Split('.');
|
string fileName = "D://Img/" + Guid.NewGuid().ToString() + $".{urlArr[urlArr.Length - 1]}";
|
WebClient MyWebClient = new WebClient();
|
if (!url.StartsWith("http"))
|
{
|
url = "https://cbu01.alicdn.com/img/" + url;
|
}
|
MyWebClient.DownloadFile(url, fileName);
|
//上传至有赞
|
UploadImageResponse response = YouZanUploadeImg.UploadImage(yzToken, fileName);
|
|
if (!response.IsNull() && response.success)
|
{
|
return response.data.image_id;
|
}
|
return 0;
|
}
|
|
/// <summary>
|
/// 添加铺货任务
|
/// </summary>
|
/// <param name="request"></param>
|
/// <returns></returns>
|
public async Task<bool> AddDistributionTask(ProductDistributionRequest request)
|
{
|
//判断是否有生成中的
|
var history = new DistributionHistoryDAL().ListGet(t => request.ProductId.Contains(t.ProductId) && (t.DisStatus == 0 || t.DisStatus == 1));
|
List<DistributionHistory> tasks = new List<DistributionHistory>();
|
string taskId = TopUtil.GetId().ToString();
|
foreach (var pid in request.ProductId)
|
{
|
if (history.Any(t => t.ProductId == pid))
|
{//正在执行中或未执行的跳过
|
continue;
|
}
|
DistributionHistory distributionHistory = new DistributionHistory()
|
{
|
Id = TopUtil.GetId().ToString(),
|
ProductId = pid,
|
CreateTime = DateTime.Now,
|
TaskId = taskId,
|
DisStatus = 0,
|
ProSource = request.ProSource
|
};
|
tasks.Add(distributionHistory);
|
}
|
if (!tasks.IsNull() && tasks.Count > 0)
|
{
|
//插入记录表
|
new DistributionHistoryDAL().InsertRange(tasks);
|
//发执行mq
|
ProductDistributionMq productDistributionMq = new ProductDistributionMq()
|
{
|
TaskId = taskId
|
};
|
string ret = MQClientFullChannel.SendMessageStatic(0, "product_distribution", JSONUtil.ObjectToJson(productDistributionMq));
|
if (ret != "ok")
|
{
|
LogUtil.Info($"发MQ失败:{taskId}", "铺货任务mq失败");
|
return false;
|
}
|
return true;
|
}
|
return false;
|
}
|
|
/// <summary>
|
/// 解除商品关联
|
/// </summary>
|
/// <param name="aliProductId"></param>
|
/// <param name="aliToken"></param>
|
/// <returns></returns>
|
|
public bool RemoveRelatProduct(string aliProductId, string aliToken, string yzToken, DistributionHistory history, string yzShopId)
|
{
|
try
|
{
|
//取消关注商品
|
AlibabaProductUnFollowRequest request = new AlibabaProductUnFollowRequest()
|
{
|
productId = long.Parse(aliProductId)
|
};
|
var response = AliabaClient.Execute(request, aliToken);
|
if (response.IsNull() || response.message != "success")
|
{
|
return false;
|
}
|
if (history.ProSource == 1)
|
{//代发方案商品,需额外解除分销关系
|
FenXiaoOutproductRelationDeleteRequest deReq = new FenXiaoOutproductRelationDeleteRequest()
|
{
|
channel = "youzan",
|
offerId = long.Parse(history.ProductId),
|
outItemCode = history.YzItemId,
|
outShopCode = yzShopId
|
};
|
var relaRsp = AliabaClient.Execute(deReq, aliToken);
|
if (relaRsp.IsNull() || !relaRsp.Success)
|
{
|
return false;
|
}
|
DaifaProduct daifaProduct = new DaifaProduct()
|
{
|
IsDistribute = 0
|
};
|
new DaifaProductDAL().Update(daifaProduct, i => new { i.IsDistribute }, t => t.Id == history.ProductId);
|
}
|
//表里关系解除关注
|
DistributionRelation distributionRelation = new DistributionRelation()
|
{
|
ReStatus = 0
|
};
|
new DistributionRelationDAL().Update(distributionRelation, i => new { i.ReStatus }, t => t.SourceProduct == aliProductId);
|
//删除有赞商品
|
YouZanItemDeleteRequest youZanItemDeleteRequest = new YouZanItemDeleteRequest()
|
{
|
item_id = long.Parse(history.YzItemId)
|
};
|
var youZanItemDeleteRsp = YouZanClient.Execute(youZanItemDeleteRequest, yzToken);
|
if (youZanItemDeleteRsp.IsNull() || !youZanItemDeleteRsp.success || !youZanItemDeleteRsp.data.is_success)
|
{
|
LogUtil.Info($"id:{history.YzItemId}--error:{youZanItemDeleteRsp.message}", "有赞商品删除error");
|
}
|
|
return true;
|
|
}
|
catch (Exception e)
|
{
|
LogUtil.Info("aliProductId:" + aliProductId + "--" + e.ToString(), "解除商品关联error");
|
return false;
|
}
|
}
|
|
public static string FilterMsg(List<ProductFilter> filter, string msg)
|
{
|
try
|
{
|
foreach (var fi in filter)
|
{
|
string replaceStr = fi.Replace.IsNullOrEmpty() ? "" : fi.Replace;
|
msg = msg.Replace(fi.KeyWord, replaceStr);
|
}
|
}
|
catch (Exception e)
|
{
|
LogUtil.Info(e.ToString(), "过滤关键词error");
|
}
|
return msg;
|
}
|
|
public static string ImgCheck(List<ProductFilter> filter, string imgUrl)
|
{
|
if (!imgUrl.StartsWith("http"))
|
{
|
imgUrl = "https://cbu01.alicdn.com/img/" + imgUrl;
|
}
|
string imgMsg = FilterImg(filter, imgUrl);
|
if (!imgMsg.IsNullOrEmpty())
|
{
|
return imgMsg;
|
}
|
return null;
|
}
|
|
#region 处理商品详情图片
|
public static string FilterDesc(List<ProductFilter> filter, string desc)
|
{
|
HtmlDocument doc = new HtmlDocument();
|
doc.LoadHtml(desc);
|
var imgNode = doc.DocumentNode.SelectNodes("//img");
|
foreach (var imgItem in imgNode)
|
{
|
var imgsrc = imgItem.Attributes["src"].Value;
|
string imgError = ImgCheck(filter, imgsrc);
|
if (!imgError.IsNullOrEmpty())
|
{
|
imgItem.Remove();
|
}
|
}
|
return doc.DocumentNode.OuterHtml;
|
}
|
|
#endregion
|
|
#region 图片关键词过滤
|
public static string FilterImg(List<ProductFilter> filter, string imgUrl)
|
{
|
try
|
{
|
StringBuilder keyError = new StringBuilder();
|
//百度ai图片识别
|
var res = BaiDuClient.WebImageUrl(imgUrl);
|
if (!res.IsSuccess)
|
{
|
LogUtil.Info($"百度ai错误:{res.error_msg}--图片:{imgUrl}", "过滤关键词error");
|
}
|
if (res.words_result_num <= 0)
|
{
|
return null;
|
}
|
var msgList = res.words_result.Select(t => t.words).ToList();
|
string msg = string.Join(',', msgList);
|
var filterKey = filter.Where(t => msg.Contains(t.KeyWord)).ToList();
|
if (!filterKey.IsNull() && filterKey.Count > 0)
|
{
|
var filterList = filterKey.Select(t => t.KeyWord).ToList();
|
return string.Join(',', filterList);
|
}
|
}
|
catch (Exception e)
|
{
|
LogUtil.Info(e.ToString(), "过滤关键词error");
|
}
|
return null;
|
}
|
#endregion
|
|
#region 处理sku不对应的情况
|
private List<SkuList> ResetSkuInfo(List<SkuInfosItem> aliSkuinfo, List<SkuList> youzanSkuInfo)
|
{
|
try
|
{
|
Dictionary<string, List<string>> attrbuteDic = new Dictionary<string, List<string>>();
|
|
}
|
catch (Exception e)
|
{
|
|
}
|
return null;
|
}
|
|
#endregion
|
|
public List<string> GetYzItemIdByTag(ListGetDistributionHistoryRequest request, string yzToken)
|
{
|
List<string> itemList = new List<string>();
|
int pageSize = 50;
|
int currentPage = 1;
|
int totalPage = 1;
|
while (currentPage <= totalPage)
|
{
|
|
YouZanItemCommonSearchRequest itemReq = new YouZanItemCommonSearchRequest()
|
{
|
page_size = pageSize,
|
page_no = currentPage,
|
tag_ids = request.TagIds,
|
is_display = request.IsDisplay
|
};
|
var itemRsp = YouZanClient.Execute(itemReq, yzToken);
|
currentPage++;
|
if (itemRsp.IsNull() || !itemRsp.success)
|
{
|
continue;
|
}
|
//计算总页数
|
if (totalPage == 1)
|
{
|
totalPage = itemRsp.data.paginator.total_count % pageSize == 0 ? itemRsp.data.paginator.total_count / pageSize : (itemRsp.data.paginator.total_count / pageSize) + 1;
|
}
|
foreach (var yzpro in itemRsp.data.items)
|
{
|
if (!itemList.Contains(yzpro.item_id.ToString()))
|
{
|
itemList.Add(yzpro.item_id.ToString());
|
}
|
}
|
}
|
return itemList;
|
|
}
|
|
|
|
//public void Dispose()
|
//{
|
// return base.dis
|
//}
|
}
|
}
|