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

510 lines
22 KiB
C#

using AllBase;
using AllBase.Helper;
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.Extension;
using TemuKJD.BaseForms;
using TemuKJD.KJDForms.ShopForms;
using Work;
using TemuKJD.BLL;
namespace TemuKJD.KJDForms.ProductForms
{
public partial class PurchasePriceForm : BaseForm
{
private CheckBox chkSelectAll = null;
public CancellationTokenSource cancellationTokenSource { get; set; } = null;
List<TemuListProductInfo> lstProductInfo = new List<TemuListProductInfo>();
List<TemuDBProductPurchasePriceInfo> lstProductPurchasePrice = new List<TemuDBProductPurchasePriceInfo>();
public PurchasePriceForm()
{
InitializeComponent();
}
private void PurchasePriceForm_Load(object sender, EventArgs e)
{
chkSelectAll = dgvShop.Columns["colSelect"].AddHeaderCheckBox(HorizontalAlignment.Center, 0, 0, null, null, false);
dgvShop.Columns["colSelect"].HeaderText = "";
//chkSelectAll.Width = chkSelectAll.Height = 13;
chkSelectAll.CheckedChanged += chkSelectAll_CheckedChanged;
this.dgvProduct.AddSelectorColumn("colCheck");
//this.dgvProduct.MergeColumnHeader(new List<string>() { "colSupplierId", "colSupplierName" }, "店铺信息", true);
}
private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
if (!chkSelectAll.Checked)
{
foreach (DataGridViewRow row in dgvShop.Rows)
{
row.Cells["colSelect"].Value = false;
}
}
else
{
var list = GlobalConfig.ShopLoginList.Where(s => s.LoginStatus2 == "国际版在线").Select(ss => ss.ShopId);
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (list.Any(l => l == row.Cells["colShopId"]?.Value?.ToString()))
row.Cells["colSelect"].Value = true;
}
}
}
private void PurchasePriceForm_VisibleChanged(object sender, EventArgs e)
{
if (Visible == true)
RefreshShop();
}
private void btnRefreshShop_Click(object sender, EventArgs e)
{
RefreshShop();
}
private void RefreshShop()
{
// 店铺Id
var selectIds = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList();
// 获取被删除的店铺
List<DataGridViewRow> dgvRowList = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> !GlobalConfig.ShopLoginList.Any(s => s.ShopId == row.Cells["colShopId"]?.Value?.ToString())).ToList();
// 更新被删除的店铺列表
foreach (var row in dgvRowList)
{
dgvShop.Rows.Remove(row);
}
// 绑定其他店铺(含新导入的店铺)
foreach (ShopLoginInfo shopEntity in GlobalConfig.ShopLoginList)
{
if (!string.IsNullOrEmpty(shopEntity.ShopId))
BindShop(shopEntity, selectIds);
}
}
private void BindShop(ShopLoginInfo shopEntity, List<string> selectShopId = null)
{
if (shopEntity == null)
return;
if (selectShopId == null)
selectShopId = new List<string>();
bool canUse = shopEntity.LoginStatus2 == "国际版在线";
var row = dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(p => p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == shopEntity.ShopId);
if (row == null)
{
int id = this.dgvShop.Rows.Add(
selectShopId.Contains(shopEntity.ShopId) && canUse,
shopEntity.LoginName,
shopEntity.ShopId,
shopEntity.ShopAccount,
shopEntity.Notes,
canUse ? "在线" : "掉线",
canUse,
string.Empty
);
row = dgvShop.Rows[id];
row.Cells["colLoginStatus"].Style.ForeColor = canUse ? Color.Green : Color.Red;
}
else
{
row.Cells["colSelect"].Value = selectShopId.Contains(shopEntity.ShopId) && canUse;
row.Cells["colShopLoginName"].Value = shopEntity.LoginName;
row.Cells["colShopName"].Value = shopEntity.ShopAccount;
row.Cells["colShopNotes"].Value = shopEntity.Notes;
row.Cells["colLoginStatus"].Value = canUse ? "在线" : "掉线";
row.Cells["colLoginStatus"].Style.ForeColor = canUse ? Color.Green : Color.Red;
row.Cells["colCanUse"].Value = canUse;
}
}
private void dgvShop_CellClick(object sender, DataGridViewCellEventArgs e)
{
string columnName = dgvShop.Columns[e.ColumnIndex].Name;
switch (columnName)
{
case "colSelect":
dgvShop.CellContentClick -= dgvShop_CellContentClick;
dgvShop_CellContentClick(sender, e);
break;
default:
dgvShop.CellContentClick -= dgvShop_CellContentClick;
dgvShop.CellContentClick += dgvShop_CellContentClick;
break;
}
}
private void dgvShop_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvShop.Columns[e.ColumnIndex].HeaderText;
string columnName = dgvShop.Columns[e.ColumnIndex].Name;
long shopId = dgvShop.Rows[e.RowIndex].Cells["colShopId"].Value.ParseToLong();
string shopAccount = dgvShop.Rows[e.RowIndex].Cells["colShopName"].Value.ToString();
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId.ToString());
var row = dgvShop.Rows[e.RowIndex];
switch (columnName)
{
case "colSelect":
if (row.Cells["colCanUse"].Value.ParseToBool() || row.Cells["colSelect"].Value.ParseToBool())
{
row.Cells["colSelect"].Value = !row.Cells["colSelect"].Value.ParseToBool();
chkSelectAll.CheckedChanged -= chkSelectAll_CheckedChanged;
if (dgvShop.Rows.Cast<DataGridViewRow>().All(r => r.Cells["colSelect"].Value.ParseToBool()))
chkSelectAll.Checked = true;
else
chkSelectAll.Checked = false;
chkSelectAll.CheckedChanged += chkSelectAll_CheckedChanged;
}
else
{
BaseMsgForm.ShowInfo("店铺国际版未登录!");
}
break;
}
}
private string GetProductList(ShopLoginInfo shop, int page = 1, string skuIds="")
{
page = Math.Max(page, 1);
string url = "https://agentseller.temu.com/visage-agent-seller/product/skc/pageQuery";
string body;
body = @"{""page"":" + page + @",""pageSize"":200,""skcTopStatus"":100}";
if (!string.IsNullOrEmpty(skuIds))
body = @"{""productSkuIds"":[" + skuIds + @"],""page"":" + page + @",""pageSize"":200,""skcTopStatus"":100}";
string refere = "https://agentseller.temu.com/goods/list";
return HttpResponseBLL.PostResponse2(shop, url, body, refere);
}
private void btnSearchPrice_Click(object sender, EventArgs e)
{
var lstShopId = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList();
if (lstShopId.Count == 0)
{
BaseMsgForm.ShowInfo("请选择店铺!");
return;
}
lstProductInfo.Clear();
dgvProduct.Rows.Clear();
var dgvRows = this.dgvShop.Rows.Cast<DataGridViewRow>();//.Where(r => lstShopId.Contains(r.Cells["colShopId"].Value.ParseToString()));
foreach (var row in dgvRows)
{
row.Cells["colMessage"].Value = "";
}
ucGroupBoxEx2.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
var lstShopIdTemp = new List<string>();
lstShopIdTemp.AddRange(lstShopId);
int i = 0;
foreach (var shopId in lstShopIdTemp)
{
this.Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "正在查询...";
this.statusBar.pgbTaskProgress.Maximum = lstShopIdTemp.Count;
this.statusBar.UpdateProgressBar(i + 1);
i++;
}));
if (cancellationTokenSource.IsCancellationRequested)
break;
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
continue;
#region 检测登录
if (shop.LoginStatus2 != "国际版在线")
{
continue;
}
if (ShopListForm.Instance == null)
ShopListForm.Instance = new ShopListForm();
ShopListForm.Instance.CheckShopLogin(new string[] { shop.LoginName }, false);
if (shop.LoginStatus2 != "国际版在线")
{
Invoke(new Action(() =>
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colShopLoginName"].Value.ToString() == shop.LoginName);
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "店铺掉线";
row.Cells["colLoginStatus"].Value = "国际版未登录";
row.Cells["colCanUse"].Value = false;
}
}));
continue;
}
#endregion
Invoke(new Action(() =>
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId);
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "正在查询";
}
}));
int page = 1;
int totalPage = 1;
bool isError = false;
string errMsg = "";
while (page <= totalPage)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
int tryCount = 0;
tryAgain:
Thread.Sleep(100 + Randomx.GetId(200));
string jsonStr = GetProductList(shop, page);
if (jsonStr.Contains("指定的值含有无效的控制字符"))
{
BaseMsgForm.ShowError("店铺" + shop.LoginName + " " + shop.ShopId + "已掉线");
isError = true;
break;
}
if (jsonStr.Contains("当前操作人数太多,请稍后重试") && tryCount < 5)
{
tryCount++;
Thread.Sleep(Randomx.GetId(500, 1000));
goto tryAgain;
}
if (jsonStr.Contains("当前操作人数太多,请稍后重试"))
{
}
if (!jsonStr.Contains("\"success\":true"))
{
isError = true;
string sErr = BaseRegex.GetStringJson(ref jsonStr, "errorMsg");
if (!string.IsNullOrWhiteSpace(sErr) && !errMsg.Contains(sErr))
errMsg += sErr + " ";
page++;
continue;
}
string tag = BaseClass.DateTimeToTimestampMilliseconds(DateTime.Now).ToString();
if (jsonStr.Contains("\"success\":true"))
{
var jArr = new JArray();
try
{
var jObj = JObject.Parse(jsonStr);
jArr = jObj["result"]?["pageItems"] as JArray;
if (jArr == null)
jArr = new JArray();
List<TemuListProductInfo> productInfoLst = new List<TemuListProductInfo>();
List<string> productInfoSpuIdLst = new List<string>();
foreach (var item in jArr)
{
string sItem = JsonHelper.SerializeObject(item);
TemuListProductInfo pInfo = JsonHelper.DeserializeJsonToObject<TemuListProductInfo>(sItem); // 反序列化得到类
if (pInfo != null && !lstProductInfo.Any(a => a.productId == pInfo.productId))
{
lstProductInfo.Add(pInfo);
productInfoLst.Add(pInfo);
productInfoSpuIdLst.Add(pInfo.productId.ParseToString());
}
}
List<TemuDBProductPurchasePriceInfo> productPurchasePriceList = GetPurchasePrice(productInfoSpuIdLst);
this.lstProductPurchasePrice.AddRange(productPurchasePriceList);
foreach (var pInfo in productInfoLst)
{
Invoke(new Action(() =>
{
int rowId = this.dgvProduct.Rows.Add(
true,
shop.ShopId,
shop.ShopAccount, // pInfo.supplierName, // 列表里取不到,这里取shop里的
pInfo.mainImageUrl.Replace("https", "http").Replace("img.kwcdn.com", "img.cdnfe.com") + "?imageMogr2/thumbnail/60x",
defaultBitmap,//image, // skc图片
pInfo.productId,
pInfo.productSkcId,
pInfo.productName, // 商品标题
pInfo.extCode,
"",
"",
"设置",
"" // 操作结果,状态
);
dgvProduct.Rows[rowId].Height = 60;
}));
}
}
catch (Exception ex)
{
BaseMsgForm.ShowError(ex.Message);
}
Invoke(new Action(() =>
{
ShowDgvImg(dgvProduct);
}));
int total = BaseRegex.GetStringJson(ref jsonStr, "total").ParseToInt();
totalPage = Math.Ceiling(total / 200.0).ParseToInt();
}
page++;
}
Invoke(new Action(() =>
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId);
if (!isError)
{
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "已查询";
}
}
else
{
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "查询失败 " + errMsg;
}
}
}));
}
Invoke(new Action(() =>
{
ucGroupBoxEx2.Enabled = true;
string sRst = "查询结束!";
if (cancellationTokenSource.IsCancellationRequested)
sRst = "已取消查询!";
BaseMsgForm.ShowInfo(sRst);
this.statusBar.lblTaskStatus.Text = sRst;
}));
}, cancellationTokenSource.Token);
}
Bitmap defaultBitmap = new Bitmap(80, 80);
void ShowDgvImg(DataGridView dgv)
{
Task.Run(() =>
{
foreach (DataGridViewRow row in dgv.Rows)
{
if (row.Index > 0 && row.Cells["colProductSkcPic"].Displayed == false)
{
try
{
Invoke(new Action(() =>
{
row.Cells["colProductSkcPic"].Value = defaultBitmap;
}));
}
catch
{
}
continue;
}
if (row.Cells["colProductSkcPic"].Value != null && row.Cells["colProductSkcPic"].Value != defaultBitmap)
continue;
Image image = null;
string imgUrl = row.Cells["colImgUrl"]?.Value.ParseToString();
string getImgError = "";
if (!string.IsNullOrWhiteSpace(imgUrl))
image = GetHtml.GetUrlImg(imgUrl, out getImgError);
if (!string.IsNullOrEmpty(getImgError))
//BaseMsgForm.ShowError("图片加载失败 " + getImgError);
image = TemuKJD.Properties.Resources.errpic;
try
{
Invoke(new Action(() =>
{
row.Cells["colProductSkcPic"].Value = image;
}));
}
catch
{
}
}
});
}
private void dgvProduct_Scroll(object sender, ScrollEventArgs e)
{
ShowDgvImg(this.dgvProduct);
}
public static List<TemuDBProductPurchasePriceInfo> GetPurchasePrice(List<string> productIdList)
{
List<TemuDBProductPurchasePriceInfo> list = new List<TemuDBProductPurchasePriceInfo>();
for (int i = 0; i < productIdList.Count; i++)
{
productIdList[i] = productIdList[i].Replace(",", "").Replace("'", "").Replace("\"", "");
}
var url = BaseClass.BuildObjString("price/get_purchase_price_list");
var data = UserLogin.GetSignaturex();
data += "&page=1";
data += "&page_size=" + productIdList.Count;
data += "&in_spu_id=" + string.Join(",", productIdList);
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("\"code\":200"))
{
return list;
}
if (!html.Contains("data"))
return list;
var jArr = JObject.Parse(html)["data"];
if (jArr.Count() == 0)
return list;
list = JsonHelper.DeserializeJsonToList<TemuDBProductPurchasePriceInfo>(jArr.ToString());
foreach (var pPrice in list)
{
pPrice.dbSkuPurchasePriceList = JsonHelper.DeserializeJsonToList<TemuDBSkuPurchasePriceInfo>(pPrice.sku_purchase_price_json);
if (pPrice.dbSkuPurchasePriceList == null)
pPrice.dbSkuPurchasePriceList = new List<TemuDBSkuPurchasePriceInfo>();
else
{
pPrice.price_text = "¥" + (pPrice.dbSkuPurchasePriceList.Min(s => s.purchasePriceValue) * 0.01).ParseToDecimal().ToString("0.00") + "~"
+ "¥" + (pPrice.dbSkuPurchasePriceList.Max(s => s.purchasePriceValue) * 0.01).ParseToDecimal().ToString("0.00");
}
}
return list;
}
}
}