Files
KJD/TEMUKJD/KJDForms/ProductForms/FissionUserControl/Fission.cs
T

2968 lines
128 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.IO;
using AllBase;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
using DevComponents.DotNetBar;
using System.Text;
using AllBase.Helper;
using NaiBa.Util.Extension;
using Work.CollectClass;
using TemuKJD.BaseForms;
using AllBase.Model.Param.FissionManage;
using Work;
using Work.Api;
using System.Threading;
using TemuKJD.KJDForms.ToolForms;
using TemuKJD.KJDForms.ToolForms.JDVerify;
using NaiBa.Util;
using Work.DouyinApiClass;
using Work.BLL.Upload;
using NaiBa.CefHelper;
using AllBase.Model.Param.ProductManage;
using TemuKJD.KJDForms.ProductForms.FissionUserControl;
using AllBase.Model.Result;
using NaiBa.CefHelper.Handler;
using TemuKJD.KJDForms.ToolForms.KeywordsForms;
namespace TemuKJD.KJDForms.ProductForms
{
public partial class Fission : LRBaseForm
{
public ChromiumWebBrowser browser;
private static string sFissionPage = Directory.GetCurrentDirectory() + @"\page.html";
private string _url;
private string _urlListStr;
private string _fullCate;
private string _teamGroup;
private string _fissionTitle;
public List<FissionData> _lstDataBaseProductFissData;
ProductCollectBase detailDataPcb = new ProductCollectBase();
public static List<GoodsCategoryModelEx> goodsCategoryList = new List<GoodsCategoryModelEx>();
public static Dictionary<string, GoodsCategoryModel> dicNameCate = new Dictionary<string, GoodsCategoryModel>();
private decimal RandAddPriceBegin = 1.3M;
private decimal BaseAddPrice = 10M;
/// <summary>
/// 折扣比例
/// </summary>
private decimal discount;
private string path = "temp/FissionBackup.txt";
private List<string> _listUrlTemp = new List<string>(); // 临时队列 存放url 留备份到txt使用
private readonly object ob = new object(); // 锁文件
private static Fission instance;
public string fullCatStrings = "";
public static List<KeyValueBase> sCustomPropList = new List<KeyValueBase>();
public static List<quality_file> sQulityFileList = new List<quality_file>();
/// <summary>
/// 食品饮料一级类目:粮油米面/南北干货/调味品 零食/坚果/特产 咖啡/麦片/冲饮 茶 酒类 保健食品/膳食营养补充食品 传统滋补营养品 传统滋补营养品 食品卡券
/// </summary>
public static string[] foodCate1Names = new string[] { "粮油米面/南北干货/调味品", "零食/坚果/特产", "咖啡/麦片/冲饮", "茶",
"酒类", "保健食品/膳食营养补充食品", "传统滋补营养品", "食品卡券"};
public int currentRowIndex = 0;
public static Fission GetInstance()
{
return instance;
}
internal static List<GoodsCategoryModelEx> GoodsCategories
{
get
{
//if (goodsCategoryList.Count == 0)
// goodsCategoryList = GetShopGoodsCategories();
return goodsCategoryList;
}
}
public Fission(string sUrl, string urlListStr, List<FissionData> dataBaseProductFissDataList = null, ProductCollectBase data = null,
string teamGroup = "", string fullCate = "", string fissionTitle = "", string sKeywords = "", string sVoicewords = "")
{
InitializeComponent();
instance = this;
this.splitPage.Panel2Collapsed = true;
pnlMsg.Text = "";
this.detailDataPcb = data;
this._url = sUrl;
this._urlListStr = urlListStr;
this._fissionTitle = fissionTitle;
this._teamGroup = teamGroup;
this._fullCate = fullCate;
this._lstDataBaseProductFissData = dataBaseProductFissDataList;
}
private void Fission_Load(object sender, EventArgs e)
{
if (BaseClass.Ico != null)
{
Iconx = BaseClass.Ico;
Icon = BaseClass.Ico;
}
//CleanDataForm.LstFissionForm.Add(this);
this.lklbResetShop_LinkClicked(null, null);
var tempPcb = GetDataBaseProductPcb(detailDataPcb);
if (tempPcb != null)
{
detailDataPcb = tempPcb;
this.pnlShowOriginal.Visible = true;
}
if (detailDataPcb == null)
return;
if (!string.IsNullOrEmpty(_fissionTitle))
txtTitle.Text = _fissionTitle.Replace(";", "\r\n");
if (!string.IsNullOrEmpty(_fullCate))
lblCategory.Text = _fullCate;
// 获取商品的店铺标记/分组
GetTeamGroupContent(_teamGroup);
// 初始化净化数据网页及页面内容
InitFissionData(detailDataPcb);
GetMeiTuPath();
ReloadShop();
if (BaseClass.IsCloudBuyOrder)
btnCatchWords.Visible = true;
}
/// <summary>
/// 初始化净化数据网页及页面内容
/// </summary>
/// <param name="sUrl"></param>
/// <param name="urlListStr"></param>
/// <param name="data"></param>
private void InitFissionData(ProductCollectBase data)
{
try
{
this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
if (!string.IsNullOrEmpty(_url))
{
InitBrowser();
}
else
{
return;
}
if (!string.IsNullOrEmpty(_urlListStr))
{
InitWinForm(data);
}
this.WindowState = FormWindowState.Minimized;
}
catch (Exception ex)
{
BaseMsgForm.ShowInfo("未正确获取商品信息!(请确认商品ID是否正确以及网络)");
}
}
private void InitWinForm(ProductCollectBase data = null)
{
_listUrlTemp.Clear();
string[] urlList = _urlListStr.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
int i = 1;
urlList = urlList.Distinct().ToArray(); // 去重 add by tl 20190610
foreach (string str in urlList)
{
string productUrl = FilterURL(str); // 商品url
string proName = "";
if (str.Contains("-----"))
{
proName = str.Substring(0, str.IndexOf("-----"));
}
if (!_listUrlTemp.Contains(productUrl))
{
i++;
_listUrlTemp.Add(productUrl);
var from_id = GetIdFromURLByRegex(productUrl);
var finalFissionData = _lstDataBaseProductFissData?.FirstOrDefault(f => f.fession_id == from_id.ToString());
dataGridView1.Rows.Add(
i,
finalFissionData == null ? 0 : finalFissionData?.id,
productUrl,
proName,
"待处理",
"移除",
finalFissionData == null ? "" : "从数据库删除");
}
}
// 保存到临时文件
using (StreamWriter st = new StreamWriter(new FileStream(path, FileMode.Create)))
{
foreach (string str in _listUrlTemp)
{
st.WriteLine(str.Trim('\r', '\n'));
}
}
if (data != null)
{
InitGoodsDetail(data);
}
// 检查数据库是否已有此商品
GetIsExistProduct();
}
public delegate void DelFormLoaded();
private delegate void DelChangeWindowState();
public delegate void DelCloseEvent();
public DelCloseEvent CloseEvent { get; set; }
public DelFormLoaded FormLoadedEvent { get; set; }
FissionBrowserObject fissionBrowserObject = new FissionBrowserObject();
private void InitBrowser()
{
this.updateBtn.Enabled = false;
this.addToDBBtn.Enabled = false;
//CefSettings settings = new CefSettings();
//settings.Locale = "zh-CN";
// Initialize cef with the provided settings
//Cef.Initialize(settings);
if (browser == null)
{
browser = new ChromiumWebBrowser(_url) { Dock = DockStyle.Fill, KeyboardHandler = new KeyboardHandler() };
fissionBrowserObject = new FissionBrowserObject();
fissionBrowserObject.InformationReceived += fissionBrowserObject_InfomationReceived;
// 注册C#类为JS对象(FissionBrowserObject.cs)类
//browser.RegisterJsObject("cefBrowser", fissionBrowserObject, new CefSharp.BindingOptions { CamelCaseJavascriptNames = false });
//CefSharpSettings.LegacyJavascriptBindingEnabled = true;//cef 79 84以后:“CefSharpSettings”未包含“LegacyJavascriptBindingEnabled”的定义
CefSharpSettings.WcfEnabled = true;
browser.JavascriptObjectRepository.Register("cefBrowser", fissionBrowserObject, isAsync: false, options: new BindingOptions { /*CamelCaseJavascriptNames = false*/ /*cef79*/ });
browser.FrameLoadEnd += Browser_FrameLoadEnd;
browser.SizeChanged += Browser_SizeChanged;
this.panel1.Controls.Add(browser);
}
else
{
browser.Load(_url);
}
}
private void Browser_SizeChanged(object sender, EventArgs e)
{
Task.Run(() =>
{
while (!browser.IsBrowserInitialized || browser.IsLoading)
{
Thread.Sleep(100);
}
Thread.Sleep(10);
var jsCode = @"initDragHtml();";
browser.GetMainFrame().EvaluateScriptAsync(jsCode, null);
});
}
private void Browser_IsBrowserInitializedChanged(object sender, EventArgs e)
{
//当网页加载完毕之后,将上传按钮置为可用。
Action act = delegate
{
if (!string.IsNullOrEmpty(this.lblCategory.Text))
{
this.updateBtn.Enabled = true;
this.addToDBBtn.Enabled = true;
}
};
this.Invoke(act);
}
private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
FormLoadedEvent?.Invoke();
ChangeWindowState();
// 当网页加载完毕之后,将上传按钮置为可用。
Action act = delegate
{
if (!string.IsNullOrEmpty(this.lblCategory.Text))
{
this.updateBtn.Enabled = true;
this.addToDBBtn.Enabled = true;
}
};
this.Invoke(act);
}
private void ChangeWindowState()
{
if (this.Created)
{
if (this.WindowState == FormWindowState.Minimized)
{
if (this.InvokeRequired)
{
DelChangeWindowState delChangeWindowState = ChangeWindowState;
this.Invoke(delChangeWindowState);
}
else
{
WindowState = FormWindowState.Maximized;
}
}
}
}
public override void PictureBox1_Click(object sender, EventArgs e)
{
if (File.Exists(sFissionPage))
{
File.Delete(sFissionPage);
}
if (CloseEvent != null)
{
CloseEvent.Invoke();
}
base.PictureBox1_Click(sender, e);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (File.Exists(sFissionPage))
{
File.Delete(sFissionPage);
}
if (CloseEvent != null)
{
CloseEvent.Invoke();
}
this.Close();
}
#region 窗体移动
//定义无边框窗体Form 
[DllImport("user32.dll")]//*********************拖动无窗体的控件 
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
private void panel2_MouseDown(object sender, MouseEventArgs e)
{
//MoveForm(this, this.panel2);
}
private void MoveForm(Form form, Panel panel)
{
ReleaseCapture();
SendMessage(form.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);//*********************调用移动无窗体控件函数
}
#endregion
private void importFileBtn_Click(object sender, EventArgs e)
{
BaseMsgForm.ShowInfo("格式1:商品地址\r\n" +
"格式2:关键词-----商品地址\r\n", "导入格式");
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "文本文件(*.txt)|*.txt";
openFileDialog.RestoreDirectory = true;
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
_listUrlTemp.Clear();
string fName = openFileDialog.FileName;
string line = string.Empty;
string productUrl = string.Empty;
// 追加保存到临时文件
using (StreamWriter st = new StreamWriter(new FileStream(path, FileMode.Create)))
{
using (StreamReader sr = new StreamReader(openFileDialog.FileName, System.Text.Encoding.Default))
{
dataGridView1.Rows.Clear();
int i = 1;
while ((line = sr.ReadLine()) != null)
{
importURLtextBox.Text = openFileDialog.FileName;
productUrl = FilterURL(line);
string proName = "";
if (line.Contains("-----"))
{
proName = line.Substring(0, line.IndexOf("-----"));
}
if (!_listUrlTemp.Contains(productUrl))
{
i++;
_listUrlTemp.Add(productUrl); // 新添加的文件 需要给集合重新赋值
dataGridView1.Rows.Add(
i,
0,
productUrl,
proName,
"待处理",
"移除",
"");
st.Write(productUrl + "\r\n");
}
}
}
}
}
}
private void splitContainer2_Panel2_Paint(object sender, PaintEventArgs e)
{
}
private long GetIdFromURLByRegex(string url)
{
try
{
if (url.Contains(@"yangkeduo.com"))
{
Regex pddurl = new Regex(@"[?&]goods_id=([^&#]+)");
string id = pddurl.Match(url).ToString();
//Regex idRegex = new Regex(@"[^0-9]+");
string Num = Regex.Replace(id, @"[^0-9]+", "");
return long.Parse(Num);
}
if (url.Contains(@"1688.com"))
{
string str = url.Substring(0, url.IndexOf(".html")).Replace(@"1688.com", "");
string num = Regex.Replace(str, @"[^0-9]+", "");
return long.Parse(num);
}
if (url.Contains("jd.com"))
{
//https://item.jd.com/69126349289.html
string str = url.Substring(url.IndexOf("jd.com/")).Replace(".html", "");
string num = Regex.Replace(str, @"[^0-9]+", "");
return long.Parse(num);
}
Regex urlRegex = new Regex(@"[?&]id=([^&#]+)");
string idStr = urlRegex.Match(url).ToString();
//Regex idRegex = new Regex(@"[^0-9]+");
string idNum = Regex.Replace(idStr, @"[^0-9]+", "");
return long.Parse(idNum);
}
catch (Exception ex)
{
return 0;
}
}
private string FilterURL(string url)
{
if (url.Contains("1688.com"))
{
string str = url.Substring(0, url.IndexOf("html") + 4);
return str;
}
if (url.Contains(@"yangkeduo.com"))
{
Regex pddurl = new Regex(@"[?&]goods_id=([^&#]+)");
string id = pddurl.Match(url).ToString();
string Num = Regex.Replace(id, @"[^0-9]+", "");
if (url.Contains(@"mobile.angkeduo.com"))
{
return "http://mobile.yangkeduo.com/goods.html?goods_id=" + Num;
}
else
{
return "http://yangkeduo.com/goods.html?goods_id=" + Num;
}
}
if (url.Contains("jd.com"))
{
string str = url.Substring(url.IndexOf("jd.com/")).Replace(".html", "");
string num = Regex.Replace(str, @"[^0-9]+", "");
return "https://item.jd.com/" + num + ".html";
}
Regex urlRegex = new Regex(@"(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?");
string idStr = urlRegex.Match(url).ToString();
string finalUrl = idStr + "?id=" + GetIdFromURLByRegex(url);
return finalUrl;
}
/// <summary>
/// 初始化商品详情信息(不包含图片)并显示
/// </summary>
/// <param name="data"></param>
private void InitGoodsDetail(ProductCollectBase data)
{
fullCatStrings = "";
GoodsCategoryModel cat = null;
// 抖音商品或者产品数据库商品不再获取所有类目推荐列表
if (data.isFission || data.from == "抖音")
{
if (Fission.goodsCategoryList.Count == 0)
Fission.goodsCategoryList = JsonHelper.DeserializeJsonToList<GoodsCategoryModelEx>(DyCategoryParam.DyCategorys);
cat = Fission.goodsCategoryList.FirstOrDefault(c => c.id == data.cat_id);
if (cat != null)
{
// {"id":21621,"name":"电吹风","parent_cid":20099,"level":2,"enable":true,"first_cid":20099,"second_cid":21621,"third_cid":0,"fourth_cid":0,"first_name":"个人保健/护理电器","second_name":"电吹风","third_name":"","fourth_name":"","is_leaf":true,"highlight_levels":[],"extra_info":null,"industry_status":0}
fullCatStrings = "[{\"id\":" + cat.id + ",\"name\":\"" + cat.name + "\"," +
"\"parent_cid\":" + cat.parent_id + ",\"level\":" + cat.level + ",\"enable\":" + cat.enable.ToString().ToLower() + ",";
List<GoodsCategoryModel> cl = new List<GoodsCategoryModel>();
cl.Add(cat);
var catEx = Fission.goodsCategoryList.FirstOrDefault(c => c.id == cat.id);
var pCat = Fission.goodsCategoryList.FirstOrDefault(c => c.id == cat.parent_id);
while (pCat != null && pCat.id != 0)
{
cl.Insert(0, pCat);
pCat = Fission.goodsCategoryList.FirstOrDefault(c => c.id == pCat.parent_id);
}
while (cl.Count < 4)
{
cl.Add(new GoodsCategoryModelEx());
}
fullCatStrings += "\"first_cid\":" + cl[0].id + ",\"second_cid\":" + cl[1].id + ",\"third_cid\":" + cl[2].id + ",\"fourth_cid\":" + cl[3].id + "," +
"\"first_name\":\"" + cl[0].name + "\",\"second_name\":\"" + cl[1].name + "\",\"third_name\":\"" + cl[2].name + "\",\"fourth_name\":\"" + cl[3].name + "\",";
fullCatStrings += "\"is_leaf\":" + cat.is_leaf.ToString().ToLower() + ",\"highlight_levels\":[],\"extra_info\":null," +
"\"industry_status\":" + catEx.industry_status + "}]";
}
}
if (cat == null)
cat = GetCategoryInfo(data, out fullCatStrings, false);
#region 将原有的类目置0
data.main_cid = 0;
data.cat_id = 0;
data.cat1 = 0;
data.cat2 = 0;
data.cat3 = 0;
data.cat4 = 0;
if (InvokeRequired)
{
Invoke(new Action(() =>
{
pnlShowCategoryList.Visible = false;
}));
}
else
pnlShowCategoryList.Visible = false;
#endregion
data.cat_id = cat.id;
List<int> catList = GetParentCatList(data.cat_id);
if (catList.Count > 0)
{
if (string.IsNullOrEmpty(lblCategory.Text) || lblCategory.Text == "fenlei")
lblCategory.Text = GetFullCatString(cat.id);
data.cat1 = catList[0];
data.main_cid = catList[0];
}
if (catList.Count > 1)
data.cat2 = catList[1];
if (catList.Count > 2)
data.cat3 = catList[2];
if (catList.Count > 3)
data.cat4 = catList[3];
if (!string.IsNullOrEmpty(fullCatStrings))
{
JArray jArr = JArray.Parse(fullCatStrings);
if (jArr != null && jArr.Count > 0)
{
if (InvokeRequired)
Invoke(new Action(() =>
{
pnlShowCategoryList.Visible = true;
}));
else
pnlShowCategoryList.Visible = true;
if (string.IsNullOrEmpty(lblCategory.Text))
{
var fullCatString = JsonHelper.SerializeObject(jArr[0]);
data.cat1 = data.main_cid = BaseRegex.GetIntJson(ref fullCatString, "first_cid");
data.cat2 = BaseRegex.GetIntJson(ref fullCatString, "second_cid");
data.cat3 = BaseRegex.GetIntJson(ref fullCatString, "third_cid");
data.cat4 = BaseRegex.GetIntJson(ref fullCatString, "fourth_cid");
lblCategory.Text = (BaseRegex.GetStringJson(ref fullCatString, "first_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "second_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "third_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "fourth_name")).Trim('>')/*.Replace("\\t", " ")*/;
}
}
}
// 来源标题(拼多多新采集商品为data.name)
SourceTitlelabel.Text = data.from_title;
if (string.IsNullOrEmpty(SourceTitlelabel.Text) && data.from_url.Contains("yangkeduo.com"))
SourceTitlelabel.Text = data.name;
// 上货使用的标题
if (string.IsNullOrEmpty(txtTitle.Text))
SourceTitlelabel.Text = data.name;
if (string.IsNullOrEmpty(txtTitle.Text))
txtTitle.Text = SourceTitlelabel.Text.Replace(";", "\r\n");
priceLabel.Text = data.price.ToString();
if (data.from_url.Contains("taobao.com") || data.from_url.Contains("tmall.com") || data.from_url.Contains("tmall.hk"))
sourceLabel.Text = "淘宝";
else if (data.from_url.Contains("1688.com"))
sourceLabel.Text = "1688";
else if (data.from_url.Contains("yangkeduo.com"))
sourceLabel.Text = "拼多多";
else if (data.from_url.Contains("jd.com"))
sourceLabel.Text = "京喜";
else if (data.from_url.Contains("jinritemai.com"))
sourceLabel.Text = "抖音";
importURLtextBox.Text = data.from_url;
lblFromUrl.Text = data.from_url;
freePostLabel.Text = data.express_price == 0 ? "包邮" : "不包邮";
}
/// <summary>
/// 获取分类信息(通过标题搜索商品分类)
/// </summary>
/// <param name="data"></param>
/// <param name="isMainName"></param>
/// <returns></returns>
private GoodsCategoryModel GetCategoryInfo(ProductCollectBase data, out string fullCatStrings, bool isMainName = true)
{
fullCatStrings = "";
var errMsg = "";
int catid = 0;
int parent_id = 0;
int main_cat_id = 0;
bool is_leaf = true;
bool enable = true;
int level = 0;
string name = "其他";
ShopLoginInfo dyShop = null;
var item = this.cmbGetCatShop.SelectedItem as ComboBoxItem;
if (item != null && item.Name != "随机选择")
{
dyShop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == item.Name);
if (dyShop != null)
{
catid = (int)UploadProductBLL.GetCat(data.name, out errMsg, out fullCatStrings, dyShop);
if (errMsg.Contains("店铺未登录"))
{
lblCategory.Text = "请登录店铺!";
BaseMsgForm.ShowError("店铺掉线,请重新登录或更换店铺!");
}
}
else
BaseMsgForm.ShowError("店铺不存在,请重新选择!");
}
else
{
dyShop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.LoginStatus == "登录成功");
if (dyShop == null)
lblCategory.Text = "请登录店铺!";
while (dyShop != null && catid == 0)
{
catid = (int)UploadProductBLL.GetCat(data.name, out errMsg, out fullCatStrings, dyShop);
if (string.IsNullOrEmpty(data.name) && catid == 0)
break;
if (dyShop.LoginStatus == "未登录")
{
StartUp.SaveLocalShopLoginInfo();
dyShop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.LoginStatus == "登录成功");
Thread.Sleep(100);
}
}
}
GoodsCategoryModel cat = GoodsCategories.Find(x => x.id == catid);
//if (cat == null && catid != 0)
//{
// //cat_dy.json库中没有找到该类目,记录下来,后面逐步补充该文件
// //记录类目ID到 文件temp\unrecognized_category.txt
// RecordCategory(catid);
//}
if (isMainName)
cat = GoodsCategories.Find(x => x.id == cat?.main_cat_id);
if (cat == null)
{
if (!string.IsNullOrEmpty(fullCatStrings))
{
JArray jArr = JArray.Parse(fullCatStrings);
if (jArr != null && jArr.Count > 0)
{
var fullCatString = JsonHelper.SerializeObject(jArr[0]);
catid = BaseRegex.GetIntJson(ref fullCatString, "id");
main_cat_id = BaseRegex.GetIntJson(ref fullCatString, "first_cid");
name = BaseRegex.GetStringJson(ref fullCatString, "name");
parent_id = BaseRegex.GetIntJson(ref fullCatString, "parent_cid");
is_leaf = BaseRegex.GetBoolJson(ref fullCatString, "is_leaf");
enable = BaseRegex.GetBoolJson(ref fullCatString, "enable");
level = BaseRegex.GetIntJson(ref fullCatString, "level");
if (isMainName)
{
catid = BaseRegex.GetIntJson(ref fullCatString, "first_cid");
main_cat_id = 0;
name = BaseRegex.GetStringJson(ref fullCatString, "first_name");
parent_id = 0;
is_leaf = false;
enable = BaseRegex.GetBoolJson(ref fullCatString, "enable");
level = 1;
}
}
}
cat = new GoodsCategoryModel()
{
id = catid,
main_cat_id = main_cat_id,
name = name,
parent_id = parent_id,
is_leaf = is_leaf,
level = level,
enable = enable
};
}
return cat;
}
/// <summary>
/// 净化数据执行切换
/// </summary>
/// <param name="bPrev">上一条</param>
private void ExecuteProductPrevOrAfter(bool bPrev)
{
this.updateBtn.Enabled = false;
this.addToDBBtn.Enabled = false;
int selectedIndex = 0;
int selectedRow = 0;
//dataGridView1.CurrentRow.Selected = false;
if (bPrev)
{
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
if (dataGridView1.SelectedRows[i].Index < selectedIndex || selectedIndex == 0)
{
selectedIndex = dataGridView1.SelectedRows[i].Index;
}
dataGridView1.SelectedRows[i].Selected = false;
}
if (0 == selectedIndex)
{
BaseMsgForm.ShowInfo("当前为第一条!", "提示");
return;
}
dataGridView1.Rows[selectedIndex - 1].Selected = true;
selectedRow = selectedIndex - 1;
}
else
{
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
if (dataGridView1.SelectedRows[i].Index > selectedIndex)
{
selectedIndex = dataGridView1.SelectedRows[i].Index;
}
dataGridView1.SelectedRows[i].Selected = false;
}
if (dataGridView1.RowCount <= selectedIndex + 1)
{
BaseMsgForm.ShowInfo("当前为最后一条!", "提示");
return;
}
dataGridView1.Rows[selectedIndex + 1].Selected = true;
selectedRow = selectedIndex + 1;
}
dataGridView1.CurrentCell = this.dataGridView1.Rows[selectedRow].Cells[0];
CollectProductInfoAndShowBrowser(selectedRow);
}
private void NextURLBtn_Click(object sender, EventArgs e)
{
ExecuteProductPrevOrAfter(false);
}
private void LastURLBtn_Click(object sender, EventArgs e)
{
ExecuteProductPrevOrAfter(true);
}
private void randAddPercentTextBoxX_TextChanged(object sender, EventArgs e)
{
decimal i;
if (CheckInt(randAddPercentTextBoxX, out i))
RandAddPriceBegin = i;
}
private void baseAddPriceTextBoxX_TextChanged(object sender, EventArgs e)
{
decimal i;
if (CheckInt(baseAddPriceTextBoxX, out i))
BaseAddPrice = i;
}
private void txtDiscount_TextChanged(object sender, EventArgs e)
{
decimal i;
if (CheckInt(txtDiscount, out i))
discount = i;
}
/// <summary>
/// 检查是否输入数字
/// </summary>
/// <param name="box"></param>
/// <param name="d"></param>
/// <returns></returns>
public bool CheckInt(TextBox box, out decimal d)
{
if (decimal.TryParse(box.Text, out d))
return true;
BaseMsgForm.ShowInfo("请输入数字", "提示");
box.Focus();
return false;
}
bool CheckSubmit(out FissionDataModel fissionDataModel, out ProductCollectBase pcb)
{
fissionDataModel = new FissionDataModel();
pcb = new ProductCollectBase();
if (string.IsNullOrEmpty(txtTitle.Text.Trim()))
{
BaseMsgForm.ShowInfo("标题不可为空!");
return false;
}
// 折扣范围:20-90
if (checkBoxX1.Checked && (discount < 20 || discount > 90))
{
BaseMsgForm.ShowInfo("折扣超限了,折扣范围:20-90");
txtDiscount.Focus();
return false;
}
// 获取商品主图list
List<string> mainImages = GetMainImages();
if (mainImages == null || mainImages.Count == 0)
{
BaseMsgForm.ShowInfo("主图不可为空!");
return false;
}
// 获取商品详情图list
List<string> contentImages = GetContent();
if (contentImages == null || contentImages.Count == 0)
{
BaseMsgForm.ShowInfo("内容图不可为空!");
return false;
}
fissionDataModel.id = detailDataPcb.from_id.ToString();
fissionDataModel.fession_id = detailDataPcb.from_id.ToString();
fissionDataModel.sales = detailDataPcb.saleCount.ToString();
fissionDataModel.price = priceLabel.Text;
fissionDataModel.fessionTitle = txtTitle.Text.Trim().Split(new string[] { ";", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
fissionDataModel.fessionCount = "1";
fissionDataModel.mainWord = "";
fissionDataModel.viceWord = "";
fissionDataModel.teamGroup = cmbShopFlag.SelectedValue == null ? "" : cmbShopFlag.SelectedValue.ToString();
fissionDataModel.source = sourceLabel.Text;
fissionDataModel.postFree = detailDataPcb.express_price.ToString();
fissionDataModel.title = string.IsNullOrEmpty(detailDataPcb.from_title) ? detailDataPcb.name : detailDataPcb.from_title;
fissionDataModel.cate_id = detailDataPcb.cat_id;
fissionDataModel.secondCategory = lblCategory.Text.Split('>').LastOrDefault();
fissionDataModel.main_cate_id = detailDataPcb.main_cid;
fissionDataModel.mainCategory = lblCategory.Text.Split('>').FirstOrDefault();
fissionDataModel.fullCategoryName = lblCategory.Text;
var catList = fissionDataModel.fullCategoryName.Split(new string[] { ">>" }, StringSplitOptions.RemoveEmptyEntries);
if (catList.Count() >= 2)
fissionDataModel.cat2_name = catList[1];
if (catList.Count() >= 3)
fissionDataModel.cat3_name = catList[2];
fissionDataModel.adjustPrice = checkBoxX1.Checked ? 1 : 0; // 是否调节价格
fissionDataModel.addPricePercent = (RandAddPriceBegin - 1) * 100; // 加价倍数
fissionDataModel.baseAddPrice = BaseAddPrice; // 基础加价
fissionDataModel.discount = discount; // 折扣比例
// 获取自定义属性保存到fissionDataModel
sCustomPropList = GetCustomProp();
foreach (var pr in sCustomPropList)
{
var kv = detailDataPcb.Prop.FirstOrDefault(p => p.Key == pr.Key);
if (kv != null)
kv.Value = pr.Value;
else
detailDataPcb.Prop.Add(pr);
}
// 暂时属性/资质类编辑只针对食品饮料类目开放,删除非食品饮料类目"品牌编号"属性
if (!foodCate1Names.Any(f => this.lblCategory.Text.StartsWith(f)))
detailDataPcb.Prop.RemoveAll(p => p.Key == "品牌编号");
fissionDataModel.prop = JsonHelper.SerializeObject(detailDataPcb.Prop); // 商品属性
fissionDataModel.props = JsonHelper.SerializeObject(GetSkus()); // sku属性
fissionDataModel.skus = JsonHelper.SerializeObject(detailDataPcb.SkuMaps); // sku
fissionDataModel.main_pic = mainImages;
fissionDataModel.content_pic = contentImages;
fissionDataModel.from_shop_name = detailDataPcb.from_shop_name;
// 获取资质文件保存到fissionDataModel
sQulityFileList = GetQualities();
fissionDataModel.qualifications = JsonHelper.SerializeObject(sQulityFileList);
// 转换为Pcb
pcb = FissionDataModel2Pcb(fissionDataModel);
return true;
}
private void updateBtn_Click(object sender, EventArgs e)
{
FissionDataModel fessionDataModel = null;
ProductCollectBase pcb = null;
if (CheckSubmit(out fessionDataModel, out pcb))
{
//UploadProductForm.ImportFromFission(new List<ProductCollectBase>() { pcb });
#region UpdateUI
dataGridView1.SelectedRows[0].Cells["status"].Value = "提交上传处理成功";
//提交上传处理成功 则需要移除当前行,并更新txt,焦点移到下一行
string goodsId = dataGridView1.SelectedRows[0].Cells["colProductId"].Value.ToString();
if (!string.IsNullOrEmpty(goodsId))
_listUrlTemp.Remove(goodsId);
int index = dataGridView1.SelectedRows[0].Index; //记录需要移除的是哪一行
ExecuteProductPrevOrAfter(false); //焦点到下一行
dataGridView1.Rows.RemoveAt(index); //移除
Task.Factory.StartNew(() => writeTxt(_listUrlTemp)); //开个单独线程来对txt 写值
#endregion
}
}
/// <summary>
/// 将集合写到文件
/// </summary>
private void writeTxt(List<string> _urlList)
{
try
{
lock (ob)
{
if (_urlList.Count <= 0)
{
FileBase.Delete(path);
return;
}
// 保存到临时文件
using (StreamWriter st = new StreamWriter(new FileStream(path, FileMode.Create)))
{
foreach (string str in _urlList)
{
st.WriteLine(str.Trim('\r', '\n'));
}
}
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// 判断产品数据库里是否已经有此数据
/// </summary>
private bool CheckIsExistProduct(string productId)
{
if (string.IsNullOrEmpty(productId))
return false;
string requestData = UserLogin.GetSignaturex() + "&fession_id=" + GetHtml.UrlEncodeUtf8(productId);
string url = BaseClass.BuildFissionObjString("fession_api&act=check_fession");
string result = GetHtml.PostUtf8(url, requestData); // {\"code\":1,\"msg\":\"already exists!\"}
if (result != null && result.Contains("\"code\":1"))
return true;
return false;
}
private void addToDBBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(lblCategory.Text))
{
DialogResult dr = BaseMsgForm.ShowConfirm("分类为空,是否确定上传入库?", "提示").DialogResult;
if (dr != DialogResult.OK)
return;
}
updateBtn.Enabled = false;//“提交上传”不可用
addToDBBtn.Enabled = false;//“添加入库”不可用
FissionDataModel fissionDataModel = null;
ProductCollectBase pcb = null;
bool bo = CheckSubmit(out fissionDataModel, out pcb);
if (!bo)
return;
Task.Run(() =>
{
if (CheckIsExistProduct(detailDataPcb?.from_id.ToString()))
{
var d = BaseMsgForm.ShowConfirm("数据已存在,是否覆盖?", "提示", FormLevel.MEDIUM, true);
DialogResult dr = d.DialogResult;
if (dr != DialogResult.OK)
{
Invoke(new Action(() =>
{
updateBtn.Enabled = true;
addToDBBtn.Enabled = true;
}));
return;
}
}
if (bo)
{
string str = JsonHelper.SerializeObject(fissionDataModel);
string typeStr = "'update'";
string jsCode = "send_html_data_local(" + str + ", " + typeStr + ")";
Task<JavascriptResponse> t = browser.GetMainFrame().EvaluateScriptAsync(jsCode, null);
t.Wait(30000);
var response = t.Result;
if (response?.Result?.ParseToBool() != true)
{
t = browser.GetMainFrame().EvaluateScriptAsync(jsCode, null);
t.Wait(30000);
}
if (response?.Result?.ParseToBool() == true)
{
if (FissionDataBaseForm.Instance != null)
{
FissionDataBaseForm.Instance.UpdateFissionData(fissionDataModel);
}
}
Thread.Sleep(1000);
Invoke(new Action(() =>
{
var row = dataGridView1.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colProductId"].Value?.ToString().Contains(pcb.from_id.ToString()) == true);
if (row != null)
{
if (response?.Result?.ParseToBool() == true)
{
row.Cells["status"].Value = "保存入库处理成功";
// 提交上传处理成功 移除当前行,焦点移到下一行,并更新txt
string productId = row.Cells["colProductId"].Value.ToString();
if (!string.IsNullOrEmpty(productId))
_listUrlTemp.Remove(productId);
ExecuteProductPrevOrAfter(false); // 焦点到下一行
dataGridView1.Rows.Remove(row); // 移除
Task.Factory.StartNew(() => writeTxt(_listUrlTemp)); // 开个单独线程来对txt 写值
}
else
{
row.Cells["status"].Value = "保存入库处理失败,请重试";
updateBtn.Enabled = true;
addToDBBtn.Enabled = true;
}
}
}));
}
});
}
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
if (dataGridView1.SelectedRows.Count == 0)
{
if (dataGridView1.CurrentCell == null)
{
dataGridView1.Rows[0].Selected = true;
}
else
{
dataGridView1.CurrentCell.Selected = true;
}
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
var column = dataGridView1.Columns[e.ColumnIndex];
var row = dataGridView1.Rows[e.RowIndex];
var productUrl = row.Cells["colProductId"].Value.ToString();
var dbId = row.Cells["colDbId"].Value.ToString();
//点击商品网址打开商品网页
if (column.Name == "colProductId")
{
row.Selected = true;
System.Diagnostics.Process.Start(productUrl);
}
//点击删除执行从列表中去除当前商品
else if (column.Name == "colRemove")
{
row.Selected = true;
//移除当前行,并更新txt,焦点移到下一行
if (!string.IsNullOrEmpty(productUrl))
{
_listUrlTemp.Remove(productUrl);
}
int index = e.RowIndex;//记录需要移除的是哪一行
if (e.RowIndex != dataGridView1.Rows.Count - 1)
{
ExecuteProductPrevOrAfter(false);//焦点到下一行
}
dataGridView1.Rows.RemoveAt(index);//移除
Task.Factory.StartNew(() => writeTxt(_listUrlTemp)); //开个单独线程来对txt 写值
}
// 从数据库中删除数据
else if (column.Name == "colDelete")
{
if (BaseMsgForm.ShowConfirm("是否确认删除此数据?").DialogResult.Equals(DialogResult.Cancel)) return;
// 根据上家标题,原始Id删除数据库数据
new FissionDataBaseBLL().DelFessionData(dbId);
row.Selected = true;
//移除当前行,并更新txt,焦点移到下一行
if (!string.IsNullOrEmpty(productUrl))
{
_listUrlTemp.Remove(productUrl);
}
int index = e.RowIndex;//记录需要移除的是哪一行
if (e.RowIndex != dataGridView1.Rows.Count - 1)
{
ExecuteProductPrevOrAfter(false);//焦点到下一行
}
dataGridView1.Rows.RemoveAt(index);//移除
Task.Factory.StartNew(() => writeTxt(_listUrlTemp));//开个单独线程来对txt 写值
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0 || e.ColumnIndex == 1 || e.ColumnIndex == 4) return;
dataGridView1.Rows[e.RowIndex].Selected = true;
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == null)
{
return;
}
CollectProductInfoAndShowBrowser(e.RowIndex);
}
/// <summary>
/// 根据商品详情ProductCollectBase判断数据库商品缓存列表中是否已有此商品,如有则返回该商品。
/// 如果没有则检测数据库内是否有,若数据库有,显示提示信息。
/// </summary>
/// <param name="pcb"></param>
/// <returns></returns>
private ProductCollectBase GetDataBaseProductPcb(ProductCollectBase pcb)
{
var finalFissionData = _lstDataBaseProductFissData?.FirstOrDefault(f => f.fession_id == pcb?.from_id.ToString());
if (finalFissionData != null) // 列表中已有此数据,说明是批量编辑而非新增的数据净化
{
try
{
if (string.IsNullOrEmpty(finalFissionData.main_pic))
{
var fissionTemp = new FissionDataBaseBLL().GetFessionDetailById(finalFissionData.id.ParseToInt());
finalFissionData.fession_title = fissionTemp.fession_title;
finalFissionData.container_info = fissionTemp.container_info?.Replace("<img src='<", "<").Replace("'>'>", "'>");
finalFissionData.main_pic = fissionTemp.main_pic;
finalFissionData.prop_pic = fissionTemp.prop_pic;
finalFissionData.props = fissionTemp.props;
finalFissionData.mainWord = fissionTemp.mainWord;
finalFissionData.viceword = fissionTemp.viceword;
finalFissionData.prop = fissionTemp.prop;
finalFissionData.skus = fissionTemp.skus;
finalFissionData.from_shop_name = fissionTemp.from_shop_name;
finalFissionData.qualifications = fissionTemp.qualifications;
}
}
catch (Exception ex)
{
LogSave.Add("获取裂变明细信息发生异常" + ex.Message);
}
if (!string.IsNullOrEmpty(finalFissionData.fession_title))
return FissionDataBaseForm.FissionData2Pcb(finalFissionData, finalFissionData.fession_title);
}
return null;
}
private void GetIsExistProduct()
{
Task.Run(() =>
{
while (this.WindowState == FormWindowState.Minimized)
{
Thread.Sleep(100);
}
var finalFissionData = _lstDataBaseProductFissData?.FirstOrDefault(f => f.fession_id == detailDataPcb?.from_id.ToString());
if (finalFissionData == null)
{
if (CheckIsExistProduct(detailDataPcb?.from_id.ToString()))
{
Invoke(new Action(() =>
{
BaseMsgForm.ShowInfo("数据库已存在该商品!");
}));
}
}
});
}
/// <summary>
/// 点击上一条下一条或者列表选择商品时,跳转到商品并更新页面
/// </summary>
/// <param name="rowIndex"></param>
/// <param name="IsForceGetOriginal">是否强制访问来源商品(如选择false,则进行产品数据库数据审核时会优先加载产品数据库界面传递过来的数据库商品以供审核)</param>
private void CollectProductInfoAndShowBrowser(int rowIndex, bool IsForceGetOriginal = false)
{
SourceTitlelabel.Text = importURLtextBox.Text = lblCategory.Text = txtTitle.Text = "";
if (browser != null)
browser.Load("about:blank");
CurrentPositiontextBox.Text = dataGridView1.Rows[rowIndex].Cells[0].Value.ToString();
ProductCollectBase proInfoPcb = new ProductCollectBase();
if (dataGridView1.Rows[rowIndex].Cells["colProductId"].Value == null)
{
BaseMsgForm.ShowInfo("无效网址。");
return;
}
proInfoPcb.from_url = dataGridView1.Rows[rowIndex].Cells["colProductId"].Value.ToString().Trim();
proInfoPcb.from_id = GetIdFromURLByRegex(proInfoPcb.from_url);
if (proInfoPcb.from_id.Equals(0))
{
BaseMsgForm.ShowInfo("无效网址!");
return;
}
//先判断是否存在page.html临时文件,存在就先删除。
if (File.Exists(sFissionPage))
{
File.Delete(sFissionPage);
}
ProductCollectBase finalProductInfo = new ProductCollectBase();
pbLoading.Visible = true;
pbLoading.BringToFront();
pnlShowOriginal.Visible = false;
currentRowIndex = rowIndex;
Task.Factory.StartNew(() =>
{
ProductCollectBase pcbTemp = null;
if (!IsForceGetOriginal)
{
pcbTemp = GetDataBaseProductPcb(proInfoPcb);
}
if (pcbTemp != null)
{
finalProductInfo = pcbTemp;
Invoke(new Action(() =>
{
pnlShowOriginal.Visible = true;
}));
}
else if (proInfoPcb.from_url.Contains(@"yangkeduo.com"))
{
int retryTime = 0;
TaobaoProductBase tp = new TaobaoProductBase();
tp.FromId = GetIdFromURLByRegex(proInfoPcb.from_url);
tp.FromType = "拼多多";
tp.GoodsId = tp.FromId;
Retry:
PinduoduoProductCollect pdd = new PinduoduoProductCollect(Name, tp);
PinduoduoProductCollect.TempIds.Clear();
pdd.IsUseProxy = GlobalConfig.FissionSettingParam.IsUseProxyIp;
pdd.Get();
if (GlobalConfig.FissionSettingParam.IsUseProxyIp && pdd.IsOverdue)
{
BaseMsgForm.ShowInfo("代理ip套餐已过期", "提示");
}
bool isResourceEnable = true;
if (GlobalConfig.FissionSettingParam.IsUseResourcePack)
{
//Func<bool> canContinue = PinDuoDuoHelperTemp.CanContinueCollectFunc((token) => { return token.ProductDetailStatus == TokenStatus.Valid; }, null, GlobalConfig.FissionSettingParam.IsUseResourcePack, null);
//if (!canContinue())
//{
// isResourceEnable = false;
// BaseMsgForm.ShowInfo("资源包打码不可用!", "提示");
//}
}
if (pdd.IsAdvance == true || pdd.pb?.IsPreSale == true)
{
BaseMsgForm.ShowInfo("预售商品不能净化!", "提示");
}
if (pdd.IsNoToken)
{
if (GlobalConfig.FissionSettingParam.IsUseResourcePack && isResourceEnable == true && retryTime < 2)
{
retryTime++;
goto Retry;
}
else
BaseMsgForm.ShowInfo("请先登录拼多多或输入Token!", "提示");
}
proInfoPcb = pdd.pb;
//GetCatIdForPdd(proInfo);
proInfoPcb.from_url = proInfoPcb.from_url.Contains(@"mobile.yangkeduo.com")
? "http://mobile.yangkeduo.com/goods.html?goods_id=" + tp.GoodsId
: "http://yangkeduo.com/goods.html?goods_id=" + tp.GoodsId;
finalProductInfo = proInfoPcb;
}
else if (proInfoPcb.from_url.Contains("detail.1688.com"))
{
AlibabaProductGet alibbProInfo = new AlibabaProductGet(proInfoPcb);
alibbProInfo.Get();
//GetCatIdForPdd(proInfo);
finalProductInfo = alibbProInfo.Product;
}
else if (proInfoPcb.from_url.Contains("jinritemai.com"))
{
CollectDoyin cd = new CollectDoyin(proInfoPcb);
cd.GetProduct();
cd.Product.from = "抖音";
cd.Product.from_url = "https://haohuo.jinritemai.com/views/product/detail?id" + cd.Product.from_id;
finalProductInfo = cd.Product;
if (cd.Product?.IsOnSale != true)
{
Invoke(new Action(() =>
{
BaseMsgForm.ShowInfo("获取失败,商品已下架");
}));
}
}
else if (proInfoPcb.from_url.Contains("jd.com"))
{
bool isPassVerify = false;
retry:
proInfoPcb.from_url = "https://item.m.jd.com/product/" + proInfoPcb.from_id + ".html";
JingXiCollect tm = new JingXiCollect(proInfoPcb);
tm.IsUseProxy = GlobalConfig.FissionSettingParam.IsUseProxyIp;
tm.Get();
if (!string.IsNullOrEmpty(JingXiCollect.VerifyCodeUrl))
{
if (!isPassVerify && JingXiCollect.VerifyCodeUrl.Contains("wqs.jd.com/item/spider_check.shtml"))//京喜采集验证码校验 by ttzhao 2020.6.29
{
JingXiVerify(JingXiCollect.VerifyCodeUrl);
if (string.IsNullOrEmpty(JingXiCollect.VerifyCodeUrl))
{
isPassVerify = true;
goto retry;
}
}
Invoke(new Action(() =>
{
BaseMsgForm.ShowInfo("获取失败,京东商品采集需要验证");
}));
}
else if ((tm.Product != null && tm.Product.Images.Count == 0) || tm.IsOnSale == false)
{
Invoke(new Action(() =>
{
BaseMsgForm.ShowInfo("获取失败,商品不存在或不可展示");
}));
}
else
finalProductInfo = tm.Product;
}
else
{
TaobaoMobileCollect goodsFormInfo = new TaobaoMobileCollect(proInfoPcb);
goodsFormInfo.Get();
finalProductInfo = goodsFormInfo.Product;
}
}).ContinueWith(t =>
{
//调用php后台
_url = Fission.creatFissionPage(finalProductInfo);
MethodInvoker mi = () =>
{
InitBrowser();
InitGoodsDetail(finalProductInfo);
pbLoading.Visible = false;
};
BeginInvoke(mi);
detailDataPcb = finalProductInfo;
// 检查数据库是否已有此商品
GetIsExistProduct();
});
}
/// <summary>
/// 京喜采集,需要收入验证码验证
/// </summary>
/// <param name="url"></param>
public static void JingXiVerify(string url)
{
CollectVerifyForm f = new CollectVerifyForm();
f.url = url;
f.ShowDialog();
}
private void lblCategory_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(this.lblCategory.Text) && this.lblCategory.Text != "请登录店铺!")
{
this.updateBtn.Enabled = true;
this.addToDBBtn.Enabled = true;
}
//Task.Run(() =>
//{
GetPropAndQualification();
//});
}
private void checkBoxX1_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxX1.Checked)
{
this.baseAddPriceTextBoxX.Enabled = true;
this.randAddPercentTextBoxX.Enabled = true;
this.txtDiscount.Enabled = true;
RandAddPriceBegin = this.randAddPercentTextBoxX.Text.ParseToDecimal();
BaseAddPrice = this.baseAddPriceTextBoxX.Text.ParseToDecimal();
discount = this.txtDiscount.Text.Trim().ParseToDecimal();
}
else
{
this.baseAddPriceTextBoxX.Enabled = false;
this.randAddPercentTextBoxX.Enabled = false;
this.txtDiscount.Enabled = false;
}
}
private void SourceTitlelabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (string.IsNullOrEmpty(lblFromUrl.Text))
{
return;
}
System.Diagnostics.Process.Start(lblFromUrl.Text);
}
private void importURLtextBox_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(importURLtextBox.Text))
{
return;
}
System.Diagnostics.Process.Start(importURLtextBox.Text);
}
/// <summary>
/// 调用PHP后台,生成分词页面page.html。得到page.html页面后,在页面内添加主图上传及php服务器的图片跨域修改功能。
/// </summary>
/// <param name="finalProductInfo"></param>
/// <returns>返回本地保存的页面路径</returns>
public static string creatFissionPage(ProductCollectBase finalProductInfo)
{
if (finalProductInfo == null || finalProductInfo.from_id == 0)
{
return sFissionPage;
}
// 先判断此商品是否在违规库中
string requestData = UserLogin.GetSignaturex() + "&act=check_goods&product_id=" + finalProductInfo.from_id;
string url = BaseClass.BuildFissionObjString("fession");
string sRes = GetHtml.PostUtf8(url, requestData);//1-违规,0-正常
if (sRes.Equals("1"))
{
File.WriteAllText(sFissionPage, "<!doctype html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body style=\"text-align:center;\"></br>此商品云端检测为违规商品!不建议净化!</body></html>");
return sFissionPage;
}
// 生成净化数据HTML
string htmlData = CreateFissionHtml(finalProductInfo);
File.WriteAllText(sFissionPage, htmlData);
return sFissionPage;
}
/// <summary>
/// 生成净化数据HTML
/// </summary>
/// <param name="finalProductInfo">商品数据</param>
/// <returns></returns>
private static string CreateFissionHtml(ProductCollectBase finalProductInfo)
{
string htmlData = Properties.Resources.template.ToString();
string title = finalProductInfo.from_title;
if (string.IsNullOrEmpty(title) && finalProductInfo.from_url.Contains("yangkeduo.com"))
{
title = finalProductInfo.name;
}
htmlData = htmlData.Replace("{Title}", "原标题:" + title);
int imgCount = 0;
//插入主图
StringBuilder sReplace = new StringBuilder();
for (int i = 0; i < finalProductInfo.Images.Count; i++)
{
sReplace.AppendLine(
"<li id=\"image" + imgCount + "\">\r\n" +
" <img class=\"product_img\" id=\"img" + imgCount + "\" src=\"" + finalProductInfo.Images[i].Trim('"') + "\" onmousedown=\"MainImgDown();\" onmousemove=\"MainImgMove();\" onclick=\"ShowMainBigImg('" + imgCount + "');\" onload = \"OnloadImg('" + imgCount + "')\" flag=\"main\"/>\r\n" +
" <a id=\"OpenMeitu" + imgCount + "\" class=\"center\" href=\"javascript:OpenMeitu('img" + imgCount + "');\">修图</a>\r\n" +
" <a id=\"PullImg" + imgCount + "\" class=\"right\" href=\"javascript:PullImg('img" + imgCount + "');\">拉回</a>\r\n" +
" <a id=\"OpenEditTool" + imgCount + "\" href=\"javascript:;\" class=\"left\" onclick=\"OpenEditTool('img" + imgCount + "')\" target=\"_blank\">编辑</a>\r\n" +
" <a class=\"right-top\" href=\"javascript:DImage(" + imgCount + ",'" + finalProductInfo.Images[i].Trim('"') + "');\">删</a>\r\n" +
"</li>\r\n");
imgCount++;
}
htmlData = htmlData.Replace("{MainImage}", sReplace.ToString());
// 显示商品属性
string propStr = "\r\n";
for (int i = 0; i < finalProductInfo.Prop.Count; i += 3)
{
if (i % 3 == 0)
propStr += "<div class=\"prop_line\">\r\n";
for (int j = 0; j < 3; j++)
{
if (i + j >= finalProductInfo.Prop.Count)
break;
var pr = finalProductInfo.Prop[i + j];
var prValue = pr.Key + ":" + pr.Value;
propStr += "<span class=\"prop_value\" title=\"" + prValue + "\">" + prValue + "</span>\r\n";
}
if (i % 3 == 0)
propStr += "</div>\r\n";
}
htmlData = htmlData.Replace("{ProductProp}", propStr);
// 插入SKU属性图,无图片的也显示文字,以便后续删除
string skuStr = "\r\n";
foreach (var prop in finalProductInfo.Props)
{
var propGroupNew = new PropBase()
{
id = prop.id,
name = prop.name,
pinduoduo_id = prop.pinduoduo_id,
pinduoduo_name = prop.pinduoduo_name,
sort = prop.sort
};
skuStr += "<div style=\"height: 30px; color: #aaa;\">属性分组 - " + prop.name +
"<div style=\"display:none;\">propstart-" + JsonHelper.SerializeObject(propGroupNew) + "-propstartend</div>" + // hidden
"</div>";
skuStr += "<div class=\"pic-list\"><ul id=\"property_image\">\r\n";
foreach (var propValue in prop.Values)
{
string imgUrl = AppDomain.CurrentDomain.BaseDirectory + "static\\img\\nopic.jpg";
if (propValue.image != null && propValue.image != "")
imgUrl = propValue.image;
skuStr += "<li id=\"image" + imgCount + "\">";
skuStr += "<div style=\"display:none;\">propvaluestart-" + JsonHelper.SerializeObject(propValue) + "-propvaluestartend</div>";
// 有sku图片
if (!imgUrl.EndsWith("\\static\\img\\nopic.jpg"))
{
skuStr += "<input type=\"hidden\" value=\"propvalueimgstart-\"/>";
skuStr += "<img class=\"product_img\" id=\"img" + imgCount + "\" src=\"" + imgUrl + "\" sku=\"true\" onclick=\"ShowBigImg('" + imgCount + "');\" onload = \"OnloadImg('" + imgCount + "')\"/>";
skuStr += "<input type=\"hidden\" value=\"-propvalueimgend\"/>";
// 编辑、修图、拉回、转主
skuStr += "<a id=\"OpenEditTool" + imgCount + "\" href=\"javascript:;\" class=\"sku_left_left\" onclick=\"OpenEditTool('img" + imgCount + "')\" target=\"_blank\">编辑</a>" +
"<a id=\"OpenMeitu" + imgCount + "\" class=\"sku_center_left\" href=\"javascript:OpenMeitu('img" + imgCount + "');\" target=\"_blank\">修图</a>" +
"<a id=\"PullImg" + imgCount + "\" class=\"sku_center_right\" href=\"javascript:PullImg('img" + imgCount + "');\" target=\"_blank\">拉回</a>" +
"<a class=\"sku_right_right\" href=\"javascript:AddImage(" + imgCount + ");\">转主</a>";
}
else
{
skuStr += "<span class=\"text_sku\" id=\"img" + imgCount + "\" style=\"display:block; padding:9px; border:1px solid #ddd; background: #fbfaf8;\" >" +
"<span class=\"text_sku\" style=\"display:block; background-size:cover; background-image:url(" + imgUrl.Replace('\\', '/') + ");\"></span></span>";
}
skuStr += "<a href=\"javascript:;\">" + propValue.name + "</a>";
skuStr += "<a class=\"right-top\" href=\"javascript:DImage('" + imgCount + "', '" + imgUrl + "');\");>删</a></li>\r\n";
skuStr += "<input type=\"hidden\" value=\"-propvalueend\"/>";
imgCount++;
}
skuStr += "</ul></div>\r\n";
skuStr += "<input type=\"hidden\" value=\"-propend\" />";
skuStr += "<div class=\"clearfix\"></div>\r\n";
}
htmlData = htmlData.Replace("{SkuProps}", skuStr);
// 插入内容图
string insertStr = "";
string selectStr = "";
string containerImgStr = finalProductInfo.content;
if (!string.IsNullOrEmpty(containerImgStr))
{
var container_arr = containerImgStr.Split(new string[] { "new_group" }, StringSplitOptions.RemoveEmptyEntries);
int i = 0;
foreach (var strTemp in container_arr)
{
i++;
Regex reg = new Regex(@"<img([\s|\S]*?)src=""([\s|\S]*?)""");
var imgMatches = reg.Matches(strTemp);
if (imgMatches.Count == 0)
reg = new Regex(@"<img([\s|\S]*?)src='([\s|\S]*?)'");
imgMatches = reg.Matches(strTemp);
if (imgMatches.Count > 0)
{
var id = Randomx.GetId(10000000, 99999999);
var contentGroupId = "content_group" + id;
var contentSelectId = "content_select" + id;
selectStr += "<span id =\"" + contentSelectId + "\" class=\"content_select\" onclick=\"showContent('" + contentSelectId + "', '" + contentGroupId + "');\">详情" + i + "</span>";
insertStr += "<ul id=\"" + contentGroupId + "\" class=\"content_group\">";
foreach (Match imgMatch in imgMatches)
{
string imgUrl = imgMatch.Groups[2].Value;
if (!string.IsNullOrEmpty(imgUrl))
{
if (!imgUrl.StartsWith("https:"))
imgUrl = "https:" + imgUrl;
insertStr += "<li id=\"image" + imgCount + "\">" +
"<img class=\"product_img\" id=\"img" + imgCount + "\" src=\"" + imgUrl + "\" onclick=\"ShowBigImg('" + imgCount + "');\" />" +
"<a href=\"javascript:;\" class=\"left_left\" onclick=\"OpenEditTool('img" +
imgCount + "',true)\" target=\"_blank\">编辑</a>" +
"<a class=\"center_left\" href=\"javascript:OpenMeitu('img" + imgCount +
"');\" target=\"_blank\">修图</a>" +
"<a class=\"center_right\" href=\"javascript:PullImg('img" + imgCount +
"');\" target=\"_blank\">拉回</a>" +
"<a class=\"right_right\" href=\"javascript:AddImage(" + imgCount +
");\">转主</a>" +
"<a class=\"right-top\" href=\"javascript:DImage('" + imgCount + "','" +
imgUrl + "');\");>删</a>";
imgCount++;
}
}
insertStr += "</ul>";
}
}
}
htmlData = htmlData.Replace("{ContentImage}", insertStr);
htmlData = htmlData.Replace("{ContentSelect}", selectStr);
// 更改样式
var cssStr = Properties.Resources._base.ToString();
string cssPath = System.IO.Directory.GetCurrentDirectory() + @"\static\css";
if (!Directory.Exists(cssPath))
Directory.CreateDirectory(cssPath);
File.WriteAllText(cssPath + @"\base.css", cssStr);
htmlData = htmlData.Replace("{CssPath}", cssPath + @"\base.css");
// 添加拖动图片的js
var jsDragStr = Properties.Resources.jquery_dad_min.ToString();
string jsDragPath = System.IO.Directory.GetCurrentDirectory() + @"\static\js";
if (!Directory.Exists(jsDragPath))
Directory.CreateDirectory(jsDragPath);
File.WriteAllText(jsDragPath + @"\jquery.dad.min.js", jsDragStr);
htmlData = htmlData.Replace("{JsDragPath}", jsDragPath + @"\jquery.dad.min.js");
// 设置无图默认图片
var imgNoPic = Properties.Resources.nopic;
string imgPath = System.IO.Directory.GetCurrentDirectory() + @"\static\img";
if (!Directory.Exists(imgPath))
Directory.CreateDirectory(imgPath);
imgNoPic.Save(imgPath + @"\nopic.jpg");
return htmlData;
}
//public string MeituPath = "C:\\Program Files (x86)\\Meitu\\XiuXiu\\XiuXiu.exe";
public string MeituPath = "";
/// <summary>
/// 设置美图秀秀或其他修图软件的位置
/// </summary>
public void setMeituPath()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
openFileDialog.Filter = "美图秀秀|*.exe";
openFileDialog.RestoreDirectory = true;
openFileDialog.FilterIndex = 1;
openFileDialog.ValidateNames = true;
openFileDialog.CheckPathExists = true;
openFileDialog.CheckFileExists = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var fileName = openFileDialog.FileName;
if (!File.Exists(fileName))
BaseMsgForm.ShowInfo("指定的文件无效!");
else
{
MeituPath = fileName;
saveMeiTuPath();
}
}
}
public void saveMeiTuPath()
{
string path = System.IO.Directory.GetCurrentDirectory() + @"\xiuxiu.ini";
FileBase.WriteAllText(path, MeituPath);
}
public void GetMeiTuPath()
{
string fileName = System.IO.Directory.GetCurrentDirectory() + @"\xiuxiu.ini";
if (File.Exists(fileName))
{
MeituPath = FileBase.ReadAllText(fileName);
}
}
private void buttonMeituPath_Click(object sender, EventArgs e)
{
if (MeituMessageDialog.ShowMessageDialog("请指定美图秀秀启动文件。\r\n如未安装美图秀秀,请下载。", "下载美图秀秀,指定启动文件") == "指定启动文件")
{
//// 单线程单元(STA)模式运行文件对话框,否则会报错。
//System.Threading.Thread InvokeThread = new System.Threading.Thread(new System.Threading.ThreadStart(setMeituPath));
//InvokeThread.SetApartmentState(System.Threading.ApartmentState.STA);
//InvokeThread.Start();
//InvokeThread.Join();
this.setMeituPath();
}
}
private void pbPaste_Click(object sender, EventArgs e)
{
BaseClass.SetClipboard(SourceTitlelabel.Text.Trim());
}
private void lklbChangeCatId_Click(object sender, EventArgs e)
{
//CatForm form = new CatForm(detailDataPcb);
//form.frmFission = this;
//form.ShowDialog();
}
public void ReloadShop()
{
cboxShop.Items.Clear();
foreach (var shop in GlobalConfig.ShopLoginList)
{
cboxShop.Items.Add(shop.ShopAccount);
}
if (cboxShop.Items.Count > 0)
cboxShop.SelectedIndex = 0;
}
private void cboxShop_SelectedIndexChanged(object sender, EventArgs e)
{
cboxCat1.Items.Clear();
cboxCat2.Items.Clear();//有的店铺没有一级、二级、三级类目,所以,更改店铺前要把一二三级类目全部清空 by ttzhao 2020.10.13
cboxCat3.Items.Clear();//有的店铺没有一级、二级、三级类目,所以,更改店铺前要把一二三级类目全部清空 by ttzhao 2020.10.13
dicNameCate.Clear();
string shopname = cboxShop.Text;
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(x => x.ShopAccount == shopname);
if (shop == null || shop.LstShopCategory == null)
{
return;
}
foreach (var cateId in shop.LstShopCategory)
{
var cate = GoodsCategories.FirstOrDefault(c => c.id == cateId);
if (cate == null)
continue;
dicNameCate[cate.name + cate.level] = cate;
if (cate.level == 1)
{
if (!cboxCat1.Items.Contains(cate.name))
{
cboxCat1.Items.Add(cate.name);
}
}
}
if (cboxCat1.Items.Count > 0)
cboxCat1.SelectedIndex = 0;
}
private void cboxCat1_SelectedIndexChanged(object sender, EventArgs e)
{
cboxCat2.Items.Clear();
var cat = dicNameCate[cboxCat1.SelectedItem.ToString() + "1"];
var cateList = dicNameCate.Values.Where(c => c.parent_id == cat.id).ToList();
foreach (var item in cateList)
{
cboxCat2.Items.Add(item.name);
}
if (cboxCat2.Items.Count > 0)
cboxCat2.SelectedIndex = 0;
}
private void cboxCat2_SelectedIndexChanged(object sender, EventArgs e)
{
cboxCat3.Items.Clear();
var cat = dicNameCate[cboxCat2.SelectedItem.ToString() + "2"];
var cateList = dicNameCate.Values.Where(c => c.parent_id == cat.id).ToList();
foreach (var item in cateList)
{
cboxCat3.Items.Add(item.name);
}
if (cboxCat3.Items.Count > 0)
cboxCat3.SelectedIndex = 0;
}
private void lblShop_Click(object sender, EventArgs e)
{
this.ReloadShop();
}
public static FissionShowBigImgForm sbi = null;
public string ShowBigImg(string src, string imgId)
{
src = Fission.RemovePrefix(src);
Invoke(new Action(() =>
{
if (sbi == null || !sbi.Created)
{
sbi = new FissionShowBigImgForm("http://" + src, imgId);
sbi.StartPosition = FormStartPosition.CenterScreen;
sbi.TopMost = true;
sbi.Show();
sbi.TopMost = false;
}
else
{
sbi.imgId = imgId;
sbi.imgUrl = "http://" + src;
sbi.ShowImg();
}
}));
return "ok";
}
private void btnSaveShopFlag_Click(object sender, EventArgs e)
{
var shopFlag = txtNewShopFlag.Text.Trim();
if (string.IsNullOrEmpty(shopFlag))
{
return;
}
foreach (string item in (List<string>)cmbShopFlag.DataSource)
{
if (item == shopFlag)
{
BaseMsgForm.ShowInfo("该标记已经存在。");
return;
}
}
//保存分组
string requestData = UserLogin.GetSignaturex() + "&act=add&data=" + GetHtml.UrlEncodeUtf8(shopFlag);
string url = BaseClass.BuildFissionObjString("category_api");
string result = GetHtml.PostUtf8(url, requestData);
JObject jObj = (JObject)JsonConvert.DeserializeObject(result);
//获取分组并刷新分组
if (!string.IsNullOrEmpty(result) && jObj["code"].ToString() == "0")
{
GetTeamGroupContent();
BaseMsgForm.ShowInfo("分组增加成功!");
this.pnlCancelShopFlag_Click(null, null);
}
}
/// <summary>
/// 获取商品的店铺标记/分组
/// </summary>
private void GetTeamGroupContent(string teamGroup = null)
{
try
{
string getRequestData = UserLogin.GetSignaturex() + "&act=get";
string getRrl = BaseClass.BuildFissionObjString("category_api");
string categoryResult = GetHtml.PostUtf8(getRrl, getRequestData);
JObject jCategoryObj = (JObject)JsonConvert.DeserializeObject(categoryResult);
//jCategoryObj["list"]
string categoryList = jCategoryObj["list"].ToString();
JArray jCategoryList = (JArray)JsonConvert.DeserializeObject(categoryList);
List<string> cateList = new List<string>();
cateList.Add("");
foreach (var category in jCategoryList)
{
if (category["cate_name"] == null)
continue;
cateList.Add(category["cate_name"].ToString());
}
cmbShopFlag.DataSource = cateList;
if (!string.IsNullOrEmpty(teamGroup))
cmbShopFlag.Text = teamGroup;
}
catch (Exception ex)
{
BaseMsgForm.ShowError("商品分组获取失败");
}
}
private void pnlAddShopFlag_Click(object sender, EventArgs e)
{
this.txtNewShopFlag.Visible = this.pnlSaveShopFlag.Visible = this.pnlCancelShopFlag.Visible = true;
//this.pnlAddShopFlag.Visible = this.cmbShopFlag.Visible = false;
}
private void pnlCancelShopFlag_Click(object sender, EventArgs e)
{
this.txtNewShopFlag.Visible = this.pnlSaveShopFlag.Visible = this.pnlCancelShopFlag.Visible = false;
//this.pnlAddShopFlag.Visible = this.cmbShopFlag.Visible = true;
}
private void fissionBrowserObject_InfomationReceived(string infomation)
{
try
{
string[] args = infomation.Split(':');
//transformimg_start
if (args[0] == "transformimg_start")
{
this.Invoke(new Action(() =>
{
// 以下写到template.html页面中的function TransformImg(id)方法内,防止线程卡死看不到效果
pnlMsg.Text = "正在抠图中...";
pnlMsg.Visible = true;
//var jsCode = "document.getElementById('spn_matting_status').innerHTML = '正在抠图中...';";
//Task<JavascriptResponse> task = browser.GetMainFrame().EvaluateScriptAsync(jsCode, null);
LastURLBtn.Enabled = false;//“切换到上一条”不可用
NextURLBtn.Enabled = false;//“切换到下一条”不可用
updateBtn.Enabled = false;//“提交上传”不可用
addToDBBtn.Enabled = false;//“添加入库”不可用
}));
}
//transformimg_end:ok:1
//transformimg_end:fail:无效cookies
if (args[0] == "transformimg_end")
{
this.Invoke(new Action(() =>
{
LastURLBtn.Enabled = true;//“切换到上一条”可用
NextURLBtn.Enabled = true;//“切换到下一条”可用
updateBtn.Enabled = true;//“提交上传”可用
addToDBBtn.Enabled = true;//“添加入库”可用
}));
if (args[1] == "fail")
{
this.Invoke(new Action(() =>
{
pnlMsg.Text = "抠图失败:" + args[2];
pnlMsg.Visible = true;
Task.Run(() => { Thread.Sleep(3000); Invoke(new Action(() => { pnlMsg.Visible = false; })); });
var jcode = "document.getElementById('spn_matting_status').innerHTML = '抠图失败:" + args[2] + "';";
Task<JavascriptResponse> task = browser.GetMainFrame().EvaluateScriptAsync(jcode, null);
}));
}
if (args[1] == "ok")
{
this.Invoke(new Action(() =>
{
pnlMsg.Text = "抠图成功";
pnlMsg.Visible = true;
Task.Run(() => { Thread.Sleep(3000); Invoke(new Action(() => { pnlMsg.Visible = false; })); });
var jcode = "document.getElementById('spn_matting_status').innerHTML = '抠图成功';";
Task<JavascriptResponse> task = browser.GetMainFrame().EvaluateScriptAsync(jcode, null);
}));
string imgId = args[2];
StringBuilder sb = new StringBuilder();
//修图
sb.Append("document.getElementById('OpenMeitu" + imgId + "').remove();");
//拉回
sb.Append("document.getElementById('PullImg" + imgId + "').remove();");
//编辑
sb.Append("document.getElementById('OpenEditTool" + imgId + "').remove();");
string jsCode = sb.ToString();
browser.GetMainFrame().EvaluateScriptAsync(jsCode, null);
}
}
Application.DoEvents();
}
catch { }
}
/// <summary>
/// 获取类别的层级关系
/// </summary>
/// <param name="cid"></param>
/// <returns></returns>
public static List<int> GetParentCatList(int cid)
{
List<int> catList = new List<int>();
catList.Add(cid);
int ccid = cid;
while (true)
{
var c = GoodsCategories.Find(x => x.id == ccid);
if (c == null || c.parent_id <= 0)
break;
catList.Insert(0, c.parent_id);
ccid = c.parent_id;
}
return catList;
}
/// <summary>
/// 获取完整类目名称
/// </summary>
/// <param name="cid"></param>
/// <returns></returns>
public static string GetFullCatString(int cid)
{
List<int> list = GetParentCatList(cid);
List<string> listName = new List<string>();
foreach (var id in list)
{
var c = GoodsCategories.Find(x => x.id == id);
if (c != null)
listName.Add(c.name);
}
return string.Join(">>", listName);
}
/// <summary>
/// 获取抖音店铺所有类目
/// </summary>
/// <returns></returns>
public static List<GoodsCategoryModel> GetShopGoodsCategories()
{
List<GoodsCategoryModel> list = NaiBa.Util.Helper.ConfigHelper.LoadConfig<List<GoodsCategoryModel>>("cat_dy");
if (list == null)
list = new List<GoodsCategoryModel>();
if (list.Count == 0 || GlobalConfig.ShopLoginList.Any(s => s.ApiAuthStatus == "授权成功" && (s.LstShopCategory == null || s.LstShopCategory.Count == 0)))
{
//list.Clear();
foreach (var shop in GlobalConfig.ShopLoginList)
{
if (shop.ApiAuthStatus == "授权成功")
{
List<GoodsCategoryModel> lstShopCategory = new List<GoodsCategoryModel>();
lstShopCategory.Add(new GoodsCategoryModel() { enable = false, id = 0, is_leaf = false, level = 0, name = "全部分类", parent_id = -1 });
DouyinApi api = new DouyinApi(shop);
var result = api.GetShopCategory(0);
if (result.Contains("已过期"))
{
shop.ApiAuthStatus = "未授权";
StartUp.SaveLocalShopLoginInfo();
continue;
}
for (int i = 0; i < lstShopCategory.Count; i++)
{
if (lstShopCategory[i].is_leaf)
continue;
if (i > 0)
{
api = new DouyinApi(shop);
retry:
result = api.GetShopCategory(lstShopCategory[i].id);
if (!result.Contains("\"code\":10000"))
goto retry;
}
var mc = BaseRegex.GetMatchRegex(ref result, "{([\\s\\S]*?)}");
foreach (Match m in mc)
{
string r = m.Value;
bool enable = BaseRegex.GetBoolJson(ref r, "enable");
bool is_leaf = BaseRegex.GetBoolJson(ref r, "is_leaf");
int level = BaseRegex.GetIntJson(ref r, "level");
int id = BaseRegex.GetIntJson(ref r, "id");
int parent_id = BaseRegex.GetIntJson(ref r, "parent_id");
string name = BaseRegex.GetStringJson(ref r, "name");
GoodsCategoryModel model = new GoodsCategoryModel()
{
enable = enable,
id = id,
is_leaf = is_leaf,
level = level,
name = name,
parent_id = parent_id
};
lstShopCategory.Add(model);
}
}
shop.LstShopCategory = lstShopCategory.Select(s => s.id).Where(id => id != 0).ToList(); // 店铺支持的类目Id
foreach (var cat in lstShopCategory)
{
if (cat.id != 0 && !list.Any(l => l.id == cat.id))
list.Add(cat);
}
}
}
}
if (list.Count == 0)
{
BaseMsgForm.ShowInfo("获取类目失败!");
}
StartUp.SaveLocalShopLoginInfo();
NaiBa.Util.Helper.ConfigHelper.SaveConfig("cat_dy", list);
return list;
}
public static string RemovePrefix(string url)
{
string xyz = url;
if (xyz == null)
return null;
if (xyz.StartsWith("https://"))
xyz = xyz.Substring("https://".Length);
if (xyz.StartsWith("http://"))
xyz = xyz.Substring("http://".Length);
if (xyz.StartsWith("//"))
xyz = xyz.Substring("//".Length);
if (xyz.StartsWith("/"))
xyz = xyz.Substring("/".Length);
return xyz;
}
List<string> GetMainImages()
{
List<string> images = new List<string>();
var jsCode = "function getProductMainImages() { return document.getElementById('main_image').innerHTML; } getProductMainImages();";
var task = browser.GetMainFrame().EvaluateScriptAsync(jsCode, null);
task.Wait(5000);
var result = task.Result.Result?.ToString();
if (!string.IsNullOrEmpty(result))
{
var valueMatches = AllBase.BaseRegex.GetMatchRegex(ref result, "src=\"([\\s|\\S]*?)\"");
if (valueMatches.Count > 0)
{
foreach (Match valueMatch in valueMatches)
{
var img = valueMatch.Groups[1].ToString();
if (!string.IsNullOrEmpty(img))
images.Add(img);
}
}
}
return images;
}
/// <summary>
/// 获取商品的详情图list
/// </summary>
/// <returns></returns>
List<string> GetContent()
{
var dictContent = new List<string>();
var task = browser.GetBrowser().MainFrame.GetSourceAsync();
task.Wait();
var html = task.Result;
var imgMatchs = AllBase.BaseRegex.GetMatchRegex(ref html, "class=\"content_group([\\w\\W]*?)</div>");
if (imgMatchs.Count > 0)
{
for (int i = 0; i < imgMatchs.Count; i++)
{
string s1 = imgMatchs[i].ToString();
//src=\"(.*?)\"
var mc = AllBase.BaseRegex.GetMatchRegex(s1, "src=\"(.*?)\" ");
List<string> content = new List<string>();
foreach (Match m in mc)
{
string imgUrl = m.Groups[1].Value;
content.Add(imgUrl);
}
// 添加分组间隔
if (content.Count > 0 && i > 0)
dictContent.Add("new_group");
dictContent.AddRange(content);
}
}
return dictContent;
}
List<PropBase> GetSkus()
{
var props = new List<PropBase>();
var taskGetProp = this.browser.GetBrowser().MainFrame.GetSourceAsync();
taskGetProp.Wait();
var taskResult = taskGetProp.Result;
var propMatches = AllBase.BaseRegex.GetMatchRegex(taskResult, "propstart-([\\s|\\S]*?)-propend");
if (propMatches.Count > 0)
{
foreach (Match propMatch in propMatches)
{
var propStr = propMatch.ToString();
PropBase propBase = JsonHelper.DeserializeJsonToObject<PropBase>(BaseRegex.GetMatchRegexString(propStr, "propstart-([\\s|\\S]*?)-propstartend"));
if (propBase != null)
{
propBase.Values = new List<PropValueBase>();
var valueMatches = AllBase.BaseRegex.GetMatchRegex(propStr, "propvaluestart-([\\s|\\S]*?)-propvalueend");
if (valueMatches.Count > 0)
{
foreach (Match valueMatch in valueMatches)
{
var valueStr = valueMatch.ToString();
var propValueBase = JsonHelper.DeserializeJsonToObject<PropValueBase>(
BaseRegex.GetMatchRegexString(valueStr, "propvaluestart-([\\s|\\S]*?)-propvaluestartend"));
var imageMatch = BaseRegex.GetMatchRegexString(valueStr, "propvalueimgstart-([\\s|\\S]*?)-propvalueimgend");
if (imageMatch != null)
{
imageMatch = BaseRegex.GetMatchRegexString(imageMatch, "src=\"([\\s|\\S]*?)\"");
if (imageMatch != null)
{
propValueBase.image = imageMatch;
propValueBase.image_from_url = imageMatch;
}
}
propBase.Values.Add(propValueBase);
}
}
props.Add(propBase);
}
}
}
return props;
}
/// <summary>
/// 获取自定属性
/// </summary>
/// <returns></returns>
private List<KeyValueBase> GetCustomProp()
{
List<KeyValueBase> kv = new List<KeyValueBase>();
foreach (var control in flpProp.Controls)
{
var cp = control as UcCategoryProp;
if (cp != null && !string.IsNullOrEmpty(cp.PropValue))
{
kv.Add(new KeyValueBase(cp.PropName, cp.PropValue));
if (cp.PropName == "品牌" && !string.IsNullOrEmpty(cp.PropBrandId))
{
kv.Add(new KeyValueBase("品牌编号", cp.PropBrandId));
}
}
}
return kv;
}
/// <summary>
/// 获取资质文件
/// </summary>
/// <returns></returns>
private List<quality_file> GetQualities()
{
List<quality_file> q = new List<quality_file>();
foreach (var c in flpQualification.Controls)
{
var cc = c as UcQualifiaction;
if (cc != null && cc.QualificationFile != null)
{
q.Add(cc.QualificationFile);
}
}
return q;
}
ProductCollectBase FissionDataModel2Pcb(FissionDataModel fissionDataModel)
{
// 是否调节价格 对应字段:ProductCollectBase.is_changeprice
// 加价倍数 对应字段:ProductCollectBase.addPricePercent
// 基础加价 对应字段:ProductCollectBase.baseAddPrice
// 拼团折扣 对应字段:ProductCollectBase.discount
if (fissionDataModel == null)
return null;
ProductCollectBase pcb = new ProductCollectBase();
// 是否是进化数据商品
pcb.isFission = true;
// 商品id
pcb.from_id = fissionDataModel.fession_id.ParseToLong();
// 销量
pcb.saleCount = fissionDataModel.sales.ParseToInt();
// 价格
pcb.price = fissionDataModel.price.ParseToDecimal();
// 原标题:不用修改
pcb.from_title = pcb.from_name = fissionDataModel.title;
// 修改后的标题
pcb.name = fissionDataModel.fessionTitle != null && fissionDataModel.fessionTitle.Count > 0 ? fissionDataModel.fessionTitle[0] : fissionDataModel.title;
// 裂变标题
pcb.fission_names = fissionDataModel.fessionTitle;
// 来源
pcb.from = fissionDataModel.source;
// 邮费金额
pcb.express_price = fissionDataModel.postFree.ParseToDecimal();
// 主图
pcb.Images = fissionDataModel.main_pic;
// 详情图
pcb.content = "";
foreach (var imgUrl in fissionDataModel.content_pic)
{
if (imgUrl == "new_group")
pcb.content += "<br/>";
else
pcb.content += $"<img src='{imgUrl}'>";
}
// 子分类id
pcb.cat_id = fissionDataModel.cate_id;
// 主分类id
pcb.main_cid = fissionDataModel.main_cate_id;
// 主分类名称
pcb.main_cat_name = fissionDataModel.mainCategory;
// 是否调节价格
pcb.is_changeprice = (fissionDataModel.adjustPrice == 1).ToString();
// 加价比例
pcb.addPricePercent = fissionDataModel.addPricePercent;
// 基础加价
pcb.baseAddPrice = fissionDataModel.baseAddPrice;
// 商品属性
pcb.Prop = JsonHelper.DeserializeJsonToList<KeyValueBase>(fissionDataModel.prop);
// 属性列表
pcb.Props = JsonHelper.DeserializeJsonToList<PropBase>(fissionDataModel.props);
// 折扣比例
pcb.discount = fissionDataModel.discount;
List<SkuMapBase> newSkus = new List<SkuMapBase>();
pcb.SkuMaps = JsonHelper.DeserializeJsonToList<SkuMapBase>(fissionDataModel.skus);
// pcb属性和sku匹配
foreach (var sku in pcb.SkuMaps)
{
bool has = true;
var skuNames = sku.name.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var skuName in skuNames)
{
var skuProp = skuName.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
if (skuProp.Length != 2)
{
has = false;
break;
}
var skuPropGroupName = skuProp[0];
var skuPropValue = skuProp[1];
if (!pcb.Props.Any(p => p.name == skuPropGroupName && p.Values.Any(v => v.name == skuPropValue)))
{
has = false;
break;
}
}
if (has)
newSkus.Add(sku);
}
pcb.SkuMaps = newSkus;
fissionDataModel.skus = JsonHelper.SerializeObject(newSkus); // sku
pcb.qualifications = JsonHelper.DeserializeJsonToList<quality_file>(fissionDataModel.qualifications);
if (pcb.from == "淘宝") pcb.from_site_id = 1;
else if (pcb.from == "拼多多") pcb.from_site_id = 2;
else if (pcb.from == "阿里巴巴" || pcb.from == "1688") pcb.from_site_id = 3;
else if (pcb.from == "京喜") pcb.from_site_id = 4;
else if (pcb.from == "微店") pcb.from_site_id = 6;
else if (pcb.from == "抖音") pcb.from_site_id = 7;
return pcb;
}
private void lklbChangeCatId_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
private void categoryLabel_SizeChanged(object sender, EventArgs e)
{
pnlShowCategoryList.Location = new Point(lblCategory.Location.X + lblCategory.Width, lblCategory.Location.Y);
}
private PanelEx pnlCategoryBox = null;
private void pnlShowCategoryList_Click(object sender, EventArgs e)
{
if (pnlShowCategoryList.Text == "▲")
{
if (pnlCategoryBox != null)
{
if (pnlCategoryBox.Controls.Count > 0)
pnlCategoryBox.Controls[0].Controls.Clear();
pnlCategoryBox.Visible = false;
}
pnlShowCategoryList.Text = "▼";
return;
}
if (!string.IsNullOrEmpty(fullCatStrings))
{
pnlShowCategoryList.Text = "▲";
JArray jArr = null;
if (!string.IsNullOrEmpty(fullCatStrings))
jArr = JArray.Parse(fullCatStrings);
var catStrTemp = fullCatStrings;
if (jArr != null && jArr.Count <= 1)
{
GetCategoryInfo(detailDataPcb, out fullCatStrings, false);
if (!string.IsNullOrEmpty(fullCatStrings))
jArr = JArray.Parse(fullCatStrings);
else
fullCatStrings = catStrTemp;
}
if (jArr != null && jArr.Count > 0)
{
ShowCategoryList(jArr);
}
}
}
void ShowCategoryList(JArray cateJArr)
{
if (pnlCategoryBox == null)
{
pnlCategoryBox = new DevComponents.DotNetBar.PanelEx();
pnlCategoryBox.Location = new Point(lblCategory.Location.X, lblCategory.Location.Y + lblCategory.Height);
pnlCategoryBox.Height = updateBtn.Location.Y - pnlCategoryBox.Location.Y + updateBtn.Height;
pnlCategoryBox.Width = pbPaste.Location.X - pnlCategoryBox.Location.X + pbPaste.Width;
pnlCategoryBox.Style.Border = eBorderType.SingleLine;
pnlCategoryBox.Style.BorderColor.Color = Color.FromArgb(210, 210, 210);
pnlCategoryBox.Padding = new System.Windows.Forms.Padding(1);
pnlCategoryBox.Style.BackColor1.Color = Color.White;
pnlCategoryBox.Style.BackColor2.Color = Color.White;
var pnlCategoryInnerBox = new Panel();
pnlCategoryInnerBox.Dock = DockStyle.Fill;
pnlCategoryInnerBox.AutoScroll = true;
pnlCategoryBox.Controls.Add(pnlCategoryInnerBox);
this.splitContainer3.Panel2.Controls.Add(pnlCategoryBox);
pnlCategoryBox.BringToFront();
List<Control> controlList = new List<Control>();
controlList.Add(this);
for (int i = 0; i < controlList.Count; i++)
{
foreach (Control c in controlList[i].Controls)
{
if (c == pnlShowCategoryList || c == pnlCategoryBox)
continue;
controlList.Add(c);
c.Click += C_Click;
}
}
}
pnlCategoryBox.Visible = true;
pnlCategoryBox.Controls[0].Controls.Clear();
int top = 0;
foreach (JObject catJObj in cateJArr.Reverse())
{
var fullCatString = JsonHelper.SerializeObject(catJObj);
var pnlCategory = new PanelEx();
pnlCategory.Dock = DockStyle.Top;
pnlCategory.Location = new Point(0, top);
pnlCategory.Tag = fullCatString;
pnlCategory.Height = 30;
pnlCategory.Text = (BaseRegex.GetStringJson(ref fullCatString, "first_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "second_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "third_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "fourth_name")).TrimEnd('>')/*.Replace("\\t", " ")*/;
if (fullCatString.Contains("\"industry_status\":0"))
pnlCategory.Style.ForeColor.Color = Color.FromArgb(0, 0, 0);
else
pnlCategory.Style.ForeColor.Color = Color.FromArgb(128, 128, 128);
pnlCategory.Style.BackColor1.Color = Color.Transparent;
pnlCategory.Style.BackColor2.Color = Color.Transparent;
pnlCategory.Style.BorderSide = DevComponents.DotNetBar.eBorderSide.Bottom;
pnlCategory.Style.Border = DevComponents.DotNetBar.eBorderType.SingleLine;
pnlCategory.Style.BorderColor.Color = Color.FromArgb(225, 225, 225);
pnlCategory.Click += PnlCategory_Click;
pnlCategoryBox.Controls[0].Controls.Add(pnlCategory);
top += 30;
}
}
private void C_Click(object sender, EventArgs e)
{
if (pnlCategoryBox.Visible == true)
pnlShowCategoryList_Click(null, null);
}
private void PnlCategory_Click(object sender, EventArgs e)
{
var fullCatString = (sender as PanelEx)?.Tag?.ToString();
if (!string.IsNullOrEmpty(fullCatString))
{
detailDataPcb.main_cid = BaseRegex.GetIntJson(ref fullCatString, "first_cid");
detailDataPcb.cat1 = BaseRegex.GetIntJson(ref fullCatString, "first_cid");
detailDataPcb.cat2 = BaseRegex.GetIntJson(ref fullCatString, "second_cid");
detailDataPcb.cat3 = BaseRegex.GetIntJson(ref fullCatString, "third_cid");
detailDataPcb.cat4 = BaseRegex.GetIntJson(ref fullCatString, "fourth_cid");
detailDataPcb.cat_id = detailDataPcb.cat4;
if (detailDataPcb.cat_id == 0)
detailDataPcb.cat_id = detailDataPcb.cat3;
if (detailDataPcb.cat_id == 0)
detailDataPcb.cat_id = detailDataPcb.cat2;
if (detailDataPcb.cat_id == 0)
detailDataPcb.cat_id = detailDataPcb.cat1;
lblCategory.Text = (BaseRegex.GetStringJson(ref fullCatString, "first_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "second_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "third_name") + ">>" +
BaseRegex.GetStringJson(ref fullCatString, "fourth_name")).Trim('>')/*.Replace("\\t", " ")*/;
}
pnlCategoryBox.Controls[0].Controls.Clear();
pnlCategoryBox.Visible = false;
pnlShowCategoryList.Text = "▼";
}
public void GetPropAndQualification()
{
string categoryText = "";
Invoke(new Action(() =>
{
flpProp.Controls.Clear();
flpQualification.Controls.Clear();
splitPage.Panel2Collapsed = true;
categoryText = this.lblCategory.Text;
}));
if (!string.IsNullOrEmpty(categoryText) && categoryText != "fenlei")
{
// 暂时属性/资质类编辑只针对食品饮料类目开放
if (!foodCate1Names.Any(f => categoryText.StartsWith(f)))
return;
var dyShop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ApiAuthStatus == "授权成功");
if (dyShop == null)
{
BaseMsgForm.ShowError("请确保至少有一个店铺授权成功!");
return;
}
// 必填属性
DouyinApi api = new DouyinApi(dyShop);
api.JsonData["category_leaf_id"] = detailDataPcb.cat_id.ToString();
var propResult = api.GetCatePropertyV2();
while (propResult.Contains("已过期"))
{
dyShop.ApiAuthStatus = "未授权";
StartUp.SaveLocalShopLoginInfo();
dyShop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ApiAuthStatus == "授权成功");
if (dyShop == null)
{
BaseMsgForm.ShowError("请确保至少有一个店铺授权成功!");
return;
}
api = new DouyinApi(dyShop);
api.JsonData["category_leaf_id"] = detailDataPcb.cat_id.ToString();
propResult = api.GetCatePropertyV2();
}
List<KeyValueBase> propList = new List<KeyValueBase>();
if (propResult.Contains("\"code\":10000"))
{
if (propResult.Contains("生产企业名称") || propResult.Contains("品牌"))
{
var propObjs = JObject.Parse(propResult)?["data"]?["data"];
if (propObjs != null)
{
foreach (JObject jObj in propObjs)
{
var propName = jObj["property_name"].ToString();
if (propName == null)
continue;
if (propName == "生产企业名称" || propName == "品牌")
{
var name = jObj["property_name"].ToString();
var value = detailDataPcb.Prop.FirstOrDefault(p => p.Key == name)?.Value;
if (value == null)
value = "";
UcCategoryProp ucCategoryProp = new UcCategoryProp() { Margin = new System.Windows.Forms.Padding(1, 3, 3, 3), };
ucCategoryProp.PropName = name;
ucCategoryProp.PropValue = value;
if (ucCategoryProp.PropName == "品牌")
{
ucCategoryProp.txtPropValue.ReadOnly = true;
ucCategoryProp.txtPropValue.Click += TxtPropBrandValue_Click;
var brandId = detailDataPcb.Prop.FirstOrDefault(p => p.Key == "品牌编号")?.Value;
if (!string.IsNullOrEmpty(brandId))
ucCategoryProp.PropBrandId = brandId;
}
if (!flpProp.Controls.Cast<Control>().Any(c => (c as UcCategoryProp)?.PropName == ucCategoryProp.PropName))
{
Invoke(new Action(() =>
{
this.flpProp.Controls.Add(ucCategoryProp);
}));
}
}
}
}
}
}
// 资质图片
api = new DouyinApi(dyShop);
api.JsonData["category_id"] = detailDataPcb.cat_id.ToString();
var qualityResult = api.GetQualificationConfig();
if (qualityResult != null && qualityResult.Contains("\"code\":10000"))
{
List<QualificationConfig> configList = new List<QualificationConfig>();
if (qualityResult.Contains("食品生产许可证"))
{
var configs = JObject.Parse(qualityResult)?["data"]?["config_list"]?.ToString();
if (configs != null)
{
configList = JsonHelper.DeserializeJsonToList<QualificationConfig>(configs);
configList = configList.Where(c => c.name == "包装标签图" || c.name == "食品生产许可证" || c.is_required).ToList();
}
}
else
{
var configs = JObject.Parse(qualityResult)?["data"]?["config_list"]?.ToString();
if (configs != null)
{
configList = JsonHelper.DeserializeJsonToList<QualificationConfig>(configs);
configList = configList.Where(c => c.is_required).ToList();
}
}
if (configList.Count > 0)
{
foreach (var config in configList)
{
UcQualifiaction ucQualifiaction = new UcQualifiaction() { Margin = new System.Windows.Forms.Padding(1, 3, 3, 3), };
ucQualifiaction.Qualification = config;
ucQualifiaction.QualificationFile = detailDataPcb.qualifications?.FirstOrDefault(q => q?.quality_key == config.key);
//ucQualifiaction.Location = new Point(10, y);
//y += ucQualifiaction.Height + 10;
Invoke(new Action(() =>
{
this.flpQualification.Controls.Add(ucQualifiaction);
}));
}
}
}
}
if (flpProp.Controls.Count > 0 || flpQualification.Controls.Count > 0)
{
Invoke(new Action(() =>
{
this.splitPage.Panel2Collapsed = false;
}));
}
}
string BrandBase = "";
private void TxtPropBrandValue_Click(object sender, EventArgs e)
{
var txt = sender as TextBox;
if (txt == null)
return;
if (pnlBrandBox == null || pnlBrandBox.Visible == false)
{
if (pnlBrandBox == null)
txt.TextChanged += TxtPropBrandValue_TextChanged;
BrandBase = txt.Text;
TxtPropBrandValue_TextChanged(txt, null);
txt.ReadOnly = false;
txt.SelectAll();
}
else
{
pnlBrandBox.Visible = false;
txt.Text = BrandBase;
txt.ReadOnly = true;
}
}
private PanelEx pnlBrandBox = null;
private void TxtPropBrandValue_TextChanged(object sender, EventArgs e)
{
var txt = sender as TextBox;
if (txt == null)
return;
foreach (var control in this.flpProp.Controls)
{
var ucCategoryProp = control as UcCategoryProp;
if (ucCategoryProp != null && ucCategoryProp.PropName == "品牌")
{
string result = "";
var textQuery = "";
while (result == "" || result.Contains("已过期"))
{
var dyShop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ApiAuthStatus == "授权成功");
if (dyShop == null)
{
BaseMsgForm.ShowError("请确保至少有一个店铺授权成功!");
return;
}
var api = new DouyinApi(dyShop);
api.JsonData["category_id"] = detailDataPcb.cat_id.ToString();
textQuery = txt.Text.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
api.JsonData["query"] = textQuery == null ? "" : textQuery; // "JIXIN/积鑫";
result = api.cateBrandList();
}
try
{
var jArr = JObject.Parse(result)["data"]["brand_list"] as JArray;
if (textQuery == "无品牌" && !result.Contains("\"无品牌\""))
jArr.Add(JObject.Parse("{\"brand_id\":596120136,\"name_cn\":\"无品牌\",\"name_en\":\"\"}"));
ShowBrandList(jArr, txt);
}
catch (Exception ex) { }
}
}
}
void ShowBrandList(JArray brandJArr, Control baseControl)
{
if (pnlBrandBox == null)
{
pnlBrandBox = new DevComponents.DotNetBar.PanelEx();
pnlBrandBox.Height = 200;
pnlBrandBox.Width = baseControl.Width;
pnlBrandBox.Style.Border = eBorderType.SingleLine;
pnlBrandBox.Style.BorderColor.Color = Color.FromArgb(210, 210, 210);
pnlBrandBox.Padding = new System.Windows.Forms.Padding(1);
pnlBrandBox.Style.BackColor1.Color = Color.White;
pnlBrandBox.Style.BackColor2.Color = Color.White;
var pnlBrandInnerBox = new Panel();
pnlBrandInnerBox.Dock = DockStyle.Fill;
pnlBrandInnerBox.AutoScroll = true;
pnlBrandBox.Controls.Add(pnlBrandInnerBox);
this.splitPage.Panel2.Controls.Add(pnlBrandBox);
pnlBrandBox.BringToFront();
List<Control> controlList = new List<Control>();
controlList.Add(this);
for (int i = 0; i < controlList.Count; i++)
{
foreach (Control c in controlList[i].Controls)
{
if (c == pnlBrandBox || c == baseControl)
continue;
controlList.Add(c);
c.Click += ControlBrand_Click;
}
}
}
var yPos = baseControl.Location.Y;
var control = baseControl;
while (control.Parent != this.flowLayoutPanel1)
{
control = control.Parent;
yPos += control.Location.Y;
}
pnlBrandBox.Location = new Point(baseControl.Location.X + 4, yPos + baseControl.Height);
pnlBrandBox.Visible = true;
pnlBrandBox.BringToFront();
pnlBrandBox.Controls[0].Controls.Clear();
int top = 0;
foreach (JObject brandJObj in brandJArr.Reverse())
{
var fullBrandString = JsonHelper.SerializeObject(brandJObj);
var pnlBrandChild = new PanelEx();
pnlBrandChild.Dock = DockStyle.Top;
pnlBrandChild.Location = new Point(0, top);
pnlBrandChild.Tag = fullBrandString;
pnlBrandChild.Height = 30;
pnlBrandChild.Text = (BaseRegex.GetStringJson(ref fullBrandString, "name_en") + "/" +
BaseRegex.GetStringJson(ref fullBrandString, "name_cn")).Trim('/');
pnlBrandChild.Style.ForeColor.Color = Color.FromArgb(0, 0, 0);
pnlBrandChild.Style.BackColor1.Color = Color.Transparent;
pnlBrandChild.Style.BackColor2.Color = Color.Transparent;
pnlBrandChild.Style.BorderSide = DevComponents.DotNetBar.eBorderSide.Bottom;
pnlBrandChild.Style.Border = DevComponents.DotNetBar.eBorderType.SingleLine;
pnlBrandChild.Style.BorderColor.Color = Color.FromArgb(225, 225, 225);
pnlBrandChild.Click += PnlBrand_Click;
pnlBrandBox.Controls[0].Controls.Add(pnlBrandChild);
top += 30;
}
}
private void ControlBrand_Click(object sender, EventArgs e)
{
try
{
foreach (var control in this.flpProp.Controls)
{
var ucCategoryProp = control as UcCategoryProp;
if (ucCategoryProp != null && ucCategoryProp.PropName == "品牌")
{
ucCategoryProp.txtPropValue.Text = BrandBase;
}
}
pnlBrandBox.Controls[0].Controls.Clear();
pnlBrandBox.Visible = false;
}
catch (Exception ex) { }
}
private void PnlBrand_Click(object sender, EventArgs e)
{
var fullBrandString = (sender as PanelEx)?.Tag?.ToString();
if (!string.IsNullOrEmpty(fullBrandString))
{
foreach (var control in this.flpProp.Controls)
{
var ucCategoryProp = control as UcCategoryProp;
if (ucCategoryProp != null && ucCategoryProp.PropName == "品牌")
{
ucCategoryProp.txtPropValue.TextChanged -= TxtPropBrandValue_TextChanged;
ucCategoryProp.txtPropValue.Text = (BaseRegex.GetStringJson(ref fullBrandString, "name_en") + "/" +
BaseRegex.GetStringJson(ref fullBrandString, "name_cn")).Trim('/');
BrandBase = ucCategoryProp.txtPropValue.Text;
ucCategoryProp.PropBrandId = BaseRegex.GetStringJson(ref fullBrandString, "brand_id");
ucCategoryProp.txtPropValue.TextChanged += TxtPropBrandValue_TextChanged;
pnlBrandBox.Controls[0].Controls.Clear();
pnlBrandBox.Visible = false;
}
}
}
}
private void btnLoadLastSetting_Click(object sender, EventArgs e)
{
foreach (var control in this.flpProp.Controls)
{
var ucCategoryProp = control as UcCategoryProp;
if (ucCategoryProp != null)
{
var prop = sCustomPropList.FirstOrDefault(p => p.Key == ucCategoryProp.PropName);
if (prop != null)
{
ucCategoryProp.txtPropValue.Text = prop.Value;
if (ucCategoryProp.PropName == "品牌")
{
prop = sCustomPropList.FirstOrDefault(p => p.Key == "品牌编号");
if (prop != null)
{
ucCategoryProp.PropBrandId = prop.Value;
}
}
}
}
}
foreach (var control in this.flpQualification.Controls)
{
var ucQualifiaction = control as UcQualifiaction;
if (ucQualifiaction != null)
{
var qualifyFile = sQulityFileList.FirstOrDefault(q => q.quality_name == ucQualifiaction.Qualification.name);
if (qualifyFile != null)
{
ucQualifiaction.QualificationFile = qualifyFile;
ucQualifiaction.ShowQualification();
}
}
}
}
private void Fission_FormClosed(object sender, FormClosedEventArgs e)
{
//CleanDataForm.LstFissionForm.Remove(this);
}
private void btnShowOriginal_Click(object sender, EventArgs e)
{
CollectProductInfoAndShowBrowser(currentRowIndex, true);
}
private void lklbResetShop_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.cmbGetCatShop.Items.Clear();
this.cmbGetCatShop.Items.Add(new ComboBoxItem() { Name = "随机选择", Text = "随机选择" });
foreach (var shop in GlobalConfig.ShopLoginList)
{
cmbGetCatShop.Items.Add(new ComboBoxItem() { Name = shop.ShopId, Text = shop.ShopAccount + (shop.LoginStatus == "登录成功" ? "" : " 未登录") });
}
this.cmbGetCatShop.SelectedIndex = 0;
}
private void btnCatchWords_Click(object sender, EventArgs e)
{
KeywordsCatchFrom keywordsCatchFrom = new KeywordsCatchFrom() { fission = this };
keywordsCatchFrom.Show();
}
public void ChangeFissionTitle(string titles)
{
this.txtTitle.Text = titles.Replace(";", "\r\n");
}
public void MulitAddMainImageWithCatchWords(List<string> imageList)
{
foreach (var url in imageList)
{
var jsStr = "AddImageUrl('" + url + "');";
var t1 = browser.GetMainFrame().EvaluateScriptAsync(jsStr);
t1.Wait();
}
}
public void MulitAddContentImageWithCatchWords(List<string> imageList)
{
var id = Randomx.GetId(10000000, 99999999);
var contentGroupId = "content_group" + id;
var contentSelectId = "content_select" + id;
foreach (var url in imageList)
{
var jsStr = "AddContent('" + url + "', '" + contentSelectId + "', '" + contentGroupId + "');";
var t1 = browser.GetMainFrame().EvaluateScriptAsync(jsStr);
t1.Wait();
}
}
}
}