expense_detail_page.dart 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. FormFieldRow(
  260. label: l10n.get('remark'),
  261. value: expense.remark.isNotEmpty ? expense.remark : '-',
  262. readOnly: true,
  263. showArrow: false,
  264. ),
  265. ],
  266. );
  267. }
  268. // ═══ 费用明细 ═══
  269. Widget _buildExpenseDetailSection(
  270. ExpenseModel expense, AppLocalizations l10n, AppColorsExtension colors) {
  271. final totalAmount = expense.details.fold<double>(
  272. 0,
  273. (sum, d) => sum + d.totalAmount,
  274. );
  275. final totalApproved = expense.details.fold<double>(
  276. 0,
  277. (sum, d) => sum + d.approvedAmount,
  278. );
  279. return FormSection(
  280. title: l10n.get('expenseDetails'),
  281. leadingIcon: Icons.receipt_long_outlined,
  282. children: [
  283. if (expense.details.isEmpty)
  284. Padding(
  285. padding: const EdgeInsets.symmetric(vertical: 8),
  286. child: Text(l10n.get('noDetailData'),
  287. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder)),
  288. )
  289. else
  290. ...expense.details.asMap().entries.map((e) {
  291. final d = e.value;
  292. final title = d.categoryName.isNotEmpty
  293. ? '${d.expenseCategory}/${d.categoryName}'
  294. : d.expenseCategory;
  295. return GestureDetector(
  296. onTap: () => _showExpenseDetailDialog(context, d),
  297. child: Container(
  298. margin: const EdgeInsets.symmetric(vertical: 6),
  299. padding: const EdgeInsets.all(12),
  300. decoration: BoxDecoration(color: colors.bgPage, borderRadius: BorderRadius.circular(8)),
  301. child: Row(
  302. children: [
  303. Expanded(
  304. child: Column(
  305. crossAxisAlignment: CrossAxisAlignment.start,
  306. children: [
  307. Row(
  308. children: [
  309. Expanded(
  310. child: Text(title,
  311. style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w500, color: colors.textPrimary)),
  312. ),
  313. Column(
  314. crossAxisAlignment: CrossAxisAlignment.end,
  315. children: [
  316. Text('¥${d.totalAmount.toStringAsFixed(2)}',
  317. style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w600, color: colors.amountPrimary)),
  318. if (d.approvedAmount > 0)
  319. Text('¥${d.approvedAmount.toStringAsFixed(2)}',
  320. style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w600, color: colors.success)),
  321. ],
  322. ),
  323. ],
  324. ),
  325. const SizedBox(height: 2),
  326. Text('${l10n.get('amountExcludingTax')}: ¥${d.amount.toStringAsFixed(2)}',
  327. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  328. if (d.taxAmount > 0)
  329. Text('${l10n.get('taxAmount')}: ¥${d.taxAmount.toStringAsFixed(2)}',
  330. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  331. if (d.taxRate > 0)
  332. Text('${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  333. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  334. if (d.acctSubjectName.isNotEmpty)
  335. Text('${l10n.get('acctSubject')}: ${d.acctSubjectId}/${d.acctSubjectName}',
  336. maxLines: 1, overflow: TextOverflow.ellipsis,
  337. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  338. if (d.aeNo.isNotEmpty)
  339. Text('${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  340. maxLines: 1, overflow: TextOverflow.ellipsis,
  341. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  342. if (d.aeDd.isNotEmpty)
  343. Text('${l10n.get('applyDate')}: ${d.aeDd.length >= 10 ? d.aeDd.substring(0, 10) : d.aeDd}',
  344. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  345. if (d.projectName.isNotEmpty)
  346. Text('${l10n.get('project')}: ${d.projectId}/${d.projectName}',
  347. maxLines: 1, overflow: TextOverflow.ellipsis,
  348. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  349. if (d.costDeptName.isNotEmpty)
  350. Text('${l10n.get('costDept')}: ${d.costDeptId}/${d.costDeptName}',
  351. maxLines: 1, overflow: TextOverflow.ellipsis,
  352. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  353. if (d.customerVendorName.isNotEmpty)
  354. Text('${l10n.get('customerVendor')}: ${d.customerVendorId}/${d.customerVendorName}',
  355. maxLines: 1, overflow: TextOverflow.ellipsis,
  356. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  357. if (d.sqManName.isNotEmpty)
  358. Text('${l10n.get('applicant')}: ${d.sqMan}/${d.sqManName}',
  359. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  360. if (d.bankAccountName.isNotEmpty)
  361. Text('${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  362. maxLines: 1, overflow: TextOverflow.ellipsis,
  363. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  364. if (d.bankName.isNotEmpty)
  365. Text('${l10n.get('bankName')}: ${d.bankName}',
  366. maxLines: 1, overflow: TextOverflow.ellipsis,
  367. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  368. if (d.bankAccount.isNotEmpty)
  369. Text('${l10n.get('bankAccount')}: ${d.bankAccount}',
  370. maxLines: 1, overflow: TextOverflow.ellipsis,
  371. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  372. if (d.remark.isNotEmpty)
  373. Text('${l10n.get('remark')}: ${d.remark}',
  374. maxLines: 2, overflow: TextOverflow.ellipsis,
  375. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary)),
  376. ],
  377. ),
  378. ),
  379. ],
  380. ),
  381. ),
  382. );
  383. }),
  384. if (expense.details.isNotEmpty) ...[
  385. const SizedBox(height: 8),
  386. Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
  387. Text(l10n.get('total'),
  388. style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w600, color: colors.textPrimary)),
  389. Column(
  390. crossAxisAlignment: CrossAxisAlignment.end,
  391. children: [
  392. Text('¥${totalAmount.toStringAsFixed(2)}',
  393. style: TextStyle(fontSize: AppFontSizes.subtitle, fontWeight: FontWeight.w700, color: colors.amountPrimary)),
  394. if (totalApproved > 0)
  395. Text('${l10n.get('approvedAmount')} ¥${totalApproved.toStringAsFixed(2)}',
  396. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w600, color: colors.success)),
  397. ],
  398. ),
  399. ]),
  400. ],
  401. ],
  402. );
  403. }
  404. void _showExpenseDetailDialog(BuildContext context, ExpenseDetailModel d) {
  405. ExpenseDetailViewDialog.show(context, d);
  406. }
  407. // ═══ 附件 ═══
  408. Widget _buildAttachmentSection(AppLocalizations l10n, AppColorsExtension colors) {
  409. if (!_attachAvailable) {
  410. return FormSection(
  411. title: l10n.get('attachments'),
  412. leadingIcon: Icons.attach_file_outlined,
  413. children: [Text(l10n.get('attachServiceUnavailable'),
  414. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder))],
  415. );
  416. }
  417. final headerAtts = _attachments.where((a) => a.isHeader).toList();
  418. final bodyGroups = <int, List<BillAttachment>>{};
  419. for (final a in _attachments.where((a) => a.isBody)) {
  420. bodyGroups.putIfAbsent(a.srcItm, () => []).add(a);
  421. }
  422. final children = <Widget>[];
  423. if (_attachments.isEmpty) {
  424. children.add(Text(l10n.get('noAttachment'),
  425. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder)));
  426. } else {
  427. // 表头附件
  428. if (headerAtts.isNotEmpty) {
  429. children.add(Padding(
  430. padding: const EdgeInsets.only(bottom: 8),
  431. child: Text(l10n.get('headerAttachments'),
  432. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w600, color: colors.textSecondary)),
  433. ));
  434. for (final a in headerAtts) {
  435. children.add(_buildAttachmentRow(a, colors));
  436. }
  437. }
  438. // 表身附件(按明细行分组)
  439. for (final entry in bodyGroups.entries) {
  440. children.add(const SizedBox(height: 8));
  441. children.add(Padding(
  442. padding: const EdgeInsets.only(bottom: 8),
  443. child: Text('${l10n.get('detailLine')} ${entry.key}',
  444. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w600, color: colors.textSecondary)),
  445. ));
  446. for (final a in entry.value) {
  447. children.add(_buildAttachmentRow(a, colors));
  448. }
  449. }
  450. }
  451. return FormSection(
  452. title: l10n.get('attachments'),
  453. leadingIcon: Icons.attach_file_outlined,
  454. children: children,
  455. );
  456. }
  457. Widget _buildAttachmentRow(BillAttachment a, AppColorsExtension colors) {
  458. final isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].contains(a.ext.toLowerCase());
  459. return GestureDetector(
  460. onTap: () => _openAttachment(a),
  461. child: Container(
  462. margin: const EdgeInsets.symmetric(vertical: 4),
  463. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  464. decoration: BoxDecoration(
  465. color: colors.bgPage,
  466. borderRadius: BorderRadius.circular(8),
  467. ),
  468. child: Row(children: [
  469. if (isImage)
  470. _ExpAttachmentThumbnail(api: ref.read(expenseApiProvider), attachment: a, size: 40)
  471. else
  472. Icon(_fileTypeIcon(a.ext), size: 40, color: colors.primary),
  473. const SizedBox(width: 10),
  474. Expanded(
  475. child: Text(a.fileName,
  476. maxLines: 1, overflow: TextOverflow.ellipsis,
  477. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPrimary)),
  478. ),
  479. ]),
  480. ),
  481. );
  482. }
  483. Future<void> _openAttachment(BillAttachment a) async {
  484. final l10n = AppLocalizations.of(context);
  485. final ext = a.ext.toLowerCase();
  486. final isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].contains(ext);
  487. if (isImage) {
  488. // 图片 → 弹窗预览,内部自动下载并显示 loading
  489. final api = ref.read(expenseApiProvider);
  490. AttachmentPreview.show(context,
  491. loader: api.downloadAttachment(a.id),
  492. fileName: a.fileName,
  493. loadingText: l10n.get('loading'),
  494. );
  495. return;
  496. }
  497. // 非图片 → 下载后调用系统工具打开
  498. try {
  499. LoadingDialog.show(context, text: l10n.get('downloading'));
  500. final api = ref.read(expenseApiProvider);
  501. final bytes = await api.downloadAttachment(a.id);
  502. if (!mounted) return;
  503. LoadingDialog.hide(context);
  504. if (bytes == null) {
  505. TDToast.showText(l10n.get('downloadFailed'), context: context);
  506. return;
  507. }
  508. final dir = await getTemporaryDirectory();
  509. final file = File('${dir.path}/${a.fileName}');
  510. await file.writeAsBytes(bytes);
  511. await OpenFilex.open(file.path);
  512. } catch (_) {
  513. if (mounted) LoadingDialog.hide(context);
  514. if (mounted) TDToast.showText(l10n.get('openFailed'), context: context);
  515. }
  516. }
  517. IconData _fileTypeIcon(String ext) {
  518. switch (ext.toLowerCase()) {
  519. case 'pdf': return Icons.picture_as_pdf;
  520. case 'doc': case 'docx': return Icons.description;
  521. case 'xls': case 'xlsx': return Icons.table_chart;
  522. case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp': return Icons.image_outlined;
  523. default: return Icons.insert_drive_file;
  524. }
  525. }
  526. Widget _buildPageFooter(AppColorsExtension colors) {
  527. final l10n = AppLocalizations.of(context);
  528. return Center(
  529. child: Padding(
  530. padding: const EdgeInsets.only(bottom: 16),
  531. child: Row(
  532. mainAxisSize: MainAxisSize.min,
  533. children: [
  534. Icon(Icons.rocket_launch_outlined, size: 16, color: colors.textPlaceholder),
  535. const SizedBox(width: 6),
  536. Text(l10n.get('pageFooter'),
  537. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textPlaceholder)),
  538. ],
  539. ),
  540. ),
  541. );
  542. }
  543. }
  544. /// 附件缩略图 — 自动调用 DownloadAttachment 加载图片
  545. class _ExpAttachmentThumbnail extends StatefulWidget {
  546. final ExpenseApi api;
  547. final BillAttachment attachment;
  548. final double size;
  549. const _ExpAttachmentThumbnail({required this.api, required this.attachment, required this.size});
  550. @override
  551. State<_ExpAttachmentThumbnail> createState() => _ExpAttachmentThumbnailState();
  552. }
  553. class _ExpAttachmentThumbnailState extends State<_ExpAttachmentThumbnail> {
  554. Uint8List? _bytes;
  555. bool _loading = true;
  556. @override
  557. void initState() {
  558. super.initState();
  559. _load();
  560. }
  561. Future<void> _load() async {
  562. try {
  563. final bytes = await widget.api.downloadAttachment(widget.attachment.id);
  564. if (mounted) setState(() { _bytes = bytes; _loading = false; });
  565. } catch (_) {
  566. if (mounted) setState(() => _loading = false);
  567. }
  568. }
  569. @override
  570. Widget build(BuildContext context) {
  571. if (_loading) {
  572. return SizedBox(width: widget.size, height: widget.size,
  573. child: const Center(child: SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))));
  574. }
  575. if (_bytes != null) {
  576. return ClipRRect(
  577. borderRadius: BorderRadius.circular(4),
  578. child: Image.memory(_bytes!, width: widget.size, height: widget.size, fit: BoxFit.cover),
  579. );
  580. }
  581. return Icon(Icons.broken_image, size: widget.size * 0.6, color: Colors.grey);
  582. }
  583. }