expense_detail_page.dart 25 KB

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