expense_detail_page.dart 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  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 '../../shared/widgets/loading_dialog.dart';
  6. import '../../core/utils/date_utils.dart' as du;
  7. import '../../shared/widgets/form_section.dart';
  8. import '../../shared/widgets/form_field_row.dart';
  9. import '../../shared/widgets/app_skeletons.dart';
  10. import '../../shared/widgets/attachment_download_helper.dart';
  11. import '../../core/navigation/host_app_channel.dart';
  12. import 'expense_model.dart';
  13. import '../../core/i18n/app_localizations.dart';
  14. import '../../shared/models/bill_attachment.dart';
  15. import '../../shared/models/bill_file_rights.dart';
  16. import '../../core/theme/app_colors.dart';
  17. import '../../core/theme/app_colors_extension.dart';
  18. import 'expense_api.dart';
  19. import 'dart:io';
  20. import 'package:path_provider/path_provider.dart';
  21. import 'package:open_filex/open_filex.dart';
  22. import '../../shared/widgets/attachment_preview_page.dart';
  23. import 'widgets/expense_detail_view_dialog.dart';
  24. import '../../core/utils/amount_utils.dart';
  25. import '../../shared/widgets/bill_status_bar.dart';
  26. import 'package:go_router/go_router.dart';
  27. class ExpenseDetailPage extends ConsumerStatefulWidget {
  28. final String billNo;
  29. final int queryId;
  30. const ExpenseDetailPage({super.key, required this.billNo, this.queryId = 0});
  31. @override
  32. ConsumerState<ExpenseDetailPage> createState() => _ExpenseDetailPageState();
  33. }
  34. class _ExpenseDetailPageState extends ConsumerState<ExpenseDetailPage> {
  35. ExpenseModel? _expense;
  36. List<BillAttachment> _attachments = [];
  37. bool _attachAvailable = false;
  38. BillFileRights _billFileRights = BillFileRights.none;
  39. bool _isLoading = true;
  40. String? _error;
  41. BillStatusBar? _billStatusBar;
  42. @override
  43. void initState() {
  44. super.initState();
  45. _loadData();
  46. }
  47. @override
  48. void dispose() {
  49. super.dispose();
  50. }
  51. Future<void> _loadData() async {
  52. setState(() {
  53. _isLoading = true;
  54. _error = null;
  55. });
  56. try {
  57. final api = ref.read(expenseApiProvider);
  58. // 1. 加载报销详情(主表 + 明细)
  59. final expense = await api.fetchDetail(widget.billNo);
  60. setState(() => _expense = expense);
  61. // 2. 加载附件权限(非致命)
  62. BillFileRights billFileRights = BillFileRights.none;
  63. try {
  64. billFileRights = await api.getBillFileRights('BX');
  65. } catch (_) {}
  66. // 3. 加载附件(非致命)
  67. try {
  68. _attachAvailable = await api.checkAttachHealth();
  69. } catch (_) {
  70. _attachAvailable = false;
  71. }
  72. _billFileRights = billFileRights;
  73. if (_attachAvailable && billFileRights.canBrowseAttachments) {
  74. try {
  75. _attachments = await api.getAttachments('BX', widget.billNo);
  76. } catch (_) {
  77. _attachments = [];
  78. }
  79. }
  80. // 3. 获取单据状态 + 审核配置(非致命)
  81. try {
  82. final results = await Future.wait([
  83. api.getBillStatus(widget.billNo),
  84. api.getBillAuditConfig('BX'),
  85. ]);
  86. final Map<String, dynamic> status = results[0];
  87. final Map<String, dynamic> auditConfig = results[1];
  88. final canManualSubmit =
  89. auditConfig['hasAuditFlow'] == true &&
  90. auditConfig['autoSubmit'] != true;
  91. if (mounted) {
  92. setState(() {
  93. final l10n = AppLocalizations.of(context);
  94. _billStatusBar = BillStatusBar(
  95. billStatus: status,
  96. canManualSubmit: canManualSubmit,
  97. closedText: l10n.get('statusClosed'),
  98. transferredText: l10n.get('statusTransferred'),
  99. onEdit: status['canEdit'] == true
  100. ? () => GoRouter.of(context)
  101. .push('/expense/edit/${widget.billNo}')
  102. .then((result) {
  103. if (result == true && mounted) _loadData();
  104. })
  105. : null,
  106. onSubmit: () async {
  107. final l10n = AppLocalizations.of(context);
  108. final dd = _expense?.expenseDate != null
  109. ? du.DateUtils.formatDate(_expense!.expenseDate!)
  110. : '';
  111. LoadingDialog.show(context, text: l10n.get('submitting'));
  112. try {
  113. await api.shSubmit(bilNo: widget.billNo, bilDd: dd);
  114. } finally {
  115. if (mounted) LoadingDialog.hide(context);
  116. }
  117. if (mounted) _loadData();
  118. },
  119. onCancelSubmit: () async {
  120. final l10n = AppLocalizations.of(context);
  121. final dd = _expense?.expenseDate != null
  122. ? du.DateUtils.formatDate(_expense!.expenseDate!)
  123. : '';
  124. LoadingDialog.show(context, text: l10n.get('submitting'));
  125. try {
  126. await api.shSubmit(
  127. bilNo: widget.billNo,
  128. bilDd: dd,
  129. isCancel: true,
  130. );
  131. } finally {
  132. if (mounted) LoadingDialog.hide(context);
  133. }
  134. if (mounted) _loadData();
  135. },
  136. onTapStatusTag: () => _showAuditTrail('BX'),
  137. );
  138. });
  139. }
  140. } catch (_) {
  141. // 获取单据状态失败,忽略
  142. }
  143. } catch (e) {
  144. setState(() => _error = e.toString());
  145. } finally {
  146. setState(() {
  147. _isLoading = false;
  148. });
  149. }
  150. }
  151. @override
  152. Widget build(BuildContext context) {
  153. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  154. final l10n = AppLocalizations.of(context);
  155. if (_isLoading) {
  156. return const SkeletonDetailPage();
  157. }
  158. if (_error != null) {
  159. return Center(
  160. child: Column(
  161. mainAxisAlignment: MainAxisAlignment.center,
  162. children: [
  163. Icon(Icons.error_outline, size: 48, color: colors.danger),
  164. const SizedBox(height: 12),
  165. Text(
  166. _error!,
  167. style: TextStyle(
  168. fontSize: AppFontSizes.body,
  169. color: colors.danger,
  170. ),
  171. textAlign: TextAlign.center,
  172. ),
  173. const SizedBox(height: 16),
  174. TDButton(
  175. text: l10n.get('retry'),
  176. theme: TDButtonTheme.primary,
  177. onTap: _loadData,
  178. ),
  179. ],
  180. ),
  181. );
  182. }
  183. final expense = _expense!;
  184. return Column(
  185. children: [
  186. Expanded(
  187. child: SingleChildScrollView(
  188. physics: const AlwaysScrollableScrollPhysics(),
  189. padding: const EdgeInsets.all(16),
  190. child: Column(
  191. children: [
  192. _buildBasicInfoSection(expense, l10n, colors),
  193. const SizedBox(height: 16),
  194. _buildExpenseDetailSection(expense, l10n, colors),
  195. const SizedBox(height: 16),
  196. _buildAttachmentSection(l10n, colors),
  197. const SizedBox(height: 24),
  198. _buildPageFooter(colors),
  199. ],
  200. ),
  201. ),
  202. ),
  203. _billStatusBar?.buildActions(context) ?? const SizedBox.shrink(),
  204. ],
  205. );
  206. }
  207. Future<void> _showAuditTrail(String billId) async {
  208. await HostAppChannel.showAuditTrail(billId, widget.billNo);
  209. }
  210. // ═══ 基本信息 ═══
  211. Widget _buildBasicInfoSection(
  212. ExpenseModel expense,
  213. AppLocalizations l10n,
  214. AppColorsExtension colors,
  215. ) {
  216. return FormSection(
  217. title: l10n.get('basicInfo'),
  218. leadingIcon: Icons.info_outline,
  219. trailing:
  220. _billStatusBar?.buildStatusTag(context) ?? const SizedBox.shrink(),
  221. children: [
  222. FormFieldRow(
  223. label: l10n.get('expenseNo'),
  224. value: expense.expenseNo,
  225. readOnly: true,
  226. showArrow: false,
  227. ),
  228. const SizedBox(height: 16),
  229. FormFieldRow(
  230. label: l10n.get('date'),
  231. value: du.DateUtils.formatDate(expense.createTime),
  232. readOnly: true,
  233. showArrow: false,
  234. ),
  235. const SizedBox(height: 16),
  236. FormFieldRow(
  237. label: l10n.get('expensePersonnel'),
  238. value: expense.applicantId.isNotEmpty
  239. ? '${expense.applicantId}${expense.applicantName.isNotEmpty ? '/${expense.applicantName}' : ''}'
  240. : '-',
  241. readOnly: true,
  242. showArrow: false,
  243. ),
  244. const SizedBox(height: 16),
  245. FormFieldRow(
  246. label: l10n.get('expenseDept'),
  247. value: expense.deptId.isNotEmpty
  248. ? '${expense.deptId}${expense.deptName.isNotEmpty ? '/${expense.deptName}' : ''}'
  249. : '-',
  250. readOnly: true,
  251. showArrow: false,
  252. ),
  253. const SizedBox(height: 16),
  254. FormFieldRow(
  255. label: l10n.get('expenseReason'),
  256. value: expense.purpose.isNotEmpty ? expense.purpose : '-',
  257. readOnly: true,
  258. showArrow: false,
  259. bold: true,
  260. showMoreOnOverflow: true,
  261. ),
  262. const SizedBox(height: 16),
  263. FormFieldRow(
  264. label: l10n.get('voucherNo'),
  265. value: expense.voucherNo.isNotEmpty ? expense.voucherNo : '-',
  266. readOnly: true,
  267. showArrow: false,
  268. ),
  269. const SizedBox(height: 16),
  270. FormFieldRow(
  271. label: l10n.get('currency'),
  272. value: expense.currencyCode.isNotEmpty ? expense.currencyCode : '-',
  273. readOnly: true,
  274. showArrow: false,
  275. ),
  276. const SizedBox(height: 16),
  277. FormFieldRow(
  278. label: l10n.get('paymentMethod'),
  279. value: expense.paymentMethod.isNotEmpty ? expense.paymentMethod : '-',
  280. readOnly: true,
  281. showArrow: false,
  282. ),
  283. const SizedBox(height: 16),
  284. FormFieldRow(
  285. label: l10n.get('remark'),
  286. value: expense.remark.isNotEmpty ? expense.remark : '-',
  287. readOnly: true,
  288. showArrow: false,
  289. ),
  290. ],
  291. );
  292. }
  293. // ═══ 费用明细 ═══
  294. Widget _buildExpenseDetailSection(
  295. ExpenseModel expense,
  296. AppLocalizations l10n,
  297. AppColorsExtension colors,
  298. ) {
  299. final totalAmount = expense.details.fold<double>(
  300. 0,
  301. (sum, d) => sum + d.totalAmount,
  302. );
  303. final totalApproved = expense.details.fold<double>(
  304. 0,
  305. (sum, d) => sum + d.approvedAmount,
  306. );
  307. return FormSection(
  308. title: l10n.get('expenseDetails'),
  309. leadingIcon: Icons.receipt_long_outlined,
  310. children: [
  311. if (expense.details.isEmpty)
  312. Padding(
  313. padding: const EdgeInsets.symmetric(vertical: 8),
  314. child: Text(
  315. l10n.get('noDetailData'),
  316. style: TextStyle(
  317. fontSize: AppFontSizes.body,
  318. color: colors.textPlaceholder,
  319. ),
  320. ),
  321. )
  322. else
  323. ...expense.details.asMap().entries.map((e) {
  324. final d = e.value;
  325. final title = d.categoryName.isNotEmpty
  326. ? '${d.expenseCategory}/${d.categoryName}'
  327. : d.expenseCategory;
  328. return GestureDetector(
  329. onTap: () => _showExpenseDetailDialog(context, d),
  330. child: Container(
  331. margin: const EdgeInsets.symmetric(vertical: 6),
  332. padding: const EdgeInsets.all(12),
  333. decoration: BoxDecoration(
  334. color: colors.bgPage,
  335. borderRadius: BorderRadius.circular(8),
  336. ),
  337. child: Row(
  338. children: [
  339. Expanded(
  340. child: Column(
  341. crossAxisAlignment: CrossAxisAlignment.start,
  342. children: [
  343. Row(
  344. children: [
  345. Expanded(
  346. child: Text(
  347. title,
  348. style: TextStyle(
  349. fontSize: AppFontSizes.body,
  350. fontWeight: FontWeight.w500,
  351. color: colors.textPrimary,
  352. ),
  353. ),
  354. ),
  355. Column(
  356. crossAxisAlignment: CrossAxisAlignment.end,
  357. children: [
  358. Text(
  359. formatAmount(d.totalAmount),
  360. style: TextStyle(
  361. fontSize: AppFontSizes.body,
  362. fontWeight: FontWeight.w600,
  363. color: colors.amountPrimary,
  364. ),
  365. ),
  366. if (d.approvedAmount > 0)
  367. Text(
  368. formatAmount(d.approvedAmount),
  369. style: TextStyle(
  370. fontSize: AppFontSizes.body,
  371. fontWeight: FontWeight.w600,
  372. color: colors.success,
  373. ),
  374. ),
  375. ],
  376. ),
  377. ],
  378. ),
  379. const SizedBox(height: 2),
  380. Text(
  381. '${l10n.get('amountExcludingTax')}: ${formatAmount(d.amount)}',
  382. style: TextStyle(
  383. fontSize: AppFontSizes.caption,
  384. color: colors.textSecondary,
  385. ),
  386. ),
  387. if (d.taxAmount > 0)
  388. Text(
  389. '${l10n.get('taxAmount')}: ${formatAmount(d.taxAmount)}',
  390. style: TextStyle(
  391. fontSize: AppFontSizes.caption,
  392. color: colors.textSecondary,
  393. ),
  394. ),
  395. if (d.taxRate > 0)
  396. Text(
  397. '${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  398. style: TextStyle(
  399. fontSize: AppFontSizes.caption,
  400. color: colors.textSecondary,
  401. ),
  402. ),
  403. if (d.acctSubjectId.isNotEmpty)
  404. Text(
  405. '${l10n.get('acctSubject')}: ${d.acctSubjectId}${d.acctSubjectName.isNotEmpty ? '/${d.acctSubjectName}' : ''}',
  406. maxLines: 1,
  407. overflow: TextOverflow.ellipsis,
  408. style: TextStyle(
  409. fontSize: AppFontSizes.caption,
  410. color: colors.textSecondary,
  411. ),
  412. ),
  413. if (d.aeNo.isNotEmpty)
  414. Text(
  415. '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  416. maxLines: 1,
  417. overflow: TextOverflow.ellipsis,
  418. style: TextStyle(
  419. fontSize: AppFontSizes.caption,
  420. color: colors.textSecondary,
  421. ),
  422. ),
  423. if (d.aeDd.isNotEmpty)
  424. Text(
  425. '${l10n.get('applyDate')}: ${d.aeDd.length >= 10 ? d.aeDd.substring(0, 10) : d.aeDd}',
  426. style: TextStyle(
  427. fontSize: AppFontSizes.caption,
  428. color: colors.textSecondary,
  429. ),
  430. ),
  431. if (d.projectId.isNotEmpty)
  432. Text(
  433. '${l10n.get('project')}: ${d.projectId}${d.projectName.isNotEmpty ? '/${d.projectName}' : ''}',
  434. maxLines: 1,
  435. overflow: TextOverflow.ellipsis,
  436. style: TextStyle(
  437. fontSize: AppFontSizes.caption,
  438. color: colors.textSecondary,
  439. ),
  440. ),
  441. if (d.costDeptId.isNotEmpty)
  442. Text(
  443. '${l10n.get('costDept')}: ${d.costDeptId}${d.costDeptName.isNotEmpty ? '/${d.costDeptName}' : ''}',
  444. maxLines: 1,
  445. overflow: TextOverflow.ellipsis,
  446. style: TextStyle(
  447. fontSize: AppFontSizes.caption,
  448. color: colors.textSecondary,
  449. ),
  450. ),
  451. if (d.customerVendorId.isNotEmpty)
  452. Text(
  453. '${l10n.get('customerVendor')}: ${d.customerVendorId}${d.customerVendorName.isNotEmpty ? '/${d.customerVendorName}' : ''}',
  454. maxLines: 1,
  455. overflow: TextOverflow.ellipsis,
  456. style: TextStyle(
  457. fontSize: AppFontSizes.caption,
  458. color: colors.textSecondary,
  459. ),
  460. ),
  461. if (d.sqMan.isNotEmpty)
  462. Text(
  463. '${l10n.get('applicant')}: ${d.sqMan}${d.sqManName.isNotEmpty ? '/${d.sqManName}' : ''}',
  464. style: TextStyle(
  465. fontSize: AppFontSizes.caption,
  466. color: colors.textSecondary,
  467. ),
  468. ),
  469. if (d.bankAccountName.isNotEmpty)
  470. Text(
  471. '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  472. maxLines: 1,
  473. overflow: TextOverflow.ellipsis,
  474. style: TextStyle(
  475. fontSize: AppFontSizes.caption,
  476. color: colors.textSecondary,
  477. ),
  478. ),
  479. if (d.bankName.isNotEmpty)
  480. Text(
  481. '${l10n.get('bankName')}: ${d.bankName}',
  482. maxLines: 1,
  483. overflow: TextOverflow.ellipsis,
  484. style: TextStyle(
  485. fontSize: AppFontSizes.caption,
  486. color: colors.textSecondary,
  487. ),
  488. ),
  489. if (d.bankAccount.isNotEmpty)
  490. Text(
  491. '${l10n.get('bankAccount')}: ${d.bankAccount}',
  492. maxLines: 1,
  493. overflow: TextOverflow.ellipsis,
  494. style: TextStyle(
  495. fontSize: AppFontSizes.caption,
  496. color: colors.textSecondary,
  497. ),
  498. ),
  499. if (d.remark.isNotEmpty)
  500. Text(
  501. '${l10n.get('remark')}: ${d.remark}',
  502. maxLines: 2,
  503. overflow: TextOverflow.ellipsis,
  504. style: TextStyle(
  505. fontSize: AppFontSizes.caption,
  506. color: colors.textSecondary,
  507. ),
  508. ),
  509. ],
  510. ),
  511. ),
  512. ],
  513. ),
  514. ),
  515. );
  516. }),
  517. if (expense.details.isNotEmpty) ...[
  518. const SizedBox(height: 8),
  519. Row(
  520. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  521. children: [
  522. Text(
  523. l10n.get('totalExpense'),
  524. style: TextStyle(
  525. fontSize: AppFontSizes.body,
  526. fontWeight: FontWeight.w600,
  527. color: colors.textPrimary,
  528. ),
  529. ),
  530. Text(
  531. formatAmount(totalAmount),
  532. style: TextStyle(
  533. fontSize: AppFontSizes.subtitle,
  534. fontWeight: FontWeight.w700,
  535. color: colors.amountPrimary,
  536. ),
  537. ),
  538. ],
  539. ),
  540. const SizedBox(height: 4),
  541. Row(
  542. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  543. children: [
  544. Text(
  545. l10n.get('approvedTotal'),
  546. style: TextStyle(
  547. fontSize: AppFontSizes.body,
  548. fontWeight: FontWeight.w600,
  549. color: colors.textPrimary,
  550. ),
  551. ),
  552. Text(
  553. formatAmount(totalApproved),
  554. style: TextStyle(
  555. fontSize: AppFontSizes.subtitle,
  556. fontWeight: FontWeight.w700,
  557. color: totalApproved > 0
  558. ? colors.success
  559. : colors.textPrimary,
  560. ),
  561. ),
  562. ],
  563. ),
  564. ],
  565. ],
  566. );
  567. }
  568. void _showExpenseDetailDialog(BuildContext context, ExpenseDetailModel d) {
  569. ExpenseDetailViewDialog.show(context, d);
  570. }
  571. // ═══ 附件 ═══
  572. Widget _buildAttachmentSection(
  573. AppLocalizations l10n,
  574. AppColorsExtension colors,
  575. ) {
  576. if (!_attachAvailable) {
  577. return FormSection(
  578. title: l10n.get('attachments'),
  579. leadingIcon: Icons.attach_file_outlined,
  580. children: [
  581. Text(
  582. l10n.get('attachServiceUnavailable'),
  583. style: TextStyle(
  584. fontSize: AppFontSizes.body,
  585. color: colors.textPlaceholder,
  586. ),
  587. ),
  588. ],
  589. );
  590. }
  591. if (!_billFileRights.canBrowseAttachments) {
  592. return FormSection(
  593. title: l10n.get('attachments'),
  594. leadingIcon: Icons.attach_file_outlined,
  595. children: [
  596. Text(
  597. l10n.get('noAttachmentPermission'),
  598. style: TextStyle(
  599. fontSize: AppFontSizes.body,
  600. color: colors.textPlaceholder,
  601. ),
  602. ),
  603. ],
  604. );
  605. }
  606. final headerAtts = _attachments.where((a) => a.isHeader).toList();
  607. final bodyGroups = <int, List<BillAttachment>>{};
  608. for (final a in _attachments.where((a) => a.isBody)) {
  609. bodyGroups.putIfAbsent(a.srcItm, () => []).add(a);
  610. }
  611. final children = <Widget>[];
  612. if (_attachments.isEmpty) {
  613. children.add(
  614. Text(
  615. l10n.get('noAttachment'),
  616. style: TextStyle(
  617. fontSize: AppFontSizes.body,
  618. color: colors.textPlaceholder,
  619. ),
  620. ),
  621. );
  622. } else {
  623. // 表头附件
  624. if (headerAtts.isNotEmpty) {
  625. children.add(
  626. Padding(
  627. padding: const EdgeInsets.only(bottom: 8),
  628. child: Text(
  629. l10n.get('headerAttachments'),
  630. style: TextStyle(
  631. fontSize: AppFontSizes.caption,
  632. fontWeight: FontWeight.w600,
  633. color: colors.textSecondary,
  634. ),
  635. ),
  636. ),
  637. );
  638. for (final a in headerAtts) {
  639. children.add(_buildAttachmentRow(a, colors));
  640. }
  641. }
  642. // 表身附件(按明细行分组)
  643. for (final entry in bodyGroups.entries) {
  644. children.add(const SizedBox(height: 8));
  645. children.add(
  646. Padding(
  647. padding: const EdgeInsets.only(bottom: 8),
  648. child: Text(
  649. '${l10n.get('detailLine')} ${entry.key}',
  650. style: TextStyle(
  651. fontSize: AppFontSizes.caption,
  652. fontWeight: FontWeight.w600,
  653. color: colors.textSecondary,
  654. ),
  655. ),
  656. ),
  657. );
  658. for (final a in entry.value) {
  659. children.add(_buildAttachmentRow(a, colors));
  660. }
  661. }
  662. }
  663. return FormSection(
  664. title: l10n.get('attachments'),
  665. leadingIcon: Icons.attach_file_outlined,
  666. children: children,
  667. );
  668. }
  669. Widget _buildAttachmentRow(BillAttachment a, AppColorsExtension colors) {
  670. final isImage = [
  671. 'jpg',
  672. 'jpeg',
  673. 'png',
  674. 'gif',
  675. 'bmp',
  676. 'webp',
  677. ].contains(a.ext.toLowerCase());
  678. return GestureDetector(
  679. onTap: () => _openAttachment(a),
  680. child: Container(
  681. margin: const EdgeInsets.symmetric(vertical: 4),
  682. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  683. decoration: BoxDecoration(
  684. color: colors.bgPage,
  685. borderRadius: BorderRadius.circular(8),
  686. ),
  687. child: Row(
  688. children: [
  689. if (isImage)
  690. _ExpAttachmentThumbnail(
  691. api: ref.read(expenseApiProvider),
  692. attachment: a,
  693. size: 40,
  694. )
  695. else
  696. Icon(_fileTypeIcon(a.ext), size: 40, color: colors.primary),
  697. const SizedBox(width: 10),
  698. Expanded(
  699. child: Text(
  700. a.fileName,
  701. maxLines: 1,
  702. overflow: TextOverflow.ellipsis,
  703. style: TextStyle(
  704. fontSize: AppFontSizes.body,
  705. color: colors.textPrimary,
  706. ),
  707. ),
  708. ),
  709. const SizedBox(width: 8),
  710. GestureDetector(
  711. onTap: () => AttachmentDownloadHelper.downloadAndSave(
  712. context,
  713. a,
  714. ref.read(expenseApiProvider).downloadAttachment,
  715. ),
  716. child: Icon(
  717. Icons.download_outlined,
  718. size: 22,
  719. color: colors.primary,
  720. ),
  721. ),
  722. ],
  723. ),
  724. ),
  725. );
  726. }
  727. Future<void> _openAttachment(BillAttachment a) async {
  728. final l10n = AppLocalizations.of(context);
  729. final ext = a.ext.toLowerCase();
  730. final isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].contains(ext);
  731. if (isImage) {
  732. // 图片 → 弹窗预览,内部自动下载并显示 loading
  733. final api = ref.read(expenseApiProvider);
  734. AttachmentPreview.show(
  735. context,
  736. loader: api.downloadAttachment(a.id),
  737. fileName: a.fileName,
  738. loadingText: l10n.get('loading'),
  739. );
  740. return;
  741. }
  742. // 非图片 → 下载后调用系统工具打开
  743. try {
  744. LoadingDialog.show(context, text: l10n.get('downloading'));
  745. final api = ref.read(expenseApiProvider);
  746. final bytes = await api.downloadAttachment(a.id);
  747. if (!mounted) return;
  748. LoadingDialog.hide(context);
  749. if (bytes == null) {
  750. TDToast.showText(l10n.get('downloadFailed'), context: context);
  751. return;
  752. }
  753. final dir = await getTemporaryDirectory();
  754. final file = File('${dir.path}/${a.fileName}');
  755. await file.writeAsBytes(bytes);
  756. await OpenFilex.open(file.path);
  757. } catch (_) {
  758. if (mounted) LoadingDialog.hide(context);
  759. if (mounted) TDToast.showText(l10n.get('openFailed'), context: context);
  760. }
  761. }
  762. IconData _fileTypeIcon(String ext) {
  763. switch (ext.toLowerCase()) {
  764. case 'pdf':
  765. return Icons.picture_as_pdf;
  766. case 'doc':
  767. case 'docx':
  768. return Icons.description;
  769. case 'xls':
  770. case 'xlsx':
  771. return Icons.table_chart;
  772. case 'jpg':
  773. case 'jpeg':
  774. case 'png':
  775. case 'gif':
  776. case 'bmp':
  777. return Icons.image_outlined;
  778. default:
  779. return Icons.insert_drive_file;
  780. }
  781. }
  782. Widget _buildPageFooter(AppColorsExtension colors) {
  783. final l10n = AppLocalizations.of(context);
  784. return Center(
  785. child: Padding(
  786. padding: const EdgeInsets.only(bottom: 16),
  787. child: Row(
  788. mainAxisSize: MainAxisSize.min,
  789. children: [
  790. Icon(
  791. Icons.rocket_launch_outlined,
  792. size: 16,
  793. color: colors.textPlaceholder,
  794. ),
  795. const SizedBox(width: 6),
  796. Text(
  797. l10n.get('pageFooter'),
  798. style: TextStyle(
  799. fontSize: AppFontSizes.caption,
  800. color: colors.textPlaceholder,
  801. ),
  802. ),
  803. ],
  804. ),
  805. ),
  806. );
  807. }
  808. }
  809. /// 附件缩略图 — 自动调用 DownloadAttachment 加载图片
  810. class _ExpAttachmentThumbnail extends StatefulWidget {
  811. final ExpenseApi api;
  812. final BillAttachment attachment;
  813. final double size;
  814. const _ExpAttachmentThumbnail({
  815. required this.api,
  816. required this.attachment,
  817. required this.size,
  818. });
  819. @override
  820. State<_ExpAttachmentThumbnail> createState() =>
  821. _ExpAttachmentThumbnailState();
  822. }
  823. class _ExpAttachmentThumbnailState extends State<_ExpAttachmentThumbnail> {
  824. Uint8List? _bytes;
  825. bool _loading = true;
  826. @override
  827. void initState() {
  828. super.initState();
  829. _load();
  830. }
  831. Future<void> _load() async {
  832. try {
  833. final bytes = await widget.api.downloadAttachment(widget.attachment.id);
  834. if (mounted) {
  835. setState(() {
  836. _bytes = bytes;
  837. _loading = false;
  838. });
  839. }
  840. } catch (_) {
  841. if (mounted) setState(() => _loading = false);
  842. }
  843. }
  844. @override
  845. Widget build(BuildContext context) {
  846. if (_loading) {
  847. return SizedBox(
  848. width: widget.size,
  849. height: widget.size,
  850. child: const Center(
  851. child: SizedBox(
  852. width: 16,
  853. height: 16,
  854. child: CircularProgressIndicator(strokeWidth: 2),
  855. ),
  856. ),
  857. );
  858. }
  859. if (_bytes != null) {
  860. return ClipRRect(
  861. borderRadius: BorderRadius.circular(4),
  862. child: Image.memory(
  863. _bytes!,
  864. width: widget.size,
  865. height: widget.size,
  866. fit: BoxFit.cover,
  867. ),
  868. );
  869. }
  870. return Icon(
  871. Icons.broken_image,
  872. size: widget.size * 0.6,
  873. color: Colors.grey,
  874. );
  875. }
  876. }