expense_detail_page.dart 21 KB

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