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

631 lines
26 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 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 CouponForm : Form
{
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 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.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 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.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 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())
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 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.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
continue;
CouponShopForm couponShopForm = 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 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<string, string> Headers = new Dictionary<string, string>();
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<TabPage>().FirstOrDefault(t => t.Text == shop.ShopAccount && t.Name == "tab" + shop.ShopId);
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<string, string>(), 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<Task> tList = new List<Task>();
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;
}
}
}
}