Files
KJD_WebService/TEMUKJD/KJDForms/SalesCenterForms/GroupBuyForm.cs
T

903 lines
43 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;
using AllBase.Helper;
using AllBase.Model.Result;
using CefSharp;
using CefSharp.WinForms;
using TemuKJD.Extension;
using TemuKJD.Helper;
using TemuKJD.KJDForms.BaseForms;
using TemuKJD.KJDForms.ShopForms;
using NaiBa.CefHelper;
using NaiBa.CefHelper.Handler;
using NaiBa.Util;
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;
namespace TemuKJD.KJDForms.SalesCenterForms
{
public partial class GroupBuyForm : Form
{
public static List<string> CustomActivityNames = new List<string>();
private CheckBox chkSelectAll = null;
public ChromiumWebBrowser webBrowser = null;
private List<string> lstShopId = new List<string>();
public List<string> keywords = null;
public List<string> filterWords = null;
public decimal priceMin;
public decimal priceMax;
public int saleMin;
public int saleMax;
public int getPage;
public CancellationTokenSource cancellationTokenSource = null;
public GroupBuyForm()
{
InitializeComponent();
}
private void GroupBuyFrom_Load(object sender, EventArgs e)
{
dtpStartTime.Value = DateTime.Now;
dtpEndTime.Value = dtpStartTime.Value.AddDays(1);
CustomActivityNames = NaiBa.Util.Helper.ConfigHelper.LoadConfig<List<string>>("group_buy_custom_names");
if (CustomActivityNames == null)
{
CustomActivityNames = new List<string>();
}
for (int i = 1; i <= 20; i++)
{
this.cmbLimitCount.Items.Add(i + "个");
}
this.cmbLimitCount.SelectedIndex = 0;
this.cmbCancelTime.SelectedIndex = 1;
this.cmbStockType.SelectedIndex = 1;
this.cmbDiscountType.SelectedIndex = 0;
this.cmbSkuOptionType.SelectedIndex = 0;
this.ucTabControl1.TabPages.Clear();
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;
}
private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
if (!chkSelectAll.Checked)
{
lstShopId.Clear();
foreach (DataGridViewRow row in dgvShop.Rows)
{
row.Cells["colSelect"].Value = false;
}
}
else
{
lstShopId.Clear();
var list = GlobalConfig.ShopLoginList.Where(s => s.ApiAuthStatus == "授权成功" && s.LoginStatus == "登录成功").Select(ss => ss.ShopId);
lstShopId.AddRange(list);
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (list.Any(l => l == row.Cells["colShopId"]?.Value?.ToString()))
row.Cells["colSelect"].Value = true;
}
}
}
private void chkAutoGroup_CheckedChanged(object sender, EventArgs e)
{
}
private void cmbDiscountType_SelectedValueChanged(object sender, EventArgs e)
{
}
private void GroupBuyForm_VisibleChanged(object sender, EventArgs e)
{
if (Visible == true)
RefreshShop();
}
private void btnRefreshShop_Click(object sender, EventArgs e)
{
RefreshShop();
}
private void RefreshShop()
{
// 更新选中的上货店铺Id
lstShopId = lstShopId.Where(id => GlobalConfig.ShopLoginList.Any(s => s.ShopId == id && s.LoginStatus == "已授权")).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 (DouShopLoginInfo shopEntity in GlobalConfig.ShopLoginList)
{
BindShop(shopEntity);
}
}
private void BindShop(DouShopLoginInfo shopEntity)
{
if (shopEntity == null)
return;
bool canUse = shopEntity.ApiAuthStatus == "授权成功" && shopEntity.LoginStatus == "登录成功";
var row = dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(p => p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == shopEntity.ShopId);
if (row == null)
{
this.dgvShop.Rows.Add(
lstShopId.Contains(shopEntity.ShopId) && canUse,
shopEntity.ShopId,
shopEntity.ShopAccount,
shopEntity.ApiAuthStatus,
shopEntity.LoginStatus,
canUse,
string.Empty
);
}
else
{
row.Cells["colSelect"].Value = lstShopId.Contains(shopEntity.ShopId) && canUse;
row.Cells["colShopName"].Value = shopEntity.ShopAccount;
row.Cells["colAuthStatus"].Value = shopEntity.ApiAuthStatus;
row.Cells["colLoginStatus"].Value = shopEntity.LoginStatus;
row.Cells["colCanUse"].Value = canUse;
}
}
private void cmbDiscountType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbDiscountType.Text == "打折")
{
nudDiscountValue.Maximum = 9.9m;
nudDiscountValue.Minimum = 0.1m;
nudDiscountValue.Increment = 0.1m;
nudDiscountValue.DecimalPlaces = 1;
nudDiscountValue.Value = 9.9m;
}
else if (cmbDiscountType.Text == "直降")
{
nudDiscountValue.Maximum = 10000m;
nudDiscountValue.Minimum = 0.00m;
nudDiscountValue.Increment = 1m;
nudDiscountValue.DecimalPlaces = 2;
nudDiscountValue.Value = 1m;
}
else if (cmbDiscountType.Text == "一口价")
{
BaseMsgForm.ShowInfo("确定所有商品及Sku价格都按照统一价格设置,请谨慎操作!");
nudDiscountValue.Maximum = 10000m;
nudDiscountValue.Minimum = 0.00m;
nudDiscountValue.Increment = 1m;
nudDiscountValue.DecimalPlaces = 2;
nudDiscountValue.Value = 100m;
}
}
private void cmbStockType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbStockType.Text == "全部库存")
{
nudStockValue.Enabled = false;
nudStockValue.Value = 100;
nudStockValue.Width = 48;
lblPercentSign.Visible = true;
}
else if (cmbStockType.Text == "百分比库存")
{
nudStockValue.Enabled = true;
nudStockValue.Maximum = 100m;
nudStockValue.Minimum = 1m;
nudStockValue.Increment = 1m;
nudStockValue.DecimalPlaces = 0;
nudStockValue.Value = 50m;
nudStockValue.Width = 48;
lblPercentSign.Visible = true;
}
else if (cmbStockType.Text == "统一库存")
{
nudStockValue.Enabled = true;
nudStockValue.Maximum = 10000m;
nudStockValue.Minimum = 1m;
nudStockValue.Increment = 1m;
nudStockValue.DecimalPlaces = 0;
nudStockValue.Value = 100m;
nudStockValue.Width = 65;
lblPercentSign.Visible = false;
}
}
private void btnGetProduct_Click(object sender, EventArgs e)
{
if (lstShopId.Count == 0)
{
BaseMsgForm.ShowInfo("请选择店铺!");
return;
}
try
{
this.keywords = txtProductName.Text.Trim().Split(new string[] { "\r", "\n", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
this.filterWords = txtFilter.Text.Trim().Split(new string[] { "\r", "\n", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
this.priceMin = txtPriceMin.Text.ParseToDecimal();
this.priceMax = txtPriceMax.Text.ParseToDecimal();
this.saleMin = txtSaleMin.Text.ParseToInt();
this.saleMax = txtSaleMax.Text.ParseToInt();
this.getPage = txtGetPage.Text.ParseToInt();
}
catch (Exception ex)
{
BaseMsgForm.ShowError("请正确填写搜索参数!");
return;
}
btnGetProduct.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
foreach (var shopId in lstShopId)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
continue;
if (ShopListForm.Instance == null)
ShopListForm.Instance = new ShopListForm();
ShopListForm.Instance.CheckShopLogin(new string[] { shop.ShopAccount }, false);
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() =>
{
var row = this.dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId);
if (row != null)
{
row.Cells["colLoginStatus"].Value = "未登录";
row.Cells["colCanUse"].Value = false;
}
}));
continue;
}
GroupBuyShopForm groupBuyShopForm = null;
Invoke(new Action(() =>
{
var tab = this.ucTabControl1.TabPages.Cast<TabPage>().FirstOrDefault(t => t.Text == shop.ShopAccount && t.Name == "tab" + shop.ShopId);
if (tab == null)
{
tab = new TabPage();
tab.Name = "tab" + shop.ShopId;
tab.Text = shop.ShopAccount;
this.ucTabControl1.TabPages.Add(tab);
var form = new GroupBuyShopForm(shop);
form.groupBuyForm = this;
form.TopLevel = false;
form.Left = 0;
form.Top = 0;
form.FormBorderStyle = FormBorderStyle.None;
form.AutoSize = true;
form.Dock = DockStyle.Fill;
form.Show();
tab.Controls.Add(form);
}
if (tab.Controls.Count > 0)
{
groupBuyShopForm = tab.Controls[0] as GroupBuyShopForm;
this.ucTabControl1.SelectedTab = tab;
}
}));
if (groupBuyShopForm != null)
{
groupBuyShopForm.InitGetProduct();
GetProductByCef(shop);
}
}
Invoke(new Action(() => { btnGetProduct.Enabled = true; }));
}, cancellationTokenSource.Token);
}
public void GetSales(DouShopLoginInfo shop, bool isSales = true)
{
if (webBrowser == null)
{
Invoke(new Action(() =>
{
webBrowser = CEFBrowser.CreateChromiumWebBrowser("about:blank", false);
webBrowser.KeyboardHandler = new KeyboardHandler();
webBrowser.Dock = DockStyle.Fill;
Helper.CustomResourceRequestHandlerLocal resourceRequestHandler = new Helper.CustomResourceRequestHandlerLocal();
resourceRequestHandler.ResourceLoadCompleteEvent += RequestHandler_ResourceLoadCompleteEvent;
webBrowser.RequestHandler = new CustomRequestHandler(resourceRequestHandler);
webBrowser.LifeSpanHandler = new LifeSpanHandlerLocal(PopWindowType.SelfWindow);
webBrowser.SendToBack();
this.splitContainer1.Panel2.Controls.Add(webBrowser);
}));
}
while (webBrowser.Tag != null)
{
Thread.Sleep(Randomx.GetId(50, 100));
}
if (cancellationTokenSource.IsCancellationRequested)
return;
webBrowser.Tag = shop;
while (!webBrowser.IsBrowserInitialized || webBrowser.IsLoading)
continue;
var cookie = shop.Cookies;
CEFBrowser.DeleteCookie(webBrowser.RequestContext.GetCookieManager(null));
var t = CEFBrowser.SetCookieAsync("jinritemai.com", cookie, webBrowser.RequestContext.GetCookieManager(null));
t.Wait(2000);
Thread.Sleep(500);
var targetUrl = "https://fxg.jinritemai.com/ffa/g/list";
webBrowser.Load(targetUrl);
while (webBrowser.IsLoading)
{
Thread.Sleep(1000);
}
Thread.Sleep(3000);
if (!isSales)
{
Thread.Sleep(3000);
var jsStrBase = "function clickProductAnalysis(txt) {\r\n"
+ "var child = document.body.firstElementChild;\r\n"
+ "var element1 = null;\r\n"
+ " while (child) {\r\n"
+ " if (child.innerHTML.indexOf(txt) >= 0) {\r\n"
+ " element1 = child;\r\n"
+ " if (child.firstElementChild) {\r\n"
+ " child = child.firstElementChild; continue;\r\n"
+ " } else break;\r\n"
+ " }\r\n"
+ " child = child.nextElementSibling;\r\n"
+ " }\r\n"
+ " if (element1) {\r\n"
+ " element1.click(); return 'success';\r\n"
+ " } else return 'no_element';\r\n"
+ "}\r\n";
var jsStr = jsStrBase + "clickProductAnalysis('电商罗盘');\r\n";
t = webBrowser.GetMainFrame().EvaluateScriptAsync(jsStr);
t.Wait();
while (webBrowser.IsLoading)
{
Thread.Sleep(1000);
}
Thread.Sleep(Randomx.GetId(1500, 2500));
jsStr = jsStrBase + "clickProductAnalysis('商品概览');\r\n";
t = webBrowser.GetMainFrame().EvaluateScriptAsync(jsStr);
t.Wait();
while (webBrowser.IsLoading)
{
Thread.Sleep(1000);
}
Thread.Sleep(Randomx.GetId(1500, 2500));
}
while (webBrowser.Tag != null)
{
Thread.Sleep(Randomx.GetId(50, 100));
}
Thread.Sleep(3000);
}
public void GetProductByCef(DouShopLoginInfo shop)
{
if (webBrowser == null)
{
Invoke(new Action(() =>
{
webBrowser = CEFBrowser.CreateChromiumWebBrowser("about:blank", false);
webBrowser.KeyboardHandler = new KeyboardHandler();
webBrowser.Dock = DockStyle.Fill;
CustomResourceRequestHandlerLocal resourceRequestHandler = new CustomResourceRequestHandlerLocal();
resourceRequestHandler.ResourceLoadCompleteEvent += RequestHandler_ResourceLoadCompleteEvent;
webBrowser.RequestHandler = new CustomRequestHandler(resourceRequestHandler);
webBrowser.LifeSpanHandler = new LifeSpanHandlerLocal(PopWindowType.SelfWindow);
webBrowser.SendToBack();
this.splitContainer1.Panel2.Controls.Add(webBrowser);
}));
}
while (webBrowser.Tag != null)
{
Thread.Sleep(Randomx.GetId(50, 100));
}
if (cancellationTokenSource.IsCancellationRequested)
return;
webBrowser.Tag = shop;
while (!webBrowser.IsBrowserInitialized || webBrowser.IsLoading)
continue;
var cookie = shop.Cookies;
CEFBrowser.DeleteCookie(webBrowser.RequestContext.GetCookieManager(null));
var t = CEFBrowser.SetCookieAsync("jinritemai.com", cookie, webBrowser.RequestContext.GetCookieManager(null));
t.Wait(2000);
Thread.Sleep(500);
var targetUrl = "https://fxg.jinritemai.com/ffa/g/list";
webBrowser.Load(targetUrl);
while (webBrowser.IsLoading)
{
Thread.Sleep(1000);
}
Thread.Sleep(3000);
while (webBrowser.Tag != null)
{
Thread.Sleep(Randomx.GetId(50, 100));
}
Thread.Sleep(3000);
}
private void RequestHandler_ResourceLoadCompleteEvent(object sender, string url, string postData, string responseData, CefSharp.IRequest iRequest)
{
if (url.StartsWith("https://fxg.jinritemai.com/product/tproduct/list?page=0") && url.Contains("&pay_type="))
{
if (webBrowser.Tag != null)
{
var listUrl = url;
var referrerUrl = iRequest.ReferrerUrl;
var result = responseData;
Dictionary<string, string> headers = new Dictionary<string, string>();
foreach (var hk in iRequest.Headers.AllKeys)
{
headers[hk] = iRequest.Headers[hk];
}
Task.Run(() =>
{
var cookies = CEFBrowser.GetCookie("", webBrowser.RequestContext.GetCookieManager(null));
GroupBuyShopForm salesForm = null;
Invoke(new Action(() =>
{
var shop = webBrowser.Tag as DouShopLoginInfo;
var tab = this.ucTabControl1.TabPages.Cast<TabPage>().FirstOrDefault(t => t.Text == shop.ShopAccount && t.Name == "tab" + shop.ShopId);
salesForm = tab.Controls[0] as GroupBuyShopForm;
}));
if (salesForm != null)
salesForm.GetProductSim(listUrl, referrerUrl, headers, "");
Invoke(new Action(() =>
{
webBrowser.Tag = null;
}));
Thread.Sleep(1000);
});
}
}
}
private void btnSetName_Click(object sender, EventArgs e)
{
GroupBuyCustomActivityNameForm customNameForm = new GroupBuyCustomActivityNameForm();
customNameForm.ShowDialog();
}
private void label14_Click(object sender, EventArgs e)
{
if (this.webBrowser != null)
{
webBrowser.SendToBack();
}
}
private void label14_DoubleClick(object sender, EventArgs e)
{
if (this.webBrowser != null)
{
webBrowser.BringToFront();
}
}
private void btnStopGetProduct_Click(object sender, EventArgs e)
{
if (cancellationTokenSource != null)
cancellationTokenSource.Cancel();
webBrowser.Tag = null;
}
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 shopName = dgvShop.Rows[e.RowIndex].Cells["colShopId"].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 = !row.Cells["colSelect"].Value.ParseToBool();
if (dgvShop.Rows[e.RowIndex].Cells["colSelect"].Value.ParseToBool())
{
if (lstShopId.Any(p => p == shopId.ToString()))
lstShopId.RemoveAll(p => p == shopId.ToString());
lstShopId.Add(shopId.ToString());
}
else
lstShopId.Remove(shopId.ToString());
if (dgvShop.Rows.Cast<DataGridViewRow>().All(r => r.Cells["colSelect"].Value.ParseToBool()))
chkSelectAll.Checked = true;
else
chkSelectAll.Checked = false;
}
else
{
BaseMsgForm.ShowInfo("店铺未授权或未登录!");
}
break;
}
}
private void btnSetActivity_Click(object sender, EventArgs e)
{
// 每个活动商品数量
var eachActivityProductNum = nudEachActivityProductNum.Text.ParseToInt();
// 是否使用自定义活动名称
var isUseCustomActivityNames = rbCustomNames.Checked;
// 自定义活动名称临时列表
List<string> customNamesTemp = new List<string>(CustomActivityNames);
if (rbCustomNames.Checked && customNamesTemp.Count == 0)
{
BaseMsgForm.ShowInfo("请设置自定义活动名称!");
return;
}
// 开始时间
var startTime = dtpStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
// 结束时间
var endTime = dtpEndTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
// 订单取消时间
var orderExpireTime = cmbCancelTime.Text.Replace("分钟", "").ParseToInt() * 60;
// 成团数量
var groupNum = nudGroupCount.Value.ToString();
if (nudGroupCount.Value < 5)
{
nudGroupCount.Value = 5;
BaseMsgForm.ShowError("成团数量需大于等于5,已为您自动修改");
return;
}
// 自动成团
var autoGroup = this.chkAutoGroup.Checked ? "1" : "0";
// 设置单个sku
var isSetSkuOption = this.chkSetSkuOption.Checked;
var skuOptionType = this.cmbSkuOptionType.Text;
// 库存类型
var stockType = this.cmbStockType.Text;
// 库存数量
var stockValue = nudStockValue.Text.ParseToInt();
// 每人限购
var userLimit = this.cmbLimitCount.Text.Replace("个", "").Replace("不限购", "0");
// 折扣类型
var discountType = this.cmbDiscountType.Text;
// 折扣数值
var discountValue = this.nudDiscountValue.Text.ParseToDecimal();
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
foreach (var shopId in lstShopId)
{
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
continue;
if (ucTabControl1.TabPages["tab" + shopId] != null && ucTabControl1.TabPages["tab" + shopId].Controls.Count > 0)
{
var salesForm = ucTabControl1.TabPages["tab" + shopId].Controls[0] as GroupBuyShopForm;
if (salesForm == null)
continue;
Invoke(new Action(() =>
{
salesForm.statusBar.lblTaskStatus.Text = "正在创建拼团活动";
}));
List<string> productIdList = salesForm.lstProductId;
if (productIdList.Count == 0)
{
BaseMsgForm.ShowInfo("请选择店铺 " + shop.ShopAccount + " 参加活动的商品!");
continue;
}
else
{
List<string> pIdListTemp = new List<string>();
for (int i = 0; i < productIdList.Count; i++)
{
var pid = productIdList[i];
pIdListTemp.Add(pid);
if ((i + 1) % eachActivityProductNum == 0 || i == productIdList.Count - 1)
{
var pIdsStrTemp = "\"" + string.Join("\",\"", pIdListTemp) + "\"";
pIdListTemp.Clear();
#region 获取活动商品的所有Sku
string pIdData = @"{ ""product_ids"":[" + pIdsStrTemp + "]}";
var cookies = shop.Cookies;
var result = salesForm.GetSkusByProductIds(pIdData, cookies);
#endregion
#region 生成活动名称
string activityId = Math.Ceiling((i + 1m) / eachActivityProductNum).ToString();
activityId = activityId.Replace("1", "一").Replace("2", "二").Replace("3", "三").Replace("4", "四").Replace("5", "五");
activityId = activityId.Replace("6", "六").Replace("7", "七").Replace("8", "八").Replace("9", "九").Replace("0", "零");
var actvityName = "活动" + activityId;
#region 自定义活动
if (isUseCustomActivityNames)
{
if (customNamesTemp != null && customNamesTemp.Count > 0)
{
actvityName = customNamesTemp[0];
customNamesTemp.RemoveAt(0);
}
else
{
Invoke(new Action(() => { salesForm.ShowVisitorMessage("活动创建中断,自定义名称活动数量不足!"); }));
break;
}
}
#endregion
#endregion
//string postData = "{\"stype\":\"120\",\"title\":\"活动一\",
//\"begin_time\":\"2022-06-23 13:49:54\",\"end_time\":\"2022-06-24 13:49:54\",\"order_expire_time\":\"300\",
//\"group_num\":\"9\",\"auto_group\":\"1\",\"promotion_goods\":[
//{\"product_id\":\"3556136493124815095\",\"promotion_skus\":[
// {\"camp_stock_num\":\"33\",\"id\":\"1736394771542030\",\"price\":\"27100\",\"user_limit\":\"19\",\"spec_detail_id1\":\"1736394770390024\",\"spec_detail_id2\":\"1736394770391096\",\"spec_detail_id3\":\"0\"},{\"camp_stock_num\":\"44\",\"id\":\"1736394771275831\",\"price\":\"26100\",\"user_limit\":\"14\",\"spec_detail_id1\":\"1736394770390024\",\"spec_detail_id2\":\"1736394770391080\",\"spec_detail_id3\":\"0\"}]},{\"product_id\":\"3554645628321712559\",\"promotion_skus\":[{\"camp_stock_num\":\"11\",\"id\":\"1735666808135704\",\"price\":\"3700\",\"user_limit\":\"0\",\"spec_detail_id1\":\"1735666809832616\",\"spec_detail_id2\":\"0\",\"spec_detail_id3\":\"0\"},{\"camp_stock_num\":\"22\",\"id\":\"1735666808135688\",\"price\":\"4100\",\"user_limit\":\"0\",\"spec_detail_id1\":\"1735666809832600\",\"spec_detail_id2\":\"0\",\"spec_detail_id3\":\"0\"}]}]}";
var postData = "{\"stype\":\"120\",\"title\":\"" + actvityName + "\"," +
"\"begin_time\":\"" + startTime + "\",\"end_time\":\"" + endTime + "\",\"order_expire_time\":\"" + orderExpireTime + "\"," +
"\"group_num\":\"" + groupNum + "\",\"auto_group\":\"" + autoGroup + "\",\"promotion_goods\":[";
JObject jObj = JObject.Parse(result);
foreach (JProperty jProp in jObj["data"])
{
var id = jProp.Name;
DouProductPromotionListInfo info = salesForm.productList.FirstOrDefault(q => q.product_id == id);
if (info != null)
{
postData = postData + "{\"product_id\":\"" + id + "\",\"promotion_skus\":[";
if (isSetSkuOption)
{
JArray arr = jObj["data"][id] as JArray;
var objs = new List<JToken>() { arr.FirstOrDefault(o => o["stock"]?.ParseToInt() > 0) };
if (skuOptionType == "最后一个")
objs = new List<JToken>() { arr.LastOrDefault(o => o["stock"]?.ParseToInt() > 0) };
if (skuOptionType == "最贵")
objs = new List<JToken>() { arr.OrderBy(o => o["origin_price"]).LastOrDefault(o => o["stock"]?.ParseToInt() > 0) };
if (skuOptionType == "最便宜")
objs = new List<JToken>() { arr.OrderBy(o => o["origin_price"]).FirstOrDefault(o => o["stock"]?.ParseToInt() > 0) };
if (skuOptionType == "不设置最便宜")
{
objs = arr.OrderBy(o => o["origin_price"]).Skip(1).ToList();
}
if (skuOptionType == "不设置最贵")
{
objs = arr.OrderBy(o => o["origin_price"]).Take(objs.Count).ToList();
}
foreach (var obj in objs)
{
var totalStock = obj["stock"].ParseToInt();
var stock = totalStock;
if (stockType == "百分比库存")
{
stock = stockValue * totalStock / 100;
}
else if (stockType == "统一库存")
{
stock = stockValue;
}
if (stock <= groupNum.ParseToInt())
stock = groupNum.ParseToInt();
if (stock > totalStock)
stock = totalStock;
if (stock < 5) // 跳过库存不足的sku
continue;
var newPrice = obj["origin_price"].ParseToInt() * discountValue / 10; // 打折
if (discountType == "直降")
{
newPrice = obj["origin_price"].ParseToInt() - discountValue * 100;
}
else if (discountType == "一口价")
{
newPrice = discountValue * 100;
}
postData = postData + "{\"camp_stock_num\":\"" + stock +
"\",\"id\":\"" + obj["id"] + "\",\"price\":\"" + (int)newPrice +
"\",\"user_limit\":\"" + userLimit + "\",\"spec_detail_id1\":\"" + obj["spec_detail_id1"] +
"\",\"spec_detail_id2\":\"" + obj["spec_detail_id2"] + "\",\"spec_detail_id3\":\"" + obj["spec_detail_id3"] + "\"},";
}
}
else
{
JArray arr = jObj["data"][id] as JArray;
foreach (JObject obj in arr)
{
var totalStock = obj["stock"].ParseToInt();
var stock = totalStock;
if (stockType == "百分比库存")
{
stock = stockValue * totalStock / 100;
}
else if (stockType == "统一库存")
{
stock = stockValue;
}
if (stock <= groupNum.ParseToInt())
stock = groupNum.ParseToInt();
if (stock > totalStock)
stock = totalStock;
if (stock < 5) // 跳过库存不足的sku
continue;
var newPrice = obj["origin_price"].ParseToInt() * discountValue / 10; // 打折
if (discountType == "直降")
{
newPrice = obj["origin_price"].ParseToInt() - discountValue * 100;
}
else if (discountType == "一口价")
{
newPrice = discountValue * 100;
}
postData = postData + "{\"camp_stock_num\":\"" + stock +
"\",\"id\":\"" + obj["id"] + "\",\"price\":\"" + (int)newPrice +
"\",\"user_limit\":\"" + userLimit + "\",\"spec_detail_id1\":\"" + obj["spec_detail_id1"] +
"\",\"spec_detail_id2\":\"" + obj["spec_detail_id2"] + "\",\"spec_detail_id3\":\"" + obj["spec_detail_id3"] + "\"},";
}
}
postData = postData.TrimEnd(',') + "]},";
}
}
postData = postData.TrimEnd(',') + "]}";
string checkPro = salesForm.checkGroupBuyGoods(postData, cookies);
if (checkPro.Contains("{\"st\":0,\"msg\":\"\",\"code\":0,"))
{
string createPro = salesForm.createGroupBuyGoods(postData, cookies);
if (createPro.Contains("{\"st\":0,\"msg\":\"\",\"code\":0,"))
{
Invoke(new Action(() => { salesForm.ShowVisitorMessage("活动 " + actvityName + " 创建成功!", pIdsStrTemp); }));
}
else
{
Invoke(new Action(() => { salesForm.ShowVisitorMessage(actvityName + "拼团创建失败!原因:" + BaseRegex.GetStringJson(ref createPro, "msg"), pIdsStrTemp); }));
}
}
else
{
Invoke(new Action(() => { salesForm.ShowVisitorMessage(actvityName + "拼团创建失败!原因:" + BaseRegex.GetStringJson(ref checkPro, "msg"), pIdsStrTemp); }));
}
Thread.Sleep(Randomx.GetId(1500, 3500));
}
}
}
Invoke(new Action(() => { salesForm.statusBar.lblTaskStatus.Text = "创建拼团活动完成"; }));
}
}
}, cancellationTokenSource.Token);
}
private void dtpStartTime_ValueChanged(object sender, EventArgs e)
{
if (dtpEndTime.Value > dtpStartTime.Value.AddDays(1) || dtpEndTime.Value <= dtpStartTime.Value)
dtpEndTime.Value = dtpStartTime.Value.AddDays(1);
}
private void btnClear_Click(object sender, EventArgs e)
{
if (BaseMsgForm.ShowConfirm("确定要清空结果吗?清空后需要重新获取!").DialogResult == DialogResult.OK)
{
foreach (TabPage tp in ucTabControl1.TabPages)
{
if (tp.Controls.Count > 0)
{
if (tp.Text.Contains("活动管理"))
{
//var managerActiveForm = tp.Controls[0] as LimitedSalesManagerActiveForm;
//if (managerActiveForm != null)
// managerActiveForm.ClearData();
//if (splitContainer4.Panel1.Controls.Count == 2)
// splitContainer4.Panel1.Controls.RemoveAt(1);
}
else
{
var salesForm = tp.Controls[0] as GroupBuyShopForm;
if (salesForm != null)
salesForm.ClearData();
}
}
}
}
}
private void btnStopOperate_Click(object sender, EventArgs e)
{
if (cancellationTokenSource != null)
cancellationTokenSource.Cancel();
webBrowser.Tag = null;
}
private void pbPaste1_Click(object sender, EventArgs e)
{
IDataObject iData = Clipboard.GetDataObject();
if (iData != null && iData.GetDataPresent(DataFormats.Text))
{
txtProductName.Text = (string)iData.GetData(DataFormats.Text);
}
}
private void pbPaste2_Click(object sender, EventArgs e)
{
IDataObject iData = Clipboard.GetDataObject();
if (iData != null && iData.GetDataPresent(DataFormats.Text))
{
txtFilter.Text = (string)iData.GetData(DataFormats.Text);
}
}
private void nudGroupCount_ValueChanged(object sender, EventArgs e)
{
}
List<Keys> keyList = new List<Keys>();
private void nudGroupCount_KeyDown(object sender, KeyEventArgs e)
{
var x = nudGroupCount.Value;
//if (e.KeyData == (Keys.Alt | Keys.Add))
//{
// this.nudGroupCount.Maximum = 10000m;
//}
if (keyList.LastOrDefault() != e.KeyData)
keyList.Clear();
keyList.Add(e.KeyData);
if (keyList.Count >= 5 && e.KeyData == (Keys.Menu | Keys.Alt))
this.nudGroupCount.Maximum = 10000m;
}
}
}