expense_apply_detail_page.dart 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. import 'dart:typed_data';
  2. import 'dart:io';
  3. import 'package:flutter/material.dart';
  4. import 'package:path_provider/path_provider.dart';
  5. import 'package:open_filex/open_filex.dart';
  6. import 'package:go_router/go_router.dart';
  7. import '../../shared/widgets/attachment_preview_page.dart';
  8. import 'package:tdesign_flutter/tdesign_flutter.dart';
  9. import 'package:flutter_riverpod/flutter_riverpod.dart';
  10. import '../../shared/widgets/loading_dialog.dart';
  11. import '../../core/utils/date_utils.dart' as du;
  12. import '../../shared/widgets/form_section.dart';
  13. import '../../shared/widgets/form_field_row.dart';
  14. import '../../shared/widgets/app_skeletons.dart';
  15. import '../../shared/models/bill_file_rights.dart';
  16. import '../../shared/widgets/attachment_download_helper.dart';
  17. import '../../shared/widgets/action_bar.dart';
  18. import '../../shared/widgets/audit_trail_dialog.dart';
  19. import 'expense_apply_model.dart';
  20. import 'widgets/expense_apply_detail_view_dialog.dart';
  21. import '../../core/i18n/app_localizations.dart';
  22. import '../../shared/models/bill_attachment.dart';
  23. import 'expense_apply_api.dart';
  24. import '../../core/theme/app_colors.dart';
  25. import '../../core/theme/app_colors_extension.dart';
  26. import '../../core/utils/amount_utils.dart';
  27. class ExpenseApplyDetailPage extends ConsumerStatefulWidget {
  28. final String billNo;
  29. final int queryId;
  30. const ExpenseApplyDetailPage({
  31. super.key,
  32. required this.billNo,
  33. this.queryId = 0,
  34. });
  35. @override
  36. ConsumerState<ExpenseApplyDetailPage> createState() =>
  37. _ExpenseApplyDetailPageState();
  38. }
  39. class _ExpenseApplyDetailPageState
  40. extends ConsumerState<ExpenseApplyDetailPage> {
  41. bool _loading = true;
  42. String? _error;
  43. ExpenseApplyModel? _data;
  44. List<BillAttachment> _attachments = [];
  45. bool _attachAvailable = false;
  46. BillFileRights _billFileRights = BillFileRights.none;
  47. Map<String, dynamic>? _billStatus;
  48. bool _statusLoading = false;
  49. bool _canEdit = false;
  50. @override
  51. void initState() {
  52. super.initState();
  53. _loadData();
  54. }
  55. @override
  56. void dispose() {
  57. super.dispose();
  58. }
  59. Future<void> _loadData() async {
  60. setState(() {
  61. _loading = true;
  62. _error = null;
  63. });
  64. try {
  65. final api = ref.read(expenseApplyApiProvider);
  66. final detail = await api.fetchDetail(widget.billNo);
  67. // Load attachments (non-critical, best-effort)
  68. bool attachAvailable = false;
  69. try {
  70. attachAvailable = await api.checkAttachHealth();
  71. debugPrint('[Attach] checkAttachHealth result: $attachAvailable');
  72. } catch (e) {
  73. debugPrint('[Attach] checkAttachHealth error: $e');
  74. attachAvailable = false;
  75. }
  76. // 加载附件权限
  77. BillFileRights billFileRights = BillFileRights.none;
  78. try {
  79. billFileRights = await api.getBillFileRights('AE');
  80. } catch (_) {}
  81. List<BillAttachment> attachments = [];
  82. if (attachAvailable && billFileRights.canBrowseAttachments) {
  83. try {
  84. attachments = await api.getAttachments('AE', widget.billNo);
  85. debugPrint('[Attach] getAttachments count: ${attachments.length}');
  86. } catch (e) {
  87. debugPrint('[Attach] getAttachments error: $e');
  88. }
  89. }
  90. debugPrint(
  91. '[Attach] final state: attachAvailable=$attachAvailable, count=${attachments.length}',
  92. );
  93. if (mounted) {
  94. setState(() {
  95. _data = detail;
  96. _attachments = attachments;
  97. _attachAvailable = attachAvailable;
  98. _billFileRights = billFileRights;
  99. _loading = false;
  100. });
  101. }
  102. // 单据状态(非关键,尽力加载)
  103. setState(() => _statusLoading = true);
  104. try {
  105. final status = await api.getBillStatus(widget.billNo);
  106. if (mounted) {
  107. setState(() {
  108. _billStatus = status;
  109. _canEdit = status['canEdit'] == true;
  110. _statusLoading = false;
  111. });
  112. }
  113. } catch (_) {
  114. if (mounted) setState(() => _statusLoading = false);
  115. }
  116. } catch (e) {
  117. if (mounted) {
  118. setState(() {
  119. _error = e.toString();
  120. _loading = false;
  121. });
  122. }
  123. }
  124. }
  125. @override
  126. Widget build(BuildContext context) {
  127. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  128. final l10n = AppLocalizations.of(context);
  129. if (_loading) {
  130. return const SkeletonDetailPage();
  131. }
  132. if (_error != null) {
  133. return Center(
  134. child: Column(
  135. mainAxisSize: MainAxisSize.min,
  136. children: [
  137. Icon(Icons.error_outline, size: 48, color: colors.danger),
  138. const SizedBox(height: 16),
  139. Padding(
  140. padding: const EdgeInsets.symmetric(horizontal: 32),
  141. child: Text(
  142. _error!,
  143. textAlign: TextAlign.center,
  144. style: TextStyle(
  145. fontSize: AppFontSizes.body,
  146. color: colors.textSecondary,
  147. ),
  148. ),
  149. ),
  150. const SizedBox(height: 16),
  151. TDButton(
  152. text: l10n.get('retry'),
  153. size: TDButtonSize.medium,
  154. onTap: _loadData,
  155. ),
  156. ],
  157. ),
  158. );
  159. }
  160. final app = _data!;
  161. return Column(
  162. children: [
  163. Expanded(
  164. child: SingleChildScrollView(
  165. physics: const AlwaysScrollableScrollPhysics(),
  166. padding: const EdgeInsets.all(16),
  167. child: Column(
  168. children: [
  169. _buildBasicInfoSection(app, l10n, colors),
  170. const SizedBox(height: 16),
  171. _buildExpenseDetailSection(app, l10n, colors),
  172. const SizedBox(height: 16),
  173. _buildAttachmentSection(l10n, colors),
  174. const SizedBox(height: 24),
  175. _buildPageFooter(colors),
  176. ],
  177. ),
  178. ),
  179. ),
  180. // TODO: 等 ERP 提供"能否修改单据"接口后,恢复为 if (_canEdit)
  181. if (false)
  182. ActionBar(
  183. showLeft: false,
  184. showCenter: false,
  185. rightLabel: l10n.get('editApply'),
  186. onRightTap: () async {
  187. final result = await GoRouter.of(
  188. context,
  189. ).push('/expense-apply/edit/${widget.billNo}');
  190. if (result == true && mounted) _loadData();
  191. },
  192. ),
  193. ],
  194. );
  195. }
  196. // ═══ 状态 tag(标题行右侧) ═══
  197. Widget? _buildStatusTag(AppLocalizations l10n) {
  198. final isTransferred = _billStatus?['isTransferred'] == true;
  199. final approvalStatus = _billStatus?['approvalStatus'] as String?;
  200. final approvalText = _billStatus?['approvalText'] as String? ?? '';
  201. IconData icon;
  202. String text;
  203. Color color;
  204. if (isTransferred) {
  205. icon = Icons.swap_horiz;
  206. text = l10n.get('statusConvertedToExpense');
  207. color = Colors.blue;
  208. } else if (approvalStatus == null || approvalStatus.isEmpty) {
  209. return null;
  210. } else {
  211. switch (approvalStatus) {
  212. case 'SHCOUNT0':
  213. icon = Icons.edit_note;
  214. color = Colors.teal;
  215. break;
  216. case 'SHCOUNT1':
  217. icon = Icons.hourglass_empty;
  218. color = Colors.blueGrey;
  219. break;
  220. case 'SHCOUNT2':
  221. icon = Icons.cancel_outlined;
  222. color = Colors.red;
  223. break;
  224. case 'SHCOUNT3':
  225. icon = Icons.undo;
  226. color = Colors.deepOrange;
  227. break;
  228. case 'SHCOUNT4':
  229. icon = Icons.check_circle_outline;
  230. color = Colors.green;
  231. break;
  232. default:
  233. return null;
  234. }
  235. text = approvalText;
  236. }
  237. final tag = Container(
  238. padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
  239. decoration: BoxDecoration(
  240. color: color.withValues(alpha: 0.1),
  241. borderRadius: BorderRadius.circular(6),
  242. border: Border.all(color: color.withValues(alpha: 0.3), width: 0.5),
  243. ),
  244. child: Row(
  245. mainAxisSize: MainAxisSize.min,
  246. children: [
  247. Icon(icon, size: 18, color: color),
  248. const SizedBox(width: 4),
  249. Text(text, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: color)),
  250. ],
  251. ),
  252. );
  253. final canTap = approvalStatus != null && approvalStatus.isNotEmpty && approvalText.isNotEmpty;
  254. if (canTap) {
  255. return GestureDetector(
  256. onTap: () => _showAuditTrail('AE'),
  257. child: tag,
  258. );
  259. }
  260. return tag;
  261. }
  262. Future<void> _showAuditTrail(String billId) async {
  263. final api = ref.read(expenseApplyApiProvider);
  264. final billNo = widget.billNo;
  265. await AuditTrailDialog.show(context, fetcher: () => api.getAuditTrail(billId, billNo));
  266. }
  267. // ═══ 基本信息 ═══
  268. Widget _buildBasicInfoSection(
  269. ExpenseApplyModel app,
  270. AppLocalizations l10n,
  271. AppColorsExtension colors,
  272. ) {
  273. return FormSection(
  274. title: l10n.get('basicInfo'),
  275. leadingIcon: Icons.info_outline,
  276. trailing: _buildStatusTag(l10n),
  277. children: [
  278. FormFieldRow(
  279. label: l10n.get('expenseApplyNo'),
  280. value: app.expenseApplyNo,
  281. readOnly: true,
  282. showArrow: false,
  283. ),
  284. const SizedBox(height: 16),
  285. FormFieldRow(
  286. label: l10n.get('date'),
  287. value: du.DateUtils.formatDate(app.createTime),
  288. readOnly: true,
  289. showArrow: false,
  290. ),
  291. const SizedBox(height: 16),
  292. FormFieldRow(
  293. label: l10n.get('applyDept'),
  294. value: app.deptId.isNotEmpty
  295. ? '${app.deptId}${app.deptName.isNotEmpty ? '/${app.deptName}' : ''}'
  296. : '-',
  297. readOnly: true,
  298. showArrow: false,
  299. ),
  300. const SizedBox(height: 16),
  301. SizedBox(
  302. height: 24,
  303. child: Row(
  304. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  305. children: [
  306. Text(
  307. l10n.get('emergencyLevel'),
  308. style: TextStyle(
  309. fontSize: AppFontSizes.subtitle,
  310. color: colors.textSecondary,
  311. ),
  312. ),
  313. _buildUrgencyChip(app.urgency, l10n, colors),
  314. ],
  315. ),
  316. ),
  317. const SizedBox(height: 16),
  318. FormFieldRow(
  319. label: l10n.get('applyReason'),
  320. value: app.purpose.isNotEmpty ? app.purpose : '-',
  321. readOnly: true,
  322. showArrow: false,
  323. bold: true,
  324. ),
  325. const SizedBox(height: 16),
  326. FormFieldRow(
  327. label: l10n.get('remark'),
  328. value: app.remark.isNotEmpty ? app.remark : '-',
  329. readOnly: true,
  330. showArrow: false,
  331. bold: false,
  332. ),
  333. ],
  334. );
  335. }
  336. // ═══ 费用明细 ═══
  337. Widget _buildExpenseDetailSection(
  338. ExpenseApplyModel app,
  339. AppLocalizations l10n,
  340. AppColorsExtension colors,
  341. ) {
  342. return FormSection(
  343. title: l10n.get('expenseDetails'),
  344. leadingIcon: Icons.receipt_long_outlined,
  345. children: [
  346. if (app.details.isEmpty)
  347. Padding(
  348. padding: const EdgeInsets.symmetric(vertical: 8),
  349. child: Text(
  350. l10n.get('noDetailData'),
  351. style: TextStyle(
  352. fontSize: AppFontSizes.body,
  353. color: colors.textPlaceholder,
  354. ),
  355. ),
  356. )
  357. else
  358. ...app.details.asMap().entries.map((e) {
  359. final d = e.value;
  360. final catLabel = d.categoryName.isNotEmpty
  361. ? '${d.expenseCategory}/${d.categoryName}'
  362. : d.expenseCategory;
  363. return GestureDetector(
  364. onTap: () => _showExpenseDetailDialog(context, d),
  365. child: Container(
  366. margin: const EdgeInsets.symmetric(vertical: 8),
  367. padding: const EdgeInsets.all(12),
  368. decoration: BoxDecoration(
  369. color: colors.bgPage,
  370. borderRadius: BorderRadius.circular(8),
  371. ),
  372. child: Row(
  373. crossAxisAlignment: CrossAxisAlignment.center,
  374. children: [
  375. Expanded(
  376. child: Column(
  377. crossAxisAlignment: CrossAxisAlignment.start,
  378. children: [
  379. Row(
  380. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  381. children: [
  382. Expanded(
  383. child: Text(
  384. catLabel,
  385. maxLines: 1,
  386. overflow: TextOverflow.ellipsis,
  387. style: TextStyle(
  388. fontSize: AppFontSizes.subtitle,
  389. color: colors.textPrimary,
  390. ),
  391. ),
  392. ),
  393. const SizedBox(width: 12),
  394. Text(
  395. formatAmount(d.estimatedAmount),
  396. style: TextStyle(
  397. fontSize: AppFontSizes.caption,
  398. fontWeight: FontWeight.w600,
  399. color: colors.amountPrimary,
  400. ),
  401. ),
  402. ],
  403. ),
  404. if (d.acctSubjectId.isNotEmpty) ...[
  405. const SizedBox(height: 4),
  406. Text(
  407. '${l10n.get('acctSubject')}: ${d.acctSubjectId}${d.acctSubjectName.isNotEmpty ? '/${d.acctSubjectName}' : ''}',
  408. maxLines: 1,
  409. overflow: TextOverflow.ellipsis,
  410. style: TextStyle(
  411. fontSize: AppFontSizes.caption,
  412. color: colors.textSecondary,
  413. ),
  414. ),
  415. ],
  416. if (d.sqMan.isNotEmpty) ...[
  417. const SizedBox(height: 4),
  418. Text(
  419. '${l10n.get('applicant')}: ${d.sqMan}${d.sqName.isNotEmpty ? '/${d.sqName}' : ''}',
  420. maxLines: 1,
  421. overflow: TextOverflow.ellipsis,
  422. style: TextStyle(
  423. fontSize: AppFontSizes.caption,
  424. color: colors.textSecondary,
  425. ),
  426. ),
  427. ],
  428. if (d.projectId.isNotEmpty) ...[
  429. const SizedBox(height: 4),
  430. Text(
  431. '${l10n.get('project')}: ${d.projectId}${d.projectName.isNotEmpty ? '/${d.projectName}' : ''}',
  432. maxLines: 1,
  433. overflow: TextOverflow.ellipsis,
  434. style: TextStyle(
  435. fontSize: AppFontSizes.caption,
  436. color: colors.textSecondary,
  437. ),
  438. ),
  439. ],
  440. if (d.costDeptId.isNotEmpty) ...[
  441. const SizedBox(height: 4),
  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. ],
  452. if (d.estimatedStartDate != null) ...[
  453. const SizedBox(height: 4),
  454. Text(
  455. '${l10n.get('estimatedDate')}: ${du.DateUtils.formatDate(d.estimatedStartDate!)}${d.estimatedEndDate != null ? ' ~ ${du.DateUtils.formatDate(d.estimatedEndDate!)}' : ''}',
  456. maxLines: 1,
  457. overflow: TextOverflow.ellipsis,
  458. style: TextStyle(
  459. fontSize: AppFontSizes.caption,
  460. color: colors.textSecondary,
  461. ),
  462. ),
  463. ],
  464. if (d.bxNo.isNotEmpty) ...[
  465. const SizedBox(height: 4),
  466. Text(
  467. '${l10n.get('expenseNo')}: ${d.bxNo}',
  468. maxLines: 1,
  469. overflow: TextOverflow.ellipsis,
  470. style: TextStyle(
  471. fontSize: AppFontSizes.caption,
  472. color: colors.textSecondary,
  473. ),
  474. ),
  475. ],
  476. if (d.remark.isNotEmpty) ...[
  477. const SizedBox(height: 4),
  478. Text(
  479. d.remark,
  480. maxLines: 2,
  481. overflow: TextOverflow.ellipsis,
  482. style: TextStyle(
  483. fontSize: AppFontSizes.caption,
  484. color: colors.textSecondary,
  485. ),
  486. ),
  487. ],
  488. ],
  489. ),
  490. ),
  491. ],
  492. ),
  493. ),
  494. );
  495. }),
  496. if (app.details.isNotEmpty) ...[
  497. const SizedBox(height: 8),
  498. Row(
  499. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  500. children: [
  501. Text(
  502. l10n.get('total'),
  503. style: TextStyle(
  504. fontSize: AppFontSizes.body,
  505. fontWeight: FontWeight.w600,
  506. color: colors.textPrimary,
  507. ),
  508. ),
  509. Text(
  510. formatAmount(app.details.fold<double>(0, (sum, d) => sum + d.estimatedAmount)),
  511. style: TextStyle(
  512. fontSize: AppFontSizes.subtitle,
  513. fontWeight: FontWeight.w700,
  514. color: colors.amountPrimary,
  515. ),
  516. ),
  517. ],
  518. ),
  519. ],
  520. ],
  521. );
  522. }
  523. // ═══ 附件 ═══
  524. Widget _buildAttachmentSection(
  525. AppLocalizations l10n,
  526. AppColorsExtension colors,
  527. ) {
  528. final children = <Widget>[];
  529. if (!_attachAvailable) {
  530. children.add(
  531. Text(
  532. l10n.get('attachServiceUnavailable'),
  533. style: TextStyle(
  534. fontSize: AppFontSizes.body,
  535. color: colors.textPlaceholder,
  536. ),
  537. ),
  538. );
  539. } else if (!_billFileRights.canBrowseAttachments) {
  540. children.add(
  541. Text(
  542. l10n.get('noAttachmentPermission'),
  543. style: TextStyle(
  544. fontSize: AppFontSizes.body,
  545. color: colors.textPlaceholder,
  546. ),
  547. ),
  548. );
  549. } else if (_attachments.isEmpty) {
  550. children.add(
  551. Text(
  552. l10n.get('noAttachment'),
  553. style: TextStyle(
  554. fontSize: AppFontSizes.body,
  555. color: colors.textPlaceholder,
  556. ),
  557. ),
  558. );
  559. } else {
  560. children.addAll(_attachments.map((a) => _buildAttachmentRow(a, colors)));
  561. }
  562. return FormSection(
  563. title: l10n.get('attachments'),
  564. leadingIcon: Icons.attach_file_outlined,
  565. children: children,
  566. );
  567. }
  568. Widget _buildAttachmentRow(BillAttachment a, AppColorsExtension colors) {
  569. final isImage = [
  570. 'jpg',
  571. 'jpeg',
  572. 'png',
  573. 'gif',
  574. 'bmp',
  575. 'webp',
  576. ].contains(a.ext.toLowerCase());
  577. return GestureDetector(
  578. onTap: () => _openAttachment(a),
  579. child: Container(
  580. margin: const EdgeInsets.symmetric(vertical: 4),
  581. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  582. decoration: BoxDecoration(
  583. color: colors.bgPage,
  584. borderRadius: BorderRadius.circular(8),
  585. ),
  586. child: Row(
  587. children: [
  588. if (isImage)
  589. _AttachmentThumbnail(
  590. api: ref.read(expenseApplyApiProvider),
  591. attachment: a,
  592. size: 40,
  593. )
  594. else
  595. Icon(_fileTypeIcon(a.ext), size: 40, color: colors.primary),
  596. const SizedBox(width: 10),
  597. Expanded(
  598. child: Text(
  599. a.fileName,
  600. maxLines: 1,
  601. overflow: TextOverflow.ellipsis,
  602. style: TextStyle(
  603. fontSize: AppFontSizes.body,
  604. color: colors.textPrimary,
  605. ),
  606. ),
  607. ),
  608. const SizedBox(width: 8),
  609. GestureDetector(
  610. onTap: () => AttachmentDownloadHelper.downloadAndSave(
  611. context,
  612. a,
  613. ref.read(expenseApplyApiProvider).downloadAttachment,
  614. ),
  615. child: Icon(
  616. Icons.download_outlined,
  617. size: 22,
  618. color: colors.primary,
  619. ),
  620. ),
  621. ],
  622. ),
  623. ),
  624. );
  625. }
  626. Future<void> _openAttachment(BillAttachment a) async {
  627. final l10n = AppLocalizations.of(context);
  628. final ext = a.ext.toLowerCase();
  629. final isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].contains(ext);
  630. if (isImage) {
  631. // 图片 → 弹窗预览,内部自动下载并显示 loading
  632. final api = ref.read(expenseApplyApiProvider);
  633. AttachmentPreview.show(
  634. context,
  635. loader: api.downloadAttachment(a.id),
  636. fileName: a.fileName,
  637. loadingText: l10n.get('loading'),
  638. );
  639. return;
  640. }
  641. // 非图片 → 下载后调用系统工具打开
  642. try {
  643. LoadingDialog.show(context, text: l10n.get('downloading'));
  644. final api = ref.read(expenseApplyApiProvider);
  645. final bytes = await api.downloadAttachment(a.id);
  646. if (!mounted) return;
  647. LoadingDialog.hide(context);
  648. if (bytes == null) {
  649. TDToast.showText(l10n.get('downloadFailed'), context: context);
  650. return;
  651. }
  652. final dir = await getTemporaryDirectory();
  653. final file = File('${dir.path}/${a.fileName}');
  654. await file.writeAsBytes(bytes);
  655. await OpenFilex.open(file.path);
  656. } catch (_) {
  657. if (mounted) LoadingDialog.hide(context);
  658. if (mounted) TDToast.showText(l10n.get('openFailed'), context: context);
  659. }
  660. }
  661. IconData _fileTypeIcon(String ext) {
  662. switch (ext.toLowerCase()) {
  663. case 'pdf':
  664. return Icons.picture_as_pdf;
  665. case 'doc':
  666. case 'docx':
  667. return Icons.description;
  668. case 'xls':
  669. case 'xlsx':
  670. return Icons.table_chart;
  671. case 'jpg':
  672. case 'jpeg':
  673. case 'png':
  674. case 'gif':
  675. case 'bmp':
  676. return Icons.image_outlined;
  677. default:
  678. return Icons.insert_drive_file;
  679. }
  680. }
  681. Widget _buildPageFooter(AppColorsExtension colors) {
  682. final l10n = AppLocalizations.of(context);
  683. return Center(
  684. child: Padding(
  685. padding: const EdgeInsets.only(bottom: 16),
  686. child: Row(
  687. mainAxisSize: MainAxisSize.min,
  688. children: [
  689. Icon(
  690. Icons.rocket_launch_outlined,
  691. size: 16,
  692. color: colors.textPlaceholder,
  693. ),
  694. const SizedBox(width: 6),
  695. Text(
  696. l10n.get('pageFooter'),
  697. style: TextStyle(
  698. fontSize: AppFontSizes.caption,
  699. color: colors.textPlaceholder,
  700. ),
  701. ),
  702. ],
  703. ),
  704. ),
  705. );
  706. }
  707. Widget _buildUrgencyChip(
  708. String urgency,
  709. AppLocalizations l10n,
  710. AppColorsExtension colors,
  711. ) {
  712. final (label, color) = switch (urgency) {
  713. '3' || 'critical' => (l10n.get('critical'), colors.danger),
  714. '2' || 'urgent' => (l10n.get('urgent'), colors.warning),
  715. '1' || 'normal' => (l10n.get('normal'), colors.primary),
  716. _ => (l10n.get('normal'), colors.primary),
  717. };
  718. return Container(
  719. padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
  720. decoration: BoxDecoration(
  721. color: color.withValues(alpha: 0.1),
  722. borderRadius: BorderRadius.circular(4),
  723. border: Border.all(color: color, width: 0.5),
  724. ),
  725. child: Text(
  726. label,
  727. style: TextStyle(
  728. fontSize: 11,
  729. fontWeight: FontWeight.w500,
  730. color: color,
  731. ),
  732. ),
  733. );
  734. }
  735. void _showExpenseDetailDialog(
  736. BuildContext context,
  737. ExpenseApplyDetailModel d,
  738. ) {
  739. ExpenseApplyDetailViewDialog.show(context, d);
  740. }
  741. }
  742. /// 附件缩略图 — 自动调用 DownloadAttachment 加载图片
  743. class _AttachmentThumbnail extends StatefulWidget {
  744. final ExpenseApplyApi api;
  745. final BillAttachment attachment;
  746. final double size;
  747. const _AttachmentThumbnail({
  748. required this.api,
  749. required this.attachment,
  750. required this.size,
  751. });
  752. @override
  753. State<_AttachmentThumbnail> createState() => _AttachmentThumbnailState();
  754. }
  755. class _AttachmentThumbnailState extends State<_AttachmentThumbnail> {
  756. Uint8List? _bytes;
  757. bool _loading = true;
  758. @override
  759. void initState() {
  760. super.initState();
  761. _load();
  762. }
  763. Future<void> _load() async {
  764. try {
  765. final bytes = await widget.api.downloadAttachment(widget.attachment.id);
  766. if (mounted) {
  767. setState(() {
  768. _bytes = bytes;
  769. _loading = false;
  770. });
  771. }
  772. } catch (_) {
  773. if (mounted) setState(() => _loading = false);
  774. }
  775. }
  776. @override
  777. Widget build(BuildContext context) {
  778. if (_loading) {
  779. return SizedBox(
  780. width: widget.size,
  781. height: widget.size,
  782. child: const Center(
  783. child: SizedBox(
  784. width: 16,
  785. height: 16,
  786. child: CircularProgressIndicator(strokeWidth: 2),
  787. ),
  788. ),
  789. );
  790. }
  791. if (_bytes != null) {
  792. return ClipRRect(
  793. borderRadius: BorderRadius.circular(4),
  794. child: Image.memory(
  795. _bytes!,
  796. width: widget.size,
  797. height: widget.size,
  798. fit: BoxFit.cover,
  799. ),
  800. );
  801. }
  802. return Icon(
  803. Icons.broken_image,
  804. size: widget.size * 0.6,
  805. color: Colors.grey,
  806. );
  807. }
  808. }