发票助手修改,增加时间范围,增加上次读取历史,修复bug

This commit is contained in:
chfei committed 2026-09-18 14:32:52 +08:00
1 parent b42c17c013
commit 9e62672013
8 files changed
+729 -218

No files matched your search

@@ -5,55 +5,192 @@ using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Work;
namespace _29WxOrderWpf.Converters
{
public class ImageUrlToBitmapImageConverter : IValueConverter
{
/// <summary> 缓存上限,防止大量缩略图重复下载导致内存膨胀 </summary>
private const int MaxCacheCount = 200;
public class ImageUrlToBitmapImageConverter : IMultiValueConverter
{
/// <summary> 缓存上限,防止大量缩略图重复下载导致内存膨胀 </summary>
private const int MaxCacheCount = 200;
private readonly ConcurrentDictionary<string, BitmapImage> _imageCache = new ConcurrentDictionary<string, BitmapImage>();
private readonly ConcurrentDictionary<string, BitmapImage> _imageCache = new ConcurrentDictionary<string, BitmapImage>();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string url && Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
if (_imageCache.TryGetValue(url, out BitmapImage cached))
{
return cached;
}
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length == 0 || values[0] == DependencyProperty.UnsetValue)
return null;
var url = values[0] as string;
var isLoad = values[1] is bool b && b;
if (!isLoad || string.IsNullOrEmpty(url))
return null; // 或返回占位图
if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
if (_imageCache.TryGetValue(url, out BitmapImage cached))
{
return cached;
}
try
{
// 直接加载绑定如果遇到有问题的网络图片会直接崩溃。
BitmapImage bitMap = AllBase.ImageBuild.LoadBitmipImageFromUrl(url);
if (bitMap != null)
{
if (_imageCache.Count >= MaxCacheCount)
{
_imageCache.Clear();
}
_imageCache[url] = bitMap;
}
return bitMap;
}
catch
{
try
{
// 直接加载绑定如果遇到有问题的网络图片会直接崩溃。
BitmapImage bitMap = AllBase.ImageBuild.LoadBitmipImageFromUrl(url);
if (bitMap != null)
{
if (_imageCache.Count >= MaxCacheCount)
{
_imageCache.Clear();
}
_imageCache[url] = bitMap;
}
return bitMap;
}
catch
{
}
}
return null;
}
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException(); // 不需要反向转换,所以不实现。
}
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
// 建议作为静态字段复用,不要每次调用都 new HttpClient()
private static readonly HttpClient _httpClient = new HttpClient();
}
public class ImageLoadRequest
{
public string Url { get; set; }
public bool IsLoad { get; set; }
// 用于避免相同状态重复触发下载逻辑
public override bool Equals(object obj) =>
obj is ImageLoadRequest other && other.Url == Url && other.IsLoad == IsLoad;
public override int GetHashCode() => Url.GetHashCode();
}
public class ImageLoadRequestConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var url = values[0] as string;
var isLoad = values.Length > 1 && values[1] is bool b && b;
return new ImageLoadRequest { Url = url, IsLoad = isLoad };
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
public static class AsyncImageLoader
{
private static readonly HttpClient _httpClient = new HttpClient();
private static readonly ConcurrentDictionary<string, Task<BitmapImage>> _cache
= new ConcurrentDictionary<string, Task<BitmapImage>>();
public static readonly DependencyProperty RequestProperty =
DependencyProperty.RegisterAttached(
"Request",
typeof(ImageLoadRequest),
typeof(AsyncImageLoader),
new PropertyMetadata(null, OnRequestChanged));
public static ImageLoadRequest GetRequest(DependencyObject obj) => (ImageLoadRequest)obj.GetValue(RequestProperty);
public static void SetRequest(DependencyObject obj, ImageLoadRequest value) => obj.SetValue(RequestProperty, value);
private static readonly DependencyProperty CurrentUrlProperty =
DependencyProperty.RegisterAttached("CurrentUrl", typeof(string), typeof(AsyncImageLoader), new PropertyMetadata(null));
private static string GetCurrentUrl(DependencyObject obj) => (string)obj.GetValue(CurrentUrlProperty);
private static void SetCurrentUrl(DependencyObject obj, string value) => obj.SetValue(CurrentUrlProperty, value);
private static readonly DependencyProperty CtsProperty =
DependencyProperty.RegisterAttached("Cts", typeof(CancellationTokenSource), typeof(AsyncImageLoader), new PropertyMetadata(null));
private static CancellationTokenSource GetCts(DependencyObject obj) => (CancellationTokenSource)obj.GetValue(CtsProperty);
private static void SetCts(DependencyObject obj, CancellationTokenSource value) => obj.SetValue(CtsProperty, value);
private static void OnRequestChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is Image image)) return;
// 值没变(Equals 重写过),不做任何事,避免无意义触发
if (Equals(e.OldValue, e.NewValue)) return;
var request = e.NewValue as ImageLoadRequest;
GetCts(image)?.Cancel();
if (request == null || !request.IsLoad || string.IsNullOrEmpty(request.Url))
{
return; // 滚动中,不加载,保留原图,不产生任何开销
}
string url = request.Url;
SetCurrentUrl(image, url);
var cts = new CancellationTokenSource();
SetCts(image, cts);
// 关键:把真正的下载动作丢到 Dispatcher 队列里、用较低优先级去做,
// 避免在当前这一帧的布局/绑定更新过程中做任何"重"的同步开销,
// 也顺便起到一个天然的"防抖"效果——如果这一帧内 Request 又变了
// (比如滚动中又切回别的 item),上面的 Cancel() 已经先取消了。
image.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(async () =>
{
if (cts.IsCancellationRequested) return;
try
{
var bitmap = await LoadBitmapAsync(url, cts.Token);
if (bitmap != null && GetCurrentUrl(image) == url && !cts.IsCancellationRequested)
{
image.Source = bitmap;
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error loading image from {url}: {ex.Message}");
}
}));
}
private static Task<BitmapImage> LoadBitmapAsync(string url, CancellationToken token)
{
return _cache.GetOrAdd(url, async u =>
{
using var response = await _httpClient.GetAsync(u, token);
response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsByteArrayAsync();
using var stream = new MemoryStream(data);
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.DecodePixelWidth = 200;
bitmap.EndInit();
bitmap.Freeze();
return bitmap;
});
}
}
}
@@ -0,0 +1,87 @@
<UserControl
x:Class="_29WxOrderWpf.Ctrls.PDDInvoice.PDDInvoiceDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:_29WxOrderWpf.Ctrls.PDDInvoice"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wpf="WPFCommon"
Width="400"
Height="250"
d:Background="White"
d:DataContext="{d:DesignInstance Type=local:PDDInvoiceDialog}"
mc:Ignorable="d">
<UserControl.Resources>
<Style BasedOn="{StaticResource TitleContentBaseStyle}" TargetType="wpf:TitleContent">
<Setter Property="Placement" Value="Left" />
<Setter Property="Height" Value="28" />
<Setter Property="TitleVerticalAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="TitleHorizontalAlignment" Value="Right" />
<Setter Property="TitleWidth" Value="50" />
<Style.Resources>
<Style TargetType="TextBox">
<Setter Property="Height" Value="28" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
</Style.Resources>
</Style>
</UserControl.Resources>
<Border
Margin="10"
Padding="5"
BorderBrush="Gray"
BorderThickness="1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<wpf:SpacingStackPanel
Grid.Row="0"
Orientation="Vertical"
VerticalSpacing="10">
<wpf:TitleContent Title="公司:">
<TextBox d:Text="嵩县雷神商贸有限责任公司" Text="{Binding Config.Title}" />
</wpf:TitleContent>
<wpf:TitleContent Title="税号:">
<TextBox d:Text="91410325MADQERT68E" Text="{Binding Config.TaxNo}" />
</wpf:TitleContent>
<wpf:TitleContent Title="最大金额:">
<wpf:NumberBox
Width="80"
HorizontalAlignment="Left"
Maximum="999999"
Minimum="0"
Value="{Binding Config.MaxAmount}" />
</wpf:TitleContent>
<wpf:TitleContent Title="数据保存:">
<CheckBox IsChecked="{Binding Config.IsSaveData}" />
</wpf:TitleContent>
</wpf:SpacingStackPanel>
<Border
Grid.Row="1"
Margin="-5"
Padding="0,5"
BorderBrush="Gray"
BorderThickness="0,1,0,0">
<wpf:SpacingStackPanel HorizontalAlignment="Center" HorizontalSpacing="30">
<Button
Padding="10,5"
Command="{Binding ConfirmCommand}"
Content="确定"
Style="{StaticResource BasePageButtonStyle}" />
<Button
Padding="10,5"
Command="{Binding CancelCommand}"
Content="取消"
Style="{StaticResource BasePageButtonLightStyle}" />
</wpf:SpacingStackPanel>
</Border>
</Grid>
</Border>
</UserControl>
@@ -0,0 +1,64 @@
using _29WxOrderWpf.Commands;
using _29WxOrderWpf.Ctrls.PDDInvoice.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPFCommon.Models;
using static Org.BouncyCastle.Math.EC.ECCurve;
namespace _29WxOrderWpf.Ctrls.PDDInvoice;
/// <summary>
/// PDDInvoiceDialog.xaml 的交互逻辑
/// </summary>
public partial class PDDInvoiceDialog : UserControl
{
public PDDInvoiceDialog()
{
InitializeComponent();
DataContext = this;
Config = NaiBa.Util.Helper.ConfigHelper.LoadConfig<InvoiceConfig>(ConfigPath);
}
private void PDDInvoiceDialog_Loaded(object sender, RoutedEventArgs e)
{
}
private void ViewModel_RequestClose()
{
Window parentWindow = Window.GetWindow(this);
if (this.IsLoaded && parentWindow != null)
parentWindow.Close();
}
private const string ConfigPath = "./invoice.config";
public InvoiceConfig Config { get; }
public ICommand ConfirmCommand => new DelegateCommand(Confirm);
private void Confirm()
{
NaiBa.Util.Helper.ConfigHelper.SaveConfig(ConfigPath, Config);
ViewModel_RequestClose();
}
public ICommand CancelCommand => new DelegateCommand(Cancel);
private void Cancel()
{
ViewModel_RequestClose();
}
}
@@ -16,15 +16,15 @@
d:DataContext="{d:DesignInstance Type=vm:PDDInvoiceViewModel,
IsDesignTimeCreatable=True}"
d:DesignHeight="720"
d:DesignWidth="1260"
d:DesignWidth="1960"
Background="White"
mc:Ignorable="d">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibility" />
<converters:ImageUrlToBitmapImageConverter x:Key="ImageUrlToBitmapImage" />
<converters:ImageUrlToBitmapImageConverter x:Key="ImageUrlToBitmapImageConverter" />
<converters:InverseVisibleToVisibilityConverter x:Key="InverseBooleanToVisibility" />
<converters:ImageLoadRequestConverter x:Key="ImageLoadRequestConverter" />
<!-- 原型配色 -->
<SolidColorBrush x:Key="PageBgBrush" Color="#F5F6F8" />
<SolidColorBrush x:Key="CardBgBrush" Color="#FFFFFF" />
@@ -50,7 +50,7 @@
<!-- 搜索 / 表单输入框 -->
<Style x:Key="SearchTextBoxStyle" TargetType="TextBox">
<Setter Property="Height" Value="36" />
<Setter Property="Height" Value="30" />
<Setter Property="Padding" Value="12,0" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="FontSize" Value="13" />
@@ -81,76 +81,9 @@
</Setter.Value>
</Setter>
</Style>
<!-- 主按钮 -->
<Style x:Key="PrimaryButtonStyle" TargetType="Button">
<Setter Property="Height" Value="36" />
<Setter Property="Padding" Value="18,0" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Background" Value="{StaticResource PrimaryBrush}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border
x:Name="border"
Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
CornerRadius="4">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="{StaticResource PrimaryHoverBrush}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Opacity" Value="0.8" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="border" Property="Opacity" Value="0.5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style BasedOn="{StaticResource BasePageButtonStyle}" TargetType="Button">
<Setter Property="Height" Value="30" />
</Style>
<!-- 默认按钮 -->
<Style x:Key="DefaultButtonStyle" TargetType="Button">
<Setter Property="Height" Value="36" />
<Setter Property="Padding" Value="18,0" />
<Setter Property="Foreground" Value="{StaticResource TextNormalBrush}" />
<Setter Property="Background" Value="White" />
<Setter Property="BorderBrush" Value="{StaticResource InputBorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border
x:Name="border"
Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#F5F7FA" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="border" Property="Opacity" Value="0.8" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- 文字链接按钮 -->
<Style x:Key="LinkButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Transparent" />
@@ -196,7 +129,7 @@
<Border Padding="10,10,10,0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="30" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
@@ -205,10 +138,9 @@
<Border Grid.Row="0">
<wpf:SpacingStackPanel Background="{StaticResource CardBgBrush}" HorizontalSpacing="10">
<Grid Width="300">
<Grid Width="200">
<TextBox
x:Name="txtSearch"
Height="30"
Padding="5,0,0,0"
KeyDown="txtSearch_KeyDown"
Style="{StaticResource SearchTextBoxStyle}"
@@ -228,7 +160,7 @@
TitleVerticalAlignment="Center">
<ComboBox
Width="100"
Height="28"
Height="30"
d:SelectedIndex="0"
SelectedIndex="{Binding InvoiceStatus}"
Style="{StaticResource RoundedComboBox}">
@@ -238,17 +170,40 @@
</ComboBox>
</wpf:TitleContent>
<wpf:TitleContent
Title="时间范围:"
HorizontalContentAlignment="Center"
Placement="Left"
TitleVerticalAlignment="Center">
<WrapPanel>
<DatePicker
Height="30"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
d:SelectedDate="2026/01/01"
SelectedDate="{Binding StartTime}" />
<Border
Width="5"
Height="1"
BorderBrush="LightGray"
BorderThickness="1" />
<DatePicker
Height="30"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
d:SelectedDate="2026/01/01"
SelectedDate="{Binding EndTime}" />
</WrapPanel>
</wpf:TitleContent>
<Button
Width="50"
Height="30"
Command="{Binding SearchCommand}"
Content="搜索"
Style="{StaticResource BasePageButtonStyle}" />
Content="搜索" />
<Button
Height="30"
Command="{Binding ResetCommand}"
Content="重置"
Style="{StaticResource DefaultButtonStyle}" />
Style="{StaticResource LinkButtonStyle}" />
<wpf:TitleContent
Title="买手号:"
@@ -263,11 +218,9 @@
Style="{StaticResource RoundedComboBox}" />
</wpf:TitleContent>
<Button
Height="30"
Padding="5,0"
Command="{Binding ReadOrderCommand}"
Content="读取订单"
Style="{StaticResource BasePageButtonStyle}"
Visibility="{Binding IsReadOrder, Converter={StaticResource Boolean2VisibilityReConverter}}" />
<Button
Height="30"
@@ -277,13 +230,16 @@
Style="{StaticResource BasePageButtonStyle}"
Visibility="{Binding IsReadOrder, Converter={StaticResource Boolean2VisibilityConverter}}" />
<Button
Height="30"
Padding="10,0"
Command="{Binding BatchInvoiceCommand}"
Content="批量开票"
Style="{StaticResource BasePageButtonStyle}" />
Content="批量开票" />
<Button
Padding="10,0"
Command="{Binding ShowSettingDialogCommand}"
Content="设置"
Style="{StaticResource BasePageButtonLightStyle}" />
<wpf:TitleContent
<!--<wpf:TitleContent
Title="公司:"
Placement="Left"
TitleVerticalAlignment="Center">
@@ -315,11 +271,12 @@
Maximum="999999"
Minimum="0"
Value="{Binding MaxAmount}" />
</wpf:TitleContent>
</wpf:TitleContent>-->
<CheckBox
VerticalContentAlignment="Center"
Content="显示订单窗口"
IsChecked="{Binding IsOrderListDialogOpen}" />
</wpf:SpacingStackPanel>
</Border>
<!-- 订单列表(已移除分页与订单分组) -->
@@ -419,6 +376,7 @@
<Border Background="White">
<!-- 列表(虚拟化滚动加载) -->
<ItemsControl
x:Name="itemsControl"
Margin="0,2,0,-2"
Padding="0"
HorizontalContentAlignment="Stretch"
@@ -426,8 +384,10 @@
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ScrollViewer
x:Name="PART_ScrollViewer"
CanContentScroll="True"
HorizontalScrollBarVisibility="Disabled"
ScrollChanged="ScrollViewer_ScrollChanged"
VerticalScrollBarVisibility="Auto">
<ItemsPresenter />
</ScrollViewer>
@@ -508,7 +468,27 @@
Height="72"
Background="#EEEEEE"
CornerRadius="5">
<Image Source="{Binding ThumbUrl, Converter={StaticResource ImageUrlToBitmapImage}, IsAsync=True}" Stretch="UniformToFill" />
<Image Stretch="UniformToFill">
<converters:AsyncImageLoader.Request>
<MultiBinding Converter="{StaticResource ImageLoadRequestConverter}">
<Binding Path="ThumbUrl" />
<Binding Path="DataContext.IsLoadImage" RelativeSource="{RelativeSource AncestorType=UserControl}" />
</MultiBinding>
</converters:AsyncImageLoader.Request>
</Image>
<!--<Image
converters:AsyncImageLoader.IsLoadImage="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext.IsLoadImage}"
converters:AsyncImageLoader.SourceUrl="{Binding ThumbUrl}"
Stretch="UniformToFill">
-->
<!--<Image.Source>
<MultiBinding Converter="{StaticResource ImageUrlToBitmapImageConverter}" Mode="OneWay">
<Binding IsAsync="True" Path="ThumbUrl" />
<Binding Path="DataContext.IsLoadImage" RelativeSource="{RelativeSource AncestorType=UserControl}" />
</MultiBinding>
</Image.Source>-->
<!--
</Image>-->
</Border>
<StackPanel
Grid.Column="1"
@@ -668,13 +648,12 @@
Value="{Binding ProgressValue}" />
<Grid Margin="10,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="100*" />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox
Grid.Row="2"
Grid.Column="1"
Grid.Column="0"
Margin="4,0,0,0"
VerticalAlignment="Center"
d:Text="共计:{}"
@@ -683,6 +662,17 @@
Foreground="White"
IsReadOnly="True"
Text="{Binding BottomMsg}" />
<TextBox
Grid.Column="1"
Margin="4,0,0,0"
VerticalAlignment="Center"
HorizontalContentAlignment="Right"
d:Text="共计:{}"
Background="Transparent"
BorderThickness="0"
Foreground="White"
IsReadOnly="True"
Text="{Binding BottomRMsg}" />
</Grid>
</Grid>
@@ -13,6 +13,7 @@ using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace _29WxOrderWpf.Ctrls.PDDInvoice;
@@ -21,10 +22,17 @@ namespace _29WxOrderWpf.Ctrls.PDDInvoice;
/// </summary>
public partial class PDDInvoiceView : UserControl
{
private PDDInvoiceViewModel vm = new PDDInvoiceViewModel();
public PDDInvoiceView()
{
InitializeComponent();
DataContext = new PDDInvoiceViewModel();
DataContext = vm;
vm.BatchInvoiceChanged += Vm_BatchInvoiceChanged;
}
private void Vm_BatchInvoiceChanged(object sender, int e)
{
ScrollToCurrent(e);
}
private void txtSearch_KeyDown(object sender, KeyEventArgs e)
@@ -34,4 +42,62 @@ public partial class PDDInvoiceView : UserControl
viewModel.SearchCommand.Execute(null);
}
}
private DispatcherTimer _scrollStopTimer;
private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
// 每次滚动都重置计时器
if (_scrollStopTimer == null)
{
_scrollStopTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(100) // 200ms 内无滚动视为停止
};
_scrollStopTimer.Tick += ScrollStopTimer_Tick;
}
_scrollStopTimer.Stop();
_scrollStopTimer.Start();
(DataContext as PDDInvoiceViewModel).IsLoadImage = false;
}
private void ScrollStopTimer_Tick(object sender, EventArgs e)
{
_scrollStopTimer.Stop();
System.Diagnostics.Debug.WriteLine("滚动停止了");
// 用 Background 优先级设置,避免和当前这一帧的滚动惯性/渲染争抢,
// 让 UI 线程先把滚动动画收尾,再去处理这一波图片加载触发
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
vm.IsLoadImage = true;
}));
}
private void ScrollToCurrent(int index)
{
if (itemsControl == null) return;
// 方案A:逻辑滚动(你的 CanContentScroll=True,推荐)
var sv = itemsControl.Template.FindName("PART_ScrollViewer", itemsControl) as ScrollViewer;
if (sv != null)
{
if (index >= 0)
{
sv.ScrollToVerticalOffset(index - 1);
return;
}
}
// 方案B:兜底,用容器 BringIntoView
itemsControl.UpdateLayout();
var container = itemsControl.ItemContainerGenerator
.ContainerFromItem(vm.SelectedOrder) as FrameworkElement;
container?.BringIntoView();
}
}
@@ -1,4 +1,5 @@
using AllBase.Model.Result;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -22,7 +23,6 @@ public class PddBrowserOrderInvoiceViewModel : BindableBaseEx
get => _isSelected;
set => SetProperty(ref _isSelected, value, nameof(IsSelected));
}
public string buyerId { get; set; } // 买手Id
public string buyerName { get; set; } // 买手名称
/// <summary>
@@ -41,7 +41,6 @@ public class PddBrowserOrderInvoiceViewModel : BindableBaseEx
/// 订单号
/// </summary>
public string order_sn { get; set; }
public int status { get; set; }
public int pay_status { get; set; }
public string order_status_prompt { get; set; }
@@ -51,11 +50,10 @@ public class PddBrowserOrderInvoiceViewModel : BindableBaseEx
public string order_link_url { get; set; }
public List<order_good> order_Goods { get; set; }
public List<OrderButtonItem> order_buttons { get; set; }
public string GoodsName { get => order_Goods?.FirstOrDefault()?.goods_name ?? ""; }
private string _goodsName;
public string GoodsName { get => _goodsName ?? order_Goods?.FirstOrDefault()?.goods_name ?? ""; set => _goodsName = value; }
/// <summary>
/// 是否已开票
/// </summary>
@@ -78,8 +76,27 @@ public class PddBrowserOrderInvoiceViewModel : BindableBaseEx
{
get => DateTimeHelper.ConvertFromUnixTimestampInSeconds(order_time);
}
public string ThumbUrl => order_Goods?.FirstOrDefault()?.thumb_url ?? "";
private string _thumburl;
public string ThumbUrl
{
get { return _thumburl ?? order_Goods?.FirstOrDefault()?.thumb_url ?? ""; }
set { _thumburl = value; }
}
public string DisplayAmount => (order_amount / 100.0).ToString("F2");
public PddBrowserOrderInvoiceViewModel()
{
}
public PddBrowserOrderInvoiceViewModel(OrderInvoiceInfo info)
{
_goodsName = info.GoodsName;
order_amount = info.order_amount;
order_time = info.order_time;
order_sn = info.order_sn;
order_link_url = info.order_link_url;
IsInvoiced = info.IsInvoiced;
_thumburl = info.ThumbUrl;
}
}
public class OrderButtonItem
@@ -91,4 +108,31 @@ public class OrderButtonItem
public class ButtonTypeValue
{
public string Url { get; set; }
}
public class OrderInvoiceInfo
{
/// <summary>
/// 订单价
/// </summary>
public int order_amount { get; set; }
/// <summary>
/// 下单时间
/// </summary>
public long order_time { get; set; }
/// <summary>
/// 订单号
/// </summary>
public string order_sn { get; set; }
/// <summary>
/// 订单详情
/// </summary>
public string order_link_url { get; set; }
/// <summary>
/// 是否已开票
/// </summary>
public bool IsInvoiced { get; set; }
public string ThumbUrl { get; set; }
public string GoodsName { get; set; }
}
@@ -105,8 +105,8 @@ public partial class PDDInvoiceViewModel
private async Task ExecuteInvoiceApplyScriptAsync(ChromiumWebBrowser b)
{
string content = ResourceHelper.GetResourceText("/Ctrls/PDDInvoice/Resources/invoice.js", "29WxFindOrder");
content = content.Replace("{公司}", InvoiceTitle);
content = content.Replace("{税号}", TaxNo);
content = content.Replace("{公司}", Config.Title);
content = content.Replace("{税号}", Config.TaxNo);
if (string.IsNullOrEmpty(content)) return;
await b.EvaluateScriptAsync(content);
@@ -210,8 +210,6 @@ public partial class PDDInvoiceViewModel
{
IsReadOrder = false;
_cancellationTokenSource?.Cancel();
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = null;
}
private async Task autoScroll(CancellationToken token)
@@ -2,6 +2,7 @@ using _29WxOrderWpf.BaseWindows;
using _29WxOrderWpf.CefHelper;
using _29WxOrderWpf.Commands;
using _29WxOrderWpf.Common;
using _29WxOrderWpf.Ctrls.Statistics;
using AllBase;
using AllBase.Helper;
using AllBase.Model.DBModel;
@@ -32,7 +33,9 @@ using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using Work._29Tools.CefTools;
using Work.BaseForms;
using WPFCommon.Converters;
using WPFCommon.Helpers;
using WPFCommon.Models;
using WxOrder.Framework.Helpers;
@@ -44,7 +47,7 @@ namespace _29WxOrderWpf.Ctrls.PDDInvoice.ViewModels;
public partial class PDDInvoiceViewModel : BindableBaseEx
{
private const string ConfigPath = "./invoice.config";
private readonly ObservableCollection<PddBrowserOrderInvoiceViewModel> _allOrders = new();
private List<OrderInvoiceInfo> OrderInvoiceInfoList = new();
private readonly HashSet<string> _orderSns = new();
private string _searchText = "";
private PddBrowserOrderInvoiceViewModel _selectedOrder;
@@ -53,14 +56,18 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
private string _invoiceTitle = "";
private string _taxNo = "";
private CancellationTokenSource _cancellationTokenSource;
private InvoiceConfig Config { get; }
private InvoiceConfig Config { get; set; }
/// <summary> 订单列表 </summary>
public ObservableCollection<PddBrowserOrderInvoiceViewModel> Orders { get; }
public ICollectionView OrdersView { get; }
public PDDInvoiceViewModel()
{
_cancellationTokenSource = new CancellationTokenSource();
Config = NaiBa.Util.Helper.ConfigHelper.LoadConfig<InvoiceConfig>(ConfigPath);
Orders = new ObservableCollection<PddBrowserOrderInvoiceViewModel>();
Orders.CollectionChanged += Orders_CollectionChanged;
OrdersView =CollectionViewSource.GetDefaultView(Orders);
OrdersView = CollectionViewSource.GetDefaultView(Orders);
OrdersView.Filter = FilterPredicate;
OrdersView.SortDescriptions.Add(
new SortDescription(nameof(PddBrowserOrderInvoiceViewModel.order_time), ListSortDirection.Ascending));
@@ -70,18 +77,33 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
InitBrowser();
if (Config == null) Config = new InvoiceConfig();
InvoiceTitle = Config.Title;
TaxNo = Config.TaxNo;
MaxAmount = Config.MaxAmount;
EndTime = DateTime.Now;
StartTime = EndTime.AddMonths(-1);
if (EnvironmentHelper.IsTest)
{
InvoiceTitle = "嵩县雷神商贸有限责任公司";
TaxNo = "91410325MADQERT68E";
MaxAmount = 99;
Config.Title = "嵩县雷神商贸有限责任公司";
Config.TaxNo = "91410325MADQERT68E";
Config.MaxAmount = 99;
_ = InitSampleData();
}
}
private bool FilterPredicate(object obj)
{
if (obj is not PddBrowserOrderInvoiceViewModel order) return false;
// 发票状态过滤
bool? temp = InvoiceStatus == 0 ? null : InvoiceStatus == 2;
if (temp.HasValue && order.IsInvoiced != temp.Value)
return false;
// 关键字过滤
var keyword = SearchText?.Trim();
if (!IsKeywordMatch(order, keyword))
return false;
if (order.OrderTime < StartTime || EndTime < order.OrderTime) return false;
return true;
}
partial void InitBrowser();
/// <summary> 列表增删时订阅/退订订单勾选状态,用于刷新表头全选状态 </summary>
@@ -118,11 +140,7 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
public ObservableCollectionThreadSafe<BuyerLoginInfo> BuyerLoginList { get; set; } = new ObservableCollectionThreadSafe<BuyerLoginInfo>();
public int InvoiceStatus
{
get => GetValue<int>();
set => SetValue(value, InvoiceStatusChanged);
}
private void InvoiceStatusChanged()
{
@@ -139,18 +157,30 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
{
WPFCEFBrowser.SetCookieAsync(SelectedBuyer.cookie, Browser.GetCookieManager()).GetAwaiter();
WPFCEFBrowser.SetCookieAsync(SelectedBuyer.cookie, BrowserDetail.GetCookieManager()).GetAwaiter();
}
/// <summary> 订单列表 </summary>
public ObservableCollection<PddBrowserOrderInvoiceViewModel> Orders { get; }
public ICollectionView OrdersView { get; }
/// <summary> 搜索关键字:订单号 / 商品名称 / 买家 </summary>
public string SearchText
{
get => _searchText;
set => SetProperty(ref _searchText, value, nameof(SearchText));
}
public int InvoiceStatus
{
get => GetValue<int>();
set => SetValue(value, InvoiceStatusChanged);
}
public DateTime StartTime
{
get => GetValue<DateTime>();
set => SetValue(value);
}
public DateTime EndTime
{
get => GetValue<DateTime>();
set => SetValue(value);
}
/// <summary> 开票弹窗是否打开 </summary>
public bool IsOrderListDialogOpen
@@ -184,19 +214,19 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
set => SetProperty(ref _selectedOrder, value, nameof(SelectedOrder));
}
/// <summary> 发票抬头 </summary>
public string InvoiceTitle
{
get => _invoiceTitle;
set => SetProperty(ref _invoiceTitle, value, nameof(InvoiceTitle));
}
///// <summary> 发票抬头 </summary>
//public string InvoiceTitle
//{
// get => _invoiceTitle;
// set => SetProperty(ref _invoiceTitle, value, nameof(InvoiceTitle));
//}
/// <summary> 税号 </summary>
public string TaxNo
{
get => _taxNo;
set => SetProperty(ref _taxNo, value, nameof(TaxNo));
}
///// <summary> 税号 </summary>
//public string TaxNo
//{
// get => _taxNo;
// set => SetProperty(ref _taxNo, value, nameof(TaxNo));
//}
/// <summary>
/// 开始开票总金额
/// </summary>
@@ -205,14 +235,14 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
get => GetValue<decimal>();
set => SetValue(value);
}
/// <summary>
/// 最大开票金额
/// </summary>
public decimal MaxAmount
{
get => GetValue<decimal>();
set => SetValue(value);
}
///// <summary>
///// 最大开票金额
///// </summary>
//public decimal MaxAmount
//{
// get => GetValue<decimal>();
// set => SetValue(value);
//}
/// <summary>
/// 已开票金额
/// </summary>
@@ -229,6 +259,16 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
get => GetValue<decimal>();
set => SetValue(value);
}
public bool IsLoadImage
{
get => GetValue<bool>();
set => SetValue(value);
}
public ICommand SearchCommand => new DelegateCommand(Search);
public ICommand ResetCommand => new DelegateCommand(ResetSearch);
@@ -250,7 +290,6 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
BaseMsgWindow.ShowError("未填选择买手号");
return;
}
_cancellationTokenSource = new CancellationTokenSource();
Debug.WriteLine("开始读单");
BottomMsg = $"开始读取订单";
StartProgress();
@@ -259,12 +298,34 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
if (!IsReadOrder)
{
_orderSns.Clear();
_allOrders.Clear();
Orders.Clear();
OrderInvoiceInfoList.Clear();
string path = string.Format(inviceDataPath, SelectedBuyer.buyer_id);
if (File.Exists(NaiBa.Util.Helper.ConfigHelper.GetConfigUserPath(path)))
{
var ret = BaseMsgWindow.ShowConfirm("检测到已有历史数据是否加载?").DialogResult;
if (ret == true)
{
var data = NaiBa.Util.Helper.ConfigHelper.LoadConfig<List<OrderInvoiceInfo>>(path);
AddOrders(data.Select(a => new PddBrowserOrderInvoiceViewModel(a)));
BottomMsg = $"已加载历史数据";
return;
}
else if (ret == null)
{
return;
}
}
Browser.Load("https://mobile.yangkeduo.com/orders.html");
await Task.Delay(Timeout.Infinite, _cancellationTokenSource.Token);
}
await Task.Delay(Timeout.Infinite, _cancellationTokenSource.Token);
}
catch (TaskCanceledException)
@@ -373,36 +434,50 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
{
if (IsBatchInvoicing) return;
if (string.IsNullOrEmpty(InvoiceTitle) || string.IsNullOrEmpty(TaxNo))
if (string.IsNullOrEmpty(Config.Title) || string.IsNullOrEmpty(Config.TaxNo))
{
BaseMsgWindow.ShowError("未填写公司或税号");
return;
}
var targets = Orders.Where(o => o.IsSelected && !o.IsInvoiced).ToList();
var targets = OrdersView.Cast<PddBrowserOrderInvoiceViewModel>().Where(o => o.IsSelected && !o.IsInvoiced).ToList();
if (targets.Count == 0)
{
BaseMsgWindow.ShowError("请先勾选需要开票的订单");
return;
}
if (MaxAmount <= 0)
if (Config.MaxAmount <= 0)
{
BaseMsgWindow.ShowError("请填写开票总金额");
return;
}
var confirm = BaseMsgWindow.ShowConfirm(
$"已勾选 {targets.Count} 个待开票订单,确定开始批量开票吗?\n请确认发票抬头与税号无误。\n开票总金额:{MaxAmount}",
$"已勾选 {targets.Count} 个待开票订单,确定开始批量开票吗?\n请确认发票抬头与税号无误。\n开票总金额:{Config.MaxAmount}",
"批量开票");
if (confirm.DialogResult != true) return;
Config.Title = InvoiceTitle;
Config.TaxNo = TaxNo;
Config.MaxAmount = MaxAmount;
NaiBa.Util.Helper.ConfigHelper.SaveConfig(ConfigPath, Config);
//Config.Title = InvoiceTitle;
//Config.TaxNo = TaxNo;
//Config.MaxAmount = MaxAmount;
//NaiBa.Util.Helper.ConfigHelper.SaveConfig(ConfigPath, Config);
await BatchInvoiceAsync(targets);
}
public ICommand ShowSettingDialogCommand => new DelegateCommand(ShowSettingDialog);
private void ShowSettingDialog()
{
var view = new PDDInvoiceDialog();
new DialogWindow
{
Title = "设置",
Content = view,
}.ShowDialog();
Config = view.Config;
}
public event EventHandler<int> BatchInvoiceChanged;
/// <summary>
/// 后台批量开票:逐单加载开票页并自动填写提交,底部进度条实时更新,成功后更新列表状态
/// </summary>
@@ -419,13 +494,15 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
for (int i = 0; i < targets.Count; i++)
{
if (AmountTotal >= MaxAmount)
if (AmountTotal >= Config.MaxAmount)
{
return;
}
var order = targets[i];
BottomMsg = $"正在批量开票:{i}/{targets.Count},当前订单:{order.order_sn}";
ProgressValue = i;
SelectedOrder = order;
BatchInvoiceChanged?.Invoke(this, OrdersView.Cast<PddBrowserOrderInvoiceViewModel>().ToList().IndexOf(order));
bool ok = false;
if (EnvironmentHelper.IsTest)
{
@@ -454,6 +531,7 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
}
ProgressValue = success + fail;
BottomMsg = $"正在批量开票:{i}/{targets.Count},当前订单:{order.order_sn}。总金额:{AmountTotal.ToString("N2")}";
BottomRMsg = $"批量开票状态:成功 {success} 个,失败 {fail} 个。总金额:{AmountTotal.ToString("N2")}";
StatisticsInvoiceAmount();
await Task.Delay(1000);
}
@@ -468,7 +546,6 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
_currentInvoiceTcs = null;
ProgressMaximum = targets.Count;
ProgressValue = targets.Count;
BottomMsg = $"批量开票完成:成功 {success} 个,失败 {fail} 个。总金额:{AmountTotal.ToString("N2")}";
IsBatchInvoicing = false;
BaseMsgWindow.ShowInfo(BottomMsg);
}
@@ -478,8 +555,8 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
/// </summary>
private void StatisticsInvoiceAmount()
{
InvoicedAmountTotal = Orders.Where(a => a.IsInvoiced).Sum(a => a.order_amount) / 100m;
UninvoicedAmountTotal = Orders.Where(a => a.IsInvoiced == false).Sum(a => a.order_amount) / 100m;
InvoicedAmountTotal = OrdersView.Cast<PddBrowserOrderInvoiceViewModel>().Where(a => a.IsInvoiced).Sum(a => a.order_amount) / 100m;
UninvoicedAmountTotal = OrdersView.Cast<PddBrowserOrderInvoiceViewModel>().Where(a => a.IsInvoiced == false).Sum(a => a.order_amount) / 100m;
}
#endregion
@@ -487,21 +564,22 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
/// <summary> 按 订单号 / 商品名称 过滤订单 </summary>
private void Search()
{
var keyword = SearchText?.Trim();
Orders.Clear();
bool? _tempIsInvoiced = InvoiceStatus == 0 ? null : InvoiceStatus == 2;
foreach (var order in _allOrders)
{
if (_tempIsInvoiced.HasValue)
{
if (order.IsInvoiced != _tempIsInvoiced.Value) continue;
}
if (!IsKeywordMatch(order, keyword))
{
continue;
}
Orders.Add(order);
}
OrdersView.Refresh();
StatisticsInvoiceAmount();
//var keyword = SearchText?.Trim();
//bool? _tempIsInvoiced = InvoiceStatus == 0 ? null : InvoiceStatus == 2;
//foreach (var order in Orders)
//{
// if (_tempIsInvoiced.HasValue)
// {
// if (order.IsInvoiced != _tempIsInvoiced.Value) continue;
// }
// if (!IsKeywordMatch(order, keyword))
// {
// continue;
// }
// Orders.Add(order);
//}
}
private static bool IsKeywordMatch(PddBrowserOrderInvoiceViewModel order, string keyword)
@@ -515,6 +593,8 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
{
SearchText = "";
InvoiceStatus = 0;
EndTime = DateTime.Now;
StartTime = EndTime.AddMonths(-1);
Search();
}
/// <summary>
@@ -524,7 +604,7 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
private void OpenInvoice(PddBrowserOrderInvoiceViewModel order)
{
SelectedOrder = order;
if (string.IsNullOrEmpty(InvoiceTitle) || string.IsNullOrEmpty(TaxNo))
if (string.IsNullOrEmpty(Config.Title) || string.IsNullOrEmpty(Config.TaxNo))
{
BaseMsgWindow.ShowError("未填写公司或税号");
return;
@@ -602,15 +682,30 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
{
continue;
}
_allOrders.Add(item);
if (IsKeywordMatch(item, keyword))
if (item.IsInvoiced == false)
{
item.IsInvoiced = item.order_buttons?.Any(a => a.brief_prompt == "发票详情") ?? false;
Orders.Add(item);
}
Orders.Add(item);
if (Config.IsSaveData)
{
OrderInvoiceInfoList.Add(new OrderInvoiceInfo
{
GoodsName = item.GoodsName,
order_amount = item.order_amount,
order_time = item.order_time,
order_sn = item.order_sn,
order_link_url = item.order_link_url,
IsInvoiced = item.IsInvoiced,
ThumbUrl = item.ThumbUrl
});
}
}
StatisticsInvoiceAmount();
SaveOrderInvoiceInfo();
}
#endregion
@@ -651,7 +746,29 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
return Task.CompletedTask;
}
private const string inviceDataPath = "inviceData_{0}";
/// <summary>
/// 保存数据
/// </summary>
private void SaveOrderInvoiceInfo()
{
if (SelectedBuyer == null) return;
string path = string.Format(inviceDataPath, SelectedBuyer.buyer_id);
NaiBa.Util.Helper.ConfigHelper.SaveConfig<List<OrderInvoiceInfo>>(path, OrderInvoiceInfoList);
}
private void GetOrderInvoiceInfo()
{
if (SelectedBuyer == null) return;
string path = string.Format(inviceDataPath, SelectedBuyer.buyer_id);
if (File.Exists(NaiBa.Util.Helper.ConfigHelper.GetConfigUserPath(path)))
{
if (BaseMsgWindow.ShowConfirm("检测到已有旧数据是否加载?").DialogResult == true)
{
var data = NaiBa.Util.Helper.ConfigHelper.LoadConfig<List<OrderInvoiceInfo>>(path);
AddOrders(data.Select(a => new PddBrowserOrderInvoiceViewModel(a)));
}
}
}
@@ -664,6 +781,13 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
set => SetValue(ref _bottomMsg, value);
}
private string _bottomRMsg = "";
public string BottomRMsg
{
get => _bottomRMsg;
set => SetValue(ref _bottomRMsg, value);
}
private double _progressValue;
public double ProgressValue
{
@@ -754,9 +878,10 @@ public partial class PDDInvoiceViewModel : BindableBaseEx
#endregion
}
class InvoiceConfig
public class InvoiceConfig
{
public string Title { get; set; }
public string TaxNo { get; set; }
public decimal MaxAmount { get; set; }
public bool IsSaveData { get; set; }
}