Files
KJD/TEMUKJD/VDianForms/VDianUploadProductForm.cs
T

1179 lines
53 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using NaiBa.Util.Extension;
using System.Threading;
using AllBase;
using Work.CollectClass;
using AllBase.Helper;
using CefSharp.WinForms;
using NaiBa.CefHelper;
using CefSharp;
using AllBase.Model.Result;
using AllBase.Model.Param.VDianManage;
using AllBase.Model.Param.ToolsManage;
using Work.Api;
using TemuKJD.BaseForms;
using NaiBa.Util.Helper;
using TemuKJD.BLL.VDian;
using CefSharp.Handler;
using TemuKJD.Extension;
using LittleCow.Model.Param.WeiDianManage;
namespace KJD.VDianForms
{
public partial class VDianUploadProductForm : BaseForm
{
public NaiBa.Util.ConcurrentList<TemuDBProductSelect> lstTemuDBProductSelect = new NaiBa.Util.ConcurrentList<TemuDBProductSelect>();
/// <summary>
/// 微店上货地址(使用getUa(); js方法获取ua算法)
/// </summary>
public static string vDianUploadUrl = "https://d.weidian.com/weidian-pc/pc-vue-item/#/item/edit";
//public static string vDianUploadUrl = "https://d.weidian.com/weidian-pc/pc-vue-item/#/item/listNew";
//public static string vDianUploadUrl = "https://d.weidian.com/weidian-pc/pc-vue-index/index.html";
public static Dictionary<string, string> sShopProductOnSaleCountDic = new Dictionary<string, string>();
public static Dictionary<string, string> sShopProductOffSaleCountDic = new Dictionary<string, string>();
public static Dictionary<string, string> sShopCpsRateDic = new Dictionary<string, string>();
//private WeiDianProductTable weiDianProductTable = new WeiDianProductTable();
//private ProductBLL productBLL = new ProductBLL();
private List<string> lstUpVDianShopId = new List<string>();
decimal addPercent = 30;
decimal addPrice = 10;
int threadCount = 1;
bool isRun = false;
bool isSetCPS = false;
decimal CPSPercent = 10;
/// <summary>
/// 当前正在上货的微店,同一微店同时只能上一件货
/// </summary>
private Dictionary<VDianShopLoginInfo, DateTime> dicCurrentVDian = new Dictionary<VDianShopLoginInfo, DateTime>();
private CheckBox chkSelectAll = null;
List<ChromiumWebBrowser> lstCef = new List<ChromiumWebBrowser>();
List<ChromiumWebBrowser> lstCefUsing = new List<ChromiumWebBrowser>();
int cefId = -1;
int labelClickTimes = 0;
public VDianUploadProductForm()
{
InitializeComponent();
}
#region 窗体事件
private void UploadProductForm_Load(object sender, EventArgs e)
{
GlobalConfig.WeiDianUploadParam = ConfigHelper.LoadConfig<WeiDianSettingParam>("vdian_upload_setting_param");
if (GlobalConfig.WeiDianUploadParam == null)
{
GlobalConfig.WeiDianUploadParam = new WeiDianSettingParam
{
AddPercent = "400",
AddPrice = "0",
IsSetCps = false,
CpsPercent = "10",
ThreadCount = "1",
};
}
// 连续单击6次出现显示网页按钮
Task.Run(() =>
{
while (true)
{
Thread.Sleep(200);
if (labelClickTimes > 0)
{
Thread.Sleep(6000);
labelClickTimes = 0;
}
}
});
LoadThreadCount();
LoadUploadQueue();
RefreshQueueCount();
BtnRefreshShop_Click(null, null);
this.VisibleChanged += UploadProductForm_VisibleChanged;
chkSelectAll = dgvShop.Columns["colIsUpload"].AddHeaderCheckBox(HorizontalAlignment.Right, 0, 0, null, null, false);
chkSelectAll.Width = chkSelectAll.Height = 13;
chkSelectAll.CheckedChanged += chkSelectAll_CheckedChanged;
this.chkCPS.Checked = GlobalConfig.WeiDianUploadParam.IsSetCps;
this.txtCPSRate.Text = GlobalConfig.WeiDianUploadParam.CpsPercent;
this.txtPriceBase.Text = GlobalConfig.WeiDianUploadParam.AddPrice;
this.txtPriceRatio.Text = GlobalConfig.WeiDianUploadParam.AddPercent;
this.cmbThreadCount.SelectedIndexChanged -= cmbThreadCount_SelectedIndexChanged;
try { this.cmbThreadCount.SelectedValue = Convert.ToInt32(GlobalConfig.WeiDianUploadParam.ThreadCount); } catch { }
this.cmbThreadCount.SelectedIndexChanged += cmbThreadCount_SelectedIndexChanged;
}
private void UploadProductForm_VisibleChanged(object sender, EventArgs e)
{
if (Visible == true)
RefreshShop();
}
private void BtnImport_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "请选择需要导入的商品";
ofd.Filter = "文本文件|*.txt";
if (DialogResult.OK == ofd.ShowDialog())
{
this.btnImport.Enabled = false;
this.btnUpload.Enabled = false;
this.btnClear.Enabled = false;
Task.Run(new Action(() =>
{
try
{
//List<ProductInfo> importList = new List<ProductInfo>();
//List<IdValueTypeEntity> dbList = new List<IdValueTypeEntity>();
//List<ProductInfo> uploadQueueList = DataManageBLL.WeiDianUploadQueueList.Clone();
//string file = ofd.FileName;
//string source = File.ReadAllText(file, Encoding.Default);
//string[] sourceArr = source.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToArray();
//for (int i = 0; i < sourceArr.Length; i++)
//{
// string[] lineArr = sourceArr[i].Split(new string[] { "-----" }, StringSplitOptions.RemoveEmptyEntries);
// ProductInfo product = null;
// if (lineArr.Length > 0)
// {
// product = new ProductInfo();
// productBLL.GetProductInfoByUrl(product, lineArr);
// }
// if (product.ProductId <= 0)
// {
// product = new ProductInfo();
// var text = sourceArr[i];
// var pStr = BaseRegex.GetMatchRegexString(text, "id=(\\d{5,18})");
// if (!text.Contains(',') && string.IsNullOrEmpty(pStr) && !text.Contains("detail.1688.com/offer/"))
// text = BaseEncrypt.EncryptDecode(text);
// // 通用格式 "来源", "商品ID", "商品标题",...
// if (text != null && text.Contains(','))
// {
// var productArr = text.Split(',');
// if (productArr.Length >= 6)
// {
// string From = productArr[0].Trim('"');
// string ProductId = productArr[1].Trim('"');
// string ProductTitle = productArr[2].Trim('"');
// string RealProductId = productArr[1].Trim('"');
// string CatId = productArr[5].Trim('"');
// if (From == "淘宝" || From == "天猫")
// {
// product.Platform = (int)ShopPlatform.TaoBao;
// }
// else if (From == "拼多多" || From == "搜款网")
// {
// product.Platform = (int)ShopPlatform.PinDuoDuo;
// }
// else if (From == "1688" || From == "阿里巴巴")
// {
// product.Platform = (int)ShopPlatform.Alibaba;
// }
// if (From == "搜款网")
// {
// var idStr = ProductId.ToString();
// if (idStr.Length >= 2)
// {
// var idStrNew = idStr[idStr.Length - 1] + idStr.Substring(1, idStr.Length - 2) + idStr[0];
// RealProductId = idStrNew;
// }
// }
// product.ProductId = RealProductId.ParseToLong();
// product.FissionProductName = ProductTitle;
// }
// }
// }
// if (product != null && product.ProductId > 0)
// {
// if (!importList.Where(p => p.ProductId == product.ProductId && p.Platform == product.Platform && p.FissionProductName == product.FissionProductName).Any())
// {
// if (!uploadQueueList.Where(p => p.ProductId == product.ProductId && p.Platform == product.Platform && p.FissionProductName == product.FissionProductName).Any())
// {
// if (i % 30 == 0)
// {
// RefreshQueueCount(importList.Count);
// }
// importList.Add(product);
// dbList.Add(new IdValueTypeEntity
// {
// Id = product.ProductId,
// Type = product.Platform,
// Value = JsonConvert.SerializeObject(product)
// });
// }
// }
// }
// if (importList.Count > 100)
// {
// SaveBatch(dbList, importList);
// }
//}
//SaveBatch(dbList, importList);
//RefreshQueueCount();
}
catch (Exception ex)
{
LogHelper.WriteWithTime(ex);
}
this.BeginInvoke(new Action(() =>
{
this.btnImport.Enabled = true;
this.btnUpload.Enabled = true;
this.btnClear.Enabled = true;
}));
}));
}
}
private void BtnUpload_Click(object sender, EventArgs e)
{
if (lstTemuDBProductSelect.Count == 0)
{
BaseMsgForm.ShowError("上传队列不能为空");
return;
}
if (lstUpVDianShopId.Count == 0)
{
BaseMsgForm.ShowInfo("请选择要上货店铺");
return;
}
try
{
addPercent = Convert.ToDecimal(txtPriceRatio.Text);
addPrice = Convert.ToDecimal(txtPriceBase.Text);
threadCount = this.cmbThreadCount.SelectedValue.ParseToInt();
isSetCPS = chkCPS.Checked;
CPSPercent = Convert.ToDecimal(txtCPSRate.Text);
this.dgvProduct.Columns["colCPSResult"].Visible = isSetCPS;
GlobalConfig.WeiDianUploadParam.CpsPercent = CPSPercent.ToString();
GlobalConfig.WeiDianUploadParam.IsSetCps = isSetCPS;
GlobalConfig.WeiDianUploadParam.AddPercent = addPercent.ToString();
GlobalConfig.WeiDianUploadParam.AddPrice = addPrice.ToString();
GlobalConfig.WeiDianUploadParam.ThreadCount = threadCount.ToString();
ConfigHelper.SaveConfig("vdian_upload_setting_param", GlobalConfig.WeiDianUploadParam);
}
catch
{
BaseMsgForm.ShowInfo("请输入正确的加价数据或推广金比例");
return;
}
this.btnUpload.Enabled = false;
int i = 0;
int total = lstTemuDBProductSelect.Count;
this.isRun = true;
Task.Run(() =>
{
List<Thread> threadList = new List<Thread>();
while (lstTemuDBProductSelect.Count > 0)
{
// 中断操作
if (!isRun)
break;
i++;
this.Invoke(new Action(() =>
{
this.statusBarUpload.lblTaskStatus.Text = "正在上货...";
this.statusBarUpload.pgbTaskProgress.Value = i;
this.statusBarUpload.pgbTaskProgress.Text = i + "/" + total;
this.statusBarUpload.pgbTaskProgress.Maximum = total;
}));
var pInfo = lstTemuDBProductSelect[0];
lstTemuDBProductSelect.Remove(pInfo);
//weiDianProductTable.Remove(new IdValueTypeEntity { Id = pInfo.ProductId, Type = pInfo.Platform });
Thread thread = new Thread(obj =>
{
try
{
var prodInfo = obj as KJDDBProduct;
var prod = new ProductMappingImportParam()
{
From = "",
ProductId = prodInfo.spu_id.ToString(),
RealProductId = prodInfo.spu_id.ToString(),
ProductTitle = prodInfo.product_name
};
ProductCollectBase product = null;
//if (prodInfo.Platform == (int)ShopPlatform.TaoBao)
//{
// prod.From = "淘宝";
// product = GetTaobaoProduct(prod);
//}
//else if (prodInfo.Platform == (int)ShopPlatform.PinDuoDuo)
//{
// prod.From = "拼多多";
// product = GetPinDuoDuoProduct(prod);
//}
//else if (prodInfo.Platform == (int)ShopPlatform.Alibaba)
//{
// prod.From = "阿里巴巴";
// product = GetAlibabaProduct(prod);
//}
VDianParam.VDianProductBase vDianProduct = null;
if (product != null && !string.IsNullOrEmpty(product.content) && (!string.IsNullOrEmpty(product.image) || product.Images.Count > 0))
{
// 确定待转换商品图片
prod.Image = !string.IsNullOrEmpty(product.image) ? product.image : product.Images[0];
if (prod.Image.StartsWith("https:"))
prod.Image = prod.Image.Substring(6);
else if (prod.Image.StartsWith("http:"))
prod.Image = prod.Image.Substring(5);
// 确定待转换商品标题
if (string.IsNullOrEmpty(prod.ProductTitle))
prod.ProductTitle = product.name;
var pre = txtPrefix.Text.Trim();
if (!string.IsNullOrEmpty(pre))
{
var leg = pre.Length;
if (prod.ProductTitle.Length > 60 - leg)
{
prod.ProductTitle = prod.ProductTitle.Substring(prod.ProductTitle.Length - (60 - leg));
}
prod.ProductTitle = pre + prod.ProductTitle;
}
// 新接口
//vDianProduct = UpLoadProductUseMutliApi(prod, product);
// 开箱小店和威武宝宝接口
vDianProduct = UpLoadProductUseApi(prod, product);
if (vDianProduct == null)
{
Thread.Sleep(5000);
//vDianProduct = UpLoadProductUseApi(prod, product);
prod.MappingResult = "";
vDianProduct = UploadProductSim(prod, product);
}
if (!string.IsNullOrEmpty(prod.MappingResult))
{
prod.MappingResult = prod.MappingResult.Replace("转换失败", "上货失败");
}
}
else
{
if (string.IsNullOrEmpty(prod.MappingResult))
{
if (string.IsNullOrEmpty(product.image) && (product.Images == null || product.Images.Count == 0))
{
prod.MappingResult = "上货失败,未找到商品主图或详情图";
}
else if (string.IsNullOrEmpty(product.content) && !string.IsNullOrEmpty(product.name))
{
prod.MappingResult = "上货失败,未找到上家商品详情";
}
else if (string.IsNullOrEmpty(prod.MappingResult))
{
if (prod.From == "拼多多" || prod.From == "搜款网")
prod.MappingResult = "上货失败,可能不满足上货条件或拼多多Token失效";
else
prod.MappingResult = "上货失败,可能不满足上货条件";
}
}
prod.MappingResult = prod.MappingResult.Replace("转换失败", "上货失败");
}
Invoke(new Action(() =>
{
dgvProduct.Rows.Add(product?.upShopId, prodInfo?.product_get_type_text, product?.from_id, product?.from_title, product?.price, product?.saleCount
, vDianProduct?.itemId, vDianProduct?.itemName, prod?.MappingResult, prod?.CPSResult, vDianProduct?.shopName, "删除");
}));
}
catch (Exception ex)
{
}
finally
{
RefreshQueueCount();
}
});
Thread.Sleep(1500 + Randomx.GetId(1000));
Threadx.ThreadListWait(ref threadList, thread, threadCount, pInfo);
}
Threadx.ThreadListWait(ref threadList);
Invoke(new Action(() =>
{
btnUpload.Enabled = true;
if (isRun)
{
this.statusBarUpload.lblTaskStatus.Text = "上货完毕";
BaseMsgForm.ShowInfo("上货完成!");
}
else
{
this.statusBarUpload.lblTaskStatus.Text = "上货中断";
BaseMsgForm.ShowInfo("上货中断!");
}
isRun = false;
}));
});
}
private ProductCollectBase GetTaobaoProduct(ProductMappingImportParam prod)
{
ProductCollectBase proInfo = new ProductCollectBase
{
from_url = "https://item.taobao.com/item.htm?id=" + prod.RealProductId,
from_id = Convert.ToInt64(prod.RealProductId),
};
TaobaoMobileCollect goodsFromTaobaoInfo = new TaobaoMobileCollect(proInfo);
goodsFromTaobaoInfo.Get();
var product = goodsFromTaobaoInfo.Product;
if (goodsFromTaobaoInfo.IsDown)
prod.MappingResult = "转换失败,可能是商品已下架或商品不存在";
return product;
}
private ProductCollectBase GetPinDuoDuoProduct(ProductMappingImportParam prod)
{
TaobaoProductBase tp = new TaobaoProductBase();
tp.GoodsId = tp.FromId = Convert.ToInt64(prod.RealProductId);
tp.FromType = "拼多多";
PinduoduoProductCollect pinduoduoProductCollect = new PinduoduoProductCollect(Name, tp);
PinduoduoProductCollect.TempIds.Clear();
//PinduoduoProductCollect.ConPddTokenList = GlobalConfig.PinDuoDuoTokenList;
pinduoduoProductCollect.Get();
var product = pinduoduoProductCollect.pb;
// 如果无法获取拼多多商品信息了,提示重连
//if (pinduoduoProductCollect.IsNeedLogin)
prod.MappingResult = "转换失败,需要登录拼多多或登录Token!";
if (pinduoduoProductCollect.IsOnSale == false)
prod.MappingResult = "转换失败,可能是商品下架或商品不存在";
if (pinduoduoProductCollect.IsPresale == true)
prod.MappingResult = "转换失败,预售商品不能上货";
//if (pinduoduoProductCollect.IsResultError)
prod.MappingResult = "转换失败,可能是商品不存在或服务器出错";
return product;
}
private ProductCollectBase GetAlibabaProduct(ProductMappingImportParam prod)
{
ProductCollectBase proInfo = new ProductCollectBase
{
from_url = "https://detail.1688.com/offer/" + prod.RealProductId + ".html",
from_id = Convert.ToInt64(prod.RealProductId),
};
AlibabaProductGet goodsFrom1688Info = new AlibabaProductGet(proInfo);
goodsFrom1688Info.Get();
var product = goodsFrom1688Info.Product;
return product;
}
/// <summary>
/// 服务端获取的随机Api接口上传
/// </summary>
/// <param name="prod"></param>
/// <param name="product"></param>
/// <returns></returns>
private VDianParam.VDianProductBase UpLoadProductUseMutliApi(ProductMappingImportParam prod, ProductCollectBase product)
{
VDianParam.VDianProductBase vDianProduct = null;
var UpShopList = GlobalConfig.VDianShopLoginList.Where(s => lstUpVDianShopId.Contains(s.ShopId)).ToList();
#region 随机api接口 暂时注释
//if (UpShopList.Count > 0 && vDianProduct == null)
//{
// prod.MappingResult = null;
// var simUpShops = GlobalConfig.VDianShopLoginList.Where(v => v.UpGoodAuth == "认证成功").ToList();
// while (simUpShops.Count == 0)
// {
// Thread.Sleep(500);
// simUpShops = GlobalConfig.VDianShopLoginList.Where(v => v.UpGoodAuth == "认证成功").ToList();
// }
// var simVdianShop = simUpShops[Randomx.GetId(simUpShops.Count)];
// var canUpList = UpShopList.Where(v => !dicCurrentVDian.Keys.Contains(v)).ToList();
// while (canUpList.Count == 0)
// {
// Thread.Sleep(500);
// canUpList = UpShopList.Where(v => !dicCurrentVDian.Keys.Contains(v)).ToList();
// }
// var vDianShops = canUpList.Where(s => s.MainAuth == "认证成功").ToList();
// VDianShopLoginInfo vDianShop = null;
// if (vDianShops.Count > 0)
// {
// var id = Randomx.GetId(vDianShops.Count);
// vDianShop = vDianShops[id];
// }
// else
// {
// var id = Randomx.GetId(canUpList.Count);
// vDianShop = canUpList[id];
// }
// while (dicCurrentVDian.Keys.Contains(vDianShop))
// {
// Thread.Sleep(500);
// }
// dicCurrentVDian.Add(vDianShop, DateTime.Now);
// int retryApiTime = 0;
//retryApi:
// try
// {
// ProductMappingForm.GetMultiApiAccesstoken(vDianShop, this);
// if (//vDianShop.MultiAttrApiToken?.AppKey?.PropCountStatus == "ok"
// //&& vDianShop.MultiImgApiToken?.AppKey?.ImgsCountStatus == "ok"
// //&&
// vDianShop.MultiProductApiToken?.AppKey?.GoodsCountStatus == "ok")
// vDianProduct = new MappingVDianMultiApiBLL().ConvertProductToVDian(prod, product, vDianShop, this.addPercent, this.addPrice, true, simVdianShop);
// else
// {
// prod.MappingResult = "转换失败,error,未找到合适的转换接口";
// }
// ProductMappingForm.UpdateMultiApi(vDianShop);
// }
// catch (Exception ex)
// {
// }
// if (prod.MappingResult != null && prod.MappingResult.Contains("无效或已过期") && prod.MappingResult.Contains("access_token:"))
// {
// if (retryApiTime == 0)
// {
// prod.MappingResult = null;
// retryApiTime++;
// goto retryApi;
// }
// }
// if (prod.MappingResult != null && prod.MappingResult.Contains("长时间未登录"))
// {
// prod.MappingResult = prod.MappingResult.Insert(prod.MappingResult.IndexOf("长时间未登录"), vDianShop.ShopName);
// }
// Thread.Sleep(2000 + Randomx.GetId(2000));
// dicCurrentVDian.Remove(vDianShop);
//}
return vDianProduct;
#endregion
}
#region 微店模拟接口
private VDianParam.VDianProductBase UploadProductSim(ProductMappingImportParam prod, ProductCollectBase product)
{
VDianParam.VDianProductBase vDianProduct = null;
var UpShopList = GlobalConfig.VDianShopLoginList.Where(s => lstUpVDianShopId.Contains(s.ShopId) && s.UpGoodAuth == "认证成功").ToList();
if (UpShopList.Count > 0 && vDianProduct == null)
{
var canUpList = UpShopList.Where(v => !dicCurrentVDian.Keys.Contains(v)).ToList();
while (canUpList.Count == 0)
{
Thread.Sleep(500);
canUpList = UpShopList.Where(v => !dicCurrentVDian.Keys.Contains(v)).ToList();
}
var vDianShop = canUpList[Randomx.GetId(canUpList.Count)];
while (dicCurrentVDian.Keys.Contains(vDianShop))
{
Thread.Sleep(500);
}
dicCurrentVDian.Add(vDianShop, DateTime.Now);
if (vDianProduct == null &&
(string.IsNullOrEmpty(prod.MappingResult) || prod.MappingResult.Contains("系统错误") || prod.MappingResult.Contains("频次超过上限")
|| prod.MappingResult.Contains("未找到合适的转换接口")))
{
Thread.Sleep(Randomx.GetId(2000, 4000));
vDianProduct = new VDianUpProdMappingBLL().ProductToVDianBySim(prod, product, vDianShop, this.addPercent, this.addPrice, GetVDianUa);
}
if (prod.MappingResult != null && prod.MappingResult.Contains("现在人太多了, 请稍后重试"))
{
prod.MappingResult = "调用太多了, 请稍后重试";
for (int i = 0; i < 25; i++)
{
if (!isRun)
break;
Thread.Sleep(1000);
}
}
Thread.Sleep(Randomx.GetId(2500, 4000));
if (vDianProduct != null)
{
prod.MappingResult = "店铺" + vDianShop.ShopName + "上货成功";
// 设置分成推广金
if (isSetCPS)
{
SetCps(prod, vDianShop, vDianProduct);
}
}
Thread.Sleep(Randomx.GetId(1500, 2500));
dicCurrentVDian.Remove(vDianShop);
}
return vDianProduct;
}
public string GetVDianUa(VDianShopLoginInfo vDianShop)
{
while (lstCef.Count < 3)
{
var browser = CEFBrowser.CreateChromiumWebBrowser("about:blank", false);
browser.KeyboardHandler = new KeyboardHandler();
Invoke(new Action(() =>
{
this.panel1.Controls.Add(browser);
}));
lstCef.Add(browser);
}
var notUseCefList = lstCef.Where(c => !lstCefUsing.Contains(c)).ToList();
while (notUseCefList.Count == 0)
{
Thread.Sleep(Randomx.GetId(250, 750));
notUseCefList = lstCef.Where(c => !lstCefUsing.Contains(c)).ToList();
}
var cefWebBrowser = notUseCefList[Randomx.GetId(notUseCefList.Count)];
while (lstCefUsing.Contains(cefWebBrowser))
{
Thread.Sleep(Randomx.GetId(250, 750));
}
lstCefUsing.Add(cefWebBrowser);
var vDianUa = "";
// 登录cef店铺为模拟上传计算ua值
var cookieManager = cefWebBrowser.RequestContext.GetCookieManager(null);
if (vDianShop != null)
{
var task = CEFBrowser.SetCookieAsync("weidian.com", vDianShop.Cookies, cookieManager);
task.Wait(2000);
Thread.Sleep(500);
}
cefWebBrowser.Load(vDianUploadUrl);
Thread.Sleep(Randomx.GetId(6000, 8000));
var t = cefWebBrowser.GetMainFrame().GetSourceAsync();
t.Wait(5000);
if (t.Result.Contains("进入微店"))
{
// 模拟登录
//ProductMappingVDianLoginForm.InputUserNameAndPassword(cefWebBrowser, vDianShop.Phone, vDianShop.Password);
//ProductMappingVDianLoginForm.ClickLogin(cefWebBrowser);
//ProductMappingVDianLoginForm.SelectShop(cefWebBrowser);
vDianShop.LoginStatus = 2;
Thread.Sleep(2000);
return "店铺掉线";
}
var response = cefWebBrowser.GetBrowser().MainFrame.EvaluateScriptAsync("getUa();");
response.Wait(2000);
Thread.Sleep(500 + Randomx.GetId(1000));
vDianUa = response.Result?.Result?.ToString();
if (vDianUa == null)
vDianUa = "";
lstCefUsing.Remove(cefWebBrowser);
return vDianUa;
}
#endregion
// api上货暂时注释
private VDianParam.VDianProductBase UpLoadProductUseApi(ProductMappingImportParam prod, ProductCollectBase product)
{
VDianParam.VDianProductBase vDianProduct = null;
//var UpShopList = GlobalConfig.VDianShopLoginList.Where(s => lstUpVDianShopId.Contains(s.ShopId));
//var canUpList = UpShopList.Where(v => !dicCurrentVDian.Keys.Contains(v)).ToList();
//while (canUpList.Count == 0)
//{
// Thread.Sleep(500);
// canUpList = UpShopList.Where(v => !dicCurrentVDian.Keys.Contains(v)).ToList();
//}
//var id = Randomx.GetId(canUpList.Count);
//var vDianShop = canUpList[id];
//// 实时更新微店token的状态
//foreach (var token in vDianShop.LstWdApiToken)
//{
// var newKey = ProductMappingVDianLoginForm.lstVDianAppKey.FirstOrDefault(k => k.AppKey == token.AppKey.AppKey);
// if (newKey != null)
// {
// if (newKey.GoodsCountStatus == "error" && newKey.ImgsCountStatus == "error" && newKey.PropCountStatus == "error")
// newKey.Status = "error";
// token.AppKey = newKey;
// }
//}
//dicCurrentVDian[vDianShop] = DateTime.Now;
//try
//{
// int retryApiTime = 0;
//retryApi:
// vDianProduct = new MappingVDianApiBLL().ConvertProductToVDian(prod, product, vDianShop, addPercent, addPrice, false, vDianShop);
// if (vDianProduct == null && prod.MappingResult != null && !prod.MappingResult.Contains("上限"))
// vDianProduct = new MappingVDianApiBLL().ConvertProductToVDian(prod, product, vDianShop, addPercent, addPrice, false, vDianShop);
// if (vDianProduct != null)
// {
// if (vDianProduct != null && !string.IsNullOrEmpty(vDianProduct.itemId))
// {
// prod.MappingResourceType = "Api";
// // 0上货缓存 1标题缓存 2标题搜索 3接口上货 4接口上货失败 5模拟上货 6微店群控接口上货
// MappingVDianApiBLL.UpDateMappingResultToStatistics("6");
// }
// prod.MappingResult = "店铺" + vDianShop.ShopName + "上货成功";
// // 设置分成推广金
// if (isSetCPS)
// {
// SetCps(prod, vDianShop, vDianProduct);
// }
// }
// if (prod.MappingResult != null && prod.MappingResult.Contains("无效或已过期") && prod.MappingResult.Contains("access_token:"))
// {
// prod.MappingResult = null;
// // 刷新已过期的token
// foreach (var token in vDianShop.LstWdApiToken)
// {
// var sVDianTokenApiUrl = ProductMappingVDianLoginForm.VDianUrl + "?" + BaseClass.ObjUrl + "weidian_token";
// var data = UserLogin.GetSignaturex() + "&act=reflesh_token&shop_id=" + vDianShop.ShopId + "&appkey=" + token.AppKey.AppKey;
// var refreshResult = GetHtml.PostUtf8(sVDianTokenApiUrl, data);
// if (refreshResult.StartsWith("ok,") && refreshResult.Length > 3)
// {
// token.ApiAccessToken = refreshResult.Substring(3);
// token.ApiAuth = "已授权";
// StartUp.SaveVDianShopLogin();
// }
// else
// {
// token.ApiAuth = "已过期";
// StartUp.SaveVDianShopLogin();
// }
// }
// if (!vDianShop.LstWdApiToken.All(t => t.ApiAuth == "已授权"))
// {
// prod.MappingResult = "店铺" + vDianShop.ShopName + "需要重新授权";
// vDianShop.ApiAuth = "未授权";
// }
// else if (retryApiTime == 0)
// {
// retryApiTime++;
// goto retryApi;
// }
// }
// if (prod.MappingResult != null && prod.MappingResult.Contains("长时间未登录"))
// {
// prod.MappingResult = prod.MappingResult.Insert(prod.MappingResult.IndexOf("长时间未登录"), vDianShop.ShopName);
// }
// Thread.Sleep(500 + Randomx.GetId(1000));
//}
//catch (Exception ex)
//{
//}
//dicCurrentVDian.Remove(vDianShop);
return vDianProduct;
}
private void SetCps(ProductMappingImportParam prod, VDianShopLoginInfo vDianShop, VDianParam.VDianProductBase vDianProduct)
{
//var CPSResultCode = new WeiDianProductBLL().UpdateCps(vDianProduct.itemId, vDianShop, this.CPSPercent.ToString());
//if (CPSResultCode.Contains("\"code\":0"))
// prod.CPSResult = "推广金设置成功";
//else if (CPSResultCode.Contains("供应商不存在"))
//{
// prod.CPSResult = "店铺未开通分成推广功能";
// //vDianShop.IsCPSable = "未开通";
//}
//else if (CPSResultCode.Contains("LOGIN ERROR"))
//{
// prod.CPSResult = "店铺未网页登录";
// //vDianShop.IsCPSable = "未登录";
//}
//else
//{
// var failMessage = AllBase.BaseRegex.GetStringJson(ref CPSResultCode, "message");
// if (string.IsNullOrEmpty(failMessage))
// failMessage = CPSResultCode;
// if (string.IsNullOrEmpty(failMessage))
// failMessage = "推广金设置失败";
// prod.CPSResult = failMessage;
// //vDianShop.IsCPSable = "发生错误";
//}
//prod.CPSResult = prod.CPSResult.Replace("CPS", "分成推广");
}
private void BtnClear_Click(object sender, EventArgs e)
{
ClearGood();
}
private void ClearGood()
{
if (BaseMsgForm.ShowConfirm("是否清理备用产品").DialogResult == DialogResult.OK)
{
//DataManageBLL.WeiDianUploadQueueList.Clear();
//weiDianProductTable.RemoveAll();
//RefreshQueueCount();
lstTemuDBProductSelect.Clear();
ConfigHelper.SaveConfig("vdian_db_prod_upload_list", this.lstTemuDBProductSelect);
}
}
private void BtnRefreshShop_Click(object sender, EventArgs e)
{
RefreshShop();
}
private void RefreshShop()
{
// 更新选中的上货店铺Id
lstUpVDianShopId = lstUpVDianShopId.Where(id => GlobalConfig.VDianShopLoginList.Any(s => s.ShopId == id && s.ApiAuth == "已授权")).ToList();
// 获取被删除的店铺
List<DataGridViewRow> dgvRowList = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> !GlobalConfig.VDianShopLoginList.Any(s => s.ShopId == row.Cells["colShopId"]?.Value?.ToString())).ToList();
// 更新被删除的店铺列表
foreach (var row in dgvRowList)
{
dgvShop.Rows.Remove(row);
}
// 绑定其他店铺(含新导入的店铺)
foreach (VDianShopLoginInfo shopEntity in GlobalConfig.VDianShopLoginList)
{
BindShop(shopEntity);
}
}
private void BindShop(VDianShopLoginInfo shopEntity)
{
var row = dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(p => p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == shopEntity.ShopId);
if (row == null)
{
this.dgvShop.Rows.Add(0, shopEntity.ShopId, shopEntity.ShopName,
VDianUploadProductForm.sShopProductOnSaleCountDic.Keys.Contains(shopEntity.ShopId) ? VDianUploadProductForm.sShopProductOnSaleCountDic[shopEntity.ShopId] : "",
shopEntity.ApiAuth == "已授权" ? true : false, false, string.Empty);
}
else
{
row.Cells["colIsAuthorize"].Value = shopEntity.ApiAuth == "已授权" ? true : false;
row.Cells["colShopName"].Value = shopEntity.ShopName;
row.Cells["colIsUpload"].Value = lstUpVDianShopId.Contains(shopEntity.ShopId);
row.Cells["colProductCount"].Value =
VDianUploadProductForm.sShopProductOnSaleCountDic.Keys.Contains(shopEntity.ShopId) ? VDianUploadProductForm.sShopProductOnSaleCountDic[shopEntity.ShopId] : "";
}
}
private void DgvShop_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvShop.Columns[e.ColumnIndex].HeaderText;
long shopId = dgvShop.Rows[e.RowIndex].Cells["colShopId"].Value.ParseToLong();
switch (headerText)
{
case "店铺名称":
FileHelper.OpenUrl(string.Format("https://weidian.com/?userid=", shopId));
break;
case "上货":
if (dgvShop.Rows[e.RowIndex].Cells["colIsAuthorize"].Value.ParseToBool())
{
dgvShop.Rows[e.RowIndex].Cells["colIsUpload"].Value = !dgvShop.Rows[e.RowIndex].Cells["colIsUpload"].Value.ParseToBool();
if (dgvShop.Rows[e.RowIndex].Cells["colIsUpload"].Value.ParseToBool())
lstUpVDianShopId.Add(shopId.ToString());
else
lstUpVDianShopId.Remove(shopId.ToString());
}
else
{
BaseMsgForm.ShowInfo("店铺未授权");
}
break;
}
}
#endregion
#region 私有方法
private void LoadThreadCount()
{
Dictionary<int, int> dict = new Dictionary<int, int>();
dict.Add(1, 1);
dict.Add(2, 2);
dict.Add(3, 3);
dict.Add(5, 5);
dict.Add(8, 8);
dict.Add(10, 10);
dict.Add(15, 15);
//dict.Add(20, 20);
//dict.Add(30, 30);
//dict.Add(50, 50);
this.cmbThreadCount.DataSource = new BindingSource(dict, null);
this.cmbThreadCount.DisplayMember = "Value";
this.cmbThreadCount.ValueMember = "Key";
}
public void RefreshQueueCount(int addCount = 0)
{
this.Invoke(new Action(() =>
{
this.lblQueueCount.Text = (addCount + lstTemuDBProductSelect.Count).ParseToString() + " 个";
}));
}
private void LoadUploadQueue()
{
//Task.Run(new Action(() =>
//{
// List<IdValueTypeEntity> productQueueList = new WeiDianProductTable().GetList();
// for (int i = 0; i < productQueueList.Count; i++)
// {
// ProductInfo productInfoEntity = JsonConvert.DeserializeObject<ProductInfo>(productQueueList[i].Value);
// DataManageBLL.WeiDianUploadQueueList.Add(productInfoEntity);
// if (i % 5000 == 0)
// {
// RefreshQueueCount();
// }
// }
// RefreshQueueCount();
//}));
}
//private void SaveBatch(List<IdValueTypeEntity> dbList, List<ProductInfo> importList)
//{
// weiDianProductTable.Save(dbList);
// DataManageBLL.WeiDianUploadQueueList.AddRange(importList);
// dbList.Clear();
// importList.Clear();
//}
#endregion
private void cmbThreadCount_SelectedIndexChanged(object sender, EventArgs e)
{
threadCount = this.cmbThreadCount.SelectedValue.ParseToInt();
if (threadCount > 0)
{
GlobalConfig.WeiDianUploadParam.ThreadCount = threadCount.ToString();
//StartUp.SaveWeiDianUploadSettingParam();
ConfigHelper.SaveConfig("vdian_upload_setting_param", GlobalConfig.WeiDianUploadParam);
}
}
private void dgvProduct_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvProduct.Columns[e.ColumnIndex].HeaderText;
switch (headerText)
{
case "上家Id":
case "上家标题":
int platform = dgvProduct.Rows[e.RowIndex].Cells["colProductPlatform"].Value.ParseToInt();
long productId = dgvProduct.Rows[e.RowIndex].Cells["colProductId"].Value.ParseToLong();
switch (platform)
{
case (int)ShopPlatform.TaoBao:
//FileHelper.OpenUrl(string.Format(TaoBaoHelper.TaoBaoProductUrl, productId));
break;
case (int)ShopPlatform.PinDuoDuo:
//FileHelper.OpenUrl(string.Format(PinDuoDuoHelper.PinDuoDuoProductUrl, productId));
break;
case (int)ShopPlatform.Alibaba:
//FileHelper.OpenUrl(string.Format(AlibabaHelper.AlibabaProductUrl, productId));
break;
}
break;
case "微店标题":
long vDianProductId = dgvProduct.Rows[e.RowIndex].Cells["colWeiDianProductId"].Value.ParseToLong();
FileHelper.OpenUrl(string.Format("https://weidian.com/item.html?itemID={0}", vDianProductId));
break;
case "操作":
dgvProduct.Rows.RemoveAt(e.RowIndex);
break;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
isRun = false;
}
private void btnClearUpload_Click(object sender, EventArgs e)
{
ClearUpload();
}
void ClearUpload()
{
dgvProduct.Rows.Clear();
}
private void btnGetProductCount_Click(object sender, EventArgs e)
{
GetShopProductCount();
}
void GetShopProductCount()
{
if (lstUpVDianShopId.Count == 0)
{
BaseMsgForm.ShowInfo("请选择要查询的店铺");
return;
}
this.btnGetProductCount.Enabled = false;
foreach (DataGridViewRow row in dgvShop.Rows)
{
row.Cells["colStatus"].Value = "";
}
Task.Run(() =>
{
var shopList = GlobalConfig.VDianShopLoginList.Where(s => s.ApiAuth == "已授权").ToList();
foreach (var vShop in shopList)
{
DataGridViewRow row = null;
Invoke(new Action(() =>
{
row = this.dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colShopId"].Value.ToString() == vShop.ShopId);
if (row != null)
row.Cells["colStatus"].Value = "正在获取店铺商品数量";
}));
// 获取商品总数目
int totalNum = -1;
int page = 1;
string resultText = "";
var result = new WeiDianProductBLL().GetShopProductIds(vShop, page);
Thread.Sleep(1500);
if (!result.Contains("\"status_code\":0"))
result = new WeiDianProductBLL().GetShopProductIds(vShop, page);
if (result.Contains("\"status_code\":0"))
{
totalNum = AllBase.BaseRegex.GetIntJson(ref result, "total_num");
VDianUploadProductForm.sShopProductOnSaleCountDic[vShop.ShopId] = totalNum.ToString();
resultText = "商品数量获取成功";
}
else
{
if (result.Contains("频次超过上限")) // {"status":{"status_code":10005,"status_reason":"用户请求频次超过上限"}}
resultText = "商品数量获取失败,商品获取频次超过上限";
else
{
resultText = BaseRegex.GetMatchRegexString(result, "\"status_reason\":\"([\\s\\S]*?)\"");
if (string.IsNullOrEmpty(resultText))
resultText = result;
resultText = "商品数量获取失败," + resultText;
}
}
Invoke(new Action(() =>
{
if (row != null)
{
row.Cells["colProductCount"].Value = totalNum == -1 ? "" : totalNum.ToString();
row.Cells["colStatus"].Value = resultText;
}
}));
}
Invoke(new Action(() =>
{
btnGetProductCount.Enabled = true;
BaseMsgForm.ShowInfo("商品数量获取完成");
}));
});
}
private void linklblOpen_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
////FileHelper.OpenUrl("https://d.weidian.com/weidian-pc/pc-vue-fx/DistributionConfig.html");
//CPSIntoForm cf = new CPSIntoForm();
//cf.ShowDialog();
}
private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
if (!chkSelectAll.Checked)
{
lstUpVDianShopId.Clear();
foreach (DataGridViewRow row in dgvShop.Rows)
{
row.Cells["colIsUpload"].Value = false;
}
}
else
{
lstUpVDianShopId.Clear();
var list = GlobalConfig.VDianShopLoginList.Where(s => s.ApiAuth == "已授权").Select(ss => ss.ShopId);
lstUpVDianShopId.AddRange(list);
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (list.Any(l => l == row.Cells["colShopId"]?.Value?.ToString()))
row.Cells["colIsUpload"].Value = true;
}
}
}
private void labelX4_Click(object sender, EventArgs e)
{
labelClickTimes++;
if (labelClickTimes >= 6)
{
labelClickTimes = 0;
btnShowCef.Visible = !btnShowCef.Visible;
}
}
private void btnShowCef_Click(object sender, EventArgs e)
{
if (btnShowCef.Text == "显示网页")
{
cefId++;
if (cefId >= lstCef.Count - 1)
{
cefId = lstCef.Count - 1;
btnShowCef.Text = "隐藏网页";
}
if (cefId >= 0 && lstCef[cefId] != null)
lstCef[cefId].BringToFront();
}
else
{
btnShowCef.Text = "显示网页";
cefId = -1;
foreach (var cefWebBrowser in lstCef)
{
if (cefWebBrowser != null)
cefWebBrowser.SendToBack();
}
}
}
private void btnManageVDian_Click(object sender, EventArgs e)
{
VDianShopListForm vDianShopForm = new VDianShopListForm();
vDianShopForm.ShowDialog();
}
}
}