expense_apply_detail_page.dart 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 '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/widgets/action_bar.dart';
  16. import '../../shared/widgets/status_banner.dart';
  17. import 'expense_apply_model.dart';
  18. import 'widgets/expense_apply_detail_view_dialog.dart';
  19. import '../../core/i18n/app_localizations.dart';
  20. import '../../shared/models/bill_attachment.dart';
  21. import 'expense_apply_api.dart';
  22. import '../../core/theme/app_colors.dart';
  23. import '../../core/theme/app_colors_extension.dart';
  24. class ExpenseApplyDetailPage extends ConsumerStatefulWidget {
  25. final String billNo;
  26. final int queryId;
  27. const ExpenseApplyDetailPage({super.key, required this.billNo, this.queryId = 0});
  28. @override
  29. ConsumerState<ExpenseApplyDetailPage> createState() => _ExpenseApplyDetailPageState();
  30. }
  31. class _ExpenseApplyDetailPageState extends ConsumerState<ExpenseApplyDetailPage>
  32. {
  33. bool _loading = true;
  34. String? _error;
  35. ExpenseApplyModel? _data;
  36. List<BillAttachment> _attachments = [];
  37. bool _attachAvailable = false;
  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(() { _loading = true; _error = null; });
  52. try {
  53. final api = ref.read(expenseApplyApiProvider);
  54. final detail = await api.fetchDetail(widget.billNo);
  55. // Load attachments (non-critical, best-effort)
  56. bool attachAvailable = false;
  57. try {
  58. attachAvailable = await api.checkAttachHealth();
  59. debugPrint('[Attach] checkAttachHealth result: $attachAvailable');
  60. } catch (e) {
  61. debugPrint('[Attach] checkAttachHealth error: $e');
  62. attachAvailable = false;
  63. }
  64. List<BillAttachment> attachments = [];
  65. if (attachAvailable) {
  66. try {
  67. attachments = await api.getAttachments('AE', widget.billNo);
  68. debugPrint('[Attach] getAttachments count: ${attachments.length}');
  69. } catch (e) {
  70. debugPrint('[Attach] getAttachments error: $e');
  71. // 附件列表加载失败不影响服务可用状态,保持空列表
  72. }
  73. }
  74. debugPrint('[Attach] final state: attachAvailable=$attachAvailable, count=${attachments.length}');
  75. if (mounted) {
  76. setState(() {
  77. _data = detail;
  78. _attachments = attachments;
  79. _attachAvailable = attachAvailable;
  80. _loading = false;
  81. });
  82. }
  83. // 单据状态(非关键,尽力加载)
  84. setState(() => _statusLoading = true);
  85. try {
  86. final status = await api.getBillStatus(widget.billNo);
  87. if (mounted) {
  88. setState(() {
  89. _billStatus = status;
  90. _canEdit = status['canEdit'] == true;
  91. _statusLoading = false;
  92. });
  93. }
  94. } catch (_) {
  95. if (mounted) setState(() => _statusLoading = false);
  96. }
  97. } catch (e) {
  98. if (mounted) {
  99. setState(() { _error = e.toString(); _loading = false; });
  100. }
  101. }
  102. }
  103. @override
  104. Widget build(BuildContext context) {
  105. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  106. final l10n = AppLocalizations.of(context);
  107. if (_loading) {
  108. return const SkeletonDetailPage();
  109. }
  110. if (_error != null) {
  111. return Center(
  112. child: Column(
  113. mainAxisSize: MainAxisSize.min,
  114. children: [
  115. Icon(Icons.error_outline, size: 48, color: colors.danger),
  116. const SizedBox(height: 16),
  117. Padding(
  118. padding: const EdgeInsets.symmetric(horizontal: 32),
  119. child: Text(
  120. _error!,
  121. textAlign: TextAlign.center,
  122. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textSecondary),
  123. ),
  124. ),
  125. const SizedBox(height: 16),
  126. TDButton(
  127. text: l10n.get('retry'),
  128. size: TDButtonSize.medium,
  129. onTap: _loadData,
  130. ),
  131. ],
  132. ),
  133. );
  134. }
  135. final app = _data!;
  136. return Column(
  137. children: [
  138. Expanded(
  139. child: SingleChildScrollView(
  140. physics: const AlwaysScrollableScrollPhysics(),
  141. padding: const EdgeInsets.all(16),
  142. child: Column(
  143. children: [
  144. if (_statusLoading) ...[
  145. const Padding(
  146. padding: EdgeInsets.symmetric(vertical: 8),
  147. child: Center(child: TDLoading(size: TDLoadingSize.small, icon: TDLoadingIcon.activity)),
  148. ),
  149. ],
  150. Builder(builder: (ctx) {
  151. final badge = _buildStatusBadge(l10n);
  152. if (badge == null) return const SizedBox.shrink();
  153. return Column(children: [badge, const SizedBox(height: 16)]);
  154. }),
  155. _buildBasicInfoSection(app, l10n, colors),
  156. const SizedBox(height: 16),
  157. _buildExpenseDetailSection(app, l10n, colors),
  158. const SizedBox(height: 16),
  159. _buildAttachmentSection(l10n, colors),
  160. const SizedBox(height: 24),
  161. _buildPageFooter(colors),
  162. ],
  163. ),
  164. ),
  165. ),
  166. if (_canEdit)
  167. ActionBar(
  168. showLeft: false,
  169. showCenter: false,
  170. rightLabel: l10n.get('editApply'),
  171. onRightTap: () async {
  172. final result = await GoRouter.of(context).push(
  173. '/expense-apply/edit/${widget.billNo}',
  174. );
  175. if (result == true && mounted) _loadData();
  176. },
  177. ),
  178. ],
  179. );
  180. }
  181. // ═══ 状态徽章 ═══
  182. Widget? _buildStatusBadge(AppLocalizations l10n) {
  183. final isTransferred = _billStatus?['isTransferred'] == true;
  184. final approvalStatus = _billStatus?['approvalStatus'] as String?;
  185. if (isTransferred) {
  186. return StatusBanner(icon: Icons.swap_horiz, statusText: l10n.get('statusTransferred'), subText: '', color: Colors.blueGrey);
  187. }
  188. switch (approvalStatus) {
  189. case 'SHCOUNT4':
  190. return StatusBanner(icon: Icons.check_circle_outline, statusText: l10n.get('statusApproved'), subText: '', color: Colors.green);
  191. case 'SHCOUNT5':
  192. return StatusBanner(icon: Icons.cancel_outlined, statusText: l10n.get('statusFinalRejected'), subText: '', color: Colors.red);
  193. case 'SHCOUNT1':
  194. return StatusBanner(icon: Icons.hourglass_empty, statusText: l10n.get('statusPendingReview'), subText: '', color: Colors.blue);
  195. case 'SHCOUNT2':
  196. return StatusBanner(icon: Icons.block_outlined, statusText: l10n.get('statusReviewRejected'), subText: '', color: Colors.deepOrange);
  197. default:
  198. return null;
  199. }
  200. }
  201. // ═══ 基本信息 ═══
  202. Widget _buildBasicInfoSection(
  203. ExpenseApplyModel app,
  204. AppLocalizations l10n,
  205. AppColorsExtension colors,
  206. ) {
  207. return FormSection(
  208. title: l10n.get('basicInfo'),
  209. leadingIcon: Icons.info_outline,
  210. children: [
  211. FormFieldRow(label: l10n.get('expenseApplyNo'), value: app.expenseApplyNo, readOnly: true, showArrow: false),
  212. const SizedBox(height: 16),
  213. FormFieldRow(label: l10n.get('date'), value: du.DateUtils.formatDate(app.createTime), readOnly: true, showArrow: false),
  214. const SizedBox(height: 16),
  215. FormFieldRow(label: l10n.get('applicant'), value: app.applicantName.isNotEmpty ? '${app.applicantId}/${app.applicantName}' : '-', readOnly: true, showArrow: false),
  216. const SizedBox(height: 16),
  217. FormFieldRow(label: l10n.get('department'), value: app.deptName.isNotEmpty ? '${app.deptId}/${app.deptName}' : '-', readOnly: true, showArrow: false),
  218. const SizedBox(height: 16),
  219. SizedBox(
  220. height: 24,
  221. child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
  222. Text(l10n.get('emergencyLevel'), style: TextStyle(fontSize: AppFontSizes.subtitle, color: colors.textSecondary)),
  223. _buildUrgencyChip(app.urgency, l10n, colors),
  224. ]),
  225. ),
  226. const SizedBox(height: 16),
  227. FormFieldRow(label: l10n.get('applyReason'), value: app.purpose.isNotEmpty ? app.purpose : '-', readOnly: true, showArrow: false, bold: true),
  228. const SizedBox(height: 16),
  229. FormFieldRow(label: l10n.get('remark'), value: app.remark.isNotEmpty ? app.remark : '-', readOnly: true, showArrow: false),
  230. ],
  231. );
  232. }
  233. // ═══ 费用明细 ═══
  234. Widget _buildExpenseDetailSection(
  235. ExpenseApplyModel app,
  236. AppLocalizations l10n,
  237. AppColorsExtension colors,
  238. ) {
  239. return FormSection(
  240. title: l10n.get('expenseDetails'),
  241. leadingIcon: Icons.receipt_long_outlined,
  242. children: [
  243. if (app.details.isEmpty)
  244. Padding(
  245. padding: const EdgeInsets.symmetric(vertical: 8),
  246. child: Text(l10n.get('noDetailData'), style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder)),
  247. )
  248. else
  249. ...app.details.asMap().entries.map((e) {
  250. final d = e.value;
  251. final catLabel = d.categoryName.isNotEmpty
  252. ? '${d.expenseCategory}/${d.categoryName}'
  253. : d.expenseCategory;
  254. return GestureDetector(
  255. onTap: () => _showExpenseDetailDialog(context, d),
  256. child: Container(
  257. margin: const EdgeInsets.symmetric(vertical: 8),
  258. padding: const EdgeInsets.all(12),
  259. decoration: BoxDecoration(color: colors.bgPage, borderRadius: BorderRadius.circular(8)),
  260. child: Row(
  261. crossAxisAlignment: CrossAxisAlignment.center,
  262. children: [
  263. Expanded(
  264. child: Column(
  265. crossAxisAlignment: CrossAxisAlignment.start,
  266. children: [
  267. Row(
  268. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  269. children: [
  270. Expanded(
  271. child: Text(
  272. catLabel,
  273. maxLines: 1,
  274. overflow: TextOverflow.ellipsis,
  275. style: TextStyle(fontSize: AppFontSizes.subtitle, color: colors.textPrimary),
  276. ),
  277. ),
  278. const SizedBox(width: 12),
  279. Text(
  280. '¥${d.estimatedAmount.toStringAsFixed(2)}',
  281. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w600, color: colors.amountPrimary),
  282. ),
  283. ],
  284. ),
  285. if (d.acctSubjectId.isNotEmpty) ...[
  286. const SizedBox(height: 4),
  287. Text(
  288. '${l10n.get('acctSubject')}: ${d.acctSubjectId}${d.acctSubjectName.isNotEmpty ? '/${d.acctSubjectName}' : ''}',
  289. maxLines: 1,
  290. overflow: TextOverflow.ellipsis,
  291. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  292. ),
  293. ],
  294. if (d.projectId.isNotEmpty && d.projectName.isNotEmpty) ...[
  295. const SizedBox(height: 4),
  296. Text(
  297. '${l10n.get('project')}: ${d.projectId}/${d.projectName}',
  298. maxLines: 1,
  299. overflow: TextOverflow.ellipsis,
  300. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  301. ),
  302. ],
  303. if (d.costDeptId.isNotEmpty && d.costDeptName.isNotEmpty) ...[
  304. const SizedBox(height: 4),
  305. Text(
  306. '${l10n.get('costDept')}: ${d.costDeptId}/${d.costDeptName}',
  307. maxLines: 1,
  308. overflow: TextOverflow.ellipsis,
  309. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  310. ),
  311. ],
  312. if (d.estimatedStartDate != null) ...[
  313. const SizedBox(height: 4),
  314. Text(
  315. '${l10n.get('estimatedDate')}: ${du.DateUtils.formatDate(d.estimatedStartDate!)}${d.estimatedEndDate != null ? ' ~ ${du.DateUtils.formatDate(d.estimatedEndDate!)}' : ''}',
  316. maxLines: 1,
  317. overflow: TextOverflow.ellipsis,
  318. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  319. ),
  320. ],
  321. if (d.bxNo.isNotEmpty) ...[
  322. const SizedBox(height: 4),
  323. Text(
  324. '${l10n.get('expenseNo')}: ${d.bxNo}',
  325. maxLines: 1,
  326. overflow: TextOverflow.ellipsis,
  327. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  328. ),
  329. ],
  330. if (d.remark.isNotEmpty) ...[
  331. const SizedBox(height: 4),
  332. Text(
  333. d.remark,
  334. maxLines: 2,
  335. overflow: TextOverflow.ellipsis,
  336. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  337. ),
  338. ],
  339. ],
  340. ),
  341. ),
  342. ],
  343. ),
  344. ),
  345. );
  346. }),
  347. if (app.details.isNotEmpty) ...[
  348. const SizedBox(height: 8),
  349. Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
  350. Text(l10n.get('total'), style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w600, color: colors.textPrimary)),
  351. Text('¥${app.details.fold<double>(0, (sum, d) => sum + d.estimatedAmount).toStringAsFixed(2)}',
  352. style: TextStyle(fontSize: AppFontSizes.subtitle, fontWeight: FontWeight.w700, color: colors.amountPrimary)),
  353. ]),
  354. ],
  355. ],
  356. );
  357. }
  358. // ═══ 附件 ═══
  359. Widget _buildAttachmentSection(AppLocalizations l10n, AppColorsExtension colors) {
  360. final children = <Widget>[];
  361. if (!_attachAvailable) {
  362. children.add(Text(l10n.get('attachServiceUnavailable'),
  363. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder)));
  364. } else if (_attachments.isEmpty) {
  365. children.add(Text(l10n.get('noAttachment'),
  366. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder)));
  367. } else {
  368. children.addAll(_attachments.map((a) => _buildAttachmentRow(a, colors)));
  369. }
  370. return FormSection(
  371. title: l10n.get('attachments'),
  372. leadingIcon: Icons.attach_file_outlined,
  373. children: children,
  374. );
  375. }
  376. Widget _buildAttachmentRow(BillAttachment a, AppColorsExtension colors) {
  377. final isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].contains(a.ext.toLowerCase());
  378. return GestureDetector(
  379. onTap: () => _openAttachment(a),
  380. child: Container(
  381. margin: const EdgeInsets.symmetric(vertical: 4),
  382. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  383. decoration: BoxDecoration(
  384. color: colors.bgPage,
  385. borderRadius: BorderRadius.circular(8),
  386. ),
  387. child: Row(children: [
  388. if (isImage)
  389. _AttachmentThumbnail(api: ref.read(expenseApplyApiProvider), attachment: a, size: 40)
  390. else
  391. Icon(_fileTypeIcon(a.ext), size: 40, color: colors.primary),
  392. const SizedBox(width: 10),
  393. Expanded(
  394. child: Text(a.fileName,
  395. maxLines: 1, overflow: TextOverflow.ellipsis,
  396. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPrimary)),
  397. ),
  398. ]),
  399. ),
  400. );
  401. }
  402. Future<void> _openAttachment(BillAttachment a) async {
  403. final l10n = AppLocalizations.of(context);
  404. final ext = a.ext.toLowerCase();
  405. final isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].contains(ext);
  406. if (isImage) {
  407. // 图片 → 弹窗预览,内部自动下载并显示 loading
  408. final api = ref.read(expenseApplyApiProvider);
  409. AttachmentPreview.show(context,
  410. loader: api.downloadAttachment(a.id),
  411. fileName: a.fileName,
  412. loadingText: l10n.get('loading'),
  413. );
  414. return;
  415. }
  416. // 非图片 → 下载后调用系统工具打开
  417. try {
  418. LoadingDialog.show(context, text: l10n.get('downloading'));
  419. final api = ref.read(expenseApplyApiProvider);
  420. final bytes = await api.downloadAttachment(a.id);
  421. if (!mounted) return;
  422. LoadingDialog.hide(context);
  423. if (bytes == null) {
  424. TDToast.showText(l10n.get('downloadFailed'), context: context);
  425. return;
  426. }
  427. final dir = await getTemporaryDirectory();
  428. final file = File('${dir.path}/${a.fileName}');
  429. await file.writeAsBytes(bytes);
  430. await OpenFilex.open(file.path);
  431. } catch (_) {
  432. if (mounted) LoadingDialog.hide(context);
  433. if (mounted) TDToast.showText(l10n.get('openFailed'), context: context);
  434. }
  435. }
  436. IconData _fileTypeIcon(String ext) {
  437. switch (ext.toLowerCase()) {
  438. case 'pdf': return Icons.picture_as_pdf;
  439. case 'doc': case 'docx': return Icons.description;
  440. case 'xls': case 'xlsx': return Icons.table_chart;
  441. case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp': return Icons.image_outlined;
  442. default: return Icons.insert_drive_file;
  443. }
  444. }
  445. Widget _buildPageFooter(AppColorsExtension colors) {
  446. final l10n = AppLocalizations.of(context);
  447. return Center(
  448. child: Padding(
  449. padding: const EdgeInsets.only(bottom: 16),
  450. child: Row(
  451. mainAxisSize: MainAxisSize.min,
  452. children: [
  453. Icon(Icons.rocket_launch_outlined, size: 16, color: colors.textPlaceholder),
  454. const SizedBox(width: 6),
  455. Text(l10n.get('pageFooter'),
  456. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textPlaceholder)),
  457. ],
  458. ),
  459. ),
  460. );
  461. }
  462. Widget _buildUrgencyChip(String urgency, AppLocalizations l10n, AppColorsExtension colors) {
  463. final (label, color) = switch (urgency) {
  464. '3' || 'critical' => (l10n.get('critical'), colors.danger),
  465. '2' || 'urgent' => (l10n.get('urgent'), colors.warning),
  466. '1' || 'normal' => (l10n.get('normal'), colors.primary),
  467. _ => (l10n.get('normal'), colors.primary),
  468. };
  469. return Container(
  470. padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
  471. decoration: BoxDecoration(
  472. color: color.withValues(alpha: 0.1),
  473. borderRadius: BorderRadius.circular(4),
  474. border: Border.all(color: color, width: 0.5),
  475. ),
  476. child: Text(label, style: TextStyle(fontSize: 11, fontWeight: FontWeight.w500, color: color)),
  477. );
  478. }
  479. void _showExpenseDetailDialog(BuildContext context, ExpenseApplyDetailModel d) {
  480. ExpenseApplyDetailViewDialog.show(context, d);
  481. }
  482. }
  483. /// 附件缩略图 — 自动调用 DownloadAttachment 加载图片
  484. class _AttachmentThumbnail extends StatefulWidget {
  485. final ExpenseApplyApi api;
  486. final BillAttachment attachment;
  487. final double size;
  488. const _AttachmentThumbnail({required this.api, required this.attachment, required this.size});
  489. @override
  490. State<_AttachmentThumbnail> createState() => _AttachmentThumbnailState();
  491. }
  492. class _AttachmentThumbnailState extends State<_AttachmentThumbnail> {
  493. Uint8List? _bytes;
  494. bool _loading = true;
  495. @override
  496. void initState() {
  497. super.initState();
  498. _load();
  499. }
  500. Future<void> _load() async {
  501. try {
  502. final bytes = await widget.api.downloadAttachment(widget.attachment.id);
  503. if (mounted) setState(() { _bytes = bytes; _loading = false; });
  504. } catch (_) {
  505. if (mounted) setState(() => _loading = false);
  506. }
  507. }
  508. @override
  509. Widget build(BuildContext context) {
  510. if (_loading) {
  511. return SizedBox(width: widget.size, height: widget.size,
  512. child: const Center(child: SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))));
  513. }
  514. if (_bytes != null) {
  515. return ClipRRect(
  516. borderRadius: BorderRadius.circular(4),
  517. child: Image.memory(_bytes!, width: widget.size, height: widget.size, fit: BoxFit.cover),
  518. );
  519. }
  520. return Icon(Icons.broken_image, size: widget.size * 0.6, color: Colors.grey);
  521. }
  522. }