Files
KJD/TEMUKJD/KJDForms/SalesCenterForms/SeckillingAndLimitedSalesShopForm.cs
T

564 lines
27 KiB
C#

using AllBase;
using AllBase.Extension;
using AllBase.Helper;
using AllBase.Model.Result;
using TemuKJD.Extension;
using TemuKJD.KJDForms.BaseForms;
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.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Work.BLL.Product;
namespace TemuKJD.KJDForms.SalesCenterForms
{
public partial class SeckillingAndLimitedSalesShopForm : Form
{
private DouShopLoginInfo shop = null;
private CheckBox chkSelectAll = null;
private string _signature = "";
private string _timeSpan = "";
private bool isGetSalesSuccess = false;
private bool isGetProductSuccess = false;
private Dictionary<long, int> dicProductSales = new Dictionary<long, int>();
public SeckillingAndLimitedSalesForm SeckillingAndLimitedSalesForm { get; set; } = null;
public List<DouProductPromotionListInfo> ProductList { get; set; } = new List<DouProductPromotionListInfo>();
public List<string> LstProductId
{
get
{
return this.dgvProduct.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colSelect"].Value.ParseToBool()).Select(r => r.Cells["colProductId"].Value.ToString()).ToList();
}
}
public SeckillingAndLimitedSalesShopForm(DouShopLoginInfo _shop = null)
{
InitializeComponent();
shop = _shop;
//设置全选按钮
chkSelectAll = dgvProduct.Columns["colSelect"].AddHeaderCheckBox(HorizontalAlignment.Center, 0, 0, null, null, false);
dgvProduct.Columns["colSelect"].HeaderText = "";
chkSelectAll.Width = chkSelectAll.Height = 13;
chkSelectAll.CheckedChanged += chkSelectAll_CheckedChanged; //全选事件
}
private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
if (!chkSelectAll.Checked)
{
foreach (DataGridViewRow row in dgvProduct.Rows)
{
row.Cells["colSelect"].Value = false;
}
}
else
{
foreach (DataGridViewRow row in dgvProduct.Rows)
{
if (row.Cells["colAllow"].Value?.ToString() == "可用")
row.Cells["colSelect"].Value = true;
}
}
}
public void GetProductSim(string listUrl, string referrerUrl, Dictionary<string, string> headers, string firstPageData = "", string campaign_start_time = "", string campaign_end_time = "")
{
ShowVisitorMessage("");
string salesUrl = listUrl;
foreach (DataGridViewRow r in this.dgvProduct.Rows)
{
Invoke(new Action(() =>
{
r.Cells["colSales"].Value = "获取中";
r.Cells["colStock"].Value = "获取中";
r.Cells["colAllow"].Value = "获取中";
r.Cells["colMessage"].Value = "";
}));
}
foreach (var p in ProductList)
{
p.sell_num = null;
}
bool isGetSalesOver = false;
Task t1 = Task.Run(() =>
{
int totalT1 = -1;
int numberT1 = 0;
string resultT1 = "";
if (!string.IsNullOrEmpty(firstPageData))
resultT1 = firstPageData;
ShowVisitorMessage("正在准备获取商品销量");
// 获取有销量的商品
for (int i = 0; i < 10000; i++)
{
numberT1 += 20;
for (int j = 0; j < 3 && !resultT1.Contains("\"st\":0"); j++)
{
CommonSimRequest simRequest = new CommonSimRequest();
simRequest.Accept = "application/json, text/plain, */*";
if (headers.ContainsKey("Accept"))
simRequest.Accept = headers["Accept"];
if (headers.ContainsKey("UserAgent"))
simRequest.UserAgent = headers["UserAgent"];
var cookie = shop.Cookies;
ShowVisitorMessage("商品销量获取中,第 " + (i + 1) + " 页");
var rUrl = salesUrl.Replace("page=0", "page=" + i).Replace("&pay_type=", "&pay_type=&sell_num_min=1"); // 获取所有有销量的商品,Replace不可注释!!
resultT1 = simRequest.Request_Get(rUrl, referrerUrl, new Dictionary<string, string>(), cookie);
if (j > 0)
{
Thread.Sleep(Randomx.GetId(250, 750));
Thread.Sleep(Randomx.GetId(250, 750));
}
}
if (resultT1.Contains("\"st\":0") && !SeckillingAndLimitedSalesForm.cancellationTokenSource.IsCancellationRequested)
{
this.isGetSalesSuccess = true;
if (totalT1 == -1)
{
totalT1 = BaseRegex.GetIntJson(ref resultT1, "total");
}
var jObj = JObject.Parse(resultT1);
var jArr = jObj["data"] as JArray;
foreach (var productObj in jArr)
{
//DouProductWithSalesListInfo product = new DouProductWithSalesListInfo();
var prod = JsonHelper.SerializeObject(productObj);
//product.product_id = BaseRegex.GetLongJson(ref prod, "product_id");
//product.sell_num = BaseRegex.GetIntJson(ref prod, "sell_num");
//product.stock_num = BaseRegex.GetIntJson(ref prod, "stock_num");
//product.name = BaseRegex.GetStringJson(ref prod, "name");
//product.discount_price = BaseRegex.GetDecimalJson(ref prod, "discount_price") / 100;
//product.create_time_str = BaseRegex.GetStringJson(ref prod, "create_time");
//product.create_time = BaseClass.DateTimeToTimestampSeconds(product.create_time_str.ParseToDateTime());
//Invoke(new Action(() =>
//{
// this.dgvProduct.Rows.Add(false, product.product_id, product.name, product.stock_num, product.sell_num, product.discount_price, product.create_time_str);
//}));
var product_id = BaseRegex.GetLongJson(ref prod, "product_id");
var sell_num = BaseRegex.GetIntJson(ref prod, "sell_num");
this.dicProductSales[product_id] = sell_num;
}
Thread.Sleep(Randomx.GetId(250, 750));
Thread.Sleep(Randomx.GetId(250, 750));
resultT1 = "";
}
else
{
isGetSalesSuccess = false;
ShowVisitorMessage("获取商品销量失败");
isGetSalesOver = true;
break;
}
if (numberT1 >= totalT1)
{
ShowVisitorMessage("获取商品销量完成");
isGetSalesOver = true;
// 填写商品销量
foreach (var product in this.ProductList)
{
if (dicProductSales.ContainsKey(product.product_id.ParseToLong()))
product.sell_num = dicProductSales[product.product_id.ParseToLong()];
else if (isGetSalesSuccess)
product.sell_num = 0;
else
product.sell_num = -1;
var row = this.dgvProduct.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colProductId"].Value.ToString() == product.product_id);
if (row != null && row.Cells["colSales"].Value.ToString() == "获取中")
{
if (product.sell_num >= 0)
row.Cells["colSales"].Value = product.sell_num;
if (product.sell_num >= 0)
row.Cells["colSales"].Value = product.sell_num;
}
}
break;
}
}
});
var total = -1;
var number = 0;
var result = "";
referrerUrl = "https://fxg.jinritemai.com/market/center/tools/limitsales/detail?refer=new";
DateTime date = DateTime.Now.Date;
if (string.IsNullOrEmpty(campaign_start_time))
campaign_start_time = date.ToString("yyyy-MM-dd") + "+00:00:00";
if (string.IsNullOrEmpty(campaign_end_time))
campaign_end_time = date.ToString("yyyy-MM-dd") + "+23:59:59";
_timeSpan = BaseRegex.GetMatchRegexString(ref listUrl, "&_=([\\s\\S]+?)&");
if (string.IsNullOrEmpty(_timeSpan))
_timeSpan = BaseRegex.GetMatchRegexString(ref listUrl, "&_=([\\s\\S]+?)");
if (string.IsNullOrEmpty(_timeSpan))
_timeSpan = BaseClass.DateTimeToTimestampMilliseconds(DateTime.Now).ToString();
_signature = BaseRegex.GetMatchRegexString(ref listUrl, "&_signature=([\\s\\S]+?)&");
if (string.IsNullOrEmpty(_signature))
{
var listUrl2 = listUrl + "&";
_signature = BaseRegex.GetMatchRegexString(ref listUrl2, "&_signature=([\\s\\S]+?)&");
}
// 查询单件商品
// https://fxg.jinritemai.com/byteshop/promotion/queryAvailableGoods?name=3550481296776157865&page=1&pageSize=15&campaign_start_time=2022-07-12+13:53:58&campaign_end_time=2022-07-13+13:53:58&stype=7&_bid=ecom_market_shop&appid=1&_=1657605277264&_signature=_02B4Z6wo00901vPj2jgAAIDAgf3-u.2wcb7z596AAN5DTpZAb6P6BWjbWf6p.E8w0icSl9d8vqMw9VdyRVtMyHUP25-fyQJA9.JSE1OQhQnubxfnISMkVfqQ0u80uuh3ezzpRpzTvt0UVyVyfa
// 查询列表
listUrl = "https://fxg.jinritemai.com/byteshop/promotion/queryAvailableGoods?name=&page=0&pageSize=15&campaign_start_time=" + campaign_start_time +
"&campaign_end_time=" + campaign_end_time + "&stype=7&_bid=ecom_market_shop&appid=1" +
"&_=" + _timeSpan + "&_signature=" + _signature;
int num = 9999;
// 是否获取指定商品
bool getWithName = false;
if (SeckillingAndLimitedSalesForm.LstSearthProductId.Count > 0 && !string.IsNullOrEmpty(SeckillingAndLimitedSalesForm.LstSearthProductId[0]))
{
num = SeckillingAndLimitedSalesForm.LstSearthProductId.Count;
getWithName = true;
}
for (int i = 1; i <= num; i++)
{
result = "";
number += 15;
// {\"st\":0,\"msg\":\"账号未登录\",\"code\":10008,\"data\":{},\"page\":0,\"size\":0,\"total\":0}
for (int j = 0; j < 3 && !result.Contains("\"st\":0") || result.Contains("\"msg\":\"账号未登录\""); j++)
{
CommonSimRequest simRequest = new CommonSimRequest();
simRequest.Accept = "application/json, text/plain, */*";
if (headers.ContainsKey("Accept"))
simRequest.Accept = headers["Accept"];
if (headers.ContainsKey("UserAgent"))
simRequest.UserAgent = headers["UserAgent"];
var cookie = shop.Cookies;
var rUrl = "";
//int pageSize = 15;
//if (number > 10000)
//{
// pageSize = 15 - (number - 10000);
// if (pageSize < 0)
// pageSize = 0;
// rUrl = rUrl.Replace("pageSize=15", "pageSize=" + pageSize);
//}
// 获取列表商品
if (!getWithName)
{
rUrl = listUrl.Replace("page=0", "page=" + i);
}
// 获取指定商品
else
{
rUrl = listUrl.Replace("page=0", "page=1").Replace("name=&", "name=" + SeckillingAndLimitedSalesForm.LstSearthProductId[i - 1] + "&");
}
result = simRequest.Request_Get(rUrl, referrerUrl, new Dictionary<string, string>(), cookie);
if (result.Contains("账号未登录"))
{
}
if (j > 0)
{
Thread.Sleep(Randomx.GetId(200, 500));
}
}
if (!result.Contains("\"st\":0"))
{
}
if (result.Contains("\"st\":0") && !SeckillingAndLimitedSalesForm.cancellationTokenSource.IsCancellationRequested)
{
this.isGetProductSuccess = true;
if (total == -1)
{
total = BaseRegex.GetIntJson(ref result, "total");
}
int totalPage = Math.Ceiling(total / 15M).ParseToInt();
string message = "";
if (!getWithName)
message = "正在获取商品第" + i + "页,共" + totalPage + "页";
else
message = "正在获取商品第" + i + "条,共" + num + "条";
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = message;
this.statusBar.pgbTaskProgress.Value = i;
if (!getWithName)
{
this.statusBar.pgbTaskProgress.Text = i + "/" + totalPage;
this.statusBar.pgbTaskProgress.Maximum = totalPage;
}
else
{
this.statusBar.pgbTaskProgress.Text = i + "/" + num;
this.statusBar.pgbTaskProgress.Maximum = num;
}
}));
try
{
var jObj = JObject.Parse(result);
var pList = JsonHelper.DeserializeJsonToList<DouProductPromotionListInfo>(jObj["data"]?.ToString());
foreach (var product in pList)
{
if (product.allow == false && product.reject_msg == "不可售卖商品")
{
continue;
}
if (dicProductSales.ContainsKey(product.product_id.ParseToLong()))
product.sell_num = dicProductSales[product.product_id.ParseToLong()];
else if (isGetSalesOver && isGetSalesSuccess)
product.sell_num = 0;
else if (isGetSalesOver)
product.sell_num = -1;
if (this.ProductList.Any(p => p.product_id == product.product_id))
this.ProductList.RemoveAll(p => p.product_id == product.product_id);
this.ProductList.Add(product);
var row = this.dgvProduct.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colProductId"].Value.ToString() == product.product_id);
Invoke(new Action(() =>
{
if (row != null)
{
dgvProduct.Rows.Remove(row);
}
var priceText = product.min_price / 100M + " - " + product.max_price / 100M;
object sellNum = "获取中";
if (product.sell_num != null && product.sell_num != -1)
sellNum = product.sell_num;
else if (product.sell_num == -1)
sellNum = "获取失败";
var rejectMsg = "可用";
if (product.allow == false)
rejectMsg = product.reject_msg;
DataGridViewRow r = new DataGridViewRow();
r.Cells.Add(new DataGridViewCheckBoxCell() { Value = false, });
r.Cells.Add(new DataGridViewTextBoxCell() { Value = product.product_id, });
r.Cells.Add(new DataGridViewTextBoxCell() { Value = product.name, });
r.Cells.Add(new DataGridViewTextBoxCell() { Value = product.stock_num, }); // 库存
r.Cells.Add(new DataGridViewTextBoxCell() { Value = sellNum, }); // 销量
r.Cells.Add(new DataGridViewTextBoxCell() { Value = priceText, }); // 价格区间
r.Cells.Add(new DataGridViewTextBoxCell() { Value = "", }); // 创建时间
r.Cells.Add(new DataGridViewTextBoxCell() { Value = rejectMsg });
this.dgvProduct.Rows.Add(r);
if (product.allow == false)
{
r.Cells["colSelect"].ReadOnly = true;
r.Cells["colAllow"].Style.ForeColor = Color.Red;
}
else
{
r.Cells["colSelect"].ReadOnly = false;
r.Cells["colAllow"].Style.ForeColor = Color.Green;
}
}));
}
Thread.Sleep(Randomx.GetId(100, 250));
}
catch (Exception ex)
{
isGetProductSuccess = false;
break;
}
}
else
{
isGetProductSuccess = false;
break;
}
// 列表获取超过最大数值后跳出
if (!getWithName && number >= total)
break;
}
t1.Wait();
// 最后填写商品销量
foreach (var product in this.ProductList)
{
if (dicProductSales.ContainsKey(product.product_id.ParseToLong()))
product.sell_num = dicProductSales[product.product_id.ParseToLong()];
else if (isGetSalesSuccess)
product.sell_num = 0;
else
product.sell_num = -1;
var row = this.dgvProduct.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colProductId"].Value.ToString() == product.product_id);
if (row != null && row.Cells["colSales"].Value.ToString() == "获取中")
{
if (product.sell_num >= 0)
row.Cells["colSales"].Value = product.sell_num;
if (product.sell_num >= 0)
row.Cells["colSales"].Value = product.sell_num;
}
}
Invoke(new Action(() =>
{
if (SeckillingAndLimitedSalesForm.cancellationTokenSource.IsCancellationRequested)
{
this.statusBar.lblTaskStatus.Text = "获取中断";
}
else if (!isGetSalesSuccess)
{
this.statusBar.lblTaskStatus.Text = "获取完成,但获取销量信息失败";
}
else if (!isGetProductSuccess)
{
this.statusBar.lblTaskStatus.Text = "获取商品信息失败";
}
else
{
this.statusBar.lblTaskStatus.Text = "获取完成";
}
ShowVisitorMessage("");
//this.statusBar.pgbTaskProgress.Value = 0;
//this.statusBar.pgbTaskProgress.Text = 0 + "/" + 0;
//this.statusBar.pgbTaskProgress.Maximum = 0;
}));
}
public void GetProduct()
{
if (shop == null)
return;
ShowVisitorMessage("");
foreach (DataGridViewRow r in this.dgvProduct.Rows)
{
r.Cells["colSales"].Value = "获取中";
r.Cells["colStock"].Value = "获取中";
r.Cells["colMessage"].Value = "";
}
foreach (var p in ProductList)
{
p.sell_num = null;
}
List<Task> tList = new List<Task>();
var t2 = Task.Run(() =>
{
if (shop.LoginStatus == "登录成功")
SeckillingAndLimitedSalesForm.GetProductByCef(this.shop);
var rowsTemp = dgvProduct.Rows.Cast<DataGridViewRow>().ToList();
rowsTemp.Reverse();
foreach (var r in rowsTemp)
{
try
{
//if (r.Cells["colPrice"].Value.ParseToDecimal() < priceMin || r.Cells["colPrice"].Value.ParseToDecimal() > priceMax
// || r.Cells["colSales"].Value.ParseToDecimal() < salesMin || r.Cells["colSales"].Value.ParseToDecimal() > salesMax
// || (productName?.Count > 0 && !productName.Any(n => r.Cells["colProductName"].Value.ToString().Contains(n))))
//{
// Invoke(new Action(() =>
// {
// dgvProduct.Rows.Remove(r);
// }));
//}
}
catch (Exception ex)
{
}
}
});
tList.Add(t2);
t2.Wait();
}
//根据id获取sku
public string GetSkusByProductIds(string postData, string cookies)
{
CommonSimRequest request = new CommonSimRequest();
request.ContentType = "application/json";
Dictionary<string, string> dicts = new Dictionary<string, string>();
string reqUrl = "https://fxg.jinritemai.com/byteshop/promotion/batchGetSkuByProductIds?_bid=ecom_market_shop&appid=1&_=" + _timeSpan + "&_signature=" + _signature;
string result = request.Request_PostByBigLength(reqUrl, "https://fxg.jinritemai.com/market/center/tools/limitsales/detail?refer=new", dicts, cookies, postData);
return result;
}
public string checkFlashAndGoods(string postData, string cookies)
{
CommonSimRequest request = new CommonSimRequest();
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36";
request.ContentType = "application/json";
Dictionary<string, string> dicts = new Dictionary<string, string>();
string reqUrl = "https://fxg.jinritemai.com/byteshop/promotion/checkFlashAndGoods?_bid=ecom_market_shop&appid=1&_=" + _timeSpan + "&_signature=" + _signature;
string result = request.Request_PostByBigLength(reqUrl, "https://fxg.jinritemai.com/market/center/tools/limitsales/detail?refer=new", dicts, cookies, postData);
return result;
}
public string createFlashAndGoods(string postData, string cookies)
{
CommonSimRequest request = new CommonSimRequest();
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36";
request.ContentType = "application/json";
Dictionary<string, string> dicts = new Dictionary<string, string>();
string reqUrl = "https://fxg.jinritemai.com/byteshop/promotion/createFlashAndGoods?_bid=ecom_market_shop&appid=1&_=" + _timeSpan + "&_signature=" + _signature;
string result = request.Request_PostByBigLength(reqUrl, "https://fxg.jinritemai.com/market/center/tools/limitsales/detail?refer=new", dicts, cookies, postData);
return result;
}
public void ShowVisitorMessage(string msg, string ids = "", bool onlyShowInGrid = false)
{
Invoke(new Action(() =>
{
this.label1.Text = msg;
if (!string.IsNullOrEmpty(ids))
{
var idList = ids.Split(new string[] { "\",\"", "\"" }, StringSplitOptions.RemoveEmptyEntries);
var rows = this.dgvProduct.Rows.Cast<DataGridViewRow>().Where(r => idList.Contains(r.Cells["colProductId"].Value?.ToString()));
foreach (var row in rows)
{
row.Cells["colMessage"].Value = msg;
}
}
}));
}
public void ClearData()
{
this.ProductList.Clear();
this.dicProductSales.Clear();
this.dgvProduct.Rows.Clear();
}
//选择参与活动的商品
private void dgvProduct_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvProduct.Columns[e.ColumnIndex].HeaderText;
string columnName = dgvProduct.Columns[e.ColumnIndex].Name;
long ProductId = dgvProduct.Rows[e.RowIndex].Cells["colProductId"].Value.ParseToLong();
var row = dgvProduct.Rows[e.RowIndex];
switch (columnName)
{
case "colSelect":
row.Cells["colSelect"].Value = !row.Cells["colSelect"].Value.ParseToBool();
break;
}
}
}
}