using AllBase; using AllBase.Helper; using AllBase.Model.Result; 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.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 SeckillingAndLimitedSalesForm : Form { public static List CustomActivityNames { get; set; } = new List(); public CancellationTokenSource cancellationTokenSource { get; set; } = null; public CancellationTokenSource addActiveCancellationTokenSource { get; set; } = null; public ChromiumWebBrowser webBrowser { get; set; } = null; private CheckBox chkSelectAll = null; private List customActivityNamesTemp = null; private List lstShopId = new List(); private string shop_stype = "2"; // 1一口价 2直降 3打折 private string campaign_start_time; private string campaign_end_time; // 每个活动商品数量 int eachActivityProductNum = 1; // 每人限购 string userLimit = "1"; // 活动时间类型 // 按开始结束时间 或 按时间段 string timeSetType = "1"; // 活动库存售完后如何操作 string soldOutType = "1"; // 开始时间 DateTime startTime = new DateTime(); // 结束时间 DateTime endTime = new DateTime(); // (按时间段类型活动的)活动持续时间 int actDuration = 0; // 预热提前天 string preDayStr = ""; // 预热提前小时 string pteHourStr = ""; // 取消订单时间 string cancelTime = ""; // 是否预热 bool isPreheat = false; // 只设置一个或设设置指定sku bool isSetSkuOption = false; // 设置一个sku的类型(第一个,最后一个,价格最高,最低) string skuOptionType = ""; // 批量设置自定义名称 bool isUseCustomActivityNames = false; // 库存类型 string stockType = ""; // 库存数量 int stockValue = 1; // 最低折扣 decimal maxDiscount = 0.95M; // 最少降价金额 decimal minReducePrice = 1M; // 普通sku折扣/降价 string strPrice = string.Empty; // 最低sku折扣/降价 string strPriceMin = string.Empty; /// /// 普通sku换算后用于设置的折扣/降价 /// string strSetPrice = string.Empty; /// /// 最低sku换算后用于设置的折扣/降价 /// string strSetPriceMin = string.Empty; /// /// 搜索指定商品列表 /// public List LstSearthProductId { get; set; } = new List(); public SeckillingAndLimitedSalesForm() { InitializeComponent(); } private void SeckillingAndLimitedSalesForm_Load(object sender, EventArgs e) { this.ucTabControl1.TabPages.Clear(); CustomActivityNames = NaiBa.Util.Helper.ConfigHelper.LoadConfig>("limited_sales_custom_names"); if (CustomActivityNames == null && FileBase.Exists("SetActiveNames.txt")) { var namesStr = FileBase.ReadAllText("SetActiveNames.txt"); CustomActivityNames = namesStr.Split(new string[] { "\r", "\n", "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); } if (CustomActivityNames == null) { CustomActivityNames = new List(); } 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; dtpStartTime.Value = DateTime.Now.Date; dtpEndTime.Value = DateTime.Now.Date.AddDays(1).AddSeconds(-1); if (cmbCancelTime.Items.Count > 1) cmbCancelTime.SelectedIndex = 1; for (int i = 0; i <= 10; i++) { cmbDays.Items.Add(i + "天"); } cmbDays.SelectedIndex = 0; cmbHours.Items.Add("0.25小时"); cmbHours.Items.Add("0.5小时"); cmbHours.Items.Add("1小时"); cmbHours.Items.Add("1.5小时"); cmbHours.Items.Add("2小时"); cmbHours.Items.Add("2.5小时"); cmbHours.Items.Add("3小时"); cmbHours.Items.Add("3.5小时"); for (int i = 4; i <= 12; i++) { cmbHours.Items.Add(i + "小时"); } cmbHours.SelectedIndex = 0; //设置限购数 for (int x = 1; x <= 20; x++) { cmbLimit.Items.Add(x); } cmbLimit.SelectedIndex = 0; //设置一个活动多少产品 for (int a = 1; a <= 20; a++) { cmbSetPro.Items.Add(a); } cmbSetPro.SelectedIndex = 0; nudStockValue.Text = "1"; //参与活动库存 txtSKUPriceMin.Text = "1"; //设置打折数 txtSKUPriceCommon.Text = "1"; cmbActCont.SelectedIndex = 3; //按时间段选择默认30分钟 this.cmbStockType.SelectedIndex = 1; this.cmbSkuOptionType.SelectedIndex = 0; rbNotPreheat_CheckedChanged(null, null); } private void SeckillingAndLimitedSalesForm_VisibleChanged(object sender, EventArgs e) { if (Visible == true) RefreshShop(); } 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 rbNotPreheat_CheckedChanged(object sender, EventArgs e) { if (!rbNotPreheat.Checked) { pnlPreheat.Visible = true; pnlDiscount.Location = new Point(pnlDiscount.Location.X, pnlPreheat.Location.Y + pnlPreheat.Height + 5); lblDiscount.Location = new Point(lblDiscount.Location.X, pnlPreheat.Location.Y + pnlPreheat.Height + 8); flpPrice.Location = new Point(flpPrice.Location.X, pnlDiscount.Location.Y + pnlPreheat.Height); } else { pnlPreheat.Visible = false; pnlDiscount.Location = new Point(pnlDiscount.Location.X, pnlPreheat.Location.Y + 5); lblDiscount.Location = new Point(lblDiscount.Location.X, pnlPreheat.Location.Y + 8); flpPrice.Location = new Point(flpPrice.Location.X, pnlDiscount.Location.Y + pnlDiscount.Height); } } private void rbStartEndTime_CheckedChanged(object sender, EventArgs e) { if (rbStartEndTime.Checked) { dtpStartTime.Visible = true; label1.Visible = true; dtpEndTime.Visible = true; this.panel7.Visible = false; } else { dtpStartTime.Visible = false; label1.Visible = false; dtpEndTime.Visible = false; this.panel7.Visible = true; } } 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 dgvRowList = dgvShop.Rows.Cast().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().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 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.RemoveAll(p => p == shopId.ToString()); if (dgvShop.Rows.Cast().All(r => r.Cells["colSelect"].Value.ParseToBool())) chkSelectAll.Checked = true; else chkSelectAll.Checked = false; } else { BaseMsgForm.ShowInfo("店铺未授权或未登录!"); } break; } } private void btnGetProduct_Click(object sender, EventArgs e) { if (lstShopId.Count == 0) { BaseMsgForm.ShowInfo("请选择店铺!"); return; } LstSearthProductId = txtContainsId.Text.Split(new string[] { "\r", "\n", "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); campaign_start_time = dtpStartTime.Value.ToString("yyyy-MM-dd+HH:mm:ss"); campaign_end_time = dtpEndTime.Value.ToString("yyyy-MM-dd+HH:mm:ss"); if (rbTimePeriod.Checked) { var time = DateTime.Now; var actDuration = cmbActCont.Text.Replace("小时", "").Replace("分钟", "").ParseToInt() * (cmbActCont.Text.Contains("小时") ? 60 : 1); campaign_start_time = time.ToString("yyyy-MM-dd+HH:mm:ss"); campaign_end_time = time.AddMinutes(actDuration).ToString("yyyy-MM-dd+HH:mm:ss"); } btnGetProduct.Enabled = false; cancellationTokenSource = new CancellationTokenSource(); Task.Run(() => { var lstShopIdTemp = new List(); lstShopIdTemp.AddRange(lstShopId); foreach (var shopId in lstShopIdTemp) { 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().FirstOrDefault(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId); if (row != null) { row.Cells["colLoginStatus"].Value = "未登录"; row.Cells["colCanUse"].Value = false; } })); continue; } SeckillingAndLimitedSalesShopForm salesShopForm = null; Invoke(new Action(() => { var tab = this.ucTabControl1.TabPages.Cast().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 SeckillingAndLimitedSalesShopForm = new SeckillingAndLimitedSalesShopForm(shop); SeckillingAndLimitedSalesShopForm.SeckillingAndLimitedSalesForm = this; SeckillingAndLimitedSalesShopForm.TopLevel = false; SeckillingAndLimitedSalesShopForm.Left = 0; SeckillingAndLimitedSalesShopForm.Top = 0; SeckillingAndLimitedSalesShopForm.FormBorderStyle = FormBorderStyle.None; SeckillingAndLimitedSalesShopForm.AutoSize = true; SeckillingAndLimitedSalesShopForm.Dock = DockStyle.Fill; SeckillingAndLimitedSalesShopForm.Show(); tab.Controls.Add(SeckillingAndLimitedSalesShopForm); } if (tab.Controls.Count > 0) { salesShopForm = tab.Controls[0] as SeckillingAndLimitedSalesShopForm; this.ucTabControl1.SelectedTab = tab; } })); if (salesShopForm != null) { salesShopForm.GetProduct(); } } Invoke(new Action(() => { btnManageAct.Enabled = btnGetProduct.Enabled = btnSubAct.Enabled = btnMdyAct.Enabled = true; })); }, cancellationTokenSource.Token); } 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; 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); 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 headers = new Dictionary(); foreach (var hk in iRequest.Headers.AllKeys) { headers[hk] = iRequest.Headers[hk]; } var shop = webBrowser.Tag as DouShopLoginInfo; var tab = this.ucTabControl1.TabPages.Cast().FirstOrDefault(t => t.Text == shop.ShopAccount && t.Name == "tab" + shop.ShopId); var salesForm = tab.Controls[0] as SeckillingAndLimitedSalesShopForm; Task.Run(() => { var cookies = CEFBrowser.GetCookie("", webBrowser.RequestContext.GetCookieManager(null)); if (salesForm != null) salesForm.GetProductSim(listUrl, referrerUrl, headers, "", campaign_start_time, campaign_end_time); webBrowser.Tag = null; Thread.Sleep(1000); }); } } // 活动管理界面 else if (url.StartsWith("https://fxg.jinritemai.com/shop/promotion/listFlashWithTimeLimit?campaign_status=") && url.Contains("&shop_stype=")) { if (webBrowser.Tag != null) { var listUrl = url; var referrerUrl = iRequest.ReferrerUrl; var result = responseData; Dictionary headers = new Dictionary(); foreach (var hk in iRequest.Headers.AllKeys) { headers[hk] = iRequest.Headers[hk]; } var shop = webBrowser.Tag as DouShopLoginInfo; var tab = this.ucTabControl1.TabPages.Cast().FirstOrDefault(t => t.Text == shop.ShopAccount + "活动管理" && t.Name == "tab" + shop.ShopId + "Active"); var managerActiveForm = tab.Controls[0] as LimitedSalesManagerActiveForm; Task.Run(() => { var cookies = CEFBrowser.GetCookie("", webBrowser.RequestContext.GetCookieManager(null)); if (managerActiveForm != null) managerActiveForm.GetActiveSim(listUrl, referrerUrl, headers, result); webBrowser.Tag = null; Thread.Sleep(1000); }); } } } private void lblTime_Click(object sender, EventArgs e) { if (this.webBrowser != null) { webBrowser.SendToBack(); } } private void lblTime_DoubleClick(object sender, EventArgs e) { if (this.webBrowser != null) { webBrowser.BringToFront(); } } private void btnSubAct_Click(object sender, EventArgs e) { lstShopId = dgvShop.Rows.Cast().Where(row => row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); if (lstShopId.Count <= 0) { BaseMsgForm.ShowInfo("请选择要设置的店铺!"); return; } var initResult = InitParams(); if (!initResult) return; addActiveCancellationTokenSource = new CancellationTokenSource(); btnGetProduct.Enabled = false; btnSubAct.Enabled = false; btnMdyAct.Enabled = false; Task.Run(() => { var lstShopIdTemp = new List(); lstShopIdTemp.AddRange(lstShopId); foreach (var shopId in lstShopIdTemp) { 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 SeckillingAndLimitedSalesShopForm; if (salesForm == null) continue; Invoke(new Action(() => { salesForm.statusBar.lblTaskStatus.Text = "正在创建活动"; })); List productIdList = salesForm.LstProductId; if (productIdList.Count == 0) { BaseMsgForm.ShowInfo("请选择店铺 " + shop.ShopAccount + " 参加活动的商品!"); continue; } else { var productList = salesForm.ProductList.Where(p => productIdList.Contains(p.product_id)).ToList(); AddOrMdyActivity(shop, productList, null, salesForm); } Invoke(new Action(() => { if (addActiveCancellationTokenSource.IsCancellationRequested) salesForm.statusBar.lblTaskStatus.Text = "活动创建中断"; else salesForm.statusBar.lblTaskStatus.Text = "活动创建结束"; })); } } Invoke(new Action(() => { btnManageAct.Enabled = btnGetProduct.Enabled = btnSubAct.Enabled = btnMdyAct.Enabled = true; })); }, addActiveCancellationTokenSource.Token); } private void AddOrMdyActivity(DouShopLoginInfo shop, List productList, ActiveInfo active, SeckillingAndLimitedSalesShopForm salesForm = null, LimitedSalesManagerActiveForm manageForm = null) { string activityName = ""; string pIdData = @"{""product_ids"":["; List pIdList = new List(); int nameId = 1; for (int i = 0; i < productList.Count; i++) { if (addActiveCancellationTokenSource.IsCancellationRequested) break; activityName = ""; if (active != null) activityName = active.title; DouProductPromotionListInfo info = productList[i]; string pid = info.product_id; pIdList.Add(pid); if ((i + 1) % eachActivityProductNum == 0 || i == productList.Count - 1) { string pIdStr = "\"" + string.Join("\",\"", pIdList) + "\""; pIdData = pIdData + pIdStr.TrimEnd(',') + "]}"; pIdList.Clear(); string cookies = shop.Cookies; string result = ""; if (salesForm != null) result = salesForm.GetSkusByProductIds(pIdData, cookies); else if (manageForm != null) result = manageForm.GetSkusByProductIds(pIdData, cookies); if (!result.Contains("\"st\":0")) continue; // 还原商品详情查询字段 pIdData = @"{""product_ids"":["; // 设置活动名称 if (string.IsNullOrEmpty(activityName)) { activityName = "限时限量" + nameId + "-" + DateTime.Now.ToString("MMddHHmmss"); nameId++; if (isUseCustomActivityNames) { if (customActivityNamesTemp != null && customActivityNamesTemp.Count > 0) { activityName = customActivityNamesTemp[0]; customActivityNamesTemp.RemoveAt(0); } else { Invoke(new Action(() => { if (salesForm != null) salesForm.ShowVisitorMessage("活动创建失败,自定义名称数量不足!", pIdStr); })); break; } } } string postData = "{\"sub_stype\":\"0\",\"shop_stype\":\"" + shop_stype + "\",\"title\":\"" + activityName + "\",\"time_set_type\":\"" + timeSetType + "\",\"promotion_goods\":["; JObject jObj = JObject.Parse(result); foreach (JProperty jp in jObj["data"]) { string errorMsg = ""; var id = jp.Name; var productJson = "{\"product_id\":\"" + id + "\",\"title\":\"" + info.name + "\",\"cover\":\"" + info.img + "\",\"config_scope\":\"0\",\"promotion_skus\":["; JArray arr = jp.Value as JArray; // 处理指定sku下商品的逻辑 if (isSetSkuOption) { // 默认第一个 var objs = new List() { arr.FirstOrDefault(o => o["stock"]?.ParseToInt() > 0) }; if (skuOptionType == "最后一个") objs = new List() { arr.LastOrDefault(o => o["stock"]?.ParseToInt() > 0) }; if (skuOptionType == "最贵") objs = new List() { arr.OrderBy(o => o["origin_price"]).LastOrDefault(o => o["stock"]?.ParseToInt() > 0) }; if (skuOptionType == "最便宜") objs = new List() { 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(); } if (objs == null || objs.Count == 0) { errorMsg = "满足条件的商品库存为0"; pIdStr = pIdStr.Replace(id, ""); break; } foreach (var obj in objs) { int totalStock = obj["stock"].ParseToInt(); int origin_price = obj["origin_price"].ParseToInt(); var stockNum = totalStock; if (stockType == "百分比库存") { stockNum = stockValue * totalStock / 100; } else if (stockType == "统一库存") { stockNum = stockValue; } if (stockNum > totalStock) { //stockNum = totalStock; errorMsg = "商品Sku库存不足"; pIdStr = pIdStr.Replace(id, ""); break; } if (stockNum < 1) stockNum = 1; if (shop_stype == "1") productJson = productJson + "{\"id\":\"" + obj["id"] + "\",\"camp_stock_num\":\"" + stockNum + "\",\"user_limit\":\"" + userLimit + "\",\"price\":\"" + strSetPrice + "\"},"; else { if (shop_stype == "2" && strSetPrice.ParseToDecimal() / origin_price < 1 - maxDiscount) { errorMsg = "商品优惠力度不足" + (maxDiscount * 10).ToString() + "折"; pIdStr = pIdStr.Replace(id, ""); break; } if (shop_stype == "3" && origin_price * (1 - strSetPrice.ParseToDecimal() / 100) < 100) { errorMsg = "商品优惠力度不足" + minReducePrice + "元"; pIdStr = pIdStr.Replace(id, ""); break; } productJson = productJson + "{\"id\":\"" + obj["id"] + "\",\"camp_stock_num\":\"" + stockNum + "\",\"user_limit\":\"" + userLimit + "\",\"price\":\"undefined\",\"shop_svalue\":\"" + strSetPrice + "\"},"; } } } else { bool isSetMin = false; var minPrice = arr.Where(s => s["stock"].ParseToInt() > 0).Min(s => s["origin_price"]?.ParseToInt()); if (minPrice == null) { errorMsg = "商品库存为0"; pIdStr = pIdStr.Replace("\"" + id + "\"", ""); } foreach (JObject obj in arr) { int totalStock = obj["stock"].ParseToInt(); int origin_price = obj["origin_price"].ParseToInt(); if (totalStock > 0) { var stockNum = totalStock; if (stockType == "百分比库存") { stockNum = stockValue * totalStock / 100; } else if (stockType == "统一库存") { stockNum = stockValue; } if (stockNum > totalStock) { //stockNum = totalStock; errorMsg = "商品Sku库存不足"; pIdStr = pIdStr.Replace(id, ""); break; } if (stockNum < 1) stockNum = 1; if (shop_stype != "1" && !isSetMin && obj["origin_price"].ParseToInt() == minPrice) { if (shop_stype == "2" && strSetPriceMin.ParseToDecimal() / origin_price < 1 - maxDiscount) { errorMsg = "商品优惠力度不足" + (maxDiscount * 10).ToString() + "折"; pIdStr = pIdStr.Replace(id, ""); break; } if (shop_stype == "3" && origin_price * (1 - strSetPriceMin.ParseToDecimal() / 100) < 100) { errorMsg = "商品优惠力度不足" + minReducePrice + "元"; pIdStr = pIdStr.Replace(id, ""); break; } productJson = productJson + "{\"id\":\"" + obj["id"] + "\",\"camp_stock_num\":\"" + stockNum + "\",\"user_limit\":\"" + userLimit + "\",\"price\":\"undefined\",\"shop_svalue\":\"" + strSetPriceMin + "\"},"; isSetMin = true; } else { if (shop_stype == "1") productJson = productJson + "{\"id\":\"" + obj["id"] + "\",\"camp_stock_num\":\"" + stockNum + "\",\"user_limit\":\"" + userLimit + "\",\"price\":\"" + strSetPrice + "\"},"; else { if (shop_stype == "2" && strSetPrice.ParseToDecimal() / origin_price < 1 - maxDiscount) { errorMsg = "商品优惠力度不足" + (maxDiscount * 10).ToString() + "折"; pIdStr = pIdStr.Replace(id, ""); break; } if (shop_stype == "3" && origin_price * (1 - strSetPrice.ParseToDecimal() / 100) < 100) { errorMsg = "商品优惠力度不足" + minReducePrice + "元"; pIdStr = pIdStr.Replace(id, ""); break; } productJson = productJson + "{\"id\":\"" + obj["id"] + "\",\"camp_stock_num\":\"" + stockNum + "\",\"user_limit\":\"" + userLimit + "\",\"price\":\"undefined\",\"shop_svalue\":\"" + strSetPrice + "\"},"; } } } } } if (errorMsg == "") { // 结束sku列表 postData = postData + productJson.TrimEnd(',') + "]},"; } else { if (salesForm != null) salesForm.ShowVisitorMessage(activityName + "活动创建失败!原因:" + errorMsg, id, true); else if (manageForm != null) manageForm.ShowVisitorMessage(activityName + "活动创建失败!原因:" + errorMsg, active?.campaign_id); } } if (pIdStr.Trim(',') == "") { Invoke(new Action(() => { if (salesForm != null) salesForm.ShowVisitorMessage(activityName + "活动创建失败!原因:没有满足设置条件的商品", pIdStr); else if (manageForm != null) manageForm.ShowVisitorMessage(activityName + "活动创建失败!原因:没有满足设置条件的商品", active?.campaign_id); })); Thread.Sleep(Randomx.GetId(1500, 3500)); } else { DateTime begin_time = startTime; DateTime end_time = endTime; if (timeSetType != "0") { begin_time = DateTime.Now; end_time = begin_time.AddMinutes(actDuration); } var pre_begin_time = begin_time; if (isPreheat) { var day = preDayStr.Replace("天", "").ParseToInt(); var hour = pteHourStr.Replace("小时", "").ParseToDouble(); if (day > 0) pre_begin_time = pre_begin_time.AddDays(-day); if (hour > 0) pre_begin_time = pre_begin_time.AddHours(-hour); } postData = postData.TrimEnd(',') + "],\"order_expire_time\":\"" + cancelTime.Replace("分钟", "").ParseToInt() * 60 + "\",\"pre_begin_time\":\"" + pre_begin_time.ToString("yyyy-MM-dd HH:mm:ss") + "\",\"begin_time\":\"" + begin_time.ToString("yyyy-MM-dd HH:mm:ss") + "\",\"end_time\":\"" + end_time.ToString("yyyy-MM-dd HH:mm:ss") + "\",\"sold_out_type\":\"" + soldOutType + "\",\"create_action_type\":\"0\"}"; string checkPro = ""; for (int times = 0; !checkPro.Contains("{\"st\":0,\"msg\"") && !checkPro.Contains("Gateway Timeout") && times < 3; times++) { if (salesForm != null) checkPro = salesForm.checkFlashAndGoods(postData, cookies); else if (manageForm != null) checkPro = manageForm.checkFlashAndGoods(postData, cookies); } if (checkPro == "" || checkPro.Contains("Gateway Timeout") || checkPro.Contains("{\"st\":0,\"msg\":\"\",\"code\":0,")) { string createPro = ""; if (salesForm != null) { createPro = salesForm.createFlashAndGoods(postData, cookies); for (int times = 0; times < 2 && (!createPro.Contains("{\"st\":0,\"msg\"") || createPro.Contains("系统内部错误")); times++) { checkPro = salesForm.checkFlashAndGoods(postData, cookies); if (checkPro.Contains("已参加同时段")) { createPro = "{\"st\":0,\"msg\":\"\",\"code\":0,"; break; } else createPro = salesForm.createFlashAndGoods(postData, cookies); } // 如果商品sku过多导致失败则分开建相同名称的活动 if (createPro.Contains("Gateway Timeout") || createPro.Contains("系统内部错误")) { JObject parentObj = JObject.Parse(postData); var goodsArr = parentObj["promotion_goods"]; JArray goodsJArr = new JArray(); foreach (JObject prodObj in goodsArr) { goodsJArr.Add(prodObj); if (goodsJArr.Count() >= 10 || goodsArr.LastOrDefault() == prodObj) { parentObj["promotion_goods"] = goodsJArr; goodsJArr = new JArray(); createPro = ""; for (int num = 0; num < 3 && !createPro.Contains("{\"st\":0,\"msg\":\"\",\"code\":0,"); num++) { checkPro = salesForm.checkFlashAndGoods(JsonHelper.SerializeObject(parentObj), cookies); if (checkPro.Contains("已参加同时段")) { createPro = "{\"st\":0,\"msg\":\"\",\"code\":0,"; break; } createPro = salesForm.createFlashAndGoods(JsonHelper.SerializeObject(parentObj), cookies); } if (!createPro.Contains("{\"st\":0,\"msg\":\"\",\"code\":0,")) break; } } } } else if (manageForm != null) { createPro = manageForm.createFlashAndGoods(postData, cookies); if (!createPro.Contains("{\"st\":0,\"msg\"")) createPro = manageForm.createFlashAndGoods(postData, cookies); if (!createPro.Contains("{\"st\":0,\"msg\"")) createPro = manageForm.createFlashAndGoods(postData, cookies); } if (createPro.Contains("{\"st\":0,\"msg\":\"\",\"code\":0,")) { Invoke(new Action(() => { if (salesForm != null) salesForm.ShowVisitorMessage("活动 " + activityName + " 创建成功!", pIdStr); else if (manageForm != null) manageForm.ShowVisitorMessage("活动 " + activityName + " 修改成功!", active?.campaign_id); })); } else { if (createPro.Contains("Gateway Timeout")) createPro = "{\"msg\":\"接口调用超时\"}"; Invoke(new Action(() => { if (salesForm != null) salesForm.ShowVisitorMessage(activityName + "活动创建失败!原因:" + BaseRegex.GetStringJson(ref createPro, "msg"), pIdStr); else if (manageForm != null) manageForm.ShowVisitorMessage(activityName + "活动创建失败!原因:" + BaseRegex.GetStringJson(ref createPro, "msg"), active?.campaign_id); })); } } else { Invoke(new Action(() => { if (salesForm != null) salesForm.ShowVisitorMessage(activityName + "活动创建失败!原因:" + BaseRegex.GetStringJson(ref checkPro, "msg"), pIdStr); else if (manageForm != null) manageForm.ShowVisitorMessage(activityName + "活动创建失败!原因:" + BaseRegex.GetStringJson(ref checkPro, "msg"), active?.campaign_id); })); } Thread.Sleep(Randomx.GetId(1500, 3500)); } } //var tab1 = this.ucTabControl1.TabPages.Cast().FirstOrDefault(t => t.Text == shop.ShopName + "活动管理" && t.Name == "tab" + shop.ShopId + "Active"); //if (tab1 != null) //{ // LimitedSalesManagerActiveForm actForm = tab1.Controls[0] as LimitedSalesManagerActiveForm; // actForm.activeList.Clear(); //} } } private bool InitParams(bool isModify = false) { customActivityNamesTemp = new List(); //活动名称 if (chkSetName.Checked && !isModify) { customActivityNamesTemp.AddRange(CustomActivityNames); if (customActivityNamesTemp.Count == 0) { BaseMsgForm.ShowInfo("请设置自定义活动名称!"); return false; } } // 每个活动商品数量 eachActivityProductNum = cmbSetPro.Text.ParseToInt(); if (isModify) eachActivityProductNum = 20; // 每人限购 userLimit = cmbLimit.Text; // 活动时间类型 timeSetType = rbTimePeriod.Checked ? "1" : "0"; // 按开始结束时间 或 按时间段 // 活动库存售完后如何操作 soldOutType = rbSoldOut.Checked ? "1" : "0"; // 开始时间 startTime = dtpStartTime.Value; // 结束时间 endTime = dtpEndTime.Value; // (按时间段类型活动的)活动持续时间 actDuration = cmbActCont.Text.Replace("小时", "").Replace("分钟", "").ParseToInt() * (cmbActCont.Text.Contains("小时") ? 60 : 1); // 预热提前天 preDayStr = cmbDays.Text.Trim(); // 预热提前小时 pteHourStr = cmbHours.Text.Trim(); // 取消订单时间 cancelTime = cmbCancelTime.Text.Trim(); // 是否预热 isPreheat = rbPreheat.Checked; // 只设置一个sku isSetSkuOption = chkSetSkuOption.Checked; // 设置一个sku的类型(第一个,最后一个,价格最高,最低) skuOptionType = this.cmbSkuOptionType.Text; // 批量设置自定义名称 isUseCustomActivityNames = chkSetName.Checked; // 库存类型 stockType = this.cmbStockType.Text; // 库存数量 stockValue = nudStockValue.Text.ParseToInt(); // 最低折扣 maxDiscount = 0.95M; // 最少降价金额 minReducePrice = 1M; // 普通sku折扣/降价 strPrice = string.Empty; // 最低sku折扣/降价 strPriceMin = string.Empty; if (rbBuyoutPrice.Checked || isSetSkuOption) { strPrice = txtSKUPriceCommon.Text.Trim(); if (strPrice == string.Empty || !BaseRegex.IsNumber(strPrice)) { BaseMsgForm.ShowError("请认真填写一口价的优惠数值!"); txtSKUPriceCommon.Focus(); return false; } //判断打折的数字是否正确 if (rbDiscount.Checked) { if (strPrice.Length > 3 || strPrice.EndsWith(".") || strPrice.ParseToDecimal() > 9.5M || strPrice.ParseToDecimal() < 0.1M) { BaseMsgForm.ShowError("参加活动的商品打折数必须在0.1-9.5之间,且小数点后只能有一位!"); return false; } } else if (rbReducePrice.Checked) { if (strPrice.ParseToDecimal() < 1M) { BaseMsgForm.ShowError("参加活动的商品优惠金额最少1元!"); return false; } } } else { strPriceMin = txtSKUPriceMin.Text.Trim(); strPrice = txtSKUPriceCommon.Text.Trim(); if (strPrice == string.Empty || !BaseRegex.IsNumber(strPrice) || strPriceMin == string.Empty || !BaseRegex.IsNumber(strPriceMin)) { BaseMsgForm.ShowInfo("请认真填写活动的优惠数值!"); return false; } //判断打折的数字是否正确 if (rbDiscount.Checked) { if (strPrice.Length > 3 || strPrice.EndsWith(".") || strPriceMin.Length > 3 || strPriceMin.EndsWith(".") || strPrice.ParseToDecimal() > 9.5M || strPrice.ParseToDecimal() < 0.1M || strPriceMin.ParseToDecimal() > 9.5M || strPriceMin.ParseToDecimal() < 0.1M) { BaseMsgForm.ShowInfo("参加活动的商品打折数必须在0-10之间,且小数点后只能有一位!"); return false; } } else if (rbReducePrice.Checked) { if (strPrice.ParseToDecimal() < 1M) { BaseMsgForm.ShowError("参加活动的商品优惠金额最少1元!"); return false; } } } if (isSetSkuOption || shop_stype == "1") { if (shop_stype == "3") strSetPrice = (strPrice.ParseToDouble() * 10).ToString(); //打折精确到小数点后一位(0-10之间) else strSetPrice = (strPrice.ParseToDouble() * 100).ToString(); //一口价、直降精确到小数点后两位(0-原价之间) } else { if (shop_stype == "3") { strSetPrice = (strPrice.ParseToDouble() * 10).ToString(); //打折精确到小数点后一位(0-10之间) strSetPriceMin = (strPriceMin.ParseToDouble() * 10).ToString(); } else if (shop_stype == "2") { strSetPrice = (strPrice.ParseToDouble() * 100).ToString(); //直降精确到小数点后两位(0-原价之间) strSetPriceMin = (strPriceMin.ParseToDouble() * 100).ToString(); } } return true; } 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(); } else { var salesForm = tp.Controls[0] as SeckillingAndLimitedSalesShopForm; if (salesForm != null) salesForm.ClearData(); } } } } } private void btnStopGetProduct_Click(object sender, EventArgs e) { if (cancellationTokenSource != null) cancellationTokenSource.Cancel(); if (addActiveCancellationTokenSource != null) addActiveCancellationTokenSource.Cancel(); webBrowser.Tag = null; Task.Run(() => { Thread.Sleep(10000); if (cancellationTokenSource == null || cancellationTokenSource.IsCancellationRequested) { Invoke(new Action(() => { btnGetProduct.Enabled = btnSubAct.Enabled = btnMdyAct.Enabled = btnManageAct.Enabled = true; })); } }); } private void rbDiscount_Click(object sender, EventArgs e) { if (shop_stype == "3" && rbDiscount.Checked) return; if (chkSetSkuOption.Checked) { pnlSkuPriceMin.Visible = false; } else { pnlSkuPriceMin.Visible = true; } this.lblSKUPriceMin2.Text = "打"; this.lblSKUPriceMin3.Text = "折"; this.lblSKUPriceCommon2.Text = "打"; this.lblSKUPriceCommon3.Text = "折"; this.txtSKUPriceMin.Text = "9"; this.txtSKUPriceCommon.Text = "9.5"; shop_stype = "3"; this.rbDiscount.Checked = true; } private void rbReducePrice_Click(object sender, EventArgs e) { if (shop_stype == "2" && rbReducePrice.Checked) return; if (chkSetSkuOption.Checked) { pnlSkuPriceMin.Visible = false; } else { pnlSkuPriceMin.Visible = true; } this.lblSKUPriceMin2.Text = "减"; this.lblSKUPriceMin3.Text = "元"; this.lblSKUPriceCommon2.Text = "减"; this.lblSKUPriceCommon3.Text = "元"; this.txtSKUPriceMin.Text = "1"; this.txtSKUPriceCommon.Text = "1"; shop_stype = "2"; this.rbReducePrice.Checked = true; } private void rbBuyoutPrice_Click(object sender, EventArgs e) { if (shop_stype == "1" && rbBuyoutPrice.Checked) return; if (BaseMsgForm.ShowConfirm("确定所有商品的价格都按照统一的价格来设置?建议谨慎操作!").DialogResult == DialogResult.OK) { this.txtSKUPriceCommon.Text = "100"; this.lblSKUPriceCommon2.Text = ""; this.lblSKUPriceCommon3.Text = "元"; shop_stype = "1"; pnlSkuPriceMin.Visible = false; this.rbBuyoutPrice.Checked = true; } else { if (shop_stype == "2") rbReducePrice_Click(sender, e); else rbDiscount_Click(sender, e); } } private void btnManageAct_Click(object sender, EventArgs e) { if (lstShopId.Count == 0) { BaseMsgForm.ShowInfo("请选择店铺!"); 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().FirstOrDefault(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId); if (row != null) { row.Cells["colLoginStatus"].Value = "未登录"; row.Cells["colCanUse"].Value = false; } })); continue; } LimitedSalesManagerActiveForm managerActiveForm = null; Invoke(new Action(() => { var tab = this.ucTabControl1.TabPages.Cast().FirstOrDefault(t => t.Text == shop.ShopAccount + "活动管理" && t.Name == "tab" + shop.ShopId + "Active"); if (tab == null) { tab = new TabPage(); tab.Name = "tab" + shop.ShopId + "Active"; tab.Text = shop.ShopAccount + "活动管理"; this.ucTabControl1.TabPages.Add(tab); var limitedSalesManagerActiveForm = new LimitedSalesManagerActiveForm(shop); limitedSalesManagerActiveForm.seckillingAndLimitedSalesForm = this; limitedSalesManagerActiveForm.TopLevel = false; limitedSalesManagerActiveForm.Left = 0; limitedSalesManagerActiveForm.Top = 0; limitedSalesManagerActiveForm.FormBorderStyle = FormBorderStyle.None; limitedSalesManagerActiveForm.AutoSize = true; limitedSalesManagerActiveForm.Dock = DockStyle.Fill; limitedSalesManagerActiveForm.Show(); tab.Controls.Add(limitedSalesManagerActiveForm); } if (tab.Controls.Count > 0) { managerActiveForm = tab.Controls[0] as LimitedSalesManagerActiveForm; this.ucTabControl1.SelectedTab = tab; } })); if (managerActiveForm != null) { managerActiveForm.GetActive(); } } Invoke(new Action(() => { btnGetProduct.Enabled = true; })); }, cancellationTokenSource.Token); } public void GetActiveByCef(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(); splitContainer4.Panel1.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/market/center/tools/limitsales"; 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 chkSetName_CheckedChanged(object sender, EventArgs e) { } private void chkSetOneSku_CheckedChanged(object sender, EventArgs e) { if (rbBuyoutPrice.Checked) return; if (chkSetSkuOption.Checked) { pnlSkuPriceMin.Visible = false; } else { pnlSkuPriceMin.Visible = true; } } private void btnSetName_Click(object sender, EventArgs e) { LimitedSalesActivityNameForm customNameForm = new LimitedSalesActivityNameForm(); customNameForm.ShowDialog(); } 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 btnCancelGet_Click(object sender, EventArgs e) { if (cancellationTokenSource != null) cancellationTokenSource.Cancel(); if (addActiveCancellationTokenSource != null) addActiveCancellationTokenSource.Cancel(); webBrowser.Tag = null; Task.Run(() => { Thread.Sleep(10000); if (cancellationTokenSource == null || cancellationTokenSource.IsCancellationRequested) { Invoke(new Action(() => { btnGetProduct.Enabled = btnSubAct.Enabled = btnMdyAct.Enabled = btnManageAct.Enabled = true; })); } }); } private void btnMdyAct_Click(object sender, EventArgs e) { //https://fxg.jinritemai.com/byteshop/promotion/detailFlashAndGoods?campaign_id=7129422311865811232&filter_unable_product=0&_bid=ecom_market_shop&appid=1&_=1660017441378&_signature=_02B4Z6wo00d01iVfrVQAAIDDRlVtPWgRUO4lW6nAAOu0sAsG56mTgW-GugrVNIvOFK.nRZ2WI7FAQvOEAM7Akj1ERBjJAOPHQWw72Qx1eAqWHCS9zJ6RFjCyrannBvRvfpJr6aNhuwjX.UjXab if (lstShopId.Count <= 0) { BaseMsgForm.ShowInfo("请选择要修改活动的店铺!"); return; } var initResult = InitParams(true); if (!initResult) return; addActiveCancellationTokenSource = new CancellationTokenSource(); btnGetProduct.Enabled = false; btnSubAct.Enabled = false; btnMdyAct.Enabled = false; Task.Run(() => { var lstShopIdTemp = new List(); lstShopIdTemp.AddRange(lstShopId); foreach (var shopId in lstShopIdTemp) { var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId); if (shop == null) continue; if (ucTabControl1.TabPages["tab" + shopId + "Active"] != null && ucTabControl1.TabPages["tab" + shopId + "Active"].Controls.Count > 0) { var manageForm = ucTabControl1.TabPages["tab" + shopId + "Active"].Controls[0] as LimitedSalesManagerActiveForm; if (manageForm == null) continue; Invoke(new Action(() => { manageForm.statusBar.lblTaskStatus.Text = "正在修改活动"; })); List activityList = manageForm.activeList.Where(a => manageForm.lstActiveId.Contains(a.campaign_id)).ToList(); if (activityList.Count == 0) { BaseMsgForm.ShowInfo("请选择店铺 " + shop.ShopAccount + " 要修改的活动!"); continue; } else { foreach (ActiveInfo activity in activityList) { List productList = new List(); var activity_product_result = manageForm.GetProductByActivityId(activity.campaign_id, shop.Cookies); if (activity_product_result.Contains("\"st\":0,\"msg\":\"\"")) { JObject obj = JObject.Parse(activity_product_result); JArray arr = obj["data"]?["promotion_goods"] as JArray; if (arr != null) { foreach (JObject token in arr) { var tokenStr = token.ToString(); DouProductPromotionListInfo douProduct = new DouProductPromotionListInfo(); douProduct.product_id = BaseRegex.GetStringJson(ref tokenStr, "product_id"); douProduct.name = BaseRegex.GetStringJson(ref tokenStr, "title"); douProduct.img = BaseRegex.GetStringJson(ref tokenStr, "cover"); productList.Add(douProduct); } } } manageForm.DelActive(activity.campaign_id.ParseToLong(), false); AddOrMdyActivity(shop, productList, activity, null, manageForm); } } Invoke(new Action(() => { if (addActiveCancellationTokenSource.IsCancellationRequested) manageForm.statusBar.lblTaskStatus.Text = "活动修改中断"; else manageForm.statusBar.lblTaskStatus.Text = "活动修改结束"; })); } } Invoke(new Action(() => { btnManageAct.Enabled = btnGetProduct.Enabled = btnSubAct.Enabled = btnMdyAct.Enabled = true; })); }, addActiveCancellationTokenSource.Token); } } }