expense_detail_page.dart 20 KB

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