expense_detail_page.dart 29 KB

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