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; using CefSharp.WinForms; using CefSharp; using TemuKJD.Helper; using NaiBa.CefHelper; using NaiBa.CefHelper.Handler; namespace TemuKJD.WXForms.ProductForms { public partial class WXFinderSquareForm : BaseForm { public CancellationTokenSource cancellationTokenSource { get; set; } = null; public bool IsLoadComplate { get; set; } = false; WXAddFinderParam wxAddFinderParam = new WXAddFinderParam(); ChromiumWebBrowser mainWebBrowser = null; CheckBox chkSelectAll = null; ShopLoginInfo currentShop; int PageBegin = 1; int PageEnd = 20; string currentGetTalentParam = ""; List lstWXFinderTalentInfo = new List(); List lstWXLiveObjectInfo = new List(); List lstWXFeedObjectInfo = new List(); public WXFinderSquareForm() { InitializeComponent(); } private void UserSelectDbProductForm_Load(object sender, EventArgs e) { this.splitContainer1.Dock = DockStyle.Fill; // 选中信息 //dicCheckedShopId = NaiBa.Util.Helper.ConfigHelper.LoadConfig>("wx_checked_shop_dic"); //if (dicCheckedShopId == null) // dicCheckedShopId = new Dictionary(); // 邀约参数 wxAddFinderParam = NaiBa.Util.Helper.ConfigHelper.LoadConfig("wx_add_finder_param"); if (wxAddFinderParam == null) wxAddFinderParam = new WXAddFinderParam(); txtContactPerson.TextAlignChanged -= txtContactPerson_TextChanged; txtExplain.TextAlignChanged -= txtExplain_TextChanged; txtMobile.TextAlignChanged -= txtMobile_TextChanged; txtWxNumber.TextAlignChanged -= txtWxNumber_TextChanged; this.txtContactPerson.Text = wxAddFinderParam.ContactPerson; this.txtExplain.Text = wxAddFinderParam.Explain; this.txtMobile.Text = wxAddFinderParam.Mobile; this.txtWxNumber.Text = wxAddFinderParam.WxNumber; txtContactPerson.TextAlignChanged += txtContactPerson_TextChanged; txtExplain.TextAlignChanged += txtExplain_TextChanged; txtMobile.TextAlignChanged += txtMobile_TextChanged; txtWxNumber.TextAlignChanged += txtWxNumber_TextChanged; chkSelectAll = dgvShop.Columns["colSelect"].AddHeaderCheckBox(HorizontalAlignment.Center, 0, 0, null, null, false); dgvShop.Columns["colSelect"].HeaderText = ""; chkSelectAll.CheckedChanged += chkSelectAll_CheckedChanged; this.dgvTalent.AddSelectorColumn("colCheck"); dgvTalent.AddImgColumn("colImg", "colImgUrl"); this.dgvDaRenProd.AddSelectorColumn("colDgvProdCheck"); dgvDaRenProd.AddImgColumn("colLiveObjectImg", "colLiveObjectImgUrl"); dgvDaRenProd.AddImgColumn("colDgvProdImg", "colDgvProdImgUrl"); InitCef(); Task.Run(() => { // 直到店铺加载完后再加载客服内容 while (!StartUp.IsShopInit) Thread.Sleep(100); currentShop = GlobalConfig.ValidShopLoginList.FirstOrDefault(); Invoke(new Action(() => { this.txtCurrentShop.Text = currentShop?.ShopAccount; this.txtCurrentShop.Tag = currentShop?.ShopId; })); if (currentShop != null) SetMainBrowserUrl(currentShop); }); IsLoadComplate = true; } void InitCef() { if (mainWebBrowser == null) { mainWebBrowser = CEFBrowser.CreateChromiumWebBrowser("about:blank", false); mainWebBrowser.KeyboardHandler = new KeyboardHandler(); mainWebBrowser.Dock = DockStyle.Fill; var lifeSpanHandler = new LifeSpanHandlerLocal(PopWindowType.NewTitleWindow); lifeSpanHandler.parent = mainWebBrowser; lifeSpanHandler.OnPop += MainLifeHandler_OnPop; mainWebBrowser.LifeSpanHandler = lifeSpanHandler; CustomResourceRequestHandlerLocal resourceRequestHandler = new CustomResourceRequestHandlerLocal(); resourceRequestHandler.ResourceLoadCompleteEvent += RequestHandler_ResourceLoadComplete; resourceRequestHandler.BeforeResourceLoadEvent += RequestHandler_BeforeResourceLoad; mainWebBrowser.RequestHandler = new CustomRequestHandler(resourceRequestHandler); mainWebBrowser.AddressChanged += MainWebBrowser_AddressChanged; mainWebBrowser.FrameLoadEnd += MainWebBrowser_FrameLoadEnd; mainPanel.Controls.Add(mainWebBrowser); } } private void MainWebBrowser_AddressChanged(object sender, AddressChangedEventArgs e) { //this.txtAddress.Text = e.Address; } private void MainWebBrowser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e) { } private bool RequestHandler_BeforeResourceLoad(object sender, string url, string postData, IRequest request) { return false; } private void RequestHandler_ResourceLoadComplete(object sender, string url, string postData, string responseData, IRequest request) { if (url.StartsWith("https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/finderSquare/cgi/getSquareTalentList")) { currentGetTalentParam = postData; } if (/*responseData.Contains("mpAppid") ||*/ responseData.Contains("wxb32c03106e812d73")) { } } private void MainLifeHandler_OnPop(object sender, PopData e) { var targetUrl = e.Url; var lifeHandler = sender as LifeSpanHandlerLocal; Task.Run(() => { if (lifeHandler.parent != null) { var cookies = CEFBrowser.GetCookieList("", lifeHandler.parent.RequestContext.GetCookieManager(null)); Invoke(new Action(() => { CefForm cefForm = new CefForm(targetUrl, cookies); cefForm.Show(); })); } }); } 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.ValidShopLoginList.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()) //{ // 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(); } } private void RefreshShopLogin() { // 店铺Id var selectIds = dgvShop.Rows.Cast().Where(row => row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); // 获取被删除的店铺 List dgvRowList = dgvShop.Rows.Cast().Where(row => !GlobalConfig.ValidShopLoginList.Any(s => s.ShopId == row.Cells["colShopId"]?.Value?.ToString())).ToList(); // 更新被删除的店铺列表 foreach (var row in dgvRowList) { dgvShop.Rows.Remove(row); } // 绑定其他店铺(含新导入的店铺) foreach (ShopLoginInfo shopEntity in GlobalConfig.ValidShopLoginList) { if (!string.IsNullOrEmpty(shopEntity.ShopId)) BindShop(shopEntity, selectIds); } cmbFilterShopNotes.Items.Clear(); foreach (var note in GlobalConfig.ValidShopLoginList.Select(s => s.Notes).Where(s => !s.IsNullOrEmpty()).Distinct()) { cmbFilterShopNotes.Items.Add(note); } cmbFilterShopGroup.Items.Clear(); foreach (var group in GlobalConfig.ValidShopLoginList.Select(s => s.GroupName).Where(s => !s.IsNullOrEmpty()).Distinct()) { cmbFilterShopGroup.Items.Add(group); } pbLoadingShop.Visible = false; } private void BindShop(ShopLoginInfo shopEntity, List selectShopId = null, string msg = "") { if (shopEntity == null) return; if (shopEntity.is_point_shop_expire) return; if (selectShopId == null) selectShopId = new List(); bool canUse = shopEntity.LoginStatus == "登录成功"; //canUse = true; // 内部库不需要校验登录状态 var row = dgvShop.Rows.Cast().FirstOrDefault(p => p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == shopEntity.ShopId); var day = DateTime.Now.ToString("yyyyMMdd").ParseToInt(); if (row == null) { this.dgvShop.Rows.Add( dgvShop.Rows.Count == 0 ? true : (selectShopId.Contains(shopEntity.ShopId) && canUse), shopEntity.LoginName, shopEntity.ShopId, shopEntity.ShopAccount, shopEntity.Notes, shopEntity.GroupName, "选择商品", canUse ? "在线" : "掉线", GlobalConfig.lstWxShopAuthInfo.FirstOrDefault(sa => sa.ShopId == shopEntity.ShopId)?.ExpiresTime > DateTime.Now.AddMinutes(5) ? "可用" : "过期", canUse, GlobalConfig.dicWxShopUploadInfo.ContainsKey(shopEntity.ShopId) ? GlobalConfig.dicWxShopUploadInfo[shopEntity.ShopId].DicDayUploadCount[day] : 0, GlobalConfig.dicWxShopUploadInfo.ContainsKey(shopEntity.ShopId) ? GlobalConfig.dicWxShopUploadInfo[shopEntity.ShopId].OnSaleCount : 0, shopEntity.AddProductRemaining, msg ); } else { row.Cells["colSelect"].Value = 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 = GlobalConfig.lstWxShopAuthInfo.FirstOrDefault(sa => sa.ShopId == shopEntity.ShopId)?.ExpiresTime > DateTime.Now.AddMinutes(5) ? "可用" : "过期"; row.Cells["colRemaining"].Value = shopEntity.AddProductRemaining; row.Cells["colUploadCount"].Value = GlobalConfig.dicWxShopUploadInfo.ContainsKey(shopEntity.ShopId) ? GlobalConfig.dicWxShopUploadInfo[shopEntity.ShopId].DicDayUploadCount[day] : 0; row.Cells["colOnSaleNum"].Value = GlobalConfig.dicWxShopUploadInfo.ContainsKey(shopEntity.ShopId) ? GlobalConfig.dicWxShopUploadInfo[shopEntity.ShopId].OnSaleCount : 0; row.Cells["colMessage"].Value = msg; } displayAuthStatus(shopEntity); } void displayAuthStatus(ShopLoginInfo shop) { var rows = this.dgvShop.Rows.Cast().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_CellClick(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.ValidShopLoginList.FirstOrDefault(s => s.ShopId == shopId.ToString()); var row = dgvShop.Rows[e.RowIndex]; foreach(DataGridViewRow r in dgvShop.Rows) { if (r == row) continue; if (r.Cells["colSelect"].Value.ParseToBool() == true) r.Cells["colSelect"].Value = false; } row.Cells["colSelect"].Value = true; if (currentShop != shop) { this.txtCurrentShop.Text = shopAccount; this.txtCurrentShop.Tag = shopId; currentShop = shop; Task.Run(() => { SetMainBrowserUrl(shop); }); } } 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.ValidShopLoginList.FirstOrDefault(s => s.ShopId == shopId.ToString()); var row = dgvShop.Rows[e.RowIndex]; this.txtCurrentShop.Text = shopAccount; this.txtCurrentShop.Tag = shopId; currentShop = shop; 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().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 dgvTalent_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex < 0 || e.RowIndex < 0) return; string headerText = dgvTalent.Columns[e.ColumnIndex].HeaderText; var shopId = dgvTalent.Rows[e.RowIndex].Cells["colSupplierId"].Value.ParseToString(); var shop = GlobalConfig.ValidShopLoginList.FirstOrDefault(s => s.ShopId == shopId); var talentAppid = dgvTalent.Rows[e.RowIndex].Cells["colTalentAppid"].Value.ParseToString(); var talent = this.lstWXFinderTalentInfo.FirstOrDefault(t => t.talentAppid == talentAppid); 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 "图片": { ShowImgForm imgFrom = new ShowImgForm(dgvTalent.Rows[e.RowIndex].Cells["colImgUrl"].Value.ParseToString()); imgFrom.ShowDialog(); break; } case "": dgvTalent.Rows[e.RowIndex].Cells["colCheck"].Value = !(bool)dgvTalent.Rows[e.RowIndex].Cells["colCheck"].Value; break; default: break; } } private void btnStop_Click(object sender, EventArgs e) { if (this.cancellationTokenSource != null) this.cancellationTokenSource.Cancel(); } private void btnSearchTalent_Click(object sender, EventArgs e) { //var shopIdLst = dgvShop.Rows.Cast().Where(row // => row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); //if (shopIdLst.Count <= 0) //{ // BaseMsgForm.ShowError("未勾选店铺!"); // return; //} if (currentShop == null) { BaseMsgForm.ShowError("当前店铺为空!"); return; } btnSearchTalent.Enabled = false; pbLoading.Visible = true; if (cancellationTokenSource != null) cancellationTokenSource.Cancel(); cancellationTokenSource = new CancellationTokenSource(); dgvTalent.Rows.Clear(); Task.Run(() => { GetTalent(currentShop, currentGetTalentParam); Invoke(new Action(() => { this.statusBar.lblTaskStatus.Text = "达人查询完毕"; BaseMsgForm.ShowInfo("达人查询完毕"); pbLoading.Visible = false; btnSearchTalent.Enabled = true; })); }, cancellationTokenSource.Token); } void GetTalent(ShopLoginInfo shop, string searchParam) { if (shop.LoginStatus != "登录成功") { return; } lstWXFinderTalentInfo = new List(); var shopRow = dgvShop.Rows.Cast().FirstOrDefault(r => r.Cells["colShopId"].Value.ParseToString() == shop.ShopId); int page = PageBegin - 1; int totalPage = 1; int pageSize = 20; while (page < totalPage && page < PageEnd) { if (cancellationTokenSource.IsCancellationRequested) break; page++; Invoke(new Action(() => { this.pbLoading.Visible = true; this.statusBar.lblTaskStatus.Text = "正在查询店铺:" + shop.ShopAccount + " 达人 " + page + "/" + Math.Min(PageEnd, totalPage); })); Thread.Sleep(Randomx.GetId(2500, 5000)); string getFinderTalentRst = ""; try { JObject getTalentParamObj = JsonHelper.JObjectParse(currentGetTalentParam); getTalentParamObj["filter"]["offset"] = (page - 1) * getTalentParamObj["filter"]["limit"].ParseToInt(); getFinderTalentRst = WXFinderSquareBLL.getSquareTalentList(shop, JsonHelper.SerializeObject(getTalentParamObj)); } catch (Exception ex) { if (shopRow != null) { Invoke(new Action(() => { shopRow.Cells["colMessage"].Value = "达人查询格式错误"; })); } } Thread.Sleep(Randomx.GetId(50, 100)); if (!getFinderTalentRst.Contains("\"code\":0") && !getFinderTalentRst.Contains("\"success\":true")) { var error = BaseRegex.GetStringJson(ref getFinderTalentRst, "msg"); if (string.IsNullOrEmpty(error)) error = getFinderTalentRst; WXShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false); if (shop.LoginStatus != "登录成功") { var selectIds = dgvShop.Rows.Cast().Where(row => row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); })); } if (shopRow != null) { Invoke(new Action(() => { shopRow.Cells["colMessage"].Value = error; })); } break; } try { var talentObj = JsonHelper.JObjectParse(getFinderTalentRst)["list"]; var wxFinderTalentInfo = JsonHelper.DeserializeJsonToList(JsonHelper.SerializeObject(talentObj)); if (page == 1 || 1 == 1) { var totalNum = BaseRegex.GetIntJson(ref getFinderTalentRst, "totalNum"); totalPage = Math.Ceiling(1m * totalNum / pageSize).ParseToInt(); } lstWXFinderTalentInfo.AddRange(wxFinderTalentInfo); foreach (var finderTalent in wxFinderTalentInfo) { Invoke(new Action(() => { string tag = ""; if (finderTalent.finderInfo.topDaren == 1) tag += "优质带货者 "; if (finderTalent.finderInfo.highResponse == 1) tag += "回复率高 "; var rowIndex = this.dgvTalent.Rows.Add ( false, shop.ShopId, shop.ShopAccount, "登录", "进店", finderTalent.finderInfo.headImg, DataGridViewExtension.defaultBitmap, finderTalent.talentAppid, finderTalent.finderInfo.nickname, tag, string.Join(" ", finderTalent.finderInfo.topCatList.Select(c => c.topCatName)) + "\r\n" + finderTalent.promotionInfo.windowsScore, finderTalent.finderInfo.fansNumber, finderTalent.promotionInfo.gmv, finderTalent.promotionInfo.liveGmv, finderTalent.promotionInfo.videoGmv, finderTalent.promotionInfo.bizPayGmv, "删除", "" ); dgvTalent.Rows[rowIndex].Height = 60; })); } } catch (Exception ex) { } } } private void btnClearDgv_Click(object sender, EventArgs e) { var rows = this.dgvTalent.Rows.Cast().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.dgvTalent.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) { } private void btnFilterShop_Click(object sender, EventArgs e) { string notes = cmbFilterShopNotes.Text.Trim().Trim(';'); if (notes == "全部") notes = ""; List notesLst = notes.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); string group = cmbFilterShopGroup.Text.Trim().Trim(';'); if (group == "全部") group = ""; List groupLst = group.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (DataGridViewRow row in dgvShop.Rows) { 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; } if (!string.IsNullOrWhiteSpace(group) && !groupLst.Contains(row.Cells["colGroup"].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 = "全部"; cmbFilterShopGroup.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 notesLst = notes.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); string group = cmbFilterShopGroup.Text.Trim().Trim(';'); if (group == "全部") group = ""; List groupLst = group.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (DataGridViewRow row in dgvShop.Rows) { if (row.Visible == false) continue; if (!row.Cells["colShopName"].Value.ParseToString().Contains(txtFilterShopName.Text.Trim())) continue; if (!string.IsNullOrWhiteSpace(notes) && !notesLst.Contains(row.Cells["colShopNotes"].Value.ParseToString())) continue; if (!string.IsNullOrWhiteSpace(group) && !groupLst.Contains(row.Cells["colGroup"].Value.ParseToString())) continue; row.Cells["colSelect"].Value = true; } } private void btnAddUnSelect_Click(object sender, EventArgs e) { string notes = cmbFilterShopNotes.Text.Trim().Trim(';'); if (notes == "全部") notes = ""; List notesLst = notes.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); string group = cmbFilterShopGroup.Text.Trim().Trim(';'); if (group == "全部") group = ""; List groupLst = group.Split(new string[] { ";", ";", ",", "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); foreach (DataGridViewRow row in dgvShop.Rows) { if (row.Visible == false) continue; if (!row.Cells["colShopName"].Value.ParseToString().Contains(txtFilterShopName.Text.Trim())) continue; if (!string.IsNullOrWhiteSpace(notes) && !notesLst.Contains(row.Cells["colShopNotes"].Value.ParseToString())) continue; if (!string.IsNullOrWhiteSpace(group) && !groupLst.Contains(row.Cells["colGroup"].Value.ParseToString())) continue; 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 SetMainBrowserUrl(ShopLoginInfo shop) { if (shop == null) return; var cookieLst = new List(); try { cookieLst = JsonHelper.DeserializeJsonToList(shop.Cookies.ParseToString().Replace("empty=true;", "[]")); } catch { } if (mainWebBrowser == null) { Invoke(new Action(() => { InitCef(); })); } var cookieManager = mainWebBrowser.RequestContext.GetCookieManager(null); cookieManager.DeleteCookiesAsync("qq.com", null).Wait(); foreach (var cook in cookieLst) { var t = CEFBrowser.SetCookieAsync(cook.Domain, cook.Name + "=" + cook.Value + ";", cookieManager); t.Wait(5000); } mainWebBrowser.Load("https://store.weixin.qq.com/shop/findersquare/find"); } private void txtPageEnd_TextChanged(object sender, EventArgs e) { PageEnd = txtPageEnd.Text.ParseToInt(); } private void txtContactPerson_TextChanged(object sender, EventArgs e) { wxAddFinderParam.ContactPerson = txtContactPerson.Text.Trim(); NaiBa.Util.Helper.ConfigHelper.SaveConfig("wx_add_finder_param", wxAddFinderParam); } private void txtWxNumber_TextChanged(object sender, EventArgs e) { wxAddFinderParam.WxNumber = txtWxNumber.Text.Trim(); NaiBa.Util.Helper.ConfigHelper.SaveConfig("wx_add_finder_param", wxAddFinderParam); } private void txtMobile_TextChanged(object sender, EventArgs e) { wxAddFinderParam.Mobile = txtMobile.Text.Trim(); NaiBa.Util.Helper.ConfigHelper.SaveConfig("wx_add_finder_param", wxAddFinderParam); } private void txtExplain_TextChanged(object sender, EventArgs e) { wxAddFinderParam.Explain = txtExplain.Text.Trim(); NaiBa.Util.Helper.ConfigHelper.SaveConfig("wx_add_finder_param", wxAddFinderParam); } private void btnAddFinder_Click(object sender, EventArgs e) { if (wxAddFinderParam.ContactPerson.IsNullOrEmpty()) { BaseMsgForm.ShowError("联系人不能为空"); return; } if (wxAddFinderParam.WxNumber.IsNullOrEmpty() || wxAddFinderParam.WxNumber.Length < 6) { BaseMsgForm.ShowError("请确定微信号不为空,最少六个字符"); return; } if (wxAddFinderParam.Mobile.IsNullOrEmpty() || wxAddFinderParam.Mobile.ParseToLong().ToString().Length != 11) { BaseMsgForm.ShowError("手机号码格式不正确"); return; } if (wxAddFinderParam.Explain.IsNullOrEmpty()) { BaseMsgForm.ShowError("合作说明不能为空"); return; } var selectRows = dgvTalent.Rows.Cast().Where(r => r.Cells["colCheck"].Value.ParseToBool() == true).ToList(); if (selectRows.Count == 0) { BaseMsgForm.ShowError("请选择要邀约的达人"); return; } pbLoading.Visible = true; string prodIds = txtProductIds.Text.Trim(); this.btnAddFinder.Enabled = false; Task.Run(() => { Thread.Sleep(5000); Invoke(new Action(() => { this.btnAddFinder.Enabled = true; })); }); if (cancellationTokenSource != null) cancellationTokenSource.Cancel(); cancellationTokenSource = new CancellationTokenSource(); Task.Run(() => { if (string.IsNullOrEmpty(prodIds)) { var shopId = selectRows.FirstOrDefault().Cells["colSupplierId"].Value.ParseToString(); var shop = GlobalConfig.ValidShopLoginList.FirstOrDefault(s => s.ShopId == shopId); if(chkReUse.Visible && chkReUse.Checked) shop = currentShop; var talentAppid = selectRows.FirstOrDefault().Cells["colTalentAppid"].Value.ParseToString(); var talent = this.lstWXFinderTalentInfo.FirstOrDefault(t => t.talentAppid == talentAppid); prodIds = GetFinderProdList(shop, talent); if (prodIds.Contains("\"success\":false")) { Invoke(new Action(() => { var errMsg = BaseRegex.GetStringJson(ref prodIds, "msg"); if (!string.IsNullOrEmpty(errMsg)) { errMsg = GetHtml.UrlDecode(errMsg); selectRows.FirstOrDefault().Cells["colOpResult"].Value = errMsg; } else selectRows.FirstOrDefault().Cells["colOpResult"].Value = "达人邀约失败,请稍后再试"; })); Invoke(new Action(() => { pbLoading.Visible = false; this.statusBar.lblTaskStatus.Text = "达人邀约操作中断"; BaseMsgForm.ShowError("达人邀约操作中断"); })); return; } } { int num = 0; foreach (var row in selectRows) { num++; Invoke(new Action(() => { this.statusBar.lblTaskStatus.Text = "达人邀约 第 " + num + " 条,共 " + selectRows.Count + " 条"; row.Cells["colOpResult"].Value = ""; })); if (this.cancellationTokenSource.IsCancellationRequested) break; var shopId = row.Cells["colSupplierId"].Value.ParseToString(); var shop = GlobalConfig.ValidShopLoginList.FirstOrDefault(s => s.ShopId == shopId); if (chkReUse.Visible && chkReUse.Checked) shop = currentShop; var talentAppid = row.Cells["colTalentAppid"].Value.ParseToString(); var talent = this.lstWXFinderTalentInfo.FirstOrDefault(t => t.talentAppid == talentAppid); if (shop!=null && talent != null) { List prodIdLst = prodIds.Split(new string[] { ",", ",", ";", ";", " " }, StringSplitOptions.RemoveEmptyEntries).ToList(); var finderUsername = talent.accountList.FirstOrDefault(a => !a.finderUsername.IsNullOrEmpty())?.finderUsername; var promotionInvitationRst = WXFinderSquareBLL.createPromotionInvitation(shop, prodIdLst, finderUsername, talent.talentAppid, wxAddFinderParam.ContactPerson, wxAddFinderParam.WxNumber, wxAddFinderParam.Mobile, wxAddFinderParam.Explain.Replace("\r", "").Replace("\n", "")); Thread.Sleep(Randomx.GetId(3000, 5000)); if (!promotionInvitationRst.ParseToString().Contains("\"code\":0")) { var error = BaseRegex.GetStringJson(ref promotionInvitationRst, "errmsg"); if (string.IsNullOrEmpty(error)) error = promotionInvitationRst; if (promotionInvitationRst.ParseToString().Contains("biz magic invalid")) { shop.LoginStatus = "未登录"; var selectIds = dgvShop.Rows.Cast().Where(r => r.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); })); error = "店铺掉线"; } Invoke(new Action(() => { row.Cells["colOpResult"].Value = "达人邀约失败 " + error; })); } else { Invoke(new Action(() => { row.Cells["colOpResult"].Value = "已发送邀约"; })); } } } } Invoke(new Action(() => { pbLoading.Visible = false; this.statusBar.lblTaskStatus.Text += "达人邀约操作结束"; BaseMsgForm.ShowInfo("达人邀约操作结束"); })); }, cancellationTokenSource.Token); } public string GetFinderProdList(ShopLoginInfo shop, WXFinderTalentInfo finderTalent) { int page = 0; int pageSize = 10; int totalPage = 1; List wxProdIds = new List(); List wxProdIdWithListingTimeLst = new List(); while (page < totalPage ) { page++; Invoke(new Action(() => { this.statusBar.lblTaskStatus.Text = "正在查询达人邀约商品 第 " + page + " 页"; if (totalPage > 1) this.statusBar.lblTaskStatus.Text = "正在查询达人邀约商品 第 " + page + " 页,共 " + totalPage + " 页"; })); var finderUsername = finderTalent.accountList.FirstOrDefault(a => !a.finderUsername.IsNullOrEmpty())?.finderUsername; var getFinderProdRst = WXFinderSquareBLL.WxFinderSquareGetProdList(shop, page, finderUsername, finderTalent.talentAppid); Thread.Sleep(Randomx.GetId(1500, 2500)); if (!getFinderProdRst.Contains("\"code\":0")) { if (getFinderProdRst.Contains("\"code\":100002")) { return "{\"success\":false,\"code\":100002,\"msg\":\"店铺未设置达人推广商品,请先设置后再邀约达人\"}"; } if (getFinderProdRst.Contains("biz magic invalid")) { shop.LoginStatus = "未登录"; var selectIds = dgvShop.Rows.Cast().Where(r => r.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); })); return "{\"success\":false,\"msg\":\"查询达人商品列表失败,店铺掉线\"}"; } var error = BaseRegex.GetStringJson(ref getFinderProdRst, "msg"); if (string.IsNullOrEmpty(error)) error = getFinderProdRst; return "{\"success\":false,\"msg\":\"查询达人商品列表失败 " + GetHtml.UrlEncodeUtf8(error) + "\"}"; } if (page == 1) { var totalNum = BaseRegex.GetIntJson(ref getFinderProdRst, "totalNum"); totalPage = Math.Ceiling(1m * totalNum / pageSize).ParseToInt(); } try { var jArr = JsonHelper.JObjectParse(getFinderProdRst)["itemList"] as JArray; foreach (var jItem in jArr) { WXProdIdWithListingTime p = new WXProdIdWithListingTime() { listingTime = jItem["listingTime"].ParseToInt(), productName = jItem["productName"].ParseToString(), spuId = jItem["spuId"].ParseToString(), }; wxProdIdWithListingTimeLst.Add(p); } } catch (Exception ex) { return "{\"success\":false,\"msg\":\"查询达人商品列表失败 " + ex.Message + "\"}"; } } // 商品总数不到30,直接返回 if (wxProdIdWithListingTimeLst.Count <= 30) return string.Join(",", wxProdIdWithListingTimeLst.Select(p => p.spuId)); // 商品数量超过30,按出单量和上架时间倒序取前30 var wxProdIdWithListingTimeLstTmp = new List();//wxProdIdWithListingTimeLst wxProdIdWithListingTimeLstTmp.AddRange(wxProdIdWithListingTimeLst); while (wxProdIdWithListingTimeLstTmp.Count() > 0) { var getProdRst = WXFinderSquareBLL.getSaleSortProduct(shop, wxProdIdWithListingTimeLstTmp.Take(200).Select(p => p.spuId).ToList()); // 每次最多传200个id,取最高的50,每组销量最高的50在一起一定能获取全部商品最高的50(带货最多30个商品,可以确保一定是销量最高的前30) wxProdIdWithListingTimeLstTmp.RemoveRange(0, Math.Min(wxProdIdWithListingTimeLstTmp.Count, 200)); Thread.Sleep(Randomx.GetId(1500, 2500)); if (!getProdRst.Contains("\"success\":true")) { if (getProdRst.Contains("biz magic invalid")) { shop.LoginStatus = "未登录"; var selectIds = dgvShop.Rows.Cast().Where(r => r.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); })); return "{\"success\":false,\"msg\":\"查询达人商品列表2失败,店铺掉线\"}"; } var error = BaseRegex.GetStringJson(ref getProdRst, "msg"); if (string.IsNullOrEmpty(error)) error = getProdRst; return "{\"success\":false,\"msg\":\"查询达人商品列表2失败 " + GetHtml.UrlEncodeUtf8(error) + "\"}"; } try { var jArr = JsonHelper.JObjectParse(getProdRst)["productList"] as JArray; foreach (var jItem in jArr) { var soldNum = jItem["soldNum"]?.ParseToInt(); var pExist = wxProdIdWithListingTimeLst.FirstOrDefault(p => p.spuId == jItem["productId"].ParseToString()); if (pExist != null) { pExist.soldNum = soldNum; } else { return "{\"success\":false,\"msg\":\"查询达人商品列表2失败 商品未找到\"}"; } } } catch (Exception ex) { return "{\"success\":false,\"msg\":\"查询达人商品列表2失败 " + ex.Message + "\"}"; } } wxProdIdWithListingTimeLst = wxProdIdWithListingTimeLst.OrderByDescending(p => p.soldNum).ThenByDescending(p => p.listingTime).ToList().Take(30).ToList(); return string.Join(",", wxProdIdWithListingTimeLst.Select(p => p.spuId)); } private void btnSearch_Click(object sender, EventArgs e) { var selectRows = dgvTalent.Rows.Cast().Where(r => r.Cells["colCheck"].Value.ParseToBool() == true).ToList(); if (selectRows.Count == 0) { BaseMsgForm.ShowError("请在操作列表页选择要查询的达人"); return; } pictureBox1.Visible = true; string prodIds = txtProductIds.Text.Trim(); this.btnSearchDaRenProd.Enabled = false; Task.Run(() => { Thread.Sleep(5000); Invoke(new Action(() => { this.btnSearchDaRenProd.Enabled = true; })); }); dgvDaRenProd.Rows.Clear(); lstWXLiveObjectInfo.Clear(); lstWXFeedObjectInfo.Clear(); if (cancellationTokenSource != null) cancellationTokenSource.Cancel(); cancellationTokenSource = new CancellationTokenSource(); Task.Run(() => { int num = 0; foreach (var row in selectRows) { num++; Invoke(new Action(() => { this.statusBar.lblTaskStatus.Text = "达人带货商品查询 第 " + num + " 位,共 " + selectRows.Count + " 位达人"; row.Cells["colOpResult"].Value = ""; })); if (this.cancellationTokenSource.IsCancellationRequested) break; var shopId = row.Cells["colSupplierId"].Value.ParseToString(); var shop = GlobalConfig.ValidShopLoginList.FirstOrDefault(s => s.ShopId == shopId); if (chkReUse.Visible && chkReUse.Checked) shop = currentShop; var talentAppid = row.Cells["colTalentAppid"].Value.ParseToString(); var talent = this.lstWXFinderTalentInfo.FirstOrDefault(t => t.talentAppid == talentAppid); if (shop != null && talent != null && talent.accountList != null) { // 短视频带货 if (chkFeed.Checked) { var finderUser = talent.accountList.FirstOrDefault(a => !a.finderUsername.IsNullOrEmpty() && !a.mpAppid.IsNullOrEmpty()); finderUser = talent.accountList.FirstOrDefault(a => !a.finderUsername.IsNullOrEmpty()); var finderUsername = finderUser?.finderUsername; var mpAppid = finderUser?.mpAppid; var endMs = BaseClass.DateTimeToTimestampMilliseconds(DateTime.Now.Date) - 1; var startMs = BaseClass.DateTimeToTimestampMilliseconds(DateTime.Now.Date.AddDays(-7)); int page = 0; int pageSize = 10; while (true) { page++; var getLiveObjectRst = WXFinderSquareBLL.GetDaRenLiveFeedList(shop, finderUsername, mpAppid, talent.talentAppid, startMs, endMs, 2, page, pageSize); Thread.Sleep(Randomx.GetId(300, 600)); if (!getLiveObjectRst.ParseToString().Contains("\"code\":0")) { var error = BaseRegex.GetStringJsonByRegs(ref getLiveObjectRst, getLiveObjectRst, "errmsg"); if (error.ParseToString().Contains("biz magic invalid")) { shop.LoginStatus = "未登录"; var selectIds = dgvShop.Rows.Cast().Where(r => r.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); })); error = "店铺掉线"; } Invoke(new Action(() => { row.Cells["colOpResult"].Value = "达人带货商品查询失败 " + error; })); break; } var wxFeedObjectInfoResult = JsonHelper.DeserializeJsonToObject(getLiveObjectRst); var feedList = wxFeedObjectInfoResult.list; this.lstWXFeedObjectInfo.AddRange(feedList); foreach (var feed in feedList) { var prod = feed; Invoke(new Action(() => { if (prod.spuMonthSales.ParseToInt() >= txtSaleCount.Text.Trim().ParseToInt() && !dgvDaRenProd.Rows.Cast().Any(r => r.Cells["colTalentSpuId"].Value.ParseToString() == prod.spuId)) { var startTimeStr = BaseClass.StampToDateTime(feed.feedObjectStartTime.ParseToInt()).ToString("yy-MM-dd HH:mm"); var rowIndex = dgvDaRenProd.Rows.Add( false, shop.ShopId, shop.ShopAccount, "登录", "进店", "短视频", talent.talentAppid, finderUser.finderUsername, finderUser.nickname, // 达人昵称 feed.objectId, // 达人活动ID feed.feedObjectImg, DataGridViewExtension.defaultBitmap, // 短视频标题图 feed.feedObjectDescription, // 达人活动短视频标题 startTimeStr + " 点赞数" + feed.finderxshortvideoLikeCnt + " 分享数" + feed.finderxshortvideoShareCnt + " 喜欢数" + feed.finderxshortvideoFavoriteCnt, prod.spuImgUrl, DataGridViewExtension.defaultBitmap, prod.spuAppid, prod.spuShopNickname, prod.spuId, prod.spuName, prod.spuPrice.ParseToInt() * 0.01m, prod.spuMonthSales.ParseToInt(), "联系达人" ); dgvDaRenProd.Rows[rowIndex].Height = 60; } })); } var total = wxFeedObjectInfoResult.total.ParseToInt(); var totalPage = Math.Ceiling(total * 1m / pageSize).ParseToInt(); if (page >= totalPage) break; } } // 直播带货 if (chkLive.Checked) { var finderUser = talent.accountList.FirstOrDefault(a => !a.finderUsername.IsNullOrEmpty() && !a.mpAppid.IsNullOrEmpty()); finderUser = talent.accountList.FirstOrDefault(a => !a.finderUsername.IsNullOrEmpty()); var finderUsername = finderUser?.finderUsername; var mpAppid = finderUser?.mpAppid; var endMs = BaseClass.DateTimeToTimestampMilliseconds(DateTime.Now.Date) - 1; var startMs = BaseClass.DateTimeToTimestampMilliseconds(DateTime.Now.Date.AddDays(-7)); int page = 0; int pageSize = 10; while (true) { page++; var getLiveObjectRst = WXFinderSquareBLL.GetDaRenLiveFeedList(shop, finderUsername, mpAppid, talent.talentAppid, startMs, endMs, 1, page, pageSize); Thread.Sleep(Randomx.GetId(300, 600)); if (!getLiveObjectRst.ParseToString().Contains("\"code\":0")) { var error = BaseRegex.GetStringJsonByRegs(ref getLiveObjectRst, getLiveObjectRst, "errmsg"); if (error.ParseToString().Contains("biz magic invalid")) { shop.LoginStatus = "未登录"; var selectIds = dgvShop.Rows.Cast().Where(r => r.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); })); error = "店铺掉线"; } Invoke(new Action(() => { row.Cells["colOpResult"].Value = "达人带货商品查询失败 " + error; })); break; } var wxLiveObjectInfoResult = JsonHelper.DeserializeJsonToObject(getLiveObjectRst); var liveList = wxLiveObjectInfoResult.list; this.lstWXLiveObjectInfo.AddRange(liveList); foreach (var live in liveList) { foreach (var prod in live.productList.list) { Invoke(new Action(() => { if (prod.spuMonthSales.ParseToInt() >= txtSaleCount.Text.Trim().ParseToInt() && !dgvDaRenProd.Rows.Cast().Any(r => r.Cells["colTalentSpuId"].Value.ParseToString() == prod.spuId)) { var startTimeStr = BaseClass.StampToDateTime(live.liveObjectStartTime.ParseToInt()).ToString("yy-MM-dd HH:mm"); var duration = new TimeSpan(live.liveObjectDuringTimeSecond.ParseToLong() * 10000000); var durationStr = duration.Hours + "时" + (Math.Ceiling(duration.TotalMinutes).ParseToInt() - duration.Hours * 60) + "分"; var rowIndex = dgvDaRenProd.Rows.Add( false, shop.ShopId, shop.ShopAccount, "登录", "进店", "直播", talent.talentAppid, finderUser.finderUsername, finderUser.nickname, // 达人昵称 live.objectId, // 达人活动ID live.liveObjectImg, DataGridViewExtension.defaultBitmap, // 直播标题图 live.liveObjectDescription, // 达人活动直播标题 startTimeStr + "\r\n" + durationStr + " " + "观看人数" + live.livediagnosisFinderuinxfeedidWatchUv.ParseToInt(), prod.spuImgUrl, DataGridViewExtension.defaultBitmap, prod.spuAppid, prod.spuShopNickname, prod.spuId, prod.spuName, prod.spuPrice.ParseToInt() * 0.01m, prod.spuMonthSales.ParseToInt(), "联系达人" ); dgvDaRenProd.Rows[rowIndex].Height = 60; } })); } if (live.productList.total > 10) { int prodPage = 1; int prodPageSize = 10; var prodTotalPage = Math.Ceiling(live.productList.total.ParseToInt() * 1m / prodPageSize).ParseToInt(); while (prodPage < prodTotalPage) { if (this.cancellationTokenSource.IsCancellationRequested) break; prodPage++; var getProdRst = WXFinderSquareBLL.GetDaRenLiveProductList(shop, finderUsername, mpAppid, talentAppid, live.objectId, prodPage, prodPageSize); Thread.Sleep(Randomx.GetId(300, 600)); if (!getProdRst.ParseToString().Contains("\"code\":0")) { var error = BaseRegex.GetStringJsonByRegs(ref getProdRst, getProdRst, "errmsg"); if (error.ParseToString().Contains("biz magic invalid")) { shop.LoginStatus = "未登录"; var selectIds = dgvShop.Rows.Cast().Where(r => r.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList(); Invoke(new Action(() => { BindShop(shop, selectIds, "店铺掉线"); })); error = "店铺掉线"; } Invoke(new Action(() => { row.Cells["colOpResult"].Value = "达人带货商品查询失败 " + error; })); break; } var darenProdLst = JsonHelper.DeserializeJsonToList(JsonHelper.JObjectParse(getProdRst)["list"].ParseToString()); live.productList.list.AddRange(darenProdLst); foreach (var prod in darenProdLst) { Invoke(new Action(() => { if (prod.spuMonthSales.ParseToInt() >= txtSaleCount.Text.Trim().ParseToInt() && !dgvDaRenProd.Rows.Cast().Any(r => r.Cells["colTalentSpuId"].Value.ParseToString() == prod.spuId)) { var startTimeStr = BaseClass.StampToDateTime(live.liveObjectStartTime.ParseToInt()).ToString("yy-MM-dd HH:mm"); var duration = new TimeSpan(live.liveObjectDuringTimeSecond.ParseToLong() * 10000000); var durationStr = duration.Hours + "时" + (Math.Ceiling(duration.TotalMinutes).ParseToInt() - duration.Hours * 60) + "分"; var rowIndex = dgvDaRenProd.Rows.Add( false, shop.ShopId, shop.ShopAccount, "登录", "进店", "直播", talent.talentAppid, finderUser.finderUsername, finderUser.nickname, // 达人昵称 live.objectId, // 达人活动ID live.liveObjectImg, DataGridViewExtension.defaultBitmap, // 直播标题图 live.liveObjectDescription, // 达人活动直播标题 startTimeStr + "\r\n" + durationStr + " " + "观看人数" + live.livediagnosisFinderuinxfeedidWatchUv.ParseToInt(), prod.spuImgUrl, DataGridViewExtension.defaultBitmap, prod.spuAppid, prod.spuShopNickname, prod.spuId, prod.spuName, prod.spuPrice.ParseToInt() * 0.01m, prod.spuMonthSales.ParseToInt(), "联系达人" ); dgvDaRenProd.Rows[rowIndex].Height = 60; } })); } } } } var total = wxLiveObjectInfoResult.total.ParseToInt(); var totalPage = Math.Ceiling(total * 1m / pageSize).ParseToInt(); if (page >= totalPage) break; } } } } Invoke(new Action(() => { pictureBox1.Visible = false; this.statusBar.lblTaskStatus.Text += " 达人带货商品查询操作结束"; BaseMsgForm.ShowInfo("达人带货商品查询操作结束"); })); }, cancellationTokenSource.Token); } private void btnStopSearchTalentProd_Click(object sender, EventArgs e) { if (this.cancellationTokenSource != null) this.cancellationTokenSource.Cancel(); } private void dgvDaRenProd_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex < 0 || e.RowIndex < 0) return; string headerText = dgvDaRenProd.Columns[e.ColumnIndex].HeaderText; var shopId = dgvDaRenProd.Rows[e.RowIndex].Cells["colDgvProdShopId"].Value.ParseToString(); var shop = GlobalConfig.ValidShopLoginList.FirstOrDefault(s => s.ShopId == shopId); var talentAppid = dgvDaRenProd.Rows[e.RowIndex].Cells["colDgvProdTalentAppid"].Value.ParseToString(); var talent = this.lstWXFinderTalentInfo.FirstOrDefault(t => t.talentAppid == talentAppid); switch (headerText) { case "删除": break; case "登录": { WXShopLoginForm shopLoginForm = new WXShopLoginForm(shop); 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 "商品图片": { ShowImgForm imgFrom = new ShowImgForm(dgvDaRenProd.Rows[e.RowIndex].Cells["colDgvProdImgUrl"].Value.ParseToString()); imgFrom.ShowDialog(); break; } case "带货题图": { ShowImgForm imgFrom = new ShowImgForm(dgvDaRenProd.Rows[e.RowIndex].Cells["colLiveObjectImgUrl"].Value.ParseToString()); imgFrom.ShowDialog(); break; } case "联系达人": { var finderUser = talent.accountList?.FirstOrDefault(a => !a.finderUsername.IsNullOrEmpty()); if (finderUser != null) { var createChatRst = WXFinderSquareBLL.userCreateChatRoom(shop, finderUser.finderUsername, finderUser.mpAppid, talentAppid); //ShowImgForm imgFrom = new ShowImgForm(dgvDaRenProd.Rows[e.RowIndex].Cells["colLiveObjectImgUrl"].Value.ParseToString()); //imgFrom.ShowDialog(); var room_id = BaseRegex.GetStringJson(ref createChatRst, "room_id"); if (string.IsNullOrEmpty(room_id)) { BaseMsgForm.ShowError("联系窗口打开失败,请重试"); } else { WXShopLoginForm loginForm = new WXShopLoginForm(shop); loginForm.openType = EnumOpenType.manage; loginForm.InitUrl = "https://store.weixin.qq.com/shop/kf/collab/im?mode=business&roomId=" + room_id; loginForm.Show(); } } break; } case "": dgvDaRenProd.Rows[e.RowIndex].Cells["colDgvProdCheck"].Value = !(bool)dgvDaRenProd.Rows[e.RowIndex].Cells["colDgvProdCheck"].Value; break; default: break; } } } public class WXFinderSquareBLL { public static string getSquareTalentList(ShopLoginInfo shop, string bodyJson) { string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/finderSquare/cgi/getSquareTalentList?token=&lang=zh_CN"; string referer = "https://store.weixin.qq.com/shop/findersquare/find"; //@"{""filter"":{""isLiveFinder"":0,""isVideoFinder"":0,""isMpPromoter"":0,""limit"":20,""offset"":20,""topCatId"":[1495,6870],""otherCheckers"":[""hasContact""],""hasContact"":1,""randomSeed"":8275,""sortKey"":0,""sortDirection"":1,""topCatIdList"":[1495,6870]}}"; string body = bodyJson; var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer); return result; } public static string WxFinderSquareGetProdList(ShopLoginInfo shop, int page, string finderUsername, string talentAppid) { string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/finderSquare/cgi/getItemList?token=&lang=zh_CN&offset=" + (page - 1) * 10 + "&pageSize=10&productTitle="; string referer = "https://store.weixin.qq.com/shop/findersquare/initiate-invite?finderUsername=" + finderUsername + "&talentAppid=" + talentAppid + "&from=5"; var result = WXHttpResponseBLL.WeiXinGetResponse(shop, url, referer); return result; } public static string getSaleSortProduct(ShopLoginInfo shop, List spuIdLst, int page = 1) { var spuIdStr = "+" + string.Join("+", spuIdLst); string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeproductcore/cgi/goods/searchProduct" + "?token=&lang=zh_CN&pageSize=50&productStatus[]=-1&productSource=[1,16,32]&searchSource=1&useNew=true&pageNum=" + page + "&status[]=5&spuId=" + spuIdStr + "&sortType=6"; string referer = "https://store.weixin.qq.com/shop/goods/list?currentTab=PRODUCT_STATUS_ON"; var result = WXHttpResponseBLL.WeiXinGetResponse(shop, url, referer); return result; } public static string getListingTimeSortProduct(ShopLoginInfo shop, List spuIdLst, int page = 1) { var spuIdStr = "+" + string.Join("+", spuIdLst); string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeproductcore/cgi/goods/searchProduct" + "?token=&lang=zh_CN&pageSize=50&productStatus[]=-1&productSource=[1,16,32]&searchSource=1&useNew=true&pageNum=" + page + "&status[]=5&spuId=" + spuIdStr + "&sortType=18"; string referer = "https://store.weixin.qq.com/shop/goods/list?currentTab=PRODUCT_STATUS_ON"; var result = WXHttpResponseBLL.WeiXinGetResponse(shop, url, referer); return result; } public static string createPromotionInvitation(ShopLoginInfo shop, List productIdLst, string finderUsername, string talentAppid, string contactName, string contactWxId, string contactPhoneNumber, string invitationIntroduction) { string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/finderSquare/cgi/createPromotionInvitation?token=&lang=zh_CN"; //string referer = "https://store.weixin.qq.com/shop/findersquare/initiate-invite?finderUsername=v2_060000231003b20faec8c6e08811c4d1cc01ee36b077a7e7c19b328d3bad1d0f59b8cd9a6d26@finder&talentAppid=wx6ea8fdc1005228f1&from=5"; string referer = "https://store.weixin.qq.com/shop/findersquare/initiate-invite?finderUsername=" + "&talentAppid=" + "&from=5"; //string body = @"{""finderUsername"":""v2_060000231003b20faec8c6e08811c4d1cc01ee36b077a7e7c19b328d3bad1d0f59b8cd9a6d26@finder"",""talentAppid"":""wx6ea8fdc1005228f1"",""itemList"":{""itemInfo"":[{""spuId"":""10000539273216""},{""spuId"":""10000539258278""}]},""contactInfo"":{""contactName"":""孙xiansheng"",""contactWxId"":""wx2311"",""contactPhoneNumber"":""11111111111"",""invitationIntroduction"":""你好你好"",""inviteScene"":""5""}}"; string body = @"{""finderUsername"":""" + finderUsername + @""",""talentAppid"":""" + talentAppid + @""",""itemList"":{""itemInfo"":["; foreach (var spuId in productIdLst) { body += @"{""spuId"":""" + spuId + @"""},"; } body = body.TrimEnd(','); body += @"]},""contactInfo"":{""contactName"":""" + contactName + @""",""contactWxId"":""" + contactWxId + @""",""contactPhoneNumber"":""" + contactPhoneNumber + @""",""invitationIntroduction"":""" + invitationIntroduction + @""",""inviteScene"":""5""}}"; var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer); return result; } /// /// /// /// /// /// /// /// 直播或短视频带货 1直播 2短视频 /// /// /// public static string GetDaRenLiveFeedList(ShopLoginInfo shop, string finderUsername, string mpAppid, string talentAppid, long startMs, long endMs, int liveOrFeed = 1, int page = 1, int pageSize = 10) { string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/finderSquare/cgi/GetSameIndustryDetailLiveFeedList?token=&lang=zh_CN"; //"https://store.weixin.qq.com/shop/findersquare/finder-detail?from=5&fromTab=all&finderUsername=v2_060000231003b20faec8c7e58110c3d5ca01ee32b077ca155bf8a7fb3c2469d6ba215af008d9@finder&mpAppid=wx0e6b9a6557b6c7a9&talentAppid=wx34b8353cf2e12005"; string referer = "https://store.weixin.qq.com/shop/findersquare/finder-detail?from=5&fromTab=all&finderUsername=" + finderUsername; if (!mpAppid.IsNullOrEmpty()) referer += "&mpAppid=" + mpAppid; referer += "&talentAppid=" + talentAppid; //{"appid":"wx34b8353cf2e12005","liveOrFeed":1,"page":{"limit":10,"offset":0},"startMs":1778342400000,"endMs":1780934399999,"sortControl":null} //{"appid":"wx34b8353cf2e12005","liveOrFeed":1,"page":{"limit":10,"offset":0},"startMs":1778342400000,"endMs":1780934399999,"sortControl":[{"sortColName":"livediagnosis_finderuinxfeedid_watch_uv","sortRule":1}]} //sortRule 1 降序 string body = @"{""appid"":""" + talentAppid + @""",""liveOrFeed"":" + liveOrFeed + @",""page"":{""limit"":" + pageSize + @",""offset"":" + (page - 1) * 10 + @"},""startMs"":" + startMs + @",""endMs"":" + endMs + @",""sortControl"":null}"; var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer); return result; } public static string GetDaRenLiveProductList(ShopLoginInfo shop, string finderUsername, string mpAppid, string talentAppid, string objectId, int page = 1, int pageSize = 10) { string url = "https://store.weixin.qq.com/shop-faas/mmchannelstradeleague/finderSquare/cgi/getLiveProductList?token=&lang=zh_CN"; //"https://store.weixin.qq.com/shop/findersquare/finder-detail?from=5&fromTab=all&finderUsername=v2_060000231003b20faec8c7e58110c3d5ca01ee32b077ca155bf8a7fb3c2469d6ba215af008d9@finder&mpAppid=wx0e6b9a6557b6c7a9&talentAppid=wx34b8353cf2e12005"; string referer = "https://store.weixin.qq.com/shop/findersquare/finder-detail?from=5&fromTab=all&finderUsername=" + finderUsername; if (!mpAppid.IsNullOrEmpty()) referer += "&mpAppid=" + mpAppid; referer += "&talentAppid=" + talentAppid; string body = @"{""appid"":""" + talentAppid + @""",""objectId"":""" + objectId + @""",""limit"":" + pageSize + @",""offset"":" + (page - 1) * 10 + @"}"; var result = WXHttpResponseBLL.WeiXinPostResponse(shop, url, body, referer); return result; } public static string userCreateChatRoom(ShopLoginInfo shop, string finderUsername, string mpAppid, string talentAppid) { string url = "https://store.weixin.qq.com/shop/commkf/user_room?action=user_create_room&token=&lang=zh_CN"; //"https://store.weixin.qq.com/shop/findersquare/finder-detail?from=5&fromTab=all&finderUsername=v2_060000231003b20faec8c7e58110c3d5ca01ee32b077ca155bf8a7fb3c2469d6ba215af008d9@finder&mpAppid=wx0e6b9a6557b6c7a9&talentAppid=wx34b8353cf2e12005"; string referer = "https://store.weixin.qq.com/shop/findersquare/finder-detail?from=1&fromTab=all&finderUsername=" + finderUsername; if (!mpAppid.IsNullOrEmpty()) referer += "&mpAppid=" + mpAppid; referer += "&talentAppid=" + talentAppid; string body = @"{""open_account"":""" + talentAppid + @"""}"; var result = WXHttpResponseBLL.WeiXinTalentOpenKfPostResponse(shop, url, body, referer); return result; } } public class WXAddFinderParam { public string ContactPerson { get; set; } public string WxNumber { get; set; } public string Mobile { get; set; } public string Explain { get; set; } } public class WXProdIdWithListingTime { public string spuId { get; set; } // "10000538960743" public string productName { get; set; } // "点教英语 《高中英语听力精听训练》强化版" public int? listingTime { get; set; } // 1773912220 public int? soldNum { get; set; } } }