using AllBase; using AllBase.Helper; using AllBase.Model.Result; using CefSharp; using CefSharp.WinForms; using LittleRabbit.Extension; using LittleRabbit.Helper; using LittleRabbit.LittleRabbitForms.BaseForms; 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 LittleRabbit.LittleRabbitForms.SalesCenterForms { public partial class CouponForm : Form { private CheckBox chkSelectAll = null; public ChromiumWebBrowser webBrowser = null; private List lstShopId = new List(); public List keywords = null; public List filterWords = null; public CancellationTokenSource cancellationTokenSource = null; public CouponForm() { InitializeComponent(); } private void CouponForm_Load(object sender, EventArgs e) { 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; this.cmbType.SelectedIndex = 0; this.cmbUserCountLimited.SelectedIndex = 0; this.dtpStartApplyTime.Value = DateTime.Now.Date; this.dtpEndApplyTime.Value = this.dtpStartApplyTime.Value.AddDays(1).AddSeconds(-1); } 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.DouShopLoginList.Where(s => s.ApiAuthStatus == "授权成功" && s.LoginStatus == "登录成功").Select(ss => ss.ShopAccountId); 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 CouponForm_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.DouShopLoginList.Any(s => s.ShopAccountId == id && s.LoginStatus == "已授权")).ToList(); // 获取被删除的店铺 List dgvRowList = dgvShop.Rows.Cast().Where(row => !GlobalConfig.DouShopLoginList.Any(s => s.ShopAccountId == row.Cells["colShopId"]?.Value?.ToString())).ToList(); // 更新被删除的店铺列表 foreach (var row in dgvRowList) { dgvShop.Rows.Remove(row); } // 绑定其他店铺(含新导入的店铺) foreach (DouShopLoginInfo shopEntity in GlobalConfig.DouShopLoginList) { 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.ShopAccountId); if (row == null) { this.dgvShop.Rows.Add( lstShopId.Contains(shopEntity.ShopAccountId) && canUse, shopEntity.ShopAccountId, shopEntity.ShopAccount, shopEntity.ApiAuthStatus, shopEntity.LoginStatus, canUse, string.Empty ); } else { row.Cells["colSelect"].Value = lstShopId.Contains(shopEntity.ShopAccountId) && 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.DouShopLoginList.FirstOrDefault(s => s.ShopAccountId == 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()) lstShopId.Add(shopId.ToString()); else lstShopId.Remove(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; } 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(); } catch (Exception ex) { } cancellationTokenSource = new CancellationTokenSource(); Task.Run(() => { foreach (var shopId in lstShopId) { if (cancellationTokenSource.IsCancellationRequested) break; var shop = GlobalConfig.DouShopLoginList.FirstOrDefault(s => s.ShopAccountId == shopId); if (shop == null) continue; CouponShopForm couponShopForm = null; Invoke(new Action(() => { var tab = this.ucTabControl1.TabPages.Cast().FirstOrDefault(t => t.Text == shop.ShopAccount && t.Name == "tab" + shop.ShopAccountId); if (tab == null) { tab = new TabPage(); tab.Name = "tab" + shop.ShopAccountId; tab.Text = shop.ShopAccount; this.ucTabControl1.TabPages.Add(tab); var form = new CouponShopForm(shop); form.couponForm = 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) couponShopForm = tab.Controls[0] as CouponShopForm; })); if (couponShopForm != null) { couponShopForm.GetProduct( txtPriceMin.Text.ParseToDecimal(), txtPriceMax.Text.ParseToDecimal(), txtSaleMin.Text.ParseToInt(), txtSaleMax.Text.ParseToInt(), this.keywords, this.filterWords); } } }, 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; 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); } 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=")) { 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]; } if (webBrowser.Tag != null) { var shop = webBrowser.Tag as DouShopLoginInfo; var tab = this.ucTabControl1.TabPages.Cast().FirstOrDefault(t => t.Text == shop.ShopAccount && t.Name == "tab" + shop.ShopAccountId); var clearForm = tab.Controls[0] as CouponShopForm; Task.Run(() => { int total = -1; int number = 0; for (int i = 0; i < 10000; i++) { number += 20; result = ""; for (int j = 0; j < 3 && !result.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; var rUrl = listUrl.Replace("page=0", "page=" + i) .Replace("&pay_type=", "&pay_type=&sell_num_min=1"); result = simRequest.Request_Get(rUrl, referrerUrl, new Dictionary(), cookie); if (j > 0) { Thread.Sleep(Randomx.GetId(2000, 3000)); } } if (result.Contains("\"st\":0") && !cancellationTokenSource.IsCancellationRequested) { clearForm.isGetProductSalesSuccess = true; if (total == -1) { total = BaseRegex.GetIntJson(ref result, "total"); } var jObj = JObject.Parse(result); var jArr = jObj["data"] as JArray; foreach (var productObj in jArr) { var prod = JsonHelper.SerializeObject(productObj); var pId = BaseRegex.GetStringJson(ref prod, "product_id"); var sales = BaseRegex.GetIntJson(ref prod, "sell_num"); if (sales == 0) { number = 99999999; break; } else { clearForm.dicProductSales[pId] = sales; } } Thread.Sleep(Randomx.GetId(2000, 3000)); } else { clearForm.isGetProductSalesSuccess = false; webBrowser.Tag = null; break; } if (number >= total) break; } webBrowser.Tag = null; Thread.Sleep(1000); }); } else { webBrowser.Tag = null; } } } private void lblProductName_Click(object sender, EventArgs e) { if (this.webBrowser != null) { webBrowser.SendToBack(); } } private void lblProductName_DoubleClick(object sender, EventArgs e) { if (this.webBrowser != null) { webBrowser.BringToFront(); } } private void btnSet_Click(object sender, EventArgs e) { cancellationTokenSource = new CancellationTokenSource(); int periodType = this.rbUseTypePeriod.Checked ? 1 : 2; int favouredType = 41; if (this.cmbType.Text == "商品直减券") favouredType = 42; else if (this.cmbType.Text == "商品满减券") favouredType = 43; int days = this.nudDays.Text.ParseToInt(); int startApplyTime = BaseClass.DateTimeToTimestampSeconds(this.dtpStartApplyTime.Value); int endApplyTime = BaseClass.DateTimeToTimestampSeconds(this.dtpEndApplyTime.Value); int startUseTime = BaseClass.DateTimeToTimestampSeconds(this.dtpStartUseTime.Value.Date); int endUseTime = BaseClass.DateTimeToTimestampSeconds(this.dtpEndUseTime.Value.Date.AddDays(1).AddSeconds(-1)); int totalCount = nudTotalCount.Value.ParseToInt(); int countLimit = 1; decimal discount = this.nudCredit.Value.ParseToDecimal(); // 折扣 int thresHold = this.nudThresHold.Value.ParseToInt(); // 满x元 单位元 int credit = this.nudCredit.Value.ParseToInt(); // 减x元 单位元 bool igonre = rbNotReckonIn.Checked; bool oneProductEachCoupon = this.rbOneProductEachCoupon.Checked; Task.Run(() => { int i = 0; List tList = new List(); foreach (TabPage tp in ucTabControl1.TabPages) { i++; Invoke(new Action(() => { this.statusBar.lblTaskStatus.Text = "正在设置优惠券"; this.statusBar.pgbTaskProgress.Value = i; this.statusBar.pgbTaskProgress.Text = i + "/" + ucTabControl1.TabPages.Count; this.statusBar.pgbTaskProgress.Maximum = ucTabControl1.TabPages.Count; })); if (tp.Controls.Count > 0) { var cForm = tp.Controls[0] as CouponShopForm; if (cForm != null) { var t = Task.Run(() => { cForm.SetCoupon(periodType, favouredType, startApplyTime, endApplyTime, startUseTime, endUseTime, days, totalCount, countLimit, discount, thresHold, credit, igonre, oneProductEachCoupon); }); tList.Add(t); if (tList.Count >= 10) Task.WaitAny(tList.ToArray()); var ts = tList.Where(t1 => t1.IsCompleted || t1.IsCanceled || t1.IsFaulted); foreach (var t1 in ts) { tList.Remove(t1); } } } } Task.WaitAll(tList.ToArray()); tList.Clear(); Invoke(new Action(() => { if (cancellationTokenSource.IsCancellationRequested) { this.statusBar.lblTaskStatus.Text = "设置中断"; } else { this.statusBar.lblTaskStatus.Text = "设置完成"; } this.statusBar.pgbTaskProgress.Value = 0; this.statusBar.pgbTaskProgress.Text = 0 + "/" + 0; this.statusBar.pgbTaskProgress.Maximum = 0; })); }, cancellationTokenSource.Token); } private void btnStopOperate_Click(object sender, EventArgs e) { if (cancellationTokenSource != null) cancellationTokenSource.Cancel(); } private void btnStopGetProduct_Click(object sender, EventArgs e) { if (cancellationTokenSource != null) cancellationTokenSource.Cancel(); } private void rbUseTypePeriod_CheckedChanged(object sender, EventArgs e) { if (rbUseTypePeriod.Checked) { pnlTimePeriod.Visible = true; lblUseTypeText.Text = "日期范围"; } else { pnlTimePeriod.Visible = false; lblUseTypeText.Text = "领券当日起"; } } 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 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 CouponShopForm; if (salesForm != null) salesForm.ClearData(); } } } } } private void cmbType_SelectedIndexChanged(object sender, EventArgs e) { if (cmbType.Text == "商品折扣券") { this.lblDiscountText.Text = "  折扣"; nudCredit.Minimum = 0.1M; nudCredit.Increment = 0.1M; nudCredit.Maximum = 9.9M; nudCredit.DecimalPlaces = 1; nudCredit.Value = 9.9M; lblCreditText.Text = "折"; nudThresHold.Visible = false; lblThresHold.Visible = false; } else if (cmbType.Text == "商品直减券") { this.lblDiscountText.Text = "直减面额"; nudCredit.Minimum = 1; nudCredit.Increment = 1; nudCredit.Maximum = 1000; nudCredit.DecimalPlaces = 0; nudCredit.Value = 1; lblCreditText.Text = "元"; nudThresHold.Visible = false; lblThresHold.Visible = false; } else { this.lblDiscountText.Text = "满减 满"; nudCredit.Minimum = 1; nudCredit.Increment = 1; nudCredit.Maximum = 99999; nudCredit.DecimalPlaces = 0; nudCredit.Value = 1; lblCreditText.Text = "元"; nudThresHold.Visible = true; lblThresHold.Visible = true; } } } }