Files
KJD_WebService/TEMUKJD/KJDForms/JITForms/JitPushOrder.cs
T

1980 lines
96 KiB
C#

using AllBase;
using AllBase.Helper;
using AllBase.Model.Result;
using NaiBa.Util;
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.ProductForms;
using TemuKJD.KJDForms.ShopForms;
using TemuKJD.KJDForms.ShopForms.Statistics;
using TemuKJD.ToolForms;
using Work;
namespace TemuKJD.KJDForms.JITForms
{
public partial class JitPushOrder : BaseForm
{
public bool IsClientJit { get; set; } = false;
public CancellationTokenSource cancellationTokenSource { get; set; } = null;
public ConcurrentList<ShopLoginInfo> lstAdminShopInfo { get; set; } = new ConcurrentList<ShopLoginInfo>();
public ConcurrentList<TemuDBOrderInfo> lstTemuDBOrderInfo { get; set; } = new ConcurrentList<TemuDBOrderInfo>();
public ConcurrentList<subOrderForSupplier> lstOrderForSupplierInfo = new ConcurrentList<subOrderForSupplier>();
public ConcurrentList<CateSizeWeightConfig> lstCateSizeWeightConfig = new ConcurrentList<CateSizeWeightConfig>();
public Bitmap defaultBitmap = new Bitmap(1, 1);
int indexId = 0;
string indexOrderSn = "";
/// <summary>
/// 界面参数配置
/// </summary>
SetJitConfig jitPushOrderConfig = null;
CheckBox chkSelectAll;
public JitPushOrder()
{
InitializeComponent();
}
private void JitPushOrder_Load(object sender, EventArgs e)
{
//if (BaseClass.Mobile == "15288888888")
//{
// btnRestoreSizeAndNumber.Visible = true;
//}
if (!IsClientJit)
{
ucSplitPage1.Visible = true;
//btnGetDbOrder.Visible = true;
btnGetDbOrder.Text = "拉取已上传订单";
pnlGetNewOrder.Visible = false;
pnlStatistics.Visible = false;
colJitStatus.Visible = false;
dgvShop.Columns["colOrderToday"].Visible = false;
dgvShop.Columns["colOrder7days"].Visible = false;
splitContainer2.SplitterDistance = 320;
}
else
{
ucSplitPage1.Visible = false;
//btnGetDbOrder.Visible = false;
btnGetDbOrder.Text = "刷新已读取订单";
pnlGetNewOrder.Visible = true;
pnlStatistics.Visible = true;
}
splitContainer4.SplitterDistance = splitContainer2.SplitterDistance - 4;
lblNextGetTime.Text = "";
chkSelectAll = dgvShop.Columns["colSelect"].AddHeaderCheckBox(HorizontalAlignment.Center, 0, 0, null, null, false, null, true);
chkSelectAll.CheckedChanged += chkSelectAll_CheckedChanged;
dgvStock.AddImgColumn("colProductSkcPic", "colImgUrl");
dgvStock.AddImgColumn("colSkuImg", "colSkuImgUrl");
this.dtpEndTime.Value = DateTime.Now.Date.AddDays(1).AddMilliseconds(-1);
this.dtpStartTime.Value = DateTime.Now.Date.AddDays(-7);
if (!IsClientJit)
jitPushOrderConfig = NaiBa.Util.Helper.ConfigHelper.LoadConfig<SetJitConfig>("admin_jit_push_order_config");
else
jitPushOrderConfig = NaiBa.Util.Helper.ConfigHelper.LoadConfig<SetJitConfig>("jit_push_order_config");
if (jitPushOrderConfig == null)
jitPushOrderConfig = new SetJitConfig();
this.txtNotes.Text = jitPushOrderConfig.SearchNotes;
this.txtShopId.Text = jitPushOrderConfig.SearchShopId;
this.txtShopName.Text = jitPushOrderConfig.SearchShopName;
this.chkSearchAllShop.Checked = jitPushOrderConfig.SearchAllShop;
this.txtSpuId.Text = jitPushOrderConfig.SearchSpuId;
this.txtSkcId.Text = jitPushOrderConfig.SearchSkcId;
this.txtExtCode.Text = jitPushOrderConfig.SearchExtCode;
this.chkSearchTime.Checked = jitPushOrderConfig.SearchDuration;
this.txtNotes.TextChanged += Txt_TextChanged;
this.txtShopId.TextChanged += Txt_TextChanged;
this.txtShopName.TextChanged += Txt_TextChanged;
this.chkSearchAllShop.CheckedChanged += Txt_TextChanged;
this.txtSpuId.TextChanged += Txt_TextChanged;
this.txtExtCode.TextChanged += Txt_TextChanged;
this.chkSearchTime.CheckedChanged += Txt_TextChanged;
lblAuthorizedAmount.Text = "" + BaseClass.AuthorizedAmount.ParseToDecimal().ToString("0.0");
if (IsClientJit)
btnGetDbOrder_Click(null, null);
}
private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
if (!chkSelectAll.Checked)
{
foreach (DataGridViewRow row in dgvShop.Rows)
{
row.Cells["colSelect"].Value = false;
}
}
else
{
var list = lstAdminShopInfo.Where(s => s.LoginStatus2 == "国际版在线").ToList();
if (IsClientJit)
list = GlobalConfig.ShopLoginList.Where(s => s.LoginStatus2 == "国际版在线" && s.jit_expire_time >= DateTime.Now.Date).ToList();
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (list.Any(l => l.ShopId == row.Cells["colShopId"]?.Value?.ToString()))
row.Cells["colSelect"].Value = true;
}
}
}
private void Txt_TextChanged(object sender, EventArgs e)
{
jitPushOrderConfig.SearchNotes = this.txtNotes.Text.Trim();
jitPushOrderConfig.SearchShopId = this.txtShopId.Text.Trim();
jitPushOrderConfig.SearchShopName = this.txtShopName.Text.Trim();
jitPushOrderConfig.SearchAllShop = this.chkSearchAllShop.Checked;
jitPushOrderConfig.SearchSpuId = this.txtSpuId.Text.Trim();
jitPushOrderConfig.SearchSkcId = this.txtSkcId.Text.Trim();
jitPushOrderConfig.SearchExtCode = this.txtExtCode.Text.Trim();
jitPushOrderConfig.SearchDuration = this.chkSearchTime.Checked;
if (!IsClientJit)
NaiBa.Util.Helper.ConfigHelper.SaveConfig("admin_jit_push_order_config", jitPushOrderConfig);
else
NaiBa.Util.Helper.ConfigHelper.SaveConfig("jit_push_order_config", jitPushOrderConfig);
}
private void JitPushOrder_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
if (!IsClientJit)
{
//this.pbShopLoading.Visible = true;
SearchShop(this.ucSplitPage1.CurrentPage);
}
else
{
RefreshShop();
}
}
}
private void btnRefreshShop_Click(object sender, EventArgs e)
{
if (!IsClientJit)
{
if (this.ucSplitPage1.CurrentPage != 1)
this.ucSplitPage1.CurrentPage = 1;
else
SearchShop(1);
}
else
{
RefreshShop();
}
}
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,
string.Empty,
string.Empty
);
displayShopStatus(shop);
}));
}
Invoke(new Action(() =>
{
this.pbShopLoading.Visible = false;
}));
});
}
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 RefreshShop()
{
// 店铺Id
var selectIds = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> row.Cells["colSelect"]?.Value.ParseToBool() == true).Select(r => r.Cells["colShopId"]?.Value.ToString()).ToList();
var shopLst = GlobalConfig.ShopLoginList.ToList();
if (!string.IsNullOrWhiteSpace(txtShopId.Text.Trim()))
{
shopLst = shopLst.Where(s => ("," + txtShopId.Text.Trim() + ",").Contains("," + s.ShopId + ",") || s.ShopId.Contains(txtShopId.Text.Trim())).ToList();
}
if (!string.IsNullOrWhiteSpace(txtShopName.Text.Trim()))
{
shopLst = shopLst.Where(s => ("," + txtShopName.Text.Trim() + ",").Contains("," + s.ShopAccount + ",") || s.ShopAccount.ToLower().Contains(txtShopName.Text.Trim().ToLower())).ToList();
}
if (!string.IsNullOrWhiteSpace(txtNotes.Text.Trim()))
{
shopLst = shopLst.Where(s => ("," + txtNotes.Text.Trim() + ",").Contains("," + s.Notes + ",") || s.Notes.ToLower().Contains(txtNotes.Text.Trim().ToLower())).ToList();
}
// 获取被删除的店铺
List<DataGridViewRow> dgvRowList = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> !shopLst.Any(s => s.ShopId == row.Cells["colShopId"]?.Value?.ToString())).ToList();
// 更新被删除的店铺列表
foreach (var row in dgvRowList)
{
dgvShop.Rows.Remove(row);
}
// 绑定其他店铺(含新导入的店铺)
foreach (ShopLoginInfo shopEntity in shopLst)
{
if (!string.IsNullOrEmpty(shopEntity.ShopId))
BindShop(shopEntity, selectIds);
}
}
private void BindShop(ShopLoginInfo shopEntity, List<string> selectShopId = null)
{
if (shopEntity == null)
return;
if (selectShopId == null)
selectShopId = new List<string>();
bool canUse = shopEntity.LoginStatus2 == "国际版在线";
var row = dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(p => p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == shopEntity.ShopId);
if (row == null)
{
int id = this.dgvShop.Rows.Add(
selectShopId.Contains(shopEntity.ShopId) && canUse,
shopEntity.UserName,
shopEntity.LoginName,
shopEntity.ShopId,
shopEntity.ShopAccount,
shopEntity.Notes,
canUse ? "在线" : "掉线",
shopEntity.jit_expire_time >= DateTime.Now.Date ? "可用" : "失效",
canUse,
string.Empty
);
displayShopStatus(shopEntity);
}
else
{
row.Cells["colSelect"].Value = selectShopId.Contains(shopEntity.ShopId) && canUse;
row.Cells["colLoginName"].Value = shopEntity.LoginName;
row.Cells["colShopName"].Value = shopEntity.ShopAccount;
row.Cells["colShopNotes"].Value = shopEntity.Notes;
row.Cells["colLoginStatus"].Value = canUse ? "在线" : "掉线";
displayShopStatus(shopEntity);
}
}
private void dgvShop_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvShop.Columns[e.ColumnIndex].HeaderText;
string loginName = dgvShop.Rows[e.RowIndex].Cells["colLoginName"].Value.ParseToString();
string accountId = dgvShop.Rows[e.RowIndex].Cells["colShopId"].Value.ParseToString();
ShopLoginInfo shop = null;
if (!IsClientJit)
shop = lstAdminShopInfo.FirstOrDefault(v => v.LoginName == loginName && v.ShopId == accountId);
else
shop = GlobalConfig.ShopLoginList.FirstOrDefault(v => v.LoginName == loginName && v.ShopId == accountId);
switch (headerText)
{
case "登录":
case "状态":
{
if (!IsClientJit)
{
AdminShopListForm.Instance.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
if (shop.LoginStatus2 == "国际版在线")
{
AdminShopLoginForm adminLoginForm = new AdminShopLoginForm(shop);
adminLoginForm.openType = EnumOpenType.manage;
adminLoginForm.WindowState = FormWindowState.Maximized;
adminLoginForm.InitUrl = "https://agentseller.temu.com";
adminLoginForm.Show();
}
else
{
AdminShopLoginForm shopLoginForm = new AdminShopLoginForm(shop);
shopLoginForm.openType = EnumOpenType.login;
shopLoginForm.SaveComplete += shopLoginForm_SaveComplete;
shopLoginForm.ShowDialog();
}
}
else
{
ShopListForm.Instance.CheckShopLogin(new string[] { shop.ShopAccount }, false);
if (shop.LoginStatus2 == "国际版在线")
{
ShopLoginForm adminLoginForm = new ShopLoginForm(shop);
adminLoginForm.openType = EnumOpenType.manage;
adminLoginForm.WindowState = FormWindowState.Maximized;
adminLoginForm.InitUrl = "https://agentseller.temu.com";
adminLoginForm.Show();
}
else
{
ShopLoginForm shopLoginForm = new ShopLoginForm(shop);
shopLoginForm.openType = EnumOpenType.login;
shopLoginForm.SaveComplete += shopLoginForm_SaveComplete;
shopLoginForm.ShowDialog();
}
}
}
break;
case "":
if (IsClientJit)
{
if (shop != null && shop.jit_expire_time > DateTime.Now.Date)
{
if (shop.LoginStatus2 != "国际版在线")
{
dgvShop.Rows[e.RowIndex].Cells["colSelect"].Value = false;
BaseMsgForm.ShowError("店铺未登录", "JIT-操作失败");
return;
}
}
else
{
dgvShop.Rows[e.RowIndex].Cells["colSelect"].Value = false;
BaseMsgForm.ShowError("JIT卡密过期或未开通", "JIT-操作失败");
return;
}
}
dgvShop.Rows[e.RowIndex].Cells["colSelect"].Value = !(bool)dgvShop.Rows[e.RowIndex].Cells["colSelect"].Value;
break;
default:
break;
}
}
private void shopLoginForm_SaveComplete(object obj)
{
var shop = obj as ShopLoginInfo;
if (shop == null)
return;
displayShopStatus(shop);
}
private void btnEmpty_Click(object sender, EventArgs e)
{
txtNotes.Text = txtShopId.Text = txtShopName.Text = "";
}
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;
}
if (IsClientJit)
{
var jitRow = this.dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colShopId"].Value.ParseToString() == shop?.ShopId);
jitRow.Cells["colJitStatus"].Style.ForeColor = JitShopActiveForm.GetJitStatusStyleColor(shop);
}
}
/// <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"":1,""isCustomGoods"":false,""statusList"":[1]," +
@"""oneDimensionSort"":{""firstOrderByParam"":""expectLatestDeliverTime"",""firstOrderByDesc"":0}}";
string refere = "https://agentseller.temu.com/stock/fully-mgt/order-manage-urgency";
return HttpResponseBLL.PostResponse2(shop, url, body, refere);
}
private string SearchForChainSupplier(ShopLoginInfo shop, int page, string prodSkcIds = null, string type = "待卖家确认", long startTime = 0, long endTime = 0)
{
string url = "https://agentseller.temu.com/api/kiana/mms/robin/searchForChainSupplier";
string body = "";
body = "{\"pageSize\":100,\"pageNum\":" + page + ",";
if (!string.IsNullOrEmpty(txtExtCode.Text.Trim()))
body += "\"skcExtCodeKeyword\":\"" + txtExtCode.Text.Trim() + "\",";
if (startTime != 0 && endTime != 0) // 查询创建时间
body += "\"timeType\":1,\"timeBegin\":" + startTime + ",\"timeEnd\":" + endTime + ",";
if (type == "待卖家确认")
body += "\"priceReviewStatusList\":[1],\"secondarySelectStatusList\":[7],";
else if (type == "待创建首单")
body += "\"secondarySelectStatusList\":[10],";
else if (type == "已发布到站点")
body += "\"secondarySelectStatusList\":[12],\"supplierTodoTypeList\":[],";
body += "\"supplierTodoTypeList\":[],";
if (!string.IsNullOrEmpty(prodSkcIds))
body += "\"productSkcIdList\":[" + prodSkcIds + "],";
body = body.TrimEnd(',');
body += "}";
string referer = "https://agentseller.temu.com/newon/product-select";
return HttpResponseBLL.PostResponse2(shop, url, body, referer);
}
private void btnSearchOrder_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;
}
btnSearchOrder.Enabled = false;
//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 = "";
}
txtErr.Text = "状态正常";
txtErr.ForeColor = Color.Black;
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
GetNewOrderLoop(lstShopId, cancellationTokenSource);
}, cancellationTokenSource.Token);
}
void GetNewOrderLoop(List<string> lstShopId, CancellationTokenSource _cancellationTokenSource)
{
var nextReadTime = DateTime.Now;
while (true)
{
if (nextReadTime <= DateTime.Now)
{
Task.Run(() =>
{
Task.Run(() => { GetMainStatics(lstShopId, cancellationTokenSource); });
lstOrderForSupplierInfo.Clear();
GetNewOrder(lstShopId, cancellationTokenSource);
statisticsListOrder();
});
nextReadTime = DateTime.Now.AddMinutes(30);
}
Thread.Sleep(1000);
Invoke(new Action(() => {
var ticks = nextReadTime - DateTime.Now;
lblNextGetTime.Text = "下次读取:" + nextReadTime.ToString("HH:mm") + ",剩余:" + ticks.Minutes + "分" + ticks.Seconds + "秒";
}));
if (cancellationTokenSource?.IsCancellationRequested == true)
{
Invoke(new Action(() =>
{
btnSearchOrder.Enabled = true;
lblNextGetTime.Text = "已停止";
}));
break;
}
}
}
void GetMainStatics(List<string> lstShopId, CancellationTokenSource _cancellationTokenSource)
{
var lstShopIdTemp = new ConcurrentList<string>();
lstShopIdTemp.AddRange(lstShopId);
foreach (var shopId in lstShopIdTemp)
{
if (_cancellationTokenSource.IsCancellationRequested)
break;
bool rst = true;
ShopLoginInfo shop = GetAndCheckShopLogin(shopId, ref rst);
if (!rst)
{
continue;
}
ShopOrderStatisticsInfo statistics = new ShopOrderStatisticsInfo();
string html = ShopOrderStatisticsForm.GetMainStatistics(shop);
if (!html.Contains("\"success\":true"))
html = ShopOrderStatisticsForm.GetMainStatistics(shop);
if (html.Contains("\"success\":true"))
{
statistics.aboutToSellOutNumber = BaseRegex.GetNullableIntJson(ref html, "aboutToSellOutNumber");
statistics.adjustPrice = BaseRegex.GetNullableIntJson(ref html, "adjustPrice");
statistics.advicePrepareSkcNumber = BaseRegex.GetNullableIntJson(ref html, "advicePrepareSkcNumber");
statistics.alreadySoldOutNumber = BaseRegex.GetNullableIntJson(ref html, "alreadySoldOutNumber");
statistics.havePublishProduct = BaseRegex.GetNullableBoolJson(ref html, "havePublishProduct");
statistics.highPriceLimitNumber = BaseRegex.GetNullableIntJson(ref html, "highPriceLimitNumber");
statistics.lackSkcNumber = BaseRegex.GetNullableIntJson(ref html, "lackSkcNumber");
statistics.onSaleProductNumber = BaseRegex.GetNullableIntJson(ref html, "onSaleProductNumber");
statistics.qualityAfterSaleRatio90d = BaseRegex.GetNullableIntJson(ref html, "qualityAfterSaleRatio90d");
statistics.reviewAdjustPrice = BaseRegex.GetNullableIntJson(ref html, "reviewAdjustPrice");
statistics.saleVolume = BaseRegex.GetNullableIntJson(ref html, "saleVolume");
statistics.sevenDaysSaleVolume = BaseRegex.GetNullableIntJson(ref html, "sevenDaysSaleVolume");
statistics.thirtyDaysSaleVolume = BaseRegex.GetNullableIntJson(ref html, "thirtyDaysSaleVolume");
statistics.waitProductNumber = BaseRegex.GetNullableIntJson(ref html, "waitProductNumber");
statistics.is_search_1 = true;
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["colOrderToday"].Value = statistics.saleVolume;
row.Cells["colOrder7Days"].Value = statistics.sevenDaysSaleVolume;
}
}));
}
else
{
string errStr = BaseRegex.GetStringJson(ref html, "errorMsg");
if (string.IsNullOrEmpty(errStr))
errStr = BaseRegex.GetStringJson(ref html, "error_msg");
if (string.IsNullOrEmpty(errStr))
errStr = html;
if (errStr.Contains("Invalid Login State"))
{
ShopListForm.Instance.CheckShopLogin(new string[] { shop.LoginName }, false);
}
Thread.Sleep(Randomx.GetId(100, 200));
statistics.err_msg = errStr;
continue;
}
}
}
void GetNewOrder(List<string> lstShopId, CancellationTokenSource _cancellationTokenSource)
{
var lstShopIdTemp = new ConcurrentList<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;
bool rst = true;
ShopLoginInfo shop = GetAndCheckShopLogin(shopId, ref rst);
if (!rst)
{
continue;
}
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;
string errorMsg = "";
while (page <= totalPage)
{
if (_cancellationTokenSource.IsCancellationRequested)
break;
Thread.Sleep(100 + Randomx.GetId(200));
string jsonStr = GetShopStockList2(shop, page, pageSize);
if (!jsonStr.Contains("\"success\":true"))
{
isError = true;
var errMsg = BaseRegex.GetStringJson(ref jsonStr, "error_msg");
if (string.IsNullOrEmpty(errMsg))
errMsg = BaseRegex.GetStringJson(ref jsonStr, "errorMsg");
if (string.IsNullOrEmpty(errMsg))
errMsg = jsonStr;
if (!errorMsg.Contains(errMsg))
{
errorMsg += " " + errMsg;
}
}
ConcurrentList<subOrderForSupplier> subOrderInfoLst = new ConcurrentList<subOrderForSupplier>();
if (jsonStr.Contains("\"success\":true"))
{
int total = BaseRegex.GetStringJson(ref jsonStr, "total").ParseToInt();
totalPage = Math.Ceiling(1.0m * total / pageSize).ParseToInt();
var jArr = new JArray();
try
{
var jObj = JObject.Parse(jsonStr);
jArr = jObj["result"]?["subOrderForSupplierList"] as JArray;
if (jArr == null)
jArr = new JArray();
var list = JsonHelper.DeserializeJsonToList<subOrderForSupplier>(jArr.ToString());
list = list.Where(s => !lstTemuDBOrderInfo.Any(o => o.subPurchaseOrderSn == s.subPurchaseOrderSn)).ToList();
subOrderInfoLst.AddRange(list);
}
catch (Exception ex)
{
//BaseMsgForm.ShowError(ex.Message);
Invoke(new Action(() =>
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colLoginName"].Value.ToString() == shop.LoginName);
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "读取错误" + ex.Message;
row.Cells["colCanUse"].Value = false;
}
}));
}
List<DBProdDraftIdMapUpSpuIdInfo> upProdList = new List<DBProdDraftIdMapUpSpuIdInfo>();
if (subOrderInfoLst.Count > 0)
{
var spuIdLst = subOrderInfoLst.Select(o => o.productId.ParseToString()).Distinct().ToList();
// 获取产品数据库中的成本价格
upProdList = AdminProductPriceCheckForm.GetUpSpuIdLst(spuIdLst);
}
foreach (var subOrderInfo in subOrderInfoLst)
{
var upProd = upProdList.FirstOrDefault(p => p.draft_id == subOrderInfo.productId.ParseToLong());
TemuDBOrderInfo dbOrderInfo = new TemuDBOrderInfo()
{
add_time = DateTime.Now,
availableSaleDays = subOrderInfo.skuQuantityDetailList.FirstOrDefault().availableSaleDays,
barCodeMd5 = null,
category = subOrderInfo.category,
className = subOrderInfo.skuQuantityDetailList.FirstOrDefault().className,
costPrice = (upProd?.cost_price * 100m)?.ParseToInt(),
currencyType = subOrderInfo.skuQuantityDetailList.FirstOrDefault().currencyType,
deliverQuantity = subOrderInfo.skuQuantityDetailList.FirstOrDefault().deliverQuantity.ParseToInt(),
deliverTime = subOrderInfo.deliverInfo.deliverTime,
deliveryFee = (upProd?.delivery_fee * 100m)?.ParseToInt(),
deliveryOrderSn = subOrderInfo.deliverInfo.deliveryOrderSn,
expectLatestArrivalTimeOrDefault = subOrderInfo.deliverInfo.expectLatestArrivalTimeOrDefault.ParseToLong(),
expectLatestDeliverTimeOrDefault = subOrderInfo.deliverInfo.expectLatestDeliverTimeOrDefault.ParseToLong(),
extCode = subOrderInfo.skuQuantityDetailList.FirstOrDefault().extCode,
id = null,
jiaTongCode = null,
markFee = (upProd?.mark_fee * 100m)?.ParseToInt(),
mdy_time = DateTime.Now,
notes = null,
originalPurchaseOrderSn = subOrderInfo.originalPurchaseOrderSn,
productId = subOrderInfo.productId.ParseToString(),
productName = subOrderInfo.productName,
productSkcId = subOrderInfo.productSkcId.ParseToString(),
productSkcPicture = subOrderInfo.productSkcPicture,
productSkuId = subOrderInfo.skuQuantityDetailList.FirstOrDefault().productSkuId.ParseToString(),
productSn = subOrderInfo.productSn,
purchaseQuantity = subOrderInfo.skuQuantityDetailList.FirstOrDefault().purchaseQuantity.ParseToInt(),
purchaseTime = subOrderInfo.purchaseTime.ParseToLong(),
qcResult = subOrderInfo.skuQuantityDetailList.FirstOrDefault().qcResult,
realReceiveAuthenticQuantity = subOrderInfo.skuQuantityDetailList.FirstOrDefault().realReceiveAuthenticQuantity.ParseToInt(),
receiveTime = subOrderInfo.deliverInfo.receiveTime,
receiveWarehouseId = subOrderInfo.deliverInfo.receiveWarehouseId.ParseToString(),
receiveWarehouseName = subOrderInfo.deliverInfo.receiveWarehouseName,
shippingMarkMd5 = null,
status = subOrderInfo.status.ParseToInt(),
subPurchaseOrderSn = subOrderInfo.subPurchaseOrderSn,
supplierId = subOrderInfo.supplierId.ParseToString(),
supplierName = subOrderInfo.supplierName,
supplierPrice = subOrderInfo.skuQuantityDetailList.FirstOrDefault().supplierPrice.ParseToInt(),
thumbUrlList = subOrderInfo.skuQuantityDetailList.FirstOrDefault().thumbUrlList.FirstOrDefault(),
upLoadStatus = 0,
upProductId = upProd?.draft_id.ParseToString(),
warehouseGroupId = subOrderInfo.warehouseGroupId.ParseToString(),
};
lstOrderForSupplierInfo.Add(subOrderInfo);
lstTemuDBOrderInfo.Add(dbOrderInfo);
var url = BaseClass.BuildObjString("order/add_order");
var data = UserLogin.GetSignaturex() +
"&shop_id=" + dbOrderInfo.supplierId +
"&order_data=" + HttpUtility.UrlEncode(JsonHelper.SerializeObject(dbOrderInfo), Encoding.UTF8);
var html = GetHtml.PostUtf8(url, data);
#if RELEASE
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
#endif
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
{
var errMsg = BaseRegex.GetStringJson(ref html, "msg");
Invoke(new Action(() =>
{
txtErr.Text = "订单入库失败,请检查网络" + errMsg;
txtErr.ForeColor = Color.Red;
}));
}
Invoke(new Action(() =>
{
int rowId = 0;
var rw = this.dgvStock.Rows.Cast<DataGridViewRow>().LastOrDefault(r =>
r.Cells["colSupplierId"].Value.ParseToString() == shop.ShopId &&
r.Cells["colCreateTimeTick"].Value.ParseToLong() > dbOrderInfo.purchaseTime
);
if (rw != null)
{
rowId = rw.Index + 1;
}
if (dbOrderInfo.costPrice > 0)
InsertRow(rowId, dbOrderInfo);
}));
}
}
page++;
}
InsertRowEnd(); // 处理合并单元格恰在好最后一行的情况
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 = "查询失败" + errorMsg;
}
}
}));
}
Invoke(new Action(() =>
{
string sRst = "查询结束!";
if (_cancellationTokenSource.IsCancellationRequested)
sRst = "已取消查询!";
//BaseMsgForm.ShowInfo(sRst);
this.statusBar.lblTaskStatus.Text = sRst;
}));
}
Dictionary<string, ConcurrentList<DataGridViewCell>> dicMergeInfoCells = new Dictionary<string, ConcurrentList<DataGridViewCell>>();
Dictionary<string, ConcurrentList<DataGridViewCell>> dicMergeImgCells = new Dictionary<string, ConcurrentList<DataGridViewCell>>();
ConcurrentList<DataGridViewCell> MergeInfoCells = new ConcurrentList<DataGridViewCell>();
ConcurrentList<DataGridViewCell> MergeImgCells = new ConcurrentList<DataGridViewCell>();
void InsertRow(int rowId, TemuDBOrderInfo dbOrderInfo)
{
this.dgvStock.Rows.Insert(rowId,
false,
"",
dbOrderInfo.supplierId,
dbOrderInfo.supplierName,
dbOrderInfo.supplierId + "\r\n" + dbOrderInfo.supplierName,
dbOrderInfo.subPurchaseOrderSn,
dbOrderInfo.subPurchaseOrderSn +
"\r\n需 " + BaseClass.StampToDateTime((dbOrderInfo.expectLatestDeliverTimeOrDefault / 1000).ParseToInt()).ToString("MM-dd HH:mm:ss") + " 前发货" +
"\r\n需 " + BaseClass.StampToDateTime((dbOrderInfo.expectLatestArrivalTimeOrDefault / 1000).ParseToInt()).ToString("MM-dd HH:mm:ss") + " 前到货",
dbOrderInfo.productSkcPicture.Replace("https", "http").Replace("img.kwcdn.com", "img.cdnfe.com") + "?imageMogr2/thumbnail/54x54&quot;",
DataGridViewExtension.defaultBitmap,
dbOrderInfo.originalPurchaseOrderSn,
dbOrderInfo.productId,
dbOrderInfo.upProductId,
dbOrderInfo.productSkcId,
dbOrderInfo.productName,
dbOrderInfo.productSn,
"备货母单号: " + dbOrderInfo.originalPurchaseOrderSn + "\r\n"
+ "SKC: " + dbOrderInfo.productSkcId + "\r\n"
+ "货号: " + dbOrderInfo.productSn + "\r\n"
+ getLength2312Str(dbOrderInfo.productName, 50),
dbOrderInfo.thumbUrlList.Replace("https", "http").Replace("img.kwcdn.com", "img.cdnfe.com") + "?imageMogr2/thumbnail/54x54&quot;",
DataGridViewExtension.defaultBitmap,
dbOrderInfo.className + "\r\nSKU ID: " + dbOrderInfo.productSkuId,
"成本价:" + (dbOrderInfo.costPrice / 100m) + "\r\n车队费:" + (dbOrderInfo.deliveryFee / 100m) + "\r\n贴单费:" + (dbOrderInfo.markFee / 100m),
dbOrderInfo.supplierPrice / 100m,
dbOrderInfo.purchaseQuantity, // 备货件数
dbOrderInfo.purchaseTime,
BaseClass.StampToDateTime((dbOrderInfo.purchaseTime / 1000).ParseToInt()).ToString("yyyy-MM-dd HH:mm:ss"), // 备货单创建时间
"",
""
);
var row = dgvStock.Rows[rowId];
row.Height = 120;
SetRowLinkCellText(dbOrderInfo, row);
if (dbOrderInfo.originalPurchaseOrderSn != indexOrderSn)
{
indexId++;
indexOrderSn = dbOrderInfo.originalPurchaseOrderSn;
if (MergeInfoCells.Count > 1)
{
ConcurrentList<DataGridViewCell> cells = new ConcurrentList<DataGridViewCell>();
cells.AddRange(MergeInfoCells.OrderBy(c => c.RowIndex));
dgvStock.AddVerticalMergeCell(cells);
}
if (MergeImgCells.Count > 1)
{
ConcurrentList<DataGridViewCell> cells = new ConcurrentList<DataGridViewCell>();
cells.AddRange(MergeImgCells.OrderBy(c => c.RowIndex));
dgvStock.AddVerticalMergeCell(cells);
}
MergeInfoCells.Clear();
MergeImgCells.Clear();
MergeInfoCells.Insert(0, dgvStock.Rows[rowId].Cells["colProdInfo"]);
MergeImgCells.Insert(0, dgvStock.Rows[rowId].Cells["colProductSkcPic"]);
}
else
{
MergeInfoCells.Insert(0, dgvStock.Rows[rowId].Cells["colProdInfo"]);
MergeImgCells.Insert(0, dgvStock.Rows[rowId].Cells["colProductSkcPic"]);
}
//if (!dicMergeInfoCells.ContainsKey(dbOrderInfo.originalPurchaseOrderSn))
// dicMergeInfoCells.Add(dbOrderInfo.originalPurchaseOrderSn, new ConcurrentList<DataGridViewCell>());
//dicMergeInfoCells["dbOrderInfo.originalPurchaseOrderSn"].Add(dgvStock.Rows[rowId].Cells["colProdInfo"]);
//if (!dicMergeImgCells.ContainsKey(dbOrderInfo.originalPurchaseOrderSn))
// dicMergeImgCells.Add(dbOrderInfo.originalPurchaseOrderSn, new ConcurrentList<DataGridViewCell>());
//dicMergeImgCells["dbOrderInfo.originalPurchaseOrderSn"].Add(dgvStock.Rows[rowId].Cells["colProductSkcPic"]);
if (indexId % 2 == 1)
row.DefaultCellStyle.BackColor = Color.White;
else
row.DefaultCellStyle.BackColor = Color.FromArgb(235, 235, 235);
FilterRow(row);
}
void InsertRowEnd()
{
if (MergeInfoCells.Count > 1)
{
ConcurrentList<DataGridViewCell> cells = new ConcurrentList<DataGridViewCell>();
cells.AddRange(MergeInfoCells.OrderBy(c => c.RowIndex));
dgvStock.AddVerticalMergeCell(cells);
}
if (MergeImgCells.Count > 1)
{
ConcurrentList<DataGridViewCell> cells = new ConcurrentList<DataGridViewCell>();
cells.AddRange(MergeImgCells.OrderBy(c => c.RowIndex));
dgvStock.AddVerticalMergeCell(cells);
}
MergeInfoCells.Clear();
MergeImgCells.Clear();
}
void SetRowLinkCellText(TemuDBOrderInfo dbOrderInfo, DataGridViewRow row)
{
string upLoadCodeText = "";
if(IsClientJit)
{
upLoadCodeText = "上传";
if (!string.IsNullOrWhiteSpace(dbOrderInfo.jiaTongCode) && !string.IsNullOrWhiteSpace(dbOrderInfo.barCodeMd5) &&
!string.IsNullOrWhiteSpace(dbOrderInfo.shippingMarkMd5))
{
upLoadCodeText = "修改上传";
}
}
else
{
upLoadCodeText = "查看";
}
string upLoadOrderText = "";
if (IsClientJit)
{
if (dbOrderInfo.upLoadStatus < 2)
{
if (!string.IsNullOrWhiteSpace(dbOrderInfo.jiaTongCode) && !string.IsNullOrWhiteSpace(dbOrderInfo.barCodeMd5) &&
!string.IsNullOrWhiteSpace(dbOrderInfo.shippingMarkMd5))
{
upLoadOrderText = "上传订单";
}
}
if (dbOrderInfo.upLoadStatus == 2)
{
upLoadOrderText = "已上传";
}
if (dbOrderInfo.upLoadStatus == 3)
{
upLoadOrderText = "已打单";
}
if (dbOrderInfo.upLoadStatus == 4)
{
upLoadOrderText = "已发货";
}
}
else
{
if (dbOrderInfo.upLoadStatus == 2)
{
upLoadOrderText = "已上传 点击打单";
}
if (dbOrderInfo.upLoadStatus == 3)
{
upLoadOrderText = "已打单 点击发货";
}
if (dbOrderInfo.upLoadStatus == 4)
{
upLoadOrderText = "已发货";
}
}
row.Cells["colUploadCode"].Value = upLoadCodeText;
row.Cells["colUploadOrder"].Value = upLoadOrderText;
}
void clientLoadServerDbOrder()
{
var shops = GlobalConfig.ShopLoginList;
for (int i = shops.Count - 1; i >= 0; i--)
{
var shop = shops[i];
if (shop.jit_expire_time >= DateTime.Now.Date)
{
loadServerDbOrder(shop);
}
}
statisticsListOrder();
}
void loadServerDbOrder(ShopLoginInfo shop)
{
int page = 0;
int totalPage = 1;
int pageSize = 200;
while (page < totalPage)
{
page++;
var url = BaseClass.BuildObjString("order/get_order_list");
var data = UserLogin.GetSignaturex() +
"&page_size=" + pageSize +
"&page=" + page;
if (shop != null)
data += "&shop_id=" + shop.ShopId;
if (!IsClientJit)
data += "&upload_order_status=2";
var html = GetHtml.PostUtf8(url, data);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
html = GetHtml.PostUtf8(url, data);
Thread.Sleep(50);
if (string.IsNullOrEmpty(html) || !html.Contains("\"code\":200"))
{
var errMsg = BaseRegex.GetStringJson(ref html, "msg");
Invoke(new Action(() =>
{
txtErr.Text = "拉取入库订单失败,请检查网络" + errMsg;
txtErr.ForeColor = Color.Red;
}));
}
else
{
int total = BaseRegex.GetStringJson(ref html, "count").ParseToInt();
totalPage = Math.Ceiling(1.0m * total / pageSize).ParseToInt();
var jObj = JObject.Parse(html);
var list = JsonHelper.DeserializeJsonToList<TemuDBOrderInfo>(jObj["data"].ToString());
list = list.Where(s => !lstTemuDBOrderInfo.Any(o => o.subPurchaseOrderSn == s.subPurchaseOrderSn)).ToList();
lstTemuDBOrderInfo.AddRange(list);
foreach (var dbOrderInfo in list)
{
Invoke(new Action(() =>
{
int rowId = 0;
var rw = this.dgvStock.Rows.Cast<DataGridViewRow>().LastOrDefault(r =>
r.Cells["colSupplierId"].Value.ParseToString() == shop.ShopId &&
r.Cells["colCreateTimeTick"].Value.ParseToLong() > dbOrderInfo.purchaseTime
);
if (rw != null)
{
rowId = rw.Index + 1;
}
if(dbOrderInfo.costPrice > 0)
InsertRow(rowId, dbOrderInfo);
}));
}
}
}
InsertRowEnd(); // 处理合并单元格恰在好最后一行的情况
}
string getLength2312Str(string text, int length = 30)
{
var newTxt = text;
while (Encoding.GetEncoding("gb2312").GetBytes(newTxt).Length > length)
{
newTxt = newTxt.Substring(0, newTxt.Length - 1);
}
return newTxt == text ? newTxt : newTxt + "…";
}
private void btnStop_Click(object sender, EventArgs e)
{
if (cancellationTokenSource != null)
cancellationTokenSource.Cancel();
}
private void btnRestoreSizeAndNumber_Click(object sender, EventArgs e)
{
RestoreSizeAndNumber();
}
/// <summary>
/// 因已出单商品无法再修改尺寸重量,暂时作废
/// </summary>
void RestoreSizeAndNumber()
{
// 因已出单商品无法再修改尺寸重量,暂时作废
if (DateTime.Now > new DateTime(2025, 12, 1))
return;
//this.statusBar.lblTaskStatus.Text = "正在批量还原包装规格尺寸与SKU分类数量";
//this.pbLoading.Visible = true;
Task.Run(() =>
{
// 获取未还原的商品列表
var orderLst = this.lstTemuDBOrderInfo.Where(o => o.upLoadStatus == 0).ToList();
List<string> prodIdLst = new List<string>();
foreach (var order in orderLst)
{
if (prodIdLst.Contains(order.productId) || order.status > 0)
continue;
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == order.supplierId);
if (shop == null || shop.LoginStatus2 != "国际版在线")
continue;
var searchRst = SearchForChainSupplier(shop, 1, order.productSkcId, "");
if (!searchRst.Contains("\"success\":true") && !searchRst.Contains("登录过期") && !searchRst.Contains("Invalid Login State"))
searchRst = SearchForChainSupplier(shop, 1, order.productSkcId, "");
if (!searchRst.Contains("\"success\":true"))
{
this.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
Invoke(new Action(() =>
{
displayShopStatus(shop);
}));
continue;
}
try
{
var jObj = JObject.Parse(searchRst);
var jArr = jObj["result"]["dataList"] as JArray;
if (jArr == null)
jArr = new JArray();
List<string> extCodeTmpLst = new List<string>();
List<string> spuIdLst = new List<string>();
var item = jArr.FirstOrDefault();
var jStr = JsonHelper.SerializeObject(item);
TemuForChainProductInfo priceInfo = JsonHelper.DeserializeJsonToObject<TemuForChainProductInfo>(jStr);
if (priceInfo != null)
{
if (!checkNeedRestoreSizeAndNumber(priceInfo))
{
//不用再修尺寸的商品提交到数据库更新所有同id商品,已废弃;
var url = BaseClass.BuildObjString("order/update_order_status1");
var data = UserLogin.GetSignaturex() +
"&shop_id=" + shop.ShopId +
"&product_id=" + priceInfo.productId;
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"))
{
}
else
{
foreach(var o in lstTemuDBOrderInfo)
{
if (o.upLoadStatus < 1)
o.upLoadStatus = 1;
}
}
continue;
}
var t = Task.Run(() => { return RestoreSizeAndNumber(priceInfo, shop); });
#if DEBUG
t.Wait(250000);
#endif
t.Wait(25000);
var rRst = t.Result;
if (string.IsNullOrEmpty(rRst))
{
prodIdLst.Add(priceInfo.productId.ParseToString());
}
}
}
catch
{
}
}
});
}
string RestoreSizeAndNumber(TemuForChainProductInfo price, ShopLoginInfo shop)
{
//----------------------------------------------------------------------------------------
// 查询是否有修改记录,如果没有申请新的修改,获取taskId
var rows = this.dgvStock.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colProductId"].Value.ParseToString() == price.productId.ParseToString()).ToList();
if (IsClientJit)
shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == price.supplierId.ParseToString());
if (shop == null)
return "店铺不存在"; // continue;
if (shop.LoginStatus2 != "国际版在线")
{
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "店铺掉线";
}));
return "店铺掉线"; //continue;
}
//var pName = price.productName;
if (checkNeedRestoreSizeAndNumber(price))
{
}
else
{
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "无需处理订单参数"; // "无需还原包装规格尺寸与SKU分类数量";
}));
return "无需处理订单参数"; //continue;
}
var taskUid = "";
var html = AdminProductPriceCheckForm.editPriceProductSizeAndNumberBatchAdd(shop, price.productId.ParseToString());
//{"success":true,"errorCode":1000000,"errorMsg":null,"result":{"handleFailedList":[{"failedBizId":4432690492,"failedReason":"This product has pending or in-progress modification tasks, cannot initiate again"}],"addFailedList":[{"failedBizId":4432690492,"failedReason":"This product has pending or in-progress modification tasks, cannot initiate again","failedReasonType":8}],"successBizId2TaskUidMap":{}}}
if (html.Contains("This product has pending or in-progress modification tasks"))
{
var taskHtml = AdminProductPriceCheckForm.editPriceProductSizeAndNumberTaskQuery(shop, price.productId.ParseToString());
taskUid = BaseRegex.GetStringJson(ref taskHtml, "taskUid");
if (string.IsNullOrEmpty(taskUid) || !taskHtml.Contains("\"productEditTaskItems\":[{\"editItem\":4,\"editAdvice\":\"优化\"},{\"editItem\":8,\"editAdvice\":\"优化\"}]"))
{
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "有正在处理的订单参数";
}));
return "有正在处理的订单参数"; //continue;
}
}
if (!html.Contains("\"success\":true"))
{
if (html.Contains("登录过期") || html.Contains("Invalid Login State"))
{
this.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
Invoke(new Action(() =>
{
displayShopStatus(shop);
}));
}
string sErrMsg = BaseRegex.GetStringJson(ref html, "errorMsg").ParseToString();
if (string.IsNullOrEmpty(sErrMsg))
{
sErrMsg = BaseRegex.GetStringJson(ref html, "error_msg").ParseToString();
}
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "修改订单请求失败 " + sErrMsg;
}));
return "修改订单请求失败" + sErrMsg;//continue;
}
try
{
if (string.IsNullOrEmpty(taskUid))
{
JObject jObj = JObject.Parse(html);
taskUid = jObj["result"]["successBizId2TaskUidMap"].LastOrDefault().LastOrDefault().ParseToString();
}
}
catch (Exception ex)
{
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "序列化修改订单请求结果失败 " + ex.Message;
}));
return "序列化修改订单请求结果失败 " + ex.Message; // continue;
}
html = AdminProductPriceCheckForm.editPriceProductQuery(shop, price.productId.ParseToString(), taskUid).ParseToString();
if (html.Contains("This product has pending or in-progress modification tasks"))
{
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "已提交过修改任务";
}));
return "已提交过修改任务"; // continue;
}
if (!html.Contains("\"success\":true"))
{
if (html.Contains("登录过期") || html.Contains("Invalid Login State"))
{
this.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
Invoke(new Action(() =>
{
displayShopStatus(shop);
}));
}
string sErrMsg = BaseRegex.GetStringJson(ref html, "errorMsg").ParseToString();
if (string.IsNullOrEmpty(sErrMsg))
{
sErrMsg = BaseRegex.GetStringJson(ref html, "error_msg").ParseToString();
}
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "查询已提交修改任务失败 " + sErrMsg;
}));
return "查询已提交修改任务失败 " + sErrMsg; // continue;
}
try
{
//int len = Randomx.GetId(15, 31); //300
//int width = Randomx.GetId(10, 15); //200
//int height = Randomx.GetId(5, 10); //100
//int weight = Randomx.GetId(100, 200); //500000
//int numberOfPieces = Randomx.GetId(450, 601);// 单品数量
int len = Randomx.GetId(numLen1.Value.ParseToInt(), numLen2.Value.ParseToInt() + 1) * 10;
int width = Randomx.GetId(numWidth1.Value.ParseToInt(), Math.Min(len, numWidth2.Value.ParseToInt() + 1)) * 10;
int height = Randomx.GetId(numHeight1.Value.ParseToInt(), Math.Min(width, numHeight2.Value.ParseToInt() + 1)) * 10;
int weight = Randomx.GetId(numWeight1.Value.ParseToInt(), numWeight2.Value.ParseToInt() + 1) * 1000;
int numberOfPieces = Math.Max(1, numPieces.Value.ParseToInt());
JObject obj = JObject.Parse(html);
var result = JsonHelper.SerializeObject(obj["result"]);
TemuDetailProductInfo prodInfo = JsonHelper.DeserializeJsonToObject<TemuDetailProductInfo>(result);
var catId = Math.Max(0, prodInfo.categories.cat1.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat2.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat3.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat4.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat5.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat6.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat7.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat8.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat9.catId.ParseToInt());
catId = Math.Max(catId, prodInfo.categories.cat10.catId.ParseToInt());
var cateSizeWeightConfig = lstCateSizeWeightConfig.FirstOrDefault(c => c.catId == catId.ToString());
if (cateSizeWeightConfig == null)
{
var url = BaseClass.BuildObjString("product/get_cate_size_weight_config_v2");
var data = UserLogin.GetSignaturex() +
"&cat_id=" + catId;
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"))
{
}
else
{
try
{
var jArr = JObject.Parse(html)["data"];
cateSizeWeightConfig = JsonHelper.DeserializeJsonToObject<CateSizeWeightConfig>(jArr.ToString());
if (cateSizeWeightConfig != null)
lstCateSizeWeightConfig.Add(cateSizeWeightConfig);
}
catch
{
}
}
}
if (cateSizeWeightConfig == null)
{
//查询接口尺寸重量限制
html = AdminProductPriceCheckForm.queryProductSizeAndWeightConfig(shop, taskUid.ParseToString(), price.productId.ParseToString(), catId.ParseToString());
var html1 = AdminProductPriceCheckForm.queryCatSizeAndWeightConfig(shop, taskUid.ParseToString(), price.productId.ParseToString(), catId.ParseToString());
if (!string.IsNullOrEmpty(html1) && html1.Contains("length"))
html = html1;
//{"success":true,"errorCode":1000000,"errorMsg":null,"result":{"common":{"operatorId":null,"operatorName":null,"operatorType":null,"checkSideRelation":false,"noticeSideEquation":false,"length":{"min":10,"max":2999},"width":{"min":5,"max":2999},"height":{"min":2,"max":2999},"weight":{"min":2000,"max":99999000}}}}
Thread.Sleep(Randomx.GetId(25, 75));
commonSleep();
if (html.Contains("\"success\":true"))
{
try
{
JObject jObj = JObject.Parse(html);
cateSizeWeightConfig = new CateSizeWeightConfig() { catId = catId.ToString() };
if (html.Contains("common"))
{
cateSizeWeightConfig.minLen = jObj["result"]["common"]["length"]["min"].ParseToInt();
cateSizeWeightConfig.maxLen = jObj["result"]["common"]["length"]["max"].ParseToInt();
cateSizeWeightConfig.minWidth = jObj["result"]["common"]["width"]["min"].ParseToInt();
cateSizeWeightConfig.maxWidth = jObj["result"]["common"]["width"]["max"].ParseToInt();
cateSizeWeightConfig.minHeight = jObj["result"]["common"]["height"]["min"].ParseToInt();
cateSizeWeightConfig.maxHeight = jObj["result"]["common"]["height"]["max"].ParseToInt();
cateSizeWeightConfig.minWeight = jObj["result"]["common"]["weight"]["min"].ParseToInt();
cateSizeWeightConfig.maxWeight = jObj["result"]["common"]["weight"]["max"].ParseToInt();
}
else
{
cateSizeWeightConfig.minLen = jObj["result"]["length"]["min"].ParseToInt();
cateSizeWeightConfig.maxLen = jObj["result"]["length"]["max"].ParseToInt();
cateSizeWeightConfig.minWidth = jObj["result"]["width"]["min"].ParseToInt();
cateSizeWeightConfig.maxWidth = jObj["result"]["width"]["max"].ParseToInt();
cateSizeWeightConfig.minHeight = jObj["result"]["height"]["min"].ParseToInt();
cateSizeWeightConfig.maxHeight = jObj["result"]["height"]["max"].ParseToInt();
cateSizeWeightConfig.minWeight = jObj["result"]["weight"]["min"].ParseToInt();
cateSizeWeightConfig.maxWeight = jObj["result"]["weight"]["max"].ParseToInt();
}
lstCateSizeWeightConfig.Add(cateSizeWeightConfig);
var url = BaseClass.BuildObjString("product/add_cate_size_weight_config_v2");
var data = UserLogin.GetSignaturex();
data += "&cat_id=" + catId;
data += "&minLen=" + cateSizeWeightConfig.minLen;
data += "&maxLen=" + cateSizeWeightConfig.maxLen;
data += "&minWidth=" + cateSizeWeightConfig.minWidth;
data += "&maxWidth=" + cateSizeWeightConfig.maxWidth;
data += "&minHeight=" + cateSizeWeightConfig.minHeight;
data += "&maxHeight=" + cateSizeWeightConfig.maxHeight;
data += "&minWeight=" + cateSizeWeightConfig.minWeight;
data += "&maxWeight=" + cateSizeWeightConfig.maxWeight;
html = GetHtml.PostUtf8(url, data);
}
catch { }
}
else
{
if (html.Contains("登录过期") || html.Contains("Invalid Login State"))
{
this.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
Invoke(new Action(() =>
{
displayShopStatus(shop);
}));
}
string sErrMsg = BaseRegex.GetStringJson(ref html, "errorMsg").ParseToString();
if (string.IsNullOrEmpty(sErrMsg))
sErrMsg = BaseRegex.GetStringJson(ref html, "error_msg").ParseToString();
if (string.IsNullOrEmpty(sErrMsg))
sErrMsg = html;
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "修改请求失败 " + sErrMsg;
}));
return "修改请求失败 " + sErrMsg; //continue;
}
}
if (cateSizeWeightConfig != null)
{
// 设置长宽高
if (len < cateSizeWeightConfig.minLen) len = cateSizeWeightConfig.minLen;
if (len > cateSizeWeightConfig.maxLen) len = cateSizeWeightConfig.maxLen;
if (width < cateSizeWeightConfig.minWidth) width = cateSizeWeightConfig.minWidth;
if (width > cateSizeWeightConfig.maxWidth) width = cateSizeWeightConfig.maxWidth;
if (height < cateSizeWeightConfig.minHeight) height = cateSizeWeightConfig.minHeight;
if (height > cateSizeWeightConfig.maxHeight) height = cateSizeWeightConfig.maxHeight;
if (weight < cateSizeWeightConfig.minWeight) weight = cateSizeWeightConfig.minWeight;
if (weight > cateSizeWeightConfig.maxWeight) weight = cateSizeWeightConfig.maxWeight;
}
//JObject jPost = new JObject();
//jPost.Add("productId", price.productId);
//jPost.Add("taskUid", taskUid.ParseToString());
//jPost.Add("taskVersion", 0);
//jPost.Add("refuseEdit", false);
//var jProductSkcMainReqs = new JArray();
//jPost.Add("productSkcReqs", jProductSkcMainReqs);
//JObject jProductSkcMainReq = new JObject();
//jProductSkcMainReqs.Add(jProductSkcMainReq);
//var jMainProductSkuSpecReqs = new JArray();
//jProductSkcMainReq.Add("mainProductSkuSpecReqs", jMainProductSkuSpecReqs);
//jMainProductSkuSpecReqs.Add(new JObject() {
// new JProperty("parentSpecId",0),
// new JProperty("parentSpecName",""),
// new JProperty("specId",0),
// new JProperty("specName",""),
//});
var jStr = "{";
jStr += "\r\n\"productId\":" + price.productId + ",";
jStr += "\r\n\"taskUid\":\"" + taskUid.ParseToString() + "\",";
jStr += "\r\n\"taskVersion\":" + 0 + ",";
jStr += "\r\n\"refuseEdit\":false,";
jStr += "\r\n\"productSkcReqs\":[{";
jStr += " \r\n\"mainProductSkuSpecReqs\":[{".Trim();
jStr += " \r\n\"parentSpecId\":0,".Trim();
jStr += " \r\n\"parentSpecName\":\"\",".Trim();
jStr += " \r\n\"specId\":0,".Trim();
jStr += " \r\n\"specName\":\"\"".Trim();
jStr += " \r\n}],".Trim();
jStr += " \r\n\"productSkuReqs\":[".Trim();
foreach (var sku in prodInfo.productSkcList.FirstOrDefault().productSkuList)
{
jStr += " \r\n{".Trim();
//productSkuSpecReqs
jStr += " \r\n\"productSkuSpecReqs\":[".Trim();
foreach (var spec in sku.productSkuSpecList)
{
jStr += "{";
jStr += "\"parentSpecId\":" + spec.parentSpecId + ",";
jStr += "\"parentSpecName\":\"" + spec.parentSpecName + "\",";
jStr += "\"specId\":" + spec.specId + ",";
jStr += "\"specName\":\"" + spec.specName + "\",";
var specProp = prodInfo.productSpecPropertyVOS.FirstOrDefault(p => p.parentSpecId == spec.parentSpecId);
if (!string.IsNullOrEmpty(specProp?.valueGroupId.ParseToString()))
jStr += "\"groupId\":" + specProp?.valueGroupId.ParseToString() + ",";
if (!string.IsNullOrEmpty(specProp?.vid.ParseToString()))
jStr += "\"vid\":" + specProp?.vid.ParseToString() + ",";
jStr = jStr.TrimEnd(',');
jStr += "},";
}
jStr = jStr.TrimEnd(',');
jStr += " \r\n],".Trim();
//productSkuWhExtAttrReq
jStr += "\"productSkuWhExtAttrReq\":{";
jStr += " \"productSkuWeightReq\":{\"value\":" + weight + "},";
jStr += " \"productSkuVolumeReq\":{";
jStr += " \"len\":" + len + ",";
jStr += " \"width\":" + width + ",";
jStr += " \"height\":" + height;
jStr += " }";
jStr += "},";
//productSkuMultiPackReq
jStr += "\"productSkuMultiPackReq\":{";
jStr += " \"skuClassification\":1,";
jStr += " \"numberOfPieces\":" + numberOfPieces + ",";
jStr += " \"pieceUnitCode\":" + Math.Max(1, sku.productSkuMultiPack.pieceUnitCode.ParseToInt()) + ",";
jStr += " \"productSkuNetContentReq\":{";
jStr += " },";
jStr += " \"individuallyPacked\":-1";
jStr += "},";
//productSkuAccessoriesReq
jStr += "\"productSkuAccessoriesReq\":{";
jStr += "\"productSkuAccessories\":[";
jStr += "]";
jStr += "}";
jStr += " \r\n},".Trim();
}
jStr = jStr.TrimEnd(',');
jStr += " \r\n]".Trim();
jStr += "\r\n}]";
jStr += "\r\n}";
var jStrObj = JObject.Parse(jStr);
jStr = JsonHelper.SerializeObject(jStrObj);
html = AdminProductPriceCheckForm.editPriceProductSizeAndNumber(shop, taskUid.ParseToString(), price.productId.ParseToString(), jStr);
Thread.Sleep(Randomx.GetId(25, 75));
commonSleep();
if (html.Contains("\"success\":true"))
{
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "调整订单成功";
}));
return "修改成功";
}
else
{
if (html.Contains("登录过期") || html.Contains("Invalid Login State"))
{
this.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
Invoke(new Action(() =>
{
displayShopStatus(shop);
}));
}
string sErrMsg = BaseRegex.GetStringJson(ref html, "errorMsg").ParseToString();
if (string.IsNullOrEmpty(sErrMsg))
sErrMsg = BaseRegex.GetStringJson(ref html, "error_msg").ParseToString();
if (string.IsNullOrEmpty(sErrMsg))
sErrMsg = html;
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "修改请求失败 " + sErrMsg;
}));
return "修改请求失败 " + sErrMsg;//continue;
}
}
catch (Exception ex)
{
Invoke(new Action(() =>
{
foreach (var row in rows)
row.Cells["colMsg"].Value = "修改请求失败 " + ex.Message;
}));
return "修改请求失败 " + ex.Message; //continue;
}
//return "";
}
bool checkNeedRestoreSizeAndNumber(TemuForChainProductInfo info)
{
//最长边:60 - 100 cm//生成时需转换为mm
//次长边:60 - 90 cm//生成时需转换为mm
//最短边:50 - 80 cm//生成时需转换为mm
//重量:80000 - 99999g //生成时需转换为mg
var skc = info.skcList.FirstOrDefault();
//长宽高少于15且重量小于1000克认为是有意改大了参数需要还原
if (skc.skuList.Any(s => (s.len < numJudgeLen.Value * 10 || s.width < numJudgeLen.Value * 10 || s.height < numJudgeLen.Value * 10) && s.weight < numJudgeWeight.Value * 1000))
return true;
return false;
}
void CheckShopLogin(ShopLoginInfo[] shops, bool isShowProgress)
{
if (!IsClientJit)
AdminShopListForm.Instance.CheckShopLogin(shops, isShowProgress);
else
ShopListForm.Instance.CheckShopLogin(shops, isShowProgress);
}
ShopLoginInfo GetAndCheckShopLogin(string shopId, ref bool chkRst)
{
ShopLoginInfo shop = null;
if (!IsClientJit)
{
shop = this.lstAdminShopInfo.FirstOrDefault(s => s.ShopId == shopId);
}
else
{
shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
}
if (shop == null)
{
chkRst = false;
return shop;
}
#region 检测登录
if (shop.LoginStatus2 != "国际版在线")
{
chkRst = false;
return shop;
}
this.CheckShopLogin(new ShopLoginInfo[] { shop }, false);
if (shop.LoginStatus2 != "国际版在线")
{
Invoke(new Action(() =>
{
var rows = this.dgvShop.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["colLoginName"].Value.ToString() == shop.LoginName);
foreach (var row in rows)
{
row.Cells["colMessage"].Value = "店铺掉线";
row.Cells["colLoginStatus"].Value = "未登录";
row.Cells["colCanUse"].Value = false;
}
}));
chkRst = false;
return shop;
}
#endregion
chkRst = true;
return shop;
}
public static int sleepTime = 300;
void commonSleep()
{
Thread.Sleep(sleepTime);
}
private void dgvStock_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvStock.Columns[e.ColumnIndex].HeaderText;
string shopId = dgvStock.Rows[e.RowIndex].Cells["colSupplierId"].Value.ParseToString();
string prodId = dgvStock.Rows[e.RowIndex].Cells["colProductId"].Value.ParseToString();
string subOrderId = dgvStock.Rows[e.RowIndex].Cells["colSubOrderSn"].Value.ParseToString(); // 备货单号
switch (headerText)
{
case "Skc图":
case "SKC图":
{
string url = dgvStock.Rows[e.RowIndex].Cells["colImgUrl"].Value.ParseToString().Replace("img.kwcdn.com", "img.cdnfe.com").Split('?').FirstOrDefault();
url = url.IndexOf("?") < 0 ? url : url.Substring(0, url.IndexOf("?"));
ShowImgForm imgFrom = new ShowImgForm(url);
imgFrom.ShowDialog();
}
break;
case "SKU图":
{
string url = dgvStock.Rows[e.RowIndex].Cells["colSkuImgUrl"].Value.ParseToString().Replace("img.kwcdn.com", "img.cdnfe.com").Split('?').FirstOrDefault();
url = url.IndexOf("?") < 0 ? url : url.Substring(0, url.IndexOf("?"));
ShowImgForm imgFrom = new ShowImgForm(url);
imgFrom.ShowDialog();
}
break;
}
}
private void dgvStock_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvStock.Columns[e.ColumnIndex].HeaderText;
string shopId = dgvStock.Rows[e.RowIndex].Cells["colSupplierId"].Value.ParseToString();
string prodId = dgvStock.Rows[e.RowIndex].Cells["colProductId"].Value.ParseToString();
string subOrderId = dgvStock.Rows[e.RowIndex].Cells["colSubOrderSn"].Value.ParseToString(); // 备货单号
switch (headerText)
{
case "上传条码/箱唛":
{
var dbOrder = this.lstTemuDBOrderInfo.FirstOrDefault(o => o.subPurchaseOrderSn == subOrderId);
var row = dgvStock.Rows[e.RowIndex];
if (dbOrder == null)
{
BaseMsgForm.ShowError("订单不存在!");
return;
}
decimal fee = (dbOrder.costPrice.ParseToDecimal() * 0.01m + dbOrder.deliveryFee.ParseToDecimal() * 0.01m +
dbOrder.markFee.ParseToDecimal() * 0.01m) * dbOrder.purchaseQuantity;
if (fee <= 0)
{
BaseMsgForm.ShowError("该订单类型不支持操作!");
return;
}
JitOrderUploadFileForm uploadFileForm = new JitOrderUploadFileForm(dbOrder);
uploadFileForm.isClientJit = this.IsClientJit;
uploadFileForm.ShowDialog();
SetRowLinkCellText(dbOrder, row);
}
break;
case "上传订单":
{
var dbOrder = this.lstTemuDBOrderInfo.FirstOrDefault(o => o.subPurchaseOrderSn == subOrderId);
var row = dgvStock.Rows[e.RowIndex];
if (IsClientJit)
{
if (row.Cells["colUploadOrder"].Value.ParseToString() != "上传订单")
{
//BaseMsgForm.ShowError("订单状态不可上传!");
return;
}
if (BaseMsgForm.ShowConfirm("确定上传?将扣除授权金!").DialogResult == DialogResult.OK)
{
decimal fee = (dbOrder.costPrice.ParseToDecimal() * 0.01m + dbOrder.deliveryFee.ParseToDecimal() * 0.01m +
dbOrder.markFee.ParseToDecimal() * 0.01m) * dbOrder.purchaseQuantity;
if (fee < 0)
{
BaseMsgForm.ShowError("该订单类型不支持操作!");
return;
}
if (fee > BaseClass.AuthorizedAmount)
{
BaseMsgForm.ShowError("剩余授权金不足,请联系管理员!");
return;
}
var url = BaseClass.BuildObjString("order/upload_order");
var data = UserLogin.GetSignaturex();
data += "&shop_id=" + dbOrder.supplierId;
data += "&subPurchaseOrderSn=" + dbOrder.subPurchaseOrderSn;
data += "&purchaseTime=" + dbOrder.purchaseTime;
data += "&fee=" + fee;
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"))
{
var errMsg = BaseRegex.GetStringJson(ref html, "msg");
BaseMsgForm.ShowError(errMsg);
return;
}
else
{
BaseClass.AuthorizedAmount -= fee;
this.lblAuthorizedAmount.Text = "剩余授权金:" + BaseClass.AuthorizedAmount;
dbOrder.upLoadStatus = 2;
SetRowLinkCellText(dbOrder, row);
}
}
}
else
{
if (row.Cells["colUploadOrder"].Value.ParseToString() == "已上传 点击打单")
{
if (BaseMsgForm.ShowConfirm("确定更改状态为发货?").DialogResult == DialogResult.OK)
{
decimal fee = (dbOrder.deliveryFee.ParseToDecimal() * 0.01m + dbOrder.markFee.ParseToDecimal() * 0.01m) * dbOrder.purchaseQuantity;
var url = BaseClass.BuildObjString("order/update_order_status");
var data = UserLogin.GetSignaturex();
data += "&shop_id=" + dbOrder.supplierId;
data += "&subPurchaseOrderSn=" + dbOrder.subPurchaseOrderSn;
data += "&purchaseTime=" + dbOrder.purchaseTime;
data += "&new_status=3";
data += "&old_status=2";
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"))
{
var errMsg = BaseRegex.GetStringJson(ref html, "msg");
BaseMsgForm.ShowError(errMsg);
return;
}
else
{
dbOrder.upLoadStatus = 3;
SetRowLinkCellText(dbOrder, row);
}
}
}
else if (row.Cells["colUploadOrder"].Value.ParseToString() == "已打单 点击发货")
{
if (BaseMsgForm.ShowConfirm("确定更改状态为发货?").DialogResult == DialogResult.OK)
{
decimal fee = (dbOrder.deliveryFee.ParseToDecimal() * 0.01m + dbOrder.markFee.ParseToDecimal() * 0.01m) * dbOrder.purchaseQuantity;
var url = BaseClass.BuildObjString("order/update_order_status");
var data = UserLogin.GetSignaturex();
data += "&shop_id=" + dbOrder.supplierId;
data += "&subPurchaseOrderSn=" + dbOrder.subPurchaseOrderSn;
data += "&purchaseTime=" + dbOrder.purchaseTime;
data += "&new_status=4";
data += "&old_status=3";
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"))
{
var errMsg = BaseRegex.GetStringJson(ref html, "msg");
BaseMsgForm.ShowError(errMsg);
return;
}
else
{
dbOrder.upLoadStatus = 4;
SetRowLinkCellText(dbOrder, row);
}
}
}
}
}
break;
case "":
dgvStock.Rows[e.RowIndex].Cells["colCheck"].Value = !(bool)dgvStock.Rows[e.RowIndex].Cells["colCheck"].Value;
break;
default:
break;
}
}
private void btnFilter_Click(object sender, EventArgs e)
{
//if (IsClientJit)
{
foreach (DataGridViewRow row in dgvStock.Rows)
{
FilterRow(row);
}
}
//else
{
}
}
void FilterRow(DataGridViewRow row)
{
if (row.Cells["colSubOrderSn"].Value.ParseToString().Contains(txtSubOrderSn.Text.Trim()) &&
(row.Cells["colProductId"].Value.ParseToString().Contains(txtProductId.Text.Trim()) || row.Cells["colProdSkc"].Value.ParseToString().Contains(txtProductId.Text.Trim())) &&
row.Cells["colProductSn"].Value.ParseToString().Contains(txtProductSn.Text.Trim()))
{
row.Visible = true;
}
else
{
row.Visible = false;
}
}
private void btnRestore_Click(object sender, EventArgs e)
{
txtSubOrderSn.Text = txtProductSn.Text = txtProductId.Text = "";
}
private void btnGetDbOrder_Click(object sender, EventArgs e)
{
lstTemuDBOrderInfo.Clear();
dgvStock.Rows.Clear();
this.pbLoading.Visible = true;
Task.Run(() =>
{
if(IsClientJit)
clientLoadServerDbOrder();
else
loadServerDbOrder(null);
Invoke(new Action(() => { this.pbLoading.Visible = false; }));
});
}
private void ucSplitPage1_PageChange(object obj)
{
if (!IsClientJit)
{
SearchShop(this.ucSplitPage1.CurrentPage);
}
}
private void lblRefreshAmount_Click(object sender, EventArgs e)
{
var url = BaseClass.BuildObjString("user/get_user_amount");
var data = UserLogin.GetSignaturex();
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"))
{
var errMsg = BaseRegex.GetStringJson(ref html, "msg");
BaseMsgForm.ShowError(errMsg);
return;
}
else
{
BaseClass.AuthorizedAmount = BaseRegex.GetStringJson(ref html, "data").ParseToDecimal();
this.lblAuthorizedAmount.Text = "" + BaseClass.AuthorizedAmount.ParseToDecimal().ToString("0.0");
}
}
void statisticsListOrder()
{
Invoke(new Action(() =>
{
lblOriginalOrderNumber.Text = this.dgvStock.Rows.Cast<DataGridViewRow>().Select(r => r.Cells["colParentStockId"].Value.ParseToString()).Distinct().Count().ToString();
lblOrderNumber.Text = this.dgvStock.Rows.Cast<DataGridViewRow>().Select(r => r.Cells["colSubOrderSn"].Value.ParseToString()).Distinct().Count().ToString();
lblOrderTotalPrice.Text = lstTemuDBOrderInfo.Where(o => o.costPrice > 0).Sum(o => o.supplierPrice * o.purchaseQuantity * 0.01).ToString("0.00");
lblOrderTotalCost.Text = lstTemuDBOrderInfo.Where(o => o.costPrice > 0).Sum(o => (o.costPrice + o.deliveryFee + o.markFee) * o.purchaseQuantity * 0.01).ParseToDecimal().ToString("0.00");
lblOrderTotalProfit.Text = (lblOrderTotalPrice.Text.ParseToDecimal() - lblOrderTotalCost.Text.ParseToDecimal()).ToString("0.00");
}));
}
}
}