Files
KJD/TEMUKJD/BLL/ImportConverters/ConverterWXToPddV4.cs
T

466 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using AllBase.Model.Result;
using AllBase.Model.Result.PDDResult;
using NaiBa.Util.Extension;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace TemuKJD.BLL.ImportConverters
{
/// <summary>
/// 微信转拼多多数据源 V4版本
/// 针对微信商品详情API(/channels/ec/product/get)返回的完整数据结构
///
/// 数据结构特点:
/// - 顶层为 { detail: { product: { product_key, info, product_skus, ... } } }
/// - info 节点包含商品基本信息、主图、详情图、参数、SKU列表等
/// - product_skus 节点包含完整的SKU信息(含库存、价格、规格)
/// - product_sale_attrs 节点包含销售属性(颜色、尺码)
/// - extra_service 节点包含售后服务信息
/// - qualification_list 节点包含资质信息
/// </summary>
internal class ConverterWXToPddV4 : GoodsConverterBase
{
private JObject _jsonRoot;
private JObject _productNode; // detail.product
private JObject _infoNode; // detail.product.info
private JArray _skuList; // detail.product.info.product_skus
private JArray _saleAttrs; // detail.product.info.product_sale_attrs
public override string ConverterName => "微信转拼多多数据源 V4";
public override PlatformType Platform => PlatformType.WX;
protected override bool IsMatchProvider()
{
try
{
_jsonRoot = JsonConvert.DeserializeObject<JObject>(RawData);
if (_jsonRoot == null) return false;
// 1. 检查是否为详情API格式(detail.product 结构)
var detail = _jsonRoot.SelectToken("$.detail") as JObject;
if (detail == null) return false;
var product = detail.SelectToken("$.product") as JObject;
if (product == null) return false;
// 2. 检查 product_key 是否存在
var productKey = product.SelectToken("$.product_key") as JObject;
if (productKey == null) return false;
var productId = productKey.SelectToken("$.product_id")?.ToString();
if (string.IsNullOrEmpty(productId)) return false;
// 3. 检查 info 节点是否存在
var info = product.SelectToken("$.info") as JObject;
if (info == null) return false;
// 4. 检查是否有标题
var title = info.SelectToken("$.title")?.ToString();
if (string.IsNullOrEmpty(title)) return false;
// 5. 检查是否有SKU列表
var skus = product.SelectToken("$.product_skus") as JArray;
if (skus == null || skus.Count == 0) return false;
// 缓存节点
_productNode = product;
_infoNode = info;
_skuList = skus;
_saleAttrs = info.SelectToken("$.product_sale_attrs") as JArray;
return true;
}
catch
{
return false;
}
}
protected override PDDFrontProductInfo5 ConverterProvider()
{
var product = new PDDFrontProductInfo5
{
Platform = Platform,
GoodsId = ParseGoodsId()
};
product.ListingTime = GetListingTime();
// ========== 1. 商品基本信息 ==========
product.Title = GetStringValue(_infoNode, "title");
product.Description = GetStringValue(_infoNode, "short_title");
if (string.IsNullOrEmpty(product.Description))
{
product.Description = GetStringValue(_infoNode, "ai_gen_short_title");
}
// ========== 2. 品牌信息 ==========
product.BrandId = GetLongValue(_infoNode, "brand_id");
// ========== 3. 类目信息 ==========
product.CategoryId = GetCategoryId();
product.CategoryPath = GetCategoryPath();
// ========== 4. 主图 ==========
product.MainImages = GetMainImages();
// ========== 5. 详情图 ==========
product.DetailImages = GetDetailImages();
// ========== 6. 商品属性 ==========
product.Propertys = GetProperties();
// ========== 7. SKU和规格信息 ==========
var skuResult = GetSkusAndSpecs();
product.Skus = skuResult.Item1;
product.Specs = skuResult.Item2;
// ========== 8. 其他信息 ==========
product.ThumbUrl = product.MainImages.FirstOrDefault() ?? string.Empty;
product.MallId = 0;
product.Price = GetMinPrice();
product.Videos = GetVideoUrls();
return product;
}
#region 核心字段解析
/// <summary>
/// 解析商品ID
/// </summary>
private long ParseGoodsId()
{
var productId = _productNode.SelectToken("$.product_key.product_id")?.ToString();
if (long.TryParse(productId, out var result))
return result;
// 回退到文件路径
return Path.GetFileNameWithoutExtension(FilePath).ParseToLong();
}
/// <summary>
/// 获取类目ID(取最细分类目)
/// </summary>
private int GetCategoryId()
{
var category = _infoNode["category"] as JArray;
if (category == null || category.Count == 0)
return 0;
// 取最后一个类目(最细分类目)
var lastCat = category.Last as JObject;
return lastCat?["cat_id"]?.Value<int>() ?? 0;
}
/// <summary>
/// 获取类目路径
/// </summary>
private List<int> GetCategoryPath()
{
var result = new List<int>();
var category = _infoNode["category"] as JArray;
if (category == null)
return result;
foreach (var cat in category)
{
var catId = cat["cat_id"]?.Value<int>();
if (catId.HasValue && catId.Value > 0)
result.Add(catId.Value);
}
return result;
}
/// <summary>
/// 获取主图列表
/// </summary>
private List<string> GetMainImages()
{
var result = new List<string>();
// 优先使用 head_img 数组
var headImg = _infoNode["head_img"] as JArray;
if (headImg != null && headImg.Count > 0)
{
foreach (var img in headImg)
{
var url = img?.Value<string>();
if (!string.IsNullOrEmpty(url))
result.Add(url);
}
return result;
}
// 回退到 head_img_infos
var headImgInfos = _infoNode["head_img_infos"] as JArray;
if (headImgInfos != null)
{
foreach (var img in headImgInfos)
{
var url = img["img_url"]?.Value<string>();
if (!string.IsNullOrEmpty(url))
result.Add(url);
}
}
return result;
}
/// <summary>
/// 获取详情图列表
/// </summary>
private List<string> GetDetailImages()
{
var result = new List<string>();
var detail = _infoNode["detail"] as JObject;
if (detail == null)
return result;
var detailImg = detail["detail_img"] as JArray;
if (detailImg == null)
return result;
foreach (var img in detailImg)
{
var url = img?.Value<string>();
if (!string.IsNullOrEmpty(url))
result.Add(url);
}
return result;
}
/// <summary>
/// 获取商品属性列表(从 param 节点解析)
/// </summary>
private List<Property> GetProperties()
{
var result = new List<Property>();
var param = _infoNode["param"] as JArray;
if (param == null)
return result;
foreach (var item in param)
{
var categorys = item["categorys"] as JArray;
if (categorys == null || categorys.Count < 2)
continue;
var key = categorys[0]?["name"]?.Value<string>();
var value = categorys[1]?["name"]?.Value<string>();
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
{
// 去重
if (!result.Any(p => p.Key == key))
{
result.Add(new Property
{
Key = key,
Value = value
});
}
}
}
return result;
}
/// <summary>
/// 获取视频URL列表
/// </summary>
private List<string> GetVideoUrls()
{
var result = new List<string>();
var headVideoInfo = _infoNode["head_video_info"] as JArray;
if (headVideoInfo == null)
return result;
foreach (var video in headVideoInfo)
{
var url = video["video_url"]?.Value<string>();
if (!string.IsNullOrEmpty(url))
result.Add(url);
}
return result;
}
private DateTime? GetListingTime()
{
string time = _infoNode["listing_time"].ToString();
if (time != null)
{
if (int.TryParse(time, out int v))
{
return NaiBa.Util.Helper.DateTimeHelper.IntStampToDateTime(v);
}
}
return null;
}
#endregion
#region SKU和规格解析
/// <summary>
/// 获取SKU和规格信息
/// </summary>
private Tuple<List<SkuItem>, List<SpecItem>> GetSkusAndSpecs()
{
var skuList = new List<SkuItem>();
var specList = new List<SpecItem>();
if (_skuList == null || _skuList.Count == 0)
return new Tuple<List<SkuItem>, List<SpecItem>>(skuList, specList);
// 收集所有规格
var specDict = new Dictionary<string, HashSet<string>>();
foreach (var sku in _skuList)
{
var skuObj = sku as JObject;
if (skuObj == null) continue;
// 获取 SKU 基本信息
var skuKey = skuObj["sku_key"] as JObject;
var skuInfo = skuObj["product_sku_info"] as JObject;
if (skuKey == null || skuInfo == null) continue;
var skuId = skuKey["sku_id"]?.Value<string>() ?? string.Empty;
var outSkuId = skuKey["out_sku_id"]?.Value<string>() ?? string.Empty;
// 解析销售属性
var saleParams = skuInfo["sale_param"] as JArray;
var specValues = new List<string>();
if (saleParams != null)
{
foreach (var param in saleParams)
{
var paramV2 = param["param_v2"] as JObject;
if (paramV2 == null) continue;
var attrName = paramV2["attr_name"]?.Value<string>() ?? string.Empty;
var attrValue = paramV2["attr_value_name"]?.Value<string>() ?? string.Empty;
if (!string.IsNullOrEmpty(attrName) && !string.IsNullOrEmpty(attrValue))
{
specValues.Add($"{attrName}:{attrValue}");
// 收集规格
if (!specDict.ContainsKey(attrName))
specDict[attrName] = new HashSet<string>();
specDict[attrName].Add(attrValue);
}
}
}
// 价格(单位:分)
var salePrice = skuInfo["sale_price"]?.Value<decimal>() ?? 0;
// 库存
var stockInfo = skuInfo["stock_info"] as JObject;
var stockNum = 0;
if (stockInfo != null)
{
var stockStr = stockInfo["stock_num"]?.Value<string>();
if (!string.IsNullOrEmpty(stockStr))
{
int.TryParse(stockStr, out stockNum);
}
}
// 缩略图
var thumbImg = skuInfo["thumb_img"]?.Value<string>() ?? string.Empty;
skuList.Add(new SkuItem
{
SkuId = !string.IsNullOrEmpty(outSkuId) ? outSkuId : skuId,
Spec = string.Join(";", specValues),
Price = salePrice / 100, // 分转元
OriginalPrice = salePrice.ToString(),
Stock = stockNum,
SpecImage = thumbImg
});
}
// 构建规格列表
foreach (var spec in specDict)
{
foreach (var value in spec.Value)
{
specList.Add(new SpecItem
{
SpecKey = spec.Key,
SpecValue = value,
SpecKeyId = 0,
SpecValueId = 0
});
}
}
return new Tuple<List<SkuItem>, List<SpecItem>>(skuList, specList);
}
/// <summary>
/// 获取最低价格(元)
/// </summary>
private decimal GetMinPrice()
{
if (_skuList == null || _skuList.Count == 0)
return 0;
var minPrice = decimal.MaxValue;
foreach (var sku in _skuList)
{
var skuObj = sku as JObject;
if (skuObj == null) continue;
var skuInfo = skuObj["product_sku_info"] as JObject;
if (skuInfo == null) continue;
var price = skuInfo["sale_price"]?.Value<decimal>() ?? 0;
if (price > 0 && price < minPrice)
minPrice = price;
}
// 回退到 sku_list.min_price
if (minPrice == decimal.MaxValue)
{
var skuListInfo = _infoNode["sku_list"] as JObject;
var minPriceToken = skuListInfo?["min_price"]?.Value<decimal>() ?? 0;
return minPriceToken / 100;
}
return minPrice > 0 ? minPrice / 100 : 0;
}
#endregion
#region 辅助方法
private string GetStringValue(JObject obj, string path)
{
return obj?.SelectToken(path)?.Value<string>() ?? string.Empty;
}
private long GetLongValue(JObject obj, string path)
{
var token = obj?.SelectToken(path);
if (token == null) return 0;
if (token.Type == JTokenType.String)
return long.TryParse(token.Value<string>(), out var result) ? result : 0;
return token.Value<long>();
}
#endregion
}
}