Files
KJD/TEMUKJD/WXForms/ProductForms/WXProdCouponOrderBoomForm.cs
T
2026-03-19 20:44:33 +08:00

1843 lines
85 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 NaiBa.Util.Extension;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TemuKJD.Extension;
using TemuKJD.BaseForms;
using TemuKJD.ToolForms;
using Work;
using TemuKJD.BLL;
using System.Text.RegularExpressions;
using TemuKJD.PDDForms.ProductSelectForms;
using TemuKJD.WXForms.ShopForms;
using AllBase.Model.Result.PDDResult;
using AllBase.Model.Param.WXParam;
using AllBase.Model.Result.WXResult;
using Newtonsoft.Json;
using NaiBa.Util;
using AllBase.Model.Config;
namespace TemuKJD.WXForms.ProductForms
{
public partial class WXProdCouponOrderBoomForm : BaseForm
{
int PageBegin = 1;
int PageEnd = 999;
string PreType = "";
public CancellationTokenSource cancellationTokenSource { get; set; } = null;
public bool IsLoadComplate { get; set; } = false;
bool isInit = false;
CheckBox chkSelectAll = null;
ConcurrentList<AuthInfo> lstShopAuthInfo = new ConcurrentList<AuthInfo>();
ConcurrentList<WXShopTokenInfo> lstWXShopTokenInfo = new ConcurrentList<WXShopTokenInfo>();
public NaiBa.Util.ConcurrentList<TemuDBProductSelect> lstTemuDBProductSelect = new NaiBa.Util.ConcurrentList<TemuDBProductSelect>();
NaiBa.Util.ConcurrentList<AddPriceRule> lstAddPriceRule = new NaiBa.Util.ConcurrentList<AddPriceRule>();
//public Dictionary<string, List<string>> dicCheckedShopIdList = new Dictionary<string, List<string>>();
public Dictionary<string, bool> dicCheckedShopId = new Dictionary<string, bool>();
public Dictionary<string, WxShopUploadInfo> dicShopUpload = new Dictionary<string, WxShopUploadInfo>();
public string pdd_product_cates = "";
public WXProdCouponOrderBoomForm()
{
InitializeComponent();
}
private void UserSelectDbProductForm_Load(object sender, EventArgs e)
{
this.splitContainer1.Dock = DockStyle.Fill;
btnClearCoupon_Click(null, null);
lstShopAuthInfo = NaiBa.Util.Helper.ConfigHelper.LoadConfig<NaiBa.Util.ConcurrentList<AuthInfo>>("wx_shop_auth_list");
if (lstShopAuthInfo == null)
lstShopAuthInfo = new ConcurrentList<AuthInfo>();
lstWXShopTokenInfo = NaiBa.Util.Helper.ConfigHelper.LoadConfig<NaiBa.Util.ConcurrentList<WXShopTokenInfo>>("wx_shop_token_list");
if (lstWXShopTokenInfo == null)
lstWXShopTokenInfo = new ConcurrentList<WXShopTokenInfo>();
lstTemuDBProductSelect = NaiBa.Util.Helper.ConfigHelper.LoadConfig<NaiBa.Util.ConcurrentList<TemuDBProductSelect>>("wx_db_prod_upload_list");
if (lstTemuDBProductSelect == null)
lstTemuDBProductSelect = new NaiBa.Util.ConcurrentList<TemuDBProductSelect>();
lstAddPriceRule = NaiBa.Util.Helper.ConfigHelper.LoadConfig<NaiBa.Util.ConcurrentList<AddPriceRule>>("wx_add_price_rules");
if (lstAddPriceRule == null)
{
lstAddPriceRule = new NaiBa.Util.ConcurrentList<AddPriceRule>();
lstAddPriceRule.Add(new AddPriceRule() { MoreThanPrice = 0, LessThanPrice = 10, AddPriceTimes = 2, AddMorePrice = 10, SinglePriceAdd = 1 });
lstAddPriceRule.Add(new AddPriceRule() { MoreThanPrice = 10, LessThanPrice = 20, AddPriceTimes = 2, AddMorePrice = 10, SinglePriceAdd = 1 });
lstAddPriceRule.Add(new AddPriceRule() { MoreThanPrice = 20, LessThanPrice = 999, AddPriceTimes = 2, AddMorePrice = 10, SinglePriceAdd = 1 });
}
dicCheckedShopId = NaiBa.Util.Helper.ConfigHelper.LoadConfig<Dictionary<string, bool>>("wx_checked_shop_dic");
if (dicCheckedShopId == null)
dicCheckedShopId = new Dictionary<string, bool>();
dicShopUpload = NaiBa.Util.Helper.ConfigHelper.LoadConfig<Dictionary<string, WxShopUploadInfo>>("wx_shop_upload_info");
if (dicShopUpload == null)
dicShopUpload = new Dictionary<string, WxShopUploadInfo>();
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;
//chkSelectAll.Checked = true;
this.dgvSelectProduct.AddSelectorColumn("colCheck");
dgvSelectProduct.AddImgColumn("colProductSkcPic", "colImgUrl");
dgvSelectProduct.AddImgColumn("colSkuFakeImg", "colSkuFakeImgUrl");
dgvSelectProduct.Columns["colSkuFakeImg"].Visible = false;
//#if DEBUG
if (BaseClass.SaLevel == 1)
{
//txtIdFilter.Visible = true;
//txtExtCodeFilter.Visible = true;
//lblIdFilter.Visible = true;
//lblExtCodeFilter.Visible = true;
}
//#endif
IsLoadComplate = true;
}
private void btnRefreshAuthor_Click(object sender, EventArgs e)
{
updateAuthor(true);
}
/// <summary>
/// 升级授权
/// </summary>
/// <param name="idRefreshTodayHasGet">今日取过的也取</param>
private void updateAuthor(bool idRefreshTodayHasGet = false)
{
this.pbLoadingShop.Visible = true;
Task.Run(() =>
{
// 店铺Id
var updateIds = dgvShop.Rows.Cast<DataGridViewRow>().Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList();
var selectIds = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList();
if (idRefreshTodayHasGet == true)
updateIds = selectIds;
List<Task> tList = new List<Task>();
if (idRefreshTodayHasGet)
lstShopAuthInfo.RemoveAll(s => updateIds.Contains(s.ShopId));
foreach (var shop in GlobalConfig.ShopLoginList.Where(s => updateIds.Contains(s.ShopId)))
{
Invoke(new Action(() => { BindShop(shop, selectIds, ""); }));
var t = Task.Run(() =>
{
try
{
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); }));
return;
}
var authInfo = lstShopAuthInfo.FirstOrDefault(sa => sa.ShopId == shop.ShopId);
if (idRefreshTodayHasGet || authInfo == null || authInfo?.AddTime.Date != DateTime.Now.Date)
{
lstShopAuthInfo.RemoveAll(sa => sa.ShopId == shop.ShopId);
var rst = WXUpload.GetApiServiceList(shop);
if (!rst.Contains("\"code\":0"))
{
WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); }));
return;
}
lstShopAuthInfo.Add(new AuthInfo() { ShopId = shop.ShopId, AddTime = DateTime.Now, ExpiresTime = DateTime.Now });
Invoke(new Action(() => { BindShop(shop, selectIds, "授权查询失败"); }));
return;
}
foreach (var itemObj in JsonHelper.JObjectParse(rst)["itemList"])
{
// 找到了指定服务
if (itemObj["serviceName"].ParseToString() == "店统领供应链-商品管理")
{
var expiresTick = itemObj["expireTime"].ParseToLong();
lstShopAuthInfo.Add(new AuthInfo() { ShopId = shop.ShopId, AddTime = DateTime.Now, ExpiresTime = BaseClass.StampToDateTime(expiresTick.ParseToInt()) });
Invoke(new Action(() => { BindShop(shop, selectIds, "已查询"); }));
return;
}
}
// 没找到指定服务
lstShopAuthInfo.Add(new AuthInfo() { ShopId = shop.ShopId, AddTime = DateTime.Now, ExpiresTime = DateTime.Now });
Invoke(new Action(() => { BindShop(shop, selectIds, "已查询"); }));
}
}
catch (Exception ex)
{
}
});
tList.Add(t);
while (tList.Where(ta => !ta.IsFaulted && !ta.IsCompleted).Count() >= 20) { Thread.Sleep(100); }
}
while (tList.Where(ta => !ta.IsFaulted && !ta.IsCompleted).Count() >= 1) { Thread.Sleep(100); }
NaiBa.Util.Helper.ConfigHelper.SaveConfig( "wx_shop_auth_list", lstShopAuthInfo);
Invoke(new Action(() => { pbLoadingShop.Visible = false; }));
});
}
private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
if (!chkSelectAll.Checked)
{
foreach (DataGridViewRow row in dgvShop.Rows)
{
row.Cells["colSelect"].Value = false;
}
}
else
{
//var list = GlobalConfig.ShopLoginList.Where(s => s.LoginStatus == "登录成功").Select(ss => ss.ShopId);
foreach (DataGridViewRow row in dgvShop.Rows)
{
//if (list.Any(l => l == row.Cells["colShopId"]?.Value?.ToString()))
if(row.Visible == true)
row.Cells["colSelect"].Value = true;
}
}
foreach (var r in dgvShop.Rows.Cast<DataGridViewRow>())
{
dicCheckedShopId[r.Cells["colShopId"].Value.ParseToString()] = r.Cells["colSelect"].Value.ParseToBool();
}
NaiBa.Util.Helper.ConfigHelper.SaveConfig("wx_checked_shop_dic", dicCheckedShopId);
}
private void btnRefreshShop_Click(object sender, EventArgs e)
{
pbLoadingShop.Visible = true;
RefreshShopLogin();
}
private void UserSelectDbProductForm_VisibleChanged(object sender, EventArgs e)
{
if (Visible == true)
{
RefreshShopLogin();
updateAuthor();
if (!isInit)
{
Task.Run(() =>
{
foreach (var shop in GlobalConfig.ShopLoginList)
{
//if (shop.LoginStatus == "登录成功")
//{
// var rst = WXPreSale.scanProductPreview(shop);
// if (!rst.Contains("\"code\":0") && !rst.Contains("\"success\":true"))
// {
// WXShopListForm.Instance.CheckShopLogin(new string[] { shop.LoginName }, false);
// }
//}
}
});
}
isInit = true;
}
}
private void RefreshShopLogin()
{
// 店铺Id
var selectIds = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).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 (ShopLoginInfo shopEntity in GlobalConfig.ShopLoginList)
{
if (!string.IsNullOrEmpty(shopEntity.ShopId))
BindShop(shopEntity, selectIds);
}
cmbFilterShopNotes.Items.Clear();
//cmbFilterShopNotes.Items.Add("");
foreach (var note in GlobalConfig.ShopLoginList.Select(s => s.Notes).Where(s => !s.IsNullOrEmpty()).Distinct())
{
cmbFilterShopNotes.Items.Add(note);
}
}
private void BindShop(ShopLoginInfo shopEntity, List<string> selectShopId = null, string msg = "")
{
if (shopEntity == null)
return;
if (selectShopId == null)
selectShopId = new List<string>();
bool canUse = shopEntity.LoginStatus == "登录成功";
//canUse = true; // 内部库不需要校验登录状态
var row = dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(p => p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == shopEntity.ShopId);
var day = DateTime.Now.ToString("yyyyMMdd").ParseToInt();
if (row == null)
{
this.dgvShop.Rows.Add(
//!isInit || (selectShopId.Contains(shopEntity.ShopId) && canUse),
dicCheckedShopId.Keys.Contains(shopEntity.ShopId) && dicCheckedShopId[shopEntity.ShopId] == true,
shopEntity.LoginName,
shopEntity.ShopId,
shopEntity.ShopAccount,
shopEntity.Notes,
"选择商品",
canUse ? "在线" : "掉线",
lstShopAuthInfo.FirstOrDefault(sa => sa.ShopId == shopEntity.ShopId)?.ExpiresTime > DateTime.Now.AddMinutes(5) ? "可用" : "过期",
canUse,
dicShopUpload.ContainsKey(shopEntity.ShopId) && dicShopUpload[shopEntity.ShopId].DicDayUploadCount.ContainsKey(day) ?
dicShopUpload[shopEntity.ShopId].DicDayUploadCount[day] : 0,
dicShopUpload.ContainsKey(shopEntity.ShopId) && dicShopUpload[shopEntity.ShopId].OnSaleRefreshDay == DateTime.Now.ToString("yyyyMMdd").ParseToInt() ?
dicShopUpload[shopEntity.ShopId].OnSaleCount : 0,
shopEntity.AddProductRemaining,
"",
msg
);
}
else
{
row.Cells["colSelect"].Value = !isInit || (selectShopId.Contains(shopEntity.ShopId) && canUse);
row.Cells["colShopLoginName"].Value = shopEntity.LoginName;
row.Cells["colShopName"].Value = shopEntity.ShopAccount;
row.Cells["colShopNotes"].Value = shopEntity.Notes;
row.Cells["colLoginStatus"].Value = canUse ? "在线" : "掉线";
row.Cells["colLoginStatus"].Style.ForeColor = canUse ? Color.Green : Color.Red;
row.Cells["colCanUse"].Value = canUse;
row.Cells["colApi"].Value = lstShopAuthInfo.FirstOrDefault(sa => sa.ShopId == shopEntity.ShopId)?.ExpiresTime > DateTime.Now.AddMinutes(5) ? "可用" : "过期";
row.Cells["colRemaining"].Value = shopEntity.AddProductRemaining;
row.Cells["colUploadCount"].Value = dicShopUpload.ContainsKey(shopEntity.ShopId) && dicShopUpload[shopEntity.ShopId].DicDayUploadCount.ContainsKey(day) ?
dicShopUpload[shopEntity.ShopId].DicDayUploadCount[day] : 0;
row.Cells["colOnSaleNum"].Value = dicShopUpload.ContainsKey(shopEntity.ShopId) && dicShopUpload[shopEntity.ShopId].OnSaleRefreshDay == DateTime.Now.ToString("yyyyMMdd").ParseToInt() ?
dicShopUpload[shopEntity.ShopId].OnSaleCount : 0;
row.Cells["colMessage"].Value = msg;
}
displayAuthStatus(shopEntity);
}
void displayAuthStatus(ShopLoginInfo shop)
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colShopId"].Value.ParseToString() == shop?.ShopId);
foreach (var row in rows)
{
bool canUse = row.Cells["colLoginStatus"].Value.ParseToString() == "在线";
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).Style.ForeColor = canUse ? Color.Blue : Color.Red;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).LinkColor = canUse ? Color.Blue : Color.Red;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).ActiveLinkColor = canUse ? Color.LightBlue : Color.OrangeRed;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).VisitedLinkColor = canUse ? Color.DarkBlue : Color.DarkRed;
canUse = row.Cells["colApi"].Value.ParseToString() == "可用";
(row.Cells["colApi"] as DataGridViewLinkCell).Style.ForeColor = canUse ? Color.Blue : Color.Red;
(row.Cells["colApi"] as DataGridViewLinkCell).LinkColor = canUse ? Color.Blue : Color.Red;
(row.Cells["colApi"] as DataGridViewLinkCell).ActiveLinkColor = canUse ? Color.LightBlue : Color.OrangeRed;
(row.Cells["colApi"] as DataGridViewLinkCell).VisitedLinkColor = canUse ? Color.DarkBlue : Color.DarkRed;
}
}
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;
string shopId = dgvShop.Rows[e.RowIndex].Cells["colShopId"].Value.ParseToString();
string shopAccount = dgvShop.Rows[e.RowIndex].Cells["colShopName"].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();
chkSelectAll.CheckedChanged -= chkSelectAll_CheckedChanged;
if (dgvShop.Rows.Cast<DataGridViewRow>().All(r => r.Cells["colSelect"].Value.ParseToBool()))
chkSelectAll.Checked = true;
else
chkSelectAll.Checked = false;
chkSelectAll.CheckedChanged += chkSelectAll_CheckedChanged;
}
//else
{
//BaseMsgForm.ShowInfo("店铺未登录!");
}
dicCheckedShopId[row.Cells["colShopId"].Value.ParseToString()] = row.Cells["colSelect"].Value.ParseToBool();
NaiBa.Util.Helper.ConfigHelper.SaveConfig("wx_checked_shop_dic", dicCheckedShopId);
break;
case "colLoginStatus":
{
if (WXShopListForm.Instance == null)
WXShopListForm.Instance = new WXShopListForm();
WXShopListForm.Instance.CheckShopLogin(new string[] { shop.LoginName }, false);
WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop);
//shopLoginForm.prodUserSelectForm = this;
if (shop.LoginStatus != "登录成功")
{
shopLoginForm.openType = EnumOpenType.login;
shopLoginForm.ShowDialog();
RefreshShopLogin();
}
else
{
shopLoginForm.openType = EnumOpenType.manage;
shopLoginForm.WindowState = FormWindowState.Maximized;
shopLoginForm.Show();
}
}
break;
case "colApi":
{
WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop);
shopLoginForm.openType = EnumOpenType.manage;
shopLoginForm.WindowState = FormWindowState.Maximized;
shopLoginForm.InitUrl = "https://store.weixin.qq.com/shop/servicemarket/detail?serviceId=3984039898079707139";
shopLoginForm.Show();
}
break;
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
var lstShopId = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList();
if (lstShopId.Count == 0)
{
BaseMsgForm.ShowInfo("请选择店铺!");
return;
}
}
private void dgvSelectProduct_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvSelectProduct.Columns[e.ColumnIndex].HeaderText;
var dbId = dgvSelectProduct.Rows[e.RowIndex].Cells["colSelectId"].Value.ParseToString();
var dbProduct = lstTemuDBProductSelect.FirstOrDefault(p => p.id.ToString() == dbId);
var shopId = dgvSelectProduct.Rows[e.RowIndex].Cells["colSupplierId"].Value.ParseToString();
var draftId = dgvSelectProduct.Rows[e.RowIndex].Cells["colDraftId"].Value.ParseToString();
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
switch (headerText)
{
case "删除":
break;
case "登录":
{
WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop);
//shopLoginForm.prodUserSelectForm = this;
shopLoginForm.openType = EnumOpenType.login;
shopLoginForm.ShowDialog();
RefreshShopLogin();
}
break;
case "进店":
{
WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop);
WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
if (shop.LoginStatus == "登录成功")
{
shopLoginForm.openType = EnumOpenType.manage;
shopLoginForm.WindowState = FormWindowState.Maximized;
shopLoginForm.InitUrl = "https://store.weixin.qq.com/shop/home";
shopLoginForm.Show();
}
else
{
shopLoginForm.openType = EnumOpenType.login;
shopLoginForm.ShowDialog();
RefreshShopLogin();
}
}
break;
case "上传商品Id":
//if (!string.IsNullOrEmpty(draftId) && shop != null)
//{
// ShopLoginForm shopLoginForm = new ShopLoginForm(shop);
// shopLoginForm.InitUrl = "https://seller.kuajingmaihuo.com/goods/product-create/product-edit?productDraftId=" +
// draftId + "&from=productDraftList";
// shopLoginForm.openType = EnumOpenType.manage;
// shopLoginForm.WindowState = FormWindowState.Maximized;
// shopLoginForm.ShowDialog();
//}
break;
case "图片":
{
ShowImgForm imgFrom = new ShowImgForm(dgvSelectProduct.Rows[e.RowIndex].Cells["colImgUrl"].Value.ParseToString());
imgFrom.ShowDialog();
break;
}
case "SKU替换图":
{
ShowImgForm imgFrom = new ShowImgForm(dgvSelectProduct.Rows[e.RowIndex].Cells["colSkuFakeImgUrl"].Value.ParseToString());
imgFrom.ShowDialog();
break;
}
case "":
dgvSelectProduct.Rows[e.RowIndex].Cells["colCheck"].Value = !(bool)dgvSelectProduct.Rows[e.RowIndex].Cells["colCheck"].Value;
break;
default:
break;
}
}
Task tskPreSale = null;
private void btnSetPreSale_Click(object sender, EventArgs e)
{
var rowLst = dgvSelectProduct.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colCheck"].Value.ParseToBool() == true).ToList();
if (rowLst.Count <= 0)
{
BaseMsgForm.ShowError("请勾选需要操作的商品!");
return;
}
if (cmbCouponType.Text != "满减" && cmbCouponType.Text != "每满" && cmbCouponType.Text != "直减" && cmbCouponType.Text != "统一折扣" && cmbCouponType.Text != "条件折扣")
{
BaseMsgForm.ShowError("请填写正确的优惠方式参数!");
return;
}
if (cmbCouponType.Text == "满减" && (txtProductPrice.Text.Trim().ParseToDecimal() == 0 || txtDiscountFee.Text.Trim().ParseToDecimal() == 0))
{
BaseMsgForm.ShowError("请填写正确的优惠方式参数!");
return;
}
else if (cmbCouponType.Text == "每满" && (txtProductPrice.Text.Trim().ParseToDecimal() == 0 || txtDiscountFee.Text.Trim().ParseToDecimal() == 0))
{
BaseMsgForm.ShowError("请填写正确的优惠方式参数!");
return;
}
else if (cmbCouponType.Text == "直减" && (txtDiscountFee.Text.Trim().ParseToDecimal() == 0))
{
BaseMsgForm.ShowError("请填写正确的优惠方式参数!");
return;
}
else if (cmbCouponType.Text == "统一折扣" && (txtDiscountNum.Text.Trim().ParseToDecimal() == 0))
{
BaseMsgForm.ShowError("请填写正确的优惠方式参数!");
return;
}
else if (cmbCouponType.Text == "条件折扣" && (txtProductCnt.Text.Trim().ParseToDecimal() == 0 || txtDiscountNum.Text.Trim().ParseToDecimal() == 0))
{
BaseMsgForm.ShowError("请填写正确的优惠方式参数!");
return;
}
else if (cmbCouponType.Text == "统一折扣" && (txtDiscountNum.Text.Trim().ParseToDecimal() > 9.9m || txtDiscountNum.Text.Trim().ParseToDecimal() < 2))
{
BaseMsgForm.ShowError("折扣必须在2-9.9之间,最多一位小数");
return;
}
else if (cmbCouponType.Text == "条件折扣" && (txtDiscountNum.Text.Trim().ParseToDecimal() > 9.9m || txtDiscountNum.Text.Trim().ParseToDecimal() < 2))
{
BaseMsgForm.ShowError("折扣必须在2-9.9之间,最多一位小数");
return;
}
if (txtLimitNumOnePerson.Text.Trim().ParseToInt() == 0)
{
BaseMsgForm.ShowError("请填写正确的限领参数!");
return;
}
if (txtTotalCnt.Text.Trim().ParseToInt() == 0)
{
BaseMsgForm.ShowError("请填写正确的发放数量参数!");
return;
}
this.pbLoading.Visible = true;
this.btnSetPreSale.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
dgvSelectProduct.Columns["colCouponNum"].Visible = false;
tskPreSale = Task.Run(() =>
{
SetProdCoupon(rowLst.Select(r => r.Cells["colDraftId"].Value.ParseToString()).Distinct().ToList());
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "商品设置完毕";
BaseMsgForm.ShowInfo("商品设置完毕");
this.pbLoading.Visible = false;
this.btnSetPreSale.Enabled = true;
}));
}, cancellationTokenSource.Token);
}
void SetProdCoupon(List<string> prodIdLst)
{
Invoke(new Action(() =>
{
this.pbLoading.Visible = true;
this.statusBar.lblTaskStatus.Text = "正在设置" + "...".Substring(0, DateTime.Now.Second % 4);
this.statusBar.pgbTaskProgress.Maximum = prodIdLst.Count;
this.statusBar.UpdateProgressBar(0);
}));
foreach (var prodId in prodIdLst)
{
var row = dgvSelectProduct.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colDraftId"].Value.ParseToString() == prodId);
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "正在设置" + "...".Substring(0, DateTime.Now.Second % 4);
this.statusBar.UpdateProgressBar(this.statusBar.pgbTaskProgress.Value + 1);
row.Cells["colOpResult"].Value = "";
}));
if (cancellationTokenSource.IsCancellationRequested)
break;
var shopId = row.Cells["colSupplierId"].Value.ParseToString();
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "店铺不存在";
}));
continue;
}
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "店铺掉线";
}));
continue;
}
WXCouponParamBase wxCouponParam = new WXCouponParamBase();
Thread.Sleep(Randomx.GetId(200, 500));
//wxCouponParam.check = true;
wxCouponParam.coupon.couponInfo.name = prodId;
wxCouponParam.coupon.couponInfo.discountInfo.discountCondition.productIds.Add(prodId.ParseToLong());
wxCouponParam.coupon.couponInfo.extInfo.autoValidTime = BaseClass.DateTimeToTimestampSeconds(startTime);
wxCouponParam.coupon.couponInfo.receiveInfo.startTime = BaseClass.DateTimeToTimestampSeconds(startTime);
wxCouponParam.coupon.couponInfo.receiveInfo.endTime = BaseClass.DateTimeToTimestampSeconds(endTime);
wxCouponParam.coupon.couponInfo.validInfo.startTime = BaseClass.DateTimeToTimestampSeconds(startTime);
wxCouponParam.coupon.couponInfo.validInfo.endTime = BaseClass.DateTimeToTimestampSeconds(endTime);
wxCouponParam.coupon.couponInfo.receiveInfo.limitNumOnePerson = limitNumOnePerson;
wxCouponParam.coupon.couponInfo.receiveInfo.totalNum = totalCnt.ParseToString();
if (couponType == "满减")
{
wxCouponParam.coupon.couponKey.type = 2;
wxCouponParam.coupon.couponInfo.discountInfo.discountCondition.productPrice = productPriceValue.ParseToString();
wxCouponParam.coupon.couponInfo.discountInfo.discountFee = discountFeeValue.ParseToString();
}
else if (couponType == "每满")
{
wxCouponParam.coupon.couponKey.type = 2;
wxCouponParam.coupon.couponInfo.discountInfo.isCanUp = true;
wxCouponParam.coupon.couponInfo.discountInfo.discountCondition.productPrice = productPriceValue.ParseToString();
wxCouponParam.coupon.couponInfo.discountInfo.discountFee = discountFeeValue.ParseToString();
}
else if (couponType == "直减")
{
wxCouponParam.coupon.couponKey.type = 4;
wxCouponParam.coupon.couponInfo.discountInfo.discountFee = discountFeeValue.ParseToString();
}
else if (couponType == "统一折扣")
{
wxCouponParam.coupon.couponKey.type = 3;
wxCouponParam.coupon.couponInfo.discountInfo.discountNum = discountNum.ToString("0.##");
}
else if (couponType == "条件折扣")
{
wxCouponParam.coupon.couponKey.type = 1;
wxCouponParam.coupon.couponInfo.discountInfo.discountCondition.productCnt = productCnt;
wxCouponParam.coupon.couponInfo.discountInfo.discountNum = discountNum.ToString("0.##");
}
Thread.Sleep(Randomx.GetId(200, 500));
if (chkSkipSet.Checked)
{
var searchCouponRst = WxCoupon.WxSearchCoupon(shop, prodId);
if (searchCouponRst.Contains("biz magic invalid"))
{
WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
}
if (!searchCouponRst.Contains("\"success\":true") && !searchCouponRst.Contains("\"code\":0"))
{
var errmsg = BaseRegex.GetStringJson(ref searchCouponRst, "msg");
if (string.IsNullOrWhiteSpace(errmsg))
errmsg = searchCouponRst;
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = errmsg;
}));
continue;
}
if (searchCouponRst.Contains("\"code\":0"))
{
var totalNum = BaseRegex.GetStringJson(ref searchCouponRst, "totalNum");
Invoke(new Action(() =>
{
row.Cells["colCouponNum"].Value = totalNum;
}));
var issuedNum = 0;
try
{
var jCoupons = JsonHelper.JObjectParse(searchCouponRst);
foreach(var coupon in jCoupons)
{
var couponStr = JsonHelper.SerializeObject(coupon);
//var receiveNum = BaseRegex.GetStringJson(ref couponStr, "receiveNum");
issuedNum = BaseRegex.GetStringJson(ref couponStr, "issuedNum").ParseToInt();
if (issuedNum > 0)
break;
}
}
catch
{
}
if (issuedNum.ParseToInt() > 0)
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "商品还有未领取的专属优惠券,跳过";
}));
continue;
}
}
}
var addCouponRst = WxCoupon.WxSetCoupon(shop, wxCouponParam);
Thread.Sleep(Randomx.GetId(50, 100));
if(addCouponRst.Contains("biz magic invalid"))
{
WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
}
if (!addCouponRst.Contains("\"success\":true") && !addCouponRst.Contains("\"code\":0"))
{
var errmsg = BaseRegex.GetStringJson(ref addCouponRst, "msg");
if (string.IsNullOrWhiteSpace(errmsg))
errmsg = addCouponRst;
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = errmsg;
}));
continue;
}
if (addCouponRst.Contains("\"code\":0"))
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "设置成功";
}));
}
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (this.cancellationTokenSource != null)
this.cancellationTokenSource.Cancel();
}
private void btnSearchProd_Click(object sender, EventArgs e)
{
var shopIdLst = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList();
if (shopIdLst.Count <= 0)
{
BaseMsgForm.ShowError("未勾选上传店铺!");
return;
}
btnSearchProd.Enabled = false;
pbLoading.Visible = true;
cancellationTokenSource = new CancellationTokenSource();
dgvSelectProduct.Rows.Clear();
dgvSelectProduct.Columns["colCouponNum"].Visible = false;
Task.Run(() =>
{
GetProduct(shopIdLst);
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "商品查询完毕";
BaseMsgForm.ShowInfo("商品查询完毕");
pbLoading.Visible = false;
btnSearchProd.Enabled = true;
}));
}, cancellationTokenSource.Token);
}
void GetProduct(List<string> shopIdLst)
{
List<ShopLoginInfo> shopLst = GlobalConfig.ShopLoginList.Where(s => shopIdLst.Contains(s.ShopId)).ToList();
foreach(var shop in shopLst)
{
if(cancellationTokenSource.IsCancellationRequested)
break;
if (shop.LoginStatus != "登录成功")
{
continue;
}
int page = PageBegin - 1;
int totalPage = 1;
int pageSize = 50;
string nextKey = "";
while (page < totalPage && page < PageEnd)
{
page++;
if (cancellationTokenSource.IsCancellationRequested)
break;
string getProdOnSaleRst = "";
if (string.IsNullOrEmpty(PreType) && sortType == null)
getProdOnSaleRst = WXPreSale.scanProductPreview(shop, page, nextKey, pageSize);
else
getProdOnSaleRst = WXPreSale.searchProduct(shop, page, null, pageSize, sortType);
Thread.Sleep(Randomx.GetId(50, 100));
if (!getProdOnSaleRst.Contains("\"success\":true"))
{
var error = BaseRegex.GetStringJson(ref getProdOnSaleRst, "msg");
if (string.IsNullOrEmpty(error))
error = getProdOnSaleRst;
WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() => { BindShop(shop, shopIdLst, "店铺掉线"); }));
}
var shopRow = dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colShopId"].Value.ParseToString() == shop.ShopId);
Invoke(new Action(() => {
if (shopRow != null)
{
shopRow.Cells["colOpResult"].Value = error;
}
}));
break;
}
try
{
var prodObjs = JsonHelper.JObjectParse(getProdOnSaleRst);
if (page == 1 || 1 == 1)
{
var totalNum = prodObjs["totalNum"].ParseToInt();
totalPage = Math.Ceiling(1m * totalNum / pageSize).ParseToInt();
}
nextKey = prodObjs["nextKey"].ParseToString();
Invoke(new Action(() =>
{
this.pbLoading.Visible = true;
this.statusBar.lblTaskStatus.Text = "正在查询店铺:" + shop.ShopAccount + " " + page + "/" + Math.Min(PageEnd, totalPage);
//this.statusBar.pgbTaskProgress.Maximum = lstTemuDBProductSelect.Count;
//this.statusBar.UpdateProgressBar(0);
}));
foreach (JObject prod in prodObjs["productList"])
{
var pStr = JsonHelper.SerializeObject(prod);
Invoke(new Action(() =>
{
decimal? price = null;
try { price = prod["skuList"][0]["price"].ParseToDecimal() / 100; } catch { }
var prodId = prod["productId"].ParseToString();
if (dgvSelectProduct.Rows.Cast<DataGridViewRow>().Any(r => r.Cells["colDraftId"].ParseToString() == prodId))
{
}
var rowIndex = this.dgvSelectProduct.Rows.Add(
false,
"",
shop.ShopId,
shop.ShopAccount,
"登录",
"进店",
"",
"",
prod["productId"].ParseToString(),
prod["headImg"].ParseToString(),
DataGridViewExtension.defaultBitmap,
"", // 替换图地址
null, // 替换图
prod["title"].ParseToString(), // 用户端显示商品原名
(prod["recommendCategory"].IsJTokenNullOrEmpty() || prod["recommendCategory"]["categoryNames"].IsJTokenNullOrEmpty()) ?
"" : string.Join(" >> ", prod["recommendCategory"]["categoryNames"].Select(s => s.ParseToString())), // 类目名称
prod["spuCode"].ParseToString(),
//price,
prod["price"].ParseToDecimal() * 0.01m,
prod["soldNum"].ParseToInt(),
"在售" + (prod["presaleTag"].ParseToInt() == 1 ? "[预售]" : ""),
"", // 备注
"",
"删除",
BaseClass.StampToDateTime(prod["lastEditDraftTime"].ParseToInt()).ToString("yy-MM-dd HH:mm"),
"");
dgvSelectProduct.Rows[rowIndex].Height = 60;
dgvSelectProduct.Rows[rowIndex].Cells["colMsg"].Style.ForeColor = dgvSelectProduct.Rows[rowIndex].Cells["colMsg"].Value.ParseToString().Contains("预售") ? Color.Orange : Color.Blue;
}));
}
}
catch (Exception ex)
{
}
}
}
}
private void btnClearDgv_Click(object sender, EventArgs e)
{
var rows = this.dgvSelectProduct.Rows.Cast<DataGridViewRow>().ToList(); //Cast后Rows做foreach循环时仍会夹花跳过,所以要ToList转一个新的数组。
foreach (var row in rows)
{
if (row.Cells["colCheck"].Value.ParseToBool() == true)
{
//var draft_id = row.Cells["colDraftId"].Value.ParseToString();
//upload_draft_product_lst.RemoveAll(p => p.draft_id == draft_id);
this.dgvSelectProduct.Rows.Remove(row);
}
}
//NaiBa.Util.Helper.ConfigHelper.SaveConfig("wx_select_upload_draft_products", upload_draft_product_lst);
}
private void btnClearFilter_Click(object sender, EventArgs e)
{
txtFiltSaleNumMoreThan.Text = "0";
txtFiltSaleNumLessThan.Text = "1";
}
private void txtPreDays_TextChanged(object sender, EventArgs e)
{
}
private void chkPreSale_CheckedChanged(object sender, EventArgs e)
{
}
private void btnFilterShop_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in dgvShop.Rows)
{
string notes = cmbFilterShopNotes.Text.Trim().Trim(';');
if (notes == "全部")
notes = "";
List<string> notesLst = notes.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (!row.Cells["colShopName"].Value.ParseToString().Contains(txtFilterShopName.Text.Trim()))
{
row.Visible = false;
row.Cells["colSelect"].Value = false;
continue;
}
if (!string.IsNullOrWhiteSpace(notes) && !notesLst.Contains(row.Cells["colShopNotes"].Value.ParseToString()))
{
row.Visible = false;
row.Cells["colSelect"].Value = false;
continue;
}
row.Visible = true;
}
}
private void btnEmptyShop_Click(object sender, EventArgs e)
{
txtFilterShopName.Text = "";
cmbFilterShopNotes.Text = "全部";
btnFilterShop_Click(null, null);
}
private void btnReverse_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in dgvShop.Rows)
{
if (row.Visible == true)
row.Cells["colSelect"].Value = !row.Cells["colSelect"].Value.ParseToBool();
}
}
private void btnAddSelect_Click(object sender, EventArgs e)
{
string notes = cmbFilterShopNotes.Text.Trim().Trim(';');
if (notes == "全部")
notes = "";
List<string> notesLst = notes.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (row.Visible == true)
{
if (row.Cells["colShopName"].Value.ParseToString().Contains(txtFilterShopName.Text.Trim()) &&
(string.IsNullOrWhiteSpace(notes) || notesLst.Contains(row.Cells["colShopNotes"].Value.ParseToString())))
{
row.Cells["colSelect"].Value = true;
}
}
}
}
private void btnAddUnSelect_Click(object sender, EventArgs e)
{
string notes = cmbFilterShopNotes.Text.Trim().Trim(';');
if (notes == "全部")
notes = "";
List<string> notesLst = notes.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (row.Visible == true)
{
if (row.Cells["colShopName"].Value.ParseToString().Contains(txtFilterShopName.Text.Trim()) &&
(string.IsNullOrWhiteSpace(notes) || notesLst.Contains(row.Cells["colShopNotes"].Value.ParseToString())))
{
row.Cells["colSelect"].Value = false;
}
}
}
}
private void btnSelectOnline_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (row.Visible == true)
{
if (row.Cells["colLoginStatus"].Value.ParseToString() == "在线")
{
row.Cells["colSelect"].Value = true;
}
else
{
row.Cells["colSelect"].Value = false;
}
}
}
}
private void btnSelectOffline_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (row.Visible == true)
{
if (row.Cells["colLoginStatus"].Value.ParseToString() != "在线")
{
row.Cells["colSelect"].Value = true;
}
else
{
row.Cells["colSelect"].Value = false;
}
}
}
}
private void txtPageBegin_TextChanged(object sender, EventArgs e)
{
PageEnd = txtPageBegin.Text.ParseToInt();
}
private void txtPageEnd_TextChanged(object sender, EventArgs e)
{
PageEnd = txtPageEnd.Text.ParseToInt();
}
private void cmbPreType_SelectedIndexChanged(object sender, EventArgs e)
{
PreType = cmbPreType.Text.Trim();
}
private void btnFiltSelectMoreThan_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in dgvSelectProduct.Rows)
{
if (row.Cells["colSoldNum"].Value.ParseToInt() > txtFiltSaleNumMoreThan.Text.Trim().ParseToInt())
row.Cells["colCheck"].Value = true;
else
row.Cells["colCheck"].Value = false;
}
}
private void btnFiltSelectLessThan_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvSelectProduct.Rows)
{
if (row.Cells["colSoldNum"].Value.ParseToInt() >= txtFiltSaleNumLessThan.Text.Trim().ParseToInt())
row.Cells["colCheck"].Value = false;
else
row.Cells["colCheck"].Value = true;
}
}
string couponType = "满减";
private void cmbCouponType_TextChanged(object sender, EventArgs e)
{
couponType = cmbCouponType.Text;
//满减 //每满 //直减 //统一折扣 //条件折扣
foreach (Control c in flowLayoutPanel1.Controls)
{
c.Visible = false;
lblProductPrice.Text = "满";
lblDiscountFee.Text = "减";
}
if (cmbCouponType.Text == "满减")
{
lblProductPrice.Text = "满";
lblProductPrice.Visible = true;
txtProductPrice.Visible = true;
lblDiscountFee.Visible = true;
txtDiscountFee.Visible = true;
}
else if (cmbCouponType.Text == "每满")
{
lblProductPrice.Text = "每满";
lblProductPrice.Visible = true;
txtProductPrice.Visible = true;
lblDiscountFee.Visible = true;
txtDiscountFee.Visible = true;
}
else if (cmbCouponType.Text == "直减")
{
lblDiscountFee.Text = "直减";
lblDiscountFee.Visible = true;
txtDiscountFee.Visible = true;
}
else if (cmbCouponType.Text == "统一折扣")
{
lblDiscountNum.Visible = true;
txtDiscountNum.Visible = true;
}
else if (cmbCouponType.Text == "条件折扣")
{
lblProductPrice.Visible = true;
lblProductCnt.Visible = true;
txtProductCnt.Visible = true;
lblDiscountNum.Visible = true;
txtDiscountNum.Visible = true;
}
}
private void btnClearCoupon_Click(object sender, EventArgs e)
{
txtProductPrice.Text = "";
txtDiscountFee.Text = "";
txtProductCnt.Text = "";
txtDiscountNum.Text = "";
txtTotalCnt.Text = "100";
txtLimitNumOnePerson.Text = "1";
dtpStartTime.Value = DateTime.Now.Date;
dtpEndTime.Value = DateTime.Now.Date.AddDays(30);
}
decimal productPriceValue = 0;
private void txtProductPrice_TextChanged(object sender, EventArgs e)
{
productPriceValue = txtProductPrice.Text.Trim().ParseToDecimal();
}
decimal discountFeeValue = 0;
private void txtDiscountFee_TextChanged(object sender, EventArgs e)
{
discountFeeValue = txtDiscountFee.Text.Trim().ParseToDecimal();
}
int productCnt = 0;
private void txtProductCnt_TextChanged(object sender, EventArgs e)
{
productCnt = txtProductCnt.Text.Trim().ParseToInt();
}
decimal discountNum = 0;
private void txtDiscountNum_TextChanged(object sender, EventArgs e)
{
discountNum = txtDiscountNum.Text.Trim().ParseToDecimal();
}
int totalCnt = 100;
private void txtTotalCnt_TextChanged(object sender, EventArgs e)
{
totalCnt = txtTotalCnt.Text.Trim().ParseToInt();
}
int limitNumOnePerson = 1;
private void txtLimitNumOnePerson_TextChanged(object sender, EventArgs e)
{
limitNumOnePerson = txtLimitNumOnePerson.Text.Trim().ParseToInt();
}
DateTime startTime = DateTime.Now.Date;
private void dtpStartTime_ValueChanged(object sender, EventArgs e)
{
startTime = dtpStartTime.Value;
}
DateTime endTime = DateTime.Now.Date.AddDays(30);
private void dtpEndTime_ValueChanged(object sender, EventArgs e)
{
endTime = dtpEndTime.Value;
}
private void btnEndCoupon_Click(object sender, EventArgs e)
{
var rowLst = dgvSelectProduct.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colCheck"].Value.ParseToBool() == true).ToList();
if (rowLst.Count <= 0)
{
BaseMsgForm.ShowError("请勾选需要操作的商品!");
return;
}
this.pbLoading.Visible = true;
this.btnSetPreSale.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
dgvSelectProduct.Columns["colCouponNum"].HeaderText = "生效券数量";
dgvSelectProduct.Columns["colCouponNum"].Visible = true;
Task.Run(() =>
{
EndProdCoupon(rowLst);
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "优惠券作废删除完毕";
BaseMsgForm.ShowInfo("优惠券作废删除完毕");
this.pbLoading.Visible = false;
this.btnSetPreSale.Enabled = true;
}));
}, cancellationTokenSource.Token);
}
void EndProdCoupon(List<DataGridViewRow> rowLst)
{
Invoke(new Action(() =>
{
this.pbLoading.Visible = true;
this.statusBar.lblTaskStatus.Text = "正在作废删除" + "...".Substring(0, DateTime.Now.Second % 4);
this.statusBar.pgbTaskProgress.Maximum = rowLst.Count;
this.statusBar.UpdateProgressBar(0);
}));
foreach (var row in rowLst)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "正在作废删除" + "...".Substring(0, DateTime.Now.Second % 4);
this.statusBar.UpdateProgressBar(this.statusBar.pgbTaskProgress.Value + 1);
row.Cells["colOpResult"].Value = "";
row.Cells["colCouponNum"].Value = "";
}));
var prodId = row.Cells["colDraftId"].Value.ParseToString();
var shopId = row.Cells["colSupplierId"].Value.ParseToString();
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "店铺不存在";
}));
continue;
}
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "店铺掉线";
}));
continue;
}
var searchCouponRst = WxCoupon.WxSearchCoupon(shop, prodId);
Thread.Sleep(Randomx.GetId(500, 1000));
if (searchCouponRst.Contains("biz magic invalid"))
{
WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
}
if (!searchCouponRst.Contains("\"success\":true") && !searchCouponRst.Contains("\"code\":0"))
{
var errmsg = BaseRegex.GetStringJson(ref searchCouponRst, "msg");
if (string.IsNullOrWhiteSpace(errmsg))
errmsg = searchCouponRst;
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = errmsg;
}));
continue;
}
if (searchCouponRst.Contains("\"code\":0"))
{
var totalNum = BaseRegex.GetStringJson(ref searchCouponRst, "totalNum");
Invoke(new Action(() =>
{
row.Cells["colCouponNum"].Value = totalNum;
}));
if (totalNum == "0")
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "商品无专属优惠券,跳过";
}));
continue;
}
try
{
var couponLst = JsonHelper.DeserializeJsonToList<WXCouponParam>(JsonHelper.JObjectParse(searchCouponRst)["coupons"].ToString());
string errMsg = "";
foreach (var coupon in couponLst)
{
var endRst = WxCoupon.WxEndCoupon(shop, coupon.couponKey.couponId.ParseToString());
Thread.Sleep(Randomx.GetId(100, 300));
if (!endRst.Contains("\"code\":0"))
{
var err = BaseRegex.GetStringJson(ref endRst, "msg");
if (string.IsNullOrWhiteSpace(err))
err = endRst;
errMsg += coupon.couponKey.couponId + " " + err + " \r\n";
continue;
}
var delRst = WxCoupon.WxDelCoupon(shop, coupon.couponKey.couponId.ParseToString());
Thread.Sleep(Randomx.GetId(100, 300));
if (!delRst.Contains("\"code\":0"))
{
var err = BaseRegex.GetStringJson(ref delRst, "msg");
if (string.IsNullOrWhiteSpace(err))
err = delRst;
errMsg += coupon.couponKey.couponId + " " + err + " \r\n";
continue;
}
}
if (!errMsg.IsNullOrEmpty())
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "作废删除失败 " + errMsg;
}));
}
else
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "作废删除成功";
}));
}
}
catch (Exception ex)
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "作废删除失败 优惠券格式转换失败";
}));
}
}
}
}
int? sortType = null;
private void cmbSaleSort_TextChanged(object sender, EventArgs e)
{
sortType = null;
if (cmbSaleSort.Text == "降序")
sortType = 6;
if (cmbSaleSort.Text == "升序")
sortType = 5;
}
private void btnPromotion_Click(object sender, EventArgs e)
{
var rowLst = dgvSelectProduct.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colCheck"].Value.ParseToBool() == true).ToList();
if (rowLst.Count <= 0)
{
BaseMsgForm.ShowError("请勾选需要操作的商品!");
return;
}
if (ratioValue < 1 || ratioValue > 50)
{
BaseMsgForm.ShowError("佣金范围为1到50!");
return;
}
this.pbLoading.Visible = true;
this.btnSetPreSale.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
dgvSelectProduct.Columns["colCouponNum"].Visible = false;
Task.Run(() =>
{
SetPromotion(rowLst);
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "商品设置推广完毕";
BaseMsgForm.ShowInfo("商品设置推广完毕");
this.pbLoading.Visible = false;
this.btnSetPreSale.Enabled = true;
}));
}, cancellationTokenSource.Token);
}
void SetPromotion(List<DataGridViewRow> rowLst)
{
Invoke(new Action(() =>
{
this.pbLoading.Visible = true;
this.statusBar.lblTaskStatus.Text = "正在设置" + "...".Substring(0, DateTime.Now.Second % 4);
this.statusBar.pgbTaskProgress.Maximum = rowLst.Count;
this.statusBar.UpdateProgressBar(0);
}));
while(rowLst.Count > 0)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
var r0 = rowLst.FirstOrDefault();
var shopId = r0.Cells["colSupplierId"].Value.ParseToString();
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
var rowLstTmp = rowLst.Where(r => r.Cells["colSupplierId"].Value.ParseToString() == shopId).Take(30).ToList();
foreach(var r in rowLstTmp)
{
rowLst.Remove(r);
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "正在设置" + "...".Substring(0, DateTime.Now.Second % 4);
this.statusBar.UpdateProgressBar(this.statusBar.pgbTaskProgress.Value + 1);
r.Cells["colOpResult"].Value = "";
}));
}
if (shop == null)
{
Invoke(new Action(() =>
{
foreach (var r in rowLstTmp)
{
r.Cells["colOpResult"].Value = "店铺不存在";
}
}));
continue;
}
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() =>
{
foreach (var r in rowLstTmp)
{
r.Cells["colOpResult"].Value = "店铺掉线";
}
}));
continue;
}
List<string> prodIdLst = new List<string>();
List<string> prodIdTmpLst = new List<string>();
foreach (var row in rowLstTmp)
{
var prodId = row.Cells["colDraftId"].Value.ParseToString();
prodIdTmpLst.Add(prodId);
}
var prodCanPromotionRst = WxCoupon.WxGetCanPromotion(shop, prodIdTmpLst);
Thread.Sleep(Randomx.GetId(300, 800));
if (prodCanPromotionRst.Contains("biz magic invalid"))
{
WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
}
if (!prodCanPromotionRst.Contains("\"success\":true") && !prodCanPromotionRst.Contains("\"code\":0"))
{
var errmsg = BaseRegex.GetStringJson(ref prodCanPromotionRst, "msg");
if (string.IsNullOrWhiteSpace(errmsg))
errmsg = prodCanPromotionRst;
Invoke(new Action(() =>
{
foreach (var row in rowLstTmp)
row.Cells["colOpResult"].Value = errmsg;
}));
continue;
}
if (prodCanPromotionRst.Contains("\"code\":0"))
{
try
{
var itemLst = JsonHelper.JObjectParse(prodCanPromotionRst)["itemList"];
foreach(JObject itemObj in itemLst)
{
var spuId = itemObj["spuId"].ParseToLong();
var status = itemObj["status"].ParseToInt();
if (status == 4)
{
prodIdLst.Add(spuId.ParseToString());
}
else
{
var row = rowLstTmp.FirstOrDefault(r => r.Cells["colDraftId"].Value.ParseToString() == spuId.ParseToString());
if (row != null)
{
Invoke(new Action(() =>
{
if (status == 1)
row.Cells["colOpResult"].Value = "已存在普通推广,跳过";
else
row.Cells["colOpResult"].Value = "商品不符合推广条件,跳过";
}));
}
}
}
if (prodIdLst.Count > 0)
{
var addPromotionRst = WxCoupon.WxAddPromotion(shop, prodIdLst, (ratioValue * 10000).ParseToInt());
Thread.Sleep(Randomx.GetId(500, 1500));
//{"code":0,"errCodeList":[0,0,15978008]}
if (!addPromotionRst.Contains("\"code\":0"))
{
var errmsg = BaseRegex.GetStringJson(ref addPromotionRst, "msg");
if (string.IsNullOrWhiteSpace(errmsg))
errmsg = addPromotionRst;
foreach (var prodId in prodIdLst)
{
var row = rowLstTmp.FirstOrDefault(r => r.Cells["colDraftId"].Value.ParseToString() == prodId.ParseToString());
if (row != null)
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "推广失败," + errmsg;
}));
}
}
}
else
{
var errCodeLst = (JsonHelper.JObjectParse(addPromotionRst)["errCodeList"] as JArray).Select(code => code.ParseToLong()).ToList();
for (int i = 0; i < errCodeLst.Count; i++)
{
var prodId = prodIdLst[i];
var errCode = errCodeLst[i];
var row = rowLstTmp.FirstOrDefault(r => r.Cells["colDraftId"].Value.ParseToString() == prodId.ParseToString());
if (row != null)
{
Invoke(new Action(() =>
{
if (errCode == 15978008)
row.Cells["colOpResult"].Value = "推广设置失败,佣金比例错误,错误码 " + errCode;
else if (errCode > 0)
row.Cells["colOpResult"].Value = "推广设置失败,错误码 " + errCode;
else
row.Cells["colOpResult"].Value = "推广设置成功";
}));
}
}
}
}
}
catch (Exception ex)
{
Invoke(new Action(() =>
{
foreach (var r in rowLstTmp)
{
if (r.Cells["colOpResult"].Value.ParseToString().IsNullOrEmpty())
r.Cells["colOpResult"].Value = "推广失败" + ex.Message;
}
}));
}
//Invoke(new Action(() =>
//{
// row.Cells["colOpResult"].Value = "设置成功";
//}));
}
}
}
decimal ratioValue = 1;
private void txtRatio_TextChanged(object sender, EventArgs e)
{
ratioValue = txtRatio.Text.Trim().ParseToDecimal();
}
private void btnEndPromotion_Click(object sender, EventArgs e)
{
var rowLst = dgvSelectProduct.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colCheck"].Value.ParseToBool() == true).ToList();
if (rowLst.Count <= 0)
{
BaseMsgForm.ShowError("请勾选需要操作的商品!");
return;
}
this.pbLoading.Visible = true;
this.btnSetPreSale.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
dgvSelectProduct.Columns["colCouponNum"].HeaderText = "生效推广数量";
dgvSelectProduct.Columns["colCouponNum"].Visible = true;
Task.Run(() =>
{
EndProdPromotion(rowLst);
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "推广取消完毕";
BaseMsgForm.ShowInfo("推广取消完毕");
this.pbLoading.Visible = false;
this.btnSetPreSale.Enabled = true;
}));
}, cancellationTokenSource.Token);
}
void EndProdPromotion(List<DataGridViewRow> rowLst)
{
Invoke(new Action(() =>
{
this.pbLoading.Visible = true;
this.statusBar.lblTaskStatus.Text = "正在取消推广" + "...".Substring(0, DateTime.Now.Second % 4);
this.statusBar.pgbTaskProgress.Maximum = rowLst.Count;
this.statusBar.UpdateProgressBar(0);
}));
foreach (var row in rowLst)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "正在取消推广" + "...".Substring(0, DateTime.Now.Second % 4);
this.statusBar.UpdateProgressBar(this.statusBar.pgbTaskProgress.Value + 1);
row.Cells["colOpResult"].Value = "";
row.Cells["colCouponNum"].Value = "";
}));
var prodId = row.Cells["colDraftId"].Value.ParseToString();
var shopId = row.Cells["colSupplierId"].Value.ParseToString();
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "店铺不存在";
}));
continue;
}
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "店铺掉线";
}));
continue;
}
var searchPromotionRst = WxCoupon.WxSearchPromotion(shop, prodId);
Thread.Sleep(Randomx.GetId(500, 1000));
if (searchPromotionRst.Contains("biz magic invalid"))
{
WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
}
if (!searchPromotionRst.Contains("\"success\":true") && !searchPromotionRst.Contains("\"code\":0"))
{
var errmsg = BaseRegex.GetStringJson(ref searchPromotionRst, "msg");
if (string.IsNullOrWhiteSpace(errmsg))
errmsg = searchPromotionRst;
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = errmsg;
}));
continue;
}
if (searchPromotionRst.Contains("\"code\":0"))
{
var totalNum = BaseRegex.GetStringJson(ref searchPromotionRst, "totalNum");
Invoke(new Action(() =>
{
row.Cells["colCouponNum"].Value = totalNum;
}));
if (totalNum == "0")
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "商品无推广,跳过";
}));
continue;
}
try
{
var promArr = JsonHelper.JObjectParse(searchPromotionRst)["itemList"] as JArray;
string errMsg = "";
foreach (JObject promObj in promArr)
{
var endRst = WxCoupon.WxEndPromotion(shop, promObj["spuId"].ParseToString());
Thread.Sleep(Randomx.GetId(100, 300));
if (!endRst.Contains("\"code\":0"))
{
var err = BaseRegex.GetStringJson(ref endRst, "msg");
if (string.IsNullOrWhiteSpace(err))
err = endRst;
errMsg += promObj["spuId"].ParseToString() + " " + err + " \r\n";
continue;
}
var delRst = WxCoupon.WxDelPromotion(shop, promObj["spuId"].ParseToString());
Thread.Sleep(Randomx.GetId(100, 300));
if (!delRst.Contains("\"code\":0"))
{
var err = BaseRegex.GetStringJson(ref delRst, "msg");
if (string.IsNullOrWhiteSpace(err))
err = delRst;
errMsg += promObj["spuId"].ParseToString() + " " + err + " \r\n";
continue;
}
}
if (!errMsg.IsNullOrEmpty())
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "取消推广失败 " + errMsg;
}));
}
else
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "取消推广成功";
}));
}
}
catch (Exception ex)
{
Invoke(new Action(() =>
{
row.Cells["colOpResult"].Value = "取消推广失败 推广格式转换失败";
}));
}
}
}
}
}
public class WxCoupon
{
public static string WxSetCoupon(ShopLoginInfo shop, WXCouponParamBase couponParam)
{
string url = "https://store.weixin.qq.com/shop-faas/market/coupon/cgi/makeQp?token=&lang=zh_CN";
string referer = "https://store.weixin.qq.com/shop/marketing/coupon/make?type=990";
JsonSerializerSettings jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var prodStr = JsonConvert.SerializeObject(couponParam, jsonSetting);
string body = prodStr; //JsonHelper.SerializeObject(jObj);
var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer);
return result;
}
//{"pageSize":20,"page":0,"couponName":"10000509758262","couponCustomizeChannel":"","couponTypeList":[],"promoteTypeList":[],"couponStatusList":[]}
public static string WxSearchCoupon(ShopLoginInfo shop, string couponName)
{
string url = "https://store.weixin.qq.com/shop-faas/market/coupon/cgi/searchCoupon?token=&lang=zh_CN";
string referer = "https://store.weixin.qq.com/shop/marketing/coupon";
//所有券
//string body = "{\"pageSize\":20,\"page\":0,\"couponName\":\"10000509758262\",\"couponCustomizeChannel\":\"\",\"couponTypeList\":[],\"promoteTypeList\":[],\"couponStatusList\":[]}";
//生效中的券
string body = "{\"pageSize\":20,\"page\":0,\"couponName\":\"" + couponName + "\",\"couponCustomizeChannel\":\"\",\"couponTypeList\":[],\"promoteTypeList\":[],\"couponStatusList\":[\"2\"]}";
var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer);
return result;
}
public static string WxEndCoupon(ShopLoginInfo shop, string couponId)
{
string url = "https://store.weixin.qq.com/shop-faas/market/coupon/cgi/upCouponStatus?token=&lang=zh_CN";
string referer = "https://store.weixin.qq.com/shop/marketing/coupon";
string body = @"{""couponId"":""" + couponId + @""",""status"":4}";
var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer);
return result;
}
public static string WxDelCoupon(ShopLoginInfo shop, string couponId)
{
string url = "https://store.weixin.qq.com/shop-faas/market/coupon/cgi/upCouponStatus?token=&lang=zh_CN";
string referer = "https://store.weixin.qq.com/shop/marketing/coupon";
string body = @"{""couponId"":""" + couponId + @""",""status"":5}";
var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer);
return result;
}
public static string WxGetCanPromotion(ShopLoginInfo shop, List<string> prodIdLst)
{
string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/plan/getItemList?token=&lang=zh_CN";
foreach (var prodId in prodIdLst)
{
url += "&spuIdList[]=" + prodId;
}
url += "&offset=0&list_type=1";
string referer = "https://store.weixin.qq.com/shop/shopleague/home/normal-add";
var result = WXHttpResponseBLL.WeiXinGetResponse(shop, url, referer);
return result;
}
public static string WxAddPromotion(ShopLoginInfo shop, List<string> prodIdLst, int ratio)
{
string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/plan/batchAddItem?token=&lang=zh_CN";
string body = @"{""list"":[";
foreach (var prodId in prodIdLst)
body += @"{""spuId"":""" + prodId + @""",""ratio"":" + ratio + @",""finderCoupon"":0},";
body = body.TrimEnd(',');
body += @"]}";
string referer = "https://store.weixin.qq.com/shop/shopleague/home/normal-add";
var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer);
return result;
}
public static string WxSearchPromotion(ShopLoginInfo shop, string prodId)
{
string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/plan/getItemListBySearch?" +
"token=&lang=zh_CN&offset=0&size=10&product_title=" + prodId + "&status=1&list_type=2&needWarning=true&needStockNum=true";
string referer = "https://store.weixin.qq.com/shop/shopleague/home";
var result = WXHttpResponseBLL.WeiXinGetResponse(shop, url, referer);
return result;
}
public static string WxEndPromotion(ShopLoginInfo shop, string prodId)
{
string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/plan/updateItem?token=&lang=zh_CN";
string referer = "https://store.weixin.qq.com/shop/shopleague/home";
string body = @"{""spu_id"":""" + prodId + @""",""operate_type"":2}";
var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer);
return result;
}
public static string WxDelPromotion(ShopLoginInfo shop, string prodId)
{
string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/plan/updateItem?token=&lang=zh_CN";
string referer = "https://store.weixin.qq.com/shop/shopleague/home";
string body = @"{""spu_id"":""" + prodId + @""",""operate_type"":3}";
var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer);
return result;
}
}
}