Files
KJD/TEMUKJD/KJDForms/ProductForms/TemuJitForm.cs
T

620 lines
31 KiB
C#

using AllBase;
using AllBase.Model.Result;
using NaiBa.Util.Extension;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TemuKJD.BaseForms;
using TemuKJD.BLL;
using TemuKJD.Extension;
using TemuKJD.KJDForms.AdminForms;
using TemuKJD.KJDForms.ShopForms;
using TemuKJD.ToolForms;
using Work;
namespace TemuKJD.KJDForms.ProductForms
{
public partial class TemuJitForm : Form
{
SetJitConfig setJitConfig = null;
public CancellationTokenSource cancellationTokenSource { get; set; } = null;
public List<ShopLoginInfo> lstAdminShopInfo { get; set; } = new List<ShopLoginInfo>();
/// <summary>
/// 生命周期商品列表
/// </summary>
public List<TemuForChainProductInfo> lstChainProdInfo = new List<TemuForChainProductInfo>();
/// <summary>
/// 商品合规信息列表
/// </summary>
public List<complianceInfo> lstComplianceInfo = new List<complianceInfo>();
public TemuJitForm()
{
InitializeComponent();
}
private void TemuJitForm_Load(object sender, EventArgs e)
{
this.dgvShop.AddSelectorColumn("colSelect");
this.dgvPriceCheck.AddSelectorColumn("colCheck");
this.dgvPriceCheck.AddImgColumn("colProductSkcPic", "colImgUrl");
this.dtpEndTime.Value = DateTime.Now.Date.AddDays(1).AddMilliseconds(-1);
this.dtpStartTime.Value = DateTime.Now.Date.AddDays(-7);
setJitConfig = NaiBa.Util.Helper.ConfigHelper.LoadConfig<SetJitConfig>("set_jit_config");
if (setJitConfig == null)
setJitConfig = new SetJitConfig();
this.txtNotes.Text = setJitConfig.SearchNotes;
this.txtShopId.Text = setJitConfig.SearchShopId;
this.txtShopName.Text = setJitConfig.SearchShopName;
this.chkSearchAllShop.Checked = setJitConfig.SearchAllShop;
this.txtNotes.TextChanged += Txt_TextChanged;
this.txtShopId.TextChanged += Txt_TextChanged;
this.txtShopName.TextChanged += Txt_TextChanged;
this.chkSearchAllShop.CheckedChanged += Txt_TextChanged;
}
private void Txt_TextChanged(object sender, EventArgs e)
{
setJitConfig.SearchNotes = this.txtNotes.Text.Trim();
setJitConfig.SearchShopId = this.txtShopId.Text.Trim();
setJitConfig.SearchShopName = this.txtShopName.Text.Trim();
setJitConfig.SearchAllShop = this.chkSearchAllShop.Checked;
NaiBa.Util.Helper.ConfigHelper.SaveConfig("set_jit_config", setJitConfig);
}
private void TemuJitForm_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
this.pbShopLoading.Visible = true;
SearchShop(this.ucSplitPage1.CurrentPage);
}
}
private void btnRefreshShop_Click(object sender, EventArgs e)
{
if (this.ucSplitPage1.CurrentPage != 1)
this.ucSplitPage1.CurrentPage = 1;
else
SearchShop(1);
}
private void ucSplitPage1_PageChange(object obj)
{
SearchShop(this.ucSplitPage1.CurrentPage);
}
private void btnEmpty_Click(object sender, EventArgs e)
{
txtNotes.Text = txtShopId.Text = txtShopName.Text = "";
}
public void SearchShop(int page)
{
List<string> userShopIdList = dgvShop.Rows.Cast<DataGridViewRow>()
.Where(r => r.Cells["colSelect"].Value.ParseToBool())
.Select(r => r.Cells["colShopId"].Value.ParseToString() + r.Cells["colUser"].Value.ParseToString()).ToList();
if (InvokeRequired)
{
Invoke(new Action(() =>
{
this.pbShopLoading.Visible = true;
this.dgvShop.Rows.Clear();
lstAdminShopInfo.Clear();
}));
}
else
{
this.pbShopLoading.Visible = true;
this.dgvShop.Rows.Clear();
lstAdminShopInfo.Clear();
}
Task.Run(() =>
{
int pageCount;
var list = AdminGetServerShopLst(out pageCount, page);
lstAdminShopInfo.AddRange(list);
this.ucSplitPage1.TotalPage = pageCount;
foreach (var shop in lstAdminShopInfo)
{
bool canUse = shop.LoginStatus2 == "国际版在线";
Invoke(new Action(() =>
{
int rowIndex = this.dgvShop.Rows.Add(
userShopIdList.Contains(shop.ShopId + shop.UserName),
shop.UserName,
shop.LoginName,
shop.ShopId,
shop.ShopAccount,
shop.Notes,
canUse ? "在线" : "掉线",
canUse,
string.Empty
);
displayShopStatus(shop);
}));
}
Invoke(new Action(() =>
{
this.pbShopLoading.Visible = false;
}));
});
}
public List<ShopLoginInfo> AdminGetServerShopLst(out int pageCount, int page = 1, int pageSize = 50)
{
List<ShopLoginInfo> list = new List<ShopLoginInfo>();
pageCount = 1;
var url = BaseClass.BuildObjString("shop/admin_get_shop_list");
if (BaseClass.SaLevel > 1 && !chkSearchAllShop.Checked)
url = BaseClass.BuildObjString("shop/sub_sa_get_select_prod_shop");
var data = UserLogin.GetSignaturex() +
"&page=" + page +
"&page_size=" + pageSize +
"&shop_ids=" + txtShopId.Text.Trim().Trim(',') +
"&shop_names=" + txtShopName.Text.Trim().Trim(',') +
"&search_notes=" + txtNotes.Text.Trim().Trim(',');
if (BaseClass.SaLevel > 1 && !chkSearchAllShop.Checked)
data += "&operate_sub_sa_name=" + BaseClass.UserName;
var html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html)
|| !html.Contains("shop_id") || !html.Contains("shop_account") || !html.Contains("login_pass"))
{
return list;
}
int count = BaseRegex.GetIntJson(ref html, "count");
pageCount = Math.Ceiling(1.0 * count / pageSize).ParseToInt();
pageCount = Math.Max(pageCount, 1);
return ShopBLL.DeserializationShop(html);
}
void displayShopStatus(ShopLoginInfo shop)
{
bool canUse = shop.LoginStatus2 == "国际版在线";
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colLoginName"].Value.ParseToString() == shop?.LoginName);
foreach (var row in rows)
{
row.Cells["colCanUse"].Value = canUse;
row.Cells["colLoginStatus"].Value = canUse ? "在线" : "掉线";
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).Style.ForeColor = canUse ? Color.Green : Color.Red;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).LinkColor = canUse ? Color.Green : Color.Red;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).ActiveLinkColor = canUse ? Color.LightGreen : Color.OrangeRed;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).VisitedLinkColor = canUse ? Color.DarkGreen : Color.DarkRed;
}
}
private void dgvShop_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvShop.Columns[e.ColumnIndex].HeaderText;
string loginName = dgvShop.Rows[e.RowIndex].Cells["colLoginName"].Value.ParseToString();
string accountId = dgvShop.Rows[e.RowIndex].Cells["colShopId"].Value.ParseToString();
var shop = lstAdminShopInfo.FirstOrDefault(v => v.LoginName == loginName && v.ShopId == accountId);
switch (headerText)
{
case "登录":
case "状态":
{
AdminShopLoginForm shopLoginForm = new AdminShopLoginForm(shop);
shopLoginForm.openType = EnumOpenType.login;
shopLoginForm.SaveComplete += shopLoginForm_SaveComplete;
shopLoginForm.ShowDialog();
}
break;
default:
dgvShop.Rows[e.RowIndex].Cells["colSelect"].Value = !(bool)dgvShop.Rows[e.RowIndex].Cells["colSelect"].Value;
break;
}
}
private void shopLoginForm_SaveComplete(object obj)
{
var shop = obj as ShopLoginInfo;
if (shop == null)
return;
displayShopStatus(shop);
}
private void btnSearchPrice2_Click(object sender, EventArgs e)
{
SearchPrice("待创建首单");
}
private void SearchPrice(string type = "待创建首单")
{
var selectShopIdLst = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colSelect"].Value.ParseToBool() == true)
.Select(r => r.Cells["colShopId"].Value.ParseToString()).Distinct().ToList();
var shops = this.lstAdminShopInfo.Where(s => selectShopIdLst.Contains(s.ShopId)).ToList();
if (shops.Count == 0)
{
BaseMsgForm.ShowError("没有选择店铺!");
return;
}
if (chkSearchTime.Checked)
{
if (dtpStartTime.Value.Date.AddMonths(3) < dtpEndTime.Value.Date.AddDays(1).AddMilliseconds(-1))
{
BaseMsgForm.ShowError("一次最多只支持查询三个月!");
return;
}
}
this.dgvPriceCheck.Rows.Clear();
this.lstChainProdInfo.Clear();
this.lstComplianceInfo.Clear();
this.pbLoading.Visible = true;
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
int shopIndex = 0;
int totalProdIndex = 0;
foreach (var shopId in selectShopIdLst)
{
shopIndex++;
var shop = this.lstAdminShopInfo.Where(s => shopId == s.ShopId).ToList().FirstOrDefault();
if (shop == null)
continue;
AdminShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
if (shop.LoginStatus2 != "国际版在线")
{
Invoke(new Action(() =>
{
displayShopStatus(shop);
}));
}
int page = 0;
int totalPage = 1;
int prodIndex = 0;
while (page < totalPage)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
page++;
long startTime = 0, endTime = 0;
if (chkSearchTime.Checked)
{
startTime = BaseClass.DateTimeToTimestampMilliseconds(dtpStartTime.Value.Date);
endTime = BaseClass.DateTimeToTimestampMilliseconds(dtpEndTime.Value.Date.AddDays(1).AddMilliseconds(-1));
}
string searchSkcIds = txtSkcId.Text.Trim().Trim(',');
string searchExtCodes = txtExtCode.Text.Trim().Trim(',');
var searchRst = this.SearchForChainSupplier(shop, page, 50, searchSkcIds, searchExtCodes, type, startTime, endTime);
if (searchRst.Contains("登录过期") || searchRst.Contains("Invalid Login State"))
{
AdminShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
Invoke(new Action(() =>
{
displayShopStatus(shop);
}));
}
if (searchRst.Contains("\"success\":true"))
{
try
{
int total = BaseRegex.GetStringJson(ref searchRst, "total").ParseToInt();
totalPage = Math.Ceiling(total / 100.0).ParseToInt();
var jObj = JObject.Parse(searchRst);
var jArr = jObj["result"]["dataList"] as JArray;
if (jArr == null)
jArr = new JArray();
List<string> extCodeLst = new List<string>();
List<TemuForChainProductInfo> checkPriceInfoTmpLst = new List<TemuForChainProductInfo>();
foreach (var item in jArr)
{
var jStr = JsonHelper.SerializeObject(item);
TemuForChainProductInfo priceInfo = JsonHelper.DeserializeJsonToObject<TemuForChainProductInfo>(jStr);
lstChainProdInfo.Add(priceInfo);
checkPriceInfoTmpLst.Add(priceInfo);
extCodeLst.Add(priceInfo.skcList.FirstOrDefault()?.extCode);
}
var spuIds = "";
foreach (var priceInfo in checkPriceInfoTmpLst)
{
spuIds += priceInfo.productId + ",";
}
spuIds = "\"" + spuIds.Trim(',').Replace(",", "\",\"") + "\"";
List<complianceInfo> complianceInfoTmpLst = null;
if (spuIds.Length > 2)
{
Thread.Sleep(Randomx.GetId(50, 100));
var queryComplianceRst = this.QueryComplianceInfo(shop, 50, spuIds);
queryComplianceRst = GetHtml.Unicode2String(queryComplianceRst);
if (queryComplianceRst.Contains("\"success\":true"))
{
JObject complianceRstObj = JObject.Parse(queryComplianceRst);
string sData = JsonHelper.SerializeObject(complianceRstObj["result"]["data"]);
complianceInfoTmpLst = JsonHelper.DeserializeJsonToList<complianceInfo>(sData);
lstComplianceInfo.AddRange(complianceInfoTmpLst);
}
}
int num = 0;
foreach (var priceInfo in checkPriceInfoTmpLst)
{
num++;
if (cancellationTokenSource.IsCancellationRequested)
break;
prodIndex++;
totalProdIndex++;
Invoke(new Action(() => {
this.statusBar.lblTaskStatus.Text = "正在查询" + type + ",店铺:" + shop.ShopAccount + " " + prodIndex + "/" + total + " 件商品";
this.statusBar.pgbTaskProgress.Maximum = selectShopIdLst.Count;
this.statusBar.UpdateProgressBar(shopIndex);
}));
string imgUrl = priceInfo.skcList.FirstOrDefault()?.previewImgUrlList.FirstOrDefault();
if (imgUrl == null)
imgUrl = "";
imgUrl = imgUrl.Replace("https://", "http://").Replace("img.kwcdn.com", "img.cdnfe.com") + "?imageMogr2/thumbnail/60x";
foreach (var reviewInfo in priceInfo.skcList.FirstOrDefault().supplierPriceReviewInfoList)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
if (reviewInfo.status == 3) //放弃调整报价,报价显示已作废
continue;
string skuName = "";
var prodSkuList = reviewInfo.productSkuList;
if (prodSkuList != null)
{
foreach (var sku in prodSkuList)
{
foreach (var prop in sku.productPropertyList)
{
skuName += prop.value + ",";
}
skuName = skuName.TrimEnd(',') + ";";
skuName += "\r\n";
}
}
var reviewExtCode = priceInfo.skcList.FirstOrDefault()?.extCode;
Thread.Sleep(Randomx.GetId(20, 50));
var complianceInfo = complianceInfoTmpLst.FirstOrDefault(c => c.spu_id == priceInfo.productId);
if (complianceInfo == null)
complianceInfo = new complianceInfo();
var complianceTaskNames = complianceInfo.wait_task_dtolist
.Where(t => t.task_name == "欧盟负责人" || t.task_name == "制造商信息" || t.is_not_required == false)
.Select(t => t.task_name).ToList();
var complianceStr = string.Join("\r\n", complianceTaskNames);
Invoke(new Action(() =>
{
int rowId = this.dgvPriceCheck.Rows.Add(
false,
totalProdIndex,
reviewInfo.priceOrderId,
priceInfo.supplierId,
priceInfo.supplierName,
imgUrl,
DataGridViewExtension.defaultBitmap,
priceInfo.productId,
priceInfo.skcList.FirstOrDefault()?.skcId,
priceInfo.productName,
skuName,
reviewExtCode,
//"-", //货号价格,jit不需要
// sku不同价的会被分成多个review,priceInfo此时为价格范围
reviewInfo.productSkuList.FirstOrDefault()?.supplierPrice, //priceInfo.supplierPrice
BaseClass.StampToDateTime((priceInfo.skcList.FirstOrDefault()?.statusTime.createdTime.ParseToLong() / 1000).ParseToInt()).ToString("yy/MM/dd HH:mm:ss"),
complianceStr,
""
);
dgvPriceCheck.Rows[rowId].Height = 60;
if (num % 2 == 1)
dgvPriceCheck.Rows[rowId].DefaultCellStyle.BackColor = Color.White;
else
dgvPriceCheck.Rows[rowId].DefaultCellStyle.BackColor = Color.WhiteSmoke;
}));
}
}
}
catch (Exception ex)
{
BaseMsgForm.ShowError("查询商品失败 " + ex.Message);
break;
}
}
}
}
Invoke(new Action(() => {
this.pbLoading.Visible = false;
string sRst = type + " 查询结束!";
if (cancellationTokenSource.IsCancellationRequested)
sRst = type + " 已取消查询!";
BaseMsgForm.ShowInfo(sRst);
this.statusBar.lblTaskStatus.Text = sRst;
}));
}, cancellationTokenSource.Token);
}
private string SearchForChainSupplier(ShopLoginInfo shop, int page, int pageSize = 50, string prodSkcIds = null, string skcExtCode = null,
string type = "待创建首单", long startTime = 0, long endTime = 0)
{
string url = "https://agentseller.temu.com/api/kiana/mms/robin/searchForChainSupplier";
string body = "";
body = "{\"pageSize\":" + pageSize + ",\"pageNum\":" + page + ",";
if (!string.IsNullOrEmpty(skcExtCode))
body += "\"skcExtCodeKeyword\":\"" + skcExtCode + "\",";
if (startTime != 0 && endTime != 0) // 查询创建时间
body += "\"timeType\":1,\"timeBegin\":" + startTime + ",\"timeEnd\":" + endTime + ",";
if (type == "待卖家确认")
body += "\"priceReviewStatusList\":[1],\"secondarySelectStatusList\":[7],";
else if (type == "待创建首单")
body += "\"secondarySelectStatusList\":[10],";
body += "\"supplierTodoTypeList\":[],";
if (!string.IsNullOrEmpty(prodSkcIds))
body += "\"productSkcIdList\":[" + prodSkcIds + "],";
body = body.TrimEnd(',');
body += "}";
string referer = "https://agentseller.temu.com/newon/product-select";
return HttpResponseBLL.PostResponse2(shop, url, body, referer);
}
private string QueryComplianceInfo(ShopLoginInfo shop, int pageSize = 50, string prodSpuIds = null)
{
string url = "https://agentseller.temu.com/ms/bg-flux-ms/compliance_property/page_query";
string body = "";
body = @"{""page_num"":1,""page_size"":" + pageSize + @",""type"":2,""spu_id_list"":[" + prodSpuIds + "]}";
string referer = "https://agentseller.temu.com/govern/information-supplementation";
return HttpResponseBLL.PostResponse2(shop, url, body, referer);
}
private void dgvPriceCheck_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvPriceCheck.Columns[e.ColumnIndex].HeaderText;
string orderId = dgvPriceCheck.Rows[e.RowIndex].Cells["colOrderId"].Value.ParseToString();
string prodId = dgvPriceCheck.Rows[e.RowIndex].Cells["colProductId"].Value.ParseToString();
string accountId = dgvPriceCheck.Rows[e.RowIndex].Cells["colSupplierId"].Value.ParseToString();
var shop = lstAdminShopInfo.FirstOrDefault(v => v.ShopId == accountId);
switch (headerText)
{
case "规格名称":
{
var PriceInfo = lstChainProdInfo.FirstOrDefault(p => p.productId.ParseToString() == prodId);
if (PriceInfo != null)
{
this.pnlSpecDetail.Visible = true;
string skuName = "";
var prodSkuList = PriceInfo.skcList.FirstOrDefault().skuList;
if (prodSkuList != null)
{
foreach (var sku in prodSkuList)
{
foreach (var prop in sku.productPropertyList)
{
skuName += prop.value + ",";
}
skuName = skuName.TrimEnd(',') + ";";
skuName += " ";
skuName += " 长:" + sku.len.ParseToInt() * 0.1;
skuName += " 宽:" + sku.width.ParseToInt() * 0.1;
skuName += " 高:" + sku.height.ParseToInt() * 0.1;
skuName += " 重:" + sku.weight.ParseToInt() * 0.001;
skuName += "\r\n";
}
}
this.textBox1.Text = skuName;
}
}
break;
//case "同意报价":
// {
// applyHighPrice(shop, orderId, dgvPriceCheck.Rows[e.RowIndex]);
// }
// break;
//case "拒绝报价":
// {
// cancelLowPrice(shop, orderId, dgvPriceCheck.Rows[e.RowIndex]);
// }
// break;
//case "作废待创建":
// {
// this.cancelTitleWrongPrice(shop, prodId);
// }
// break;
case "合规":
{
//加州65号提案
//欧盟负责人
//制造商信息
//其他合规信息 商品识别码
}
break;
case "Skc图片":
string url = dgvPriceCheck.Rows[e.RowIndex].Cells["colImgUrl"].Value.ParseToString().Replace("img.kwcdn.com", "img.cdnfe.com");
url = url.IndexOf("?") < 0 ? url : url.Substring(0, url.IndexOf("?"));
ShowImgForm imgFrom = new ShowImgForm(url);
imgFrom.ShowDialog();
break;
//case "":
// dgvPriceCheck.Rows[e.RowIndex].Cells["colCheck"].Value = !(bool)dgvPriceCheck.Rows[e.RowIndex].Cells["colCheck"].Value;
// break;
default:
break;
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.pnlSpecDetail.Visible = false;
}
}
public class SetJitConfig
{
public string SearchShopId { get; set; } = "";
public string SearchShopName { get; set; } = "";
public string SearchNotes { get; set; } = "";
public bool SearchAllShop { get; set; } = true;
}
/// <summary>
/// 合规信息
/// </summary>
public class complianceInfo
{
public long? spu_id { get; set; } // 5230217458,
public string spu_name { get; set; } // "XIXITIAO 女款韩式拖鞋 - 夏季休闲纯色 EVA 拖鞋,舒适防滑低跟沙滩凉鞋,室内/室外使用,夏季凉鞋,女式人字拖,夹趾凉鞋时尚女士轻质夏季一脚蹬沙滩人字拖凉鞋,女式人字拖夹趾凉鞋休闲凉鞋淋浴鞋沙滩拖鞋拖鞋凉鞋一脚蹬淌水鞋,百搭设计,适合日常穿着,女式平底凉鞋",
public long? cat_id { get; set; } // 29186,
public string cat_name { get; set; } // "女士人字拖",
public long? goods_id { get; set; } // 601103852497488,
public string goods_url { get; set; } // "https://img.kwcdn.com/product/fancy/0f52acc1-edfe-4f70-8032-012505ad0da5.jpg",
public List<task_dto> wait_task_dtolist { get; set; }
public List<task_dto> wait_task_show_dtolist { get; set; }
public bool? on_sale { get; set; } // false
}
public class task_dto
{
public long? task_id { get; set; } // 101042759897649,
public int? task_type { get; set; } // 25,
public bool? is_not_required { get; set; } // true,
public string task_name { get; set; } // "欧盟负责人",
public int? status { get; set; } // 2,
public long? punish_time { get; set; } // 0,
public sale_effect_info sale_effect_info { get; set; }
}
public class sale_effect_info
{
public long? punish_time { get; set; } // 0,
public bool? on_site { get; set; } // false,
public List<int> region_list { get; set; } // [105, 106, 107, 108, 109, ...],
public string content { get; set; } // "德国站、法国站、意大利站、荷兰站、西班牙站、葡萄牙站、波兰站、瑞典站、希腊站、爱尔兰站、塞浦路斯站、捷克站、匈牙利站、丹麦站、罗马尼亚站、保加利亚站、比利时站、奥地利站、芬兰站、斯洛伐克站、克罗地亚站、斯洛文尼亚站、立陶宛站、爱沙尼亚站、拉脱维亚站、马耳他站、卢森堡站"
}
}