expense_detail_page.dart 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import 'dart:typed_data';
  2. import 'package:flutter/material.dart';
  3. import 'package:tdesign_flutter/tdesign_flutter.dart';
  4. import 'package:flutter_riverpod/flutter_riverpod.dart';
  5. import 'package:go_router/go_router.dart';
  6. import '../../shared/widgets/nav_bar_config.dart';
  7. import '../../shared/widgets/loading_dialog.dart';
  8. import '../../core/utils/date_utils.dart' as du;
  9. import '../../shared/widgets/form_section.dart';
  10. import '../../shared/widgets/form_field_row.dart';
  11. import '../../shared/widgets/app_skeletons.dart';
  12. import 'expense_model.dart';
  13. import '../../core/i18n/app_localizations.dart';
  14. import '../../shared/models/bill_attachment.dart';
  15. import '../../core/theme/app_colors.dart';
  16. import '../../core/theme/app_colors_extension.dart';
  17. import 'expense_api.dart';
  18. import 'dart:io';
  19. import 'package:path_provider/path_provider.dart';
  20. import 'package:open_filex/open_filex.dart';
  21. import '../expense_apply/widgets/attachment_preview_page.dart';
  22. class ExpenseDetailPage extends ConsumerStatefulWidget {
  23. final String billNo;
  24. final int queryId;
  25. const ExpenseDetailPage({super.key, required this.billNo, this.queryId = 0});
  26. @override
  27. ConsumerState<ExpenseDetailPage> createState() => _ExpenseDetailPageState();
  28. }
  29. class _ExpenseDetailPageState extends ConsumerState<ExpenseDetailPage>
  30. {
  31. ExpenseModel? _expense;
  32. List<BillAttachment> _attachments = [];
  33. bool _attachAvailable = false;
  34. bool _isLoading = true;
  35. String? _error;
  36. @override
  37. void initState() {
  38. super.initState();
  39. _loadData();
  40. }
  41. @override
  42. void dispose() {
  43. super.dispose();
  44. }
  45. Future<void> _loadData() async {
  46. setState(() {
  47. _isLoading = true;
  48. _error = null;
  49. });
  50. try {
  51. final api = ref.read(expenseApiProvider);
  52. // 1. 加载报销详情(主表 + 明细)
  53. final expense = await api.fetchDetail(widget.billNo);
  54. setState(() => _expense = expense);
  55. // 2. 加载附件(非致命)
  56. try {
  57. _attachAvailable = await api.checkAttachHealth();
  58. } catch (_) {
  59. _attachAvailable = false;
  60. }
  61. if (_attachAvailable) {
  62. try {
  63. _attachments = await api.getAttachments('BX', widget.billNo);
  64. } catch (_) {
  65. _attachments = [];
  66. }
  67. }
  68. } catch (e) {
  69. setState(() => _error = e.toString());
  70. } finally {
  71. setState(() { _isLoading = false; });
  72. }
  73. }
  74. @override
  75. Widget build(BuildContext context) {
  76. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  77. final l10n = AppLocalizations.of(context);
  78. setNavBarTitle(context, ref, NavBarConfig(
  79. title: l10n.get('expenseDetail'),
  80. showBack: true,
  81. onBack: () => context.pop(),
  82. ));
  83. if (_isLoading) {
  84. return const SkeletonDetailPage();
  85. }
  86. if (_error != null) {
  87. return Center(
  88. child: Column(
  89. mainAxisAlignment: MainAxisAlignment.center,
  90. children: [
  91. Icon(Icons.error_outline, size: 48, color: colors.danger),
  92. const SizedBox(height: 12),
  93. Text(
  94. _error!,
  95. style: TextStyle(fontSize: AppFontSizes.body, color: colors.danger),
  96. textAlign: TextAlign.center,
  97. ),
  98. const SizedBox(height: 16),
  99. TDButton(
  100. text: l10n.get('retry'),
  101. theme: TDButtonTheme.primary,
  102. onTap: _loadData,
  103. ),
  104. ],
  105. ),
  106. );
  107. }
  108. final expense = _expense!;
  109. return Expanded(
  110. child: SingleChildScrollView(
  111. physics: const AlwaysScrollableScrollPhysics(),
  112. padding: const EdgeInsets.all(16),
  113. child: Column(
  114. children: [
  115. _buildBasicInfoSection(expense, l10n, colors),
  116. const SizedBox(height: 16),
  117. _buildExpenseDetailSection(expense, l10n, colors),
  118. const SizedBox(height: 16),
  119. _buildAttachmentSection(l10n, colors),
  120. const SizedBox(height: 24),
  121. _buildPageFooter(colors),
  122. ],
  123. ),
  124. ),
  125. );
  126. }
  127. // ═══ 基本信息 ═══
  128. Widget _buildBasicInfoSection(
  129. ExpenseModel expense, AppLocalizations l10n, AppColorsExtension colors) {
  130. return FormSection(
  131. title: l10n.get('basicInfo'),
  132. leadingIcon: Icons.info_outline,
  133. children: [
  134. FormFieldRow(
  135. label: l10n.get('expenseNo'),
  136. value: expense.expenseNo,
  137. readOnly: true,
  138. showArrow: false),
  139. const SizedBox(height: 16),
  140. FormFieldRow(
  141. label: l10n.get('date'),
  142. value: du.DateUtils.formatDate(expense.createTime),
  143. readOnly: true,
  144. showArrow: false),
  145. const SizedBox(height: 16),
  146. FormFieldRow(
  147. label: l10n.get('expensePersonnel'),
  148. value: expense.applicantId.isNotEmpty
  149. ? '${expense.applicantId}/${expense.applicantName}'
  150. : expense.applicantName,
  151. readOnly: true,
  152. showArrow: false),
  153. const SizedBox(height: 16),
  154. FormFieldRow(
  155. label: l10n.get('expenseDept'),
  156. value: expense.deptId.isNotEmpty
  157. ? '${expense.deptId}/${expense.deptName}'
  158. : expense.deptName,
  159. readOnly: true,
  160. showArrow: false),
  161. const SizedBox(height: 16),
  162. SizedBox(
  163. height: 24,
  164. child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
  165. Text(l10n.get('expenseReason'),
  166. style: TextStyle(fontSize: AppFontSizes.subtitle, color: colors.textSecondary)),
  167. const SizedBox(width: 8),
  168. Expanded(
  169. child: Text(expense.purpose.isNotEmpty ? expense.purpose : '-',
  170. textAlign: TextAlign.end,
  171. maxLines: 2,
  172. overflow: TextOverflow.ellipsis,
  173. style: TextStyle(fontSize: AppFontSizes.subtitle, fontWeight: FontWeight.w500, color: colors.textPrimary)),
  174. ),
  175. ]),
  176. ),
  177. const SizedBox(height: 16),
  178. FormFieldRow(
  179. label: l10n.get('voucherNo'),
  180. value: expense.voucherNo.isNotEmpty ? expense.voucherNo : '-',
  181. readOnly: true,
  182. showArrow: false),
  183. const SizedBox(height: 16),
  184. FormFieldRow(
  185. label: l10n.get('currency'),
  186. value: expense.currencyCode.isNotEmpty ? expense.currencyCode : '-',
  187. readOnly: true,
  188. showArrow: false),
  189. const SizedBox(height: 16),
  190. FormFieldRow(
  191. label: l10n.get('paymentMethod'),
  192. value: expense.paymentMethod.isNotEmpty ? expense.paymentMethod : '-',
  193. readOnly: true,
  194. showArrow: false),
  195. const SizedBox(height: 16),
  196. SizedBox(
  197. height: 24,
  198. child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
  199. Text(l10n.get('remark'),
  200. style: TextStyle(fontSize: AppFontSizes.subtitle, color: colors.textSecondary)),
  201. const SizedBox(width: 8),
  202. Expanded(
  203. child: Text(expense.remark.isNotEmpty ? expense.remark : '-',
  204. textAlign: TextAlign.end,
  205. maxLines: 2,
  206. overflow: TextOverflow.ellipsis,
  207. style: TextStyle(fontSize: AppFontSizes.subtitle, fontWeight: FontWeight.w500, color: colors.textPrimary)),
  208. ),
  209. ]),
  210. ),
  211. ],
  212. );
  213. }
  214. // ═══ 费用明细 ═══
  215. Widget _buildExpenseDetailSection(
  216. ExpenseModel expense, AppLocalizations l10n, AppColorsExtension colors) {
  217. final totalAmount = expense.details.fold<double>(
  218. 0,
  219. (sum, d) => sum + d.totalAmount,
  220. );
  221. final totalApproved = expense.details.fold<double>(
  222. 0,
  223. (sum, d) => sum + d.approvedAmount,
  224. );
  225. return FormSection(
  226. title: l10n.get('expenseDetails'),
  227. leadingIcon: Icons.receipt_long_outlined,
  228. children: [
  229. if (expense.details.isEmpty)
  230. Padding(
  231. padding: const EdgeInsets.symmetric(vertical: 8),
  232. child: Text(l10n.get('noDetailData'),
  233. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder)),
  234. )
  235. else
  236. ...expense.details.asMap().entries.map((e) {
  237. final d = e.value;
  238. final title = d.categoryName.isNotEmpty
  239. ? '${d.expenseCategory}/${d.categoryName}'
  240. : (d.remark.isNotEmpty ? d.remark : (d.acctSubjectId.isNotEmpty ? d.acctSubjectId : '--'));
  241. return Container(
  242. margin: const EdgeInsets.symmetric(vertical: 6),
  243. padding: const EdgeInsets.all(12),
  244. decoration: BoxDecoration(color: colors.bgPage, borderRadius: BorderRadius.circular(8)),
  245. child: Row(
  246. children: [
  247. Expanded(
  248. child: Column(
  249. crossAxisAlignment: CrossAxisAlignment.start,
  250. children: [
  251. Row(
  252. children: [
  253. Expanded(
  254. child: Text(title,
  255. style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w500, color: colors.textPrimary)),
  256. ),
  257. Column(
  258. crossAxisAlignment: CrossAxisAlignment.end,
  259. children: [
  260. Text('¥${d.totalAmount.toStringAsFixed(2)}',
  261. style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w600, color: colors.amountPrimary)),
  262. if (d.approvedAmount > 0)
  263. Text('¥${d.approvedAmount.toStringAsFixed(2)}',
  264. style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w600, color: colors.success)),
  265. ],
  266. ),
  267. ],
  268. ),
  269. const SizedBox(height: 2),
  270. Text('${l10n.get('amountExcludingTax')}: ¥${d.amount.toStringAsFixed(2)}',
  271. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  272. if (d.taxAmount > 0)
  273. Text('${l10n.get('taxAmount')}: ¥${d.taxAmount.toStringAsFixed(2)}',
  274. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  275. if (d.approvedAmount > 0)
  276. Text('${l10n.get('approvedAmount')}: ¥${d.approvedAmount.toStringAsFixed(2)}',
  277. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w500, color: colors.success)),
  278. if (d.acctSubjectName.isNotEmpty)
  279. Text('${l10n.get('acctSubject')}: ${d.acctSubjectId}/${d.acctSubjectName}',
  280. maxLines: 1, overflow: TextOverflow.ellipsis,
  281. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  282. if (d.aeNo.isNotEmpty)
  283. Text('${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  284. maxLines: 1, overflow: TextOverflow.ellipsis,
  285. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  286. if (d.aeDd.isNotEmpty)
  287. Text('${l10n.get('applyDate')}: ${d.aeDd}',
  288. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  289. if (d.projectName.isNotEmpty)
  290. Text('${l10n.get('project')}: ${d.projectId}/${d.projectName}',
  291. maxLines: 1, overflow: TextOverflow.ellipsis,
  292. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  293. if (d.costDeptName.isNotEmpty)
  294. Text('${l10n.get('dept')}: ${d.costDeptId}/${d.costDeptName}',
  295. maxLines: 1, overflow: TextOverflow.ellipsis,
  296. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  297. if (d.customerVendorName.isNotEmpty)
  298. Text('${l10n.get('customerVendor')}: ${d.customerVendorName}',
  299. maxLines: 1, overflow: TextOverflow.ellipsis,
  300. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  301. if (d.remark.isNotEmpty)
  302. Text(d.remark,
  303. maxLines: 2, overflow: TextOverflow.ellipsis,
  304. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  305. ],
  306. ),
  307. ),
  308. ],
  309. ),
  310. );
  311. }),
  312. if (expense.details.isNotEmpty) ...[
  313. const SizedBox(height: 8),
  314. Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
  315. Text(l10n.get('total'),
  316. style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w600, color: colors.textPrimary)),
  317. Column(
  318. crossAxisAlignment: CrossAxisAlignment.end,
  319. children: [
  320. Text('¥${totalAmount.toStringAsFixed(2)}',
  321. style: TextStyle(fontSize: AppFontSizes.subtitle, fontWeight: FontWeight.w700, color: colors.amountPrimary)),
  322. if (totalApproved > 0)
  323. Text('${l10n.get('approvedAmount')} ¥${totalApproved.toStringAsFixed(2)}',
  324. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w600, color: colors.success)),
  325. ],
  326. ),
  327. ]),
  328. ],
  329. ],
  330. );
  331. }
  332. // ═══ 附件 ═══
  333. Widget _buildAttachmentSection(AppLocalizations l10n, AppColorsExtension colors) {
  334. if (!_attachAvailable) {
  335. return FormSection(
  336. title: l10n.get('attachments'),
  337. leadingIcon: Icons.attach_file_outlined,
  338. children: [Text(l10n.get('attachServiceUnavailable'),
  339. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder))],
  340. );
  341. }
  342. final headerAtts = _attachments.where((a) => a.isHeader).toList();
  343. final bodyGroups = <int, List<BillAttachment>>{};
  344. for (final a in _attachments.where((a) => a.isBody)) {
  345. bodyGroups.putIfAbsent(a.srcItm, () => []).add(a);
  346. }
  347. final children = <Widget>[];
  348. if (_attachments.isEmpty) {
  349. children.add(Text(l10n.get('noAttachment'),
  350. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder)));
  351. } else {
  352. // 表头附件
  353. if (headerAtts.isNotEmpty) {
  354. children.add(Padding(
  355. padding: const EdgeInsets.only(bottom: 8),
  356. child: Text(l10n.get('headerAttachments'),
  357. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w600, color: colors.textSecondary)),
  358. ));
  359. for (final a in headerAtts) {
  360. children.add(_buildAttachmentRow(a, colors));
  361. }
  362. }
  363. // 表身附件(按明细行分组)
  364. for (final entry in bodyGroups.entries) {
  365. children.add(const SizedBox(height: 8));
  366. children.add(Padding(
  367. padding: const EdgeInsets.only(bottom: 8),
  368. child: Text('${l10n.get('detailLine')} ${entry.key}',
  369. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w600, color: colors.textSecondary)),
  370. ));
  371. for (final a in entry.value) {
  372. children.add(_buildAttachmentRow(a, colors));
  373. }
  374. }
  375. }
  376. return FormSection(
  377. title: l10n.get('attachments'),
  378. leadingIcon: Icons.attach_file_outlined,
  379. children: children,
  380. );
  381. }
  382. Widget _buildAttachmentRow(BillAttachment a, AppColorsExtension colors) {
  383. final isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].contains(a.ext.toLowerCase());
  384. return GestureDetector(
  385. onTap: () => _openAttachment(a),
  386. child: Container(
  387. margin: const EdgeInsets.symmetric(vertical: 4),
  388. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  389. decoration: BoxDecoration(
  390. color: colors.bgPage,
  391. borderRadius: BorderRadius.circular(8),
  392. ),
  393. child: Row(children: [
  394. if (isImage)
  395. _ExpAttachmentThumbnail(api: ref.read(expenseApiProvider), attachment: a, size: 40)
  396. else
  397. Icon(_fileTypeIcon(a.ext), size: 40, color: colors.primary),
  398. const SizedBox(width: 10),
  399. Expanded(
  400. child: Text(a.fileName,
  401. maxLines: 1, overflow: TextOverflow.ellipsis,
  402. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPrimary)),
  403. ),
  404. ]),
  405. ),
  406. );
  407. }
  408. Future<void> _openAttachment(BillAttachment a) async {
  409. final l10n = AppLocalizations.of(context);
  410. final ext = a.ext.toLowerCase();
  411. final isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].contains(ext);
  412. if (isImage) {
  413. // 图片 → 弹窗预览,内部自动下载并显示 loading
  414. final api = ref.read(expenseApiProvider);
  415. AttachmentPreview.show(context,
  416. loader: api.downloadAttachment(a.id),
  417. fileName: a.fileName,
  418. loadingText: l10n.get('loading'),
  419. );
  420. return;
  421. }
  422. // 非图片 → 下载后调用系统工具打开
  423. try {
  424. LoadingDialog.show(context, text: l10n.get('downloading'));
  425. final api = ref.read(expenseApiProvider);
  426. final bytes = await api.downloadAttachment(a.id);
  427. if (!mounted) return;
  428. LoadingDialog.hide(context);
  429. if (bytes == null) {
  430. TDToast.showText(l10n.get('downloadFailed'), context: context);
  431. return;
  432. }
  433. final dir = await getTemporaryDirectory();
  434. final file = File('${dir.path}/${a.fileName}');
  435. await file.writeAsBytes(bytes);
  436. await OpenFilex.open(file.path);
  437. } catch (_) {
  438. if (mounted) LoadingDialog.hide(context);
  439. if (mounted) TDToast.showText(l10n.get('openFailed'), context: context);
  440. }
  441. }
  442. IconData _fileTypeIcon(String ext) {
  443. switch (ext.toLowerCase()) {
  444. case 'pdf': return Icons.picture_as_pdf;
  445. case 'doc': case 'docx': return Icons.description;
  446. case 'xls': case 'xlsx': return Icons.table_chart;
  447. case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp': return Icons.image_outlined;
  448. default: return Icons.insert_drive_file;
  449. }
  450. }
  451. Widget _buildPageFooter(AppColorsExtension colors) {
  452. final l10n = AppLocalizations.of(context);
  453. return Center(
  454. child: Padding(
  455. padding: const EdgeInsets.only(bottom: 16),
  456. child: Row(
  457. mainAxisSize: MainAxisSize.min,
  458. children: [
  459. Icon(Icons.rocket_launch_outlined, size: 16, color: colors.textPlaceholder),
  460. const SizedBox(width: 6),
  461. Text(l10n.get('pageFooter'),
  462. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textPlaceholder)),
  463. ],
  464. ),
  465. ),
  466. );
  467. }
  468. }
  469. /// 附件缩略图 — 自动调用 DownloadAttachment 加载图片
  470. class _ExpAttachmentThumbnail extends StatefulWidget {
  471. final ExpenseApi api;
  472. final BillAttachment attachment;
  473. final double size;
  474. const _ExpAttachmentThumbnail({required this.api, required this.attachment, required this.size});
  475. @override
  476. State<_ExpAttachmentThumbnail> createState() => _ExpAttachmentThumbnailState();
  477. }
  478. class _ExpAttachmentThumbnailState extends State<_ExpAttachmentThumbnail> {
  479. Uint8List? _bytes;
  480. bool _loading = true;
  481. @override
  482. void initState() {
  483. super.initState();
  484. _load();
  485. }
  486. Future<void> _load() async {
  487. try {
  488. final bytes = await widget.api.downloadAttachment(widget.attachment.id);
  489. if (mounted) setState(() { _bytes = bytes; _loading = false; });
  490. } catch (_) {
  491. if (mounted) setState(() => _loading = false);
  492. }
  493. }
  494. @override
  495. Widget build(BuildContext context) {
  496. if (_loading) {
  497. return SizedBox(width: widget.size, height: widget.size,
  498. child: const Center(child: SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))));
  499. }
  500. if (_bytes != null) {
  501. return ClipRRect(
  502. borderRadius: BorderRadius.circular(4),
  503. child: Image.memory(_bytes!, width: widget.size, height: widget.size, fit: BoxFit.cover),
  504. );
  505. }
  506. return Icon(Icons.broken_image, size: widget.size * 0.6, color: Colors.grey);
  507. }
  508. }