ops-console v1.0.2 (versionCode 8) 源码入库

This commit is contained in:
txh
2026-09-03 18:01:05 +08:00
commit 685fff27c8
170 changed files with 53049 additions and 0 deletions

View File

@@ -0,0 +1,567 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../models/store_info.dart';
import '../../services/device_service.dart';
import '../../services/org_service.dart';
import '../../services/api_client.dart';
import '../../utils/formatters.dart';
import '../../utils/i10n.dart';
/// 激活码管理页:门店选择、激活码信息、生成/重置。
class DeviceActivationPage extends ConsumerStatefulWidget {
const DeviceActivationPage({super.key});
@override
ConsumerState<DeviceActivationPage> createState() =>
_DeviceActivationPageState();
}
class _DeviceActivationPageState extends ConsumerState<DeviceActivationPage> {
final OrgService _orgService = OrgService();
final DeviceService _deviceService = DeviceService();
AppLocalizations get t => AppLocalizations.of(context);
List<StoreInfo> _stores = [];
String? _selectedStoreId;
bool _loadingStores = true;
Map<String, dynamic>? _codeInfo;
bool _loading = false;
String? _error;
@override
void initState() {
super.initState();
_loadStores();
}
Future<void> _loadStores() async {
try {
final stores = await _orgService.getMyStores();
if (!mounted) return;
setState(() {
_stores = stores;
_loadingStores = false;
if (stores.isNotEmpty) {
_selectedStoreId = stores.first.orgId;
}
});
if (_selectedStoreId != null) {
_loadCodeInfo();
}
} catch (e) {
if (!mounted) return;
setState(() => _loadingStores = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context).storeListLoadFailed(e.toString()))),
);
}
}
Future<void> _loadCodeInfo() async {
if (_selectedStoreId == null) return;
setState(() {
_loading = true;
_error = null;
});
try {
final info = await _deviceService.getActivationCodeInfo(
_selectedStoreId!,
);
if (!mounted) return;
setState(() {
_codeInfo = info;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = '$e';
_loading = false;
});
}
}
void _showGenerateSheet() {
if (_selectedStoreId == null) return;
showModalBottomSheet(
useSafeArea: true,
context: context,
isScrollControlled: true,
builder: (ctx) => _GenerateCodeSheet(
deviceService: _deviceService,
orgId: _selectedStoreId!,
onSaved: () {
Navigator.pop(ctx);
_loadCodeInfo();
},
),
);
}
Future<void> _resetCode() async {
if (_selectedStoreId == null) return;
final t = AppLocalizations.of(context);
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(t.resetActivationCode),
content: Text(t.resetActivationCodeConfirm),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: Text(t.cancel),
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
style: TextButton.styleFrom(foregroundColor: Colors.orange),
child: Text(t.reset),
),
],
),
);
if (confirmed != true) return;
try {
await _deviceService.resetActivationCode(_selectedStoreId!);
if (!mounted) return;
// 结果以页面中央弹窗展示(替代左下方 SnackBar)。
_showResultDialog(
isSuccess: true,
title: t.activationCodeResetSuccess,
);
_loadCodeInfo();
} catch (e) {
if (!mounted) return;
_showResultDialog(
isSuccess: false,
title: t.activationCodeResetFailed(formatApiError(e)),
);
}
}
/// 居中弹窗展示激活码重置结果(成功/失败)。
///
/// 替代原左下角 SnackBar,保证用户清晰看到操作反馈。
void _showResultDialog({
required bool isSuccess,
required String title,
}) {
final t = AppLocalizations.of(context);
showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
icon: Icon(
isSuccess ? Icons.check_circle_outline : Icons.error_outline,
color: isSuccess ? Colors.green : Colors.red,
size: 42,
),
title: Center(child: Text(title, textAlign: TextAlign.center)),
actionsAlignment: MainAxisAlignment.center,
actions: [
FilledButton(
onPressed: () => Navigator.pop(ctx),
child: Text(t.confirm),
),
],
),
);
}
@override
Widget build(BuildContext context) {
final t = AppLocalizations.of(context);
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(t.activationCodeManagement),
),
body: Column(
children: [
_buildStoreSelector(),
const Divider(height: 1),
Expanded(child: _buildBody()),
],
),
);
}
Widget _buildStoreSelector() {
if (_loadingStores) {
return const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
);
}
if (_stores.isEmpty) {
return Padding(
padding: const EdgeInsets.all(16),
child: Text(t.noStoreAvailable),
);
}
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: DropdownButtonFormField<String>(
value: _selectedStoreId,
decoration: InputDecoration(
labelText: t.selectStore,
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.store),
),
items: _stores
.map((s) => DropdownMenuItem(
value: s.orgId,
child: Text(s.name),
))
.toList(),
onChanged: (v) {
setState(() => _selectedStoreId = v);
_loadCodeInfo();
},
),
);
}
Widget _buildBody() {
if (_selectedStoreId == null) {
return Center(child: Text(t.pleaseSelectStoreFirst));
}
if (_loading) {
return const Center(child: CircularProgressIndicator());
}
if (_error != null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(t.activationCodeLoadFailed(_error!)),
const SizedBox(height: 8),
FilledButton.tonal(
onPressed: _loadCodeInfo,
child: Text(t.retry),
),
],
),
);
}
if (_codeInfo == null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.vpn_key_outlined,
size: 64,
color: Theme.of(context).colorScheme.outline),
const SizedBox(height: 16),
Text(t.noActivationCode),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: _showGenerateSheet,
icon: const Icon(Icons.add),
label: Text(t.generateActivationCode),
),
],
),
);
}
return RefreshIndicator(
onRefresh: _loadCodeInfo,
child: ListView(
padding: const EdgeInsets.all(16),
physics: const AlwaysScrollableScrollPhysics(),
children: [
_buildCodeCard(),
const SizedBox(height: 16),
_buildInfoCard(),
const SizedBox(height: 24),
Row(
children: [
Expanded(
child: FilledButton.icon(
onPressed: _showGenerateSheet,
icon: const Icon(Icons.refresh),
label: Text(t.generateActivationCode),
),
),
const SizedBox(width: 12),
Expanded(
child: OutlinedButton.icon(
onPressed: _resetCode,
style: OutlinedButton.styleFrom(
foregroundColor: Colors.orange,
),
icon: const Icon(Icons.restart_alt),
label: Text(t.resetActivationCode),
),
),
],
),
],
),
);
}
Widget _buildCodeCard() {
final code = _codeInfo!['code']?.toString() ?? '';
final theme = Theme.of(context);
return Card(
elevation: 2,
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.vpn_key,
color: theme.colorScheme.primary, size: 20),
const SizedBox(width: 8),
Text(t.currentActivationCode,
style: theme.textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold)),
],
),
const SizedBox(height: 16),
if (code.isEmpty)
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: Text(
t.activationCodeNoCodeHint,
style: const TextStyle(color: Colors.grey),
),
)
else
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: theme.colorScheme.primary.withOpacity(0.4)),
),
child: SelectableText(
code,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
fontFamily: 'monospace',
color: theme.colorScheme.onPrimaryContainer,
),
),
),
if (code.isNotEmpty) ...[
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton.icon(
onPressed: () {
Clipboard.setData(ClipboardData(text: code));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.activationCodeCopied)),
);
},
icon: const Icon(Icons.copy, size: 18),
label: Text(t.copy),
),
],
),
],
],
),
),
);
}
Widget _buildInfoCard() {
final theme = Theme.of(context);
final maxCount = _codeInfo!['maxActivateCount'];
final activatedCount = _codeInfo!['activatedCount'];
final createTime = _codeInfo!['createTime'];
String _formatTime(dynamic t) {
if (t == null) return '—';
final text = t.toString().trim();
if (text.isEmpty) return '—';
final dt = DateTime.tryParse(text) ??
DateTime.tryParse(text.replaceFirst(' ', 'T'));
return dt != null ? Formatters.formatDateTime(dt) : text;
}
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_infoRow(
theme,
t.maxActivateCount,
maxCount?.toString() ?? '—',
),
_infoRow(
theme,
t.activatedCount,
activatedCount?.toString() ?? '—',
),
_infoRow(theme, t.createTime, _formatTime(createTime)),
],
),
),
);
}
Widget _infoRow(ThemeData theme, String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
children: [
SizedBox(
width: 100,
child: Text(
label,
style: theme.textTheme.bodyMedium
?.copyWith(color: theme.colorScheme.onSurfaceVariant),
),
),
Expanded(
child: Text(value,
style: theme.textTheme.bodyMedium
?.copyWith(fontWeight: FontWeight.w600)),
),
],
),
);
}
}
/// 生成激活码表单。
class _GenerateCodeSheet extends StatefulWidget {
const _GenerateCodeSheet({
required this.deviceService,
required this.orgId,
required this.onSaved,
});
final DeviceService deviceService;
final String orgId;
final VoidCallback onSaved;
@override
State<_GenerateCodeSheet> createState() => _GenerateCodeSheetState();
}
class _GenerateCodeSheetState extends State<_GenerateCodeSheet> {
final _formKey = GlobalKey<FormState>();
final _countController = TextEditingController(text: '1');
bool _saving = false;
@override
void dispose() {
_countController.dispose();
super.dispose();
}
Future<void> _save() async {
final t = AppLocalizations.of(context);
if (!_formKey.currentState!.validate()) return;
setState(() => _saving = true);
try {
final count = int.parse(_countController.text.trim());
await widget.deviceService.generateActivationCode(
widget.orgId,
count,
);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.activationCodeGenerated)),
);
widget.onSaved();
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.generateFailedWithError(e.toString()))),
);
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
final t = AppLocalizations.of(context);
return SingleChildScrollView(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: Container(
padding: const EdgeInsets.all(20),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
t.generateActivationCode,
style: Theme.of(context)
.textTheme
.titleLarge
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
t.generateActivationCodeHint,
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: 13,
),
),
const SizedBox(height: 20),
TextFormField(
controller: _countController,
decoration: InputDecoration(
labelText: t.maxActivationCountLabel,
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.looks),
helperText: t.maxActivationCountHint,
),
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
validator: (v) {
final count = int.tryParse(v ?? '');
if (count == null || count <= 0) {
return t.positiveIntegerRequired;
}
return null;
},
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: FilledButton(
onPressed: _saving ? null : _save,
child: _saving
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(t.generate),
),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,488 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../models/org_node.dart';
import '../../models/store_info.dart';
import '../../services/device_service.dart';
import '../../services/org_service.dart';
/// 设备分组页:门店选择、分组列表、新增/编辑/删除。
class DeviceGroupPage extends ConsumerStatefulWidget {
const DeviceGroupPage({super.key});
@override
ConsumerState<DeviceGroupPage> createState() => _DeviceGroupPageState();
}
class _DeviceGroupPageState extends ConsumerState<DeviceGroupPage> {
final OrgService _orgService = OrgService();
final DeviceService _deviceService = DeviceService();
final _scrollController = ScrollController();
List<StoreInfo> _stores = [];
String? _selectedStoreId;
bool _loadingStores = true;
List<OrgNode> _items = [];
bool _loading = false;
bool _hasMore = true;
int _page = 1;
String? _error;
@override
void initState() {
super.initState();
_scrollController.addListener(_onScroll);
_loadStores();
}
@override
void dispose() {
_scrollController.removeListener(_onScroll);
_scrollController.dispose();
super.dispose();
}
void _onScroll() {
if (_scrollController.position.pixels >=
_scrollController.position.maxScrollExtent - 200) {
_loadMore();
}
}
Future<void> _loadStores() async {
try {
final stores = await _orgService.getMyStores();
if (!mounted) return;
setState(() {
_stores = stores;
_loadingStores = false;
if (stores.isNotEmpty) {
_selectedStoreId = stores.first.orgId;
}
});
if (_selectedStoreId != null) {
_loadData();
}
} catch (e) {
if (!mounted) return;
setState(() => _loadingStores = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('门店列表加载失败:$e')),
);
}
}
Future<void> _loadData() async {
if (_selectedStoreId == null) return;
setState(() {
_loading = true;
_error = null;
_page = 1;
_hasMore = true;
});
try {
final items = await _deviceService.getDeviceGroupList(
page: 1,
limit: 20,
storeId: _selectedStoreId!,
);
if (!mounted) return;
setState(() {
_items = items;
_hasMore = items.length >= 20;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = '$e';
_loading = false;
});
}
}
Future<void> _loadMore() async {
if (_loading || !_hasMore || _selectedStoreId == null) return;
setState(() => _loading = true);
try {
final items = await _deviceService.getDeviceGroupList(
page: _page + 1,
limit: 20,
storeId: _selectedStoreId!,
);
if (!mounted) return;
setState(() {
_page++;
_items.addAll(items);
_hasMore = items.length >= 20;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() => _loading = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('加载更多失败:$e')),
);
}
}
Future<void> _deleteGroup(OrgNode group) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('删除分组'),
content: Text('确定要删除分组「${group.name}」吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('删除'),
),
],
),
);
if (confirmed != true) return;
try {
await _deviceService.deleteDeviceGroups([group.id]);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('分组已删除')),
);
_loadData();
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('删除失败:$e')),
);
}
}
void _showAddEditSheet({OrgNode? group}) {
if (_selectedStoreId == null) return;
showModalBottomSheet(
useSafeArea: true,
context: context,
isScrollControlled: true,
builder: (ctx) => _GroupFormSheet(
deviceService: _deviceService,
storeId: _selectedStoreId!,
group: group,
onSaved: () {
Navigator.pop(ctx);
_loadData();
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('设备分组'),
),
body: Column(
children: [
_buildStoreSelector(),
const Divider(height: 1),
Expanded(child: _buildBody()),
],
),
floatingActionButton: _selectedStoreId == null
? null
: FloatingActionButton(
onPressed: () => _showAddEditSheet(),
child: const Icon(Icons.add),
),
);
}
Widget _buildStoreSelector() {
if (_loadingStores) {
return const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
);
}
if (_stores.isEmpty) {
return const Padding(
padding: EdgeInsets.all(16),
child: Text('暂无可选门店'),
);
}
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: DropdownButtonFormField<String>(
value: _selectedStoreId,
decoration: const InputDecoration(
labelText: '选择门店',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.store),
),
items: _stores
.map((s) => DropdownMenuItem(
value: s.orgId,
child: Text(s.name),
))
.toList(),
onChanged: (v) {
setState(() => _selectedStoreId = v);
_loadData();
},
),
);
}
Widget _buildBody() {
if (_selectedStoreId == null) {
return const Center(child: Text('请先选择门店'));
}
if (_loading && _items.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (_error != null && _items.isEmpty) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('加载失败:$_error'),
const SizedBox(height: 8),
FilledButton.tonal(
onPressed: _loadData,
child: const Text('重试'),
),
],
),
);
}
if (_items.isEmpty) {
return RefreshIndicator(
onRefresh: _loadData,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const [
SizedBox(height: 200),
Center(child: Text('暂无分组数据')),
],
),
);
}
return RefreshIndicator(
onRefresh: _loadData,
child: ListView.builder(
controller: _scrollController,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: _items.length + 1,
itemBuilder: (context, index) {
if (index == _items.length) {
return _loading
? const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
)
: const SizedBox.shrink();
}
final group = _items[index];
return _GroupListTile(
group: group,
onEdit: () => _showAddEditSheet(group: group),
onDelete: () => _deleteGroup(group),
);
},
),
);
}
}
/// 分组列表项。
class _GroupListTile extends StatelessWidget {
const _GroupListTile({
required this.group,
required this.onEdit,
required this.onDelete,
});
final OrgNode group;
final VoidCallback onEdit;
final VoidCallback onDelete;
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: ListTile(
leading: const CircleAvatar(
child: Icon(Icons.folder_outlined),
),
title: Text(group.name),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
if (group.address.isNotEmpty)
_line(Icons.location_on, group.address),
if (group.contactPhone.isNotEmpty)
_line(Icons.phone, group.contactPhone),
_line(Icons.tag, 'ID: ${group.id}'),
],
),
trailing: PopupMenuButton<String>(
onSelected: (value) {
if (value == 'edit') {
onEdit();
} else if (value == 'delete') {
onDelete();
}
},
itemBuilder: (ctx) => [
const PopupMenuItem(value: 'edit', child: Text('编辑')),
const PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
),
);
}
Widget _line(IconData icon, String text) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 1),
child: Row(
children: [
Icon(icon, size: 14, color: Colors.grey),
const SizedBox(width: 4),
Expanded(child: Text(text, style: const TextStyle(fontSize: 13))),
],
),
);
}
}
/// 新增/编辑分组表单。
class _GroupFormSheet extends StatefulWidget {
const _GroupFormSheet({
required this.deviceService,
required this.storeId,
this.group,
required this.onSaved,
});
final DeviceService deviceService;
final String storeId;
final OrgNode? group;
final VoidCallback onSaved;
@override
State<_GroupFormSheet> createState() => _GroupFormSheetState();
}
class _GroupFormSheetState extends State<_GroupFormSheet> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
bool _saving = false;
@override
void initState() {
super.initState();
if (widget.group != null) {
_nameController.text = widget.group!.name;
}
}
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
Future<void> _save() async {
if (!_formKey.currentState!.validate()) return;
setState(() => _saving = true);
try {
final data = <String, dynamic>{
'name': _nameController.text.trim(),
'storeId': widget.storeId,
if (widget.group != null) 'id': widget.group!.id,
};
if (widget.group != null) {
await widget.deviceService.updateDeviceGroup(data);
} else {
await widget.deviceService.saveDeviceGroup(data);
}
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(widget.group != null ? '分组已更新' : '分组已创建'),
),
);
widget.onSaved();
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('保存失败:$e')),
);
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
final isEdit = widget.group != null;
return SingleChildScrollView(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: Container(
padding: const EdgeInsets.all(20),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
isEdit ? '编辑分组' : '新增分组',
style: Theme.of(context)
.textTheme
.titleLarge
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 20),
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: '分组名称',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.folder),
),
validator: (v) =>
v == null || v.trim().isEmpty ? '请输入分组名称' : null,
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: FilledButton(
onPressed: _saving ? null : _save,
child: _saving
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(isEdit ? '保存' : '创建'),
),
),
],
),
),
),
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,554 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../models/store_info.dart';
import '../../services/api_client.dart';
import '../../services/device_service.dart';
import '../../services/org_service.dart';
import '../../utils/formatters.dart';
/// 门店配置页:门店选择、配置表单、保存/重置密码。
class StoreConfigPage extends ConsumerStatefulWidget {
const StoreConfigPage({super.key});
@override
ConsumerState<StoreConfigPage> createState() => _StoreConfigPageState();
}
class _StoreConfigPageState extends ConsumerState<StoreConfigPage> {
final OrgService _orgService = OrgService();
final DeviceService _deviceService = DeviceService();
List<StoreInfo> _stores = [];
String? _selectedStoreId;
bool _loadingStores = true;
Map<String, dynamic>? _config;
bool _loading = false;
bool _saving = false;
bool _disabled = false;
String? _error;
// 表单控制器
final _defaultVolumeController = TextEditingController();
final _heartbeatIntervalController = TextEditingController();
final _storePasswordController = TextEditingController();
final _maxVolumeController = TextEditingController();
final _offlineThresholdController = TextEditingController();
final _mediaVolumeController = TextEditingController();
final _expireTimeController = TextEditingController();
@override
void initState() {
super.initState();
_loadStores();
}
@override
void dispose() {
_defaultVolumeController.dispose();
_heartbeatIntervalController.dispose();
_storePasswordController.dispose();
_maxVolumeController.dispose();
_offlineThresholdController.dispose();
_mediaVolumeController.dispose();
_expireTimeController.dispose();
super.dispose();
}
Future<void> _loadStores() async {
try {
final stores = await _orgService.getMyStores();
if (!mounted) return;
setState(() {
_stores = stores;
_loadingStores = false;
if (stores.isNotEmpty) {
_selectedStoreId = stores.first.orgId;
}
});
if (_selectedStoreId != null) {
_loadConfig();
}
} catch (e) {
if (!mounted) return;
setState(() => _loadingStores = false);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('门店列表加载失败:$e')),
);
}
}
Future<void> _loadConfig() async {
if (_selectedStoreId == null) return;
setState(() {
_loading = true;
_error = null;
});
try {
final config = await _deviceService.getStoreConfig(_selectedStoreId!);
if (!mounted) return;
_populateControllers(config);
setState(() {
_config = config;
_loading = false;
});
} catch (e) {
if (!mounted) return;
final friendly = formatApiError(e,
fallback: '门店配置加载失败,请稍后重试');
setState(() {
_error = '$friendly\n\n若持续出现「未知异常」,请联系后端排查 /device/storeConfig/info/{orgId} 接口。';
_loading = false;
});
}
}
void _populateControllers(Map<String, dynamic> config) {
// 字段名以 Web 后台 StoreConfig 模型为准(systemDefaultVolume / password),
// 同时兼容旧移动端字段名(defaultVolume / storePassword),避免回显为空。
_defaultVolumeController.text =
_toString(config['systemDefaultVolume'] ?? config['defaultVolume']);
_heartbeatIntervalController.text =
_toString(config['heartbeatInterval']);
_storePasswordController.text =
_toString(config['password'] ?? config['storePassword']);
_maxVolumeController.text = _toString(config['maxVolume']);
_offlineThresholdController.text =
_toString(config['offlineThreshold']);
_mediaVolumeController.text =
_toString(config['mediaVolume'] ?? config['media_volume']);
_expireTimeController.text = _toString(config['expireTime']);
_disabled = _parseDisabled(config['disabled']);
}
/// 解析禁用状态:true / 非零 num / 字符串 '1' 视为禁用=true,其余 false。
static bool _parseDisabled(dynamic value) {
if (value == true) return true;
if (value is num) return value != 0;
if (value is String) return value.trim() == '1';
return false;
}
static String _toString(dynamic value) {
if (value == null) return '';
return value.toString();
}
Future<void> _save() async {
if (_selectedStoreId == null) return;
setState(() => _saving = true);
try {
// 字段名以 Web 后台 StoreConfig 模型为准(见 screen-front src/api/device.ts):
// systemDefaultVolume / maxVolume / heartbeatInterval / password / expireTime。
// 仅发送非空字段,避免把后端既有值覆盖为空;密码留空则不传(与 Web 一致,
// 防止误清空)。offlineThreshold 为旧移动端遗留字段,后端忽略无害,保留发送。
final data = <String, dynamic>{'orgId': _selectedStoreId};
final sysDef = _defaultVolumeController.text.trim();
final vSysDef = int.tryParse(sysDef);
if (sysDef.isNotEmpty && vSysDef != null) {
data['systemDefaultVolume'] = vSysDef;
}
final max = _maxVolumeController.text.trim();
final vMax = int.tryParse(max);
if (max.isNotEmpty && vMax != null) data['maxVolume'] = vMax;
final hb = _heartbeatIntervalController.text.trim();
final vHb = int.tryParse(hb);
if (hb.isNotEmpty && vHb != null) data['heartbeatInterval'] = vHb;
final off = _offlineThresholdController.text.trim();
final vOff = int.tryParse(off);
if (off.isNotEmpty && vOff != null) data['offlineThreshold'] = vOff;
final pwd = _storePasswordController.text.trim();
if (pwd.isNotEmpty) data['password'] = pwd;
final exp = _expireTimeController.text.trim();
if (exp.isNotEmpty) data['expireTime'] = exp;
final media = _mediaVolumeController.text.trim();
final vMedia = int.tryParse(media);
if (media.isNotEmpty && vMedia != null) data['mediaVolume'] = vMedia;
// disabled 始终发送当前开关状态(布尔值),确保与 Web 后台一致。
data['disabled'] = _disabled;
await _deviceService.createOrUpdateStoreConfig(data);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('配置已保存')),
);
_loadConfig();
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('保存失败:${formatApiError(e)}')),
);
} finally {
if (mounted) setState(() => _saving = false);
}
}
Future<void> _resetPassword() async {
if (_selectedStoreId == null) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('重置密码'),
content: const Text('确定要重置门店配置密码吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
style: TextButton.styleFrom(foregroundColor: Colors.orange),
child: const Text('重置'),
),
],
),
);
if (confirmed != true) return;
try {
await _deviceService.resetStoreConfigPassword(_selectedStoreId!);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('密码已重置')),
);
_loadConfig();
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('重置失败:${formatApiError(e)}')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('门店配置'),
),
body: Column(
children: [
_buildStoreSelector(),
const Divider(height: 1),
Expanded(child: _buildBody()),
],
),
);
}
Widget _buildStoreSelector() {
if (_loadingStores) {
return const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
);
}
if (_stores.isEmpty) {
return const Padding(
padding: EdgeInsets.all(16),
child: Text('暂无可选门店'),
);
}
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: DropdownButtonFormField<String>(
value: _selectedStoreId,
decoration: const InputDecoration(
labelText: '选择门店',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.store),
),
items: _stores
.map((s) => DropdownMenuItem(
value: s.orgId,
child: Text(s.name),
))
.toList(),
onChanged: (v) {
setState(() => _selectedStoreId = v);
_loadConfig();
},
),
);
}
Widget _buildBody() {
if (_selectedStoreId == null) {
return const Center(child: Text('请先选择门店'));
}
if (_loading) {
return const Center(child: CircularProgressIndicator());
}
if (_error != null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('加载失败:$_error'),
const SizedBox(height: 8),
FilledButton.tonal(
onPressed: _loadConfig,
child: const Text('重试'),
),
],
),
);
}
if (_config == null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.settings_outlined,
size: 64,
color: Theme.of(context).colorScheme.outline),
const SizedBox(height: 16),
const Text('暂无配置信息'),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: _save,
icon: const Icon(Icons.add),
label: const Text('创建配置'),
),
],
),
);
}
return RefreshIndicator(
onRefresh: _loadConfig,
child: ListView(
padding: const EdgeInsets.all(16),
physics: const AlwaysScrollableScrollPhysics(),
children: [
_buildConfigForm(),
const SizedBox(height: 16),
_buildExtraInfo(),
const SizedBox(height: 24),
_buildActions(),
],
),
);
}
Widget _buildConfigForm() {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'配置项',
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
TextFormField(
controller: _defaultVolumeController,
decoration: const InputDecoration(
labelText: '系统默认音量',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.volume_up),
helperText: '设备系统默认音量 (0-100)',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 12),
TextFormField(
controller: _mediaVolumeController,
decoration: const InputDecoration(
labelText: '媒体区域音量',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.volume_down),
helperText: '媒体播放区域音量 (0-100)',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 12),
TextFormField(
controller: _maxVolumeController,
decoration: const InputDecoration(
labelText: '最大音量',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.volume_up_sharp),
helperText: '设备允许的最大音量',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 12),
TextFormField(
controller: _heartbeatIntervalController,
decoration: const InputDecoration(
labelText: '心跳间隔 (秒)',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.favorite),
helperText: '设备心跳上报间隔',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 12),
TextFormField(
controller: _offlineThresholdController,
decoration: const InputDecoration(
labelText: '离线阈值 (秒)',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.timer_off),
helperText: '超过此时间无心跳则判定离线',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 12),
TextFormField(
controller: _storePasswordController,
decoration: const InputDecoration(
labelText: '门店密码',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock),
helperText: '设备绑定门店时的验证密码',
),
obscureText: true,
),
const SizedBox(height: 12),
TextFormField(
controller: _expireTimeController,
decoration: InputDecoration(
labelText: '到期时间',
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.event),
helperText: '留空则不修改;格式 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss',
suffixIcon: IconButton(
icon: const Icon(Icons.calendar_month),
tooltip: '选择日期',
onPressed: _saving ? null : _pickExpireDate,
),
),
keyboardType: TextInputType.datetime,
),
const SizedBox(height: 12),
Row(
children: [
const SizedBox(width: 84, child: Text('禁用')),
SegmentedButton<bool>(
segments: const [
ButtonSegment(value: false, label: Text('否')),
ButtonSegment(value: true, label: Text('是')),
],
selected: {_disabled},
onSelectionChanged: (set) => setState(() => _disabled = set.first),
),
],
),
],
),
),
);
}
Future<void> _pickExpireDate() async {
final current = _expireTimeController.text.trim();
final initial = DateTime.tryParse(current) ??
DateTime.tryParse(current.replaceFirst(' ', 'T')) ??
DateTime.now();
final picked = await showDatePicker(
context: context,
initialDate: initial,
firstDate: DateTime(2000),
lastDate: DateTime(2100),
);
if (picked != null && mounted) {
setState(() =>
_expireTimeController.text = picked.toIso8601String().substring(0, 10));
}
}
Widget _buildExtraInfo() {
final theme = Theme.of(context);
final createTime = _config?['createTime'];
final updateTime = _config?['updateTime'];
String _fmt(dynamic t) {
if (t == null) return '—';
final text = t.toString().trim();
if (text.isEmpty) return '—';
final dt = DateTime.tryParse(text) ??
DateTime.tryParse(text.replaceFirst(' ', 'T'));
return dt != null ? Formatters.formatDateTime(dt) : text;
}
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'其他信息',
style: theme.textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
_infoRow(theme, '创建时间', _fmt(createTime)),
_infoRow(theme, '更新时间', _fmt(updateTime)),
],
),
),
);
}
Widget _buildActions() {
return Row(
children: [
Expanded(
child: FilledButton.icon(
onPressed: _saving ? null : _save,
icon: _saving
? const SizedBox(
height: 18,
width: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.save),
label: const Text('保存配置'),
),
),
const SizedBox(width: 12),
Expanded(
child: OutlinedButton.icon(
onPressed: _resetPassword,
style: OutlinedButton.styleFrom(
foregroundColor: Colors.orange,
),
icon: const Icon(Icons.password),
label: const Text('重置密码'),
),
),
],
);
}
Widget _infoRow(ThemeData theme, String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
children: [
SizedBox(
width: 80,
child: Text(
label,
style: theme.textTheme.bodyMedium
?.copyWith(color: theme.colorScheme.onSurfaceVariant),
),
),
Expanded(
child: Text(value,
style: theme.textTheme.bodyMedium
?.copyWith(fontWeight: FontWeight.w600)),
),
],
),
);
}
}