Compare commits
12
Commits
6d4629e4ac
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
440510aa8c | ||
|
|
d5232c581c | ||
|
|
45829fa267 | ||
|
|
127fc22de5 | ||
|
|
9b9e4cbd82 | ||
|
|
30a6a5ea24 | ||
|
|
3dcb6a1c34 | ||
|
|
f03e2b08f4 | ||
|
|
a003d90b0e | ||
|
|
3135189ea3 | ||
|
|
499379e20b | ||
|
|
497e9f1c34 |
No files matched your search
@@ -359,16 +359,11 @@ if (AppFileHelper.PickFolder(out string path)) { FolderPath = path; }
|
|||||||
|
|
||||||
XAML 细则见 `wpf-xaml.mdc`。
|
XAML 细则见 `wpf-xaml.mdc`。
|
||||||
|
|
||||||
## 数据映射(忽略)
|
## 服务端实体与 WPF 展示模型
|
||||||
|
|
||||||
使用 Mapster:
|
- 服务端返回的业务实体命名为 `XxxInfo`(如 `UserInfo`),放在独立的 `Store.Management.Models` 项目中,可脱离 API 和 WPF 使用。
|
||||||
|
- WPF 视图绑定展示模型。单个实体的展示模型命名为 `XxxViewModel`(如 `UserViewModel`),集合中的每个元素命名为 `XxxItemViewModel`(如 `IReadOnlyList<UserItemViewModel>` 中的 `UserItemViewModel`)。
|
||||||
```csharp
|
- 从服务端实体到展示模型的转换使用 Riok.Mapperly,映射类放在使用方项目的 `Mappers/` 目录。
|
||||||
using PipeReviewReport.Shared;
|
|
||||||
|
|
||||||
var dto = model.Adapt<XxxDto>();
|
|
||||||
var model = dto.Adapt<XxxModel>();
|
|
||||||
```
|
|
||||||
|
|
||||||
## 资源引用(忽略)
|
## 资源引用(忽略)
|
||||||
|
|
||||||
|
|||||||
+82
-38
@@ -6,6 +6,8 @@ globs: "**/*.xaml"
|
|||||||
|
|
||||||
# XAML 视图编写约定
|
# XAML 视图编写约定
|
||||||
|
|
||||||
|
项目 XAML 默认不添加 `AutomationProperties.Name`。
|
||||||
|
|
||||||
## View XAML 头部模板
|
## View XAML 头部模板
|
||||||
|
|
||||||
```XML
|
```XML
|
||||||
@@ -13,35 +15,55 @@ globs: "**/*.xaml"
|
|||||||
x:Class="xxxxx.(xxxx)?.Views.XxxView"
|
x:Class="xxxxx.(xxxx)?.Views.XxxView"
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
xmlns:local="clr-namespace:xxxx.(xxxx)?.Views"
|
xmlns:local="clr-namespace:xxxx.(xxxx)?.Views"
|
||||||
xmlns:core="MAX.Core"
|
xmlns:core="MAX.Core"
|
||||||
xmlns:hc="https://handyorg.github.io/handycontrol"
|
xmlns:hc="https://handyorg.github.io/handycontrol"
|
||||||
xmlns:wpf="MAX.WPF"
|
xmlns:wpf="MAX.WPF"
|
||||||
xmlns:s="clr-namespace:xxxx.xxx;assembly=xxx.xxx"
|
xmlns:s="clr-namespace:xxxx.xxx;assembly=xxx.xxx"
|
||||||
d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"
|
|
||||||
Style="{DynamicResource UserControlStyle}"
|
Style="{DynamicResource UserControlStyle}"
|
||||||
DataContext="{core:DISource Type=local:XxxViewModel}"
|
DataContext="{core:DISource Type=local:XxxViewModel}"
|
||||||
|
d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"
|
||||||
|
d:Background="White"
|
||||||
d:DesignHeight="450"
|
d:DesignHeight="450"
|
||||||
d:DesignWidth="800">
|
d:DesignWidth="800"
|
||||||
|
mc:Ignorable="d"
|
||||||
|
>
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dialog View XAML
|
## Dialog View XAML
|
||||||
|
|
||||||
```XML
|
```XML
|
||||||
<UserControl
|
<UserControl
|
||||||
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
xmlns:core="MAX.Core"
|
xmlns:core="MAX.Core"
|
||||||
xmlns:hc="https://handyorg.github.io/handycontrol"
|
xmlns:hc="https://handyorg.github.io/handycontrol"
|
||||||
xmlns:wpf="MAX.WPF"
|
xmlns:wpf="MAX.WPF"
|
||||||
d:Background="White"
|
d:Background="White"
|
||||||
d:DataContext="{d:DesignInstance Type=local:DialogViewModel}"
|
d:DataContext="{d:DesignInstance Type=local:DialogViewModel}"
|
||||||
Style="{StaticResource DialogStyle.Base}"
|
Style="{StaticResource DialogStyle.Base}"
|
||||||
DataContext="{core:DISource Type=local:DialogViewModel}">
|
DataContext="{core:DISource Type=local:DialogViewModel}"
|
||||||
|
mc:Ignorable="d"
|
||||||
|
>
|
||||||
```
|
```
|
||||||
|
|
||||||
- `{core:DISource Type=local:XxxViewModel}` 绑定 ViewModel
|
- `{core:DISource Type=local:XxxViewModel}` 绑定 ViewModel
|
||||||
- `d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"` 提供设计时数据
|
- `d:DataContext="{d:DesignInstance Type=local:XxxViewModel}"` 提供设计时数据
|
||||||
- `UserControlStyle` 与 `ViewModelBaseEx` 强相关,必须搭配使用
|
- `UserControlStyle` 与 `ViewModelBaseEx` 强相关,必须搭配使用
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 控件必须有设计数据
|
||||||
|
|
||||||
|
页面、弹窗和 `DataTemplate` 应能在 XAML 设计器中直接看出字段内容、排列方向、对齐和间距。设计值使用 `d:` 命名空间,根元素声明 `xmlns:d`、`xmlns:mc` 和 `mc:Ignorable="d"`,保留运行时绑定。
|
||||||
|
|
||||||
|
- `TextBox`、`TextBlock` 的文本来自绑定或默认为空时,必须设置有业务含义的非空示例,如 `d:Text="示例商贸有限公司"`。静态文案已可见时无需重复填写。
|
||||||
|
- 绑定集合的 `ItemsControl`、`ListBox`、`ComboBox`、`DataGridEx` 等必须提供设计时数据,默认使用 `d:ItemsSource="{d:SampleData ItemCount=5}"`。行数可按实际布局调整。下拉框要预览选中项时可加 `d:SelectedIndex="0"`。
|
||||||
|
- 其他控件按实际显示属性提供设计值,例如绑定标题的 `wpf:TitleContent` 用 `d:Title="中转仓快递费(元/单)"`,金额输入框用 `d:Value="2.20"`,绑定按钮文案用 `d:Content="保存"`。运行时按状态显示的区域,可用 `d:Visibility="Visible"` 预览。
|
||||||
|
- 集合模板既要能看到多行,也要能看清每行内容。若样本数据未填充自定义控件的显示属性,在模板内补相应的 `d:` 值。
|
||||||
|
|
||||||
## BindingProxy + CommandProxy(DataTemplate/ContextMenu 绑定)
|
## BindingProxy + CommandProxy(DataTemplate/ContextMenu 绑定)
|
||||||
|
|
||||||
**在 `DataTemplate`、`ContextMenu`、`DataGridTemplateColumn.CellTemplate` 中禁止使用 `RelativeSource AncestorType`,必须用 `BindingProxy` + `CommandProxy`。**
|
**在 `DataTemplate`、`ContextMenu`、`DataGridTemplateColumn.CellTemplate` 中禁止使用 `RelativeSource AncestorType`,必须用 `BindingProxy` + `CommandProxy`。**
|
||||||
@@ -60,6 +82,9 @@ DataContext="{core:DISource Type=local:DialogViewModel}">
|
|||||||
|
|
||||||
**`BindingProxy` 映射关系**:`Data="{Binding}"` 把 ViewModel 存到 `BindingProxy.Data`。引用时 `Path=Data.SelectedItem` 中 `Data` 对应 `BindingProxy.Data`(即 ViewModel)。
|
**`BindingProxy` 映射关系**:`Data="{Binding}"` 把 ViewModel 存到 `BindingProxy.Data`。引用时 `Path=Data.SelectedItem` 中 `Data` 对应 `BindingProxy.Data`(即 ViewModel)。
|
||||||
|
|
||||||
|
### 文字只读显示
|
||||||
|
尽量使用 `TextBlock` 而不是 `Label`
|
||||||
|
|
||||||
### DataTemplate(CellTemplate)中
|
### DataTemplate(CellTemplate)中
|
||||||
|
|
||||||
Command 用 CommandProxy,行数据用 `{Binding}`:
|
Command 用 CommandProxy,行数据用 `{Binding}`:
|
||||||
@@ -262,6 +287,39 @@ C# 侧:`"#FF5733".toColor()`、`"#80000000".toColor()`。
|
|||||||
</Style>
|
</Style>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 顺序排列与间距布局
|
||||||
|
|
||||||
|
**页面排版需要横向、纵向顺序排列或简单自动换行时,优先使用 `wpf:SpacingStackPanel`。** 普通堆叠布局通过 `Orientation` 指定方向,需要换行时设置 `ChildWrapping="True"`。
|
||||||
|
|
||||||
|
- 优先用 `HorizontalSpacing` / `VerticalSpacing` 统一控制子项间距,避免逐项设置重复的 `Margin`;容器外边距和个别元素的特殊偏移仍按需使用 `Margin`。
|
||||||
|
- 需要统一子项尺寸或对齐时,按需设置 `ItemWidth`、`ItemHeight`、`ItemHorizontalAlignment`、`ItemVerticalAlignment`。
|
||||||
|
- “文字 + 简单内容”可由 `wpf:TitleContent` 组成,再用 `wpf:SpacingStackPanel` 排列多个字段。
|
||||||
|
- 需要行列划分、跨行跨列、重叠或虚拟化时,使用满足这些要求的布局容器,不强行替换为 `SpacingStackPanel`。
|
||||||
|
- 属性及用法见 [max-common-wpf SpacingStackPanel 参考](../skills/max-common-wpf/references/api.md#controlsspacingstackpanelcs)。
|
||||||
|
|
||||||
|
### ItemsControl 的顺序排版
|
||||||
|
|
||||||
|
少量集合项按行或列顺序排列时,必须在 `ItemsControl.ItemsPanel` 的 `ItemsPanelTemplate` 中使用 `wpf:SpacingStackPanel`。项与项之间的间距由这个面板控制;`ItemTemplate` 负责单项内部布局。优先复用已有间距样式,例如计费弹窗的 `VerticalSpacingPanel4`。需要虚拟化的长列表保留虚拟化面板。
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<ItemsControl ItemsSource="{Binding Fields, Mode=OneWay}"
|
||||||
|
d:ItemsSource="{d:SampleData ItemCount=5}">
|
||||||
|
<ItemsControl.ItemsPanel>
|
||||||
|
<ItemsPanelTemplate>
|
||||||
|
<wpf:SpacingStackPanel Style="{StaticResource VerticalSpacingPanel4}" />
|
||||||
|
</ItemsPanelTemplate>
|
||||||
|
</ItemsControl.ItemsPanel>
|
||||||
|
</ItemsControl>
|
||||||
|
```
|
||||||
|
|
||||||
|
## 文字与简单内容布局
|
||||||
|
|
||||||
|
**页面排版遇到“说明文字 + 简单内容”(如输入框、选择器、按钮等输入或点击控件)时,优先使用 `wpf:TitleContent`。** 将说明文字放在 `Title`,交互控件作为内容,避免为同一组合另用 `TextBlock` 配合 `Grid` / `StackPanel` 手工拼接。
|
||||||
|
|
||||||
|
- 按布局设置 `Placement`;左侧标题表单优先使用 `Placement="Left"`,并按需设置 `TitleWidth`、`TitleVerticalAlignment="Center"` 和 `LeftTitlePadding`,保持同组字段对齐。
|
||||||
|
- 内容控件仍自行配置绑定、命令和输入长度;`TitleContent` 只负责标题与内容的布局。
|
||||||
|
- 属性及用法见 [max-common-wpf TitleContent 参考](../skills/max-common-wpf/references/api.md#controlstitlecontentcs)。
|
||||||
|
|
||||||
## 布局注释
|
## 布局注释
|
||||||
|
|
||||||
主要布局分块/区域前加 `<!-- -->` 注释标明用途。复杂视图(多面板、多 Tab、对话框)必须注释;简单单控件视图可省略:
|
主要布局分块/区域前加 `<!-- -->` 注释标明用途。复杂视图(多面板、多 Tab、对话框)必须注释;简单单控件视图可省略:
|
||||||
@@ -302,48 +360,34 @@ C# 侧:`"#FF5733".toColor()`、`"#80000000".toColor()`。
|
|||||||
|
|
||||||
## 枚举绑定
|
## 枚举绑定
|
||||||
|
|
||||||
### EnumDisplayConverter(XAML)
|
**页面的枚举选项绑定优先使用 `EnumBindingMarkup`(`EnumBindingMarkupExtension`)生成 ItemsSource,配合 `EnumBindingExtension.SelectedEnum` 绑定选中的枚举值。** 不要仅为列出枚举值,在 ViewModel 中额外定义 `Enum.GetValues` 列表或在 XAML 中硬编码选项。
|
||||||
|
|
||||||
|
- 显示名优先使用 MAX.Common.WPF 自带的 `EnumDisplayConverter`,显式传入标记扩展的 `Converter`;未传入时默认显示枚举成员名称。
|
||||||
|
- `DisplayMemberPath="Display"` 用于显示名称,`SelectedValuePath="Value"` 对应枚举值本身。
|
||||||
|
- 系统初始化、视图加载前配置一次 `EnumDisplayConverter.EnumDisplayManager = new EnumDisplayManagerWPF(null);`;已有自定义显示管理器时复用现有配置。
|
||||||
|
- 仅显示单个枚举值的文本时,直接绑定该属性并使用 `EnumDisplayConverter`,无需生成选项列表。
|
||||||
|
|
||||||
|
### ComboBox 绑定枚举
|
||||||
|
|
||||||
|
`xmlns:wpf="MAX.WPF"`,`xmlns:local` 指向业务枚举命名空间:
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<UserControl.Resources>
|
<UserControl.Resources>
|
||||||
<conv:EnumDisplayConverter x:Key="EnumDisplayConverter"/>
|
<wpf:EnumDisplayConverter x:Key="EnumDisplayConverter" />
|
||||||
</UserControl.Resources>
|
</UserControl.Resources>
|
||||||
|
|
||||||
<!-- 直接绑定枚举值 -->
|
<ComboBox
|
||||||
<TextBlock Text="{Binding Status, Converter={StaticResource EnumDisplayConverter}}"/>
|
ItemsSource="{wpf:EnumBindingMarkup EnumType={x:Type local:MyStatus},
|
||||||
|
Converter={StaticResource EnumDisplayConverter}}"
|
||||||
|
DisplayMemberPath="Display"
|
||||||
|
SelectedValuePath="Value"
|
||||||
|
wpf:EnumBindingExtension.SelectedEnum="{Binding SelectedStatus, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
|
||||||
|
|
||||||
|
<!-- 只读显示单个枚举值 -->
|
||||||
|
<TextBlock Text="{Binding Status, Mode=OneWay, Converter={StaticResource EnumDisplayConverter}}" />
|
||||||
```
|
```
|
||||||
|
|
||||||
### ComboBox 绑定枚举(推荐:ViewModel 提供列表)
|
初始化命名空间、Description 显示、空选项等完整用法见 [max-common-wpf 枚举绑定参考](../skills/max-common-wpf/references/api.md#markupextensionsenumbindingmarkupextensioncs)。自定义枚举显示管理器见 `reference-enum-display` skill。
|
||||||
|
|
||||||
```csharp
|
|
||||||
// ViewModel
|
|
||||||
public IReadOnlyList<MyStatus> StatusList { get; } = Enum.GetValues(typeof(MyStatus)).Cast<MyStatus>().ToList();
|
|
||||||
|
|
||||||
public MyStatus SelectedStatus
|
|
||||||
{
|
|
||||||
get => GetProperty(() => SelectedStatus);
|
|
||||||
set => SetProperty(() => SelectedStatus, value);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
```xml
|
|
||||||
<ComboBox ItemsSource="{Binding StatusList}"
|
|
||||||
SelectedItem="{Binding SelectedStatus}">
|
|
||||||
<ComboBox.ItemTemplate>
|
|
||||||
<DataTemplate>
|
|
||||||
<TextBlock Text="{Binding ., Converter={StaticResource EnumDisplayConverter}}"/>
|
|
||||||
</DataTemplate>
|
|
||||||
</ComboBox.ItemTemplate>
|
|
||||||
</ComboBox>
|
|
||||||
```
|
|
||||||
|
|
||||||
### C# 获取枚举显示文本
|
|
||||||
|
|
||||||
```csharp
|
|
||||||
string displayText = MyStatus.Active.GetEnumDisplay();
|
|
||||||
```
|
|
||||||
|
|
||||||
EnumDisplayService 内部实现和自定义逻辑详见 `reference-enum-display` skill。
|
|
||||||
|
|
||||||
## MarkupExtension 示例
|
## MarkupExtension 示例
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ disable-model-invocation: false
|
|||||||
```csharp
|
```csharp
|
||||||
using MAX.Core.DependencyInjections;
|
using MAX.Core.DependencyInjections;
|
||||||
|
|
||||||
namespace PipeReviewReport.<模块名>.Services;
|
namespace 项目.<模块名>.Services;
|
||||||
|
|
||||||
public interface IXxxService
|
public interface IXxxService
|
||||||
{
|
{
|
||||||
@@ -43,7 +43,7 @@ internal class XxxService : IXxxService, ISingletonDependency
|
|||||||
using MAX.Core.DependencyInjections;
|
using MAX.Core.DependencyInjections;
|
||||||
using MAX.Core.Interfaces;
|
using MAX.Core.Interfaces;
|
||||||
|
|
||||||
namespace PipeReviewReport.<模块名>.Services;
|
namespace 项目.<模块名>.Services;
|
||||||
|
|
||||||
public interface IXxxService { }
|
public interface IXxxService { }
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
---
|
||||||
|
name: datagridex
|
||||||
|
description: DataGridEx WPF 表格控件的能力与用法,涵盖分页、行选择、序号、列显隐、自定义操作栏与分页栏、加载动画、排序和图片列。需要了解或配置 DataGridEx 时使用。
|
||||||
|
---
|
||||||
|
|
||||||
|
# DataGridEx
|
||||||
|
|
||||||
|
DataGridEx 继承 WPF DataGrid,提供以下能力。属性默认值和配置示例见 [references/usage.md](references/usage.md)。
|
||||||
|
|
||||||
|
## 行选择与序号
|
||||||
|
|
||||||
|
- 行头复选框与独立序号列,可分别显示或隐藏。
|
||||||
|
- 表头支持全选、未选和部分选中的三态显示;全选范围是当前 ItemsSource/视图。
|
||||||
|
- 点击行尾空白可选中对应行;支持行头点击切换选择、可选的右键选中和行菜单。
|
||||||
|
- SelectedItems 支持绑定可增删集合,集合内增删与表格选择双向同步。使用 OneWay 绑定集合引用,无需属性 setter;不支持只读或固定大小集合。
|
||||||
|
- 序号自动创建,按当前显示顺序和分页偏移计算,排序与行回收后更新。
|
||||||
|
- 选中行背景与前景可配置。
|
||||||
|
|
||||||
|
## 分页
|
||||||
|
|
||||||
|
- 首页、上一页、下一页、末页、页大小选择、当前页和总记录数。
|
||||||
|
- PageIndex、PageSize 支持绑定;翻页通过 PageChangedCommand 发出 DataGridPageRequest(PageIndex, PageSize)。
|
||||||
|
- 换页或改变页大小清空选择;改变页大小回到第一页,总数减少时自动调整到有效页码。
|
||||||
|
- 调用方提供当前页数据和总数;控件不请求数据,也不再次切分 ItemsSource。
|
||||||
|
- ShowPagination 控制分页栏显隐。隐藏时仍保留分页状态;不分页时保持 PageIndex=1。
|
||||||
|
|
||||||
|
## 列与排序
|
||||||
|
|
||||||
|
- 支持原生 DataGrid 列类型和自定义模板列,列放在 DataGridEx.Columns 中。
|
||||||
|
- 内置列设置面板,勾选后立即显示或隐藏列。
|
||||||
|
- CanHideColumn=False 可将业务列设为固定显示;复选框与序号使用各自开关。
|
||||||
|
- 列显示设置不持久化,没有额外的右侧冻结实现。
|
||||||
|
- 支持表头排序,排序图标位于列右侧;默认仅对当前数据源排序。
|
||||||
|
- 服务端全量排序由调用方处理 Sorting 事件并重新查询。
|
||||||
|
|
||||||
|
## 自定义内容
|
||||||
|
|
||||||
|
- ShowToolbar 控制操作栏显隐,ShowColumnSettings 控制列设置按钮。
|
||||||
|
- ToolbarContent 自定义操作栏中间区域,保留选择提示和列设置按钮。
|
||||||
|
- PaginationContent 替换整个分页栏;未设置或为 null 时使用默认分页栏。
|
||||||
|
- 两个内容槽均继承调用方 DataContext,可放置按钮、统计文字和业务布局。
|
||||||
|
|
||||||
|
## 加载与空数据
|
||||||
|
|
||||||
|
- IsLoading 控制加载遮罩及不确定进度动画,LoadingText 配置提示文字。
|
||||||
|
- 加载期间禁用表格、操作栏和分页栏,结束后恢复;不控制表格外部控件。
|
||||||
|
- NoDataTips 配置空数据提示,IsActive 可抑制空数据提示,与 IsLoading 分开控制。
|
||||||
|
- 加载状态由调用方设置,控件不推断请求开始、完成或失败。
|
||||||
|
|
||||||
|
## 图片列与虚拟化
|
||||||
|
|
||||||
|
- DataGridExImageColumn 支持图片地址绑定、占位图绑定及 ElementStyle。
|
||||||
|
- 默认图片尺寸 58×58,Stretch=Uniform。
|
||||||
|
- 可见单元格按需加载图片,行回收时取消旧请求,避免旧图片覆盖新行。
|
||||||
|
- 支持图片缓存,以及拖动滚动条期间暂停图片加载、停止后恢复。
|
||||||
|
- 启用行/列虚拟化和容器回收。
|
||||||
|
|
||||||
|
## 集合视图支持
|
||||||
|
|
||||||
|
ItemsSource 可绑定 ICollectionView。调用方可使用独立 ListCollectionView,通过 Filter 和 Refresh 实现当前页实时筛选并保留视图排序。
|
||||||
|
|
||||||
|
搜索输入框、匹配规则、后台查询、异步取消和跨页全部选择不属于控件内置能力。
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# DataGridEx 调用与属性
|
||||||
|
|
||||||
|
## 常用接入
|
||||||
|
|
||||||
|
以下绑定属性由调用方 ViewModel 提供,controls 表示 DataGridEx 所在命名空间。
|
||||||
|
|
||||||
|
~~~xml
|
||||||
|
<controls:DataGridEx x:Name="StoreGrid"
|
||||||
|
IsReadOnly="True"
|
||||||
|
ShowCheckBox="True" ShowRowNumber="True"
|
||||||
|
ShowToolbar="True" ShowColumnSettings="True" ShowPagination="True"
|
||||||
|
ItemsSource="{Binding CurrentItems, Mode=OneWay}"
|
||||||
|
SelectedItems="{Binding SelectedStores, Mode=OneWay}"
|
||||||
|
TotalItemCount="{Binding TotalCount, Mode=OneWay}"
|
||||||
|
PageSize="50"
|
||||||
|
PageChangedCommand="{Binding LoadPageCommand, Mode=OneWay}"
|
||||||
|
IsLoading="{Binding LoadingStatus.IsLoading, Mode=OneWay}"
|
||||||
|
LoadingText="{Binding LoadingStatus.Message, Mode=OneWay}">
|
||||||
|
<controls:DataGridEx.ToolbarContent>
|
||||||
|
<Button Content="批量操作" Command="{Binding BatchCommand, Mode=OneWay}"/>
|
||||||
|
</controls:DataGridEx.ToolbarContent>
|
||||||
|
<controls:DataGridEx.Columns>
|
||||||
|
<DataGridTextColumn Header="店铺名称"
|
||||||
|
Binding="{Binding Name, Mode=OneWay}"
|
||||||
|
controls:DataGridEx.CanHideColumn="False"/>
|
||||||
|
<DataGridTextColumn Header="店铺 ID"
|
||||||
|
Binding="{Binding StoreId, Mode=OneWay}"/>
|
||||||
|
</controls:DataGridEx.Columns>
|
||||||
|
</controls:DataGridEx>
|
||||||
|
~~~
|
||||||
|
|
||||||
|
首次数据由调用方装入,不依赖 PageChangedCommand 自动启动。默认不自动生成列;数据要使用正确的类型,日期/金额等通过绑定格式化展示。
|
||||||
|
|
||||||
|
## 常用属性
|
||||||
|
|
||||||
|
| 属性 | 当前默认值 / 约束 |
|
||||||
|
| --- | --- |
|
||||||
|
| ShowCheckBox / ShowRowNumber | false / false,分别显示选择行头与序号 |
|
||||||
|
| ShowSelectAll | true;同时启用 ShowCheckBox 才显示表头全选 |
|
||||||
|
| ShowToolbar / ShowColumnSettings / ShowPagination | true;列设置按钮位于操作栏 |
|
||||||
|
| ToolbarContent | null;页面 DataContext 下的自定义批量操作内容 |
|
||||||
|
| PaginationContent | null;自定义整个分页栏,null 恢复默认栏 |
|
||||||
|
| PageIndex / PageSize | 1 / 50;均须大于 0,支持双向绑定 |
|
||||||
|
| PageSizes | 20、50、100;自定义集合应包含当前 PageSize |
|
||||||
|
| TotalItemCount | 0,不能为负数;应为后台查询总数而非当前页条数 |
|
||||||
|
| PageChangedCommand | ICommand,参数 DataGridPageRequest |
|
||||||
|
| IsLoading / LoadingText | false / 正在加载数据… |
|
||||||
|
| SelectedItems | 原生选中集合;绑定时要求可增删集合 |
|
||||||
|
| SelectedRowBackground / SelectedRowForeground | 浅梅紫 / 黑色 |
|
||||||
|
| ToggleSelectionOnRowHeaderClick | true;点击行头切换选中 |
|
||||||
|
| SelectRowOnRightClick | false;开启后右击未选中行会单选该行 |
|
||||||
|
| RowContextMenu | null;行级菜单,行 Tag 可访问页面 DataContext |
|
||||||
|
| NoDataTips / IsActive | 复用 DataGridHelper;IsActive=true 抑制空数据提示,不等同于 IsLoading |
|
||||||
|
| PauseImageLoadingWhileDragging | true;拖动时暂停图片,停止滚动后延迟恢复 |
|
||||||
|
| EnableImageCache | true |
|
||||||
|
| CanHideColumn(附加属性) | true;对业务列设 false 可固定显示 |
|
||||||
|
|
||||||
|
只读状态:PageCount、PageSummary、TotalSummary、SelectionSummary、AreAllRowsSelected(三态)、IsSelectionModeActive、IsImageLoadingSuspended。不要尝试双向写入只读属性。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 自定义分页栏
|
||||||
|
|
||||||
|
将下面属性元素放在命名为 StoreGrid 的 DataGridEx 内。内置路由命令包含 FirstPageCommand、PreviousPageCommand、NextPageCommand、LastPageCommand,边界由控件判定。
|
||||||
|
|
||||||
|
~~~xml
|
||||||
|
<controls:DataGridEx.PaginationContent>
|
||||||
|
<DockPanel>
|
||||||
|
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
|
||||||
|
<Button Content="上一页"
|
||||||
|
Command="{x:Static controls:DataGridEx.PreviousPageCommand}"
|
||||||
|
CommandTarget="{Binding ElementName=StoreGrid, Mode=OneWay}"/>
|
||||||
|
<TextBlock Margin="12,0" VerticalAlignment="Center"
|
||||||
|
Text="{Binding PageSummary, ElementName=StoreGrid, Mode=OneWay}"/>
|
||||||
|
<Button Content="下一页"
|
||||||
|
Command="{x:Static controls:DataGridEx.NextPageCommand}"
|
||||||
|
CommandTarget="{Binding ElementName=StoreGrid, Mode=OneWay}"/>
|
||||||
|
</StackPanel>
|
||||||
|
<TextBlock VerticalAlignment="Center"
|
||||||
|
Text="{Binding TotalSummary, ElementName=StoreGrid, Mode=OneWay}"/>
|
||||||
|
</DockPanel>
|
||||||
|
</controls:DataGridEx.PaginationContent>
|
||||||
|
~~~
|
||||||
|
|
||||||
|
PageIndex/PageSize 如需双向绑定,明确 Mode=TwoWay 和 UpdateSourceTrigger=PropertyChanged。隐藏分页栏不会停用分页状态或改变当前数据。
|
||||||
|
|
||||||
|
## 图片列
|
||||||
|
|
||||||
|
~~~xml
|
||||||
|
<controls:DataGridExImageColumn Header="图片" Binding="{Binding ImageUrl, Mode=OneWay}"/>
|
||||||
|
~~~
|
||||||
|
|
||||||
|
图片列使用 NetworkThumbnail,默认 58×58、Stretch=Uniform;可配置 ElementStyle 和 PlaceholderBinding。可见单元格按需加载,回收时取消旧请求,避免旧图片覆盖新行。拖动暂停和缓存由所属表格配置;它们不是表格整体加载动画的开关。
|
||||||
|
|
||||||
|
## 能力边界
|
||||||
|
|
||||||
|
列显示设置不持久化;没有额外的右侧冻结实现。控件支持 ICollectionView 数据源,但搜索输入与查询逻辑由调用方实现,不承担 HTTP 请求、数据库访问或跨页全部选择。
|
||||||
@@ -18,6 +18,8 @@ description: 在 Windows WPF 项目中接入和使用 MAX.Common.WPF 的控件
|
|||||||
|
|
||||||
按任务读取 [功能索引](references/features.md)。具体命名空间、属性和方法在 [常用 API 声明](references/api.md) 中按类型搜索。声明摘录没有完整方法体;行为不明确时查看当前安装包 XML 文档、反射或可用源码,再以编译和运行验证。消费项目没有原仓库也应能使用本指南。
|
按任务读取 [功能索引](references/features.md)。具体命名空间、属性和方法在 [常用 API 声明](references/api.md) 中按类型搜索。声明摘录没有完整方法体;行为不明确时查看当前安装包 XML 文档、反射或可用源码,再以编译和运行验证。消费项目没有原仓库也应能使用本指南。
|
||||||
|
|
||||||
|
标题布局与间距布局分别参见 [TitleContent 用法](references/api.md#controlstitlecontentcs) 和 [SpacingStackPanel 用法](references/api.md#controlsspacingstackpanelcs)。
|
||||||
|
|
||||||
## XAML 资源入口
|
## XAML 资源入口
|
||||||
|
|
||||||
程序集声明了 `xmlns:wpf="MAX.WPF"`。控件样式和共享转换器位于 `Resources/Generic.xaml`,不要猜成 `Themes/Generic.xaml`。需要这些资源时,在现有 Application.Resources 的 MergedDictionaries 中合并一次:
|
程序集声明了 `xmlns:wpf="MAX.WPF"`。控件样式和共享转换器位于 `Resources/Generic.xaml`,不要猜成 `Themes/Generic.xaml`。需要这些资源时,在现有 Application.Resources 的 MergedDictionaries 中合并一次:
|
||||||
@@ -26,12 +28,14 @@ description: 在 Windows WPF 项目中接入和使用 MAX.Common.WPF 的控件
|
|||||||
<ResourceDictionary Source="/MAX.Common.WPF;component/Resources/Generic.xaml"/>
|
<ResourceDictionary Source="/MAX.Common.WPF;component/Resources/Generic.xaml"/>
|
||||||
```
|
```
|
||||||
|
|
||||||
页面最小示例(绑定属性由页面的 DataContext 提供):
|
## 页面最小示例
|
||||||
|
|
||||||
|
绑定属性由页面的 DataContext 提供:
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:wpf="MAX.WPF">
|
xmlns:wpf="MAX.WPF">
|
||||||
<StackPanel.Resources>
|
<StackPanel.Resources>
|
||||||
<wpf:Boolean2VisibilityConverter x:Key="ShowWhenTrue"/>
|
<wpf:Boolean2VisibilityConverter x:Key="ShowWhenTrue"/>
|
||||||
</StackPanel.Resources>
|
</StackPanel.Resources>
|
||||||
@@ -55,18 +59,11 @@ description: 在 Windows WPF 项目中接入和使用 MAX.Common.WPF 的控件
|
|||||||
- 虚拟化依赖有限可视区域、滚动宿主和 ItemsPanel 配置。`VirtualizingItemsControl` 默认使用 VirtualizingStackPanel,需要换行时显式设置 VirtualizingWrapPanel。不能仅添加面板便承诺大数据性能。
|
- 虚拟化依赖有限可视区域、滚动宿主和 ItemsPanel 配置。`VirtualizingItemsControl` 默认使用 VirtualizingStackPanel,需要换行时显式设置 VirtualizingWrapPanel。不能仅添加面板便承诺大数据性能。
|
||||||
- 通用命令在 `MAX.Common.Commands`,不是 WPF.Commands。MethodCommand<T> / AsyncMethodCommand<T> 的 T 需引用类型或可空值类型,状态变化手动 RaiseCanExecuteChanged;异步命令委托需自行处理业务异常。
|
- 通用命令在 `MAX.Common.Commands`,不是 WPF.Commands。MethodCommand<T> / AsyncMethodCommand<T> 的 T 需引用类型或可空值类型,状态变化手动 RaiseCanExecuteChanged;异步命令委托需自行处理业务异常。
|
||||||
|
|
||||||
## 枚举绑定示例
|
## 枚举绑定
|
||||||
|
|
||||||
已有 `xmlns:local` 指向业务枚举命名空间、`SelectedStatus` 是 `Status` 属性时:
|
枚举显示优先使用 MAX.Common.WPF 自带的 `EnumDisplayConverter`,并通过 `EnumBindingMarkupExtension.Converter` 显式传入;未设置转换器时只显示枚举成员名称。系统初始化时、视图加载前配置一次 `EnumDisplayConverter.EnumDisplayManager = new EnumDisplayManagerWPF(null);`;已有自定义管理器时复用现有配置。
|
||||||
|
|
||||||
```xml
|
初始化代码、Description 显示示例及选中值绑定见 [枚举绑定用法](references/api.md#markupextensionsenumbindingmarkupextensioncs)。
|
||||||
<ComboBox ItemsSource="{wpf:EnumBindingMarkup EnumType={x:Type local:Status}}"
|
|
||||||
DisplayMemberPath="Display"
|
|
||||||
SelectedValuePath="Value"
|
|
||||||
wpf:EnumBindingExtension.SelectedEnum="{Binding SelectedStatus, Mode=TwoWay}"/>
|
|
||||||
```
|
|
||||||
|
|
||||||
允许空选项时使用 AllowNull 并让业务属性可空;自定义显示通过扩展的 Converter 提供,勿假设自动读取所有枚举描述标记。
|
|
||||||
|
|
||||||
## 验证与交付
|
## 验证与交付
|
||||||
|
|
||||||
|
|||||||
@@ -2,12 +2,18 @@
|
|||||||
|
|
||||||
来源:MAX.Common.WPF,2026-10-27 工作区源码快照。
|
来源:MAX.Common.WPF,2026-10-27 工作区源码快照。
|
||||||
|
|
||||||
按下方主题或文件名搜索。仅摘录选定文件的 public / protected 声明;省略方法体、初始化表达式与 XML 注释。这是定位参考,不是可直接编译的 C#,不保证包含嵌套类型的完整可见性上下文。行为说明见 SKILL.md;目标包版本不同时以实际包为准。
|
按下方主题或文件名搜索。API 代码块仅摘录选定文件的 public / protected 声明;省略方法体、初始化表达式与 XML 注释。TitleContent 与 SpacingStackPanel 另附属性说明和 XAML 用法。这是定位参考,不是可直接编译的 C#,不保证包含嵌套类型的完整可见性上下文。通用集成约束见 SKILL.md;目标包版本不同时以实际包为准。
|
||||||
|
|
||||||
目录:控件与布局、枚举、视图与绑定、线程与防抖、虚拟化与转换器
|
目录:控件与布局、枚举、视图与绑定、线程与防抖、虚拟化与转换器
|
||||||
|
|
||||||
## 控件与布局
|
## 控件与布局
|
||||||
|
|
||||||
|
以下 TitleContent 与 SpacingStackPanel 示例在视图根元素声明命名空间:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
xmlns:max="clr-namespace:MAX.Common.WPF.Controls;assembly=MAX.Common.WPF"
|
||||||
|
```
|
||||||
|
|
||||||
### Controls/NumberBox.cs
|
### Controls/NumberBox.cs
|
||||||
|
|
||||||
命名空间:`MAX.Common.WPF.Controls`
|
命名空间:`MAX.Common.WPF.Controls`
|
||||||
@@ -46,6 +52,55 @@ public Thickness LeftTitlePadding
|
|||||||
public TitleContent()
|
public TitleContent()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`TitleContent` 是一个"标题 + 内容"布局控件:在 `Content` 周围额外渲染一个 `Title`,并可通过 `Placement` 决定标题相对内容的位置,同时支持标题宽度、对齐方式与内边距的精细控制。
|
||||||
|
|
||||||
|
| 属性 | 类型 | 默认值 | 说明 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `Content` | `object` | — | 继承自 `ContentControl`,主内容 |
|
||||||
|
| `Title` | `object` | `null` | 标题内容(可放字符串、任意 UIElement) |
|
||||||
|
| `Placement` | `TitlePlacementType` | `Top` | 标题相对内容的位置 |
|
||||||
|
| `TitleWidth` | `double` | `NaN` | 标题宽度;`NaN` 表示自动(Auto) |
|
||||||
|
| `TitleHorizontalAlignment` | `HorizontalAlignment` | `Left` | 标题在自身区域内的水平对齐 |
|
||||||
|
| `TitleVerticalAlignment` | `VerticalAlignment` | `Top` | 标题在自身区域内的垂直对齐 |
|
||||||
|
| `TopTitlePadding` | `Thickness` | `(7,2,0,1)` | `Placement=Top` 时标题的内边距 |
|
||||||
|
| `LeftTitlePadding` | `Thickness` | `(0,0,6,0)` | `Placement=Left` 时标题的内边距 |
|
||||||
|
|
||||||
|
标题位置示例使用 Top 与 Left;其他枚举值以实际程序集为准,不根据 padding 属性名推断。
|
||||||
|
|
||||||
|
#### 1. 最简用法(标题在上)
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<max:TitleContent Title="用户名">
|
||||||
|
<TextBox />
|
||||||
|
</max:TitleContent>
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. 标题在左侧 + 固定标题宽度(表单场景)
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<max:TitleContent Title="用户名"
|
||||||
|
Placement="Left"
|
||||||
|
TitleWidth="80"
|
||||||
|
TitleVerticalAlignment="Center"
|
||||||
|
LeftTitlePadding="0,0,8,0">
|
||||||
|
<TextBox />
|
||||||
|
</max:TitleContent>
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. 标题使用复杂 UIElement
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<max:TitleContent Placement="Top">
|
||||||
|
<max:TitleContent.Title>
|
||||||
|
<StackPanel Orientation="Horizontal">
|
||||||
|
<TextBlock Text="密码" />
|
||||||
|
<TextBlock Text="*" Foreground="Red" />
|
||||||
|
</StackPanel>
|
||||||
|
</max:TitleContent.Title>
|
||||||
|
<PasswordBox />
|
||||||
|
</max:TitleContent>
|
||||||
|
```
|
||||||
|
|
||||||
### Controls/BoolContent.cs
|
### Controls/BoolContent.cs
|
||||||
|
|
||||||
命名空间:`MAX.Common.WPF.Controls`
|
命名空间:`MAX.Common.WPF.Controls`
|
||||||
@@ -74,6 +129,87 @@ public HorizontalAlignment? ItemHorizontalAlignment
|
|||||||
public VerticalAlignment? ItemVerticalAlignment
|
public VerticalAlignment? ItemVerticalAlignment
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> `SpacingStackPanel` 是一个"带间距 + 可选自动换行 + 可选统一子项尺寸"的布局面板,可看作 `StackPanel` 的增强版:既支持 StackPanel 式的单向排列,也支持 `WrapPanel` 式的换行排列,并且可以在**每个子项之间**插入水平/垂直间距。
|
||||||
|
|
||||||
|
#### 核心属性速查
|
||||||
|
|
||||||
|
| 属性 | 类型 | 默认值 | 说明 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `Orientation` | `Orientation` | `Horizontal` | 排列方向(水平/垂直),影响"主轴"与间距的解释 |
|
||||||
|
| `ChildWrapping` | `bool` | `false` | 是否自动换行(类似 WrapPanel);`false` 时类似 StackPanel |
|
||||||
|
| `HorizontalSpacing` | `double` | `NaN`(视为 0) | 子项之间的水平间距;校验要求 `> 0` 或 `NaN` |
|
||||||
|
| `VerticalSpacing` | `double` | `NaN`(视为 0) | 子项之间的垂直间距;校验要求 `> 0` 或 `NaN` |
|
||||||
|
| `ItemWidth` | `double` | `NaN`(自动) | 统一子项宽度;示例使用数值宽度,不将其当作 GridLength 的星号尺寸 |
|
||||||
|
| `ItemHeight` | `double` | `NaN`(自动) | 统一子项高度 |
|
||||||
|
| `ItemHorizontalAlignment` | `HorizontalAlignment?` | `Stretch` | 强制设置所有子项的 `HorizontalAlignment` |
|
||||||
|
| `ItemVerticalAlignment` | `VerticalAlignment?` | `Stretch` | 强制设置所有子项的 `VerticalAlignment` |
|
||||||
|
|
||||||
|
> 关键点:`HorizontalSpacing`/`VerticalSpacing` 不是"主轴/交叉轴"间距,而是**屏幕坐标意义上的水平/垂直间距**。当 `Orientation=Horizontal` 时通常用 `HorizontalSpacing` 拉开子项;`Orientation=Vertical` 时通常用 `VerticalSpacing` 拉开子项。
|
||||||
|
|
||||||
|
#### XAML 基本用法
|
||||||
|
|
||||||
|
示例沿用本节开头的 max 命名空间声明。
|
||||||
|
|
||||||
|
##### 1. 水平排列 + 子项水平间距(最常用)
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<max:SpacingStackPanel Orientation="Horizontal" HorizontalSpacing="8">
|
||||||
|
<Button Content="确定" />
|
||||||
|
<Button Content="取消" />
|
||||||
|
<Button Content="应用" />
|
||||||
|
</max:SpacingStackPanel>
|
||||||
|
```
|
||||||
|
|
||||||
|
##### 2. 垂直排列 + 行间距
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<max:SpacingStackPanel Orientation="Vertical" VerticalSpacing="6">
|
||||||
|
<TextBlock Text="第一行" />
|
||||||
|
<TextBlock Text="第二行" />
|
||||||
|
<TextBlock Text="第三行" />
|
||||||
|
</max:SpacingStackPanel>
|
||||||
|
```
|
||||||
|
|
||||||
|
##### 3. 自动换行(标签云 / 按钮流)
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<max:SpacingStackPanel Orientation="Horizontal"
|
||||||
|
ChildWrapping="True"
|
||||||
|
HorizontalSpacing="8"
|
||||||
|
VerticalSpacing="8">
|
||||||
|
<Button Content="标签1" />
|
||||||
|
<Button Content="标签2" />
|
||||||
|
<Button Content="标签3" />
|
||||||
|
<!-- ... -->
|
||||||
|
</max:SpacingStackPanel>
|
||||||
|
```
|
||||||
|
|
||||||
|
##### 4. 统一子项尺寸(等宽卡片网格)
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<max:SpacingStackPanel Orientation="Horizontal"
|
||||||
|
ChildWrapping="True"
|
||||||
|
ItemWidth="120"
|
||||||
|
ItemHeight="80"
|
||||||
|
HorizontalSpacing="10"
|
||||||
|
VerticalSpacing="10">
|
||||||
|
<Border Background="#EEE" />
|
||||||
|
<Border Background="#EEE" />
|
||||||
|
<Border Background="#EEE" />
|
||||||
|
</max:SpacingStackPanel>
|
||||||
|
```
|
||||||
|
|
||||||
|
##### 5. 控制子项对齐
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<max:SpacingStackPanel Orientation="Horizontal"
|
||||||
|
HorizontalSpacing="8"
|
||||||
|
ItemVerticalAlignment="Center">
|
||||||
|
<TextBlock Text="姓名:" />
|
||||||
|
<TextBox Width="160" />
|
||||||
|
</max:SpacingStackPanel>
|
||||||
|
```
|
||||||
|
|
||||||
### Controls/SpacingUniformGrid.cs
|
### Controls/SpacingUniformGrid.cs
|
||||||
|
|
||||||
命名空间:`MAX.Common.WPF.Controls`
|
命名空间:`MAX.Common.WPF.Controls`
|
||||||
@@ -156,6 +292,60 @@ public override bool Equals(object obj)
|
|||||||
public override int GetHashCode()
|
public override int GetHashCode()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### 显示名称与库自带转换器
|
||||||
|
|
||||||
|
MAX.Common.WPF 已提供 `EnumDisplayConverter`,枚举显示优先复用它,不必另写读取 Description 的转换器。`EnumBindingMarkupExtension` 不会自动使用这个转换器,必须通过 `Converter` 显式传入:
|
||||||
|
|
||||||
|
- `Value` 保存枚举值本身,例如 `EEE.Admin`。
|
||||||
|
- 未设置 `Converter` 时,`Display` 为枚举值的 `ToString()`,例如 `"Admin"`,不会由标记扩展直接读取 `Description`。
|
||||||
|
- 设置 `EnumDisplayConverter` 后,`Display` 由枚举显示管理器生成;界面仍绑定 `Display`,选中值绑定 `Value`。
|
||||||
|
|
||||||
|
#### 系统初始化
|
||||||
|
|
||||||
|
`EnumDisplayConverter` 提供全局静态属性 `public static EnumDisplayManagerBase EnumDisplayManager { get; set; }`。在系统初始化、相关视图加载之前设置一次:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
using MAX.Common.WPF.Converters;
|
||||||
|
using MAX.Common.WPF.Utilities;
|
||||||
|
|
||||||
|
EnumDisplayConverter.EnumDisplayManager = new EnumDisplayManagerWPF(null);
|
||||||
|
```
|
||||||
|
|
||||||
|
将赋值放进项目已有的启动初始化流程;若已配置自定义显示管理器,复用现有配置,不要重复覆盖。
|
||||||
|
|
||||||
|
#### Description 显示示例
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
using System.ComponentModel;
|
||||||
|
|
||||||
|
public enum EEE
|
||||||
|
{
|
||||||
|
[Description("管理员")]
|
||||||
|
Admin,
|
||||||
|
[Description("用户")]
|
||||||
|
User
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`xmlns:wpf="MAX.WPF"`,`xmlns:local` 指向枚举所在命名空间。在视图资源中注册库自带转换器,再将它传给标记扩展:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<UserControl.Resources>
|
||||||
|
<wpf:EnumDisplayConverter x:Key="EnumDisplayConverter" />
|
||||||
|
</UserControl.Resources>
|
||||||
|
|
||||||
|
<ComboBox
|
||||||
|
ItemsSource="{wpf:EnumBindingMarkup EnumType={x:Type local:EEE},
|
||||||
|
Converter={StaticResource EnumDisplayConverter}}"
|
||||||
|
DisplayMemberPath="Display"
|
||||||
|
SelectedValuePath="Value"
|
||||||
|
wpf:EnumBindingExtension.SelectedEnum="{Binding SelectedRole, Mode=TwoWay}" />
|
||||||
|
```
|
||||||
|
|
||||||
|
`SelectedRole` 是带属性变更通知的 `EEE` 属性。界面显示“管理员”“用户”,选中值仍为 `EEE.Admin` 或 `EEE.User`。只需要展示选项时,可以省略 `SelectedValuePath` 和 `SelectedEnum` 绑定。
|
||||||
|
|
||||||
|
允许空选项时设置 `AllowNull=True`,并让选中属性可空。`NullDisplay` 默认为空字符串;只有显式设置为 null 时,标记扩展才会尝试调用转换器生成空选项的显示内容。`DisplayNullLast` 控制空选项是否放在末尾。
|
||||||
|
|
||||||
### Extensions/EnumBindingExtension.cs
|
### Extensions/EnumBindingExtension.cs
|
||||||
|
|
||||||
命名空间:`MAX.Common.WPF.Extensions`
|
命名空间:`MAX.Common.WPF.Extensions`
|
||||||
|
|||||||
@@ -5,8 +5,8 @@
|
|||||||
| 需求 | 类型 / 命名空间 | 使用要点 |
|
| 需求 | 类型 / 命名空间 | 使用要点 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 数值输入 | Controls.NumberBox | Value 为 double;Minimum、Maximum、Increment、DecimalPlaces、ValueFormat、ShowUpDownButton;模板资源在 Resources/Generic.xaml |
|
| 数值输入 | Controls.NumberBox | Value 为 double;Minimum、Maximum、Increment、DecimalPlaces、ValueFormat、ShowUpDownButton;模板资源在 Resources/Generic.xaml |
|
||||||
| 标题与条件内容 | Controls.TitleContent、BoolContent | TitleContent 有 Placement 等布局属性;BoolContent 用 Bool、TrueContent、FalseContent |
|
| 标题与条件内容 | Controls.TitleContent、BoolContent | [TitleContent](api.md#controlstitlecontentcs) 提供标题位置、宽度、对齐和内边距,详见属性表与示例;BoolContent 用 Bool、TrueContent、FalseContent |
|
||||||
| 间距布局 | Controls.SpacingStackPanel、SpacingUniformGrid、AutoColumnsUniformGrid | 区分面板间距与子元素 Margin,按声明配置 |
|
| 间距布局 | Controls.SpacingStackPanel、SpacingUniformGrid、AutoColumnsUniformGrid | [SpacingStackPanel](api.md#controlsspacingstackpanelcs) 支持水平/垂直间距、换行、统一子项尺寸与对齐,详见属性表与示例;区分面板间距与子元素 Margin |
|
||||||
| 图标与链接 | Controls.FontIcon、HyperlinkEx | FontIcon 继承 TextBlock,具体字体和字形必须与项目资源一致 |
|
| 图标与链接 | Controls.FontIcon、HyperlinkEx | FontIcon 继承 TextBlock,具体字体和字形必须与项目资源一致 |
|
||||||
| 按钮与弹出层 | Controls.MenuButton、ButtonPopup、CustomPopup、ClippingBorder | 按实际属性处理关闭、焦点和裁切,不猜测通用 Popup 行为 |
|
| 按钮与弹出层 | Controls.MenuButton、ButtonPopup、CustomPopup、ClippingBorder | 按实际属性处理关闭、焦点和裁切,不猜测通用 Popup 行为 |
|
||||||
| 托盘图标 | Controls.NotifyIcon;Enums.NotifyIconInfoType | 涉及 Win32 资源与应用生命周期,检查实际清理 API |
|
| 托盘图标 | Controls.NotifyIcon;Enums.NotifyIconInfoType | 涉及 Win32 资源与应用生命周期,检查实际清理 API |
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
| 标准控件附加行为 | Extensions.TextBoxExtension、ButtonExtension、ListBoxExtension、TreeViewExtension、SelectorExtension、ScrollViewerExtension、ProgressBarExtension、ToolTipExtension | 搜索对应 Get/Set 方法确认附加属性名称、默认值与事件机制 |
|
| 标准控件附加行为 | Extensions.TextBoxExtension、ButtonExtension、ListBoxExtension、TreeViewExtension、SelectorExtension、ScrollViewerExtension、ProgressBarExtension、ToolTipExtension | 搜索对应 Get/Set 方法确认附加属性名称、默认值与事件机制 |
|
||||||
| 通用控件行为 | Extensions.ControlExtension(Context / DragDrop / Focus / Keyboard / Layout / Loaded / Mouse 分文件)、WindowExtension、GridLayoutHelper | 使用实际 API 名称,不把文件名当作附加属性名 |
|
| 通用控件行为 | Extensions.ControlExtension(Context / DragDrop / Focus / Keyboard / Layout / Loaded / Mouse 分文件)、WindowExtension、GridLayoutHelper | 使用实际 API 名称,不把文件名当作附加属性名 |
|
||||||
| 上下文菜单和绑定代理 | Extensions.ContextMenuExtension、ContextMenuListener、BindingProxy / BooleanProxy、CommandProxy;Models.ContextMenuModel;ViewModels.ContextMenuViewModel | Popup/ContextMenu 不在普通可视树,核对 DataContext 来源 |
|
| 上下文菜单和绑定代理 | Extensions.ContextMenuExtension、ContextMenuListener、BindingProxy / BooleanProxy、CommandProxy;Models.ContextMenuModel;ViewModels.ContextMenuViewModel | Popup/ContextMenu 不在普通可视树,核对 DataContext 来源 |
|
||||||
| 枚举选择与显示 | MarkupExtensions.EnumBindingMarkupExtension;Extensions.EnumBindingExtension;Converters.EnumDisplayConverter;Utilities.EnumDisplayManagerWPF | ItemsSource 返回包装对象;旧 EnumBindingComboBox 已弃用 |
|
| 枚举选择与显示 | MarkupExtensions.EnumBindingMarkupExtension;Extensions.EnumBindingExtension;Converters.EnumDisplayConverter;Utilities.EnumDisplayManagerWPF | [枚举绑定用法](api.md#markupextensionsenumbindingmarkupextensioncs):显式传入库自带 EnumDisplayConverter,启动时初始化 EnumDisplayManager;ItemsSource 返回 Display/Value 包装对象;旧 EnumBindingComboBox 已弃用 |
|
||||||
| 布尔、空值与可见性 | Converters.Boolean2VisibilityConverter、Boolean2VisibilityReConverter、Object2VisibilityConverter、String2VisibilityConverter、IListToVisibilityConverter、BooleanArr2VisibilityConverter 等 | 各 Converter 对 null、空串、集合的定义不同,核对实现;多值转换器需 MultiBinding |
|
| 布尔、空值与可见性 | Converters.Boolean2VisibilityConverter、Boolean2VisibilityReConverter、Object2VisibilityConverter、String2VisibilityConverter、IListToVisibilityConverter、BooleanArr2VisibilityConverter 等 | 各 Converter 对 null、空串、集合的定义不同,核对实现;多值转换器需 MultiBinding |
|
||||||
| 格式、颜色、尺寸转换 | Converters.FileSizeDisplayConverter、DateTimeFormatConverter、FormatConverter、StringJoinConverter、ColorToBrushConverter、ContrastBrushConverter、ThicknessSplitConverter、CornerRadiusSplitConverter 等 | 按 IValueConverter / IMultiValueConverter 及 ConvertBack 支持情况选择绑定模式 |
|
| 格式、颜色、尺寸转换 | Converters.FileSizeDisplayConverter、DateTimeFormatConverter、FormatConverter、StringJoinConverter、ColorToBrushConverter、ContrastBrushConverter、ThicknessSplitConverter、CornerRadiusSplitConverter 等 | 按 IValueConverter / IMultiValueConverter 及 ConvertBack 支持情况选择绑定模式 |
|
||||||
| 视图生命周期 | ViewModels.ViewModelBase;Extensions.ViewModelExtension | LoadedOnce / Loaded / Unloaded;关联视图并非 IoC 自动创建 ViewModel |
|
| 视图生命周期 | ViewModels.ViewModelBase;Extensions.ViewModelExtension | LoadedOnce / Loaded / Unloaded;关联视图并非 IoC 自动创建 ViewModel |
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ disable-model-invocation: false
|
|||||||
|
|
||||||
| 文件 | 加载策略 | 内容范围 |
|
| 文件 | 加载策略 | 内容范围 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `.agents/rules/wpf-core.md` | alwaysApply: true | 项目结构、命名约定、ViewModel、MVVM属性、Command、服务、DI、对话框、LoadingStatus、文件对话框/文件夹选择、输入限长、Mapster |
|
| `.agents/rules/wpf-core.md` | alwaysApply: true | 项目结构、命名约定、ViewModel、MVVM属性、Command、服务、DI、对话框、LoadingStatus、文件对话框/文件夹选择、输入限长、实体与展示模型映射 |
|
||||||
| `.agents/rules/csharp-syntax.md` | alwaysApply: true | C# 语法硬约束(禁止 var、null检查、Debug.WriteLine、DRY等) |
|
| `.agents/rules/csharp-syntax.md` | alwaysApply: true | C# 语法硬约束(禁止 var、null检查、Debug.WriteLine、DRY等) |
|
||||||
| `.agents/rules/architecture.md` | alwaysApply: true | 技术栈、项目架构、编译校验 |
|
| `.agents/rules/architecture.md` | alwaysApply: true | 技术栈、项目架构、编译校验 |
|
||||||
| `.agents/rules/editor-conventions.md` | alwaysApply: true | 换行符、编码规范 |
|
| `.agents/rules/editor-conventions.md` | alwaysApply: true | 换行符、编码规范 |
|
||||||
|
|||||||
@@ -4,6 +4,10 @@
|
|||||||
|
|
||||||
规则文件使用 `.md` 格式,按以下入口要求加载。
|
规则文件使用 `.md` 格式,按以下入口要求加载。
|
||||||
|
|
||||||
|
## 主要编码规范
|
||||||
|
|
||||||
|
入口只校验一次,拒绝重复判空和滥用try/catch;单次逻辑不乱抽函数,低概率防御先征求同意。
|
||||||
|
|
||||||
## 常驻规则
|
## 常驻规则
|
||||||
|
|
||||||
开始任务前,读取并遵循:
|
开始任务前,读取并遵循:
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
const fs = require('node:fs');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const html = fs.readFileSync(__dirname + '/index.html', 'utf8');
|
||||||
|
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
|
||||||
|
const elements = new Map();
|
||||||
|
function element(id) {
|
||||||
|
if (!elements.has(id)) elements.set(id, { value: id === 'pageSize' ? '50' : '', innerHTML: '', textContent: '', classList: { toggle() { return true; } }, setAttribute() {}, showModal() {}, close() {} });
|
||||||
|
return elements.get(id);
|
||||||
|
}
|
||||||
|
const context = vm.createContext({ document: { getElementById: element, querySelectorAll: () => [] }, console: { assert: assert.ok }, setTimeout: () => 1, clearTimeout() {}, FormData, assert });
|
||||||
|
vm.runInContext(script, context);
|
||||||
|
vm.runInContext(`
|
||||||
|
assert.equal(visibleRows().length, 50);
|
||||||
|
page=2; assert.equal(visibleRows().length, 22);
|
||||||
|
query='乐乐'; assert.equal(filtered().length, 3);
|
||||||
|
query=''; group='服饰鞋包'; assert.equal(filtered().length, 24);
|
||||||
|
group=''; tab='已过期'; assert.ok(filtered().every(r=>r.status==='已过期'));
|
||||||
|
for (const key of Object.keys(configs)) {
|
||||||
|
switchPage(key);
|
||||||
|
assert.ok($('tbody').innerHTML.includes('data-edit'));
|
||||||
|
openEditor(data[key][0].id);
|
||||||
|
assert.ok($('editorFields').innerHTML.includes('name="name"'));
|
||||||
|
hiddenColumns.add('group'); renderTable();
|
||||||
|
assert.ok(!$('thead').innerHTML.includes('所属分组'));
|
||||||
|
}
|
||||||
|
switchPage('stores');
|
||||||
|
assert.equal(configs.stores.columns.length, 11);
|
||||||
|
assert.equal(configs.users.columns.length, 13);
|
||||||
|
assert.ok($('tbody').innerHTML.includes('data-store-action'));
|
||||||
|
selected.add(data.stores[3].id); $('login').onclick();
|
||||||
|
assert.equal(data.stores[3].login, '登录成功');
|
||||||
|
$('batch').onclick();
|
||||||
|
assert.equal(data.stores[3].status, '正常');
|
||||||
|
assert.equal(selected.size, 0);
|
||||||
|
query='no-matching-record'; renderTable();
|
||||||
|
assert.ok($('tbody').innerHTML.includes('没有匹配的记录'));
|
||||||
|
assert.equal($('next').disabled, true);
|
||||||
|
assert.equal(escapeHtml('<img onerror="bad">'), '<img onerror="bad">');
|
||||||
|
`, context);
|
||||||
|
console.log('PASS: script syntax, five page renders, pagination, filters, editors, columns, batch action, empty state and HTML escaping.');
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# 设计检查记录
|
||||||
|
|
||||||
|
final result: blocked
|
||||||
|
|
||||||
|
参考:D:/Desktop/上货截图 下的五张原始软件截图,已逐一查看。
|
||||||
|
|
||||||
|
设计范围:店铺管理、子账号管理、超级店铺管理、超级用户管理、OEM 贴牌管理。保留 #98638f 主色,重新组织导航、筛选、表格及编辑面板。采用演示数据,不复制真实账号。
|
||||||
|
|
||||||
|
阻碍:内置浏览器安全策略拒绝 file:// 协议,未进行替代浏览器或协议绕过。没有完成浏览器截图、视觉对比与真实浏览器交互验收,不能声称视觉 QA 通过。
|
||||||
|
|
||||||
|
代码检查:运行 node DesignDemo/check.cjs,覆盖脚本语法、五页渲染、筛选、分页、编辑表单构建、列设置、批量操作、空状态及 HTML 转义。此检查使用 DOM 桩,不代替浏览器验证。
|
||||||
|
|
||||||
|
使用:双击 index.html,以现代 Edge 或 Chrome 打开。所有资源内联,无网络依赖。数据仅保留在页面内存,刷新页面恢复初始样例;新增、编辑、续期及权限均为本地交互演示。
|
||||||
|
|
||||||
|
WPF 映射:侧栏与主区域采用 Grid,列表采用 DataGrid,筛选采用 TextBox/ComboBox,编辑采用项目对话框链路。颜色可迁入 ResourceDictionary;行高提供 36px 舒适与 28px 紧凑两档,默认紧凑;每页默认 50 条。实际 WPF 控件尺寸、DPI、性能和键盘行为需要后续实现时验证。
|
||||||
|
|
||||||
|
第二版调整:移除统计卡片与大标题说明,采用 44px 顶栏、156px 侧栏、行内筛选和表格网格线。店铺列表显示 11 个业务列,超级用户显示 13 个业务列;增加序号、模拟进入/续期和批量检测/登录操作。编辑改为居中双列表单。样例店铺扩展至 72 条以验证分页。视觉 QA 仍因前述浏览器限制未完成。
|
||||||
|
|
||||||
|
第三版调整:普通按钮、输入框、面板及表格边框使用中性灰;主按钮保留 #98638f 填充并取消彩色描边;行内次要操作改为灰色文字,悬停采用灰底,选中行保留浅品牌色。维持原有紧凑布局和业务交互。视觉验收状态仍为 blocked。
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>29 供应链 · 店铺管理设计演示</title>
|
||||||
|
<style>
|
||||||
|
:root{--brand:#98638f;--brand-dark:#784b70;--tint:#f4edf3;--ink:#292731;--muted:#85828e;--line:#e5e7eb;--canvas:#f5f6f7;--green:#31856a;--red:#c35c64;--amber:#a77725}
|
||||||
|
*{box-sizing:border-box}body{margin:0;font:14px/1.5 "Segoe UI","Microsoft YaHei",sans-serif;color:var(--ink);background:var(--canvas)}button,input,select{font:inherit}button{cursor:pointer;white-space:nowrap}button,input,select{border:1px solid #d1d5db;border-radius:6px;background:white;color:inherit}button{padding:8px 15px;transition:background .15s}button:hover:not(:disabled){background:#f0f2f4;border-color:#b9c0c8}button:disabled{background:#f5f6f7;color:#a0a6ad;border-color:#e2e5e9;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible,a:focus-visible{outline:2px solid #64748b;outline-offset:2px}input,select{height:36px;padding:0 11px;min-width:0}input[type=checkbox]{width:15px;height:15px;accent-color:var(--brand);vertical-align:middle;cursor:pointer}button.primary{background:var(--brand);color:#fff;border-color:transparent}button.primary:hover:not(:disabled){background:var(--brand-dark);border-color:transparent}button.text{border:0;background:none;color:#626970;padding:5px 8px}button.text:hover:not(:disabled){background:#e9edf0;color:#30353b}.muted{color:var(--muted)}.mono{font-family:Consolas,monospace;font-size:12px;color:#777482}.app{display:grid;grid-template-columns:218px minmax(0,1fr);height:100vh;min-height:680px}.sidebar{background:#fff;border-right:1px solid var(--line);display:flex;flex-direction:column;padding:28px 16px 16px}.brand{padding:0 12px 30px;display:flex;align-items:center;gap:10px}.brand b{font-size:29px;color:var(--brand);letter-spacing:-2px}.brand strong{font-size:17px;letter-spacing:1px}.brand small{display:block;color:var(--muted);font-size:10px;letter-spacing:2px}.section-label{padding:15px 14px 8px;color:#9a97a1;font-size:11px;letter-spacing:1.4px}.nav{display:flex;align-items:center;gap:13px;width:100%;border:0;text-align:left;padding:12px 14px;margin:3px 0;background:none;color:#65616e;border-radius:7px}.nav .nav-index{font:11px Consolas;color:#a6a0aa}.nav.active{background:var(--tint);color:var(--brand-dark);font-weight:600}.nav.active .nav-index{color:var(--brand)}.nav.active:after{content:"";width:5px;height:5px;border-radius:50%;background:var(--brand);margin-left:auto}.sidebar-bottom{margin-top:auto;padding:18px 12px 0;border-top:1px solid var(--line)}.demo-badge{font-size:11px;background:var(--tint);color:var(--brand-dark);padding:3px 7px;border-radius:4px}.sidebar-bottom p{font-size:11px;color:var(--muted);line-height:1.8}.shell{min-width:0;display:flex;flex-direction:column;overflow:hidden}.topbar{height:66px;flex-shrink:0;background:white;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 30px}.breadcrumb{font-size:12px;color:var(--muted)}.breadcrumb span{color:var(--ink);padding-left:10px}.profile{display:flex;align-items:center;gap:20px;font-size:12px}.profile b{color:var(--brand-dark);font-weight:600}.avatar{background:var(--tint);color:var(--brand-dark);padding:8px 10px;border-radius:8px;font-weight:600}.content{padding:26px 30px 18px;flex:1;min-height:0;display:flex;flex-direction:column;gap:20px}.page-heading{display:flex;justify-content:space-between;align-items:center;gap:20px}.eyebrow{font-size:10px;letter-spacing:2px;color:var(--brand);font-weight:700;margin-bottom:4px}h1{font-size:25px;letter-spacing:.5px;margin:0;font-weight:650}.page-heading p{font-size:12px;color:var(--muted);margin:6px 0 0}.heading-actions{display:flex;gap:10px}.stats{display:grid;grid-template-columns:repeat(4,1fr);border:1px solid var(--line);background:white;border-radius:9px;padding:19px 0}.stat{padding:0 25px;border-right:1px solid var(--line);position:relative}.stat:last-child{border:0}.stat-label{color:#77727f;font-size:12px}.stat-number{font-size:27px;font-weight:650;margin-top:5px;font-variant-numeric:tabular-nums;letter-spacing:-.5px}.stat-note{position:absolute;right:23px;bottom:6px;font-size:11px;color:var(--muted)}.stat:nth-child(2) .stat-number{color:var(--green)}.stat:nth-child(3) .stat-number{color:var(--amber)}.stat:nth-child(4) .stat-number{color:var(--brand)}.workspace{background:#fff;border:1px solid var(--line);border-radius:9px;display:flex;flex:1;min-height:0;flex-direction:column;overflow:hidden}.tabs{display:flex;gap:26px;margin:0 22px;border-bottom:1px solid var(--line);min-height:53px;align-items:stretch}.tab{border:0;border-radius:0;padding:0 2px;background:transparent;font-size:13px;color:#898390;position:relative}.tab.active{color:var(--brand-dark);font-weight:600}.tab.active:after{content:"";height:3px;background:var(--brand);position:absolute;bottom:0;left:0;right:0;border-radius:3px 3px 0 0}.tab small{margin-left:7px;font-size:11px;color:inherit;background:#f5f3f6;padding:2px 6px;border-radius:4px}.filters{display:flex;align-items:end;gap:12px;padding:18px 22px}.field{display:flex;flex-direction:column;gap:7px}.field label{font-size:11px;color:#77717f}.search-field{flex:1;max-width:330px}.field select{width:150px}.toolbar{display:flex;justify-content:space-between;align-Line truncated
|
||||||
|
/* Desktop workbench: controls stay compact; wide datasets scroll horizontally. */
|
||||||
|
body{font-size:12px;background:#f3f4f5;color:#30353b;min-width:1000px}
|
||||||
|
.app{grid-template-columns:156px minmax(0,1fr);min-height:560px}
|
||||||
|
.sidebar{padding:0;background:#f7f8f9;border-right:1px solid #d6d9de}
|
||||||
|
.brand{height:44px;padding:0 12px;gap:8px;background:var(--brand);color:white;border-bottom:1px solid transparent}
|
||||||
|
.brand b{color:white;font-size:24px}.brand strong{font-size:15px}.brand small{display:none}
|
||||||
|
.section-label{padding:12px 12px 5px;font-size:11px;letter-spacing:0;color:#808791}
|
||||||
|
.nav{border-radius:0;margin:0;padding:8px 12px;gap:8px;font-size:12px;height:34px}
|
||||||
|
.nav.active{background:#eee5ec;color:var(--brand-dark);border-left:0;padding-left:12px}
|
||||||
|
.nav.active:after{display:none}.nav .nav-index{font-size:10px}.sidebar-bottom{padding:10px 8px}.sidebar-bottom p{display:none}.demo-badge{font-size:10px;padding:2px 4px}.sidebar-bottom button{font-size:11px}
|
||||||
|
.topbar{height:44px;padding:0 14px;background:var(--brand);color:white;border-bottom:1px solid transparent}.breadcrumb,.breadcrumb span,.profile b{color:white}.breadcrumb{font-size:12px}.profile{gap:16px;font-size:11px}.avatar{display:none}
|
||||||
|
.content{padding:0 7px 0;gap:0}.page-heading{height:39px;min-height:39px;padding:0 4px;border-bottom:1px solid #dce0e4;gap:10px}.page-heading p,.eyebrow{display:none}h1{font-size:13px;letter-spacing:0;font-weight:600}.heading-actions{gap:6px}
|
||||||
|
button,input,select{border-radius:2px;font-size:12px}button{padding:3px 10px;height:27px}input,select{height:26px;padding:0 7px}input[type=checkbox]{height:13px;width:13px;margin:0}button.text{height:24px;padding:1px 6px}
|
||||||
|
.workspace{border:1px solid #d6d9de;border-top:0;border-radius:0}.tabs{min-height:31px;height:31px;flex-shrink:0;margin:0;padding:0 9px;gap:3px;background:#f2f3f5;border-bottom:1px solid #dce0e4}.tab{height:31px;padding:0 13px;font-size:12px;color:#746b78;border-right:1px solid #e3e5e8}.tab.active{background:white}.tab.active:after{height:2px}.tab small{font-size:10px;padding:0 4px;background:none}
|
||||||
|
.filters{padding:7px 9px;gap:9px;align-items:center;flex-wrap:wrap;background:#ffffff}.filters .field{flex-direction:row;align-items:center;gap:5px}.filters .field label{font-size:12px;color:#626970;white-space:nowrap}.filters .field select{width:112px}.search-field{flex:none;max-width:none}.search-field input{width:235px}
|
||||||
|
.toolbar{padding:5px 9px;border-top:1px solid #e5e7eb;gap:7px;min-height:36px;background:#fafafa;flex-wrap:wrap}.toolbar-left,.toolbar-right{gap:6px}.toolbar button{font-size:12px;padding:2px 9px;height:25px}.toolbar-left>span{font-size:11px;border-right:1px solid #dce0e4;padding-right:9px;margin-right:3px}
|
||||||
|
.table-scroll{border-top:1px solid #d6d9de}table{font-size:12px;width:max-content;min-width:100%}th{height:29px;font-size:12px;padding:0 9px;background:#f0f2f4;color:#59616b;font-weight:500;border-right:1px solid #e0e3e7;border-bottom:1px solid #d4d8dd}td{height:36px;padding:2px 9px;border-right:1px solid #e9ebee;border-bottom:1px solid #e9ebee;color:#343a40}.compact td{height:28px;padding:1px 9px}
|
||||||
|
th:first-child,td:first-child{width:30px;min-width:30px;padding:0 8px;position:sticky;left:0;background:white;z-index:1}th:first-child{background:#f0f2f4;z-index:3}.row-number{color:#9299a1;text-align:right;font-size:11px;min-width:34px}thead th{z-index:2}th:last-child{z-index:3;background:#f0f2f4}td:last-child,th:last-child{box-shadow:-3px 0 4px #0000000a;border-left:1px solid #dce0e4}
|
||||||
|
tbody tr:nth-child(even) td{background:#fafbfc}tbody tr:hover td{background:#f0f2f4}tbody tr.selected td{background:#f3eaf1}.entity{gap:0}.entity-mark,.entity small,.compact .entity-mark{display:none}.entity-name{margin:0;font-size:12px;font-weight:500}.pill{font-size:11px;padding:0 5px;border-radius:2px;line-height:19px}.tag{background:none;padding:0;font-size:12px;color:#60666e}.date{font-size:12px}.subline{display:inline;font-size:10px;margin-left:6px}.mono{color:#69727d;font-size:11px}.muted{color:#7c838c}.row-action{padding:0 5px!important;height:23px!important}.pagination{height:35px;min-height:35px;flex-shrink:0;padding:3px 9px;background:#f7f8f9;font-size:11px}.pagination button,.pagination select{height:24px}.pagination-controls{gap:6px}.current-page{padding:2px 8px}.statusbar{height:23px;min-height:23px;align-items:center;padding:0 5px;font-size:10px}
|
||||||
|
.drawer{margin:auto;width:620px;max-width:90vw;height:auto;max-height:90vh;border-radius:3px}.dialog-head{padding:11px 15px;background:#f5f6f7}.dialog-head h2{font-size:14px}.dialog-head p{font-size:10px;margin-top:2px}.dialog-body{padding:15px;gap:13px}.drawer .dialog-body{display:grid;grid-template-columns:1fr 1fr}.drawer .dialog-body>.help{grid-column:1/-1}.dialog-body input:not([type=checkbox]),.dialog-body select{height:29px}.dialog-body .field{gap:5px}.dialog-footer{padding:9px 15px}.permissions{grid-template-columns:1fr;gap:6px}.columns-dialog{border-radius:3px}.help{border-radius:2px;font-size:11px}
|
||||||
|
/* Desktop window frame and navigation hierarchy. */
|
||||||
|
.app{grid-template-columns:180px minmax(0,1fr);grid-template-rows:32px minmax(0,1fr);height:100dvh;min-height:594px;border:1px solid #c9c4cd}
|
||||||
|
.ui-icon{display:block;width:16px;height:16px;flex-shrink:0;fill:none;stroke:currentColor;stroke-width:1.65;stroke-linecap:round;stroke-linejoin:round}
|
||||||
|
.window-titlebar{grid-column:1/-1;display:flex;align-items:center;justify-content:space-between;background:var(--brand);border-bottom:1px solid var(--brand);user-select:none}.window-caption{display:flex;align-items:center;gap:8px;padding-left:11px;color:#fff;font-size:11px}.window-caption .ui-icon{color:#fff}.window-actions{display:flex;height:31px}.window-actions button{display:grid;place-items:center;width:46px;height:31px;padding:0;border:0;border-radius:0;background:transparent;color:#fff}.window-actions .ui-icon{width:12px;height:12px;stroke-width:1}.window-actions button:hover{background:#ffffff25}.window-actions .window-close:hover{background:#c42b1c;color:#fff}
|
||||||
|
.sidebar{grid-column:1;grid-row:2;min-height:0;overflow:auto}.shell{grid-column:2;grid-row:2;min-height:0}
|
||||||
|
.brand{justify-content:center;padding:0;background:#f7f8f9;border-bottom:1px solid #e2e4e8;color:var(--brand)}.brand>.ui-icon{width:32px;height:32px;stroke-width:1.5}
|
||||||
|
.section-label{display:flex;align-items:center;gap:8px;margin:13px 8px 4px;padding:7px 8px;background:transparent;color:#65516b;font-size:12px;font-weight:650;border-radius:3px;letter-spacing:0}.section-label>.ui-icon{width:17px;height:17px}
|
||||||
|
.sidebar nav{margin:0 8px 0 16px;border-left:1px solid #ddd6e0;padding-left:5px}.sidebar .nav{height:34px;padding:0 9px;gap:8px;border-radius:3px;font-size:12px;color:#727785}.sidebar .nav.active{padding-left:9px;background:transparent;color:var(--brand-dark);font-weight:650}.sidebar .nav .ui-icon{width:15px;height:15px}.sidebar .nav:hover:not(:disabled){background:transparent;color:var(--brand-dark)}.sidebar .nav.active:after{display:block;content:"";height:14px;width:2px;border-radius:1px;background:var(--brand);margin-left:auto}
|
||||||
|
|
||||||
|
.title-account{display:flex;align-items:center;gap:12px;margin-left:auto;padding:0 18px;color:#fff;font-size:10px}
|
||||||
|
.title-account b{font-weight:600;color:#fff}
|
||||||
|
.account-divider{height:11px;border-left:1px solid #ffffff40}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="app"><div class="window-titlebar"><div class="window-caption"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="m12 2 9 5v10l-9 5-9-5V7zM3 7l9 5 9-5M12 12v10M7.5 4.5l9 5V14"/></svg><span>29 供应链 — 运营管理工作台</span></div><div class="title-account"><span>积分 <b>9,759</b></span><span class="account-divider"></span><span>管理员</span></div><div class="window-actions" aria-label="窗口按钮外观演示"><button type="button" class="" aria-label="最小化(外观演示)" title="最小化 · 仅外观演示"><svg class="ui-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="M1 6h10"/></svg></button><button type="button" class="" aria-label="最大化(外观演示)" title="最大化 · 仅外观演示"><svg class="ui-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="M1.5 1.5h9v9h-9z"/></svg></button><button type="button" class="window-close" aria-label="关闭(外观演示)" title="关闭 · 仅外观演示"><svg class="ui-icon" viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button></div></div>
|
||||||
|
<aside class="sidebar"><div class="brand" aria-label="29 供应链"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="m12 2 9 5v10l-9 5-9-5V7zM3 7l9 5 9-5M12 12v10M7.5 4.5l9 5V14"/></svg></div><div class="section-label"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 10v11h18V10M2 10l2-7h16l2 7zM9 21v-7h6v7M7 3v7M17 3v7"/></svg><span>店铺工作台</span></div><nav aria-label="店铺工作台"><button class="nav active" data-page="stores"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 10v11h18V10M2 10l2-7h16l2 7zM9 21v-7h6v7M7 3v7M17 3v7"/></svg>店铺管理</button><button class="nav" data-page="accounts"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M16 21v-3a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v3M9 10a4 4 0 1 0 0-8 4 4 0 0 0 0 8M18 3a4 4 0 0 1 0 8M22 21v-3a4 4 0 0 0-3-4"/></svg>子账号管理</button></nav><div class="section-label"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2l9 4v6c0 5-9 10-9 10S3 17 3 12V6zM8 12l3 3 5-6"/></svg><span>超级管理</span></div><nav aria-label="超级管理"><button class="nav" data-page="superstores"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 10v11h18V10M2 10l2-7h16l2 7zM9 21v-7h6v7M7 3v7M17 3v7"/></svg>超级店铺管理</button><button class="nav" data-page="users"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M16 21v-3a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v3M9 10a4 4 0 1 0 0-8 4 4 0 0 0 0 8M18 3a4 4 0 0 1 0 8M22 21v-3a4 4 0 0 0-3-4"/></svg>超级用户管理</button><button class="nav" data-page="oem"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 3h10l7 7-11 11-7-7V4zM8 7h.01"/></svg>OEM 贴牌管理</button></nav><div class="sidebar-bottom"><span class="demo-badge">桌面工作台 · 演示</span><p>专注每一家店铺的日常运营<br>本地交互演示 · 数据均为模拟</p><button class="text" id="designNotes">界面设计说明</button></div></aside>
|
||||||
|
<div class="shell"><span id="crumb" hidden></span>
|
||||||
|
<main class="content"><section class="page-heading"><div><div class="eyebrow" id="eyebrow">STORE MANAGEMENT</div><h1 id="pageTitle">店铺管理</h1><p id="pageDescription"></p></div><div class="heading-actions"><button id="refresh">刷新列表</button><button class="primary" id="add">添加店铺</button></div></section>
|
||||||
|
|
||||||
|
<section class="workspace" aria-label="管理列表"><div class="tabs" id="tabs"></div><form class="filters" id="filterForm"><div class="field search-field"><label for="keyword">关键词</label><input id="keyword" maxlength="100" placeholder="搜索店铺名称 / 店铺 ID"></div><div class="field"><label for="groupFilter">所属分组</label><select id="groupFilter"></select></div><div class="field"><label for="statusFilter">状态</label><select id="statusFilter"><option value="">全部状态</option><option>正常</option><option>即将到期</option><option>已过期</option></select></div><button class="primary" type="submit">查询</button><button type="button" id="reset">重置</button></form>
|
||||||
|
<div class="toolbar"><div class="toolbar-left"><span id="selection" class="muted">选择记录后可批量操作</span><button id="batch" disabled>批量续期</button><button id="detect" disabled>检测选中</button><button id="login" disabled>登录选中</button></div><div class="toolbar-right"><span class="muted" id="resultCount"></span><button id="density" aria-pressed="true">舒适视图</button><button id="columnSettings">列设置</button></div></div>
|
||||||
|
<div class="table-scroll"><table id="table" class="compact"><thead id="thead"></thead><tbody id="tbody"></tbody></table></div><footer class="pagination"><span id="range"></span><div class="pagination-controls"><label for="pageSize">每页</label><select id="pageSize"><option>20</option><option selected>50</option><option>100</option></select><button id="prev" aria-label="上一页">上一页</button><span class="current-page" id="pageNumber">1</span><button id="next" aria-label="下一页">下一页</button></div></footer></section>
|
||||||
|
<footer class="statusbar"><span id="loadStatus">数据已就绪 · 本地演示</span><span>29 供应链 / 管理工作台</span></footer></main></div></div>
|
||||||
|
<dialog class="drawer" id="editor"><form id="editForm"><header class="dialog-head"><div><h2 id="editorTitle"></h2><p>修改仅在本次演示中生效</p></div><button type="button" class="text" data-close="editor">关闭</button></header><div class="dialog-body" id="editorFields"></div><footer class="dialog-footer"><button type="button" data-close="editor">取消</button><button class="primary" type="submit">保存</button></footer></form></dialog>
|
||||||
|
<dialog class="columns-dialog" id="columns"><header class="dialog-head"><h2>显示的列</h2><button class="text" data-close="columns">完成</button></header><div class="dialog-body" id="columnOptions"></div></dialog>
|
||||||
|
<dialog id="details" style="width:520px;max-width:95vw"><header class="dialog-head"><h2 id="detailTitle"></h2><button class="text" data-close="details">关闭</button></header><div class="dialog-body" id="detailBody"></div></dialog><div class="toast" role="status" id="toast" hidden></div>
|
||||||
|
<script>
|
||||||
|
'use strict';
|
||||||
|
const $=id=>document.getElementById(id);
|
||||||
|
const escapeHtml=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
|
const names=['乐乐生活馆','清麦日用百货','栖木家居旗舰店','佐薇服饰小铺','青禾优选','云朵母婴生活','拾光好物集合店','橙意食品专营店','木子家居日用','浅湾服饰店','山野户外生活','简物生活旗舰店','暖晨家纺店','知味食品小铺','白露日用百货','云间服饰集合店','小满优选','春序家居店','鹿鸣母婴店','青山好物','星野百货','暮色生活馆','沐光服饰','初禾日用品'];
|
||||||
|
const stores=Array.from({length:72},(_,i)=>({name:names[i%names.length]+(i>=24?" · "+(Math.floor(i/24)+1)+"店":""),i})).map(({name,i})=>({id:1001+i,name,code:'wx'+(316129135100+i*74031).toString(16)+'a'+i,group:['精选店铺','服饰鞋包','生活百货'][i%3],account:['运营一组','运营二组','未分配'][i%3],owner:'demo_owner_'+(i%4+1),phone:'138****'+String(1200+i),status:i%7===3?'已过期':i%5===2?'即将到期':'正常',expires:i%7===3?'2026-10-20':i%5===2?'2026-11-02':'2027-05-09',note:i%3===0?'重点运营店铺':'',permissions:['店铺列表','订单管理'],created:'2026-08-14 15:16',login:i%7===3?'未登录':'登录成功',api:i%4===0?'未购买':'已开通',permanent:i%9===0?'是':'否',secondary:i%6===0?'已启用':'未启用'}));
|
||||||
|
const data={stores,superstores:stores.map(r=>({...r,id:r.id+3000})),accounts:['林小夏','陈晓','周宁','许安','李可','宋悦'].map((name,i)=>({id:2001+i,name,code:'operator_'+(i+1),phone:'139****'+(2300+i),group:['运营','客服','仓储'][i%3],status:i===4?'已停用':'正常',account:'主账号 · 演示企业',note:'',permissions:['店铺列表','订单管理']})),users:Array.from({length:18},(_,i)=>({id:3001+i,name:['青禾供应链','云飞商贸','开兴科技','花下海','众店联源','微擎科技'][i%6]+(i>5?' '+(Math.floor(i/6)+1):''),code:'user_'+(801+i),phone:'137****'+(5600+i),group:i%4===0?'代理商':'主账户',status:i===5?'已停用':'正常',company:['青禾商贸有限公司','云飞供应链有限公司','开兴网络科技'][i%3],points:300+i*20,balance:(140+i*37.5).toFixed(2),fee:'2.50',monthly:30,returnFee:'3.00',agent:['云飞','大牛','花下海'][i%3],type:'普通用户',permissions:['商品采集','在线寄件'],note:''})),oem:['桃花源供应链','店速通','开茂科技','枫谷拍单','洋总代理','臻和网络','贝塔一体仓','佳俊商贸'].map((name,i)=>({id:5001+i,name,code:'26'+(701+i)+'TW'+i,group:'品牌合作',status:'正常',account:'demo_brand_'+(i+1),phone:'136****'+(7400+i),note:'',permissions:[]}))};
|
||||||
|
const configs={stores:{title:'店铺管理',en:'STORE MANAGEMENT',desc:'集中管理店铺、账号与授权,让日常运营井然有序。',add:'添加店铺',batch:'批量续期',search:'搜索店铺名称 / 店铺 ID',columns:[['name','店铺信息'],['group','所属分组'],['account','子账号'],['status','授权状态'],['expires','到期时间'],['note','备注']],groups:['精选店铺','服饰鞋包','生活百货']},superstores:{title:'超级店铺管理',en:'STORE ADMINISTRATION',desc:'跨账号查看全部店铺,统一管理店铺归属与授权状态。',add:'添加店铺',batch:'批量检测',search:'搜索店铺 / 所属账号 / 店铺 ID',columns:[['name','店铺信息'],['owner','所属账号'],['group','店铺分组'],['account','子账号'],['status','授权状态'],['expires','到期时间']],groups:['精选店铺','服饰鞋包','生活百货']},accounts:{title:'子账号管理',en:'TEAM & ACCESS',desc:'为团队分配独立账号,以清晰的访问权限协同管理店铺。',add:'添加子账号',batch:'批量启用',search:'搜索昵称 / 登录账号',columns:[['name','用户信息'],['phone','登录手机号'],['group','角色分组'],['status','账号状态'],['permissions','可访问页面'],['account','所属主账号']],groups:['运营','客服','仓储']},users:{title:'超级用户管理',en:'USER ADMINISTRATION',desc:'统一管理用户、功能权限与账户信息。',add:'添加用户',batch:'批量启用',search:'搜索用户 / 手机号 / 公司',columns:[['name','用户信息'],['group','用户分组'],['company','公司'],['points','积分'],['balance','快递余额'],['fee','每单快递费'],['status','账号状态']],groups:['主账户','代理商']},oem:{title:'OEM 贴牌管理',en:'BRAND PARTNERS',desc:'管理合作品牌标识与主体账号,建立统一的品牌工作空间。',add:'添加贴牌',batch:'批量启用',search:'搜索贴牌名称 / 贴牌编码',columns:[['name','贴牌名称'],['code','贴牌编码'],['account','主体账号'],['status','状态'],['assets','品牌素材']],groups:['品牌合作']}};
|
||||||
|
configs.stores.columns=[['name','店铺名称'],['code','店铺 ID'],['created','添加时间'],['expires','到期时间'],['status','授权状态'],['group','分组'],['account','子账号'],['phone','子账号手机号'],['login','登录状态'],['api','API 购买'],['note','备注']];
|
||||||
|
configs.superstores.columns=[['name','店铺名称'],['code','店铺 ID / 登录号码'],['owner','所属账号'],['account','子账号'],['group','店铺分组'],['login','登录状态'],['status','授权状态'],['api','API 购买'],['secondary','二级超管'],['permanent','永久'],['note','备注']];
|
||||||
|
configs.accounts.columns=[['name','用户昵称'],['code','登录账号'],['phone','手机号'],['group','分组'],['account','所属主账号'],['status','状态'],['permissions','可访问页面'],['note','备注']];
|
||||||
|
configs.users.columns=[['name','用户昵称'],['phone','手机 / 登录账号'],['group','分组'],['company','公司'],['type','账户类型'],['permissions','功能权限'],['agent','代理名称'],['points','积分'],['monthly','月费耗点'],['balance','快递余额'],['fee','每单快递费'],['returnFee','每单退货费'],['status','状态']];
|
||||||
|
configs.oem.columns=[['code','贴牌编码'],['name','贴牌名称'],['account','主体账号'],['assets','图标'],['assetsTitle','题图'],['status','状态'],['note','备注']];
|
||||||
|
let current='stores',tab='',page=1,query='',group='',status='',sortAsc=true,editingId=null,selected=new Set(),hiddenColumns=new Set(),toastTimer;
|
||||||
|
function isStore(){return current==='stores'||current==='superstores'}
|
||||||
|
function filtered(){return data[current].filter(r=>(!query||Object.values(r).join(' ').toLowerCase().includes(query))&&(!group||r.group===group)&&(!status||r.status===status)&&(!tab||r.status===tab)).sort((a,b)=>sortAsc?a.name.localeCompare(b.name,'zh-CN'):b.name.localeCompare(a.name,'zh-CN'))}
|
||||||
|
function visibleRows(){const rows=filtered();return rows.slice((page-1)*Number($('pageSize').value),page*Number($('pageSize').value))}
|
||||||
|
function showToast(message){$('toast').textContent=message;$('toast').hidden=false;clearTimeout(toastTimer);toastTimer=setTimeout(()=>$('toast').hidden=true,3200)}
|
||||||
|
function renderTabs(){const tabs=isStore()?[['','全部店铺'],['正常','授权正常'],['即将到期','即将到期'],['已过期','已过期']]:[['','全部'+(current==='oem'?'品牌':'账号')],['正常','正常'],['已停用','已停用']];$('tabs').innerHTML=tabs.map(([value,label])=>`<button class="tab ${tab===value?'active':''}" data-tab="${value}" aria-pressed="${tab===value}">${label}<small>${data[current].filter(r=>!value||r.status===value).length}</small></button>`).join('')}
|
||||||
|
function cell(r,key){const v=escapeHtml(r[key]);switch(key){case'name':return `<div class="entity"><span class="entity-mark ${r.id%3===0?'alt':''}">${escapeHtml(r.name.slice(0,1))}</span><div><div class="entity-name">${v}</div><small>${escapeHtml(r.code)}</small></div></div>`;case'login':return `<span style="color:${r.login==='登录成功'?'var(--green)':'var(--muted)'}">${v}</span>`;case'status':return `<span class="pill ${r.status==='即将到期'?'warn':r.status==='正常'?'':'error'}">${v==='正常'&&isStore()?'授权正常':v}</span>`;case'group':return `<span class="tag">${v}</span>`;case'expires':return `<span class="date">${v}</span>${r.status==='即将到期'?'<div class="subline" style="color:var(--amber)">5 天后到期</div>':''}`;case'permissions':return `<span class="muted">${escapeHtml(r.permissions.join('、'))||'尚未分配'}</span>`;case'assetsTitle':case'assets':return '<span class="muted">暂未上传</span>';case'balance':case'fee':case'returnFee':return `<span class="date">¥ ${v}</span>`;case'code':case'owner':return `<span class="mono">${v}</span>`;case'note':return `<span class="muted">${v||'—'}</span>`;default:return v||'<span class="muted">—</span>'}}
|
||||||
|
function renderTable(){const cfg=configs[current],rows=filtered(),size=Number($('pageSize').value);page=Math.max(1,Math.min(page,Math.ceil(rows.length/size)||1));const visible=visibleRows(),cols=cfg.columns.filter(([key])=>!hiddenColumns.has(key));$('thead').innerHTML=`<tr><th><input type="checkbox" id="selectAll" aria-label="选择当前页全部记录" ${visible.length&&visible.every(r=>selected.has(r.id))?'checked':''}></th><th class="row-number">序号</th>${cols.map(([key,label])=>`<th>${key==='name'?`<button class="sort" id="sortName">${label} ${sortAsc?'↑':'↓'}</button>`:label}</th>`).join('')}<th>操作</th></tr>`;$('tbody').innerHTML=visible.length?visible.map((r,index)=>`<tr class="${selected.has(r.id)?'selected':''}"><td><input type="checkbox" data-select="${r.id}" aria-label="选择${escapeHtml(r.name)}" ${selected.has(r.id)?'checked':''}></td><td class="row-number">${(page-1)*size+index+1}</td>${cols.map(([key])=>`<td>${cell(r,key)}</td>`).join('')}<td>${isStore()?`<button class="text row-action" data-store-action="enter" data-id="${r.id}">进入</button><button class="text row-action" data-store-action="renew" data-id="${r.id}">续期</button>`:""}<button class="text row-action" data-detail="${r.id}">${isStore()?'查看':'详情'}</button><button class="text row-action" data-edit="${r.id}">编辑</button></td></tr>`).join(''):`<tr><td class="empty" colspan="${cols.length+3}">没有匹配的记录,请调整筛选条件或重置。</td></tr>`;const all=$('selectAll');all.indeterminate=visible.some(r=>selected.has(r.id))&&!visible.every(r=>selected.has(r.id));$('selection').textContent=selected.size?`已选择 ${selected.size} 项`:'选择记录后可批量操作';$('selection').className=selected.size?'selection':'muted';$('batch').disabled=!selected.size;$('detect').disabled=$('login').disabled=!selected.size;$('resultCount').textContent=`共 ${rows.length} 条记录`;$('range').textContent=rows.length?`显示 ${(page-1)*size+1}–${Math.min(page*size,rows.length)} 条,共 ${rows.length} 条`:'共 0 条记录';$('pageNumber').textContent=`${page} / ${Math.ceil(rows.length/size)||1}`;$('prev').disabled=page===1;$('next').disabled=page*size>=rows.length}
|
||||||
|
function render(){renderTabs();renderTable()}
|
||||||
|
function switchPage(key){current=key;tab='';page=1;query='';group='';status='';selected.clear();hiddenColumns.clear();const cfg=configs[key];$('detect').hidden=$('login').hidden=!isStore();document.querySelectorAll('[data-page]').forEach(b=>{b.classList.toggle('active',b.dataset.page===key);b.setAttribute('aria-current',b.dataset.page===key?'page':'false')});$('crumb').textContent=$('pageTitle').textContent=cfg.title;$('eyebrow').textContent=cfg.en;$('pageDescription').textContent=cfg.desc;$('add').textContent=cfg.add;$('batch').textContent=cfg.batch;$('keyword').value='';$('keyword').placeholder=cfg.search;$('groupFilter').innerHTML='<option value="">全部分组</option>'+cfg.groups.map(g=>`<option>${g}</option>`).join('');$('statusFilter').innerHTML='<option value="">全部状态</option>'+(isStore()?['正常','即将到期','已过期']:['正常','已停用']).map(s=>`<option>${s}</option>`).join('');render()}
|
||||||
|
function field(label,name,value='',required=false,type='text'){return `<div class="field"><label for="edit_${name}">${label}${required?' <span style="color:var(--brand)">*</span>':''}</label><input id="edit_${name}" name="${name}" type="${type}" value="${escapeHtml(value)}" maxlength="100" ${required?'required':''}></div>`}
|
||||||
|
function openEditor(id=null){editingId=id;const r=data[current].find(r=>r.id===id)||{},cfg=configs[current];$('editorTitle').textContent=id?'编辑'+(isStore()?'店铺':current==='oem'?'贴牌':'用户'):cfg.add;let fields=field(isStore()?'店铺名称':current==='oem'?'贴牌名称':'用户昵称','name',r.name,true)+field(isStore()?'店铺 ID':current==='oem'?'贴牌编码':'登录账号','code',r.code,true);if(current==='accounts'||current==='users')fields+=field('手机号','phone',r.phone,true)+field(id?'新密码(留空则不修改)':'密码','password','',!id,'password');fields+=`<div class="field"><label for="edit_group">所属分组</label><select name="group" id="edit_group">${cfg.groups.map(g=>`<option ${r.group===g?'selected':''}>${g}</option>`).join('')}</select></div>`;if(isStore()||current==='oem')fields+=field(current==='oem'?'主体账号':'子账号','account',r.account,current==='oem');if(current==='users')fields+=field('公司','company',r.company);if(!isStore())fields+=`<div class="field"><label for="edit_status">账号状态</label><select name="status" id="edit_status"><option ${r.status!=='已停用'?'selected':''}>正常</option><option ${r.status==='已停用'?'selected':''}>已停用</option></select></div>`;if(current==='accounts'||current==='users')fields+=`<div class="field"><label>可访问页面</label><div class="permissions">${['店铺列表','订单管理','商品采集','在线寄件','评分考核','税务申报'].map(p=>`<label><input type="checkbox" name="permission" value="${p}" ${(r.permissions||[]).includes(p)?'checked':''}>${p}</label>`).join('')}</div></div>`;fields+=field('备注','note',r.note);if(isStore()&&!id)fields+='<div class="help">此处演示手动添加流程。正式系统可在此接入扫码授权;新记录默认使用演示授权。</div>';$('editorFields').innerHTML=fields;$('editor').showModal()}
|
||||||
|
document.querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>switchPage(b.dataset.page));
|
||||||
|
$('filterForm').onsubmit=e=>{e.preventDefault();query=$('keyword').value.trim().toLowerCase();group=$('groupFilter').value;status=$('statusFilter').value;page=1;selected.clear();renderTable()};
|
||||||
|
$('reset').onclick=()=>{query=group=status=tab='';page=1;selected.clear();$('keyword').value=$('groupFilter').value=$('statusFilter').value='';render()};
|
||||||
|
$('tabs').onclick=e=>{const b=e.target.closest('[data-tab]');if(b){tab=b.dataset.tab;page=1;selected.clear();renderTabs();renderTable()}};
|
||||||
|
$('prev').onclick=()=>{page--;renderTable()};$('next').onclick=()=>{page++;renderTable()};$('pageSize').onchange=()=>{page=1;renderTable()};
|
||||||
|
$('table').onchange=e=>{if(e.target.id==='selectAll')visibleRows().forEach(r=>e.target.checked?selected.add(r.id):selected.delete(r.id));else if(e.target.dataset.select){const id=Number(e.target.dataset.select);e.target.checked?selected.add(id):selected.delete(id)}renderTable()};
|
||||||
|
$('table').onclick=e=>{const action=e.target.closest('[data-store-action]');if(action){const r=data[current].find(r=>r.id===Number(action.dataset.id));if(action.dataset.storeAction==='renew'){r.status='正常';r.expires='2027-05-09';render();showToast('已模拟续期:'+r.name)}else{showToast('模拟进入店铺:'+r.name+'(未连接真实店铺)')}return}const edit=e.target.closest('[data-edit]'),detail=e.target.closest('[data-detail]');if(edit)openEditor(Number(edit.dataset.edit));if(detail){const r=data[current].find(r=>r.id===Number(detail.dataset.detail));$('detailTitle').textContent=r.name;$('detailBody').innerHTML=configs[current].columns.map(([key,label])=>`<div><div class="muted" style="font-size:11px;margin-bottom:6px">${label}</div>${cell(r,key)}</div>`).join('')+'<div class="notice">此为本地演示记录,不会连接店铺或读取真实账号。</div>';$('details').showModal()}if(e.target.id==='sortName'){sortAsc=!sortAsc;renderTable()}};
|
||||||
|
$('density').onclick=()=>{const compact=$('table').classList.toggle('compact');$('density').textContent=compact?'舒适视图':'紧凑视图';$('density').setAttribute('aria-pressed',compact)};
|
||||||
|
$('columnSettings').onclick=()=>{$('columnOptions').innerHTML=configs[current].columns.map(([key,label])=>`<label><input type="checkbox" value="${key}" ${hiddenColumns.has(key)?'':'checked'} ${key==='name'?'disabled':''}>${label}${key==='name'?'(固定)':''}</label>`).join('');$('columns').showModal()};
|
||||||
|
$('columnOptions').onchange=e=>{e.target.checked?hiddenColumns.delete(e.target.value):hiddenColumns.add(e.target.value);renderTable()};
|
||||||
|
$('add').onclick=()=>openEditor();document.querySelectorAll('[data-close]').forEach(b=>b.onclick=()=>$(b.dataset.close).close());
|
||||||
|
$('editForm').onsubmit=e=>{e.preventDefault();const values=new FormData(e.target),name=String(values.get('name')).trim(),code=String(values.get('code')).trim();if(!name||!code){showToast('名称和编号不能为空');return}if(data[current].some(r=>r.code===code&&r.id!==editingId)){showToast('该编号已存在,请使用其他编号');return}const existing=data[current].find(r=>r.id===editingId);const record={...(existing||{id:Date.now(),status:'正常',expires:'2027-05-09',owner:'demo_owner_1',points:0,balance:'0.00',fee:'2.50'}),name,code,group:values.get('group'),note:values.get('note'),permissions:values.getAll('permission')};for(const key of ['phone','account','company','status'])if(values.has(key))record[key]=values.get(key);if(existing)Object.assign(existing,record);else data[current].unshift(record);$('editor').close();render();showToast(editingId?'已保存修改(演示)':'已添加记录(演示)')};
|
||||||
|
$('batch').onclick=()=>{let count=selected.size;data[current].filter(r=>selected.has(r.id)).forEach(r=>{if(current!=='superstores'){r.status='正常';if(current==='stores')r.expires='2027-05-09'}});selected.clear();render();showToast(current==='superstores'?`已完成 ${count} 家店铺的模拟检测`:`已更新 ${count} 条演示记录`)};
|
||||||
|
$('detect').onclick=()=>{showToast('已模拟检测 '+selected.size+' 家店铺;登录状态已显示在表格中')};
|
||||||
|
$('login').onclick=()=>{data[current].filter(r=>selected.has(r.id)).forEach(r=>r.login='登录成功');renderTable();showToast('已模拟登录 '+selected.size+' 家店铺')};
|
||||||
|
$('refresh').onclick=()=>{render();$('loadStatus').textContent='已刷新 · '+new Date().toLocaleTimeString('zh-CN')+' · 本地演示';showToast('列表已刷新')};
|
||||||
|
$('designNotes').onclick=()=>{$('detailTitle').textContent='为桌面工作流而设计';$('detailBody').innerHTML='<div class="notice">品牌主色 #98638f · 梅紫</div><p>五个页面共享导航、筛选栏、表格和分页布局,降低切换页面的学习成本。</p><p>店铺名称、ID、归属、授权和登录状态分别列示,常用操作直接放在工具栏与固定操作列;编辑使用居中对话框。</p><p>默认紧凑行高 28px,舒适行高 36px;默认每页 50 条。表头与操作列固定,适合长列表与横向浏览。</p><p>后续 WPF 可对应 Grid、DataGrid、ResourceDictionary 和 Dialog。此 HTML 仅演示交互,不包含权限校验、真实登录、支付续期或 API 接入。</p>';$('details').showModal()};
|
||||||
|
switchPage('stores');
|
||||||
|
console.assert(escapeHtml('<script>')==='<script>','HTML escaping');
|
||||||
|
console.assert(filtered().length===72,'Initial store count');
|
||||||
|
query='不存在的店铺';console.assert(filtered().length===0,'Empty search');query='';
|
||||||
|
status='已过期';console.assert(filtered().every(r=>r.status==='已过期'),'Status filter');status='';
|
||||||
|
console.assert(new Set(stores.map(r=>r.id)).size===stores.length,'Unique record IDs');
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
const fs = require('node:fs');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const html = fs.readFileSync(__dirname + '/index.html', 'utf8');
|
||||||
|
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
|
||||||
|
const elements = new Map();
|
||||||
|
function element(id) {
|
||||||
|
if (!elements.has(id)) elements.set(id, { value: id === 'pageSize' ? '50' : '', innerHTML: '', textContent: '', classList: { toggle() { return true; } }, setAttribute() {}, showModal() {}, close() {} });
|
||||||
|
return elements.get(id);
|
||||||
|
}
|
||||||
|
const context = vm.createContext({ document: { getElementById: element, querySelectorAll: () => [] }, console: { assert: assert.ok }, setTimeout: () => 1, clearTimeout() {}, FormData, assert });
|
||||||
|
vm.runInContext(script, context);
|
||||||
|
vm.runInContext(`
|
||||||
|
assert.equal(visibleRows().length, 50);
|
||||||
|
page=2; assert.equal(visibleRows().length, 22);
|
||||||
|
query='乐乐'; assert.equal(filtered().length, 3);
|
||||||
|
query=''; group='服饰鞋包'; assert.equal(filtered().length, 24);
|
||||||
|
group=''; tab='已过期'; assert.ok(filtered().every(r=>r.status==='已过期'));
|
||||||
|
for (const key of Object.keys(configs)) {
|
||||||
|
switchPage(key);
|
||||||
|
assert.ok($('tbody').innerHTML.includes('data-edit'));
|
||||||
|
openEditor(data[key][0].id);
|
||||||
|
assert.ok($('editorFields').innerHTML.includes('name="name"'));
|
||||||
|
hiddenColumns.add('group'); renderTable();
|
||||||
|
assert.ok(!$('thead').innerHTML.includes('所属分组'));
|
||||||
|
}
|
||||||
|
switchPage('stores');
|
||||||
|
assert.equal(configs.stores.columns.length, 11);
|
||||||
|
assert.equal(configs.users.columns.length, 13);
|
||||||
|
assert.ok($('tbody').innerHTML.includes('data-store-action'));
|
||||||
|
selected.add(data.stores[3].id); $('login').onclick();
|
||||||
|
assert.equal(data.stores[3].login, '登录成功');
|
||||||
|
$('batch').onclick();
|
||||||
|
assert.equal(data.stores[3].status, '正常');
|
||||||
|
assert.equal(selected.size, 0);
|
||||||
|
query='no-matching-record'; renderTable();
|
||||||
|
assert.ok($('tbody').innerHTML.includes('没有匹配的记录'));
|
||||||
|
assert.equal($('next').disabled, true);
|
||||||
|
assert.equal(escapeHtml('<img onerror="bad">'), '<img onerror="bad">');
|
||||||
|
`, context);
|
||||||
|
console.log('PASS: script syntax, five page renders, pagination, filters, editors, columns, batch action, empty state and HTML escaping.');
|
||||||
|
|
||||||
|
// Verify contextual navigation against the actual HTML attributes.
|
||||||
|
const markup = html.split("<script>")[0];
|
||||||
|
const ids = [...markup.matchAll(/\bid="([^"]+)"/g)].map(m => m[1]);
|
||||||
|
assert.equal(ids.length, new Set(ids).size);
|
||||||
|
const modules = [...markup.matchAll(/data-module="([^"]+)" data-start="([^"]+)"/g)].map(m => ({ dataset: { module: m[1], start: m[2] }, classList: { toggle() {} }, setAttribute(name, value) { this[name] = value; } }));
|
||||||
|
const pages = [...markup.matchAll(/data-area="([^"]+)" data-page="([^"]+)"/g)].map(m => ({ dataset: { area: m[1], page: m[2] }, classList: { toggle() {} }, setAttribute() {} }));
|
||||||
|
context.document.querySelectorAll = selector => selector === "[data-module]" ? modules : pages;
|
||||||
|
assert.equal(modules.length, 3); assert.equal(pages.length, 5);
|
||||||
|
for (const page of pages) {
|
||||||
|
vm.runInContext("switchPage(" + JSON.stringify(page.dataset.page) + ")", context);
|
||||||
|
assert.equal(page.hidden, false);
|
||||||
|
assert.ok(pages.every(p => p.hidden === (p.dataset.area !== page.dataset.area)));
|
||||||
|
assert.equal(modules.filter(m => m["aria-pressed"]).length, 1);
|
||||||
|
assert.equal(modules.find(m => m["aria-pressed"]).dataset.module, page.dataset.area);
|
||||||
|
}
|
||||||
|
console.log("PASS: three icon modules, five contextual pages, active and hidden navigation states.");
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>29 供应链 · 桌面工作台 Demo 2</title>
|
||||||
|
<style>
|
||||||
|
:root{--brand:#98638f;--brand-dark:#784b70;--tint:#f3ebf2;--ink:#353a44;--muted:#9299a4;--line:#e0e4e9;--canvas:#f4f5f7;--green:#3b876e;--red:#bc626b;--amber:#aa7b35}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{margin:0;min-width:1040px;font:12px/1.5 "Segoe UI","Microsoft YaHei",sans-serif;color:var(--ink);background:var(--canvas)}
|
||||||
|
button,input,select{font:inherit;color:inherit}
|
||||||
|
button{cursor:pointer;white-space:nowrap;height:28px;padding:0 10px;background:white;border:1px solid #d8dde4;border-radius:4px}
|
||||||
|
button:hover:not(:disabled){background:#f2f4f7;border-color:#bcc4ce}
|
||||||
|
button:disabled{color:#abb2bc;cursor:default}
|
||||||
|
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid #98638f;outline-offset:2px}
|
||||||
|
button.primary{background:var(--brand);color:white;border-color:transparent}
|
||||||
|
button.primary:hover:not(:disabled){background:var(--brand-dark);border-color:transparent}
|
||||||
|
input,select{height:28px;padding:0 8px;border:1px solid #d8dde4;border-radius:4px;background:white;min-width:0}
|
||||||
|
input[type=checkbox]{width:13px;height:13px;margin:0;vertical-align:middle;accent-color:var(--brand);cursor:pointer}
|
||||||
|
[hidden]{display:none!important}
|
||||||
|
svg{display:block;width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
|
||||||
|
.sprite{position:absolute;width:0;height:0;overflow:hidden}
|
||||||
|
.app{height:100dvh;min-height:580px;display:grid;grid-template-rows:32px 60px minmax(0,1fr)}
|
||||||
|
.window-titlebar{display:flex;align-items:center;justify-content:space-between;background:#f5f3f6;border-bottom:1px solid #e8e4ea;user-select:none}
|
||||||
|
.window-caption{display:flex;align-items:center;gap:8px;padding-left:12px;font-size:11px;color:#77717c}
|
||||||
|
.window-caption svg{width:16px;height:16px;color:var(--brand)}
|
||||||
|
.window-actions{display:flex;height:32px}
|
||||||
|
.window-actions button{display:grid;place-items:center;width:46px;height:32px;padding:0;border:0;border-radius:0;background:transparent;color:#55525b}
|
||||||
|
.window-actions button svg{width:12px;height:12px;stroke-width:1}
|
||||||
|
.window-actions button:hover{background:#e7e4e9;border:0}
|
||||||
|
.window-actions .window-close:hover{background:#c42b1c;color:#fff}
|
||||||
|
.app-header{display:flex;align-items:stretch;background:#fff;border-bottom:1px solid #e5e3e9}
|
||||||
|
.brand{width:180px;min-width:180px;display:flex;align-items:center;gap:10px;padding:0 18px;background:#faf8fb}
|
||||||
|
.brand-mark{height:34px;width:34px;display:grid;place-items:center;color:var(--brand);flex-shrink:0}
|
||||||
|
.brand-mark svg{width:32px;height:32px;stroke-width:1.35}
|
||||||
|
.brand strong{display:block;font-size:16px;font-weight:650;letter-spacing:.5px;color:#60445c}
|
||||||
|
.brand small{display:none}
|
||||||
|
.modulebar{display:flex;gap:8px;align-items:center;padding:0 16px}
|
||||||
|
.module{display:flex;align-items:center;gap:9px;height:40px;padding:0 16px;border:1px solid transparent;border-radius:6px;background:transparent;color:#788191;font-size:12px}
|
||||||
|
.module svg{width:21px;height:21px}
|
||||||
|
.module:hover:not(:disabled){background:#f4f3f7;border-color:transparent}
|
||||||
|
.module.active{color:var(--brand-dark);background:#eee5ed;font-weight:600}
|
||||||
|
.account{display:flex;align-items:center;gap:15px;margin-left:auto;padding:0 18px;font-size:11px;color:#8a929e}
|
||||||
|
.account b{font-weight:600;color:#746071}
|
||||||
|
.account .avatar{display:grid;place-items:center;width:27px;height:27px;background:#eee8ef;color:#8e6e89;border-radius:50%;font-size:11px}
|
||||||
|
.account button{background:transparent;border:0;color:#8a929e;padding:0 2px;font-size:11px}
|
||||||
|
.desktop-body{display:grid;grid-template-columns:180px minmax(0,1fr);min-height:0}
|
||||||
|
.function-panel{display:flex;flex-direction:column;background:#faf8fb;border-right:1px solid #e7e3e9;padding:16px 10px 12px}
|
||||||
|
.panel-heading{display:flex;justify-content:space-between;align-items:center;padding:0 10px 16px;color:#929aa7;font-size:11px}
|
||||||
|
.panel-heading b{font-weight:500}
|
||||||
|
.panel-heading span{font-size:10px;color:#a49aa9;letter-spacing:1px}
|
||||||
|
.nav{display:flex;align-items:center;gap:10px;text-align:left;width:100%;height:35px;margin-bottom:5px;border:0;background:transparent;border-radius:5px;padding:0 11px;color:#6c7685}
|
||||||
|
.nav svg{width:16px;height:16px}
|
||||||
|
.nav.active{background:#eee5ed;color:var(--brand-dark);font-weight:600}
|
||||||
|
.nav.active:after{content:"";width:5px;height:5px;border-right:1px solid currentColor;border-top:1px solid currentColor;transform:rotate(45deg);margin-left:auto;opacity:.6}
|
||||||
|
.panel-bottom{margin-top:auto;padding:12px 10px 0;border-top:1px solid #e6e9ee;color:#91a095;font-size:10px}
|
||||||
|
.panel-bottom small{display:block;color:#a8afb9;font-size:9px;margin-top:4px}
|
||||||
|
.shell{display:flex;min-width:0;min-height:0}
|
||||||
|
.content{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;padding:0 12px}
|
||||||
|
.page-heading{height:44px;min-height:44px;display:flex;align-items:center;gap:12px;padding:0 1px}
|
||||||
|
h1{font-size:14px;font-weight:600;margin:0}
|
||||||
|
.page-heading p{display:none}
|
||||||
|
.workspace{display:flex;flex-direction:column;flex:1;min-height:0;background:#fff;border:1px solid #dce1e7;border-radius:5px;overflow:hidden}
|
||||||
|
.toolbar{display:flex;align-items:center;gap:9px;min-height:43px;padding:7px 10px;border-bottom:1px solid #e6e9ee}
|
||||||
|
.command-group{display:flex;gap:5px;align-items:center;padding-right:9px;border-right:1px solid #e6e9ee}
|
||||||
|
.command-group:last-child{border:0;margin-left:auto;padding:0}
|
||||||
|
.toolbar button{display:flex;align-items:center;gap:6px;font-size:11px;border-color:transparent;background:transparent;padding:0 8px}
|
||||||
|
.toolbar button.primary{background:var(--brand);color:white;padding:0 10px}
|
||||||
|
.toolbar button:before{content:"";height:15px;width:15px;background:currentColor;mask:var(--icon) center/contain no-repeat}
|
||||||
|
.filters{display:flex;align-items:center;gap:10px;min-height:44px;margin:0;padding:7px 10px;background:#fcfcfd;border-bottom:1px solid #e8ebef;flex-wrap:wrap}
|
||||||
|
.field{display:flex;flex-direction:column;gap:5px}
|
||||||
|
.filters .field{flex-direction:row;align-items:center;gap:7px}
|
||||||
|
.field label{font-size:11px;color:#89929f;white-space:nowrap}
|
||||||
|
.search-field input{width:230px}
|
||||||
|
.filters select{width:105px}
|
||||||
|
.filters button{font-size:11px}
|
||||||
|
.list-header{min-height:35px;height:35px;display:flex;align-items:center;justify-content:space-between;padding:0 11px;gap:8px}
|
||||||
|
.tabs{display:flex;align-items:stretch;height:35px;gap:18px}
|
||||||
|
.tab{height:35px;border:0;padding:0;background:transparent;border-radius:0;color:#9199a5;font-size:11px;position:relative}
|
||||||
|
.tab.active{color:var(--brand-dark);font-weight:600}
|
||||||
|
.tab.active:after{content:"";position:absolute;bottom:0;left:0;right:0;background:var(--brand);height:2px}
|
||||||
|
.tab small{font-size:10px;margin-left:6px;background:#f2f4f6;border-radius:3px;padding:0 4px}
|
||||||
|
.selection-info{display:flex;gap:10px;align-items:center;font-size:10px;white-space:nowrap}
|
||||||
|
.selection-info>span+span{padding-left:10px;border-left:1px solid #e5e8ed}
|
||||||
|
.selection{color:var(--brand-dark)}
|
||||||
|
.muted{color:var(--muted)}
|
||||||
|
.table-scroll{flex:1;min-height:100px;overflow:auto;border-top:1px solid #dce1e7}
|
||||||
|
table{border-collapse:separate;border-spacing:0;width:max-content;min-width:100%;font-size:12px;white-space:nowrap}
|
||||||
|
th{text-align:left;position:sticky;top:0;z-index:2;background:#f1f3f6;font-weight:500;color:#66717f;height:30px;border-right:1px solid #e0e5eb;border-bottom:1px solid #d9dfe6;padding:0 10px}
|
||||||
|
td{height:36px;padding:2px 10px;border-bottom:1px solid #edf0f3;border-right:1px solid #edf0f3;background:#fff}
|
||||||
|
.compact td{height:29px;padding-top:1px;padding-bottom:1px}
|
||||||
|
tbody tr:nth-child(even) td{background:#fcfcfd}
|
||||||
|
tbody tr:hover td{background:#f6f3f7}
|
||||||
|
tbody tr.selected td{background:#f0e6ef}
|
||||||
|
th:first-child,td:first-child{width:31px;min-width:31px;text-align:center;padding:0 8px;position:sticky;left:0;z-index:1}
|
||||||
|
th:first-child{z-index:3}
|
||||||
|
th:last-child,td:last-child{position:sticky;right:0;border-left:1px solid #dfe4ea;box-shadow:-3px 0 5px #00000004}
|
||||||
|
th:last-child{z-index:3}
|
||||||
|
.row-number{text-align:right;color:#9ba4b0;font-size:11px}
|
||||||
|
.entity-mark,.entity small{display:none}
|
||||||
|
.entity-name{font-weight:400}
|
||||||
|
.mono{font:11px Consolas,monospace;color:#838d9c}
|
||||||
|
.date{font-size:11px;color:#778291;font-variant-numeric:tabular-nums}
|
||||||
|
.subline{display:inline;font-size:10px;margin-left:5px}
|
||||||
|
.pill{font-size:10px;color:var(--green);background:#edf6f1;display:inline-flex;gap:5px;align-items:center;padding:1px 5px;border-radius:3px}
|
||||||
|
.pill:before{content:"";width:4px;height:4px;background:currentColor;border-radius:50%}
|
||||||
|
.pill.warn{color:var(--amber);background:#faf3e9}
|
||||||
|
.pill.error{color:var(--red);background:#fbefef}
|
||||||
|
.tag{color:#7e8794;font-size:11px}
|
||||||
|
button.text{background:transparent;border:0;color:#7c6a7b;padding:0 5px;height:24px;font-size:11px}
|
||||||
|
.sort{border:0;background:transparent;padding:0;height:auto;color:inherit;font:inherit}
|
||||||
|
.empty{text-align:center;height:150px!important;color:var(--muted)}
|
||||||
|
.pagination{height:36px;min-height:36px;display:flex;justify-content:space-between;align-items:center;padding:0 10px;border-top:1px solid #dfe4ea;background:#fcfcfd;font-size:10px;color:#959daa}
|
||||||
|
.pagination-controls{display:flex;align-items:center;gap:6px}
|
||||||
|
.pagination button,.pagination select{height:24px;font-size:11px}
|
||||||
|
.current-page{padding:2px 7px;background:var(--tint);color:var(--brand-dark);border-radius:3px}
|
||||||
|
.statusbar{height:23px;min-height:23px;display:flex;align-items:center;justify-content:space-between;font-size:9px;color:#a4abb5;padding:0 1px}
|
||||||
|
dialog{border:1px solid #dce1e7;border-radius:7px;padding:0;color:var(--ink);box-shadow:0 18px 70px #30233330;max-width:90vw;max-height:90vh}
|
||||||
|
dialog::backdrop{background:#20232c45}
|
||||||
|
.drawer{width:620px}
|
||||||
|
.dialog-head{padding:12px 16px;background:#fafbfc;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between}
|
||||||
|
.dialog-head h2{font-size:14px;margin:0}
|
||||||
|
.dialog-head p{font-size:10px;color:var(--muted);margin:3px 0 0}
|
||||||
|
.dialog-body{padding:16px;display:flex;flex-direction:column;gap:13px}
|
||||||
|
.drawer .dialog-body{display:grid;grid-template-columns:1fr 1fr}
|
||||||
|
.dialog-body input:not([type=checkbox]),.dialog-body select{width:100%;height:30px}
|
||||||
|
.dialog-footer{padding:10px 16px;display:flex;justify-content:flex-end;gap:8px;border-top:1px solid var(--line)}
|
||||||
|
.help{grid-column:1/-1;background:var(--canvas);color:var(--muted);padding:10px;font-size:11px}
|
||||||
|
.permissions{display:grid;gap:7px;font-size:11px}
|
||||||
|
.permissions label,.columns-dialog label{display:flex;align-items:center;gap:8px}
|
||||||
|
.columns-dialog{width:330px}
|
||||||
|
.notice{padding:10px;background:var(--tint);color:var(--brand-dark);border-radius:4px}
|
||||||
|
.toast{position:fixed;z-index:10;bottom:35px;left:50%;transform:translateX(-50%);padding:10px 18px;background:#4a3c49;color:white;border-radius:5px;box-shadow:0 5px 20px #0002}
|
||||||
|
@media(max-width:1180px){.account{gap:10px;padding:0 12px}.account .points{display:none}.module{padding:0 13px}.page-heading p{display:none}.content{padding:0 8px}.toolbar{gap:5px}.command-group{gap:3px;padding-right:5px}.toolbar button{padding:0 6px}.search-field input{width:190px}.filters{gap:8px}.selection-info #resultCount{display:none}}
|
||||||
|
#add{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M12%205v14M5%2012h14%22%2F%3E%3C%2Fsvg%3E")}
|
||||||
|
#refresh{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M20%207v5h-5M4%2017v-5h5M5%207a8%208%200%200%201%2014-1l1%206M4%2012l1%206a8%208%200%200%200%2014-1%22%2F%3E%3C%2Fsvg%3E")}
|
||||||
|
#batch{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M8%203h13v14H8zM3%208v13h13M11%207h7M11%2011h7%22%2F%3E%3C%2Fsvg%3E")}
|
||||||
|
#detect{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M4%2012l5%205L20%206%22%2F%3E%3C%2Fsvg%3E")}
|
||||||
|
#login{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M14%203h7v18h-7M3%2012h13M11%207l5%205-5%205%22%2F%3E%3C%2Fsvg%3E")}
|
||||||
|
#density{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%205h18M3%2012h18M3%2019h18%22%2F%3E%3C%2Fsvg%3E")}
|
||||||
|
#columnSettings{--icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%204h18v16H3zM9%204v16M15%204v16%22%2F%3E%3C%2Fsvg%3E")}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<svg class="sprite" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"><defs>
|
||||||
|
<symbol id="i-box" viewBox="0 0 24 24"><path d="m12 2 9 5v10l-9 5-9-5V7zM3 7l9 5 9-5M12 12v10M7.5 4.5l9 5V14"/></symbol>
|
||||||
|
<symbol id="i-shop" viewBox="0 0 24 24"><path d="M3 10v11h18V10M2 10l2-7h16l2 7zM9 21v-7h6v7M7 3v7M17 3v7"/></symbol>
|
||||||
|
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 2l9 4v6c0 5-9 10-9 10S3 17 3 12V6zM8 12l3 3 5-6"/></symbol>
|
||||||
|
<symbol id="i-brand" viewBox="0 0 24 24"><path d="M4 3h10l7 7-11 11-7-7V4zM8 7h.01"/></symbol>
|
||||||
|
<symbol id="i-people" viewBox="0 0 24 24"><path d="M16 21v-3a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v3M9 10a4 4 0 1 0 0-8 4 4 0 0 0 0 8M18 3a4 4 0 0 1 0 8M22 21v-3a4 4 0 0 0-3-4"/></symbol>
|
||||||
|
</defs></svg>
|
||||||
|
<div class="app">
|
||||||
|
<div class="window-titlebar">
|
||||||
|
<div class="window-caption"><svg aria-hidden="true"><use href="#i-box"/></svg><span>29 供应链</span></div>
|
||||||
|
<div class="window-actions" aria-label="窗口按钮外观演示">
|
||||||
|
<button type="button" aria-label="最小化(外观演示)" title="最小化 · 仅外观演示"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 6h10"/></svg></button>
|
||||||
|
<button type="button" aria-label="最大化(外观演示)" title="最大化 · 仅外观演示"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1.5 1.5h9v9h-9z"/></svg></button>
|
||||||
|
<button type="button" class="window-close" aria-label="关闭(外观演示)" title="关闭 · 仅外观演示"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<header class="app-header">
|
||||||
|
<div class="brand"><span class="brand-mark"><svg aria-hidden="true"><use href="#i-box"/></svg></span><div><strong>29 供应链</strong></div></div>
|
||||||
|
<nav class="modulebar" aria-label="业务模块">
|
||||||
|
<button class="module" data-module="operation" data-start="stores"><svg aria-hidden="true"><use href="#i-shop"/></svg>店铺运营</button>
|
||||||
|
<button class="module" data-module="admin" data-start="users"><svg aria-hidden="true"><use href="#i-shield"/></svg>超级管理</button>
|
||||||
|
<button class="module" data-module="brand" data-start="oem"><svg aria-hidden="true"><use href="#i-brand"/></svg>品牌管理</button>
|
||||||
|
</nav>
|
||||||
|
<div class="account"><span class="points">账户积分 <b>9,759</b></span><button id="designNotes">布局说明</button><span class="avatar" aria-hidden="true">管</span><span>管理员</span></div>
|
||||||
|
</header>
|
||||||
|
<div class="desktop-body">
|
||||||
|
<aside class="function-panel" aria-label="模块内功能">
|
||||||
|
<div class="panel-heading"><span>工作区</span><b id="moduleTitle" hidden>店铺运营</b></div>
|
||||||
|
<button class="nav" data-area="operation" data-page="stores"><svg aria-hidden="true"><use href="#i-shop"/></svg><span>店铺管理</span></button>
|
||||||
|
<button class="nav" data-area="operation" data-page="accounts"><svg aria-hidden="true"><use href="#i-people"/></svg><span>子账号管理</span></button>
|
||||||
|
<button class="nav" data-area="admin" data-page="superstores"><svg aria-hidden="true"><use href="#i-shop"/></svg><span>超级店铺</span></button>
|
||||||
|
<button class="nav" data-area="admin" data-page="users"><svg aria-hidden="true"><use href="#i-people"/></svg><span>超级用户</span></button>
|
||||||
|
<button class="nav" data-area="brand" data-page="oem"><svg aria-hidden="true"><use href="#i-brand"/></svg><span>OEM 贴牌</span></button>
|
||||||
|
<div class="panel-bottom">● 本地演示环境<small>数据仅在本次浏览中生效</small></div>
|
||||||
|
</aside>
|
||||||
|
<div class="shell"><main class="content">
|
||||||
|
<section class="page-heading"><h1 id="pageTitle">店铺管理</h1><p id="pageDescription"></p><span id="crumb" hidden></span><span id="eyebrow" hidden></span></section>
|
||||||
|
<section class="workspace" aria-label="管理列表">
|
||||||
|
<div class="toolbar" aria-label="当前页面操作">
|
||||||
|
<div class="command-group" role="group" aria-label="记录操作"><button class="primary" id="add">添加店铺</button><button id="refresh">刷新列表</button></div>
|
||||||
|
<div class="command-group" role="group" aria-label="选中记录操作"><button id="batch" disabled>批量续期</button><button id="detect" disabled>检测选中</button><button id="login" disabled>登录选中</button></div>
|
||||||
|
<div class="command-group" role="group" aria-label="表格视图"><button id="density" aria-pressed="true">舒适视图</button><button id="columnSettings">列设置</button></div>
|
||||||
|
</div>
|
||||||
|
<form class="filters" id="filterForm">
|
||||||
|
<div class="field search-field"><label for="keyword">关键词</label><input id="keyword" maxlength="100" placeholder="搜索店铺名称 / 店铺 ID"></div>
|
||||||
|
<div class="field"><label for="groupFilter">分组</label><select id="groupFilter"></select></div>
|
||||||
|
<div class="field"><label for="statusFilter">状态</label><select id="statusFilter"><option value="">全部状态</option></select></div>
|
||||||
|
<button class="primary" type="submit">查询</button><button type="button" id="reset">重置</button>
|
||||||
|
</form>
|
||||||
|
<div class="list-header"><div class="tabs" id="tabs"></div><div class="selection-info"><span id="selection" class="muted">选择记录后可批量操作</span><span id="resultCount" class="muted"></span></div></div>
|
||||||
|
<div class="table-scroll"><table id="table" class="compact"><thead id="thead"></thead><tbody id="tbody"></tbody></table></div>
|
||||||
|
<footer class="pagination"><span id="range"></span><div class="pagination-controls"><label for="pageSize">每页</label><select id="pageSize"><option>20</option><option selected>50</option><option>100</option></select><button id="prev" aria-label="上一页">上一页</button><span class="current-page" id="pageNumber">1</span><button id="next" aria-label="下一页">下一页</button></div></footer>
|
||||||
|
</section>
|
||||||
|
<footer class="statusbar"><span id="loadStatus">数据已就绪 · 本地演示</span><span>Demo 2 · 桌面工作台</span></footer>
|
||||||
|
</main></div></div></div>
|
||||||
|
<dialog class="drawer" id="editor"><form id="editForm"><header class="dialog-head"><div><h2 id="editorTitle"></h2><p>修改仅在本次演示中生效</p></div><button type="button" class="text" data-close="editor">关闭</button></header><div class="dialog-body" id="editorFields"></div><footer class="dialog-footer"><button type="button" data-close="editor">取消</button><button class="primary" type="submit">保存</button></footer></form></dialog>
|
||||||
|
<dialog class="columns-dialog" id="columns"><header class="dialog-head"><h2>显示的列</h2><button class="text" data-close="columns">完成</button></header><div class="dialog-body" id="columnOptions"></div></dialog>
|
||||||
|
<dialog id="details" style="width:520px;max-width:95vw"><header class="dialog-head"><h2 id="detailTitle"></h2><button class="text" data-close="details">关闭</button></header><div class="dialog-body" id="detailBody"></div></dialog><div class="toast" role="status" id="toast" hidden></div>
|
||||||
|
<script>
|
||||||
|
'use strict';
|
||||||
|
const $=id=>document.getElementById(id);
|
||||||
|
const escapeHtml=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
|
const names=['乐乐生活馆','清麦日用百货','栖木家居旗舰店','佐薇服饰小铺','青禾优选','云朵母婴生活','拾光好物集合店','橙意食品专营店','木子家居日用','浅湾服饰店','山野户外生活','简物生活旗舰店','暖晨家纺店','知味食品小铺','白露日用百货','云间服饰集合店','小满优选','春序家居店','鹿鸣母婴店','青山好物','星野百货','暮色生活馆','沐光服饰','初禾日用品'];
|
||||||
|
const stores=Array.from({length:72},(_,i)=>({name:names[i%names.length]+(i>=24?" · "+(Math.floor(i/24)+1)+"店":""),i})).map(({name,i})=>({id:1001+i,name,code:'wx'+(316129135100+i*74031).toString(16)+'a'+i,group:['精选店铺','服饰鞋包','生活百货'][i%3],account:['运营一组','运营二组','未分配'][i%3],owner:'demo_owner_'+(i%4+1),phone:'138****'+String(1200+i),status:i%7===3?'已过期':i%5===2?'即将到期':'正常',expires:i%7===3?'2026-10-20':i%5===2?'2026-11-02':'2027-05-09',note:i%3===0?'重点运营店铺':'',permissions:['店铺列表','订单管理'],created:'2026-08-14 15:16',login:i%7===3?'未登录':'登录成功',api:i%4===0?'未购买':'已开通',permanent:i%9===0?'是':'否',secondary:i%6===0?'已启用':'未启用'}));
|
||||||
|
const data={stores,superstores:stores.map(r=>({...r,id:r.id+3000})),accounts:['林小夏','陈晓','周宁','许安','李可','宋悦'].map((name,i)=>({id:2001+i,name,code:'operator_'+(i+1),phone:'139****'+(2300+i),group:['运营','客服','仓储'][i%3],status:i===4?'已停用':'正常',account:'主账号 · 演示企业',note:'',permissions:['店铺列表','订单管理']})),users:Array.from({length:18},(_,i)=>({id:3001+i,name:['青禾供应链','云飞商贸','开兴科技','花下海','众店联源','微擎科技'][i%6]+(i>5?' '+(Math.floor(i/6)+1):''),code:'user_'+(801+i),phone:'137****'+(5600+i),group:i%4===0?'代理商':'主账户',status:i===5?'已停用':'正常',company:['青禾商贸有限公司','云飞供应链有限公司','开兴网络科技'][i%3],points:300+i*20,balance:(140+i*37.5).toFixed(2),fee:'2.50',monthly:30,returnFee:'3.00',agent:['云飞','大牛','花下海'][i%3],type:'普通用户',permissions:['商品采集','在线寄件'],note:''})),oem:['桃花源供应链','店速通','开茂科技','枫谷拍单','洋总代理','臻和网络','贝塔一体仓','佳俊商贸'].map((name,i)=>({id:5001+i,name,code:'26'+(701+i)+'TW'+i,group:'品牌合作',status:'正常',account:'demo_brand_'+(i+1),phone:'136****'+(7400+i),note:'',permissions:[]}))};
|
||||||
|
const configs={stores:{title:'店铺管理',en:'STORE MANAGEMENT',desc:'集中管理店铺、账号与授权,让日常运营井然有序。',add:'添加店铺',batch:'批量续期',search:'搜索店铺名称 / 店铺 ID',columns:[['name','店铺信息'],['group','所属分组'],['account','子账号'],['status','授权状态'],['expires','到期时间'],['note','备注']],groups:['精选店铺','服饰鞋包','生活百货']},superstores:{title:'超级店铺管理',en:'STORE ADMINISTRATION',desc:'跨账号查看全部店铺,统一管理店铺归属与授权状态。',add:'添加店铺',batch:'批量检测',search:'搜索店铺 / 所属账号 / 店铺 ID',columns:[['name','店铺信息'],['owner','所属账号'],['group','店铺分组'],['account','子账号'],['status','授权状态'],['expires','到期时间']],groups:['精选店铺','服饰鞋包','生活百货']},accounts:{title:'子账号管理',en:'TEAM & ACCESS',desc:'为团队分配独立账号,以清晰的访问权限协同管理店铺。',add:'添加子账号',batch:'批量启用',search:'搜索昵称 / 登录账号',columns:[['name','用户信息'],['phone','登录手机号'],['group','角色分组'],['status','账号状态'],['permissions','可访问页面'],['account','所属主账号']],groups:['运营','客服','仓储']},users:{title:'超级用户管理',en:'USER ADMINISTRATION',desc:'统一管理用户、功能权限与账户信息。',add:'添加用户',batch:'批量启用',search:'搜索用户 / 手机号 / 公司',columns:[['name','用户信息'],['group','用户分组'],['company','公司'],['points','积分'],['balance','快递余额'],['fee','每单快递费'],['status','账号状态']],groups:['主账户','代理商']},oem:{title:'OEM 贴牌管理',en:'BRAND PARTNERS',desc:'管理合作品牌标识与主体账号,建立统一的品牌工作空间。',add:'添加贴牌',batch:'批量启用',search:'搜索贴牌名称 / 贴牌编码',columns:[['name','贴牌名称'],['code','贴牌编码'],['account','主体账号'],['status','状态'],['assets','品牌素材']],groups:['品牌合作']}};
|
||||||
|
configs.stores.columns=[['name','店铺名称'],['code','店铺 ID'],['created','添加时间'],['expires','到期时间'],['status','授权状态'],['group','分组'],['account','子账号'],['phone','子账号手机号'],['login','登录状态'],['api','API 购买'],['note','备注']];
|
||||||
|
configs.superstores.columns=[['name','店铺名称'],['code','店铺 ID / 登录号码'],['owner','所属账号'],['account','子账号'],['group','店铺分组'],['login','登录状态'],['status','授权状态'],['api','API 购买'],['secondary','二级超管'],['permanent','永久'],['note','备注']];
|
||||||
|
configs.accounts.columns=[['name','用户昵称'],['code','登录账号'],['phone','手机号'],['group','分组'],['account','所属主账号'],['status','状态'],['permissions','可访问页面'],['note','备注']];
|
||||||
|
configs.users.columns=[['name','用户昵称'],['phone','手机 / 登录账号'],['group','分组'],['company','公司'],['type','账户类型'],['permissions','功能权限'],['agent','代理名称'],['points','积分'],['monthly','月费耗点'],['balance','快递余额'],['fee','每单快递费'],['returnFee','每单退货费'],['status','状态']];
|
||||||
|
configs.oem.columns=[['code','贴牌编码'],['name','贴牌名称'],['account','主体账号'],['assets','图标'],['assetsTitle','题图'],['status','状态'],['note','备注']];
|
||||||
|
let current='stores',tab='',page=1,query='',group='',status='',sortAsc=true,editingId=null,selected=new Set(),hiddenColumns=new Set(),toastTimer;
|
||||||
|
function isStore(){return current==='stores'||current==='superstores'}
|
||||||
|
function filtered(){return data[current].filter(r=>(!query||Object.values(r).join(' ').toLowerCase().includes(query))&&(!group||r.group===group)&&(!status||r.status===status)&&(!tab||r.status===tab)).sort((a,b)=>sortAsc?a.name.localeCompare(b.name,'zh-CN'):b.name.localeCompare(a.name,'zh-CN'))}
|
||||||
|
function visibleRows(){const rows=filtered();return rows.slice((page-1)*Number($('pageSize').value),page*Number($('pageSize').value))}
|
||||||
|
function showToast(message){$('toast').textContent=message;$('toast').hidden=false;clearTimeout(toastTimer);toastTimer=setTimeout(()=>$('toast').hidden=true,3200)}
|
||||||
|
function renderTabs(){const tabs=isStore()?[['','全部店铺'],['正常','授权正常'],['即将到期','即将到期'],['已过期','已过期']]:[['','全部'+(current==='oem'?'品牌':'账号')],['正常','正常'],['已停用','已停用']];$('tabs').innerHTML=tabs.map(([value,label])=>`<button class="tab ${tab===value?'active':''}" data-tab="${value}" aria-pressed="${tab===value}">${label}<small>${data[current].filter(r=>!value||r.status===value).length}</small></button>`).join('')}
|
||||||
|
function cell(r,key){const v=escapeHtml(r[key]);switch(key){case'name':return `<div class="entity"><span class="entity-mark ${r.id%3===0?'alt':''}">${escapeHtml(r.name.slice(0,1))}</span><div><div class="entity-name">${v}</div><small>${escapeHtml(r.code)}</small></div></div>`;case'login':return `<span style="color:${r.login==='登录成功'?'var(--green)':'var(--muted)'}">${v}</span>`;case'status':return `<span class="pill ${r.status==='即将到期'?'warn':r.status==='正常'?'':'error'}">${v==='正常'&&isStore()?'授权正常':v}</span>`;case'group':return `<span class="tag">${v}</span>`;case'expires':return `<span class="date">${v}</span>${r.status==='即将到期'?'<div class="subline" style="color:var(--amber)">5 天后到期</div>':''}`;case'permissions':return `<span class="muted">${escapeHtml(r.permissions.join('、'))||'尚未分配'}</span>`;case'assetsTitle':case'assets':return '<span class="muted">暂未上传</span>';case'balance':case'fee':case'returnFee':return `<span class="date">¥ ${v}</span>`;case'code':case'owner':return `<span class="mono">${v}</span>`;case'note':return `<span class="muted">${v||'—'}</span>`;default:return v||'<span class="muted">—</span>'}}
|
||||||
|
function renderTable(){const cfg=configs[current],rows=filtered(),size=Number($('pageSize').value);page=Math.max(1,Math.min(page,Math.ceil(rows.length/size)||1));const visible=visibleRows(),cols=cfg.columns.filter(([key])=>!hiddenColumns.has(key));$('thead').innerHTML=`<tr><th><input type="checkbox" id="selectAll" aria-label="选择当前页全部记录" ${visible.length&&visible.every(r=>selected.has(r.id))?'checked':''}></th><th class="row-number">序号</th>${cols.map(([key,label])=>`<th>${key==='name'?`<button class="sort" id="sortName">${label} ${sortAsc?'↑':'↓'}</button>`:label}</th>`).join('')}<th>操作</th></tr>`;$('tbody').innerHTML=visible.length?visible.map((r,index)=>`<tr class="${selected.has(r.id)?'selected':''}"><td><input type="checkbox" data-select="${r.id}" aria-label="选择${escapeHtml(r.name)}" ${selected.has(r.id)?'checked':''}></td><td class="row-number">${(page-1)*size+index+1}</td>${cols.map(([key])=>`<td>${cell(r,key)}</td>`).join('')}<td>${isStore()?`<button class="text row-action" data-store-action="enter" data-id="${r.id}">进入</button><button class="text row-action" data-store-action="renew" data-id="${r.id}">续期</button>`:""}<button class="text row-action" data-detail="${r.id}">${isStore()?'查看':'详情'}</button><button class="text row-action" data-edit="${r.id}">编辑</button></td></tr>`).join(''):`<tr><td class="empty" colspan="${cols.length+3}">没有匹配的记录,请调整筛选条件或重置。</td></tr>`;const all=$('selectAll');all.indeterminate=visible.some(r=>selected.has(r.id))&&!visible.every(r=>selected.has(r.id));$('selection').textContent=selected.size?`已选择 ${selected.size} 项`:'选择记录后可批量操作';$('selection').className=selected.size?'selection':'muted';$('batch').disabled=!selected.size;$('detect').disabled=$('login').disabled=!selected.size;$('resultCount').textContent=`共 ${rows.length} 条记录`;$('range').textContent=rows.length?`显示 ${(page-1)*size+1}–${Math.min(page*size,rows.length)} 条,共 ${rows.length} 条`:'共 0 条记录';$('pageNumber').textContent=`${page} / ${Math.ceil(rows.length/size)||1}`;$('prev').disabled=page===1;$('next').disabled=page*size>=rows.length}
|
||||||
|
function render(){renderTabs();renderTable()}
|
||||||
|
function switchPage(key){const area=key==='stores'||key==='accounts'?'operation':key==='oem'?'brand':'admin';document.querySelectorAll('[data-module]').forEach(b=>{b.classList.toggle('active',b.dataset.module===area);b.setAttribute('aria-pressed',b.dataset.module===area)});document.querySelectorAll('[data-area]').forEach(b=>b.hidden=b.dataset.area!==area);$('moduleTitle').textContent={operation:'店铺运营',admin:'超级管理',brand:'品牌管理'}[area];current=key;tab='';page=1;query='';group='';status='';selected.clear();hiddenColumns.clear();const cfg=configs[key];$('detect').hidden=$('login').hidden=!isStore();document.querySelectorAll('[data-page]').forEach(b=>{b.classList.toggle('active',b.dataset.page===key);b.setAttribute('aria-current',b.dataset.page===key?'page':'false')});$('crumb').textContent=$('pageTitle').textContent=cfg.title;$('eyebrow').textContent=cfg.en;$('pageDescription').textContent=cfg.desc;$('add').textContent=cfg.add;$('batch').textContent=cfg.batch;$('keyword').value='';$('keyword').placeholder=cfg.search;$('groupFilter').innerHTML='<option value="">全部分组</option>'+cfg.groups.map(g=>`<option>${g}</option>`).join('');$('statusFilter').innerHTML='<option value="">全部状态</option>'+(isStore()?['正常','即将到期','已过期']:['正常','已停用']).map(s=>`<option>${s}</option>`).join('');render()}
|
||||||
|
function field(label,name,value='',required=false,type='text'){return `<div class="field"><label for="edit_${name}">${label}${required?' <span style="color:var(--brand)">*</span>':''}</label><input id="edit_${name}" name="${name}" type="${type}" value="${escapeHtml(value)}" maxlength="100" ${required?'required':''}></div>`}
|
||||||
|
function openEditor(id=null){editingId=id;const r=data[current].find(r=>r.id===id)||{},cfg=configs[current];$('editorTitle').textContent=id?'编辑'+(isStore()?'店铺':current==='oem'?'贴牌':'用户'):cfg.add;let fields=field(isStore()?'店铺名称':current==='oem'?'贴牌名称':'用户昵称','name',r.name,true)+field(isStore()?'店铺 ID':current==='oem'?'贴牌编码':'登录账号','code',r.code,true);if(current==='accounts'||current==='users')fields+=field('手机号','phone',r.phone,true)+field(id?'新密码(留空则不修改)':'密码','password','',!id,'password');fields+=`<div class="field"><label for="edit_group">所属分组</label><select name="group" id="edit_group">${cfg.groups.map(g=>`<option ${r.group===g?'selected':''}>${g}</option>`).join('')}</select></div>`;if(isStore()||current==='oem')fields+=field(current==='oem'?'主体账号':'子账号','account',r.account,current==='oem');if(current==='users')fields+=field('公司','company',r.company);if(!isStore())fields+=`<div class="field"><label for="edit_status">账号状态</label><select name="status" id="edit_status"><option ${r.status!=='已停用'?'selected':''}>正常</option><option ${r.status==='已停用'?'selected':''}>已停用</option></select></div>`;if(current==='accounts'||current==='users')fields+=`<div class="field"><label>可访问页面</label><div class="permissions">${['店铺列表','订单管理','商品采集','在线寄件','评分考核','税务申报'].map(p=>`<label><input type="checkbox" name="permission" value="${p}" ${(r.permissions||[]).includes(p)?'checked':''}>${p}</label>`).join('')}</div></div>`;fields+=field('备注','note',r.note);if(isStore()&&!id)fields+='<div class="help">此处演示手动添加流程。正式系统可在此接入扫码授权;新记录默认使用演示授权。</div>';$('editorFields').innerHTML=fields;$('editor').showModal()}
|
||||||
|
document.querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>switchPage(b.dataset.page));
|
||||||
|
document.querySelectorAll('[data-module]').forEach(b=>b.onclick=()=>switchPage(b.dataset.start));
|
||||||
|
$('filterForm').onsubmit=e=>{e.preventDefault();query=$('keyword').value.trim().toLowerCase();group=$('groupFilter').value;status=$('statusFilter').value;page=1;selected.clear();renderTable()};
|
||||||
|
$('reset').onclick=()=>{query=group=status=tab='';page=1;selected.clear();$('keyword').value=$('groupFilter').value=$('statusFilter').value='';render()};
|
||||||
|
$('tabs').onclick=e=>{const b=e.target.closest('[data-tab]');if(b){tab=b.dataset.tab;page=1;selected.clear();renderTabs();renderTable()}};
|
||||||
|
$('prev').onclick=()=>{page--;renderTable()};$('next').onclick=()=>{page++;renderTable()};$('pageSize').onchange=()=>{page=1;renderTable()};
|
||||||
|
$('table').onchange=e=>{if(e.target.id==='selectAll')visibleRows().forEach(r=>e.target.checked?selected.add(r.id):selected.delete(r.id));else if(e.target.dataset.select){const id=Number(e.target.dataset.select);e.target.checked?selected.add(id):selected.delete(id)}renderTable()};
|
||||||
|
$('table').onclick=e=>{const action=e.target.closest('[data-store-action]');if(action){const r=data[current].find(r=>r.id===Number(action.dataset.id));if(action.dataset.storeAction==='renew'){r.status='正常';r.expires='2027-05-09';render();showToast('已模拟续期:'+r.name)}else{showToast('模拟进入店铺:'+r.name+'(未连接真实店铺)')}return}const edit=e.target.closest('[data-edit]'),detail=e.target.closest('[data-detail]');if(edit)openEditor(Number(edit.dataset.edit));if(detail){const r=data[current].find(r=>r.id===Number(detail.dataset.detail));$('detailTitle').textContent=r.name;$('detailBody').innerHTML=configs[current].columns.map(([key,label])=>`<div><div class="muted" style="font-size:11px;margin-bottom:6px">${label}</div>${cell(r,key)}</div>`).join('')+'<div class="notice">此为本地演示记录,不会连接店铺或读取真实账号。</div>';$('details').showModal()}if(e.target.id==='sortName'){sortAsc=!sortAsc;renderTable()}};
|
||||||
|
$('density').onclick=()=>{const compact=$('table').classList.toggle('compact');$('density').textContent=compact?'舒适视图':'紧凑视图';$('density').setAttribute('aria-pressed',compact)};
|
||||||
|
$('columnSettings').onclick=()=>{$('columnOptions').innerHTML=configs[current].columns.map(([key,label])=>`<label><input type="checkbox" value="${key}" ${hiddenColumns.has(key)?'':'checked'} ${key==='name'?'disabled':''}>${label}${key==='name'?'(固定)':''}</label>`).join('');$('columns').showModal()};
|
||||||
|
$('columnOptions').onchange=e=>{e.target.checked?hiddenColumns.delete(e.target.value):hiddenColumns.add(e.target.value);renderTable()};
|
||||||
|
$('add').onclick=()=>openEditor();document.querySelectorAll('[data-close]').forEach(b=>b.onclick=()=>$(b.dataset.close).close());
|
||||||
|
$('editForm').onsubmit=e=>{e.preventDefault();const values=new FormData(e.target),name=String(values.get('name')).trim(),code=String(values.get('code')).trim();if(!name||!code){showToast('名称和编号不能为空');return}if(data[current].some(r=>r.code===code&&r.id!==editingId)){showToast('该编号已存在,请使用其他编号');return}const existing=data[current].find(r=>r.id===editingId);const record={...(existing||{id:Date.now(),status:'正常',expires:'2027-05-09',owner:'demo_owner_1',points:0,balance:'0.00',fee:'2.50'}),name,code,group:values.get('group'),note:values.get('note'),permissions:values.getAll('permission')};for(const key of ['phone','account','company','status'])if(values.has(key))record[key]=values.get(key);if(existing)Object.assign(existing,record);else data[current].unshift(record);$('editor').close();render();showToast(editingId?'已保存修改(演示)':'已添加记录(演示)')};
|
||||||
|
$('batch').onclick=()=>{let count=selected.size;data[current].filter(r=>selected.has(r.id)).forEach(r=>{if(current!=='superstores'){r.status='正常';if(current==='stores')r.expires='2027-05-09'}});selected.clear();render();showToast(current==='superstores'?`已完成 ${count} 家店铺的模拟检测`:`已更新 ${count} 条演示记录`)};
|
||||||
|
$('detect').onclick=()=>{showToast('已模拟检测 '+selected.size+' 家店铺;登录状态已显示在表格中')};
|
||||||
|
$('login').onclick=()=>{data[current].filter(r=>selected.has(r.id)).forEach(r=>r.login='登录成功');renderTable();showToast('已模拟登录 '+selected.size+' 家店铺')};
|
||||||
|
$('refresh').onclick=()=>{render();$('loadStatus').textContent='已刷新 · '+new Date().toLocaleTimeString('zh-CN')+' · 本地演示';showToast('列表已刷新')};
|
||||||
|
$('designNotes').onclick=()=>{$('detailTitle').textContent='为桌面工作流而设计';$('detailBody').innerHTML='<div class="notice">品牌主色 #98638f · 梅紫</div><p>顶部以统一线性图标区分店铺运营、超级管理与品牌管理;左侧仅展示当前业务域内的功能。</p><p>工具栏按记录、选中记录、视图分组。新增和刷新位于左侧,批量操作居中,列设置与行密度位于右侧。筛选和状态切换贴近表格,选择数量在列表右上角显示。</p><p>默认紧凑行高 29px,舒适行高 36px;默认每页 50 条。表头与操作列固定,适合长列表与横向浏览。</p><p>后续 WPF 可使用 DockPanel / Grid 组织顶部模块栏、内容区与底部状态栏,业务页面复用 DataGridEx。此 HTML 仅演示交互,不包含权限校验、真实登录、支付续期或 API 接入。</p>';$('details').showModal()};
|
||||||
|
switchPage('stores');
|
||||||
|
console.assert(escapeHtml('<script>')==='<script>','HTML escaping');
|
||||||
|
console.assert(filtered().length===72,'Initial store count');
|
||||||
|
query='不存在的店铺';console.assert(filtered().length===0,'Empty search');query='';
|
||||||
|
status='已过期';console.assert(filtered().every(r=>r.status==='已过期'),'Status filter');status='';
|
||||||
|
console.assert(new Set(stores.map(r=>r.id)).size===stores.length,'Unique record IDs');
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using System.Windows.Markup;
|
||||||
|
|
||||||
|
[assembly: XmlnsDefinition("MAX.Framework", "MAX.Framework")]
|
||||||
|
[assembly: XmlnsDefinition("MAX.Framework", "MAX.Framework.Extensions")]
|
||||||
|
[assembly: XmlnsDefinition("MAX.Framework", "MAX.Framework.Controls")]
|
||||||
|
[assembly: XmlnsDefinition("MAX.Framework", "MAX.Framework.Controls.Attach")]
|
||||||
|
|
||||||
|
[assembly: XmlnsPrefix("MAX.Framework", "mf")]
|
||||||
@@ -16,4 +16,8 @@
|
|||||||
<ProjectReference Include="..\MAX.Core\MAX.Core.csproj" />
|
<ProjectReference Include="..\MAX.Core\MAX.Core.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="Controls\Attach\" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -100,8 +100,7 @@ namespace Prism.Commands
|
|||||||
return;
|
return;
|
||||||
|
|
||||||
IsExecuting = true;
|
IsExecuting = true;
|
||||||
await _executeMethod(token)
|
await _executeMethod(token);
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ namespace Store.Management.Api;
|
|||||||
public sealed class ApiClientOptions
|
public sealed class ApiClientOptions
|
||||||
{
|
{
|
||||||
public required Uri BaseUrl { get; init; }
|
public required Uri BaseUrl { get; init; }
|
||||||
public string Version { get; init; } = "v1";
|
|
||||||
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
|
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
internal void Validate()
|
internal void Validate()
|
||||||
@@ -12,8 +11,6 @@ public sealed class ApiClientOptions
|
|||||||
(BaseUrl.Scheme != "https" && BaseUrl.Scheme != "http") ||
|
(BaseUrl.Scheme != "https" && BaseUrl.Scheme != "http") ||
|
||||||
!string.IsNullOrEmpty(BaseUrl.UserInfo) || !string.IsNullOrEmpty(BaseUrl.Query) || !string.IsNullOrEmpty(BaseUrl.Fragment))
|
!string.IsNullOrEmpty(BaseUrl.UserInfo) || !string.IsNullOrEmpty(BaseUrl.Query) || !string.IsNullOrEmpty(BaseUrl.Fragment))
|
||||||
throw new ArgumentException("BaseUrl 必须是无凭据、查询参数和片段的 HTTP(S) 绝对地址。");
|
throw new ArgumentException("BaseUrl 必须是无凭据、查询参数和片段的 HTTP(S) 绝对地址。");
|
||||||
if (!System.Text.RegularExpressions.Regex.IsMatch(Version, @"^v\d+(\.\d+)?$"))
|
|
||||||
throw new ArgumentException("Version 格式应为 v1 或 v1.0。");
|
|
||||||
if (Timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Timeout));
|
if (Timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Timeout));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using Store.Management.Models;
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using RestSharp;
|
using RestSharp;
|
||||||
using Store.Management.Api.Transport;
|
using Store.Management.Api.Transport;
|
||||||
@@ -7,28 +8,13 @@ namespace Store.Management.Api.Authentication;
|
|||||||
public sealed class LoginRequest
|
public sealed class LoginRequest
|
||||||
{
|
{
|
||||||
[Required] public string UserName { get; set; } = "";
|
[Required] public string UserName { get; set; } = "";
|
||||||
|
/// <summary>服务端要求的 UTF-8 密码的 32 位大写 MD5,由调用方计算。</summary>
|
||||||
[Required] public string Password { get; set; } = "";
|
[Required] public string Password { get; set; } = "";
|
||||||
[StringLength(100)] public string? DeviceId { get; set; }
|
[StringLength(100)] public string? DeviceId { get; set; }
|
||||||
[StringLength(100)] public string? DeviceName { get; set; }
|
[StringLength(100)] public string? DeviceName { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class LoginResult
|
public sealed class AuthApi(ApiTransport transport, TokenSession session)
|
||||||
{
|
|
||||||
public string TokenType { get; init; } = "Bearer";
|
|
||||||
public string Token { get; init; } = "";
|
|
||||||
public uint ExpiresInMinutes { get; init; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed record CurrentUser(string UserName, string? NickName);
|
|
||||||
|
|
||||||
public interface IAuthApi
|
|
||||||
{
|
|
||||||
Task<LoginResult> LoginAsync(LoginRequest request, CancellationToken cancellationToken = default);
|
|
||||||
Task LogoutAsync(CancellationToken cancellationToken = default);
|
|
||||||
Task<CurrentUser> MeAsync(CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed class AuthApi(ApiTransport transport, TokenSession session) : IAuthApi
|
|
||||||
{
|
{
|
||||||
// 登录和退出串行执行,避免迟到的登录响应覆盖退出操作。
|
// 登录和退出串行执行,避免迟到的登录响应覆盖退出操作。
|
||||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||||
@@ -39,27 +25,38 @@ internal sealed class AuthApi(ApiTransport transport, TokenSession session) : IA
|
|||||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var result = await transport.GetRequiredAsync<LoginResult>("Auth/Login", Method.Post, request,
|
LoginResult result = await transport.GetRequiredAsync<LoginResult>("Auth/Login", Method.Post, request,
|
||||||
authenticated: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
authenticated: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||||
if (string.IsNullOrWhiteSpace(result.Token) || result.Token.Contains('\r') || result.Token.Contains('\n') ||
|
if (string.IsNullOrWhiteSpace(result.Token) || result.Token.Contains('\r') || result.Token.Contains('\n') ||
|
||||||
!string.Equals(result.TokenType, "Bearer", StringComparison.OrdinalIgnoreCase))
|
!string.Equals(result.TokenType, "Bearer", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
throw new ApiException(ApiErrorKind.InvalidResponse, "登录响应缺少有效的 Bearer Token。");
|
throw new ApiException(ApiErrorKind.InvalidResponse, "登录响应缺少有效的 Bearer Token。");
|
||||||
|
}
|
||||||
session.Set(result.Token);
|
session.Set(result.Token);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
finally { _gate.Release(); }
|
finally
|
||||||
|
{
|
||||||
|
_gate.Release();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task LogoutAsync(CancellationToken cancellationToken = default)
|
public async Task LogoutAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||||
var token = session.Token;
|
string? token = session.Token;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (token is not null)
|
if (token is not null)
|
||||||
|
{
|
||||||
await transport.SendAsync<object>("Auth/Logout", Method.Post, cancellationToken: cancellationToken).ConfigureAwait(false);
|
await transport.SendAsync<object>("Auth/Logout", Method.Post, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
session.ClearIfCurrent(token);
|
||||||
|
_gate.Release();
|
||||||
}
|
}
|
||||||
finally { session.ClearIfCurrent(token); _gate.Release(); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<CurrentUser> MeAsync(CancellationToken cancellationToken = default)
|
public Task<CurrentUser> MeAsync(CancellationToken cancellationToken = default)
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ public sealed class ApiResult<T>
|
|||||||
public string? TraceId { get; init; }
|
public string? TraceId { get; init; }
|
||||||
public T? Data { get; init; }
|
public T? Data { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed record PageResult<T>(long Total, IReadOnlyList<T> Items);
|
public sealed record PageResult<T>(long Total, IReadOnlyList<T> Items);
|
||||||
|
|
||||||
public class PageRequest
|
public class PageRequest
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Store Management API 客户端
|
# Store Management API 客户端
|
||||||
|
|
||||||
独立的 net10.0 类库,使用 RestSharp 112.1.0 连接 StoreWeb。WPF 项目已引用该类库。每个服务地址及用户会话创建一个 StoreApiClient,建议在应用容器注册为单例,退出应用时释放。
|
独立的 API 类库(当前继承仓库的 net8.0-windows 目标框架),使用 RestSharp 112.1.0 连接 StoreWeb。WPF 项目已引用该类库。每个服务地址及用户会话创建一个 StoreApiClient,建议在应用容器注册为单例,退出应用时释放。
|
||||||
|
|
||||||
## 调用
|
## 调用
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ try
|
|||||||
await api.Auth.LoginAsync(new LoginRequest
|
await api.Auth.LoginAsync(new LoginRequest
|
||||||
{
|
{
|
||||||
UserName = userName,
|
UserName = userName,
|
||||||
Password = password,
|
Password = passwordMd5, // UTF-8 密码的 32 位大写 MD5,保留原密码首尾空格
|
||||||
DeviceId = deviceId, // 可选;稳定设备标识由宿主应用管理
|
DeviceId = deviceId, // 可选;稳定设备标识由宿主应用管理
|
||||||
DeviceName = Environment.MachineName
|
DeviceName = Environment.MachineName
|
||||||
});
|
});
|
||||||
@@ -44,7 +44,7 @@ catch (ApiException ex)
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
示例中的账号、密码、设备标识来自调用方输入。异步方法均支持 CancellationToken;主动取消抛出 OperationCanceledException,本地输入校验抛出 ValidationException。
|
示例中的账号、密码摘要、设备标识由调用方提供;登录窗口已负责计算密码摘要,API 层不重复计算。异步方法均支持 CancellationToken;主动取消抛出 OperationCanceledException,本地输入校验抛出 ValidationException。
|
||||||
|
|
||||||
## 文件与职责
|
## 文件与职责
|
||||||
|
|
||||||
@@ -58,13 +58,13 @@ catch (ApiException ex)
|
|||||||
|
|
||||||
## 协议与扩展
|
## 协议与扩展
|
||||||
|
|
||||||
对齐 StoreWeb 的 AuthController、TokenResult、UnifyResultFilter 和用户管理控制器。成功码为 200;HTTP 200 内的业务失败同样抛出 ApiException。登录读取 data.token,认证采用 Bearer opaque Token,不解析 JWT,不根据首次登录的有效期自行判定续期。HTTP 或业务 401 清除当前请求所用的会话;旧请求的 401 不清除新 Token。
|
对齐 StoreWeb 的 AuthController、TokenResult、UnifyResultFilter 和用户管理控制器。成功码为 200;HTTP 200 内的业务失败同样抛出 ApiException。先读取响应状态与业务码,再解析成功 data,避免错误响应的数据结构掩盖业务错误。登录读取 data.token,认证采用 Bearer opaque Token,不解析 JWT,不根据首次登录的有效期自行判定续期。HTTP 或业务 401 清除当前请求所用的会话;旧请求的 401 不清除新 Token。
|
||||||
|
|
||||||
后续商品模块按 Users 的方式新增独立 DTO、接口和实现,由 StoreApiClient 暴露模块入口。模块通过 Transport.GetRequiredAsync<T> 发送有数据请求,通过 SendAsync<object> 发送无数据操作。路由采用 user/GetAllUser 这样的相对路径,传输层自动添加版本。简单参数使用 query,复杂参数使用 body,HTTP 方法与服务端契约一致。避免按常规 REST 习惯猜测当前服务端的动作路由。
|
后续商品模块按 Users 的方式新增独立 DTO、接口和实现,由 StoreApiClient 暴露模块入口。模块通过 Transport.GetRequiredAsync<T> 发送有数据请求,通过 SendAsync<object> 发送无数据操作。路由采用 user/GetAllUser 这样的相对路径,传输层自动添加版本。简单参数使用 query,复杂参数使用 body,HTTP 方法与服务端契约一致。避免按常规 REST 习惯猜测当前服务端的动作路由。
|
||||||
|
|
||||||
请求不自动重试,避免添加、修改操作重复执行。禁止自动重定向;服务地址应直接指向最终 API 地址。退出时即使服务端请求失败也清理本地 Token,并将错误交给宿主;此时服务端会话可能仍有效。Session.Clear 可用于本地退出,不撤销服务器会话。
|
请求不自动重试,避免添加、修改操作重复执行。禁止自动重定向;服务地址应直接指向最终 API 地址。退出时即使服务端请求失败也清理本地 Token,并将错误交给宿主;此时服务端会话可能仍有效。Session.Clear 可用于本地退出,不撤销服务器会话。
|
||||||
|
|
||||||
当前不包含登录界面、Token 磁盘持久化、自动刷新或商品接口。实际地址由宿主提供,尚未进行真实服务联调。
|
登录界面由宿主项目提供;API 层不包含 Token 磁盘持久化、自动刷新或商品接口。实际地址由宿主提供,尚未进行真实服务联调。
|
||||||
|
|
||||||
## 验证
|
## 验证
|
||||||
|
|
||||||
@@ -75,4 +75,4 @@ dotnet build Store.Management.slnx
|
|||||||
dotnet run --project Tests/Store.Management.Api.SmokeTests/Store.Management.Api.SmokeTests.csproj
|
dotnet run --project Tests/Store.Management.Api.SmokeTests/Store.Management.Api.SmokeTests.csproj
|
||||||
```
|
```
|
||||||
|
|
||||||
模拟 HTTP 测试覆盖登录路由、Bearer、分页序列化与解析、输入边界、业务错误、无效 JSON、403、HTTP 与业务 401、退出及主动取消,不会调用真实服务。
|
模拟 HTTP 测试覆盖登录路由、Bearer、分页序列化与解析、输入边界、业务错误、无效 JSON、403、HTTP 与业务 401、无效 Token/data、旧请求 401 会话隔离、登录退出串行、退出失败清理及主动取消,不会调用真实服务。
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using RestSharp;
|
||||||
|
using Store.Management.Api.Models;
|
||||||
|
using Store.Management.Api.Transport;
|
||||||
|
using Store.Management.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.Api.Shops;
|
||||||
|
|
||||||
|
public sealed class ShopApi(ApiTransport transport)
|
||||||
|
{
|
||||||
|
/// <summary>按店铺 ID 获取 Cookie,仅在用户请求时读取。</summary>
|
||||||
|
public Task<IReadOnlyList<ShopCookieInfo>> GetCookiesAsync(string shopId, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(shopId);
|
||||||
|
return transport.GetRequiredAsync<IReadOnlyList<ShopCookieInfo>>("shop/GetShopCookies", Method.Post,
|
||||||
|
new { ShopIds = new[] { shopId } }, cancellationToken: cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>管理员分页查询商铺,筛选条件由服务端处理。</summary>
|
||||||
|
public Task<PageResult<ShopInfo>> SearchAsync(ShopQueryRequest request, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
return transport.GetRequiredAsync<PageResult<ShopInfo>>("shop/GetAllShops", Method.Post,
|
||||||
|
request, cancellationToken: cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
using Store.Management.Api.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.Api.Shops;
|
||||||
|
|
||||||
|
public sealed class ShopQueryRequest : PageRequest
|
||||||
|
{
|
||||||
|
public string? SearchUserName { get; init; }
|
||||||
|
public string? SearchId { get; init; }
|
||||||
|
public string? SearchName { get; init; }
|
||||||
|
public string? SearchNotes { get; init; }
|
||||||
|
}
|
||||||
@@ -4,4 +4,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="RestSharp" Version="112.1.0" />
|
<PackageReference Include="RestSharp" Version="112.1.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Store.Management.Models\Store.Management.Models.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -7,23 +7,28 @@ namespace Store.Management.Api;
|
|||||||
/// <summary>一个服务地址与一个用户会话对应一个实例;在应用容器中注册为单例。</summary>
|
/// <summary>一个服务地址与一个用户会话对应一个实例;在应用容器中注册为单例。</summary>
|
||||||
public sealed class StoreApiClient : IDisposable
|
public sealed class StoreApiClient : IDisposable
|
||||||
{
|
{
|
||||||
public TokenSession Session { get; } = new();
|
public TokenSession Session { get; } = new();
|
||||||
public ApiTransport Transport { get; }
|
public ApiTransport Transport { get; }
|
||||||
public IAuthApi Auth { get; }
|
public AuthApi Auth { get; }
|
||||||
public IUserApi Users { get; }
|
public UserApi Users { get; }
|
||||||
|
public Shops.ShopApi Shops { get; }
|
||||||
|
|
||||||
/// <param name="httpClient">可选的外部 HTTP 客户端,由调用方管理其生命周期。</param>
|
/// <param name="httpClient">可选的外部 HTTP 客户端,由调用方管理其生命周期。</param>
|
||||||
public StoreApiClient(ApiClientOptions options, HttpClient? httpClient = null)
|
public StoreApiClient(ApiClientOptions options, HttpClient? httpClient = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(options);
|
ArgumentNullException.ThrowIfNull(options);
|
||||||
Transport = new ApiTransport(options, Session, httpClient);
|
#if DEBUG
|
||||||
Auth = new AuthApi(Transport, Session);
|
Session.Set("store-local-dev-7f2c9e4a6b814d38a5910e62c4f837bd");
|
||||||
Users = new UserApi(Transport);
|
#endif
|
||||||
}
|
Transport = new ApiTransport(options, Session, httpClient);
|
||||||
|
Auth = new AuthApi(Transport, Session);
|
||||||
|
Users = new UserApi(Transport);
|
||||||
|
Shops = new Shops.ShopApi(Transport);
|
||||||
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
Session.Clear();
|
Session.Clear();
|
||||||
Transport.Dispose();
|
Transport.Dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,15 +12,13 @@ public sealed class ApiTransport : IDisposable
|
|||||||
{
|
{
|
||||||
private readonly RestClient _client;
|
private readonly RestClient _client;
|
||||||
private readonly TokenSession _session;
|
private readonly TokenSession _session;
|
||||||
private readonly string _version;
|
|
||||||
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
|
||||||
|
|
||||||
internal ApiTransport(ApiClientOptions options, TokenSession session, HttpClient? httpClient)
|
internal ApiTransport(ApiClientOptions options, TokenSession session, HttpClient? httpClient)
|
||||||
{
|
{
|
||||||
options.Validate();
|
options.Validate();
|
||||||
_session = session;
|
_session = session;
|
||||||
_version = options.Version;
|
RestClientOptions settings = new RestClientOptions(new Uri(options.BaseUrl.AbsoluteUri.TrimEnd('/') + "/"))
|
||||||
var settings = new RestClientOptions(new Uri(options.BaseUrl.AbsoluteUri.TrimEnd('/') + "/"))
|
|
||||||
{
|
{
|
||||||
Timeout = options.Timeout,
|
Timeout = options.Timeout,
|
||||||
FollowRedirects = false
|
FollowRedirects = false
|
||||||
@@ -32,30 +30,62 @@ public sealed class ApiTransport : IDisposable
|
|||||||
IReadOnlyDictionary<string, string?>? query = null, bool authenticated = true,
|
IReadOnlyDictionary<string, string?>? query = null, bool authenticated = true,
|
||||||
CancellationToken cancellationToken = default)
|
CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
if (string.IsNullOrWhiteSpace(route) || route.StartsWith('/') || route.Contains("..") ||
|
if (string.IsNullOrWhiteSpace(route) || route.StartsWith('/') || route.Contains("..") ||
|
||||||
route.Contains(':') || route.Contains('?') || route.Contains('#') || route.Contains('\\'))
|
route.Contains(':') || route.Contains('?') || route.Contains('#') || route.Contains('\\'))
|
||||||
|
{
|
||||||
throw new ArgumentException("接口必须使用相对路由,例如 user/GetAllUser。", nameof(route));
|
throw new ArgumentException("接口必须使用相对路由,例如 user/GetAllUser。", nameof(route));
|
||||||
if (body is not null) Validator.ValidateObject(body, new ValidationContext(body), true);
|
}
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
if (body is not null)
|
||||||
var token = authenticated ? _session.Token : null;
|
{
|
||||||
if (authenticated && token is null) throw new ApiException(ApiErrorKind.Unauthorized, "请先登录。", code: 401);
|
Validator.ValidateObject(body, new ValidationContext(body), true);
|
||||||
var request = new RestRequest($"{_version}/{route}", method);
|
}
|
||||||
if (token is not null) request.AddHeader("Authorization", $"Bearer {token}");
|
string? token = authenticated ? _session.Token : null;
|
||||||
if (body is not null) request.AddJsonBody(body);
|
if (authenticated && token is null)
|
||||||
|
{
|
||||||
|
throw new ApiException(ApiErrorKind.Unauthorized, "请先登录。", code: 401);
|
||||||
|
}
|
||||||
|
RestRequest request = new RestRequest($"/{route}", method);
|
||||||
|
if (token is not null)
|
||||||
|
{
|
||||||
|
request.AddHeader("Authorization", $"Bearer {token}");
|
||||||
|
}
|
||||||
|
if (body is not null)
|
||||||
|
{
|
||||||
|
request.AddJsonBody(body);
|
||||||
|
}
|
||||||
if (query is not null)
|
if (query is not null)
|
||||||
foreach (var pair in query)
|
{
|
||||||
if (pair.Value is not null) request.AddQueryParameter(pair.Key, pair.Value);
|
foreach (KeyValuePair<string, string?> pair in query)
|
||||||
var response = await _client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false);
|
{
|
||||||
|
if (pair.Value is not null)
|
||||||
|
{
|
||||||
|
request.AddQueryParameter(pair.Key, pair.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RestResponse response = await _client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false);
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
if (response.ResponseStatus == ResponseStatus.TimedOut)
|
if (response.ResponseStatus == ResponseStatus.TimedOut)
|
||||||
|
{
|
||||||
throw new ApiException(ApiErrorKind.Timeout, "请求超时,请稍后重试。", innerException: response.ErrorException);
|
throw new ApiException(ApiErrorKind.Timeout, "请求超时,请稍后重试。", innerException: response.ErrorException);
|
||||||
|
}
|
||||||
if ((int)response.StatusCode == 0)
|
if ((int)response.StatusCode == 0)
|
||||||
|
{
|
||||||
throw new ApiException(ApiErrorKind.Network, "无法连接服务器,请检查网络与服务地址。", innerException: response.ErrorException);
|
throw new ApiException(ApiErrorKind.Network, "无法连接服务器,请检查网络与服务地址。", innerException: response.ErrorException);
|
||||||
|
}
|
||||||
|
|
||||||
ApiResult<T>? result = null;
|
// 先判断状态,再解析 data;错误响应的数据结构可能与成功响应不同。
|
||||||
|
ApiResult<JsonElement>? result = null;
|
||||||
JsonException? parseError = null;
|
JsonException? parseError = null;
|
||||||
try { result = JsonSerializer.Deserialize<ApiResult<T>>(response.Content ?? "", Json); }
|
try
|
||||||
catch (JsonException ex) { parseError = ex; }
|
{
|
||||||
|
result = JsonSerializer.Deserialize<ApiResult<JsonElement>>(response.Content ?? "", Json);
|
||||||
|
}
|
||||||
|
catch (JsonException ex)
|
||||||
|
{
|
||||||
|
parseError = ex;
|
||||||
|
}
|
||||||
if (response.StatusCode == HttpStatusCode.Unauthorized || result?.Code == 401)
|
if (response.StatusCode == HttpStatusCode.Unauthorized || result?.Code == 401)
|
||||||
{
|
{
|
||||||
_session.ClearIfCurrent(token);
|
_session.ClearIfCurrent(token);
|
||||||
@@ -63,13 +93,31 @@ public sealed class ApiTransport : IDisposable
|
|||||||
response.StatusCode, 401, result?.TraceId);
|
response.StatusCode, 401, result?.TraceId);
|
||||||
}
|
}
|
||||||
if (!response.IsSuccessful)
|
if (!response.IsSuccessful)
|
||||||
|
{
|
||||||
throw new ApiException(ApiErrorKind.Http, result?.Msg ?? $"服务器请求失败({(int)response.StatusCode})。",
|
throw new ApiException(ApiErrorKind.Http, result?.Msg ?? $"服务器请求失败({(int)response.StatusCode})。",
|
||||||
response.StatusCode, result?.Code, result?.TraceId);
|
response.StatusCode, result?.Code, result?.TraceId);
|
||||||
|
}
|
||||||
if (result is null)
|
if (result is null)
|
||||||
|
{
|
||||||
throw new ApiException(ApiErrorKind.InvalidResponse, "服务器响应格式无效。", response.StatusCode, innerException: parseError);
|
throw new ApiException(ApiErrorKind.InvalidResponse, "服务器响应格式无效。", response.StatusCode, innerException: parseError);
|
||||||
|
}
|
||||||
if (result.Code != 200)
|
if (result.Code != 200)
|
||||||
|
{
|
||||||
throw new ApiException(ApiErrorKind.Business, result.Msg ?? "操作失败。", response.StatusCode, result.Code, result.TraceId);
|
throw new ApiException(ApiErrorKind.Business, result.Msg ?? "操作失败。", response.StatusCode, result.Code, result.TraceId);
|
||||||
return result.Data;
|
}
|
||||||
|
if (result.Data.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
|
||||||
|
{
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return result.Data.Deserialize<T>(Json);
|
||||||
|
}
|
||||||
|
catch (JsonException ex)
|
||||||
|
{
|
||||||
|
throw new ApiException(ApiErrorKind.InvalidResponse, "服务器响应 data 格式无效。",
|
||||||
|
response.StatusCode, result.Code, result.TraceId, ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<T> GetRequiredAsync<T>(string route, Method method, object? body = null,
|
public async Task<T> GetRequiredAsync<T>(string route, Method method, object? body = null,
|
||||||
|
|||||||
@@ -1,18 +1,12 @@
|
|||||||
using RestSharp;
|
using RestSharp;
|
||||||
using Store.Management.Api.Models;
|
using Store.Management.Api.Models;
|
||||||
using Store.Management.Api.Transport;
|
using Store.Management.Api.Transport;
|
||||||
|
using Store.Management.Models;
|
||||||
|
|
||||||
namespace Store.Management.Api.Users;
|
namespace Store.Management.Api.Users;
|
||||||
|
|
||||||
public interface IUserApi
|
|
||||||
{
|
|
||||||
Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default);
|
|
||||||
Task<UserInfo> GetAsync(string? userName = null, CancellationToken cancellationToken = default);
|
|
||||||
Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default);
|
|
||||||
Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed class UserApi(ApiTransport transport) : IUserApi
|
public sealed class UserApi(ApiTransport transport)
|
||||||
{
|
{
|
||||||
public Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default)
|
public Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
@@ -27,9 +21,24 @@ internal sealed class UserApi(ApiTransport transport) : IUserApi
|
|||||||
public Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default)
|
public Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
return transport.GetRequiredAsync<UserInfo>("user/AddUser", Method.Post, request, cancellationToken: cancellationToken);
|
string route = request.GroupId is null or UserGroup.MainAccount ? "user/AddUser" : "user/AddSubUser";
|
||||||
|
return transport.GetRequiredAsync<UserInfo>(route, Method.Post, request, cancellationToken: cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken cancellationToken = default)
|
||||||
|
=> transport.SendAsync<object>("user/ChangePassword", Method.Post, request, cancellationToken: cancellationToken);
|
||||||
|
|
||||||
|
public Task DeleteAsync(int id, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id);
|
||||||
|
return transport.SendAsync<object>("user/DelUser", Method.Post,
|
||||||
|
query: new Dictionary<string, string?> { ["id"] = id.ToString(System.Globalization.CultureInfo.InvariantCulture) },
|
||||||
|
cancellationToken: cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<UserInfo> UpdateBillingAsync(UserBillingUpdateRequest request, CancellationToken cancellationToken = default)
|
||||||
|
=> transport.GetRequiredAsync<UserInfo>("user/UpdateUser", Method.Post, request, cancellationToken: cancellationToken);
|
||||||
|
|
||||||
public Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default)
|
public Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
using Store.Management.Models;
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
using Store.Management.Api.Models;
|
using Store.Management.Api.Models;
|
||||||
|
|
||||||
namespace Store.Management.Api.Users;
|
namespace Store.Management.Api.Users;
|
||||||
@@ -6,12 +8,16 @@ namespace Store.Management.Api.Users;
|
|||||||
public sealed class UserSearchRequest : PageRequest
|
public sealed class UserSearchRequest : PageRequest
|
||||||
{
|
{
|
||||||
[StringLength(100)] public string? Keyword { get; set; }
|
[StringLength(100)] public string? Keyword { get; set; }
|
||||||
public int? GroupId { get; set; }
|
public int? GroupId { get; set; }
|
||||||
[StringLength(20)] public string? ParentUserName { get; set; }
|
[StringLength(20)] public string? ParentUserName { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class UserEditRequest
|
public class UserEditRequest
|
||||||
{
|
{
|
||||||
|
public UserGroup? GroupId { get; set; }
|
||||||
|
public UserAdminLevel? SaLevel { get; set; }
|
||||||
|
[StringLength(50)] public string? OemId { get; set; }
|
||||||
|
[StringLength(1000)] public string? Authority { get; set; }
|
||||||
[StringLength(50)] public string? NickName { get; set; }
|
[StringLength(50)] public string? NickName { get; set; }
|
||||||
[StringLength(30)] public string? Mobile { get; set; }
|
[StringLength(30)] public string? Mobile { get; set; }
|
||||||
[StringLength(100)] public string? CompanyName { get; set; }
|
[StringLength(100)] public string? CompanyName { get; set; }
|
||||||
@@ -25,22 +31,24 @@ public sealed class UserCreateRequest : UserEditRequest
|
|||||||
[StringLength(20)] public string? ParentUserName { get; set; }
|
[StringLength(20)] public string? ParentUserName { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public sealed record ChangePasswordRequest(string UserName, string NewPassword, string? OldPassword = null);
|
||||||
|
|
||||||
public sealed class UserUpdateRequest : UserEditRequest
|
public sealed class UserUpdateRequest : UserEditRequest
|
||||||
{
|
{
|
||||||
[Range(1, int.MaxValue)] public int Id { get; set; }
|
[Range(1, int.MaxValue)] public int Id { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>管理端当前使用的用户资料字段;不接收密码。</summary>
|
public sealed class UserBillingUpdateRequest
|
||||||
public sealed class UserInfo
|
|
||||||
{
|
{
|
||||||
public int Id { get; init; }
|
[Range(1, int.MaxValue)] public int Id { get; init; }
|
||||||
public string UserName { get; init; } = "";
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
public string? NickName { get; init; }
|
public int? ShopPointsPerMonth { get; set; }
|
||||||
public string? Mobile { get; init; }
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
public string? CompanyName { get; init; }
|
public decimal? PostagePerOrder { get; set; }
|
||||||
public string? Notes { get; init; }
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
public string? ParentUserName { get; init; }
|
public decimal? RefundPostagePerOrder { get; set; }
|
||||||
public int GroupId { get; init; }
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
public decimal Points { get; init; }
|
public decimal? GiftOemAmountPerOrder { get; set; }
|
||||||
public decimal? Balance { get; init; }
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
public decimal? SyncLogisticsPerOrder { get; set; }
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ public sealed class FolderConfig : IFolderConfig
|
|||||||
/// <summary>当前用户的数据根目录:%LOCALAPPDATA%\Store.Management。</summary>
|
/// <summary>当前用户的数据根目录:%LOCALAPPDATA%\Store.Management。</summary>
|
||||||
public static string AppFolder => Path.Combine(
|
public static string AppFolder => Path.Combine(
|
||||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppName);
|
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppName);
|
||||||
|
//, MAX.Core.Cryptography.MD5Helper.Md5_32(ExeFolder)
|
||||||
public static string ConfigFolder => Path.Combine(AppFolder, "Config");
|
public static string ConfigFolder => Path.Combine(AppFolder, "Config");
|
||||||
public static string DataFolder => Path.Combine(AppFolder, "Data");
|
public static string DataFolder => Path.Combine(AppFolder, "Data");
|
||||||
public static string LoggingFolder => Path.Combine(AppFolder, "Logs");
|
public static string LoggingFolder => Path.Combine(AppFolder, "Logs");
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ using System.Text;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
|
|
||||||
namespace MAX.Framework.Controls.Attach;
|
namespace Store.Management.Framework.Controls.Attach;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 弹出窗口属性值
|
/// 弹出窗口属性值
|
||||||
+6
-7
@@ -8,7 +8,7 @@ using System.Windows;
|
|||||||
using System.Windows.Input;
|
using System.Windows.Input;
|
||||||
using System.Windows.Media;
|
using System.Windows.Media;
|
||||||
|
|
||||||
namespace MAX.Framework.Controls;
|
namespace Store.Management.Framework.Controls;
|
||||||
|
|
||||||
public static class IDialogServiceExtension
|
public static class IDialogServiceExtension
|
||||||
{
|
{
|
||||||
@@ -32,7 +32,7 @@ public static class IDialogServiceExtension
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 确定取消对话框 ViewModel
|
/// 确定取消对话框 ViewModel
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class ConfirmDialogViewModel : BindableBase, IDialogAware
|
public class ConfirmDialogViewModel : ViewModelBase, IDialogAware
|
||||||
{
|
{
|
||||||
public ConfirmDialogViewModel()
|
public ConfirmDialogViewModel()
|
||||||
{
|
{
|
||||||
@@ -69,7 +69,6 @@ public class ConfirmDialogViewModel : BindableBase, IDialogAware
|
|||||||
get => allowEnter;
|
get => allowEnter;
|
||||||
set => SetProperty(ref allowEnter, value);
|
set => SetProperty(ref allowEnter, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool IsLoading
|
public bool IsLoading
|
||||||
{
|
{
|
||||||
get => isLoading;
|
get => isLoading;
|
||||||
@@ -236,26 +235,26 @@ public class ConfirmDialogViewModel : BindableBase, IDialogAware
|
|||||||
/// <typeparam name="TParameter">参数Model</typeparam>
|
/// <typeparam name="TParameter">参数Model</typeparam>
|
||||||
public class ConfirmDialogViewModel<TParameter> : ConfirmDialogViewModel where TParameter : class
|
public class ConfirmDialogViewModel<TParameter> : ConfirmDialogViewModel where TParameter : class
|
||||||
{
|
{
|
||||||
protected TParameter Args { get; set; }
|
protected TParameter Parameter { get; set; }
|
||||||
public override void OnDialogOpened(IDialogParameters parameters)
|
public override void OnDialogOpened(IDialogParameters parameters)
|
||||||
{
|
{
|
||||||
base.OnDialogOpened(parameters);
|
base.OnDialogOpened(parameters);
|
||||||
if (parameters.TryGetValue("parameter", out TParameter parameter))
|
if (parameters.TryGetValue("parameter", out TParameter parameter))
|
||||||
{
|
{
|
||||||
Args = parameter;
|
Parameter = parameter;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public abstract class ConfirmDialogViewModel<TParameter, TResult> : ConfirmDialogViewModel where TParameter : class where TResult : DialogResult/*, new()*/
|
public abstract class ConfirmDialogViewModel<TParameter, TResult> : ConfirmDialogViewModel where TParameter : class where TResult : DialogResult/*, new()*/
|
||||||
{
|
{
|
||||||
protected TParameter Args { get; set; }
|
protected TParameter Parameter { get; set; }
|
||||||
public override void OnDialogOpened(IDialogParameters parameters)
|
public override void OnDialogOpened(IDialogParameters parameters)
|
||||||
{
|
{
|
||||||
base.OnDialogOpened(parameters);
|
base.OnDialogOpened(parameters);
|
||||||
if (parameters.TryGetValue("parameter", out TParameter parameter))
|
if (parameters.TryGetValue("parameter", out TParameter parameter))
|
||||||
{
|
{
|
||||||
Args = parameter;
|
Parameter = parameter;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
protected override void _Confirm()
|
protected override void _Confirm()
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using System.Windows.Controls.Primitives;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using System.Windows.Threading;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls;
|
||||||
|
|
||||||
|
public partial class DataGridEx
|
||||||
|
{
|
||||||
|
private DispatcherTimer? imageResumeTimer;
|
||||||
|
private bool draggingScrollThumb;
|
||||||
|
|
||||||
|
private void InitializeImageLoadingPause()
|
||||||
|
{
|
||||||
|
imageResumeTimer = new DispatcherTimer(DispatcherPriority.Background, Dispatcher)
|
||||||
|
{
|
||||||
|
Interval = TimeSpan.FromMilliseconds(500)
|
||||||
|
};
|
||||||
|
imageResumeTimer.Tick += (_, _) =>
|
||||||
|
{
|
||||||
|
imageResumeTimer.Stop();
|
||||||
|
if (!draggingScrollThumb && IsLoaded) SetImageLoadingSuspended(false);
|
||||||
|
};
|
||||||
|
AddHandler(Thumb.DragStartedEvent, new DragStartedEventHandler(ScrollThumbDragStarted), true);
|
||||||
|
AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler(ScrollThumbDragCompleted), true);
|
||||||
|
AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(ImageScrollChanged), true);
|
||||||
|
Unloaded += (_, _) =>
|
||||||
|
{
|
||||||
|
imageResumeTimer.Stop(); draggingScrollThumb = false;
|
||||||
|
SetImageLoadingSuspended(true);
|
||||||
|
};
|
||||||
|
Loaded += (_, _) => { ApplyImageLoadingOptions(); SetImageLoadingSuspended(false); };
|
||||||
|
ApplyImageLoadingOptions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetImageLoadingSuspended(bool suspended)
|
||||||
|
{
|
||||||
|
SetValue(IsImageLoadingSuspendedPropertyKey, suspended);
|
||||||
|
NetworkThumbnail.SetIsLoadingSuspended(this, suspended);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ApplyImageLoadingOptions()
|
||||||
|
{
|
||||||
|
NetworkThumbnail.SetCacheEnabled(this, EnableImageCache);
|
||||||
|
if (imageResumeTimer == null) return;
|
||||||
|
if (!PauseImageLoadingWhileDragging)
|
||||||
|
{
|
||||||
|
imageResumeTimer.Stop(); draggingScrollThumb = false; SetImageLoadingSuspended(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsOwnScrollBar(DependencyObject? source)
|
||||||
|
{
|
||||||
|
var foundScrollBar = false;
|
||||||
|
for (var parent = source; parent != null; parent = VisualTreeHelper.GetParent(parent))
|
||||||
|
{
|
||||||
|
if (parent is ScrollBar) foundScrollBar = true;
|
||||||
|
if (parent is DataGrid) return ReferenceEquals(parent, this) && foundScrollBar;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScrollThumbDragStarted(object sender, DragStartedEventArgs e)
|
||||||
|
{
|
||||||
|
if (!PauseImageLoadingWhileDragging || !IsOwnScrollBar(e.OriginalSource as DependencyObject)) return;
|
||||||
|
draggingScrollThumb = true;
|
||||||
|
imageResumeTimer!.Stop();
|
||||||
|
// 继承到可见图片及随后回收生成的新行,立即取消请求并清空图片。
|
||||||
|
SetImageLoadingSuspended(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScrollThumbDragCompleted(object sender, DragCompletedEventArgs e)
|
||||||
|
{
|
||||||
|
if (!PauseImageLoadingWhileDragging || !IsOwnScrollBar(e.OriginalSource as DependencyObject)) return;
|
||||||
|
draggingScrollThumb = false;
|
||||||
|
RestartImageResumeTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ImageScrollChanged(object sender, ScrollChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (!NetworkThumbnail.GetIsLoadingSuspended(this) || draggingScrollThumb ||
|
||||||
|
(e.VerticalChange == 0 && e.HorizontalChange == 0) ||
|
||||||
|
!IsOwnScrollViewer(e.OriginalSource as DependencyObject)) return;
|
||||||
|
RestartImageResumeTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsOwnScrollViewer(DependencyObject? source)
|
||||||
|
{
|
||||||
|
for (var parent = source; parent != null; parent = VisualTreeHelper.GetParent(parent))
|
||||||
|
if (parent is DataGrid) return ReferenceEquals(parent, this);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RestartImageResumeTimer()
|
||||||
|
{
|
||||||
|
imageResumeTimer!.Stop();
|
||||||
|
imageResumeTimer.Start();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using Store.Management.Framework.Controls.Attach;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using System.Windows.Input;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls;
|
||||||
|
|
||||||
|
public partial class DataGridEx
|
||||||
|
{
|
||||||
|
public static readonly DependencyProperty NoDataTipsProperty = DataGridHelper.NoDataTipsProperty.AddOwner(typeof(DataGridEx));
|
||||||
|
public string NoDataTips { get => (string)GetValue(NoDataTipsProperty); set => SetValue(NoDataTipsProperty, value); }
|
||||||
|
public static readonly DependencyProperty IsActiveProperty = DataGridHelper.IsActiveProperty.AddOwner(typeof(DataGridEx));
|
||||||
|
/// <summary>为 true 时抑制空数据提示;可在业务加载数据期间设置。</summary>
|
||||||
|
public bool IsActive { get => (bool)GetValue(IsActiveProperty); set => SetValue(IsActiveProperty, value); }
|
||||||
|
|
||||||
|
public static readonly DependencyProperty RowContextMenuProperty = DependencyProperty.Register(nameof(RowContextMenu), typeof(ContextMenu), typeof(DataGridEx), new PropertyMetadata(null));
|
||||||
|
public ContextMenu? RowContextMenu { get => (ContextMenu?)GetValue(RowContextMenuProperty); set => SetValue(RowContextMenuProperty, value); }
|
||||||
|
|
||||||
|
public static readonly DependencyProperty ShowSelectAllProperty = DependencyProperty.Register(nameof(ShowSelectAll), typeof(bool), typeof(DataGridEx), new PropertyMetadata(true));
|
||||||
|
public static readonly DependencyProperty ToggleSelectionOnRowHeaderClickProperty = DependencyProperty.Register(nameof(ToggleSelectionOnRowHeaderClick), typeof(bool), typeof(DataGridEx), new PropertyMetadata(true));
|
||||||
|
public static readonly DependencyProperty SelectRowOnRightClickProperty = DependencyProperty.Register(nameof(SelectRowOnRightClick), typeof(bool), typeof(DataGridEx), new PropertyMetadata(false));
|
||||||
|
public static readonly DependencyProperty PauseImageLoadingWhileDraggingProperty = DependencyProperty.Register(nameof(PauseImageLoadingWhileDragging), typeof(bool), typeof(DataGridEx), new PropertyMetadata(true, ImageOptionsChanged));
|
||||||
|
public static readonly DependencyProperty EnableImageCacheProperty = DependencyProperty.Register(nameof(EnableImageCache), typeof(bool), typeof(DataGridEx), new PropertyMetadata(true, ImageOptionsChanged));
|
||||||
|
private static readonly DependencyPropertyKey IsImageLoadingSuspendedPropertyKey = DependencyProperty.RegisterReadOnly(nameof(IsImageLoadingSuspended), typeof(bool), typeof(DataGridEx), new PropertyMetadata(false));
|
||||||
|
public static readonly DependencyProperty IsImageLoadingSuspendedProperty = IsImageLoadingSuspendedPropertyKey.DependencyProperty;
|
||||||
|
|
||||||
|
public bool ShowSelectAll { get => (bool)GetValue(ShowSelectAllProperty); set => SetValue(ShowSelectAllProperty, value); }
|
||||||
|
public bool ToggleSelectionOnRowHeaderClick { get => (bool)GetValue(ToggleSelectionOnRowHeaderClickProperty); set => SetValue(ToggleSelectionOnRowHeaderClickProperty, value); }
|
||||||
|
public bool SelectRowOnRightClick { get => (bool)GetValue(SelectRowOnRightClickProperty); set => SetValue(SelectRowOnRightClickProperty, value); }
|
||||||
|
/// <summary>默认开启;拖动时暂停并清空图片,停止滚动 500ms 后恢复。</summary>
|
||||||
|
public bool PauseImageLoadingWhileDragging { get => (bool)GetValue(PauseImageLoadingWhileDraggingProperty); set => SetValue(PauseImageLoadingWhileDraggingProperty, value); }
|
||||||
|
/// <summary>默认开启图片缓存;设为 false 时不读取或写入缓存。</summary>
|
||||||
|
public bool EnableImageCache { get => (bool)GetValue(EnableImageCacheProperty); set => SetValue(EnableImageCacheProperty, value); }
|
||||||
|
public bool IsImageLoadingSuspended => (bool)GetValue(IsImageLoadingSuspendedProperty);
|
||||||
|
|
||||||
|
private static void ImageOptionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
=> ((DataGridEx)d).ApplyImageLoadingOptions();
|
||||||
|
|
||||||
|
protected override void OnPreviewMouseRightButtonDown(MouseButtonEventArgs e)
|
||||||
|
{
|
||||||
|
if (SelectRowOnRightClick && !e.Handled && SelectionUnit != DataGridSelectionUnit.Cell && e.OriginalSource is DependencyObject source)
|
||||||
|
{
|
||||||
|
var row = FindRow(source);
|
||||||
|
if (row != null && ItemsControl.ItemsControlFromItemContainer(row) == this && !row.IsSelected &&
|
||||||
|
row.Item != System.Windows.Data.CollectionView.NewItemPlaceholder)
|
||||||
|
{
|
||||||
|
UnselectAll(); row.SetCurrentValue(DataGridRow.IsSelectedProperty, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
base.OnPreviewMouseRightButtonDown(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using System.Windows.Controls.Primitives;
|
||||||
|
using System.Windows.Data;
|
||||||
|
using System.Windows.Input;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls;
|
||||||
|
|
||||||
|
/// <summary>调用方收到请求后加载对应页,再更新 ItemsSource 和 TotalItemCount。</summary>
|
||||||
|
public sealed record DataGridPageRequest(int PageIndex, int PageSize);
|
||||||
|
|
||||||
|
public partial class DataGridEx
|
||||||
|
{
|
||||||
|
public static readonly DependencyProperty IsLoadingProperty = DependencyProperty.Register(nameof(IsLoading), typeof(bool), typeof(DataGridEx), new PropertyMetadata(false));
|
||||||
|
public static readonly DependencyProperty LoadingTextProperty = DependencyProperty.Register(nameof(LoadingText), typeof(string), typeof(DataGridEx), new PropertyMetadata("正在加载数据…"));
|
||||||
|
/// <summary>加载时显示动画并禁用表格内容;由调用方控制请求生命周期。</summary>
|
||||||
|
public bool IsLoading { get => (bool)GetValue(IsLoadingProperty); set => SetValue(IsLoadingProperty, value); }
|
||||||
|
public string LoadingText { get => (string)GetValue(LoadingTextProperty); set => SetValue(LoadingTextProperty, value); }
|
||||||
|
|
||||||
|
public static readonly DependencyProperty ShowToolbarProperty = DependencyProperty.Register(nameof(ShowToolbar), typeof(bool), typeof(DataGridEx), new PropertyMetadata(true));
|
||||||
|
public static readonly DependencyProperty ShowColumnSettingsProperty = DependencyProperty.Register(nameof(ShowColumnSettings), typeof(bool), typeof(DataGridEx), new PropertyMetadata(true));
|
||||||
|
public static readonly DependencyProperty ShowPaginationProperty = DependencyProperty.Register(nameof(ShowPagination), typeof(bool), typeof(DataGridEx), new PropertyMetadata(true, HeaderOptionsChanged));
|
||||||
|
public static readonly DependencyProperty ToolbarContentProperty = DependencyProperty.Register(nameof(ToolbarContent), typeof(object), typeof(DataGridEx));
|
||||||
|
public static readonly DependencyProperty PaginationContentProperty = DependencyProperty.Register(nameof(PaginationContent), typeof(object), typeof(DataGridEx));
|
||||||
|
public static readonly DependencyProperty PageSizesProperty = DependencyProperty.Register(nameof(PageSizes), typeof(IEnumerable), typeof(DataGridEx), new PropertyMetadata(new[] { 20, 50, 100 }));
|
||||||
|
public static readonly DependencyProperty PageChangedCommandProperty = DependencyProperty.Register(nameof(PageChangedCommand), typeof(ICommand), typeof(DataGridEx));
|
||||||
|
public static readonly DependencyProperty PageIndexProperty = DependencyProperty.Register(nameof(PageIndex), typeof(int), typeof(DataGridEx), new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, PageOptionsChanged), value => (int)value > 0);
|
||||||
|
public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register(nameof(PageSize), typeof(int), typeof(DataGridEx), new FrameworkPropertyMetadata(50, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, PageOptionsChanged), value => (int)value > 0);
|
||||||
|
public static readonly DependencyProperty TotalItemCountProperty = DependencyProperty.Register(nameof(TotalItemCount), typeof(int), typeof(DataGridEx), new PropertyMetadata(0, TotalChanged), value => (int)value >= 0);
|
||||||
|
|
||||||
|
public bool ShowToolbar { get => (bool)GetValue(ShowToolbarProperty); set => SetValue(ShowToolbarProperty, value); }
|
||||||
|
public bool ShowColumnSettings { get => (bool)GetValue(ShowColumnSettingsProperty); set => SetValue(ShowColumnSettingsProperty, value); }
|
||||||
|
public bool ShowPagination { get => (bool)GetValue(ShowPaginationProperty); set => SetValue(ShowPaginationProperty, value); }
|
||||||
|
/// <summary>自定义批量按钮区,使用调用方的 DataContext。</summary>
|
||||||
|
public object? ToolbarContent { get => GetValue(ToolbarContentProperty); set => SetValue(ToolbarContentProperty, value); }
|
||||||
|
/// <summary>自定义整个分页栏,继承调用方 DataContext;null 时使用默认分页栏。</summary>
|
||||||
|
public object? PaginationContent { get => GetValue(PaginationContentProperty); set => SetValue(PaginationContentProperty, value); }
|
||||||
|
public IEnumerable PageSizes { get => (IEnumerable)GetValue(PageSizesProperty); set => SetValue(PageSizesProperty, value); }
|
||||||
|
public ICommand? PageChangedCommand { get => (ICommand?)GetValue(PageChangedCommandProperty); set => SetValue(PageChangedCommandProperty, value); }
|
||||||
|
public int PageIndex { get => (int)GetValue(PageIndexProperty); set => SetValue(PageIndexProperty, value); }
|
||||||
|
public int PageSize { get => (int)GetValue(PageSizeProperty); set => SetValue(PageSizeProperty, value); }
|
||||||
|
public int TotalItemCount { get => (int)GetValue(TotalItemCountProperty); set => SetValue(TotalItemCountProperty, value); }
|
||||||
|
|
||||||
|
private static readonly DependencyPropertyKey PageCountPropertyKey = DependencyProperty.RegisterReadOnly(nameof(PageCount), typeof(int), typeof(DataGridEx), new PropertyMetadata(1));
|
||||||
|
public static readonly DependencyProperty PageCountProperty = PageCountPropertyKey.DependencyProperty;
|
||||||
|
public int PageCount => (int)GetValue(PageCountProperty);
|
||||||
|
private static readonly DependencyPropertyKey PageSummaryPropertyKey = DependencyProperty.RegisterReadOnly(nameof(PageSummary), typeof(string), typeof(DataGridEx), new PropertyMetadata("1 / 1"));
|
||||||
|
public static readonly DependencyProperty PageSummaryProperty = PageSummaryPropertyKey.DependencyProperty;
|
||||||
|
public string PageSummary => (string)GetValue(PageSummaryProperty);
|
||||||
|
private static readonly DependencyPropertyKey TotalSummaryPropertyKey = DependencyProperty.RegisterReadOnly(nameof(TotalSummary), typeof(string), typeof(DataGridEx), new PropertyMetadata("共 0 条记录"));
|
||||||
|
public static readonly DependencyProperty TotalSummaryProperty = TotalSummaryPropertyKey.DependencyProperty;
|
||||||
|
public string TotalSummary => (string)GetValue(TotalSummaryProperty);
|
||||||
|
private static readonly DependencyPropertyKey SelectionSummaryPropertyKey = DependencyProperty.RegisterReadOnly(nameof(SelectionSummary), typeof(string), typeof(DataGridEx), new PropertyMetadata("选择记录后可批量操作"));
|
||||||
|
public static readonly DependencyProperty SelectionSummaryProperty = SelectionSummaryPropertyKey.DependencyProperty;
|
||||||
|
public string SelectionSummary => (string)GetValue(SelectionSummaryProperty);
|
||||||
|
|
||||||
|
/// <summary>设为 false 的业务列在列设置中固定显示。</summary>
|
||||||
|
public static readonly DependencyProperty CanHideColumnProperty = DependencyProperty.RegisterAttached("CanHideColumn", typeof(bool), typeof(DataGridEx), new PropertyMetadata(true, CanHideColumnChanged));
|
||||||
|
public static bool GetCanHideColumn(DependencyObject column) => (bool)column.GetValue(CanHideColumnProperty);
|
||||||
|
public static void SetCanHideColumn(DependencyObject column, bool value) => column.SetValue(CanHideColumnProperty, value);
|
||||||
|
private static void CanHideColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (!(bool)e.NewValue && d is DataGridColumn column)
|
||||||
|
{
|
||||||
|
column.SetCurrentValue(DataGridColumn.VisibilityProperty, Visibility.Visible);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly DependencyProperty RowNumberProperty = DependencyProperty.RegisterAttached("RowNumber", typeof(long), typeof(DataGridEx), new FrameworkPropertyMetadata(0L, FrameworkPropertyMetadataOptions.Inherits));
|
||||||
|
public static long GetRowNumber(DependencyObject target) => (long)target.GetValue(RowNumberProperty);
|
||||||
|
public static void SetRowNumber(DependencyObject target, long value) => target.SetValue(RowNumberProperty, value);
|
||||||
|
|
||||||
|
public static readonly RoutedUICommand FirstPageCommand = new("首页", nameof(FirstPageCommand), typeof(DataGridEx));
|
||||||
|
public static readonly RoutedUICommand PreviousPageCommand = new("上一页", nameof(PreviousPageCommand), typeof(DataGridEx));
|
||||||
|
public static readonly RoutedUICommand NextPageCommand = new("下一页", nameof(NextPageCommand), typeof(DataGridEx));
|
||||||
|
public static readonly RoutedUICommand LastPageCommand = new("末页", nameof(LastPageCommand), typeof(DataGridEx));
|
||||||
|
|
||||||
|
private readonly RowNumberColumn rowNumberColumn = new();
|
||||||
|
private Button? columnsButton;
|
||||||
|
private bool updatingPage;
|
||||||
|
|
||||||
|
private void InitializeWorkbench()
|
||||||
|
{
|
||||||
|
Columns.Add(rowNumberColumn);
|
||||||
|
UpdateHeaderOptions();
|
||||||
|
CommandBindings.Add(new CommandBinding(FirstPageCommand, (_, e) => { SetCurrentValue(PageIndexProperty, 1); e.Handled = true; }, (_, e) => { e.CanExecute = PageIndex > 1; e.Handled = true; }));
|
||||||
|
CommandBindings.Add(new CommandBinding(PreviousPageCommand, (_, e) => { SetCurrentValue(PageIndexProperty, PageIndex - 1); e.Handled = true; }, (_, e) => { e.CanExecute = PageIndex > 1; e.Handled = true; }));
|
||||||
|
CommandBindings.Add(new CommandBinding(NextPageCommand, (_, e) => { SetCurrentValue(PageIndexProperty, PageIndex + 1); e.Handled = true; }, (_, e) => { e.CanExecute = PageIndex < PageCount; e.Handled = true; }));
|
||||||
|
CommandBindings.Add(new CommandBinding(LastPageCommand, (_, e) => { SetCurrentValue(PageIndexProperty, PageCount); e.Handled = true; }, (_, e) => { e.CanExecute = PageIndex < PageCount; e.Handled = true; }));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateHeaderOptions()
|
||||||
|
{
|
||||||
|
SetCurrentValue(RowHeaderWidthProperty, ShowCheckBox ? 32d : 0d);
|
||||||
|
rowNumberColumn.Visibility = ShowRowNumber ? Visibility.Visible : Visibility.Collapsed;
|
||||||
|
QueueHeaderUpdate();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void PageOptionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
DataGridEx grid = (DataGridEx)d;
|
||||||
|
if (grid.updatingPage)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
grid.updatingPage = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
grid.SetCurrentValue(PageIndexProperty, e.Property == PageSizeProperty ? 1 : Math.Min(grid.PageIndex, grid.CalculatePageCount()));
|
||||||
|
grid.UpdatePageSummary();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
grid.updatingPage = false;
|
||||||
|
}
|
||||||
|
grid.UnselectAll();
|
||||||
|
grid.QueueHeaderUpdate();
|
||||||
|
DataGridPageRequest request = new(grid.PageIndex, grid.PageSize);
|
||||||
|
if (grid.PageChangedCommand?.CanExecute(request) == true)
|
||||||
|
{
|
||||||
|
grid.PageChangedCommand.Execute(request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TotalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
DataGridEx grid = (DataGridEx)d;
|
||||||
|
grid.UpdatePageSummary();
|
||||||
|
if (grid.PageIndex > grid.PageCount)
|
||||||
|
{
|
||||||
|
grid.SetCurrentValue(PageIndexProperty, grid.PageCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int CalculatePageCount() => Math.Max(1, (int)(((long)TotalItemCount + PageSize - 1) / PageSize));
|
||||||
|
|
||||||
|
private void UpdatePageSummary()
|
||||||
|
{
|
||||||
|
SetValue(PageCountPropertyKey, CalculatePageCount());
|
||||||
|
SetValue(PageSummaryPropertyKey, $"{PageIndex} / {PageCount}");
|
||||||
|
SetValue(TotalSummaryPropertyKey, $"共 {TotalItemCount:N0} 条记录");
|
||||||
|
CommandManager.InvalidateRequerySuggested();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnApplyTemplate()
|
||||||
|
{
|
||||||
|
if (columnsButton != null)
|
||||||
|
{
|
||||||
|
columnsButton.Click -= OpenColumnSettings;
|
||||||
|
}
|
||||||
|
base.OnApplyTemplate();
|
||||||
|
columnsButton = GetTemplateChild("PART_ColumnsButton") as Button;
|
||||||
|
if (columnsButton != null)
|
||||||
|
{
|
||||||
|
columnsButton.Click += OpenColumnSettings;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenColumnSettings(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
ContextMenu menu = new() { PlacementTarget = columnsButton, Placement = PlacementMode.Bottom, VerticalOffset = 6, Style = (Style)FindResource("DataGridExColumnMenu") };
|
||||||
|
menu.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, (_, _) => menu.IsOpen = false));
|
||||||
|
foreach (DataGridColumn column in Columns.OrderBy(column => column.DisplayIndex))
|
||||||
|
{
|
||||||
|
if (column == rowNumberColumn)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
bool canHide = GetCanHideColumn(column);
|
||||||
|
MenuItem option = new()
|
||||||
|
{
|
||||||
|
Header = $"{column.Header}{(canHide ? string.Empty : "(固定)")}",
|
||||||
|
IsCheckable = true,
|
||||||
|
IsChecked = column.Visibility == Visibility.Visible,
|
||||||
|
IsEnabled = canHide,
|
||||||
|
StaysOpenOnClick = true
|
||||||
|
};
|
||||||
|
option.Click += (_, _) => column.SetCurrentValue(DataGridColumn.VisibilityProperty, option.IsChecked ? Visibility.Visible : Visibility.Collapsed);
|
||||||
|
menu.Items.Add(option);
|
||||||
|
}
|
||||||
|
|
||||||
|
columnsButton!.ContextMenu = menu;
|
||||||
|
menu.IsOpen = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RowNumberColumn : DataGridColumn
|
||||||
|
{
|
||||||
|
public RowNumberColumn()
|
||||||
|
{
|
||||||
|
Header = "序号";
|
||||||
|
Width = 52;
|
||||||
|
IsReadOnly = true;
|
||||||
|
CanUserSort = false;
|
||||||
|
CanUserReorder = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
|
||||||
|
{
|
||||||
|
TextBlock text = new() { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };
|
||||||
|
text.SetBinding(TextBlock.TextProperty, new Binding { Path = new PropertyPath(RowNumberProperty), RelativeSource = RelativeSource.Self, Mode = BindingMode.OneWay });
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) => GenerateElement(cell, dataItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.Collections.Specialized;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using System.Windows.Controls.Primitives;
|
||||||
|
using System.Windows.Input;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using System.Windows.Threading;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls;
|
||||||
|
|
||||||
|
/// <summary>带默认样式、行号和行选择勾选框的 DataGrid。</summary>
|
||||||
|
public partial class DataGridEx : DataGrid
|
||||||
|
{
|
||||||
|
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register(
|
||||||
|
nameof(SelectedItems), typeof(IList), typeof(DataGridEx),
|
||||||
|
new FrameworkPropertyMetadata(null, OnSelectedItemsChanged));
|
||||||
|
|
||||||
|
/// <summary>可绑定的选中集合。使用 ObservableCollection 可从 VM 增删选中项;未绑定时返回原生选中集合。</summary>
|
||||||
|
public new IList SelectedItems
|
||||||
|
{
|
||||||
|
get => (IList?)GetValue(SelectedItemsProperty) ?? base.SelectedItems;
|
||||||
|
set => SetValue(SelectedItemsProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>批量恢复性能测试前的选择,只发出一次选择变更。</summary>
|
||||||
|
internal void RestoreSelection(IEnumerable<object> selected)
|
||||||
|
{
|
||||||
|
var available = Items.Cast<object>().ToHashSet();
|
||||||
|
BeginUpdateSelectedItems();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
base.SelectedItems.Clear();
|
||||||
|
foreach (var item in selected)
|
||||||
|
if (available.Contains(item)) base.SelectedItems.Add(item);
|
||||||
|
}
|
||||||
|
finally { EndUpdateSelectedItems(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool synchronizingSelection;
|
||||||
|
|
||||||
|
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
var grid = (DataGridEx)d;
|
||||||
|
if (e.NewValue is IList { IsReadOnly: true } or IList { IsFixedSize: true })
|
||||||
|
throw new ArgumentException("SelectedItems 必须绑定到可增删的集合,例如 ObservableCollection<T>。");
|
||||||
|
if (e.OldValue is INotifyCollectionChanged oldCollection)
|
||||||
|
CollectionChangedEventManager.RemoveHandler(oldCollection, grid.OnBoundSelectionChanged);
|
||||||
|
if (e.NewValue is INotifyCollectionChanged newCollection)
|
||||||
|
CollectionChangedEventManager.AddHandler(newCollection, grid.OnBoundSelectionChanged);
|
||||||
|
grid.ApplyBoundSelection();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnBoundSelectionChanged(object? sender, NotifyCollectionChangedEventArgs e) => ApplyBoundSelection();
|
||||||
|
|
||||||
|
private void ApplyBoundSelection()
|
||||||
|
{
|
||||||
|
if (synchronizingSelection || GetValue(SelectedItemsProperty) is not IList boundItems ||
|
||||||
|
ReferenceEquals(boundItems, base.SelectedItems) || SelectionUnit == DataGridSelectionUnit.Cell) return;
|
||||||
|
var available = Items.Cast<object>().ToHashSet();
|
||||||
|
var desired = boundItems.Cast<object>().Where(item => available.Contains(item) &&
|
||||||
|
item != System.Windows.Data.CollectionView.NewItemPlaceholder).Distinct().ToList();
|
||||||
|
if (SelectionMode == DataGridSelectionMode.Single) desired = desired.Take(1).ToList();
|
||||||
|
synchronizingSelection = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var desiredSet = desired.ToHashSet();
|
||||||
|
var current = base.SelectedItems.Cast<object>().ToHashSet();
|
||||||
|
if (SelectionMode == DataGridSelectionMode.Single)
|
||||||
|
SetCurrentValue(SelectedItemProperty, desired.FirstOrDefault());
|
||||||
|
else if (desired.Count == 0) UnselectAll();
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (var item in current)
|
||||||
|
if (!desiredSet.Contains(item)) base.SelectedItems.Remove(item);
|
||||||
|
foreach (var item in desired)
|
||||||
|
if (!current.Contains(item)) base.SelectedItems.Add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally { synchronizingSelection = false; }
|
||||||
|
UpdateSelectAllState();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void PublishSelection()
|
||||||
|
{
|
||||||
|
if (synchronizingSelection || GetValue(SelectedItemsProperty) is not IList boundItems ||
|
||||||
|
ReferenceEquals(boundItems, base.SelectedItems)) return;
|
||||||
|
synchronizingSelection = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var current = base.SelectedItems.Cast<object>().ToArray();
|
||||||
|
if (current.Length == 0) boundItems.Clear();
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var currentSet = current.ToHashSet();
|
||||||
|
for (var i = boundItems.Count - 1; i >= 0; i--)
|
||||||
|
if (!currentSet.Contains(boundItems[i]!)) boundItems.RemoveAt(i);
|
||||||
|
var boundSet = boundItems.Cast<object>().ToHashSet();
|
||||||
|
foreach (var item in current)
|
||||||
|
if (boundSet.Add(item)) boundItems.Add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally { synchronizingSelection = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
|
||||||
|
{
|
||||||
|
var wasSynchronizing = synchronizingSelection;
|
||||||
|
synchronizingSelection = true;
|
||||||
|
try { base.OnItemsSourceChanged(oldValue, newValue); }
|
||||||
|
finally { synchronizingSelection = wasSynchronizing; }
|
||||||
|
ApplyBoundSelection();
|
||||||
|
}
|
||||||
|
private static readonly DependencyPropertyKey IsSelectionModeActivePropertyKey = DependencyProperty.RegisterReadOnly(
|
||||||
|
nameof(IsSelectionModeActive), typeof(bool), typeof(DataGridEx), new PropertyMetadata(false));
|
||||||
|
public static readonly DependencyProperty IsSelectionModeActiveProperty = IsSelectionModeActivePropertyKey.DependencyProperty;
|
||||||
|
/// <summary>点击行头勾选框后进入批量选择,取消所有选中后退出。</summary>
|
||||||
|
public bool IsSelectionModeActive => (bool)GetValue(IsSelectionModeActiveProperty);
|
||||||
|
public static readonly RoutedUICommand ToggleSelectAllCommand = new("全选或取消全选", nameof(ToggleSelectAllCommand), typeof(DataGridEx));
|
||||||
|
private static readonly DependencyPropertyKey AreAllRowsSelectedPropertyKey = DependencyProperty.RegisterReadOnly(
|
||||||
|
nameof(AreAllRowsSelected), typeof(bool?), typeof(DataGridEx), new PropertyMetadata(false));
|
||||||
|
public static readonly DependencyProperty AreAllRowsSelectedProperty = AreAllRowsSelectedPropertyKey.DependencyProperty;
|
||||||
|
/// <summary>全部选中为 true,部分选中为 null,未选中为 false。</summary>
|
||||||
|
public bool? AreAllRowsSelected => (bool?)GetValue(AreAllRowsSelectedProperty);
|
||||||
|
public static readonly DependencyProperty SelectedRowBackgroundProperty = DependencyProperty.Register(
|
||||||
|
nameof(SelectedRowBackground), typeof(Brush), typeof(DataGridEx),
|
||||||
|
new PropertyMetadata(Brushes.LightGray));
|
||||||
|
public static readonly DependencyProperty SelectedRowForegroundProperty = DependencyProperty.Register(
|
||||||
|
nameof(SelectedRowForeground), typeof(Brush), typeof(DataGridEx), new PropertyMetadata(Brushes.Black));
|
||||||
|
public static readonly DependencyProperty ShowCheckBoxProperty = DependencyProperty.Register(
|
||||||
|
nameof(ShowCheckBox), typeof(bool), typeof(DataGridEx), new PropertyMetadata(false, HeaderOptionsChanged));
|
||||||
|
public static readonly DependencyProperty ShowRowNumberProperty = DependencyProperty.Register(
|
||||||
|
nameof(ShowRowNumber), typeof(bool), typeof(DataGridEx), new PropertyMetadata(false, HeaderOptionsChanged));
|
||||||
|
|
||||||
|
public Brush SelectedRowBackground { get => (Brush)GetValue(SelectedRowBackgroundProperty); set => SetValue(SelectedRowBackgroundProperty, value); }
|
||||||
|
public Brush SelectedRowForeground { get => (Brush)GetValue(SelectedRowForegroundProperty); set => SetValue(SelectedRowForegroundProperty, value); }
|
||||||
|
/// <summary>勾选状态与行 IsSelected 同步,可通过 SelectedItems 获取。</summary>
|
||||||
|
public bool ShowCheckBox { get => (bool)GetValue(ShowCheckBoxProperty); set => SetValue(ShowCheckBoxProperty, value); }
|
||||||
|
public bool ShowRowNumber { get => (bool)GetValue(ShowRowNumberProperty); set => SetValue(ShowRowNumberProperty, value); }
|
||||||
|
|
||||||
|
static DataGridEx()
|
||||||
|
{
|
||||||
|
DefaultStyleKeyProperty.OverrideMetadata(typeof(DataGridEx), new FrameworkPropertyMetadata(typeof(DataGridEx)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public DataGridEx()
|
||||||
|
{
|
||||||
|
InitializeImageLoadingPause();
|
||||||
|
InitializeWorkbench();
|
||||||
|
CommandBindings.Add(new CommandBinding(ToggleSelectAllCommand, (_, e) =>
|
||||||
|
{
|
||||||
|
if (AreAllRowsSelected == true) UnselectAll();
|
||||||
|
else
|
||||||
|
{
|
||||||
|
SelectAll();
|
||||||
|
SetValue(IsSelectionModeActivePropertyKey, base.SelectedItems.Count > 0);
|
||||||
|
}
|
||||||
|
e.Handled = true;
|
||||||
|
}, (_, e) =>
|
||||||
|
{
|
||||||
|
e.CanExecute = SelectionMode == DataGridSelectionMode.Extended &&
|
||||||
|
SelectionUnit != DataGridSelectionUnit.Cell && SelectableItemCount > 0;
|
||||||
|
e.Handled = true;
|
||||||
|
}));
|
||||||
|
AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(OnRowCheckBoxClick), true);
|
||||||
|
LoadingRow += (_, e) => UpdateRowNumber(e.Row);
|
||||||
|
ItemContainerGenerator.ItemsChanged += (_, _) => QueueHeaderUpdate();
|
||||||
|
Loaded += (_, _) => { ApplyBoundSelection(); QueueHeaderUpdate(); };
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnRowCheckBoxClick(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
if (e.OriginalSource is not CheckBox checkBox) return;
|
||||||
|
DependencyObject? parent = checkBox;
|
||||||
|
while (parent != null && parent != this)
|
||||||
|
{
|
||||||
|
if (parent is DataGridRowHeader header &&
|
||||||
|
ItemsControl.ItemsControlFromItemContainer(FindRow(header)) == this)
|
||||||
|
{
|
||||||
|
SetValue(IsSelectionModeActivePropertyKey, base.SelectedItems.Count > 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
parent = VisualTreeHelper.GetParent(parent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
|
||||||
|
{
|
||||||
|
if (!e.Handled && SelectionUnit == DataGridSelectionUnit.CellOrRowHeader)
|
||||||
|
{
|
||||||
|
for (DependencyObject? source = e.OriginalSource as DependencyObject; source != null && source != this;
|
||||||
|
source = source is FrameworkContentElement content ? content.Parent : VisualTreeHelper.GetParent(source))
|
||||||
|
{
|
||||||
|
if (source is DataGrid)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (source is Border border && FindRow(border) is DataGridRow blankRow &&
|
||||||
|
ItemsControl.ItemsControlFromItemContainer(blankRow) == this &&
|
||||||
|
ReferenceEquals(blankRow.Template.FindName("border", blankRow), border))
|
||||||
|
{
|
||||||
|
SelectRowThroughHeader(blankRow, e);
|
||||||
|
break;
|
||||||
|
} if (source is DataGridCell cell)
|
||||||
|
{
|
||||||
|
if (cell.Column == rowNumberColumn && FindRow(cell) is DataGridRow row)
|
||||||
|
{
|
||||||
|
SelectRowThroughHeader(row, e);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!e.Handled && ShowCheckBox && ToggleSelectionOnRowHeaderClick && SelectionUnit != DataGridSelectionUnit.Cell)
|
||||||
|
{
|
||||||
|
for (var source = e.OriginalSource as DependencyObject; source != null && source != this;
|
||||||
|
source = source is FrameworkContentElement content ? content.Parent : VisualTreeHelper.GetParent(source))
|
||||||
|
{
|
||||||
|
// 保留行高拖动和嵌套表格自己的鼠标处理。
|
||||||
|
if (source is Thumb || source is DataGrid) break;
|
||||||
|
if (source is not DataGridRowHeader header) continue;
|
||||||
|
var row = FindRow(header);
|
||||||
|
if (row == null || ItemsControl.ItemsControlFromItemContainer(row) != this ||
|
||||||
|
row.Item == System.Windows.Data.CollectionView.NewItemPlaceholder) break;
|
||||||
|
|
||||||
|
// 在 DataGridRowHeader 默认单选逻辑之前处理整个行头,
|
||||||
|
// 包括勾选框四周的留白;阻止 CheckBox 再次切换造成双重反转。
|
||||||
|
e.Handled = true;
|
||||||
|
row.SetCurrentValue(DataGridRow.IsSelectedProperty, !row.IsSelected);
|
||||||
|
SetValue(IsSelectionModeActivePropertyKey, base.SelectedItems.Count > 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
base.OnPreviewMouseLeftButtonDown(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
|
||||||
|
{
|
||||||
|
if (!e.Handled && SelectionUnit != DataGridSelectionUnit.Cell &&
|
||||||
|
e.OriginalSource is Border border &&
|
||||||
|
FindRow(border) is DataGridRow row &&
|
||||||
|
ItemsControl.ItemsControlFromItemContainer(row) == this &&
|
||||||
|
ReferenceEquals(row.Template.FindName("border", row), border))
|
||||||
|
{
|
||||||
|
SelectRowThroughHeader(row, e);
|
||||||
|
}
|
||||||
|
base.OnMouseLeftButtonDown(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SelectRowThroughHeader(DataGridRow row, MouseButtonEventArgs e)
|
||||||
|
{
|
||||||
|
// 序号和行尾留白沿用原生行头逻辑,保留 Ctrl/Shift 与选择锚点。
|
||||||
|
if (row.Template.FindName("PART_RowHeader", row) is DataGridRowHeader header)
|
||||||
|
{
|
||||||
|
header.RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, e.ChangedButton, e.StylusDevice)
|
||||||
|
{
|
||||||
|
RoutedEvent = Mouse.MouseDownEvent
|
||||||
|
});
|
||||||
|
e.Handled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static DataGridRow? FindRow(DependencyObject element)
|
||||||
|
{
|
||||||
|
for (DependencyObject? parent = element; parent != null; parent = parent is FrameworkContentElement content ? content.Parent : VisualTreeHelper.GetParent(parent))
|
||||||
|
if (parent is DataGridRow row) return row;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void HeaderOptionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
=> ((DataGridEx)d).UpdateHeaderOptions();
|
||||||
|
|
||||||
|
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
|
||||||
|
{
|
||||||
|
base.OnItemsChanged(e);
|
||||||
|
QueueHeaderUpdate();
|
||||||
|
UpdateSelectAllState();
|
||||||
|
}
|
||||||
|
|
||||||
|
private int SelectableItemCount => Items.Count - (Items.Contains(System.Windows.Data.CollectionView.NewItemPlaceholder) ? 1 : 0);
|
||||||
|
|
||||||
|
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
|
||||||
|
{
|
||||||
|
PublishSelection();
|
||||||
|
base.OnSelectionChanged(e);
|
||||||
|
UpdateSelectAllState();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateSelectAllState()
|
||||||
|
{
|
||||||
|
SetValue(AreAllRowsSelectedPropertyKey, base.SelectedItems.Count == 0 ? false :
|
||||||
|
base.SelectedItems.Count == SelectableItemCount ? true : (bool?)null);
|
||||||
|
if (base.SelectedItems.Count == 0) SetValue(IsSelectionModeActivePropertyKey, false);
|
||||||
|
SetValue(SelectionSummaryPropertyKey, base.SelectedItems.Count == 0 ? "选择记录后可批量操作" : $"已选择 {base.SelectedItems.Count} 条记录");
|
||||||
|
CommandManager.InvalidateRequerySuggested();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
base.OnPropertyChanged(e);
|
||||||
|
if (e.Property == FontSizeProperty || e.Property == FontFamilyProperty ||
|
||||||
|
e.Property == FontStyleProperty || e.Property == FontWeightProperty || e.Property == FontStretchProperty)
|
||||||
|
QueueHeaderUpdate();
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool headerUpdatePending;
|
||||||
|
private void QueueHeaderUpdate()
|
||||||
|
{
|
||||||
|
if (headerUpdatePending) return;
|
||||||
|
headerUpdatePending = true;
|
||||||
|
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
|
||||||
|
{
|
||||||
|
headerUpdatePending = false;
|
||||||
|
foreach (var row in GetRealizedRows(this)) UpdateRowNumber(row);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateRowNumber(DataGridRow row)
|
||||||
|
=> row.SetValue(RowNumberProperty, (PageIndex - 1L) * PageSize + row.GetIndex() + 1);
|
||||||
|
|
||||||
|
private IEnumerable<DataGridRow> GetRealizedRows(DependencyObject parent)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
|
||||||
|
{
|
||||||
|
var child = VisualTreeHelper.GetChild(parent, i);
|
||||||
|
if (child is DataGridRow row && ItemsControl.ItemsControlFromItemContainer(row) == this) yield return row;
|
||||||
|
else if (child is not DataGrid)
|
||||||
|
foreach (var descendant in GetRealizedRows(child)) yield return descendant;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,169 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
using System.Windows.Data;
|
||||||
|
using System.Windows.Media.Imaging;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using System.Windows;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls;
|
||||||
|
|
||||||
|
/// <summary>配套图片列:自动使用所属 DataGridEx 的拖动暂停和图片缓存能力。</summary>
|
||||||
|
public class DataGridExImageColumn : DataGridBoundColumn
|
||||||
|
{
|
||||||
|
private static readonly Style DefaultImageStyle = CreateDefaultStyle();
|
||||||
|
/// <summary>可选的逐行占位图;未设置时显示空白。</summary>
|
||||||
|
public BindingBase? PlaceholderBinding { get; set; }
|
||||||
|
|
||||||
|
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
|
||||||
|
{
|
||||||
|
var image = new NetworkThumbnail { Style = ElementStyle ?? DefaultImageStyle };
|
||||||
|
if (Binding != null) BindingOperations.SetBinding(image, NetworkThumbnail.UrlProperty, Binding);
|
||||||
|
if (PlaceholderBinding != null)
|
||||||
|
BindingOperations.SetBinding(image, NetworkThumbnail.PlaceholderProperty, PlaceholderBinding);
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) => GenerateElement(cell, dataItem);
|
||||||
|
private static Style CreateDefaultStyle()
|
||||||
|
{
|
||||||
|
var style = new Style(typeof(NetworkThumbnail));
|
||||||
|
style.Setters.Add(new Setter(FrameworkElement.WidthProperty, 58d));
|
||||||
|
style.Setters.Add(new Setter(FrameworkElement.HeightProperty, 58d));
|
||||||
|
style.Setters.Add(new Setter(System.Windows.Controls.Image.StretchProperty, Stretch.Uniform));
|
||||||
|
style.Seal(); return style;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>仅为已生成的可见单元格加载图片;回收时取消,避免旧图片覆盖新行。</summary>
|
||||||
|
public sealed class NetworkThumbnail : Image
|
||||||
|
{
|
||||||
|
public static readonly DependencyProperty CacheEnabledProperty = DependencyProperty.RegisterAttached("CacheEnabled", typeof(bool), typeof(NetworkThumbnail), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits, Changed));
|
||||||
|
public static bool GetCacheEnabled(DependencyObject target) => (bool)target.GetValue(CacheEnabledProperty);
|
||||||
|
public static void SetCacheEnabled(DependencyObject target, bool value) => target.SetValue(CacheEnabledProperty, value);
|
||||||
|
|
||||||
|
public static readonly DependencyProperty IsLoadingSuspendedProperty = DependencyProperty.RegisterAttached(
|
||||||
|
"IsLoadingSuspended", typeof(bool), typeof(NetworkThumbnail),
|
||||||
|
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits, SuspensionChanged));
|
||||||
|
public static bool GetIsLoadingSuspended(DependencyObject target) => (bool)target.GetValue(IsLoadingSuspendedProperty);
|
||||||
|
public static void SetIsLoadingSuspended(DependencyObject target, bool value) => target.SetValue(IsLoadingSuspendedProperty, value);
|
||||||
|
|
||||||
|
private static void SuspensionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (d is not NetworkThumbnail image) return;
|
||||||
|
image.CancelLoading();
|
||||||
|
image.Source = null;
|
||||||
|
if (!(bool)e.NewValue) image.QueueRefresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly DependencyProperty UrlProperty = DependencyProperty.Register(nameof(Url), typeof(string), typeof(NetworkThumbnail), new PropertyMetadata(null, Changed));
|
||||||
|
public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.Register(nameof(Placeholder), typeof(ImageSource), typeof(NetworkThumbnail), new PropertyMetadata(null, Changed));
|
||||||
|
public string? Url { get => (string?)GetValue(UrlProperty); set => SetValue(UrlProperty, value); }
|
||||||
|
public ImageSource? Placeholder { get => (ImageSource?)GetValue(PlaceholderProperty); set => SetValue(PlaceholderProperty, value); }
|
||||||
|
private CancellationTokenSource? loading;
|
||||||
|
private bool refreshPending;
|
||||||
|
|
||||||
|
public NetworkThumbnail()
|
||||||
|
{
|
||||||
|
Loaded += (_, _) => QueueRefresh();
|
||||||
|
Unloaded += (_, _) => CancelLoading();
|
||||||
|
}
|
||||||
|
private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (d is not NetworkThumbnail image) return;
|
||||||
|
image.CancelLoading();
|
||||||
|
image.Source = GetIsLoadingSuspended(image) ? null : image.Placeholder;
|
||||||
|
// 回收行时多个绑定会依次变更,等本轮绑定完成后只加载一次新 URL。
|
||||||
|
image.QueueRefresh();
|
||||||
|
}
|
||||||
|
private void QueueRefresh()
|
||||||
|
{
|
||||||
|
if (!IsLoaded || refreshPending) return;
|
||||||
|
refreshPending = true;
|
||||||
|
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Loaded, new Action(() =>
|
||||||
|
{
|
||||||
|
refreshPending = false;
|
||||||
|
if (IsLoaded) StartLoading();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
private void CancelLoading()
|
||||||
|
{
|
||||||
|
loading?.Cancel(); loading?.Dispose(); loading = null;
|
||||||
|
}
|
||||||
|
private async void StartLoading()
|
||||||
|
{
|
||||||
|
CancelLoading(); ToolTip = null;
|
||||||
|
if (GetIsLoadingSuspended(this)) { Source = null; return; }
|
||||||
|
Source = Placeholder;
|
||||||
|
if (string.IsNullOrWhiteSpace(Url)) return;
|
||||||
|
var request = new CancellationTokenSource(); loading = request;
|
||||||
|
var token = request.Token;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var bitmap = await ThumbnailLoader.LoadAsync(Url, GetCacheEnabled(this), token);
|
||||||
|
if (!token.IsCancellationRequested && ReferenceEquals(loading, request)) Source = bitmap;
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
if (!token.IsCancellationRequested && ReferenceEquals(loading, request)) ToolTip = $"图片加载失败:{ex.Message}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class ThumbnailLoader
|
||||||
|
{
|
||||||
|
private static readonly HttpClient Client = new() { Timeout = TimeSpan.FromSeconds(12) };
|
||||||
|
private static readonly SemaphoreSlim Slots = new(4);
|
||||||
|
private static readonly object CacheLock = new();
|
||||||
|
private static readonly Dictionary<string, BitmapSource> Cache = new();
|
||||||
|
private static readonly Queue<string> CacheOrder = new();
|
||||||
|
private static long started, succeeded, failed, canceled, cacheHits, bytes, totalTicks;
|
||||||
|
private static int active, pending;
|
||||||
|
public static int Pending => Volatile.Read(ref pending);
|
||||||
|
public static string Statistics => $"网络图片:请求 {Interlocked.Read(ref started)} / 成功 {Interlocked.Read(ref succeeded)} / 失败 {Interlocked.Read(ref failed)} / 取消 {Interlocked.Read(ref canceled)} / 缓存命中 {Interlocked.Read(ref cacheHits)} | 活跃 {Volatile.Read(ref active)},待完成 {Pending} | 下载 {Interlocked.Read(ref bytes) / 1024d:N0} KB | 成功平均 {AverageMilliseconds:N0} ms";
|
||||||
|
private static double AverageMilliseconds => Interlocked.Read(ref succeeded) == 0 ? 0 : Interlocked.Read(ref totalTicks) * 1000d / Stopwatch.Frequency / Interlocked.Read(ref succeeded);
|
||||||
|
|
||||||
|
public static async Task<BitmapSource> LoadAsync(string url, bool cacheEnabled, CancellationToken token)
|
||||||
|
{
|
||||||
|
var cacheKey = url;
|
||||||
|
lock (CacheLock)
|
||||||
|
if (cacheEnabled && Cache.TryGetValue(cacheKey, out var cached)) { Interlocked.Increment(ref cacheHits); return cached; }
|
||||||
|
Interlocked.Increment(ref pending);
|
||||||
|
var acquired = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Slots.WaitAsync(token).ConfigureAwait(false); acquired = true;
|
||||||
|
Interlocked.Increment(ref active); Interlocked.Increment(ref started);
|
||||||
|
var watch = Stopwatch.StartNew();
|
||||||
|
var data = await Client.GetByteArrayAsync(url, token).ConfigureAwait(false);
|
||||||
|
Interlocked.Add(ref bytes, data.Length);
|
||||||
|
var bitmap = await Task.Run(() =>
|
||||||
|
{
|
||||||
|
token.ThrowIfCancellationRequested();
|
||||||
|
using var stream = new MemoryStream(data);
|
||||||
|
var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad;
|
||||||
|
image.DecodePixelWidth = 72; image.StreamSource = stream; image.EndInit(); image.Freeze();
|
||||||
|
return image;
|
||||||
|
}, token).ConfigureAwait(false);
|
||||||
|
token.ThrowIfCancellationRequested();
|
||||||
|
lock (CacheLock)
|
||||||
|
{
|
||||||
|
if (cacheEnabled && !Cache.ContainsKey(cacheKey))
|
||||||
|
{
|
||||||
|
if (Cache.Count >= 128) Cache.Remove(CacheOrder.Dequeue());
|
||||||
|
Cache.Add(cacheKey, bitmap); CacheOrder.Enqueue(cacheKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Interlocked.Increment(ref succeeded); Interlocked.Add(ref totalTicks, watch.ElapsedTicks);
|
||||||
|
return bitmap;
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (token.IsCancellationRequested) { Interlocked.Increment(ref canceled); throw; }
|
||||||
|
catch { Interlocked.Increment(ref failed); throw; }
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (acquired) { Interlocked.Decrement(ref active); Slots.Release(); }
|
||||||
|
Interlocked.Decrement(ref pending);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
<local:WindowBase x:Class="Store.Management.Framework.Controls.DialogWindow"
|
<local:WindowBase
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
x:Class="Store.Management.Framework.Controls.DialogWindow"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
xmlns:local="clr-namespace:Store.Management.Framework.Controls"
|
xmlns:local="clr-namespace:Store.Management.Framework.Controls"
|
||||||
mc:Ignorable="d"
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
Title="DialogWindow" Height="450" Width="800">
|
Title="{Binding Title}"
|
||||||
<Grid>
|
Width="800"
|
||||||
|
Height="450"
|
||||||
</Grid>
|
mc:Ignorable="d">
|
||||||
|
<Grid />
|
||||||
</local:WindowBase>
|
</local:WindowBase>
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
|
|
||||||
using MAX.Framework.Controls;
|
|
||||||
using MAX.Framework.Controls.Attach;
|
|
||||||
using Prism.Services.Dialogs;
|
using Prism.Services.Dialogs;
|
||||||
using Store.Management.Framework.Controls;
|
using Store.Management.Framework.Controls;
|
||||||
using Store.Management.Framework.Controls.Attach;
|
using Store.Management.Framework.Controls.Attach;
|
||||||
@@ -91,6 +89,8 @@ public partial class DialogWindow : WindowBase, IDialogWindow
|
|||||||
if (newContent is UserControl control)
|
if (newContent is UserControl control)
|
||||||
{
|
{
|
||||||
|
|
||||||
|
WindowStartupLocation = DialogWindowProperty.GetWindowStartupLocation(control);
|
||||||
|
|
||||||
Setter widthSetter = this.Style.Setters.OfType<Setter>().FirstOrDefault(a => a.Property == WidthProperty);
|
Setter widthSetter = this.Style.Setters.OfType<Setter>().FirstOrDefault(a => a.Property == WidthProperty);
|
||||||
if (widthSetter == null)
|
if (widthSetter == null)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
using MAX.Common.Helpers;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls
|
||||||
|
{
|
||||||
|
internal class HorizontalIconText : Control
|
||||||
|
{
|
||||||
|
|
||||||
|
public string Icon
|
||||||
|
{
|
||||||
|
get => (string)GetValue(IconProperty);
|
||||||
|
set => SetValue(IconProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly DependencyProperty IconProperty = DependencyProperty.Register(
|
||||||
|
nameof(Icon),
|
||||||
|
typeof(string),
|
||||||
|
typeof(HorizontalIconText),
|
||||||
|
new PropertyMetadata(null, OnOnIconChanged)
|
||||||
|
);
|
||||||
|
|
||||||
|
public bool ShowIcon
|
||||||
|
{
|
||||||
|
get => (bool)GetValue(ShowIconProperty);
|
||||||
|
private set => SetValue(ShowIconPropertyKey, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly DependencyPropertyKey ShowIconPropertyKey = DependencyProperty.RegisterReadOnly(
|
||||||
|
nameof(ShowIcon),
|
||||||
|
typeof(bool),
|
||||||
|
typeof(HorizontalIconText),
|
||||||
|
new PropertyMetadata(false)
|
||||||
|
);
|
||||||
|
|
||||||
|
public static readonly DependencyProperty ShowIconProperty = ShowIconPropertyKey.DependencyProperty;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public bool ShowSpace
|
||||||
|
{
|
||||||
|
get => (bool)GetValue(ShowSpaceProperty);
|
||||||
|
private set => SetValue(ShowSpacePropertyKey, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly DependencyPropertyKey ShowSpacePropertyKey = DependencyProperty.RegisterReadOnly(
|
||||||
|
nameof(ShowSpace),
|
||||||
|
typeof(bool),
|
||||||
|
typeof(HorizontalIconText),
|
||||||
|
new PropertyMetadata(true)
|
||||||
|
);
|
||||||
|
|
||||||
|
public static readonly DependencyProperty ShowSpaceProperty = ShowSpacePropertyKey.DependencyProperty;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public string Text
|
||||||
|
{
|
||||||
|
get => (string)GetValue(TextProperty);
|
||||||
|
set => SetValue(TextProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
|
||||||
|
nameof(Text),
|
||||||
|
typeof(string),
|
||||||
|
typeof(HorizontalIconText),
|
||||||
|
new PropertyMetadata(string.Empty)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public double IconSize
|
||||||
|
{
|
||||||
|
get => (double)GetValue(IconSizeProperty);
|
||||||
|
set => SetValue(IconSizeProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly DependencyProperty IconSizeProperty = DependencyProperty.Register(
|
||||||
|
nameof(IconSize),
|
||||||
|
typeof(double),
|
||||||
|
typeof(HorizontalIconText),
|
||||||
|
new PropertyMetadata(14d)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public double Spacing
|
||||||
|
{
|
||||||
|
get => (double)GetValue(SpacingProperty);
|
||||||
|
set => SetValue(SpacingProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly DependencyProperty SpacingProperty = DependencyProperty.Register(
|
||||||
|
nameof(Spacing),
|
||||||
|
typeof(double),
|
||||||
|
typeof(HorizontalIconText),
|
||||||
|
new PropertyMetadata(4d)
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
private static void OnOnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (d is HorizontalIconText view)
|
||||||
|
{
|
||||||
|
view.ShowIcon = view.Icon.IsNotBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
base.OnPropertyChanged(e);
|
||||||
|
if (e.Property == ShowSpaceProperty)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ShowSpace = ShowIcon && Text.IsNotBlank();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using PipeReviewReport.Resources.Fonts;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls
|
||||||
|
{
|
||||||
|
public class IconText : TextBlock
|
||||||
|
{
|
||||||
|
static IconText()
|
||||||
|
{
|
||||||
|
DefaultStyleKeyProperty.OverrideMetadata(typeof(IconText), new FrameworkPropertyMetadata(typeof(IconText)));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public IconNameEnum Icon
|
||||||
|
{
|
||||||
|
get => (IconNameEnum)GetValue(IconNameProperty);
|
||||||
|
set => SetValue(IconNameProperty, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly DependencyProperty IconNameProperty = DependencyProperty.Register(
|
||||||
|
nameof(Icon),
|
||||||
|
typeof(IconNameEnum),
|
||||||
|
typeof(IconText),
|
||||||
|
new PropertyMetadata(IconNameEnum.Empty, OnIconChanged)
|
||||||
|
);
|
||||||
|
|
||||||
|
private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (d is IconText self)
|
||||||
|
{
|
||||||
|
self.Text = self.Icon.GetGlyphString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using Prism.Services.Dialogs;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls;
|
||||||
|
|
||||||
|
internal static class ViewLifecycle
|
||||||
|
{
|
||||||
|
// 卸载时 DataContext 可能已改变,记录实际收到 OnLoaded 的实例。
|
||||||
|
private static readonly DependencyProperty LoadedViewModelProperty =
|
||||||
|
DependencyProperty.RegisterAttached("LoadedViewModel", typeof(ViewModelBase), typeof(ViewLifecycle));
|
||||||
|
|
||||||
|
internal static void Register()
|
||||||
|
{
|
||||||
|
foreach (Type type in new[] { typeof(UserControl), typeof(Window) })
|
||||||
|
{
|
||||||
|
FrameworkElement.DataContextProperty.OverrideMetadata(type,
|
||||||
|
new FrameworkPropertyMetadata(null, OnDataContextChanged));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void OnDataContextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (sender is Window window)
|
||||||
|
{
|
||||||
|
if (e.OldValue is ViewModelBase)
|
||||||
|
{
|
||||||
|
window.Activated -= OnActivated;
|
||||||
|
window.Deactivated -= OnDeactivated;
|
||||||
|
window.Closing -= OnClosing;
|
||||||
|
window.Closed -= OnClosed;
|
||||||
|
}
|
||||||
|
if (e.NewValue is ViewModelBase)
|
||||||
|
{
|
||||||
|
window.Activated += OnActivated;
|
||||||
|
window.Deactivated += OnDeactivated;
|
||||||
|
window.Closing += OnClosing;
|
||||||
|
window.Closed += OnClosed;
|
||||||
|
}
|
||||||
|
if (window is IDialogWindow) return; // Prism 弹窗由内容页接收加载与卸载。
|
||||||
|
}
|
||||||
|
var view = (FrameworkElement)sender;
|
||||||
|
if (e.OldValue is ViewModelBase)
|
||||||
|
{
|
||||||
|
view.Loaded -= OnLoaded;
|
||||||
|
view.Unloaded -= OnUnloaded;
|
||||||
|
}
|
||||||
|
if (e.NewValue is ViewModelBase)
|
||||||
|
{
|
||||||
|
view.Loaded += OnLoaded;
|
||||||
|
view.Unloaded += OnUnloaded;
|
||||||
|
}
|
||||||
|
if (view.IsLoaded || view.GetValue(LoadedViewModelProperty) != null)
|
||||||
|
UpdateViewModel(view);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void OnLoaded(object sender, RoutedEventArgs e)
|
||||||
|
=> UpdateViewModel((FrameworkElement)sender);
|
||||||
|
|
||||||
|
private static void OnActivated(object? sender, EventArgs e) => (((Window)sender!).DataContext as ViewModelBase)?.OnActivated();
|
||||||
|
private static void OnDeactivated(object? sender, EventArgs e) => (((Window)sender!).DataContext as ViewModelBase)?.OnDeactivated();
|
||||||
|
private static void OnClosing(object? sender, CancelEventArgs e) => (((Window)sender!).DataContext as ViewModelBase)?.OnClosing(e);
|
||||||
|
private static void OnClosed(object? sender, EventArgs e) => (((Window)sender!).DataContext as ViewModelBase)?.OnClosed();
|
||||||
|
|
||||||
|
private static void UpdateViewModel(FrameworkElement view)
|
||||||
|
{
|
||||||
|
// 共享父级 DataContext 的页眉、导航栏等子控件不拥有页面生命周期。
|
||||||
|
var source = DependencyPropertyHelper.GetValueSource(view, FrameworkElement.DataContextProperty);
|
||||||
|
var next = source.BaseValueSource == BaseValueSource.Inherited ? null : view.DataContext as ViewModelBase;
|
||||||
|
var previous = (ViewModelBase?)view.GetValue(LoadedViewModelProperty);
|
||||||
|
if (ReferenceEquals(previous, next)) return;
|
||||||
|
view.SetValue(LoadedViewModelProperty, next);
|
||||||
|
previous?.OnUnloaded();
|
||||||
|
next?.NotifyLoaded();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void OnUnloaded(object sender, RoutedEventArgs e)
|
||||||
|
{
|
||||||
|
var view = (FrameworkElement)sender;
|
||||||
|
var previous = (ViewModelBase?)view.GetValue(LoadedViewModelProperty);
|
||||||
|
view.ClearValue(LoadedViewModelProperty);
|
||||||
|
previous?.OnUnloaded();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using Prism.Mvvm;
|
||||||
|
using System.ComponentModel;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Controls;
|
||||||
|
|
||||||
|
public abstract class ViewModelBase : BindableBase
|
||||||
|
{
|
||||||
|
private bool hasLoaded;
|
||||||
|
|
||||||
|
internal void NotifyLoaded()
|
||||||
|
{
|
||||||
|
if (!hasLoaded)
|
||||||
|
{
|
||||||
|
hasLoaded = true;
|
||||||
|
OnLoadedOnce();
|
||||||
|
}
|
||||||
|
OnLoaded();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>当前实例首次加载时调用,先于 OnLoaded。</summary>
|
||||||
|
protected virtual void OnLoadedOnce() { }
|
||||||
|
protected internal virtual void OnLoaded() { }
|
||||||
|
protected internal virtual void OnUnloaded() { }
|
||||||
|
protected internal virtual void OnActivated() { }
|
||||||
|
protected internal virtual void OnDeactivated() { }
|
||||||
|
protected internal virtual void OnClosing(CancelEventArgs e) { }
|
||||||
|
protected internal virtual void OnClosed() { }
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
|
using MAX.Common.Helpers;
|
||||||
using MAX.Framework.Logger;
|
using MAX.Framework.Logger;
|
||||||
using NLog;
|
using NLog;
|
||||||
using Prism.Autofac;
|
using Prism.Autofac;
|
||||||
using Prism.Ioc;
|
using Prism.Ioc;
|
||||||
using Prism.Services.Dialogs;
|
using Prism.Services.Dialogs;
|
||||||
|
using Store.Management.Api;
|
||||||
using Store.Management.Framework.Configs;
|
using Store.Management.Framework.Configs;
|
||||||
using Store.Management.Framework.Extensions;
|
using Store.Management.Framework.Extensions;
|
||||||
using Store.Management.Framework.Services;
|
using Store.Management.Framework.Services;
|
||||||
@@ -14,137 +16,157 @@ namespace Store.Management.Framework;
|
|||||||
|
|
||||||
public abstract class FrameworkApplication : PrismApplication
|
public abstract class FrameworkApplication : PrismApplication
|
||||||
{
|
{
|
||||||
private Mutex? _mutex;
|
private Mutex? _mutex;
|
||||||
private bool _ownsMutex;
|
private bool _ownsMutex;
|
||||||
private int _fatalHandling;
|
private int _fatalHandling;
|
||||||
private int _shutdownRequested;
|
private int _shutdownRequested;
|
||||||
public static bool ShuttingDown { get; private set; }
|
public static bool ShuttingDown { get; private set; }
|
||||||
public static bool IsAppInitialized { get; private set; }
|
public static bool IsAppInitialized { get; private set; }
|
||||||
public static event Action<Exception>? FatalErrorRaised;
|
public static event Action<Exception>? FatalErrorRaised;
|
||||||
|
private IStatusBarService StatusBarService;
|
||||||
|
private IMessageBoxService MessageBoxService;
|
||||||
|
private static bool FatalShutdown = false;
|
||||||
|
static FrameworkApplication() => Controls.ViewLifecycle.Register();
|
||||||
|
|
||||||
protected FrameworkApplication()
|
protected FrameworkApplication()
|
||||||
{
|
{
|
||||||
DispatcherUnhandledException += OnDispatcherUnhandledException;
|
DispatcherUnhandledException += OnDispatcherUnhandledException;
|
||||||
AppDomain.CurrentDomain.UnhandledException += OnDomainUnhandledException;
|
AppDomain.CurrentDomain.UnhandledException += OnDomainUnhandledException;
|
||||||
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
|
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>返回 null 可允许多开;默认限制同一登录会话中的应用实例。</summary>
|
/// <summary>返回 null 可允许多开;默认限制同一登录会话中的应用实例。</summary>
|
||||||
public virtual string? GetMutexName() => @"Local\Store.Management";
|
public virtual string? GetMutexName() => @"Local\Store.Management";
|
||||||
|
|
||||||
protected override void OnStartup(StartupEventArgs e)
|
protected override void OnStartup(StartupEventArgs e)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
//string? name = GetMutexName();
|
//string? name = GetMutexName();
|
||||||
//if (!string.IsNullOrWhiteSpace(name))
|
//if (!string.IsNullOrWhiteSpace(name))
|
||||||
//{
|
//{
|
||||||
// _mutex = new Mutex(true, name, out _ownsMutex);
|
// _mutex = new Mutex(true, name, out _ownsMutex);
|
||||||
// if (!_ownsMutex)
|
// if (!_ownsMutex)
|
||||||
// {
|
// {
|
||||||
// MessageBox.Show("程序已在运行。", Config.AppName, MessageBoxButton.OK, MessageBoxImage.Information);
|
// MessageBox.Show("程序已在运行。", Config.AppName, MessageBoxButton.OK, MessageBoxImage.Information);
|
||||||
// Shutdown();
|
// Shutdown();
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
//}
|
//}
|
||||||
FolderConfig.Initialize();
|
FolderConfig.Initialize();
|
||||||
base.OnStartup(e);
|
base.OnStartup(e);
|
||||||
ApplicationLogService.Initialize();
|
ApplicationLogService.Initialize();
|
||||||
NLogger.Instance.Info($"软件启动:{Config.AppFullName},版本:{Config.GetFullVersionString()},会话:{Config.SessionID},启动时间:{Config.AppStartTime:O},Windows:{Config.WindowsVersion}");
|
NLogger.Instance.Info($"软件启动:{Config.AppFullName},版本:{Config.GetFullVersionString()},会话:{Config.SessionID},启动时间:{Config.AppStartTime:O},Windows:{Config.WindowsVersion}");
|
||||||
DISource.Resolver = Resolve;
|
DISource.Resolver = Resolve;
|
||||||
}
|
}
|
||||||
catch (Exception ex) { Fatal(ex); }
|
catch (Exception ex) { Fatal(ex); }
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialized()
|
protected override void OnInitialized()
|
||||||
{
|
{
|
||||||
base.OnInitialized();
|
base.OnInitialized();
|
||||||
IsAppInitialized = true;
|
IsAppInitialized = true;
|
||||||
NLogger.Instance.Info("软件初始化成功,进入主页面");
|
NLogger.Instance.Info("软件初始化成功,进入主页面");
|
||||||
}
|
StatusBarService = Container?.Resolve<IStatusBarService>();
|
||||||
|
MessageBoxService = Container?.Resolve<IMessageBoxService>();
|
||||||
|
}
|
||||||
|
|
||||||
protected override void RegisterRequiredTypes(IContainerRegistry registry)
|
protected override void RegisterRequiredTypes(IContainerRegistry registry)
|
||||||
{
|
{
|
||||||
base.RegisterRequiredTypes(registry);
|
base.RegisterRequiredTypes(registry);
|
||||||
registry.RegisterDialogWindow<Controls.DialogWindow>();
|
registry.RegisterDialogWindow<Controls.DialogWindow>();
|
||||||
}
|
}
|
||||||
|
|
||||||
private object Resolve(Type type, string name)
|
private object Resolve(Type type, string name)
|
||||||
{
|
{
|
||||||
if (type == null || Container is null) return null!;
|
if (type == null || Container is null) return null!;
|
||||||
return name != null ? Container.Resolve(type, name) : Container.Resolve(type);
|
return name != null ? Container.Resolve(type, name) : Container.Resolve(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||||
{
|
{
|
||||||
e.Handled = true;
|
e.Handled = true;
|
||||||
Fatal(e.Exception);
|
StatusBarService.Report(e.Exception.Message, StatusLevel.Error);
|
||||||
}
|
Fatal(e.Exception);
|
||||||
|
|
||||||
private void OnDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
}
|
||||||
{
|
|
||||||
Exception exception = e.ExceptionObject as Exception ?? new Exception(e.ExceptionObject?.ToString());
|
|
||||||
// CLR 终止期间同步记录,不等待 UI 线程。
|
|
||||||
if (e.IsTerminating) ApplicationLogService.WriteFatal(exception, "AppDomain.UnhandledException");
|
|
||||||
else Fatal(exception);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
|
private void OnDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
||||||
{
|
{
|
||||||
ApplicationLogService.WriteFatal(e.Exception, "TaskScheduler.UnobservedTaskException");
|
Exception exception = e.ExceptionObject as Exception ?? new Exception(e.ExceptionObject?.ToString());
|
||||||
e.SetObserved();
|
StatusBarService.Report(exception.Message, StatusLevel.Error);
|
||||||
}
|
// CLR 终止期间同步记录,不等待 UI 线程。
|
||||||
|
if (e.IsTerminating) ApplicationLogService.WriteFatal(exception, "AppDomain.UnhandledException");
|
||||||
|
else Fatal(exception);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>先同步保存报告,再通知订阅者并关闭应用。</summary>
|
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
|
||||||
public static void Fatal(Exception exception)
|
{
|
||||||
{
|
ApplicationLogService.WriteFatal(e.Exception, "TaskScheduler.UnobservedTaskException");
|
||||||
ArgumentNullException.ThrowIfNull(exception);
|
e.SetObserved();
|
||||||
string? path = ApplicationLogService.WriteFatal(exception, "Fatal");
|
}
|
||||||
if (Current is not FrameworkApplication app || Interlocked.Exchange(ref app._fatalHandling, 1) != 0) return;
|
|
||||||
foreach (Action<Exception> handler in FatalErrorRaised?.GetInvocationList() ?? [])
|
|
||||||
{
|
|
||||||
try { handler(exception); }
|
|
||||||
catch (Exception ex) { ApplicationLogService.WriteFatal(ex, "FatalErrorRaised"); }
|
|
||||||
}
|
|
||||||
void ShowErrorAndShutdown()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
MessageBox.Show($"软件发生致命错误,即将关闭。\n{exception.Message}\n\n日志:{path ?? "写入失败,请查看调试输出"}",
|
|
||||||
Config.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
|
|
||||||
}
|
|
||||||
finally { TotalShutdown(-1); }
|
|
||||||
}
|
|
||||||
if (app.Dispatcher.CheckAccess()) ShowErrorAndShutdown();
|
|
||||||
else if (!app.Dispatcher.HasShutdownStarted) app.Dispatcher.BeginInvoke((Action)ShowErrorAndShutdown);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>通过 WPF 正常退出,执行退出清理。</summary>
|
/// <summary>先同步保存报告,再通知订阅者并关闭应用。</summary>
|
||||||
public static void TotalShutdown(int exitCode = 0)
|
public void Fatal(Exception exception)
|
||||||
{
|
{
|
||||||
if (Current is not FrameworkApplication app || Interlocked.Exchange(ref app._shutdownRequested, 1) != 0) return;
|
ArgumentNullException.ThrowIfNull(exception);
|
||||||
ShuttingDown = true;
|
string? path = ApplicationLogService.WriteFatal(exception, "Fatal");
|
||||||
if (app.Dispatcher.CheckAccess()) app.Shutdown(exitCode);
|
if (Current is not FrameworkApplication app || Interlocked.Exchange(ref app._fatalHandling, 1) != 0) return;
|
||||||
else if (!app.Dispatcher.HasShutdownStarted) app.Dispatcher.BeginInvoke((Action)(() => app.Shutdown(exitCode)));
|
foreach (Action<Exception> handler in FatalErrorRaised?.GetInvocationList() ?? [])
|
||||||
}
|
{
|
||||||
|
try { handler(exception); }
|
||||||
|
catch (Exception ex) { ApplicationLogService.WriteFatal(ex, "FatalErrorRaised"); }
|
||||||
|
}
|
||||||
|
void ShowErrorAndShutdown()
|
||||||
|
{
|
||||||
|
if (FatalShutdown)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
MessageBox.Show($"软件发生致命错误,即将关闭。\n{exception.Message}\n\n日志:{path ?? "写入失败,请查看调试输出"}",
|
||||||
|
Config.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
|
||||||
|
}
|
||||||
|
finally { TotalShutdown(-1); }
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
MessageBoxService.ShowError(exception.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (app.Dispatcher.CheckAccess()) ShowErrorAndShutdown();
|
||||||
|
else if (!app.Dispatcher.HasShutdownStarted) app.Dispatcher.BeginInvoke((Action)ShowErrorAndShutdown);
|
||||||
|
}
|
||||||
|
|
||||||
protected override void OnExit(ExitEventArgs e)
|
/// <summary>通过 WPF 正常退出,执行退出清理。</summary>
|
||||||
{
|
public static void TotalShutdown(int exitCode = 0)
|
||||||
ShuttingDown = true;
|
{
|
||||||
try { base.OnExit(e); }
|
if (Current is not FrameworkApplication app || Interlocked.Exchange(ref app._shutdownRequested, 1) != 0) return;
|
||||||
finally
|
ShuttingDown = true;
|
||||||
{
|
if (app.Dispatcher.CheckAccess()) app.Shutdown(exitCode);
|
||||||
DispatcherUnhandledException -= OnDispatcherUnhandledException;
|
else if (!app.Dispatcher.HasShutdownStarted) app.Dispatcher.BeginInvoke((Action)(() => app.Shutdown(exitCode)));
|
||||||
AppDomain.CurrentDomain.UnhandledException -= OnDomainUnhandledException;
|
}
|
||||||
TaskScheduler.UnobservedTaskException -= OnUnobservedTaskException;
|
|
||||||
DISource.Resolver = null!;
|
protected override void OnExit(ExitEventArgs e)
|
||||||
try { if (_ownsMutex) _mutex?.ReleaseMutex(); }
|
{
|
||||||
finally
|
ShuttingDown = true;
|
||||||
{
|
try
|
||||||
_mutex?.Dispose();
|
{
|
||||||
try { NLogger.Instance.Info($"软件关闭,退出码:{e.ApplicationExitCode}"); }
|
try { Container?.Resolve<StoreApiClient>().Dispose(); }
|
||||||
finally { LogManager.Shutdown(); }
|
finally { base.OnExit(e); }
|
||||||
}
|
}
|
||||||
}
|
finally
|
||||||
}
|
{
|
||||||
|
DispatcherUnhandledException -= OnDispatcherUnhandledException;
|
||||||
|
AppDomain.CurrentDomain.UnhandledException -= OnDomainUnhandledException;
|
||||||
|
TaskScheduler.UnobservedTaskException -= OnUnobservedTaskException;
|
||||||
|
DISource.Resolver = null!;
|
||||||
|
try { if (_ownsMutex) _mutex?.ReleaseMutex(); }
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_mutex?.Dispose();
|
||||||
|
try { NLogger.Instance.Info($"软件关闭,退出码:{e.ApplicationExitCode}"); }
|
||||||
|
finally { LogManager.Shutdown(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Windows;
|
|
||||||
using System.ComponentModel;
|
|
||||||
|
|
||||||
namespace Store.Management.Framework.Interfaces
|
|
||||||
{
|
|
||||||
|
|
||||||
public interface IMessageBoxService
|
|
||||||
{
|
|
||||||
|
|
||||||
//MessageResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageIcon icon, MessageResult defaultResult);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
using Riok.Mapperly.Abstractions;
|
||||||
|
using Store.Management.Framework.ViewModels;
|
||||||
|
using Store.Management.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Mappers;
|
||||||
|
|
||||||
|
[Mapper]
|
||||||
|
public static partial class ShopMapper
|
||||||
|
{
|
||||||
|
public static partial IReadOnlyList<ShopItemViewModel> ToItemViewModels(IReadOnlyList<ShopInfo> shops);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using Riok.Mapperly.Abstractions;
|
||||||
|
using Store.Management.Framework.ViewModels;
|
||||||
|
using Store.Management.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Mappers;
|
||||||
|
|
||||||
|
[Mapper]
|
||||||
|
public static partial class UserMapper
|
||||||
|
{
|
||||||
|
public static partial UserItemViewModel ToItemViewModel(UserInfo user);
|
||||||
|
public static partial IReadOnlyList<UserItemViewModel> ToItemViewModels(IReadOnlyList<UserInfo> users);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
public class Navigation
|
||||||
|
{
|
||||||
|
public static string MainContext { get; } = nameof(MainContext);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
|
||||||
|
<Color x:Key="LightPrimaryColor">#F4EDF3</Color>
|
||||||
|
<Color x:Key="PrimaryColor">#98638F</Color>
|
||||||
|
<Color x:Key="DarkPrimaryColor">#784B70</Color>
|
||||||
|
|
||||||
|
<Color x:Key="LightDangerColor">#FBEFF0</Color>
|
||||||
|
<Color x:Key="DangerColor">#C35C64</Color>
|
||||||
|
<Color x:Key="DarkDangerColor">#A34A52</Color>
|
||||||
|
|
||||||
|
<Color x:Key="LightWarningColor">#FBF4E7</Color>
|
||||||
|
<Color x:Key="WarningColor">#A77725</Color>
|
||||||
|
<Color x:Key="DarkWarningColor">#855D1B</Color>
|
||||||
|
|
||||||
|
<Color x:Key="LightInfoColor">#F0F2F4</Color>
|
||||||
|
<Color x:Key="InfoColor">#69727D</Color>
|
||||||
|
<Color x:Key="DarkInfoColor">#59616B</Color>
|
||||||
|
|
||||||
|
<Color x:Key="LightSuccessColor">#EAF5F0</Color>
|
||||||
|
<Color x:Key="SuccessColor">#31856A</Color>
|
||||||
|
<Color x:Key="DarkSuccessColor">#276B55</Color>
|
||||||
|
|
||||||
|
<Color x:Key="PrimaryTextColor">#292731</Color>
|
||||||
|
<Color x:Key="SecondaryTextColor">#7C838C</Color>
|
||||||
|
<Color x:Key="ThirdlyTextColor">#A0A6AD</Color>
|
||||||
|
<Color x:Key="ReverseTextColor">#FFFFFF</Color>
|
||||||
|
<Color x:Key="TextIconColor">#FFFFFF</Color>
|
||||||
|
|
||||||
|
<Color x:Key="BorderColor">#E5E7EB</Color>
|
||||||
|
<Color x:Key="SecondaryBorderColor">#D1D5DB</Color>
|
||||||
|
<Color x:Key="BackgroundColor">#F5F6F7</Color>
|
||||||
|
<Color x:Key="RegionColor">#FFFFFF</Color>
|
||||||
|
<Color x:Key="SecondaryRegionColor">#F0F2F4</Color>
|
||||||
|
<Color x:Key="ThirdlyRegionColor">#FAFBFC</Color>
|
||||||
|
<Color x:Key="TitleColor">#98638F</Color>
|
||||||
|
<Color x:Key="SecondaryTitleColor">#784B70</Color>
|
||||||
|
|
||||||
|
<Color x:Key="DefaultColor">#FFFFFF</Color>
|
||||||
|
<Color x:Key="DarkDefaultColor">#F0F2F4</Color>
|
||||||
|
|
||||||
|
<Color x:Key="AccentColor">#98638F</Color>
|
||||||
|
<Color x:Key="DarkAccentColor">#784B70</Color>
|
||||||
|
|
||||||
|
<Color x:Key="DarkMaskColor">#20000000</Color>
|
||||||
|
<Color x:Key="DarkOpacityColor">#40000000</Color>
|
||||||
|
|
||||||
|
<SolidColorBrush x:Key="SelectedBackgroundBrush" Color="#F3EAF1" />
|
||||||
|
<SolidColorBrush x:Key="SelectedForegroundBrush" Color="#784B70" />
|
||||||
|
|
||||||
|
<Color x:Key="BackgrondColor1">#F7F8F9</Color>
|
||||||
|
<Color x:Key="BackgrondColor2">#F0F2F4</Color>
|
||||||
|
<Color x:Key="BackgrondColor3">#E5E7EB</Color>
|
||||||
|
<Color x:Key="BackgrondColor4">#D1D5DB</Color>
|
||||||
|
|
||||||
|
<SolidColorBrush x:Key="Background1" Color="{StaticResource BackgrondColor1}" />
|
||||||
|
<SolidColorBrush x:Key="Background2" Color="{StaticResource BackgrondColor2}" />
|
||||||
|
<SolidColorBrush x:Key="Background3" Color="{StaticResource BackgrondColor3}" />
|
||||||
|
<SolidColorBrush x:Key="Background4" Color="{StaticResource BackgrondColor4}" />
|
||||||
|
|
||||||
|
<Color x:Key="FunctionTypeColor">#98638F</Color>
|
||||||
|
<Color x:Key="VariableTypeColor">#31856A</Color>
|
||||||
|
<Color x:Key="ConstTypeColor">#A77725</Color>
|
||||||
|
|
||||||
|
<SolidColorBrush x:Key="FunctionTypeBrush" Color="{StaticResource FunctionTypeColor}" />
|
||||||
|
<SolidColorBrush x:Key="VariableTypeBrush" Color="{StaticResource VariableTypeColor}" />
|
||||||
|
<SolidColorBrush x:Key="ConstTypeBrush" Color="{StaticResource ConstTypeColor}" />
|
||||||
|
|
||||||
|
|
||||||
|
</ResourceDictionary>
|
||||||
Binary file not shown.
@@ -0,0 +1,65 @@
|
|||||||
|
<#@ template debug="false" hostspecific="true" language="C#" #>
|
||||||
|
<#@ assembly name="System.Core" #>
|
||||||
|
<#@ import namespace="System.Linq" #>
|
||||||
|
<#@ import namespace="System.IO" #>
|
||||||
|
<#@ import namespace="System.Text" #>
|
||||||
|
<#@ import namespace="System.Collections.Generic" #>
|
||||||
|
<#@ import namespace="System.Text.RegularExpressions" #>
|
||||||
|
<#@ output extension=".xaml" encoding="utf-8" #>
|
||||||
|
|
||||||
|
<#
|
||||||
|
|
||||||
|
StringBuilder FontString = new StringBuilder();
|
||||||
|
FontString.AppendLine("<ResourceDictionary");
|
||||||
|
FontString.AppendLine("\txmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"");
|
||||||
|
FontString.AppendLine("\txmlns:PresentationOptions=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation/options\"");
|
||||||
|
FontString.AppendLine("\txmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"");
|
||||||
|
FontString.AppendLine("\txmlns:sys=\"clr-namespace:System;assembly=mscorlib\"");
|
||||||
|
FontString.AppendLine("\t>");
|
||||||
|
FontString.AppendLine("");
|
||||||
|
FontString.AppendLine("");
|
||||||
|
|
||||||
|
string cssPath = this.Host.ResolvePath("iconfont.css");
|
||||||
|
string svgPath = this.Host.ResolvePath("iconfont.js");
|
||||||
|
|
||||||
|
if (File.Exists(cssPath))
|
||||||
|
{
|
||||||
|
string cssContent = File.ReadAllText(cssPath, Encoding.UTF8);
|
||||||
|
MatchCollection matchs = Regex.Matches(cssContent, "\\.icon-(?<name>.+?):before.+?\\{.+?content:.+?\"\\\\(?<value>e.+?)\";.+?\\}", RegexOptions.Singleline);
|
||||||
|
foreach (Match match in matchs)
|
||||||
|
{
|
||||||
|
string name = match.Groups["name"].Value;
|
||||||
|
//name = Regex.Replace(name,"(a-(\\d{4,}(.*)?_fluent_|SegoeFluentIconsRegular-))|(_regular_icon|$)","",RegexOptions.Singleline);
|
||||||
|
string value = match.Groups["value"].Value;
|
||||||
|
FontString.AppendLine(string.Format("\t<sys:String x:Key=\"txt-{0}\">&#x{1};</sys:String>", name, value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (File.Exists(svgPath))
|
||||||
|
{
|
||||||
|
FontString.AppendLine("");
|
||||||
|
FontString.AppendLine("");
|
||||||
|
|
||||||
|
string svgContent = File.ReadAllText(svgPath, Encoding.UTF8);
|
||||||
|
MatchCollection matchs = Regex.Matches(svgContent, "<symbol.+?id=\"(?<name>.+?)\".+?>(?<value>.+?)</symbol>");
|
||||||
|
foreach (Match match in matchs)
|
||||||
|
{
|
||||||
|
string name = match.Groups["name"].Value;
|
||||||
|
string symbol = match.Groups["value"].Value;
|
||||||
|
StringBuilder value =new StringBuilder();
|
||||||
|
MatchCollection pathMatchs = Regex.Matches(symbol,"<path.+?d=\"(?<value>.+?)\"");
|
||||||
|
foreach(Match pathMatch in pathMatchs)
|
||||||
|
{
|
||||||
|
value.AppendLine("\t\t"+pathMatch.Groups["value"].Value);
|
||||||
|
}
|
||||||
|
FontString.AppendLine(string.Format("\t<Geometry x:Key=\"{0}\" PresentationOptions:Freeze=\"True\">\n{1}\t</Geometry>", name, value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FontString.AppendLine("");
|
||||||
|
FontString.AppendLine("");
|
||||||
|
FontString.AppendLine("</ResourceDictionary>");
|
||||||
|
string content = FontString.ToString();
|
||||||
|
string savePath =Path.Combine(this.Host.ResolvePath(""),@"..\Themes\FontGeometry.xaml");
|
||||||
|
//File.WriteAllText(savePath,content,Encoding.UTF8);
|
||||||
|
#>
|
||||||
|
<#=content#>
|
||||||
|
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,284 @@
|
|||||||
|
<#@ template debug="false" hostspecific="true" language="C#" #>
|
||||||
|
<#@ assembly name="System.Core" #>
|
||||||
|
|
||||||
|
<#@ import namespace="System.Linq" #>
|
||||||
|
<#@ import namespace="System.Text" #>
|
||||||
|
<#@ import namespace="System.IO" #>
|
||||||
|
<#@ import namespace="System.Collections.Generic" #>
|
||||||
|
<#@ import namespace="System.Text.RegularExpressions" #>
|
||||||
|
<#@ import namespace="Microsoft.VisualStudio.TextTemplating" #>
|
||||||
|
|
||||||
|
<#@ assembly name="$(ProjectDir)\Resources\DLLs\IconResourcesGenerator.dll" #>
|
||||||
|
<#@ import namespace="IconResourcesGenerator" #>
|
||||||
|
|
||||||
|
<#@ output extension=".cs" encoding="utf-8" #>
|
||||||
|
|
||||||
|
<#
|
||||||
|
ITextTemplatingEngineHost host = this.Host;
|
||||||
|
|
||||||
|
string jsPath = host.ResolvePath("iconfont.js");
|
||||||
|
string cssPath = host.ResolvePath("iconfont.css");
|
||||||
|
|
||||||
|
string namespaceName = "PipeReviewReport.Resources.Fonts";
|
||||||
|
|
||||||
|
Generator generator = new Generator(jsPath, cssPath);
|
||||||
|
Dictionary<string, string> glyphToKey = generator.ExecuteGlyphToKey();
|
||||||
|
Dictionary<string, string> keyToGlyph = generator.ExecuteKeyToGlyph();
|
||||||
|
(Dictionary<string, string> simpleNameToKey, Dictionary<string, string> keyToSimpleName) = generator.ExecuteSimpleNameToKey();
|
||||||
|
|
||||||
|
#>
|
||||||
|
|
||||||
|
using System;
|
||||||
|
// using System.ComponentModel;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Data;
|
||||||
|
using System.Windows.Media;
|
||||||
|
|
||||||
|
namespace <#= namespaceName #>;
|
||||||
|
|
||||||
|
[SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
|
||||||
|
internal class __________________Temp__________________
|
||||||
|
{
|
||||||
|
[SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "<Pending>")]
|
||||||
|
private void Test()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图标名称枚举
|
||||||
|
/// </summary>
|
||||||
|
// [TypeConverter(typeof(EnumConverter))]
|
||||||
|
public enum IconNameEnum
|
||||||
|
{
|
||||||
|
Empty,
|
||||||
|
|
||||||
|
<#
|
||||||
|
foreach (var entry in simpleNameToKey)
|
||||||
|
{
|
||||||
|
#>
|
||||||
|
/// <summary>
|
||||||
|
/// <#= keyToGlyph[entry.Value] #>
|
||||||
|
/// <br/>
|
||||||
|
/// icon-<#= entry.Value #>
|
||||||
|
/// </summary>
|
||||||
|
<#= entry.Key #>,
|
||||||
|
|
||||||
|
<#
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static class IconNameEnumExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 根据图标名称枚举获取 Key
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="e">图标名称枚举</param>
|
||||||
|
/// <returns>注册到资源中的 Key</returns>
|
||||||
|
/// <exception cref="NotImplementedException"></exception>
|
||||||
|
public static string GetKey(this IconNameEnum e) {
|
||||||
|
return e switch
|
||||||
|
{
|
||||||
|
IconNameEnum.Empty => null,
|
||||||
|
<#
|
||||||
|
foreach (var entry in simpleNameToKey)
|
||||||
|
{
|
||||||
|
#>
|
||||||
|
IconNameEnum.<#= entry.Key #> => "icon-<#= entry.Value #>",
|
||||||
|
<#
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
_ => throw new NotImplementedException(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据图标名称获取 Glyph 枚举
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="e">图标名称枚举</param>
|
||||||
|
/// <returns>图标 Glyph 枚举</returns>
|
||||||
|
/// <exception cref="NotImplementedException"></exception>
|
||||||
|
public static IconGlyphEnum GetGlyphEnum(this IconNameEnum e) {
|
||||||
|
return e switch
|
||||||
|
{
|
||||||
|
IconNameEnum.Empty => IconGlyphEnum.Empty,
|
||||||
|
<#
|
||||||
|
foreach (var entry in simpleNameToKey)
|
||||||
|
{
|
||||||
|
#>
|
||||||
|
IconNameEnum.<#= entry.Key #> => IconGlyphEnum.<#= keyToGlyph[entry.Value] #>,
|
||||||
|
<#
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
_ => throw new NotImplementedException(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据图标名称获取 Glyph 字符串
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="e">图标名称枚举</param>
|
||||||
|
/// <returns>图标 Glyph 字符串</returns>
|
||||||
|
/// <exception cref="NotImplementedException"></exception>
|
||||||
|
public static string GetGlyphString(this IconNameEnum e) {
|
||||||
|
return e switch
|
||||||
|
{
|
||||||
|
IconNameEnum.Empty => string.Empty,
|
||||||
|
<#
|
||||||
|
foreach (var entry in simpleNameToKey)
|
||||||
|
{
|
||||||
|
#>
|
||||||
|
IconNameEnum.<#= entry.Key #> => "\u<#= keyToGlyph[entry.Value] #>",
|
||||||
|
<#
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
_ => throw new NotImplementedException(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetImageSourceKey(this IconNameEnum e) {
|
||||||
|
return GetKey(e) + "_Image";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 图标 Glyph 枚举
|
||||||
|
/// </summary>
|
||||||
|
// [TypeConverter(typeof(EnumConverter))]
|
||||||
|
public enum IconGlyphEnum
|
||||||
|
{
|
||||||
|
Empty,
|
||||||
|
|
||||||
|
<#
|
||||||
|
foreach (var entry in glyphToKey)
|
||||||
|
{
|
||||||
|
#>
|
||||||
|
/// <summary>
|
||||||
|
/// <#= keyToSimpleName[entry.Value] #>
|
||||||
|
/// <br/>
|
||||||
|
/// icon-<#= entry.Value #>
|
||||||
|
/// </summary>
|
||||||
|
<#= entry.Key #>,
|
||||||
|
|
||||||
|
<#
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class IconGlyphEnumExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 根据 Glyph 枚举获取 Key
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="e">Glyph 枚举</param>
|
||||||
|
/// <returns>注册到资源中的 Key</returns>
|
||||||
|
/// <exception cref="NotImplementedException"></exception>
|
||||||
|
public static string GetKey(this IconGlyphEnum e)
|
||||||
|
{
|
||||||
|
return e switch
|
||||||
|
{
|
||||||
|
IconGlyphEnum.Empty => null,
|
||||||
|
<#
|
||||||
|
foreach (var entry in glyphToKey)
|
||||||
|
{
|
||||||
|
#>
|
||||||
|
IconGlyphEnum.<#= entry.Key #> => "icon-<#= entry.Value #>",
|
||||||
|
<#
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
_ => throw new NotImplementedException(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据图标 Glyph 枚举获取图标名称枚举
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="e">图标 Glyph 枚举</param>
|
||||||
|
/// <returns>图标名称枚举</returns>
|
||||||
|
/// <exception cref="NotImplementedException"></exception>
|
||||||
|
public static IconNameEnum GetNameEnum(this IconGlyphEnum e) {
|
||||||
|
return e switch
|
||||||
|
{
|
||||||
|
IconGlyphEnum.Empty => IconNameEnum.Empty,
|
||||||
|
<#
|
||||||
|
foreach (var entry in glyphToKey)
|
||||||
|
{
|
||||||
|
#>
|
||||||
|
IconGlyphEnum.<#= entry.Key #> => IconNameEnum.<#= keyToSimpleName[entry.Value] #>,
|
||||||
|
<#
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
_ => throw new NotImplementedException(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据图标 Glyph 枚举获取 Glyph 字符串
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="e">图标 Glyph 枚举</param>
|
||||||
|
/// <returns>图标 Glyph 字符串</returns>
|
||||||
|
/// <exception cref="NotImplementedException"></exception>
|
||||||
|
public static string GetGlyphString(this IconGlyphEnum e) {
|
||||||
|
return e switch
|
||||||
|
{
|
||||||
|
IconGlyphEnum.Empty => string.Empty,
|
||||||
|
<#
|
||||||
|
foreach (var entry in glyphToKey)
|
||||||
|
{
|
||||||
|
#>
|
||||||
|
IconGlyphEnum.<#= entry.Key #> => "\u<#= keyToGlyph[entry.Value] #>",
|
||||||
|
<#
|
||||||
|
}
|
||||||
|
#>
|
||||||
|
_ => throw new NotImplementedException(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetImageSourceKey(this IconGlyphEnum e) {
|
||||||
|
return GetKey(e) + "_Image";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public class IconEnumNameToGlyphConverter : IValueConverter {
|
||||||
|
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||||
|
if (value is IconNameEnum nameEnum) {
|
||||||
|
return nameEnum.GetGlyphEnum();
|
||||||
|
}
|
||||||
|
return DependencyProperty.UnsetValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||||
|
if (value is IconGlyphEnum glyphEnum) {
|
||||||
|
return glyphEnum.GetNameEnum();
|
||||||
|
}
|
||||||
|
return DependencyProperty.UnsetValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class IconGlyphNameToNameConverter : IValueConverter {
|
||||||
|
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||||
|
if (value is IconGlyphEnum glyphEnum) {
|
||||||
|
return glyphEnum.GetNameEnum();
|
||||||
|
}
|
||||||
|
return DependencyProperty.UnsetValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||||
|
if (value is IconNameEnum nameEnum) {
|
||||||
|
return nameEnum.GetGlyphEnum();
|
||||||
|
}
|
||||||
|
return DependencyProperty.UnsetValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
|||||||
|
window._iconfont_svg_string_5223831='<svg><symbol id="icon-fapiao" viewBox="0 0 1024 1024"><path d="M170.666667 868.693333l98.346666-94.72a21.333333 21.333333 0 0 1 30.72 1.173334l98.176 110.122666 98.176-110.122666a21.333333 21.333333 0 0 1 31.829334 0l98.176 110.122666 98.176-110.122666a21.333333 21.333333 0 0 1 30.72-1.173334L853.333333 868.693333V128H170.666667v740.693333z m-42.666667 49.386667V106.709333C128 94.890667 137.706667 85.333333 149.333333 85.333333h725.333334c11.776 0 21.333333 9.642667 21.333333 21.184v811.541334a21.333333 21.333333 0 0 1-36.117333 16.149333l-118.506667-114.133333-99.349333 111.445333a21.333333 21.333333 0 0 1-31.850667 0L512 821.397333l-98.176 110.122667a21.333333 21.333333 0 0 1-31.850667 0l-99.349333-111.445333-118.485333 114.133333A21.333333 21.333333 0 0 1 128 918.08zM298.666667 320c0-11.776 9.493333-21.333333 21.184-21.333333h341.632c11.690667 0 21.184 9.472 21.184 21.333333 0 11.776-9.493333 21.333333-21.184 21.333333H319.850667A21.205333 21.205333 0 0 1 298.666667 320z m0 128c0-11.776 9.6-21.333333 21.482666-21.333333h255.701334c11.861333 0 21.482667 9.472 21.482666 21.333333 0 11.776-9.6 21.333333-21.482666 21.333333H320.149333A21.354667 21.354667 0 0 1 298.666667 448z m0 128c0-11.776 9.6-21.333333 21.482666-21.333333h255.701334c11.861333 0 21.482667 9.472 21.482666 21.333333 0 11.776-9.6 21.333333-21.482666 21.333333H320.149333A21.354667 21.354667 0 0 1 298.666667 576z" fill="#3D3D3D" ></path></symbol><symbol id="icon-calendar_work_week" viewBox="0 0 1024 1024"><path d="M330.666667 298.666667a32 32 0 0 0-32 32v170.666666c0 17.664 14.336 32 32 32h362.666666a32 32 0 0 0 32-32v-170.666666a32 32 0 0 0-32-32h-362.666666z m32 170.666666V362.666667h298.666666V469.333333h-298.666666z" ></path><path d="M757.333333 896A138.666667 138.666667 0 0 0 896 757.333333V266.666667A138.666667 138.666667 0 0 0 757.333333 128H266.666667A138.666667 138.666667 0 0 0 128 266.666667v490.666666A138.666667 138.666667 0 0 0 266.666667 896h490.666666zM832 266.666667v490.666666a74.666667 74.666667 0 0 1-74.666667 74.666667H266.666667a74.666667 74.666667 0 0 1-74.666667-74.666667V266.666667c0-41.216 33.450667-74.666667 74.666667-74.666667h490.666666c41.216 0 74.666667 33.450667 74.666667 74.666667z" ></path></symbol><symbol id="icon-document_endnote" viewBox="0 0 1024 1024"><path d="M234.666667 181.333333a32 32 0 0 1 32-32H512V341.333333a85.333333 85.333333 0 0 0 85.333333 85.333334h192v416a32 32 0 0 1-32 32H554.666667V938.666667h202.666666A96 96 0 0 0 853.333333 842.666667V412.330667c0-19.797333-7.850667-38.784-21.888-52.778667l-252.330666-252.330667A74.666667 74.666667 0 0 0 526.336 85.333333H266.666667A96 96 0 0 0 170.666667 181.333333V512h64V181.333333z m341.333333 160V194.56l168.106667 168.106667H597.333333a21.333333 21.333333 0 0 1-21.333333-21.333334zM192 586.666667a32 32 0 0 1-32 32H106.666667v298.666666h53.333333a32 32 0 0 1 0 64H106.666667A64 64 0 0 1 42.666667 917.333333v-298.666666A64 64 0 0 1 106.666667 554.666667h53.333333a32 32 0 0 1 32 32z" ></path><path d="M394.666667 618.666667a32 32 0 0 1 0-64h53.333333a64 64 0 0 1 64 64v298.666666a64 64 0 0 1-64 64H394.666667a32 32 0 0 1 0-64h53.333333v-298.666666H394.666667zM277.333333 714.666667a32 32 0 0 1 32 32V896a32 32 0 0 1-64 0v-149.333333a32 32 0 0 1 32-32zM277.333333 682.666667a32 32 0 1 0 0-64 32 32 0 0 0 0 64z" ></path></symbol><symbol id="icon-leaf_three" viewBox="0 0 1024 1024"><path d="M810.666667 320c0 22.186667-3.072 43.648-8.832 64h69.12C908.373333 384 938.666667 414.293333 938.666667 451.669333V661.333333a277.333333 277.333333 0 0 1-449.493334 217.429334L438.613333 929.28a32 32 0 1 1-45.226666-45.226667l50.517333-50.56a277.077333 277.077333 0 0 1-40.704-70.613333A256 256 0 0 1 96 512V320.597333C96 284.928 124.928 256 160.597333 256h189.568A234.752 234.752 0 0 1 576 85.333333h173.226667c33.92 0 61.44 27.52 61.44 61.44V320zM414.805333 263.765333a256.554667 256.554667 0 0 1 165.504 132.266667A277.290667 277.290667 0 0 1 661.333333 384h72.96c7.978667-19.754667 12.373333-41.386667 12.373334-64v-170.666667h-170.666667a170.752 170.752 0 0 0-161.194667 114.432z m120.021334 569.344A213.333333 213.333333 0 0 0 874.666667 661.333333v-209.664a3.669333 3.669333 0 0 0-3.669334-3.669333H661.333333a213.333333 213.333333 0 0 0-171.776 339.84l181.162667-181.12a32 32 0 1 1 45.226667 45.226667l-181.12 181.162666zM384 661.333333c0-25.258667 3.413333-49.749333 9.728-73.002666L276.053333 470.613333a32 32 0 1 1 45.226667-45.226666l98.901333 98.858666a278.698667 278.698667 0 0 1 101.333334-102.485333A192 192 0 0 0 352 320H160.384l-0.213333 0.170667a0.938667 0.938667 0 0 0-0.128 0.213333l-0.042667 0.213333V512a192 192 0 0 0 226.816 188.842667A279.765333 279.765333 0 0 1 384 661.333333z" ></path></symbol><symbol id="icon-re_order_dots_horizontal" viewBox="0 0 1024 1024"><path d="M298.666667 661.333333a64 64 0 1 1-128 0 64 64 0 0 1 128 0z m0-298.666666a64 64 0 1 1-128 0 64 64 0 0 1 128 0z m298.666666 298.666666a64 64 0 1 1-128 0 64 64 0 0 1 128 Line truncated
|
||||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
@@ -0,0 +1,291 @@
|
|||||||
|
<ResourceDictionary
|
||||||
|
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:f="clr-namespace:Store.Management.Framework.Controls"
|
||||||
|
xmlns:hc="https://handyorg.github.io/handycontrol"
|
||||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
|
xmlns:wpf="MAX.WPF"
|
||||||
|
mc:Ignorable="d">
|
||||||
|
<ResourceDictionary.MergedDictionaries>
|
||||||
|
<ResourceDictionary Source="Fonts/FontGeometry.xaml" />
|
||||||
|
<ResourceDictionary Source="pack://application:,,,/MAX.Common.WPF;component/Resources/Generic.xaml" />
|
||||||
|
<ResourceDictionary Source="/Store.Management.Framework;component/Controls/DataGridEx/DataGridEx.xaml" />
|
||||||
|
</ResourceDictionary.MergedDictionaries>
|
||||||
|
|
||||||
|
<Style
|
||||||
|
x:Key="IconButtonStyle"
|
||||||
|
BasedOn="{StaticResource ButtonCustom}"
|
||||||
|
TargetType="Button">
|
||||||
|
<Setter Property="Width" Value="32" />
|
||||||
|
<Setter Property="Height" Value="28" />
|
||||||
|
<Setter Property="Padding" Value="0" />
|
||||||
|
<Setter Property="Background" Value="Transparent" />
|
||||||
|
<Setter Property="BorderThickness" Value="0" />
|
||||||
|
<Setter Property="Cursor" Value="Hand" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
|
||||||
|
<!-- 表格搜索区:统一尺寸,窄窗口允许换行。 -->
|
||||||
|
<Style x:Key="TableSearchTextBoxStyle" BasedOn="{StaticResource TextBoxExtend}" TargetType="TextBox">
|
||||||
|
<Setter Property="Width" Value="180" />
|
||||||
|
<Setter Property="Height" Value="32" />
|
||||||
|
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="TableSearchComboBoxStyle" BasedOn="{StaticResource {x:Type ComboBox}}" TargetType="ComboBox">
|
||||||
|
<Setter Property="Width" Value="180" />
|
||||||
|
<Setter Property="Height" Value="32" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="TableSearchButtonStyle" BasedOn="{StaticResource {x:Type Button}}" TargetType="Button">
|
||||||
|
<Setter Property="Width" Value="80" />
|
||||||
|
<Setter Property="Height" Value="32" />
|
||||||
|
<Setter Property="Padding" Value="8,0" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="TableSearchPrimaryButtonStyle" BasedOn="{StaticResource ButtonPrimary}" TargetType="Button">
|
||||||
|
<Setter Property="Width" Value="80" />
|
||||||
|
<Setter Property="Height" Value="32" />
|
||||||
|
<Setter Property="Padding" Value="8,0" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="TableSearchBarStyle" TargetType="wpf:SpacingStackPanel">
|
||||||
|
<Style.Resources>
|
||||||
|
<Style BasedOn="{StaticResource TableSearchTextBoxStyle}" TargetType="TextBox" />
|
||||||
|
<Style BasedOn="{StaticResource TableSearchComboBoxStyle}" TargetType="ComboBox" />
|
||||||
|
<Style BasedOn="{StaticResource TableSearchButtonStyle}" TargetType="Button" />
|
||||||
|
</Style.Resources>
|
||||||
|
<Setter Property="MinHeight" Value="44" />
|
||||||
|
<Setter Property="Margin" Value="10,0" />
|
||||||
|
<Setter Property="Orientation" Value="Horizontal" />
|
||||||
|
<Setter Property="ChildWrapping" Value="True" />
|
||||||
|
<Setter Property="HorizontalSpacing" Value="8" />
|
||||||
|
<Setter Property="VerticalSpacing" Value="8" />
|
||||||
|
<Setter Property="ItemVerticalAlignment" Value="Center" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<FontFamily x:Key="IconPack">Fonts/iconfont.ttf#iconfont</FontFamily>
|
||||||
|
|
||||||
|
<Style BasedOn="{StaticResource DataGridExBaseStyle}" TargetType="{x:Type f:DataGridEx}">
|
||||||
|
<Setter Property="SelectedRowBackground" Value="{DynamicResource SelectedBackgroundBrush}" />
|
||||||
|
<Setter Property="SelectedRowForeground" Value="{DynamicResource SelectedForegroundBrush}" />
|
||||||
|
</Style>
|
||||||
|
<Style x:Key="TextBlockIcon" TargetType="{x:Type TextBlock}">
|
||||||
|
<Setter Property="FontFamily" Value="{StaticResource IconPack}" />
|
||||||
|
<Setter Property="HorizontalAlignment" Value="Center" />
|
||||||
|
<Setter Property="VerticalAlignment" Value="Center" />
|
||||||
|
<Setter Property="FontSize" Value="18" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style BasedOn="{StaticResource TextBlockIcon}" TargetType="{x:Type f:IconText}" />
|
||||||
|
<Style BasedOn="{StaticResource {x:Type MenuItem}}" TargetType="{x:Type MenuItem}">
|
||||||
|
<Setter Property="Width" Value="200" />
|
||||||
|
<Style.Resources>
|
||||||
|
<Style BasedOn="{StaticResource TextBlockIcon}" TargetType="{x:Type f:IconText}">
|
||||||
|
<Setter Property="FontSize" Value="16" />
|
||||||
|
</Style>
|
||||||
|
</Style.Resources>
|
||||||
|
</Style>
|
||||||
|
<Style
|
||||||
|
x:Key="WindowBase"
|
||||||
|
BasedOn="{StaticResource WindowWin10}"
|
||||||
|
TargetType="f:WindowBase">
|
||||||
|
<Setter Property="Background" Value="White" />
|
||||||
|
</Style>
|
||||||
|
<Style
|
||||||
|
x:Key="DialogWindowStyle"
|
||||||
|
BasedOn="{StaticResource WindowBase}"
|
||||||
|
TargetType="f:DialogWindow">
|
||||||
|
<Setter Property="Tag" Value="Default" />
|
||||||
|
<Setter Property="ResizeMode" Value="NoResize" />
|
||||||
|
<Setter Property="ShowInTaskbar" Value="False" />
|
||||||
|
<Setter Property="WindowChrome.GlassFrameThickness" Value="-1" />
|
||||||
|
</Style>
|
||||||
|
<Style BasedOn="{StaticResource WindowBase}" TargetType="f:WindowBase" />
|
||||||
|
<Style BasedOn="{StaticResource DialogWindowStyle}" TargetType="f:DialogWindow" />
|
||||||
|
|
||||||
|
|
||||||
|
<!--<Style x:Key="HorizontalSpacingPanel" TargetType="hc:UniformSpacingPanel">
|
||||||
|
<Setter Property="Orientation" Value="Horizontal" />
|
||||||
|
<Setter Property="HorizontalSpacing" Value="2" />
|
||||||
|
<Setter Property="ItemVerticalAlignment" Value="Center" />
|
||||||
|
</Style>-->
|
||||||
|
|
||||||
|
<!--<Style x:Key="HorizontalSpacingPanel2" TargetType="hc:UniformSpacingPanel">
|
||||||
|
<Setter Property="Orientation" Value="Horizontal" />
|
||||||
|
<Setter Property="HorizontalSpacing" Value="4" />
|
||||||
|
<Setter Property="ItemVerticalAlignment" Value="Center" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="VerticalSpacingPanel" TargetType="hc:UniformSpacingPanel">
|
||||||
|
<Setter Property="Orientation" Value="Vertical" />
|
||||||
|
<Setter Property="VerticalSpacing" Value="2" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="VerticalSpacingPanel2" TargetType="hc:UniformSpacingPanel">
|
||||||
|
<Setter Property="Orientation" Value="Vertical" />
|
||||||
|
<Setter Property="VerticalSpacing" Value="4" />
|
||||||
|
</Style>-->
|
||||||
|
|
||||||
|
|
||||||
|
<Style x:Key="HorizontalSpacingPanel" TargetType="wpf:SpacingStackPanel">
|
||||||
|
<Setter Property="Orientation" Value="Horizontal" />
|
||||||
|
<Setter Property="HorizontalSpacing" Value="2" />
|
||||||
|
<Setter Property="ItemVerticalAlignment" Value="Center" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="HorizontalSpacingPanel4" TargetType="wpf:SpacingStackPanel">
|
||||||
|
<Setter Property="Orientation" Value="Horizontal" />
|
||||||
|
<Setter Property="HorizontalSpacing" Value="4" />
|
||||||
|
<Setter Property="ItemVerticalAlignment" Value="Center" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="HorizontalSpacingPanel8" TargetType="wpf:SpacingStackPanel">
|
||||||
|
<Setter Property="Orientation" Value="Horizontal" />
|
||||||
|
<Setter Property="HorizontalSpacing" Value="8" />
|
||||||
|
<Setter Property="ItemVerticalAlignment" Value="Center" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
|
||||||
|
<Style x:Key="VerticalSpacingPanel" TargetType="wpf:SpacingStackPanel">
|
||||||
|
<Setter Property="Orientation" Value="Vertical" />
|
||||||
|
<Setter Property="VerticalSpacing" Value="2" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style x:Key="VerticalSpacingPanel4" TargetType="wpf:SpacingStackPanel">
|
||||||
|
<Setter Property="Orientation" Value="Vertical" />
|
||||||
|
<Setter Property="VerticalSpacing" Value="4" />
|
||||||
|
</Style>
|
||||||
|
<Style x:Key="VerticalSpacingPanel8" TargetType="wpf:SpacingStackPanel">
|
||||||
|
<Setter Property="Orientation" Value="Vertical" />
|
||||||
|
<Setter Property="VerticalSpacing" Value="8" />
|
||||||
|
</Style>
|
||||||
|
<Style
|
||||||
|
x:Key="HorizontalIconText"
|
||||||
|
BasedOn="{StaticResource BaseStyle}"
|
||||||
|
TargetType="f:HorizontalIconText">
|
||||||
|
<Setter Property="Spacing" Value="4" />
|
||||||
|
<Setter Property="Focusable" Value="False" />
|
||||||
|
<Setter Property="IconSize" Value="16" />
|
||||||
|
<Setter Property="Template">
|
||||||
|
<Setter.Value>
|
||||||
|
<ControlTemplate TargetType="f:HorizontalIconText">
|
||||||
|
<Border>
|
||||||
|
<DockPanel>
|
||||||
|
<TextBlock
|
||||||
|
FontSize="{TemplateBinding IconSize}"
|
||||||
|
Style="{StaticResource TextBlockIcon}"
|
||||||
|
Text="{TemplateBinding Icon}"
|
||||||
|
Visibility="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ShowIcon, Converter={StaticResource Boolean2VisibilityConverter}}" />
|
||||||
|
<Border Width="{TemplateBinding Spacing}" Visibility="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ShowSpace, Converter={StaticResource Boolean2VisibilityConverter}}" />
|
||||||
|
<TextBlock
|
||||||
|
VerticalAlignment="Center"
|
||||||
|
Text="{TemplateBinding Text}"
|
||||||
|
TextTrimming="CharacterEllipsis" />
|
||||||
|
</DockPanel>
|
||||||
|
</Border>
|
||||||
|
</ControlTemplate>
|
||||||
|
</Setter.Value>
|
||||||
|
</Setter>
|
||||||
|
</Style>
|
||||||
|
<Style BasedOn="{StaticResource HorizontalIconText}" TargetType="f:HorizontalIconText" />
|
||||||
|
|
||||||
|
<Style x:Key="Dialog" TargetType="UserControl">
|
||||||
|
<Setter Property="Padding" Value="0" />
|
||||||
|
<Setter Property="Focusable" Value="True" />
|
||||||
|
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
|
||||||
|
<Setter Property="Background" Value="White" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style
|
||||||
|
x:Key="DialogButtonStyle"
|
||||||
|
BasedOn="{StaticResource ButtonDefault}"
|
||||||
|
TargetType="Button">
|
||||||
|
<Setter Property="MinWidth" Value="70" />
|
||||||
|
<Setter Property="Height" Value="26" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
<Style
|
||||||
|
x:Key="DialogPrimaryButtonStyle"
|
||||||
|
BasedOn="{StaticResource ButtonPrimary}"
|
||||||
|
TargetType="Button">
|
||||||
|
<Setter Property="MinWidth" Value="70" />
|
||||||
|
<Setter Property="Height" Value="26" />
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<Style
|
||||||
|
x:Key="ConfirmDialog"
|
||||||
|
BasedOn="{StaticResource Dialog}"
|
||||||
|
TargetType="UserControl">
|
||||||
|
<Setter Property="Background" Value="White" />
|
||||||
|
<Setter Property="Padding" Value="10" />
|
||||||
|
<Setter Property="Template">
|
||||||
|
<Setter.Value>
|
||||||
|
<ControlTemplate TargetType="UserControl">
|
||||||
|
<Border
|
||||||
|
d:DataContext="{d:DesignInstance Type=f:ConfirmDialogViewModel}"
|
||||||
|
Background="{TemplateBinding Background}"
|
||||||
|
BorderBrush="{TemplateBinding BorderBrush}"
|
||||||
|
BorderThickness="{TemplateBinding BorderThickness}">
|
||||||
|
<Grid>
|
||||||
|
<Grid.RowDefinitions>
|
||||||
|
<RowDefinition Height="*" />
|
||||||
|
<RowDefinition Height="auto" />
|
||||||
|
</Grid.RowDefinitions>
|
||||||
|
|
||||||
|
<Border Padding="{TemplateBinding Padding}">
|
||||||
|
<ContentPresenter />
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<Border
|
||||||
|
Grid.Row="1"
|
||||||
|
Padding="5,8"
|
||||||
|
BorderBrush="{StaticResource BorderBrush}"
|
||||||
|
BorderThickness="0,1,0,0">
|
||||||
|
<Grid>
|
||||||
|
<Border Padding="2,0">
|
||||||
|
<f:HorizontalIconText
|
||||||
|
d:Text="错误信息"
|
||||||
|
Foreground="{StaticResource DangerBrush}"
|
||||||
|
Icon="{StaticResource txt-warning}"
|
||||||
|
Text="{Binding ErrorMsg}"
|
||||||
|
Visibility="{Binding ErrorMsg, Converter={StaticResource String2VisibilityConverter}}" />
|
||||||
|
</Border>
|
||||||
|
<wpf:SpacingStackPanel HorizontalAlignment="Right" Style="{StaticResource HorizontalSpacingPanel4}">
|
||||||
|
<Button Command="{Binding ConfirmCommand}" Style="{StaticResource DialogPrimaryButtonStyle}">
|
||||||
|
<TextBlock Text="确认" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
HorizontalAlignment="Right"
|
||||||
|
Command="{Binding CancelCommand}"
|
||||||
|
Style="{StaticResource DialogButtonStyle}">
|
||||||
|
<TextBlock Text="取消" />
|
||||||
|
</Button>
|
||||||
|
</wpf:SpacingStackPanel>
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
</ControlTemplate>
|
||||||
|
</Setter.Value>
|
||||||
|
</Setter>
|
||||||
|
</Style>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<Style
|
||||||
|
x:Key="VerticalAlignment"
|
||||||
|
BasedOn="{StaticResource TitleContentBaseStyle}"
|
||||||
|
TargetType="wpf:TitleContent">
|
||||||
|
<Setter Property="VerticalAlignment" Value="Center" />
|
||||||
|
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||||
|
<Setter Property="TitleVerticalAlignment" Value="Center" />
|
||||||
|
<Setter Property="Placement" Value="Left" />
|
||||||
|
</Style>
|
||||||
|
</ResourceDictionary>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Store.Management.Api;
|
||||||
|
using Store.Management.Api.Authentication;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Services;
|
||||||
|
|
||||||
|
/// <summary>用户登录服务,复用应用 API 客户端的认证会话。</summary>
|
||||||
|
public interface ILoginService
|
||||||
|
{
|
||||||
|
/// <summary>提交登录;passwordHash 为 UTF-8 密码的 32 位大写 MD5。</summary>
|
||||||
|
Task LoginAsync(string userName, string passwordHash, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class LoginService(StoreApiClient apiClient) : ILoginService, ISingletonDependency
|
||||||
|
{
|
||||||
|
public Task LoginAsync(string userName, string passwordHash, CancellationToken cancellationToken = default)
|
||||||
|
=> apiClient.Auth.LoginAsync(new LoginRequest
|
||||||
|
{
|
||||||
|
UserName = userName.Trim(),
|
||||||
|
Password = passwordHash
|
||||||
|
}, cancellationToken);
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
using MAX.Core.Commons;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
public interface IMessageBoxService
|
||||||
|
{
|
||||||
|
MessageResult Show(string messageBoxText, string caption, MessageButton button, MessageIcon icon, MessageResult defaultResult);
|
||||||
|
|
||||||
|
|
||||||
|
void ShowInformation(string content);
|
||||||
|
void ShowWarning(string content);
|
||||||
|
void ShowError(string content);
|
||||||
|
void ShowError(string content, Exception exception);
|
||||||
|
bool ShowYesNoQuestion(string content);
|
||||||
|
bool ShowYesNoWarning(string content);
|
||||||
|
bool ShowYesNoError(string content);
|
||||||
|
bool ShowOkCancelQuestion(string content);
|
||||||
|
bool ShowOkCancelWarning(string content);
|
||||||
|
bool ShowOkCancelError(string content);
|
||||||
|
MessageResult ShowYesNoCancelQuestion(string content);
|
||||||
|
MessageResult ShowYesNoCancelWarning(string content);
|
||||||
|
MessageResult ShowYesNoCancelError(string content);
|
||||||
|
}
|
||||||
|
}
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using System.Windows;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
public static class MessageBoxEnumsConverter
|
||||||
|
{
|
||||||
|
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
public static bool? ToBool(this MessageBoxResult result)
|
||||||
|
{
|
||||||
|
switch (result)
|
||||||
|
{
|
||||||
|
case MessageBoxResult.Cancel: return null;
|
||||||
|
case MessageBoxResult.No: return false;
|
||||||
|
default: return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
public static bool? ToBool(this MessageResult result)
|
||||||
|
{
|
||||||
|
switch (result)
|
||||||
|
{
|
||||||
|
case MessageResult.Cancel: return null;
|
||||||
|
case MessageResult.No: return false;
|
||||||
|
default: return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
public static MessageBoxResult ToMessageBoxResult(this MessageResult result)
|
||||||
|
{
|
||||||
|
switch (result)
|
||||||
|
{
|
||||||
|
case MessageResult.Cancel: return MessageBoxResult.Cancel;
|
||||||
|
case MessageResult.No: return MessageBoxResult.No;
|
||||||
|
case MessageResult.Yes: return MessageBoxResult.Yes;
|
||||||
|
case MessageResult.OK: return MessageBoxResult.OK;
|
||||||
|
default: return MessageBoxResult.None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
public static MessageResult ToMessageResult(this MessageBoxResult result)
|
||||||
|
{
|
||||||
|
switch (result)
|
||||||
|
{
|
||||||
|
case MessageBoxResult.Cancel: return MessageResult.Cancel;
|
||||||
|
case MessageBoxResult.No: return MessageResult.No;
|
||||||
|
case MessageBoxResult.Yes: return MessageResult.Yes;
|
||||||
|
case MessageBoxResult.OK: return MessageResult.OK;
|
||||||
|
default: return MessageResult.None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
public static MessageBoxButton ToMessageBoxButton(this MessageButton button)
|
||||||
|
{
|
||||||
|
switch (button)
|
||||||
|
{
|
||||||
|
case MessageButton.OKCancel: return MessageBoxButton.OKCancel;
|
||||||
|
case MessageButton.YesNo: return MessageBoxButton.YesNo;
|
||||||
|
case MessageButton.YesNoCancel: return MessageBoxButton.YesNoCancel;
|
||||||
|
default: return MessageBoxButton.OK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
public static MessageButton ToMessageButton(this MessageBoxButton button)
|
||||||
|
{
|
||||||
|
switch (button)
|
||||||
|
{
|
||||||
|
case MessageBoxButton.OKCancel: return MessageButton.OKCancel;
|
||||||
|
case MessageBoxButton.YesNo: return MessageButton.YesNo;
|
||||||
|
case MessageBoxButton.YesNoCancel: return MessageButton.YesNoCancel;
|
||||||
|
default: return MessageButton.OK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
public static MessageBoxImage ToMessageBoxImage(this MessageIcon icon)
|
||||||
|
{
|
||||||
|
switch (icon)
|
||||||
|
{
|
||||||
|
case MessageIcon.Error: return MessageBoxImage.Error;
|
||||||
|
case MessageIcon.Information: return MessageBoxImage.Information;
|
||||||
|
case MessageIcon.Question: return MessageBoxImage.Question;
|
||||||
|
case MessageIcon.Warning: return MessageBoxImage.Warning;
|
||||||
|
default: return MessageBoxImage.None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
|
||||||
|
public static MessageIcon ToMessageIcon(this MessageBoxImage icon)
|
||||||
|
{
|
||||||
|
switch (icon)
|
||||||
|
{
|
||||||
|
case MessageBoxImage.Error: return MessageIcon.Error;
|
||||||
|
case MessageBoxImage.Information: return MessageIcon.Information;
|
||||||
|
case MessageBoxImage.Question: return MessageIcon.Question;
|
||||||
|
case MessageBoxImage.Warning: return MessageIcon.Warning;
|
||||||
|
default: return MessageIcon.None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Store.Management.Framework.Configs;
|
||||||
|
using System.Windows;
|
||||||
|
using MessageBox = HandyControl.Controls.MessageBox;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
public class MessageBoxService : IMessageBoxService, ISingletonDependency
|
||||||
|
{
|
||||||
|
protected readonly Guid id = Guid.NewGuid();
|
||||||
|
|
||||||
|
public string MessageTitle { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public MessageBoxService()
|
||||||
|
{
|
||||||
|
MessageTitle = AppConfig.AppDisplayName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual MessageResult Show(string messageBoxText, string caption, MessageButton button, MessageIcon icon, MessageResult defaultResult)
|
||||||
|
{
|
||||||
|
Window? window = Application.Current?.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
|
||||||
|
if (window is null)
|
||||||
|
{
|
||||||
|
return MessageBox.Show(
|
||||||
|
messageBoxText: messageBoxText,
|
||||||
|
caption: caption,
|
||||||
|
button: button.ToMessageBoxButton(),
|
||||||
|
icon: icon.ToMessageBoxImage(),
|
||||||
|
defaultResult: defaultResult.ToMessageBoxResult()
|
||||||
|
).ToMessageResult();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return MessageBox.Show(
|
||||||
|
owner: window,
|
||||||
|
messageBoxText: messageBoxText,
|
||||||
|
caption: caption,
|
||||||
|
button: button.ToMessageBoxButton(),
|
||||||
|
icon: icon.ToMessageBoxImage(),
|
||||||
|
defaultResult: defaultResult.ToMessageBoxResult()
|
||||||
|
).ToMessageResult();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ShowInformation(string content)
|
||||||
|
{
|
||||||
|
this.ShowMessage(content, MessageTitle, MessageButton.OK, MessageIcon.Information, MessageResult.OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ShowWarning(string content)
|
||||||
|
{
|
||||||
|
this.ShowMessage(content, MessageTitle, MessageButton.OK, MessageIcon.Warning, MessageResult.OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ShowError(string content, Exception exception)
|
||||||
|
{
|
||||||
|
if (exception is null)
|
||||||
|
{
|
||||||
|
ShowError(content);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
this.ShowMessage(content + "\n" + exception.Message, MessageTitle, MessageButton.OK, MessageIcon.Error, MessageResult.OK);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ShowError(string content)
|
||||||
|
{
|
||||||
|
this.ShowMessage(content, MessageTitle, MessageButton.OK, MessageIcon.Error, MessageResult.OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ShowYesNoQuestion(string content)
|
||||||
|
{
|
||||||
|
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.YesNo, MessageIcon.Question, MessageResult.No);
|
||||||
|
return result == MessageResult.Yes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ShowYesNoWarning(string content)
|
||||||
|
{
|
||||||
|
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.YesNo, MessageIcon.Warning, MessageResult.No);
|
||||||
|
return result == MessageResult.Yes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ShowYesNoError(string content)
|
||||||
|
{
|
||||||
|
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.YesNo, MessageIcon.Error, MessageResult.No);
|
||||||
|
return result == MessageResult.Yes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ShowOkCancelQuestion(string content)
|
||||||
|
{
|
||||||
|
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.OKCancel, MessageIcon.Question, MessageResult.OK);
|
||||||
|
return result == MessageResult.OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ShowOkCancelWarning(string content)
|
||||||
|
{
|
||||||
|
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.OKCancel, MessageIcon.Warning, MessageResult.OK);
|
||||||
|
return result == MessageResult.OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ShowOkCancelError(string content)
|
||||||
|
{
|
||||||
|
MessageResult result = this.ShowMessage(content, MessageTitle, MessageButton.OKCancel, MessageIcon.Error, MessageResult.OK);
|
||||||
|
return result == MessageResult.OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MessageResult ShowYesNoCancelQuestion(string content)
|
||||||
|
{
|
||||||
|
return this.ShowMessage(content, MessageTitle, MessageButton.YesNoCancel, MessageIcon.Question, MessageResult.Cancel);
|
||||||
|
}
|
||||||
|
|
||||||
|
public MessageResult ShowYesNoCancelWarning(string content)
|
||||||
|
{
|
||||||
|
return this.ShowMessage(content, MessageTitle, MessageButton.YesNoCancel, MessageIcon.Warning, MessageResult.Cancel);
|
||||||
|
}
|
||||||
|
|
||||||
|
public MessageResult ShowYesNoCancelError(string content)
|
||||||
|
{
|
||||||
|
return this.ShowMessage(content, MessageTitle, MessageButton.YesNoCancel, MessageIcon.Error, MessageResult.Cancel);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
public static class MessageBoxServiceExtensions
|
||||||
|
{
|
||||||
|
extension(IMessageBoxService service)
|
||||||
|
{
|
||||||
|
public MessageResult ShowMessage(string messageBoxText, string caption, MessageButton button, MessageIcon icon, MessageResult defaultResult)
|
||||||
|
{
|
||||||
|
VerifyService(service);
|
||||||
|
return service.Show(messageBoxText, caption, button, icon, defaultResult);
|
||||||
|
}
|
||||||
|
public bool? ShowMessage(string messageBoxText)
|
||||||
|
{
|
||||||
|
return service.ShowMessage(messageBoxText, string.Empty);
|
||||||
|
}
|
||||||
|
public bool? ShowMessage(string messageBoxText, string caption)
|
||||||
|
{
|
||||||
|
return service.ShowMessage(messageBoxText, caption, MessageButton.OK).ToBool();
|
||||||
|
}
|
||||||
|
public MessageResult ShowMessage(string messageBoxText, string caption, MessageButton button)
|
||||||
|
{
|
||||||
|
return service.ShowMessage(messageBoxText, caption, button, MessageIcon.None);
|
||||||
|
}
|
||||||
|
public MessageResult ShowMessage(string messageBoxText, string caption, MessageButton button, MessageIcon icon)
|
||||||
|
{
|
||||||
|
VerifyService(service);
|
||||||
|
return service.Show(messageBoxText, caption, button, icon, MessageResult.None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void VerifyService(IMessageBoxService service)
|
||||||
|
{
|
||||||
|
if (service == null)
|
||||||
|
throw new ArgumentNullException(nameof(service));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
public enum MessageButton
|
||||||
|
{
|
||||||
|
OK, OKCancel, YesNoCancel, YesNo,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
public enum MessageIcon
|
||||||
|
{
|
||||||
|
None, Error, Question, Warning, Information,
|
||||||
|
Hand = Error, Stop = Error, Exclamation = Warning, Asterisk = Information
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
public enum MessageResult
|
||||||
|
{
|
||||||
|
None, OK, Cancel, Yes, No,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Store.Management.Api;
|
||||||
|
using Store.Management.Api.Models;
|
||||||
|
using Store.Management.Api.Shops;
|
||||||
|
using Store.Management.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Services;
|
||||||
|
|
||||||
|
public interface IShopService
|
||||||
|
{
|
||||||
|
Task<IReadOnlyList<ShopCookieInfo>> GetCookiesAsync(string shopId, CancellationToken cancellationToken = default);
|
||||||
|
Task<PageResult<ShopInfo>> SearchAsync(ShopQueryRequest request, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class ShopService(StoreApiClient client) : IShopService, ISingletonDependency
|
||||||
|
{
|
||||||
|
public Task<IReadOnlyList<ShopCookieInfo>> GetCookiesAsync(string shopId, CancellationToken cancellationToken = default)
|
||||||
|
=> client.Shops.GetCookiesAsync(shopId, cancellationToken);
|
||||||
|
|
||||||
|
public Task<PageResult<ShopInfo>> SearchAsync(ShopQueryRequest request, CancellationToken cancellationToken = default)
|
||||||
|
=> client.Shops.SearchAsync(request, cancellationToken);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
using MAX.Common.WPF.Helpers;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Prism.Mvvm;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Services;
|
||||||
|
|
||||||
|
public enum StatusLevel
|
||||||
|
{
|
||||||
|
Info,
|
||||||
|
Success,
|
||||||
|
Warning,
|
||||||
|
Error
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record StatusBarMessage(string Text, StatusLevel Level, int? Progress);
|
||||||
|
|
||||||
|
/// <summary>各页面共享主窗口底部的最新状态。</summary>
|
||||||
|
public interface IStatusBarService
|
||||||
|
{
|
||||||
|
StatusBarMessage Current { get; }
|
||||||
|
|
||||||
|
/// <summary>发布一条状态。进度范围为 0 到 100,省略时隐藏进度条。</summary>
|
||||||
|
void Report(string text, StatusLevel level = StatusLevel.Info, int? progress = null);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class StatusBarService : BindableBase, IStatusBarService, ISingletonDependency
|
||||||
|
{
|
||||||
|
private StatusBarMessage _current = new("就绪", StatusLevel.Info, null);
|
||||||
|
public StatusBarMessage Current
|
||||||
|
{
|
||||||
|
get => _current;
|
||||||
|
private set => SetProperty(ref _current, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Report(string text, StatusLevel level = StatusLevel.Info, int? progress = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(text);
|
||||||
|
if (progress is < 0 or > 100)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(progress), "进度必须在 0 到 100 之间。");
|
||||||
|
}
|
||||||
|
DispatcherHelper.RunInDispatcher(() => Current = new StatusBarMessage(text, level, progress));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
using Store.Management.Models;
|
||||||
|
using MAX.Core.DependencyInjection;
|
||||||
|
using Store.Management.Api;
|
||||||
|
using Store.Management.Api.Users;
|
||||||
|
using Store.Management.Api.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.Services;
|
||||||
|
|
||||||
|
public interface IUserService
|
||||||
|
{
|
||||||
|
Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default);
|
||||||
|
Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default);
|
||||||
|
Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default);
|
||||||
|
Task<UserInfo> UpdateBillingAsync(UserBillingUpdateRequest request, CancellationToken cancellationToken = default);
|
||||||
|
Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken cancellationToken = default);
|
||||||
|
Task DeleteAsync(int id, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class UserService(StoreApiClient client) : IUserService, ISingletonDependency
|
||||||
|
{
|
||||||
|
public Task<PageResult<UserInfo>> SearchAsync(UserSearchRequest request, CancellationToken cancellationToken = default)
|
||||||
|
=> client.Users.SearchAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
public Task<UserInfo> CreateAsync(UserCreateRequest request, CancellationToken cancellationToken = default)
|
||||||
|
=> client.Users.CreateAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
public Task<UserInfo> UpdateAsync(UserUpdateRequest request, CancellationToken cancellationToken = default)
|
||||||
|
=> client.Users.UpdateAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
public Task<UserInfo> UpdateBillingAsync(UserBillingUpdateRequest request, CancellationToken cancellationToken = default)
|
||||||
|
=> client.Users.UpdateBillingAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
public Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken cancellationToken = default)
|
||||||
|
=> client.Users.ChangePasswordAsync(request, cancellationToken);
|
||||||
|
|
||||||
|
public Task DeleteAsync(int id, CancellationToken cancellationToken = default)
|
||||||
|
=> client.Users.DeleteAsync(id, cancellationToken);
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
using Autofac;
|
||||||
|
using MAX.Common.WPF.Converters;
|
||||||
|
using MAX.Common.WPF.Utilities;
|
||||||
|
using MAX.Core;
|
||||||
|
using MAX.Core.Autofac;
|
||||||
|
using MAX.Framework.Interfaces;
|
||||||
|
using Store.Management.Api;
|
||||||
|
using Store.Management.Framework.Extensions;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework
|
||||||
|
{
|
||||||
|
internal class Startup : IStartup
|
||||||
|
{
|
||||||
|
public int Priority => IntPriority.High;
|
||||||
|
|
||||||
|
public void Initialize()
|
||||||
|
{
|
||||||
|
EnumDisplayConverter.EnumDisplayManager = new EnumDisplayManagerWPF(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Register(ContainerBuilder builder)
|
||||||
|
{
|
||||||
|
var client = new StoreApiClient(new ApiClientOptions
|
||||||
|
{
|
||||||
|
BaseUrl = new Uri("http://localhost:14312/api/")
|
||||||
|
});
|
||||||
|
builder.Register(_ => client).SingleInstance().PreserveExistingDefaults();
|
||||||
|
|
||||||
|
DISource.Resolver = Resolve;
|
||||||
|
}
|
||||||
|
protected virtual object? Resolve(Type? type, string? name)
|
||||||
|
{
|
||||||
|
if (type == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IocManager.Container is not null)
|
||||||
|
{
|
||||||
|
if (name != null)
|
||||||
|
{
|
||||||
|
if (IocManager.Container.IsRegisteredWithName(name, type))
|
||||||
|
{
|
||||||
|
return IocManager.Container.ResolveNamed(name, type);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return IocManager.Resolve(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Activator.CreateInstance(type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,14 +10,49 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<None Remove="Resources\Fonts\iconfont.ttf" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Store.Management.Models\Store.Management.Models.csproj" />
|
||||||
|
<PackageReference Include="Riok.Mapperly" Version="4.3.1" PrivateAssets="all" />
|
||||||
<PackageReference Include="HandyControl" Version="3.6.2.1" />
|
<PackageReference Include="HandyControl" Version="3.6.2.1" />
|
||||||
<PackageReference Include="MAX.Common.WPF" Version="1.4.23" />
|
<PackageReference Include="MAX.Common.WPF" Version="1.4.23" />
|
||||||
|
<ProjectReference Include="..\Store.Management.Api\Store.Management.Api.csproj" />
|
||||||
<ProjectReference Include="..\Core\MAX.Core\MAX.Core.csproj" />
|
<ProjectReference Include="..\Core\MAX.Core\MAX.Core.csproj" />
|
||||||
<ProjectReference Include="..\Core\MAX.Framework\MAX.Framework.csproj" />
|
<ProjectReference Include="..\Core\MAX.Framework\MAX.Framework.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<Folder Include="Controls\DataGridEx\" />
|
||||||
<Folder Include="DependencyInjection\" />
|
<Folder Include="DependencyInjection\" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Resource Include="Resources\Fonts\iconfont.ttf" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="Resources\Fonts\FontGeometry.tt">
|
||||||
|
<Generator>TextTemplatingFileGenerator</Generator>
|
||||||
|
<LastGenOutput>FontGeometry.xaml</LastGenOutput>
|
||||||
|
</None>
|
||||||
|
<None Update="Resources\Fonts\IconEnum.tt">
|
||||||
|
<Generator>TextTemplatingFileGenerator</Generator>
|
||||||
|
<LastGenOutput>IconEnum.cs</LastGenOutput>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Update="Resources\Fonts\IconEnum.cs">
|
||||||
|
<DesignTime>True</DesignTime>
|
||||||
|
<AutoGen>True</AutoGen>
|
||||||
|
<DependentUpon>IconEnum.tt</DependentUpon>
|
||||||
|
</Compile>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace Store.Management.Framework.ViewModels;
|
||||||
|
|
||||||
|
public sealed class ShopItemViewModel
|
||||||
|
{
|
||||||
|
public int Id { get; init; }
|
||||||
|
public string? UserName { get; init; }
|
||||||
|
public string? ShopId { get; init; }
|
||||||
|
public string? ShopAccount { get; init; }
|
||||||
|
public string? LoginStatus { get; init; }
|
||||||
|
public bool IsLoggedOut => LoginStatus?.Contains("未登录", StringComparison.Ordinal) == true;
|
||||||
|
public string? CompanyName { get; init; }
|
||||||
|
public string? Notes { get; init; }
|
||||||
|
public string? GroupName { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using Store.Management.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.Framework.ViewModels;
|
||||||
|
|
||||||
|
public sealed class UserItemViewModel
|
||||||
|
{
|
||||||
|
public int Id { get; init; }
|
||||||
|
public string UserName { get; init; } = "";
|
||||||
|
public string? NickName { get; init; }
|
||||||
|
public string? Mobile { get; init; }
|
||||||
|
public string? CompanyName { get; init; }
|
||||||
|
public string? Notes { get; init; }
|
||||||
|
public string? ParentUserName { get; init; }
|
||||||
|
public int GroupId { get; init; }
|
||||||
|
public UserGroup? Group => GroupId is >= byte.MinValue and <= byte.MaxValue ? (UserGroup)GroupId : null;
|
||||||
|
public UserAdminLevel? SaLevel { get; init; }
|
||||||
|
public string? OemId { get; init; }
|
||||||
|
public string? Authority { get; init; }
|
||||||
|
public int ShopPointsPerMonth { get; init; }
|
||||||
|
public decimal? PostagePerOrder { get; init; }
|
||||||
|
public decimal? RefundPostagePerOrder { get; init; }
|
||||||
|
public decimal? GiftOemAmountPerOrder { get; init; }
|
||||||
|
public decimal? SyncLogisticsPerOrder { get; init; }
|
||||||
|
public decimal Points { get; init; }
|
||||||
|
public decimal? Balance { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
namespace Store.Management.Models;
|
||||||
|
|
||||||
|
public sealed record CurrentUser(string UserName, string? NickName);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Store.Management.Models;
|
||||||
|
|
||||||
|
public sealed class LoginResult
|
||||||
|
{
|
||||||
|
public string TokenType { get; init; } = "Bearer";
|
||||||
|
public string Token { get; init; } = "";
|
||||||
|
public uint ExpiresInMinutes { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace Store.Management.Models;
|
||||||
|
|
||||||
|
public sealed class ShopCookieInfo
|
||||||
|
{
|
||||||
|
public required string ShopId { get; init; }
|
||||||
|
public required string Cookies { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace Store.Management.Models;
|
||||||
|
|
||||||
|
/// <summary>商铺列表所需的服务端字段。</summary>
|
||||||
|
public sealed class ShopInfo
|
||||||
|
{
|
||||||
|
public int Id { get; init; }
|
||||||
|
public string? UserName { get; init; }
|
||||||
|
public string? ShopId { get; init; }
|
||||||
|
public string? ShopAccount { get; init; }
|
||||||
|
public string? LoginStatus { get; init; }
|
||||||
|
public string? CompanyName { get; init; }
|
||||||
|
public string? Notes { get; init; }
|
||||||
|
public string? GroupName { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace Store.Management.Models;
|
||||||
|
|
||||||
|
public enum UserAdminLevel : short
|
||||||
|
{
|
||||||
|
[System.ComponentModel.Description("普通用户")] Normal = 0,
|
||||||
|
[System.ComponentModel.Description("超级管理员")] SuperAdmin = 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace Store.Management.Models;
|
||||||
|
|
||||||
|
public enum UserGroup : byte
|
||||||
|
{
|
||||||
|
/// <summary>主号。</summary>
|
||||||
|
[System.ComponentModel.Description("主号")] MainAccount = 3,
|
||||||
|
/// <summary>客服。</summary>
|
||||||
|
[System.ComponentModel.Description("客服")] CustomerService = 4,
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
namespace Store.Management.Models;
|
||||||
|
|
||||||
|
/// <summary>管理端当前使用的用户资料字段;不接收密码。</summary>
|
||||||
|
public sealed class UserInfo
|
||||||
|
{
|
||||||
|
public int Id { get; init; }
|
||||||
|
public string UserName { get; init; } = "";
|
||||||
|
public string? NickName { get; init; }
|
||||||
|
public string? Mobile { get; init; }
|
||||||
|
public string? CompanyName { get; init; }
|
||||||
|
public string? Notes { get; init; }
|
||||||
|
public string? ParentUserName { get; init; }
|
||||||
|
public int GroupId { get; init; }
|
||||||
|
public UserAdminLevel? SaLevel { get; init; }
|
||||||
|
public string? OemId { get; init; }
|
||||||
|
public string? Authority { get; init; }
|
||||||
|
public int ShopPointsPerMonth { get; init; }
|
||||||
|
public decimal? PostagePerOrder { get; init; }
|
||||||
|
public decimal? RefundPostagePerOrder { get; init; }
|
||||||
|
public decimal? GiftOemAmountPerOrder { get; init; }
|
||||||
|
public decimal? SyncLogisticsPerOrder { get; init; }
|
||||||
|
public decimal Points { get; init; }
|
||||||
|
public decimal? Balance { get; init; }
|
||||||
|
}
|
||||||
@@ -5,17 +5,15 @@
|
|||||||
xmlns:mf="clr-namespace:Store.Management.Framework;assembly=Store.Management.Framework">
|
xmlns:mf="clr-namespace:Store.Management.Framework;assembly=Store.Management.Framework">
|
||||||
<Application.Resources>
|
<Application.Resources>
|
||||||
<ResourceDictionary>
|
<ResourceDictionary>
|
||||||
<SolidColorBrush x:Key="PrimaryBrush" Color="#3267C8" />
|
|
||||||
<SolidColorBrush x:Key="TextIconBrush" Color="#FFFFFF" />
|
|
||||||
<SolidColorBrush x:Key="BackgroundBrush" Color="#FFFFFF" />
|
|
||||||
<Style x:Key="DialogWindowStyle" TargetType="Window">
|
|
||||||
<Setter Property="ResizeMode" Value="NoResize" />
|
|
||||||
</Style>
|
|
||||||
|
|
||||||
<ResourceDictionary.MergedDictionaries>
|
<ResourceDictionary.MergedDictionaries>
|
||||||
<ResourceDictionary Source="pack://application:,,,/Store.Management.Framework;component/Resources/HandyControlBasic.xaml" />
|
<ResourceDictionary Source="pack://application:,,,/Store.Management.Framework;component/Resources/HandyControlBasic.xaml" />
|
||||||
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml" />
|
<ResourceDictionary Source="/Store.Management.Framework;component/Resources/Colors.xaml" />
|
||||||
|
|
||||||
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" />
|
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" />
|
||||||
|
<ResourceDictionary Source="pack://application:,,,/Store.Management.Framework;component/Resources/FrameworkTheme.xaml" />
|
||||||
|
|
||||||
</ResourceDictionary.MergedDictionaries>
|
</ResourceDictionary.MergedDictionaries>
|
||||||
</ResourceDictionary>
|
</ResourceDictionary>
|
||||||
</Application.Resources>
|
</Application.Resources>
|
||||||
|
|||||||
@@ -1,72 +1,110 @@
|
|||||||
using Prism.Ioc;
|
|
||||||
using Prism.Services.Dialogs;
|
|
||||||
using MAX.Notification;
|
using MAX.Notification;
|
||||||
using Store.Management.Notifications;
|
using Prism.Ioc;
|
||||||
|
using Prism.Mvvm;
|
||||||
|
using Prism.Services.Dialogs;
|
||||||
using Store.Management.Framework;
|
using Store.Management.Framework;
|
||||||
|
using Store.Management.Notifications;
|
||||||
using Store.Management.Services;
|
using Store.Management.Services;
|
||||||
using Store.Management.ViewModels;
|
using Store.Management.ViewModels;
|
||||||
using Store.Management.Views;
|
using Store.Management.Views;
|
||||||
|
using Store.Management.Views.Dialogs;
|
||||||
|
using System.Diagnostics;
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
using Store.Management.Api;
|
|
||||||
namespace Store.Management;
|
namespace Store.Management;
|
||||||
public partial class App : FrameworkApplication
|
public partial class App : FrameworkApplication
|
||||||
{
|
{
|
||||||
private readonly StoreApiClient? _apiClient;
|
private AppSplashScreen _appSplashScreen;
|
||||||
|
protected override Window CreateShell()
|
||||||
public App() { }
|
|
||||||
|
|
||||||
public App(StoreApiClient apiClient) => _apiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient));
|
|
||||||
|
|
||||||
private StoreApiClient CreateApiClient() => _apiClient ?? new(new ApiClientOptions
|
|
||||||
{
|
{
|
||||||
BaseUrl = new Uri("http://localhost:14312/api/")
|
if (Environment.GetCommandLineArgs().Contains("--grid-demo"))
|
||||||
});
|
{
|
||||||
|
return new Framework.Controls.WindowBase
|
||||||
protected override Window CreateShell() => null!;
|
|
||||||
|
|
||||||
protected override void OnInitialized()
|
|
||||||
{
|
|
||||||
base.OnInitialized();
|
|
||||||
// 登录弹窗关闭与主窗口创建之间不触发 WPF 的最后窗口退出。
|
|
||||||
ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
|
||||||
Container.Resolve<IDialogService>().ShowDialog(
|
|
||||||
nameof(LoginWindow), new DialogParameters(), result =>
|
|
||||||
{
|
{
|
||||||
if (result.Result != ButtonResult.OK)
|
Title = "DataGridEx 控件测试", Width = 1360, Height = 800,
|
||||||
{
|
MinWidth = 900, MinHeight = 560,
|
||||||
Shutdown();
|
WindowStartupLocation = WindowStartupLocation.CenterScreen,
|
||||||
return;
|
Content = new DataGridTestView()
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
return Container.Resolve<MainWindow>();
|
||||||
|
}
|
||||||
|
protected override void OnStartup(StartupEventArgs e)
|
||||||
|
{
|
||||||
|
_appSplashScreen = new()
|
||||||
|
{
|
||||||
|
CloseCallBack = () =>
|
||||||
|
{
|
||||||
|
base.OnStartup(e);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
_appSplashScreen.ShowDialog();
|
||||||
|
}
|
||||||
|
protected override async void OnInitialized()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//await LoadModules();
|
||||||
|
base.OnInitialized();
|
||||||
|
|
||||||
MainWindow = Container.Resolve<MainWindow>();
|
_appSplashScreen.Close();
|
||||||
ShutdownMode = ShutdownMode.OnMainWindowClose;
|
_appSplashScreen = null;
|
||||||
MainWindow.Show();
|
}
|
||||||
});
|
catch (Exception ex)
|
||||||
}
|
{
|
||||||
|
Fatal(ex);
|
||||||
|
Debug.WriteLine(ex);
|
||||||
|
}
|
||||||
|
|
||||||
protected override void RegisterTypes(IContainerRegistry registry)
|
//base.OnInitialized();
|
||||||
|
//// 登录弹窗关闭与主窗口创建之间不触发 WPF 的最后窗口退出。
|
||||||
|
//ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
||||||
|
//Container.Resolve<IDialogService>().ShowDialog(
|
||||||
|
// nameof(LoginWindow), new DialogParameters(), result =>
|
||||||
|
// {
|
||||||
|
// if (result.Result != ButtonResult.OK)
|
||||||
|
// {
|
||||||
|
// Shutdown();
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// MainWindow = Container.Resolve<MainWindow>();
|
||||||
|
// ShutdownMode = ShutdownMode.OnMainWindowClose;
|
||||||
|
// MainWindow.Show();
|
||||||
|
// });
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void RegisterTypes(IContainerRegistry containerRegistry)
|
||||||
{
|
{
|
||||||
registry.RegisterInstance(CreateApiClient());
|
|
||||||
registry.Register<LoginViewModel>(provider => new LoginViewModel(provider.Resolve<StoreApiClient>().Auth));
|
|
||||||
registry.RegisterSingleton<SingletonProbe>();
|
|
||||||
registry.Register<TransientProbe>();
|
|
||||||
registry.RegisterSingleton<NotificationExampleState>();
|
|
||||||
registry.Register<IPublisher>(provider => new NotificationPublisher(
|
|
||||||
new PrismNotificationServiceProvider(provider)));
|
|
||||||
// 显式提供处理器集合,展示一条通知分发给多个业务模块。
|
|
||||||
registry.Register<IEnumerable<INotificationHandler<ProductSavedNotification>>>(provider =>
|
|
||||||
new INotificationHandler<ProductSavedNotification>[]
|
|
||||||
{
|
|
||||||
new ProductCacheHandler(provider.Resolve<NotificationExampleState>()),
|
|
||||||
new ProductAuditHandler(provider.Resolve<NotificationExampleState>())
|
|
||||||
});
|
|
||||||
registry.RegisterDialog<LoginWindow, LoginViewModel>();
|
|
||||||
registry.RegisterDialog<FrameworkTestDialog, FrameworkTestDialogViewModel>();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override void OnExit(ExitEventArgs e)
|
containerRegistry.RegisterDialogWindow<Framework.Controls.DialogWindow>();
|
||||||
{
|
containerRegistry.RegisterDialog<UserBillingDialog, UserBillingDialogViewModel>();
|
||||||
try { Container?.Resolve<StoreApiClient>().Dispose(); }
|
containerRegistry.RegisterDialog<UserEditorDialog, UserEditorDialogViewModel>();
|
||||||
finally { base.OnExit(e); }
|
|
||||||
}
|
containerRegistry.RegisterDialog<DataGridTestView, DataGridTestViewModel>();
|
||||||
|
|
||||||
|
ViewModelLocationProvider.Register<MainWindow, MainViewModel>();
|
||||||
|
containerRegistry.RegisterDialog<LoginWindow, LoginViewModel>();
|
||||||
|
|
||||||
|
|
||||||
|
containerRegistry.RegisterForNavigation<UserManagementPage, UserManagementPageViewModel>(nameof(UserManagementPage));
|
||||||
|
containerRegistry.RegisterForNavigation<ShopManagementView, ShopManagementViewModel>(nameof(ShopManagementView));
|
||||||
|
containerRegistry.RegisterForNavigation<DataGridTestView, DataGridTestViewModel>(nameof(DataGridTestView));
|
||||||
|
|
||||||
|
|
||||||
|
// registry.RegisterSingleton<SingletonProbe>();
|
||||||
|
// registry.Register<TransientProbe>();
|
||||||
|
// registry.RegisterSingleton<NotificationExampleState>();
|
||||||
|
// registry.Register<IPublisher>(provider => new NotificationPublisher(
|
||||||
|
// new PrismNotificationServiceProvider(provider)));
|
||||||
|
// // 显式提供处理器集合,展示一条通知分发给多个业务模块。
|
||||||
|
// registry.Register<IEnumerable<INotificationHandler<ProductSavedNotification>>>(provider =>
|
||||||
|
// new INotificationHandler<ProductSavedNotification>[]
|
||||||
|
// {
|
||||||
|
// new ProductCacheHandler(provider.Resolve<NotificationExampleState>()),
|
||||||
|
// new ProductAuditHandler(provider.Resolve<NotificationExampleState>())
|
||||||
|
// });
|
||||||
|
// registry.RegisterDialog<LoginWindow, LoginViewModel>();
|
||||||
|
// registry.RegisterDialog<FrameworkTestDialog, FrameworkTestDialogViewModel>();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<Window
|
|
||||||
x:Class="Store.Management.MainWindow"
|
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
||||||
xmlns:views="clr-namespace:Store.Management.Views"
|
|
||||||
Title="Store.Management · 框架能力测试"
|
|
||||||
Width="960"
|
|
||||||
Height="720"
|
|
||||||
MinWidth="720"
|
|
||||||
MinHeight="560"
|
|
||||||
WindowStartupLocation="CenterScreen">
|
|
||||||
<views:FrameworkTestPage />
|
|
||||||
</Window>
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
using System.Windows;
|
|
||||||
namespace Store.Management;
|
|
||||||
public partial class MainWindow : Window
|
|
||||||
{
|
|
||||||
public MainWindow() => InitializeComponent();
|
|
||||||
}
|
|
||||||
@@ -2,11 +2,14 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>WinExe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<UseWPF>true</UseWPF>
|
<UseWPF>true</UseWPF>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Bogus" Version="35.6.5" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Store.Management.Framework\Store.Management.Framework.csproj" />
|
<ProjectReference Include="..\Store.Management.Framework\Store.Management.Framework.csproj" />
|
||||||
<ProjectReference Include="..\Store.Management.Api\Store.Management.Api.csproj" />
|
<ProjectReference Include="..\Store.Management.Api\Store.Management.Api.csproj" />
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
using Bogus;
|
||||||
|
using Prism.Commands;
|
||||||
|
using Prism.Mvvm;
|
||||||
|
using Store.Management.Framework.Controls;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.Windows.Data;
|
||||||
|
|
||||||
|
namespace Store.Management.ViewModels;
|
||||||
|
|
||||||
|
/// <summary>固定随机种子的离线样例;不请求真实 API。</summary>
|
||||||
|
public sealed class DataGridTestViewModel : ConfirmDialogViewModel
|
||||||
|
{
|
||||||
|
public Store.Management.Framework.ViewModels.LoadingStatus LoadingStatus { get; } = new();
|
||||||
|
public const int SearchTextLimit = 250;
|
||||||
|
private readonly List<DemoStore> stores;
|
||||||
|
private IReadOnlyList<DemoStore> searchResults = [];
|
||||||
|
private readonly List<DemoStore> pageItems = [];
|
||||||
|
private string localKeyword = string.Empty;
|
||||||
|
private string backendKeyword = string.Empty;
|
||||||
|
private readonly ListCollectionView currentItems;
|
||||||
|
private string localFilter = string.Empty;
|
||||||
|
private int totalCount;
|
||||||
|
private int pageSize = 50;
|
||||||
|
private string message = "Bogus 生成 237 条样例。全选仅作用于当前页,换页清空选择;表头排序作用于当前页。";
|
||||||
|
|
||||||
|
public DataGridTestViewModel()
|
||||||
|
{
|
||||||
|
currentItems = new ListCollectionView(pageItems) { Filter = item => Matches((DemoStore)item, localFilter) };
|
||||||
|
Title = "DataGridEx 控件测试";
|
||||||
|
AllowEnter = false;
|
||||||
|
DateTime reference = new(2026, 10, 28);
|
||||||
|
stores = new Faker<DemoStore>("zh_CN").UseSeed(29)
|
||||||
|
.RuleFor(row => row.Name, faker => faker.Company.CompanyName() + "小店")
|
||||||
|
.RuleFor(row => row.StoreId, faker => "wx" + faker.Random.Hexadecimal(14, string.Empty))
|
||||||
|
.RuleFor(row => row.CreatedAt, faker => reference.AddDays(-faker.Random.Int(30, 180)))
|
||||||
|
.RuleFor(row => row.ExpiresAt, faker => reference.AddDays(faker.Random.Int(-20, 180)))
|
||||||
|
.RuleFor(row => row.Group, faker => faker.PickRandom("生活百货", "服饰鞋包", "食品生鲜"))
|
||||||
|
.RuleFor(row => row.OperatorName, faker => faker.Name.FullName())
|
||||||
|
.RuleFor(row => row.Phone, faker => faker.Phone.PhoneNumber("138****####"))
|
||||||
|
.RuleFor(row => row.Note, faker => faker.PickRandom("重点运营", "新品店铺", "", "待补充店铺资料"))
|
||||||
|
.FinishWith((_, row) => row.Status = row.ExpiresAt < reference ? "已过期" : row.ExpiresAt <= reference.AddDays(7) ? "即将到期" : "正常")
|
||||||
|
.Generate(237);
|
||||||
|
SelectedStores.CollectionChanged += (_, _) =>
|
||||||
|
{
|
||||||
|
RenewCommand.RaiseCanExecuteChanged();
|
||||||
|
InspectSelectionCommand.RaiseCanExecuteChanged();
|
||||||
|
};
|
||||||
|
searchResults = stores;
|
||||||
|
TotalCount = stores.Count;
|
||||||
|
LoadPage(new DataGridPageRequest(1, pageSize));
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObservableCollection<DemoStore> SelectedStores { get; } = [];
|
||||||
|
public ICollectionView CurrentItems => currentItems;
|
||||||
|
public int TotalCount { get => totalCount; private set => SetProperty(ref totalCount, value); }
|
||||||
|
public string Message { get => message; private set => SetProperty(ref message, value); }
|
||||||
|
|
||||||
|
public string LocalKeyword
|
||||||
|
{
|
||||||
|
get => localKeyword;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
if (SetProperty(ref localKeyword, value))
|
||||||
|
{
|
||||||
|
FilterCurrentPage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public string BackendKeyword { get => backendKeyword; set => SetProperty(ref backendKeyword, value); }
|
||||||
|
public string LocalSearchSummary => $"本页显示 {currentItems.Count} / {pageItems.Count} 条";
|
||||||
|
|
||||||
|
public AsyncDelegateCommand SearchCommand => field ??= new(Search);
|
||||||
|
private async Task Search()
|
||||||
|
{
|
||||||
|
string keyword = BackendKeyword.Trim();
|
||||||
|
LoadingStatus.Initialize("正在搜索店铺…");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 演示网络等待;正式接入时替换为异步 API 请求。
|
||||||
|
await Task.Delay(2450);
|
||||||
|
searchResults = stores.Where(store => Matches(store, keyword)).ToArray();
|
||||||
|
LocalKeyword = string.Empty;
|
||||||
|
TotalCount = 0;
|
||||||
|
TotalCount = searchResults.Count;
|
||||||
|
LoadPage(new DataGridPageRequest(1, pageSize));
|
||||||
|
Message = $"模拟后台搜索完成,共 {TotalCount} 条;未连接真实 API。";
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
LoadingStatus.Done();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FilterCurrentPage()
|
||||||
|
{
|
||||||
|
SelectedStores.Clear();
|
||||||
|
localFilter = LocalKeyword.Trim();
|
||||||
|
currentItems.Refresh();
|
||||||
|
RaisePropertyChanged(nameof(LocalSearchSummary));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool Matches(DemoStore store, string keyword) =>
|
||||||
|
store.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
store.StoreId.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
store.Group.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
store.OperatorName.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
store.Phone.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
store.Status.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
store.Note.Contains(keyword, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
public DelegateCommand<DataGridPageRequest> LoadPageCommand => field ??= new(LoadPage);
|
||||||
|
private void LoadPage(DataGridPageRequest request)
|
||||||
|
{
|
||||||
|
pageSize = request.PageSize;
|
||||||
|
SelectedStores.Clear();
|
||||||
|
pageItems.Clear();
|
||||||
|
pageItems.AddRange(searchResults.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize));
|
||||||
|
FilterCurrentPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
public DelegateCommand RenewCommand => field ??= new(Renew, () => SelectedStores.Count > 0);
|
||||||
|
private void Renew()
|
||||||
|
{
|
||||||
|
foreach (DemoStore store in SelectedStores)
|
||||||
|
{
|
||||||
|
store.ExpiresAt = new DateTime(2027, 5, 9);
|
||||||
|
store.Status = "正常";
|
||||||
|
}
|
||||||
|
Message = $"已模拟续期 {SelectedStores.Count} 家店铺,未产生真实费用。";
|
||||||
|
}
|
||||||
|
|
||||||
|
public DelegateCommand InspectSelectionCommand => field ??= new(InspectSelection, () => SelectedStores.Count > 0);
|
||||||
|
private void InspectSelection() => Message = $"选择 {SelectedStores.Count} 条:{string.Join("、", SelectedStores.Take(3).Select(store => store.Name))}";
|
||||||
|
|
||||||
|
public DelegateCommand EmptyCommand => field ??= new(Empty);
|
||||||
|
private void Empty()
|
||||||
|
{
|
||||||
|
searchResults = [];
|
||||||
|
TotalCount = 0;
|
||||||
|
LoadPage(new DataGridPageRequest(1, pageSize));
|
||||||
|
Message = "空数据状态:总数为 0,不能继续翻页。";
|
||||||
|
}
|
||||||
|
|
||||||
|
public DelegateCommand RestoreCommand => field ??= new(Restore);
|
||||||
|
private void Restore()
|
||||||
|
{
|
||||||
|
LocalKeyword = string.Empty;
|
||||||
|
BackendKeyword = string.Empty;
|
||||||
|
// 总数先归零,让控件同步回第一页,再装入恢复的数据。
|
||||||
|
TotalCount = 0;
|
||||||
|
searchResults = stores;
|
||||||
|
TotalCount = stores.Count;
|
||||||
|
LoadPage(new DataGridPageRequest(1, pageSize));
|
||||||
|
Message = "已恢复 237 条样例,列显示设置保持不变。";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class DemoStore : BindableBase
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
public string StoreId { get; set; } = string.Empty;
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
private DateTime expiresAt;
|
||||||
|
public DateTime ExpiresAt { get => expiresAt; set => SetProperty(ref expiresAt, value); }
|
||||||
|
private string status = string.Empty;
|
||||||
|
public string Status { get => status; set => SetProperty(ref status, value); }
|
||||||
|
public string Group { get; set; } = string.Empty;
|
||||||
|
public string OperatorName { get; set; } = string.Empty;
|
||||||
|
public string Phone { get; set; } = string.Empty;
|
||||||
|
public string Note { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
using MAX.Framework.Controls;
|
|
||||||
using Prism.Services.Dialogs;
|
using Prism.Services.Dialogs;
|
||||||
|
using Store.Management.Framework.Controls;
|
||||||
namespace Store.Management.ViewModels;
|
namespace Store.Management.ViewModels;
|
||||||
public sealed class FrameworkTestDialogViewModel : ConfirmDialogViewModel
|
public sealed class FrameworkTestDialogViewModel : ConfirmDialogViewModel
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ using Prism.Commands;
|
|||||||
using MAX.Notification;
|
using MAX.Notification;
|
||||||
using Store.Management.Notifications;
|
using Store.Management.Notifications;
|
||||||
using Prism.Ioc;
|
using Prism.Ioc;
|
||||||
using Prism.Mvvm;
|
using Store.Management.Framework.Controls;
|
||||||
using Prism.Services.Dialogs;
|
using Prism.Services.Dialogs;
|
||||||
using Store.Management.Services;
|
using Store.Management.Services;
|
||||||
using Store.Management.Views;
|
using Store.Management.Views;
|
||||||
namespace Store.Management.ViewModels;
|
namespace Store.Management.ViewModels;
|
||||||
public sealed class FrameworkTestPageViewModel : BindableBase
|
public sealed class FrameworkTestPageViewModel : ViewModelBase
|
||||||
{
|
{
|
||||||
private readonly IContainerProvider container;
|
private readonly IContainerProvider container;
|
||||||
private readonly SingletonProbe singleton;
|
private readonly SingletonProbe singleton;
|
||||||
|
|||||||
@@ -1,19 +1,33 @@
|
|||||||
using System.Security.Cryptography;
|
using Prism.Commands;
|
||||||
using System.Text;
|
|
||||||
using Prism.Commands;
|
|
||||||
using MAX.Framework.Controls;
|
|
||||||
using Prism.Services.Dialogs;
|
using Prism.Services.Dialogs;
|
||||||
using System.Windows.Input;
|
|
||||||
using Store.Management.Api.Authentication;
|
|
||||||
using Store.Management.Api.Transport;
|
using Store.Management.Api.Transport;
|
||||||
|
using Store.Management.Framework.Controls;
|
||||||
|
using Store.Management.Framework.Services;
|
||||||
using Store.Management.Framework.ViewModels;
|
using Store.Management.Framework.ViewModels;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Windows.Input;
|
||||||
|
|
||||||
namespace Store.Management.ViewModels;
|
namespace Store.Management.ViewModels;
|
||||||
|
|
||||||
/// <summary>登录校验、认证请求和窗口生命周期内的请求取消。</summary>
|
public enum EEE
|
||||||
public sealed class LoginViewModel(IAuthApi auth) : ConfirmDialogViewModel, IDisposable
|
|
||||||
{
|
{
|
||||||
private readonly IAuthApi _auth = auth ?? throw new ArgumentNullException(nameof(auth));
|
[Description("管理员")]
|
||||||
|
Admin,
|
||||||
|
[Description("用户")]
|
||||||
|
User
|
||||||
|
}
|
||||||
|
/// <summary>登录校验、认证请求和窗口生命周期内的请求取消。</summary>
|
||||||
|
public sealed class LoginViewModel(ILoginService loginService) : ConfirmDialogViewModel, IDisposable
|
||||||
|
{
|
||||||
|
private EEE _ee;
|
||||||
|
public EEE ee
|
||||||
|
{
|
||||||
|
get => _ee;
|
||||||
|
set => SetProperty(ref _ee, value);
|
||||||
|
}
|
||||||
private readonly CancellationTokenSource _lifetime = new();
|
private readonly CancellationTokenSource _lifetime = new();
|
||||||
private string _userName = "";
|
private string _userName = "";
|
||||||
private string _passwordHash = "";
|
private string _passwordHash = "";
|
||||||
@@ -38,9 +52,11 @@ public sealed class LoginViewModel(IAuthApi auth) : ConfirmDialogViewModel, IDis
|
|||||||
|
|
||||||
// 服务端要求 UTF-8 密码的 32 位大写 MD5,保留首尾空格。
|
// 服务端要求 UTF-8 密码的 32 位大写 MD5,保留首尾空格。
|
||||||
_passwordHash = string.IsNullOrEmpty(password)
|
_passwordHash = string.IsNullOrEmpty(password)
|
||||||
? "" : Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(password)));
|
? "" : HashPassword(password);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static string HashPassword(string password) => Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(password)));
|
||||||
|
|
||||||
public override ICommand ConfirmCommand => LoginCommand;
|
public override ICommand ConfirmCommand => LoginCommand;
|
||||||
|
|
||||||
public override void OnDialogOpened(IDialogParameters parameters)
|
public override void OnDialogOpened(IDialogParameters parameters)
|
||||||
@@ -73,11 +89,7 @@ public sealed class LoginViewModel(IAuthApi auth) : ConfirmDialogViewModel, IDis
|
|||||||
NotifyStateChanged();
|
NotifyStateChanged();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await _auth.LoginAsync(new LoginRequest
|
await loginService.LoginAsync(UserName, _passwordHash, _lifetime.Token);
|
||||||
{
|
|
||||||
UserName = UserName.Trim(),
|
|
||||||
Password = _passwordHash
|
|
||||||
}, _lifetime.Token);
|
|
||||||
if (!_disposed)
|
if (!_disposed)
|
||||||
{
|
{
|
||||||
_authenticated = true;
|
_authenticated = true;
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Store.Management.ViewModels
|
||||||
|
{
|
||||||
|
partial class MainViewModel
|
||||||
|
{
|
||||||
|
partial void InitHeader()
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
using MAX.Common.Helpers;
|
||||||
|
using PipeReviewReport.Resources.Fonts;
|
||||||
|
using Prism.Commands;
|
||||||
|
using Prism.Regions;
|
||||||
|
using Store.Management.Framework;
|
||||||
|
using Store.Management.Views;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Windows.Input;
|
||||||
|
|
||||||
|
namespace Store.Management.ViewModels
|
||||||
|
{
|
||||||
|
partial class MainViewModel
|
||||||
|
{
|
||||||
|
public ObservableCollection<NavItemViewModel> NavItems { get; } = [];
|
||||||
|
partial void InitNav()
|
||||||
|
{
|
||||||
|
NavItems.Add(new NavItemViewModel
|
||||||
|
{
|
||||||
|
Code = "1",
|
||||||
|
Title = "角色管理",
|
||||||
|
Icon = IconNameEnum.Person,
|
||||||
|
Url = nameof(UserManagementPage)
|
||||||
|
});
|
||||||
|
NavItems.Add(new NavItemViewModel
|
||||||
|
{
|
||||||
|
Code = "1",
|
||||||
|
Title = "商铺管理",
|
||||||
|
Icon = IconNameEnum.BuildingShop,
|
||||||
|
Url = nameof(ShopManagementView),
|
||||||
|
IsSelected = true,
|
||||||
|
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public ICommand NavItemCommand => new AsyncDelegateCommand<NavItemViewModel>(NavItem);
|
||||||
|
|
||||||
|
private async Task NavItem(NavItemViewModel model)
|
||||||
|
{
|
||||||
|
NavItems.ForEach(a => a.IsSelected = false);
|
||||||
|
model.IsSelected = true;
|
||||||
|
|
||||||
|
_regionManager.RequestNavigate(Navigation.MainContext, model.Url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using Store.Management.Framework.Services;
|
||||||
|
using Store.Management.Framework.Controls;
|
||||||
|
using Prism.Regions;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Store.Management.ViewModels
|
||||||
|
{
|
||||||
|
partial class MainViewModel : ViewModelBase
|
||||||
|
{
|
||||||
|
private readonly IRegionManager _regionManager;
|
||||||
|
public IStatusBarService StatusBar { get; }
|
||||||
|
public MainViewModel(IRegionManager regionManager, IStatusBarService statusBar)
|
||||||
|
{
|
||||||
|
_regionManager = regionManager;
|
||||||
|
StatusBar = statusBar;
|
||||||
|
InitNav();
|
||||||
|
InitHeader();
|
||||||
|
}
|
||||||
|
partial void InitNav();
|
||||||
|
partial void InitHeader();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using PipeReviewReport.Resources.Fonts;
|
||||||
|
using Prism.Mvvm;
|
||||||
|
|
||||||
|
namespace Store.Management.ViewModels
|
||||||
|
{
|
||||||
|
public class NavItemViewModel : BindableBase
|
||||||
|
{
|
||||||
|
public string Code { get; set; }
|
||||||
|
public string Title { get; set; }
|
||||||
|
public IconNameEnum Icon { get; set; }
|
||||||
|
public string Url { get; set; }
|
||||||
|
private bool _isSelected;
|
||||||
|
public bool IsSelected
|
||||||
|
{
|
||||||
|
get => _isSelected;
|
||||||
|
set => SetProperty(ref _isSelected, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
using Prism.Commands;
|
||||||
|
using Store.Management.Api.Models;
|
||||||
|
using Store.Management.Api.Shops;
|
||||||
|
using Store.Management.Api.Transport;
|
||||||
|
using Store.Management.Framework.Controls;
|
||||||
|
using Store.Management.Framework.Mappers;
|
||||||
|
using Store.Management.Framework.Services;
|
||||||
|
using Store.Management.Framework.ViewModels;
|
||||||
|
using Store.Management.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.ViewModels;
|
||||||
|
|
||||||
|
public sealed class ShopManagementViewModel(IShopService shopService, IStatusBarService statusBar) : ViewModelBase
|
||||||
|
{
|
||||||
|
public const int SearchTextLimit = 250;
|
||||||
|
private string account = string.Empty;
|
||||||
|
private string shopId = string.Empty;
|
||||||
|
private string shopName = string.Empty;
|
||||||
|
private string notes = string.Empty;
|
||||||
|
private int page = 1;
|
||||||
|
private int pageSize = 50;
|
||||||
|
private int total;
|
||||||
|
private IReadOnlyList<ShopItemViewModel> shops = [];
|
||||||
|
private ShopQueryRequest appliedQuery = new();
|
||||||
|
|
||||||
|
public string Account { get => account; set => SetProperty(ref account, value); }
|
||||||
|
public string ShopId { get => shopId; set => SetProperty(ref shopId, value); }
|
||||||
|
public string ShopName { get => shopName; set => SetProperty(ref shopName, value); }
|
||||||
|
public string Notes { get => notes; set => SetProperty(ref notes, value); }
|
||||||
|
public int Page { get => page; private set => SetProperty(ref page, value); }
|
||||||
|
public int Total { get => total; private set => SetProperty(ref total, value); }
|
||||||
|
public IReadOnlyList<ShopItemViewModel> Shops { get => shops; private set => SetProperty(ref shops, value); }
|
||||||
|
public LoadingStatus LoadingStatus { get; } = new();
|
||||||
|
|
||||||
|
public AsyncDelegateCommand SearchCommand => field ??= new(SearchAsync);
|
||||||
|
private Task SearchAsync() => LoadAsync(new ShopQueryRequest
|
||||||
|
{
|
||||||
|
SearchUserName = Account.Trim(), SearchId = ShopId.Trim(),
|
||||||
|
SearchName = ShopName.Trim(), SearchNotes = Notes.Trim(), PageSize = pageSize
|
||||||
|
});
|
||||||
|
|
||||||
|
public AsyncDelegateCommand ResetCommand => field ??= new(ResetAsync);
|
||||||
|
private Task ResetAsync()
|
||||||
|
{
|
||||||
|
Account = ShopId = ShopName = Notes = string.Empty;
|
||||||
|
return SearchAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public AsyncDelegateCommand<DataGridPageRequest> PageCommand => field ??= new(request => LoadAsync(new ShopQueryRequest
|
||||||
|
{
|
||||||
|
SearchUserName = appliedQuery.SearchUserName, SearchId = appliedQuery.SearchId,
|
||||||
|
SearchName = appliedQuery.SearchName, SearchNotes = appliedQuery.SearchNotes,
|
||||||
|
Page = request.PageIndex, PageSize = request.PageSize
|
||||||
|
}));
|
||||||
|
|
||||||
|
public AsyncDelegateCommand<ShopItemViewModel> CopyCookieCommand => field ??= new(CopyCookieAsync,
|
||||||
|
shop => !string.IsNullOrWhiteSpace(shop?.ShopId));
|
||||||
|
private async Task CopyCookieAsync(ShopItemViewModel shop)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
IReadOnlyList<ShopCookieInfo> cookies = await shopService.GetCookiesAsync(shop.ShopId!);
|
||||||
|
string? cookie = cookies.FirstOrDefault(item => item.ShopId == shop.ShopId)?.Cookies;
|
||||||
|
if (string.IsNullOrWhiteSpace(cookie))
|
||||||
|
{
|
||||||
|
statusBar.Report("该店铺没有可复制的 Cookie。", StatusLevel.Warning);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
System.Windows.Clipboard.SetText(cookie);
|
||||||
|
statusBar.Report("Cookie 已复制。", StatusLevel.Success);
|
||||||
|
}
|
||||||
|
catch (ApiException ex)
|
||||||
|
{
|
||||||
|
statusBar.Report(ex.Message, StatusLevel.Error);
|
||||||
|
}
|
||||||
|
catch (System.Runtime.InteropServices.COMException)
|
||||||
|
{
|
||||||
|
statusBar.Report("剪贴板暂时不可用,请重试。", StatusLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnLoadedOnce() => _ = SearchAsync();
|
||||||
|
|
||||||
|
private async Task LoadAsync(ShopQueryRequest request)
|
||||||
|
{
|
||||||
|
if (LoadingStatus.IsLoading)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LoadingStatus.Initialize("正在查询商铺…");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
PageResult<ShopInfo> result = await shopService.SearchAsync(request);
|
||||||
|
int lastPage = (int)Math.Clamp((result.Total - 1) / request.PageSize + 1, 1, request.Page);
|
||||||
|
if (request.Page > lastPage)
|
||||||
|
{
|
||||||
|
request.Page = lastPage;
|
||||||
|
result = await shopService.SearchAsync(request);
|
||||||
|
}
|
||||||
|
appliedQuery = request;
|
||||||
|
pageSize = request.PageSize;
|
||||||
|
Shops = ShopMapper.ToItemViewModels(result.Items);
|
||||||
|
Total = (int)Math.Min(result.Total, int.MaxValue);
|
||||||
|
Page = request.Page;
|
||||||
|
LoadingStatus.Done();
|
||||||
|
statusBar.Report($"商铺查询完成,共 {Total} 条。", StatusLevel.Success, 100);
|
||||||
|
}
|
||||||
|
catch (ApiException ex)
|
||||||
|
{
|
||||||
|
Shops = [];
|
||||||
|
Total = 0;
|
||||||
|
Page = 1;
|
||||||
|
LoadingStatus.Error(ex.Message);
|
||||||
|
statusBar.Report(ex.Message, StatusLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
using Store.Management.Framework.Mappers;
|
||||||
|
using Store.Management.Framework.ViewModels;
|
||||||
|
using Store.Management.Models;
|
||||||
|
using Prism.Commands;
|
||||||
|
using Prism.Services.Dialogs;
|
||||||
|
using Store.Management.Api.Transport;
|
||||||
|
using Store.Management.Api.Users;
|
||||||
|
using Store.Management.Framework.Controls;
|
||||||
|
using Store.Management.Framework.Services;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Windows.Input;
|
||||||
|
|
||||||
|
namespace Store.Management.ViewModels;
|
||||||
|
|
||||||
|
public sealed class UserEditorDialogViewModel(IUserService userService) : ConfirmDialogViewModel
|
||||||
|
{
|
||||||
|
public const int UserNameLimit = 20;
|
||||||
|
public const int PasswordLimit = 128;
|
||||||
|
public const int NickNameLimit = 50;
|
||||||
|
public const int MobileLimit = 30;
|
||||||
|
public const int CompanyLimit = 100;
|
||||||
|
public const int NotesLimit = 255;
|
||||||
|
|
||||||
|
public const int AgentCodeLimit = 50;
|
||||||
|
public sealed class PermissionOption(string name)
|
||||||
|
{
|
||||||
|
public string Name { get; } = name;
|
||||||
|
public bool IsSelected { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public PermissionOption[] Permissions { get; } =
|
||||||
|
[
|
||||||
|
new("微信回采"), new("货源选择"), new("评分考核"), new("爆款数据"),
|
||||||
|
new("在线寄件"), new("佣金上货"), new("充值用户"), new("商品采集"),
|
||||||
|
new("裂变调试"), new("学员数据"), new("定向品牌"), new("活动库存")
|
||||||
|
];
|
||||||
|
|
||||||
|
private UserItemViewModel? user;
|
||||||
|
private string? passwordHash;
|
||||||
|
private string? confirmationHash;
|
||||||
|
private string? oldPasswordHash;
|
||||||
|
public bool ShowOldPassword => !IsCreate && passwordHash != null;
|
||||||
|
public string? ParentUserName { get; set; }
|
||||||
|
public bool IsCreatingSubUser => IsCreate && Group != UserGroup.MainAccount;
|
||||||
|
public UserGroup? Group
|
||||||
|
{
|
||||||
|
get;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
if (SetProperty(ref field, value))
|
||||||
|
{
|
||||||
|
RaisePropertyChanged(nameof(IsCreatingSubUser));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public UserAdminLevel Level { get; set => SetProperty(ref field, value); }
|
||||||
|
public string AgentCode { get; set => SetProperty(ref field, value); } = "";
|
||||||
|
public bool IsCreate => user == null;
|
||||||
|
public string UserName { get; set => SetProperty(ref field, value); } = "";
|
||||||
|
public UserEditRequest Draft { get; private set => SetProperty(ref field, value); } = new();
|
||||||
|
|
||||||
|
public override void OnDialogOpened(IDialogParameters parameters)
|
||||||
|
{
|
||||||
|
user = parameters.GetValue<UserItemViewModel?>("user");
|
||||||
|
UserName = user?.UserName ?? "";
|
||||||
|
Draft = user == null ? new UserCreateRequest() : new UserUpdateRequest
|
||||||
|
{
|
||||||
|
Id = user.Id, NickName = user.NickName, Mobile = user.Mobile,
|
||||||
|
CompanyName = user.CompanyName, Notes = user.Notes
|
||||||
|
};
|
||||||
|
Group = user == null ? UserGroup.MainAccount : (UserGroup)user.GroupId;
|
||||||
|
Level = user?.SaLevel ?? UserAdminLevel.Normal;
|
||||||
|
AgentCode = user?.OemId ?? "";
|
||||||
|
var granted = (user?.Authority ?? "").Split(',', StringSplitOptions.TrimEntries);
|
||||||
|
foreach (var option in Permissions)
|
||||||
|
{
|
||||||
|
option.IsSelected = granted.Contains(option.Name);
|
||||||
|
}
|
||||||
|
Title = IsCreate ? "创建用户" : "编辑用户";
|
||||||
|
RaisePropertyChanged(nameof(IsCreate));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdatePasswords(string password, string confirmation, string oldPassword)
|
||||||
|
{
|
||||||
|
passwordHash = password.Length == 0 ? null : password.Length >= 6 && !string.IsNullOrWhiteSpace(password)
|
||||||
|
? LoginViewModel.HashPassword(password) : "";
|
||||||
|
oldPasswordHash = oldPassword.Length == 0 ? null : LoginViewModel.HashPassword(oldPassword);
|
||||||
|
RaisePropertyChanged(nameof(ShowOldPassword));
|
||||||
|
confirmationHash = confirmation.Length == 0 ? null : LoginViewModel.HashPassword(confirmation);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanCloseDialog() => !IsLoading;
|
||||||
|
public override ICommand ConfirmCommand => field ??= new AsyncDelegateCommand(SaveAsync);
|
||||||
|
|
||||||
|
private async Task SaveAsync()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(Draft.NickName) || string.IsNullOrWhiteSpace(Draft.Mobile))
|
||||||
|
{
|
||||||
|
ErrorMsg = "请输入昵称和手机号。";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Draft.Mobile.Trim().Length != 11 || !Draft.Mobile.Trim().All(char.IsAsciiDigit))
|
||||||
|
{
|
||||||
|
ErrorMsg = "手机号应为 11 位数字。";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (passwordHash == "" || (IsCreate && passwordHash == null))
|
||||||
|
{
|
||||||
|
ErrorMsg = "请输入至少 6 位密码。";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (passwordHash != confirmationHash)
|
||||||
|
{
|
||||||
|
ErrorMsg = "两次输入的密码不一致。";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Group == null || (user != null && Group != (UserGroup)user.GroupId &&
|
||||||
|
(Group == UserGroup.MainAccount || user.GroupId == (int)UserGroup.MainAccount)))
|
||||||
|
{
|
||||||
|
ErrorMsg = "请选择有效分组,已有账户不能切换主号和子账号。";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Draft.GroupId = user?.GroupId == (int?)Group ? null : Group;
|
||||||
|
Draft.SaLevel = Level == (user?.SaLevel ?? UserAdminLevel.Normal) ? null : Level;
|
||||||
|
Draft.OemId = AgentCode.Trim() == (user?.OemId ?? "") ? null : AgentCode.Trim();
|
||||||
|
var granted = (user?.Authority ?? "").Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).ToHashSet();
|
||||||
|
bool changed = false;
|
||||||
|
foreach (var option in Permissions)
|
||||||
|
{
|
||||||
|
changed |= option.IsSelected ? granted.Add(option.Name) : granted.Remove(option.Name);
|
||||||
|
}
|
||||||
|
Draft.Authority = changed ? string.Join(",", granted) : null;
|
||||||
|
|
||||||
|
if (Draft is UserCreateRequest create)
|
||||||
|
{
|
||||||
|
create.ParentUserName = IsCreatingSubUser ? ParentUserName : null;
|
||||||
|
create.UserName = Draft.Mobile.Trim();
|
||||||
|
create.Password = passwordHash!;
|
||||||
|
}
|
||||||
|
|
||||||
|
IsLoading = true;
|
||||||
|
ErrorMsg = "";
|
||||||
|
bool profileSaved = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Draft is UserCreateRequest newUser)
|
||||||
|
{
|
||||||
|
await userService.CreateAsync(newUser);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
user = UserMapper.ToItemViewModel(await userService.UpdateAsync((UserUpdateRequest)Draft));
|
||||||
|
profileSaved = true;
|
||||||
|
if (passwordHash != null)
|
||||||
|
{
|
||||||
|
await userService.ChangePasswordAsync(new ChangePasswordRequest(UserName, passwordHash, oldPasswordHash));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (ApiException ex)
|
||||||
|
{
|
||||||
|
ErrorMsg = profileSaved ? $"资料已保存,密码修改失败:{ex.Message}" : ex.Message;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
catch (ValidationException ex)
|
||||||
|
{
|
||||||
|
ErrorMsg = ex.Message;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
IsLoading = false;
|
||||||
|
}
|
||||||
|
OnRequestClose(new DialogResult(ButtonResult.OK));
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnDialogClosed()
|
||||||
|
{
|
||||||
|
passwordHash = confirmationHash = oldPasswordHash = null;
|
||||||
|
if (Draft is UserCreateRequest create)
|
||||||
|
{
|
||||||
|
create.Password = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
using Store.Management.Framework.Mappers;
|
||||||
|
using Store.Management.Framework.ViewModels;
|
||||||
|
using Store.Management.Models;
|
||||||
|
using Prism.Commands;
|
||||||
|
using Prism.Mvvm;
|
||||||
|
using Prism.Regions;
|
||||||
|
using Prism.Services.Dialogs;
|
||||||
|
using Store.Management.Api.Transport;
|
||||||
|
using Store.Management.Api.Users;
|
||||||
|
using Store.Management.Framework.Controls;
|
||||||
|
using Store.Management.Framework.Services;
|
||||||
|
using Store.Management.Views;
|
||||||
|
using Store.Management.Views.Dialogs;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Controls.Primitives;
|
||||||
|
using Store.Management.Api.Models;
|
||||||
|
|
||||||
|
namespace Store.Management.ViewModels;
|
||||||
|
|
||||||
|
public sealed class UserManagementPageViewModel(IUserService userService, IDialogService dialogs, IStatusBarService statusBar) : ViewModelBase
|
||||||
|
{
|
||||||
|
public const int KeywordLimit = 100;
|
||||||
|
private string appliedKeyword = "";
|
||||||
|
private UserGroup? appliedGroup;
|
||||||
|
private int pageSize = 50;
|
||||||
|
|
||||||
|
public string Keyword { get; set; } = "";
|
||||||
|
public UserGroup? SelectedGroup { get; set; }
|
||||||
|
private bool _canInteract = true;
|
||||||
|
public bool CanInteract { get => _canInteract; private set => SetProperty(ref _canInteract, value); }
|
||||||
|
public int Page { get; private set => SetProperty(ref field, value); } = 1;
|
||||||
|
public int Total { get; private set => SetProperty(ref field, value); }
|
||||||
|
public IReadOnlyList<UserItemViewModel> Users { get; private set => SetProperty(ref field, value); } = [];
|
||||||
|
public UserItemViewModel? SelectedUser { get; set => SetProperty(ref field, value); }
|
||||||
|
|
||||||
|
public AsyncDelegateCommand SearchCommand => field ??= new(() => LoadAsync(Keyword.Trim(), SelectedGroup, 1, pageSize));
|
||||||
|
public AsyncDelegateCommand<DataGridPageRequest> PageCommand => field ??= new(
|
||||||
|
request => LoadAsync(appliedKeyword, appliedGroup, request.PageIndex, request.PageSize), _ => CanInteract);
|
||||||
|
public AsyncDelegateCommand CreateCommand => field ??= new(() => OpenEditorAsync(null));
|
||||||
|
public AsyncDelegateCommand EditCommand => field ??= new AsyncDelegateCommand(() => OpenEditorAsync(SelectedUser),
|
||||||
|
() => SelectedUser != null).ObservesProperty(() => SelectedUser);
|
||||||
|
public AsyncDelegateCommand BillingCommand => field ??= new AsyncDelegateCommand(async () =>
|
||||||
|
{
|
||||||
|
ButtonResult result = ButtonResult.None;
|
||||||
|
dialogs.ShowDialog(nameof(UserBillingDialog), SelectedUser!, response => result = response.Result);
|
||||||
|
if (result == ButtonResult.OK)
|
||||||
|
{
|
||||||
|
await LoadAsync(appliedKeyword, appliedGroup, Page, pageSize);
|
||||||
|
}
|
||||||
|
}, () => SelectedUser != null).ObservesProperty(() => SelectedUser);
|
||||||
|
public AsyncDelegateCommand DeleteCommand => field ??= new AsyncDelegateCommand(DeleteAsync,
|
||||||
|
() => SelectedUser != null).ObservesProperty(() => SelectedUser);
|
||||||
|
|
||||||
|
protected override void OnLoadedOnce()
|
||||||
|
{
|
||||||
|
_ = LoadAsync(Keyword.Trim(), SelectedGroup, 1, pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task LoadAsync(string keyword, UserGroup? group, int page, int size)
|
||||||
|
{
|
||||||
|
if (!CanInteract)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
CanInteract = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
statusBar.Report("正在查询用户…");
|
||||||
|
UserSearchRequest request = new() { Keyword = keyword, GroupId = (int?)group, Page = page, PageSize = size };
|
||||||
|
PageResult<UserInfo> result = await userService.SearchAsync(request);
|
||||||
|
// 删除末页最后一条记录后,按服务端总数回到有效页。
|
||||||
|
int lastPage = (int)Math.Clamp((result.Total - 1) / size + 1, 1, page);
|
||||||
|
if (page > lastPage)
|
||||||
|
{
|
||||||
|
request.Page = lastPage;
|
||||||
|
result = await userService.SearchAsync(request);
|
||||||
|
}
|
||||||
|
appliedKeyword = keyword;
|
||||||
|
appliedGroup = group;
|
||||||
|
pageSize = size;
|
||||||
|
SelectedUser = null;
|
||||||
|
Users = UserMapper.ToItemViewModels(result.Items);
|
||||||
|
Total = (int)Math.Min(result.Total, int.MaxValue);
|
||||||
|
Page = request.Page;
|
||||||
|
|
||||||
|
statusBar.Report($"用户查询完成,共 {Total} 条。", StatusLevel.Success, 100);
|
||||||
|
}
|
||||||
|
catch (ApiException ex)
|
||||||
|
{
|
||||||
|
SelectedUser = null;
|
||||||
|
Users = [];
|
||||||
|
Total = 0;
|
||||||
|
Page = 1;
|
||||||
|
appliedKeyword = keyword;
|
||||||
|
appliedGroup = group;
|
||||||
|
pageSize = size;
|
||||||
|
statusBar.Report(ex.Message, StatusLevel.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
CanInteract = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task OpenEditorAsync(UserItemViewModel? user)
|
||||||
|
{
|
||||||
|
ButtonResult result = ButtonResult.None;
|
||||||
|
dialogs.ShowDialog(nameof(UserEditorDialog), new DialogParameters { { "user", user } },
|
||||||
|
response => result = response.Result);
|
||||||
|
if (result == ButtonResult.OK)
|
||||||
|
{
|
||||||
|
await LoadAsync(appliedKeyword, appliedGroup, user == null ? 1 : Page, pageSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task DeleteAsync()
|
||||||
|
{
|
||||||
|
UserItemViewModel user = SelectedUser!;
|
||||||
|
if (MessageBox.Show($"确定删除用户“{user.UserName}”?", "删除用户", MessageBoxButton.OKCancel,
|
||||||
|
MessageBoxImage.Warning, MessageBoxResult.Cancel) != MessageBoxResult.OK)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
CanInteract = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
statusBar.Report("正在删除用户…");
|
||||||
|
await userService.DeleteAsync(user.Id);
|
||||||
|
}
|
||||||
|
catch (ApiException ex)
|
||||||
|
{
|
||||||
|
statusBar.Report(ex.Message, StatusLevel.Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
CanInteract = true;
|
||||||
|
}
|
||||||
|
await LoadAsync(appliedKeyword, appliedGroup, Page, pageSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<Window
|
||||||
|
x:Class="Store.Management.Views.AppSplashScreen"
|
||||||
|
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:Store.Management.Views"
|
||||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
|
Title="AppSplashScreen"
|
||||||
|
Width="990"
|
||||||
|
Height="570"
|
||||||
|
AllowsTransparency="True"
|
||||||
|
Background="Transparent"
|
||||||
|
ResizeMode="NoResize"
|
||||||
|
ShowInTaskbar="False"
|
||||||
|
Topmost="True"
|
||||||
|
WindowStartupLocation="CenterScreen"
|
||||||
|
WindowStyle="None"
|
||||||
|
mc:Ignorable="d">
|
||||||
|
<Border>
|
||||||
|
<!--<Viewbox>
|
||||||
|
<TextBlock Foreground="#dedede" Text="启动" />
|
||||||
|
</Viewbox>-->
|
||||||
|
</Border>
|
||||||
|
</Window>
|
||||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user