Files
KJD_WebService/TEMUKJD/KJDForms/ProductForms/JoinDeliveryFrom.cs
T

456 lines
19 KiB
C#

using AllBase;
using AllBase.Helper;
using AllBase.Model.Result;
using NaiBa.Util.Extension;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TemuKJD.BaseForms;
using TemuKJD.BLL;
using TemuKJD.Extension;
using TemuKJD.KJDForms.AdminForms;
using TemuKJD.KJDForms.ShopForms;
using Work;
namespace TemuKJD.KJDForms.ProductForms
{
public partial class JoinDeliveryFrom : Form
{
JoinDeliveryConfig joinDeliveryConfig = null;
public bool IsAdmin = false;
public CancellationTokenSource cancellationTokenSource { get; set; } = null;
public List<ShopLoginInfo> lstAdminShopInfo { get; set; } = new List<ShopLoginInfo>();
/// <summary>
/// 备货单列表
/// </summary>
List<TemuStockInfo> lstStockInfo = new List<TemuStockInfo>();
public JoinDeliveryFrom()
{
InitializeComponent();
}
private void JoinDeliveryFrom_Load(object sender, EventArgs e)
{
ucSplitPage1.Visible = IsAdmin;
dgvShop.AddSelectorColumn("colSelect");
dgvStock.AddSelectorColumn("colCheck");
dgvStock.AddImgColumn("colProductSkcPic", "colImgUrl");
joinDeliveryConfig = NaiBa.Util.Helper.ConfigHelper.LoadConfig<JoinDeliveryConfig>("join_delivery_config");
if (joinDeliveryConfig == null)
joinDeliveryConfig = new JoinDeliveryConfig();
this.txtNotes.Text = joinDeliveryConfig.SearchNotes;
this.txtShopId.Text = joinDeliveryConfig.SearchShopId;
this.txtShopName.Text = joinDeliveryConfig.SearchShopName;
this.txtRetryInterval.Text = Math.Max(1, joinDeliveryConfig.RetryInterval).ParseToString();
this.chkSearchAllShop.Checked = joinDeliveryConfig.SearchAllShop;
this.txtNotes.TextChanged += Txt_TextChanged;
this.txtShopId.TextChanged += Txt_TextChanged;
this.txtShopName.TextChanged += Txt_TextChanged;
this.txtRetryInterval.TextChanged += Txt_TextChanged;
this.chkSearchAllShop.CheckedChanged += Txt_TextChanged;
}
private void Txt_TextChanged(object sender, EventArgs e)
{
joinDeliveryConfig.SearchNotes = this.txtNotes.Text.Trim();
joinDeliveryConfig.SearchShopId = this.txtShopId.Text.Trim();
joinDeliveryConfig.SearchShopName = this.txtShopName.Text.Trim();
joinDeliveryConfig.RetryInterval = Math.Max(1, this.txtRetryInterval.Text.Trim().ParseToInt());
joinDeliveryConfig.SearchAllShop = this.chkSearchAllShop.Checked;
NaiBa.Util.Helper.ConfigHelper.SaveConfig("join_delivery_config", joinDeliveryConfig);
}
private void JoinDeliveryFrom_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
if (IsAdmin)
{
SearchShop(this.ucSplitPage1.CurrentPage);
}
}
}
private void ucSplitPage1_PageChange(object obj)
{
if (IsAdmin)
{
if (this.ucSplitPage1.CurrentPage != 1)
this.ucSplitPage1.CurrentPage = 1;
else
SearchShop(1);
}
}
public void SearchShop(int page)
{
List<string> userShopIdList = dgvShop.Rows.Cast<DataGridViewRow>()
.Where(r => r.Cells["colSelect"].Value.ParseToBool())
.Select(r => r.Cells["colShopId"].Value.ParseToString() + r.Cells["colUser"].Value.ParseToString()).ToList();
Invoke(new Action(() =>
{
this.pbShopLoading.Visible = true;
this.dgvShop.Rows.Clear();
lstAdminShopInfo.Clear();
}));
Task.Run(() =>
{
int pageCount;
var list = AdminGetServerShopLst(out pageCount, page);
lstAdminShopInfo.AddRange(list);
this.ucSplitPage1.TotalPage = pageCount;
foreach (var shop in lstAdminShopInfo)
{
bool canUse = shop.LoginStatus2 == "国际版在线";
Invoke(new Action(() =>
{
int rowIndex = this.dgvShop.Rows.Add(
userShopIdList.Contains(shop.ShopId + shop.UserName),
shop.UserName,
shop.LoginName,
shop.ShopId,
shop.ShopAccount,
shop.Notes,
canUse ? "在线" : "掉线",
canUse,
string.Empty
);
displayShopStatus(shop);
}));
}
Invoke(new Action(() =>
{
this.pbShopLoading.Visible = false;
}));
});
}
void displayShopStatus(ShopLoginInfo shop)
{
bool canUse = shop.LoginStatus2 == "国际版在线";
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colLoginName"].Value.ParseToString() == shop?.LoginName);
foreach (var row in rows)
{
row.Cells["colCanUse"].Value = canUse;
row.Cells["colLoginStatus"].Value = canUse ? "在线" : "掉线";
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).Style.ForeColor = canUse ? Color.Green : Color.Red;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).LinkColor = canUse ? Color.Green : Color.Red;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).ActiveLinkColor = canUse ? Color.LightGreen : Color.OrangeRed;
(row.Cells["colLoginStatus"] as DataGridViewLinkCell).VisitedLinkColor = canUse ? Color.DarkGreen : Color.DarkRed;
}
}
public List<ShopLoginInfo> AdminGetServerShopLst(out int pageCount, int page = 1, int pageSize = 50)
{
List<ShopLoginInfo> list = new List<ShopLoginInfo>();
pageCount = 1;
var url = BaseClass.BuildObjString("shop/admin_get_shop_list");
//if (BaseClass.SaLevel > 1 && !chkSearchAllShop.Checked)
// url = BaseClass.BuildObjString("shop/sub_sa_get_select_prod_shop");
var data = UserLogin.GetSignaturex() +
"&page=" + page +
"&page_size=" + pageSize +
"&shop_ids=" + txtShopId.Text.Trim().Trim(',') +
"&shop_names=" + txtShopName.Text.Trim().Trim(',') +
"&search_notes=" + txtNotes.Text.Trim().Trim(',');
//if (BaseClass.SaLevel > 1 && !chkSearchAllShop.Checked)
// data += "&operate_sub_sa_name=" + BaseClass.UserName;
var html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html)
|| !html.Contains("shop_id") || !html.Contains("shop_account") || !html.Contains("login_pass"))
{
return list;
}
int count = BaseRegex.GetIntJson(ref html, "count");
pageCount = Math.Ceiling(1.0 * count / pageSize).ParseToInt();
pageCount = Math.Max(pageCount, 1);
return ShopBLL.DeserializationShop(html);
}
private void btnRefreshShop_Click(object sender, EventArgs e)
{
if (this.ucSplitPage1.CurrentPage != 1)
this.ucSplitPage1.CurrentPage = 1;
else
SearchShop(1);
}
private void btnEmpty_Click(object sender, EventArgs e)
{
txtNotes.Text = txtShopId.Text = txtShopName.Text = "";
}
private void btnSearch_Click(object sender, EventArgs e)
{
var lstShopId = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList();
if (lstShopId.Count == 0)
{
BaseMsgForm.ShowInfo("请选择店铺!");
return;
}
var columns = this.dgvStock.Columns.Cast<DataGridViewColumn>();
foreach (var col in columns)
{
if (col.Name == "colParentStockId" || col.Name == "colStockId")
{
col.Visible = true;
}
if (col.Name == "colTodaySaleVolume" || col.Name == "colLastSevenDaysSaleVolume" || col.Name == "colInCartNumber7d" || col.Name == "colSalesInventoryNum"
|| col.Name == "colWaitReceiveNum" || col.Name == "colNeedStockUp" || col.Name == "colQualityScore")
{
col.Visible = false;
}
}
lstStockInfo.Clear();
dgvStock.Rows.Clear();
var dgvRows = this.dgvShop.Rows.Cast<DataGridViewRow>();//.Where(r => lstShopId.Contains(r.Cells["colShopId"].Value.ParseToString()));
foreach (var row in dgvRows)
{
row.Cells["colMessage"].Value = "";
}
ucGroupBoxEx3.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
var lstShopIdTemp = new List<string>();
lstShopIdTemp.AddRange(lstShopId);
int i = 0;
foreach (var shopId in lstShopIdTemp)
{
this.Invoke(new Action(() =>
{
this.statusBar.lblTaskStatus.Text = "正在查询...";
this.statusBar.pgbTaskProgress.Maximum = lstShopIdTemp.Count;
this.statusBar.UpdateProgressBar(i + 1);
i++;
}));
if (cancellationTokenSource.IsCancellationRequested)
break;
ShopLoginInfo shop = null;
if (IsAdmin)
{
shop = this.lstAdminShopInfo.FirstOrDefault(s => s.ShopId == shopId);
}
else
{
shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
}
if (shop == null)
continue;
#region 检测登录
if (shop.LoginStatus != "登录成功")
{
continue;
}
if(IsAdmin)
{
AdminShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
}
else
{
ShopListForm.Instance.CheckShopLogin(new string[] { shop.LoginName }, false);
}
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() =>
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colShopLoginName"].Value.ToString() == shop.LoginName);
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "店铺掉线";
row.Cells["colLoginStatus"].Value = "未登录";
row.Cells["colCanUse"].Value = false;
}
}));
continue;
}
#endregion
Invoke(new Action(() =>
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId);
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "正在查询";
}
}));
int page = 1;
int totalPage = 1;
int pageSize = 20;
bool isError = false;
while (page <= totalPage)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
Thread.Sleep(100 + Randomx.GetId(200));
string jsonStr = GetShopStockList2(shop, page, pageSize);
if (jsonStr.Contains("指定的值含有无效的控制字符"))
{
BaseMsgForm.ShowError("店铺" + shop.LoginName + " " + shop.ShopId + "已掉线");
isError = true;
break;
}
if (!jsonStr.Contains("\"success\":true"))
jsonStr = GetShopStockList2(shop, page, pageSize);
if (!jsonStr.Contains("\"success\":true"))
{
isError = true;
}
if (jsonStr.Contains("\"success\":true"))
{
var jArr = new JArray();
try
{
var jObj = JObject.Parse(jsonStr);
jArr = jObj["result"]?["subOrderForSupplierList"] as JArray;
if (jArr == null)
jArr = new JArray();
}
catch (Exception ex) { BaseMsgForm.ShowError(ex.Message); }
foreach (var item in jArr)
{
string sItem = item.ToString();
TemuStockInfo sInfo = JsonHelper.DeserializeJsonToObject<TemuStockInfo>(sItem); // 反序列化得到类
if (sInfo != null)
{
lstStockInfo.Add(sInfo);
Invoke(new Action(() =>
{
int rowId = this.dgvStock.Rows.Add(
"",
true,
sInfo.supplierId,
sInfo.supplierName,
sInfo.subPurchaseOrderSn,
sInfo.originalPurchaseOrderSn,
sInfo.productSkcPicture.Replace("https", "http"),
DataGridViewExtension.defaultBitmap,
sInfo.productId,
sInfo.productSkcId,
sInfo.productName,
"",
"",
"",
"",
"",
"",
0.0,
"",
""
);
dgvStock.Rows[rowId].Height = 60;
}));
}
}
int total = BaseRegex.GetStringJson(ref jsonStr, "total").ParseToInt();
totalPage = Math.Ceiling(1.0m * total / pageSize).ParseToInt();
}
page++;
}
Invoke(new Action(() =>
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId);
if (!isError)
{
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "已查询";
}
}
else
{
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "查询失败";
}
}
}));
}
Invoke(new Action(() =>
{
ucGroupBoxEx3.Enabled = true;
string sRst = "查询结束!";
if (cancellationTokenSource.IsCancellationRequested)
sRst = "已取消查询!";
BaseMsgForm.ShowInfo(sRst);
this.statusBar.lblTaskStatus.Text = sRst;
}));
}, cancellationTokenSource.Token);
}
/// <summary>
/// 读取待加入发货台
/// </summary>
/// <param name="shop"></param>
/// <param name="page"></param>
/// <returns></returns>
private string GetShopStockList2(ShopLoginInfo shop, int page = 1, int pageSize = 20)
{
page = Math.Max(page, 1);
string url = "https://agentseller.temu.com/mms/venom/api/supplier/purchase/manager/querySubOrderList";
string body;
body = @"{""pageNo"":" + page + @",""pageSize"":" + pageSize + @",""urgencyType"":0,""isCustomGoods"":false,""statusList"":[1]," +
@"""oneDimensionSort"":{""firstOrderByParam"":""expectLatestDeliverTime"",""firstOrderByDesc"":0}}";
string refere = "https://agentseller.temu.com/stock/fully-mgt/order-manage";
return HttpResponseBLL.PostResponse2(shop, url, body, refere);
}
}
public class JoinDeliveryConfig
{
public string SearchShopId { get; set; } = "";
public string SearchShopName { get; set; } = "";
public string SearchNotes { get; set; } = "";
/// <summary>
/// 重试加入发货台的时间间隔
/// </summary>
public int RetryInterval { get; set; } = 1;
public bool SearchAllShop { get; set; } = true;
}
}