Files
KJD/TEMUKJD/KJDForms/ShopForms/FreightTemplateForm.cs
T

666 lines
28 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
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 AllBase;
using AllBase.Helper;
using AllBase.Model.Param.OrderManage;
using AllBase.Model.Result;
using TemuKJD.Extension;
using TemuKJD.KJDForms.BaseForms;
using NaiBa.Util.Extension;
using NaiBa.Util.Helper;
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 Work;
using Work.DouyinApiClass;
namespace TemuKJD.KJDForms.ShopForms
{
public partial class FreightTemplateForm : Form
{
public static List<AddressAreaInfo> LstAddress = new List<AddressAreaInfo>();
public static List<string> CustomFreightTemplateNames { get; set; } = new List<string>();
public static Dictionary<string, string> AreaNotSendDict = new Dictionary<string, string>();
private CheckBox chkSelectAll = null;
public CancellationTokenSource cancellationTokenSource { get; set; } = null;
public FreightTemplateForm()
{
InitializeComponent();
}
private void FreightTemplateForm_Load(object sender, EventArgs e)
{
pnlSamePostage.Location = pnlStepPostage.Location;
this.ucTabControl1.TabPages.Clear();
CustomFreightTemplateNames = ConfigHelper.LoadConfig<List<string>>("freight_template_custom_names");
if (CustomFreightTemplateNames == null)
{
CustomFreightTemplateNames = new List<string>();
}
AreaNotSendDict = ConfigHelper.LoadConfig<Dictionary<string, string>>("not_send_address");
if (AreaNotSendDict == null)
AreaNotSendDict = new Dictionary<string, string>();
chkSelectAll = dgvShop.Columns["colSelect"].AddHeaderCheckBox(HorizontalAlignment.Center, 0, 0, null, null, false);
dgvShop.Columns["colSelect"].HeaderText = "";
chkSelectAll.Width = chkSelectAll.Height = 13;
chkSelectAll.CheckedChanged += chkSelectAll_CheckedChanged;
GetAddress("0");
var provinceNames = LstAddress.Where(a => a.level == "Province").Select(a => a.name as object).ToArray();
this.cmbProvince.Items.Clear();
this.cmbProvince.Items.AddRange(provinceNames);
this.cmbProvince.SelectedIndex = 0;
}
private void FreightTemplateForm_VisibleChanged(object sender, EventArgs e)
{
if (Visible == true)
RefreshShop();
}
private void btnRefreshShop_Click(object sender, EventArgs e)
{
RefreshShop();
}
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();
// 获取被删除的店铺
List<DataGridViewRow> dgvRowList = dgvShop.Rows.Cast<DataGridViewRow>().Where(row
=> !GlobalConfig.ShopLoginList.Any(s => s.ShopId == row.Cells["colShopId"]?.Value?.ToString())).ToList();
// 更新被删除的店铺列表
foreach (var row in dgvRowList)
{
dgvShop.Rows.Remove(row);
}
// 绑定其他店铺(含新导入的店铺)
foreach (DouShopLoginInfo shopEntity in GlobalConfig.ShopLoginList)
{
BindShop(shopEntity, selectIds);
}
}
private void BindShop(DouShopLoginInfo shopEntity, List<string> selectShopId = null)
{
if (shopEntity == null)
return;
if (selectShopId == null)
selectShopId = new List<string>();
bool canUse = shopEntity.BuyApiAuth.ApiAuthStatus == "授权成功" && shopEntity.LoginStatus == "登录成功";
var row = dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(p => p.Cells.GetCellValueFromColumnName("colShopId").ParseToString() == shopEntity.ShopId);
if (row == null)
{
this.dgvShop.Rows.Add(
selectShopId.Contains(shopEntity.ShopId) && canUse,
shopEntity.ShopId,
shopEntity.ShopAccount,
shopEntity.BuyApiAuth.ApiAuthStatus,
shopEntity.LoginStatus,
canUse,
string.Empty
);
}
else
{
row.Cells["colSelect"].Value = selectShopId.Contains(shopEntity.ShopId) && canUse;
row.Cells["colShopName"].Value = shopEntity.ShopAccount;
row.Cells["colBuyAuthStatus"].Value = shopEntity.BuyApiAuth.ApiAuthStatus;
row.Cells["colLoginStatus"].Value = shopEntity.LoginStatus;
row.Cells["colCanUse"].Value = canUse;
}
}
private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
if (!chkSelectAll.Checked)
{
foreach (DataGridViewRow row in dgvShop.Rows)
{
row.Cells["colSelect"].Value = false;
}
}
else
{
var list = GlobalConfig.ShopLoginList.Where(s => s.ApiAuthStatus == "授权成功" && s.LoginStatus == "登录成功").Select(ss => ss.ShopId);
foreach (DataGridViewRow row in dgvShop.Rows)
{
if (list.Any(l => l == row.Cells["colShopId"]?.Value?.ToString()))
row.Cells["colSelect"].Value = true;
}
}
}
private void dgvShop_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
string headerText = dgvShop.Columns[e.ColumnIndex].HeaderText;
string columnName = dgvShop.Columns[e.ColumnIndex].Name;
long shopId = dgvShop.Rows[e.RowIndex].Cells["colShopId"].Value.ParseToLong();
string shopName = dgvShop.Rows[e.RowIndex].Cells["colShopId"].Value.ToString();
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId.ToString());
var row = dgvShop.Rows[e.RowIndex];
switch (columnName)
{
case "colSelect":
if (row.Cells["colCanUse"].Value.ParseToBool())
{
row.Cells["colSelect"].Value = !row.Cells["colSelect"].Value.ParseToBool();
if (dgvShop.Rows.Cast<DataGridViewRow>().All(r => r.Cells["colSelect"].Value.ParseToBool()))
chkSelectAll.Checked = true;
else
chkSelectAll.Checked = false;
}
else
{
BaseMsgForm.ShowInfo("店铺未授权或未登录!");
}
break;
}
}
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;
}
string searchText = txtSearchText.Text.Trim();
btnSearch.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
var lstShopIdTemp = new List<string>();
lstShopIdTemp.AddRange(lstShopId);
foreach (var shopId in lstShopIdTemp)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
continue;
if (ShopListForm.Instance == null)
ShopListForm.Instance = new ShopListForm();
ShopListForm.Instance.CheckShopLogin(new string[] { shop.ShopAccount }, false);
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() =>
{
var row = this.dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId);
if (row != null)
{
row.Cells["colLoginStatus"].Value = "未登录";
row.Cells["colCanUse"].Value = false;
}
}));
continue;
}
FreightTemplateListForm templateListForm = null;
Invoke(new Action(() =>
{
var tab = this.ucTabControl1.TabPages.Cast<TabPage>().FirstOrDefault(t => t.Text == shop.ShopAccount && t.Name == "tab" + shop.ShopId);
if (tab == null)
{
tab = new TabPage();
tab.Name = "tab" + shop.ShopId;
tab.Text = shop.ShopAccount;
this.ucTabControl1.TabPages.Add(tab);
var freightTemplateListForm = new FreightTemplateListForm(shop);
//freightTemplateListForm.SeckillingAndLimitedSalesForm = this;
freightTemplateListForm.TopLevel = false;
freightTemplateListForm.Left = 0;
freightTemplateListForm.Top = 0;
freightTemplateListForm.FormBorderStyle = FormBorderStyle.None;
freightTemplateListForm.AutoSize = true;
freightTemplateListForm.Dock = DockStyle.Fill;
freightTemplateListForm.Show();
tab.Controls.Add(freightTemplateListForm);
templateListForm = freightTemplateListForm;
}
if (tab.Controls.Count > 0)
{
templateListForm = tab.Controls[0] as FreightTemplateListForm;
this.ucTabControl1.SelectedTab = tab;
}
}));
if (templateListForm != null)
{
templateListForm.GetTemplate(this.txtSearchText.Text);
}
}
Invoke(new Action(() =>
{
btnSearch.Enabled = true;
}));
}, cancellationTokenSource.Token);
}
public static AddressAreaInfo GetAddress(string areaId)
{
if (LstAddress.Count == 0)
LstAddress = ConfigHelper.LoadConfig<List<AddressAreaInfo>>("address_area");
if (LstAddress == null)
LstAddress = new List<AddressAreaInfo>();
if (string.IsNullOrEmpty(areaId) || areaId == "0")
{
if (LstAddress.Count > 0)
return null;
}
var addr = LstAddress.FirstOrDefault(a => a.code.ToString() == areaId);
if (addr != null && (addr.sub_districts != null || addr.level == "Town"))
return addr;
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.BuyApiAuth.ApiAuthStatus == "授权成功");
if (shop == null)
{
BaseMsgForm.ShowError("请确保有店铺拍单授权成功!");
return null;
}
DouyinApi api = new DouyinApi(shop);
var result = api.GetDouyinAddressAreaByBuyApi(areaId);
if (!result.Contains("\"code\":10000"))
{
var msg = BaseRegex.GetStringJson(ref result, "msg") + ":" + BaseRegex.GetStringJson(ref result, "sub_msg");
BaseMsgForm.ShowError(msg);
return null;
}
if (string.IsNullOrEmpty(areaId) || areaId == "0")
{
JObject obj = JObject.Parse(result);
List<AddressProvinceInfo> provinceList = AllBase.JsonHelper.DeserializeJsonToList<AddressProvinceInfo>(obj["data"].ToString());
foreach (var province in provinceList)
{
LstAddress.Add(new AddressAreaInfo()
{
father_code = 1,
code = province.province_id.ParseToInt(),
level = "Province",
name = province.province,
});
}
ConfigHelper.SaveConfig("address_area", LstAddress);
return LstAddress.FirstOrDefault();
}
else
{
JObject obj = JObject.Parse(result);
AddressAreaInfo area = AllBase.JsonHelper.DeserializeJsonToObject<AddressAreaInfo>(obj["data"].FirstOrDefault().ToString());
if (area != null)
{
var areaExist = LstAddress.FirstOrDefault(a => a.name == area.name && a.level == area.level);
if (areaExist == null)
{
LstAddress.Add(area);
ConfigHelper.SaveConfig("address_area", LstAddress);
return area;
}
else
{
areaExist.sub_districts = area.sub_districts;
areaExist.father_code = area.father_code;
ConfigHelper.SaveConfig("address_area", LstAddress);
return areaExist;
}
foreach (var area1 in area.sub_districts)
{
}
}
}
return null;
}
private void cmbProvince_SelectedIndexChanged(object sender, EventArgs e)
{
var area = LstAddress.FirstOrDefault(a => a.name == cmbProvince.Text && a.level == "Province");
if (area != null)
{
if (area.sub_districts == null || area.sub_districts.Count == 0)
{
area = GetAddress(area.code.ToString());
}
var cityArr = area.sub_districts.Select(a => a.name).ToArray();
this.cmbCity.Items.Clear();
this.cmbCity.Items.AddRange(cityArr);
this.cmbCity.SelectedIndex = 0;
}
}
private void btnStopSearch_Click(object sender, EventArgs e)
{
if (cancellationTokenSource != null)
cancellationTokenSource.Cancel();
}
private void btnSetName_Click(object sender, EventArgs e)
{
FreightTemplateNameForm customNameForm = new FreightTemplateNameForm();
customNameForm.ShowDialog();
}
private void rbStepPostage_CheckedChanged(object sender, EventArgs e)
{
pnlStepPostage.Visible = rbStepPostage.Checked;
}
private void rbSamePostage_CheckedChanged(object sender, EventArgs e)
{
pnlSamePostage.Visible = rbSamePostage.Checked;
}
private void rbWithWeight_CheckedChanged(object sender, EventArgs e)
{
if (rbWithWeight.Checked)
{
lblWeightOrCountStep1.Text = "kg以内,";
lblWeightOrCountStep2.Text = "kg,增加运费";
}
else
{
lblWeightOrCountStep1.Text = "件以内,";
lblWeightOrCountStep2.Text = "件,增加运费";
}
}
private void btnSetNotArea_Click(object sender, EventArgs e)
{
FreightTemplateNotSendAreaForm form = new FreightTemplateNotSendAreaForm();
form.ShowDialog();
}
private void btnAdd_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;
}
int templateCount = nudGroupCount.Value.ParseToInt();
bool isLimit = chkLimited.Checked;
List<string> nameList = new List<string>();
if (rbCustomName.Checked)
{
if (CustomFreightTemplateNames.Count < templateCount)
{
BaseMsgForm.ShowError("自定义模板名称数量不足");
return;
}
for (int i = 0; i < templateCount; i++)
{
nameList.Add(CustomFreightTemplateNames[i]);
}
}
else
{
var name = "模板" + DateTime.Now.ToString("yyMMddHHmmss");
for (int i = 0; i < templateCount; i++)
{
nameList.Add(name + "-" + i.ToString());
}
}
TemplateParam templateParam = new TemplateParam();
var area = LstAddress.FirstOrDefault(a => a.name == cmbProvince.Text && a.level == "Province");
if (area != null)
{
templateParam.product_province = area.code;
templateParam.product_city = (area.sub_districts.FirstOrDefault(a => a.name == cmbCity.Text && a.level == "City")?.code).ParseToLong();
}
if (rbStepPostage.Checked && rbWithWeight.Checked)
templateParam.calculate_type = 1;
templateParam.transfer_type = 1;
templateParam.rule_type = rbStepPostage.Checked ? 0 : rbSamePostage.Checked ? 1 : 2;
templateParam.fixed_amount = (int)(txtSamePostagePrice.Text.ParseToDecimal() * 100);
List<TemplateRulesParam> ruleList = new List<TemplateRulesParam>();
if (templateParam.rule_type == 0)
{
TemplateRulesParam defaultRules = new TemplateRulesParam();
defaultRules.is_default = 1;
if (rbWithCount.Checked)
{
defaultRules.first_num = txtWeightOrCountStep1.Text.ParseToInt();
defaultRules.first_num_price = txtWeightOrCountPrice1.Text.ParseToDecimal();
defaultRules.add_num = txtWeightOrCountStep2.Text.ParseToInt();
defaultRules.add_num_price = txtWeightOrCountPrice2.Text.ParseToDecimal();
}
else
{
defaultRules.first_weight = txtWeightOrCountStep1.Text.ParseToInt();
defaultRules.first_weight_price = txtWeightOrCountPrice1.Text.ParseToDecimal();
defaultRules.add_weight = txtWeightOrCountStep2.Text.ParseToInt();
defaultRules.add_weight_price = txtWeightOrCountPrice2.Text.ParseToDecimal();
}
ruleList.Add(defaultRules);
}
if (isLimit)
{
TemplateRulesParam rules = new TemplateRulesParam();
if (ruleList.Count == 0)
{
//rules.is_default = 1;
}
rules.is_limited = true;
Dictionary<string, object> pDict = new Dictionary<string, object>();
foreach (var key in AreaNotSendDict.Keys)
{
var keys = key.Trim('p').Split('c', 'd', 't');
if (!pDict.Keys.Contains(keys[0]))
pDict[keys[0]] = null;
if (keys.Length > 1)
{
var cDict = pDict[keys[0]] as Dictionary<string, object>;
if (cDict == null)
{
cDict = new Dictionary<string, object>();
pDict[keys[0]] = cDict;
}
if (!cDict.Keys.Contains(keys[1]))
cDict[keys[1]] = null;
if (keys.Length > 2)
{
var dDict = cDict[keys[1]] as Dictionary<string, object>;
if (dDict == null)
{
dDict = new Dictionary<string, object>();
cDict[keys[1]] = dDict;
}
if (!dDict.Keys.Contains(keys[2]))
dDict[keys[2]] = null;
if (keys.Length > 3)
{
var tList = new List<string>();
tList.Add(keys[3]);
if (dDict[keys[2]] == null)
dDict[keys[2]] = tList;
else
(dDict[keys[2]] as List<string>).AddRange(tList);
}
}
}
}
var str = AllBase.JsonHelper.SerializeObject(pDict);
//rules.rule_address = str.Replace("\"", "\\\"");
List<ProvinceInfo> areaInfos = new List<ProvinceInfo>();
foreach (var key in AreaNotSendDict.Keys)
{
var keys = key.Trim('p').Split('c', 'd', 't');
ProvinceInfo pInfo = areaInfos.FirstOrDefault(p => p.id == keys[0]);
if (pInfo == null)
{
pInfo = new ProvinceInfo() { id = keys[0] };
areaInfos.Add(pInfo);
}
if (keys.Length > 1)
{
if (pInfo.children == null)
pInfo.children = new List<ProvinceInfo>();
var cInfo = pInfo.children.FirstOrDefault(c => c.id == keys[1]);
if (cInfo == null)
{
cInfo = new ProvinceInfo() { id = keys[1] };
pInfo.children.Add(cInfo);
}
if (keys.Length > 2)
{
if (cInfo.children == null)
cInfo.children = new List<ProvinceInfo>();
var dInfo = cInfo.children.FirstOrDefault(d => d.id == keys[2]);
if (dInfo == null)
{
dInfo = new ProvinceInfo() { id = keys[2] };
cInfo.children.Add(dInfo);
}
if (keys.Length > 3)
{
if (dInfo.children == null)
dInfo.children = new List<ProvinceInfo>();
var tInfo = dInfo.children.FirstOrDefault(t => t.id == keys[3]);
if (tInfo == null)
{
tInfo = new ProvinceInfo() { id = keys[3] };
dInfo.children.Add(tInfo);
}
}
}
}
}
rules.province_infos = areaInfos;
ruleList.Add(rules);
}
btnSearch.Enabled = false;
cancellationTokenSource = new CancellationTokenSource();
Task.Run(() =>
{
var lstShopIdTemp = new List<string>();
lstShopIdTemp.AddRange(lstShopId);
foreach (var shopId in lstShopIdTemp)
{
if (cancellationTokenSource.IsCancellationRequested)
break;
var shop = GlobalConfig.ShopLoginList.FirstOrDefault(s => s.ShopId == shopId);
if (shop == null)
continue;
if (ShopListForm.Instance == null)
ShopListForm.Instance = new ShopListForm();
ShopListForm.Instance.CheckShopLogin(new string[] { shop.ShopAccount }, false);
if (shop.LoginStatus != "登录成功")
{
Invoke(new Action(() =>
{
var row = this.dgvShop.Rows.Cast<DataGridViewRow>().FirstOrDefault(r => r.Cells["colShopId"].Value.ToString() == shop.ShopId);
if (row != null)
{
row.Cells["colLoginStatus"].Value = "未登录";
row.Cells["colCanUse"].Value = false;
}
}));
continue;
}
FreightTemplateListForm templateListForm = null;
Invoke(new Action(() =>
{
var tab = this.ucTabControl1.TabPages.Cast<TabPage>().FirstOrDefault(t => t.Text == shop.ShopAccount && t.Name == "tab" + shop.ShopId);
if (tab == null)
{
tab = new TabPage();
tab.Name = "tab" + shop.ShopId;
tab.Text = shop.ShopAccount;
this.ucTabControl1.TabPages.Add(tab);
var freightTemplateListForm = new FreightTemplateListForm(shop);
//freightTemplateListForm.SeckillingAndLimitedSalesForm = this;
freightTemplateListForm.TopLevel = false;
freightTemplateListForm.Left = 0;
freightTemplateListForm.Top = 0;
freightTemplateListForm.FormBorderStyle = FormBorderStyle.None;
freightTemplateListForm.AutoSize = true;
freightTemplateListForm.Dock = DockStyle.Fill;
freightTemplateListForm.Show();
tab.Controls.Add(freightTemplateListForm);
templateListForm = freightTemplateListForm;
}
if (tab.Controls.Count > 0)
{
templateListForm = tab.Controls[0] as FreightTemplateListForm;
this.ucTabControl1.SelectedTab = tab;
}
}));
if (templateListForm != null)
{
templateListForm.AddTemplate(nameList, templateParam, ruleList);
}
}
Invoke(new Action(() =>
{
btnSearch.Enabled = true;
}));
}, cancellationTokenSource.Token);
}
private void btnStopAdd_Click(object sender, EventArgs e)
{
}
}
}