expense_apply_detail_page.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import 'package:flutter/material.dart';
  2. import 'package:tdesign_flutter/tdesign_flutter.dart';
  3. import 'package:flutter_riverpod/flutter_riverpod.dart';
  4. import 'package:go_router/go_router.dart';
  5. import '../../shared/widgets/nav_bar_config.dart';
  6. import '../../core/utils/date_utils.dart' as du;
  7. import '../../shared/widgets/form_section.dart';
  8. import '../../shared/widgets/form_field_row.dart';
  9. import '../../shared/widgets/approval_actions.dart';
  10. import '../../shared/widgets/approval_timeline.dart';
  11. import '../../shared/models/approval_status.dart';
  12. import 'expense_apply_model.dart';
  13. import '../../core/i18n/app_localizations.dart';
  14. import '../../shared/widgets/loading_dialog.dart';
  15. import '../../shared/models/bill_attachment.dart';
  16. import 'expense_apply_api.dart';
  17. import '../../core/theme/app_colors.dart';
  18. import '../../core/theme/app_colors_extension.dart';
  19. class ExpenseApplyDetailPage extends ConsumerStatefulWidget {
  20. final String billNo;
  21. final int queryId;
  22. const ExpenseApplyDetailPage({super.key, required this.billNo, this.queryId = 0});
  23. @override
  24. ConsumerState<ExpenseApplyDetailPage> createState() => _ExpenseApplyDetailPageState();
  25. }
  26. class _ExpenseApplyDetailPageState extends ConsumerState<ExpenseApplyDetailPage> {
  27. bool _loading = true;
  28. String? _error;
  29. ExpenseApplyModel? _data;
  30. List<BillAttachment> _attachments = [];
  31. List<ApprovalRecord> _approvalRecords = [];
  32. List<String> _approvalChain = [];
  33. String _currentApproverId = '';
  34. @override
  35. void initState() {
  36. super.initState();
  37. _loadData();
  38. }
  39. Future<void> _loadData() async {
  40. setState(() { _loading = true; _error = null; });
  41. try {
  42. final api = ref.read(expenseApplyApiProvider);
  43. final detail = await api.fetchDetail(widget.billNo);
  44. // Load approval timeline (non-critical, best-effort)
  45. List<ApprovalRecord> records = [];
  46. List<String> chain = [];
  47. String currentId = '';
  48. try {
  49. final timeline = await api.fetchApprovalTimeline('AE', widget.billNo);
  50. records = (timeline['records'] as List<dynamic>?)
  51. ?.map((e) => ApprovalRecord.fromJson(e as Map<String, dynamic>))
  52. .toList() ??
  53. [];
  54. chain = (timeline['chain'] as List<dynamic>?)
  55. ?.map((e) => e as String)
  56. .toList() ??
  57. [];
  58. currentId = timeline['currentApproverId'] as String? ?? '';
  59. } catch (_) {
  60. // Timeline load failure is non-fatal
  61. }
  62. // Load attachments (non-critical, best-effort)
  63. List<BillAttachment> attachments = [];
  64. try {
  65. attachments = await api.getAttachments('AE', widget.billNo);
  66. } catch (_) {
  67. // Attachment load failure is non-fatal
  68. }
  69. if (mounted) {
  70. setState(() {
  71. _data = detail;
  72. _approvalRecords = records;
  73. _approvalChain = chain;
  74. _currentApproverId = currentId;
  75. _attachments = attachments;
  76. _loading = false;
  77. });
  78. }
  79. } catch (e) {
  80. if (mounted) {
  81. setState(() { _error = e.toString(); _loading = false; });
  82. }
  83. }
  84. }
  85. void _handleApprove() async {
  86. final l10n = AppLocalizations.of(context);
  87. final rem = await _showOpinionDialog(
  88. title: l10n.get('confirmApprove'),
  89. hint: l10n.get('approvalComment'),
  90. );
  91. if (rem == null || !mounted) return;
  92. await _doAudit('approve', rem: rem);
  93. }
  94. void _handleReject() async {
  95. final l10n = AppLocalizations.of(context);
  96. final rem = await _showOpinionDialog(
  97. title: l10n.get('confirmReject'),
  98. hint: l10n.get('rejectReason'),
  99. );
  100. if (rem == null || !mounted) return;
  101. await _doAudit('reject', rem: rem);
  102. }
  103. void _handleReverseAudit() async {
  104. final l10n = AppLocalizations.of(context);
  105. final confirmed = await showDialog<bool>(
  106. context: context,
  107. builder: (ctx) => TDAlertDialog(
  108. title: l10n.get('withdrawConfirm'),
  109. content: l10n.get('withdrawConfirmTip'),
  110. leftBtn: TDDialogButtonOptions(title: l10n.get('cancel'), action: () => Navigator.pop(ctx, false)),
  111. rightBtn: TDDialogButtonOptions(title: l10n.get('confirm'), action: () => Navigator.pop(ctx, true)),
  112. ),
  113. );
  114. if (confirmed != true || !mounted) return;
  115. final rem = await _showOpinionDialog(
  116. title: l10n.get('withdrawConfirm'),
  117. hint: l10n.get('approvalComment'),
  118. );
  119. if (rem == null || !mounted) return;
  120. await _doAudit('reverseAudit', rem: rem);
  121. }
  122. /// 弹出审批意见输入框,返回 null 表示取消
  123. Future<String?> _showOpinionDialog({
  124. required String title,
  125. required String hint,
  126. }) async {
  127. final ctrl = TextEditingController();
  128. return showDialog<String>(
  129. context: context,
  130. builder: (ctx) => TDAlertDialog(
  131. title: title,
  132. content: hint,
  133. leftBtn: TDDialogButtonOptions(
  134. title: AppLocalizations.of(context).get('cancel'),
  135. action: () => Navigator.pop(ctx),
  136. ),
  137. rightBtn: TDDialogButtonOptions(
  138. title: AppLocalizations.of(context).get('confirm'),
  139. action: () => Navigator.pop(ctx, ctrl.text),
  140. ),
  141. ),
  142. );
  143. }
  144. Future<void> _doAudit(String action, {String rem = ''}) async {
  145. try {
  146. LoadingDialog.show(context);
  147. final api = ref.read(expenseApplyApiProvider);
  148. await api.executeApproval(bilId: 'AE', bilNo: widget.billNo, action: action, rem: rem);
  149. if (mounted) {
  150. LoadingDialog.hide(context);
  151. TDToast.showSuccess(AppLocalizations.of(context).get('submitSuccess'), context: context);
  152. if (mounted) context.pop();
  153. }
  154. } catch (e) {
  155. if (mounted) {
  156. LoadingDialog.hide(context);
  157. TDToast.showFail(e.toString(), context: context);
  158. }
  159. }
  160. }
  161. @override
  162. Widget build(BuildContext context) {
  163. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  164. final l10n = AppLocalizations.of(context);
  165. ref
  166. .read(navBarConfigProvider.notifier)
  167. .update(
  168. NavBarConfig(
  169. title: l10n.get('expenseApplyDetail'),
  170. showBack: true,
  171. onBack: () => context.pop(),
  172. ),
  173. );
  174. if (_loading) {
  175. return const Center(
  176. child: TDLoading(size: TDLoadingSize.large, icon: TDLoadingIcon.activity),
  177. );
  178. }
  179. if (_error != null) {
  180. return Center(
  181. child: Column(
  182. mainAxisSize: MainAxisSize.min,
  183. children: [
  184. Icon(Icons.error_outline, size: 48, color: colors.danger),
  185. const SizedBox(height: 16),
  186. Padding(
  187. padding: const EdgeInsets.symmetric(horizontal: 32),
  188. child: Text(
  189. _error!,
  190. textAlign: TextAlign.center,
  191. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textSecondary),
  192. ),
  193. ),
  194. const SizedBox(height: 16),
  195. TDButton(
  196. text: l10n.get('retry'),
  197. size: TDButtonSize.medium,
  198. onTap: _loadData,
  199. ),
  200. ],
  201. ),
  202. );
  203. }
  204. final app = _data!;
  205. return Column(
  206. children: [
  207. Expanded(
  208. child: SingleChildScrollView(
  209. padding: const EdgeInsets.all(16),
  210. child: Column(
  211. children: [
  212. _buildBasicInfoSection(app, l10n, colors),
  213. const SizedBox(height: 16),
  214. _buildExpenseDetailSection(app, l10n, colors),
  215. const SizedBox(height: 16),
  216. _buildAttachmentSection(l10n, colors),
  217. const SizedBox(height: 16),
  218. if (_approvalChain.isNotEmpty)
  219. Container(
  220. padding: const EdgeInsets.all(16),
  221. decoration: BoxDecoration(
  222. color: colors.bgCard,
  223. borderRadius: BorderRadius.circular(8),
  224. ),
  225. child: ApprovalTimeline(
  226. records: _approvalRecords,
  227. chain: _approvalChain,
  228. currentApproverId: _currentApproverId,
  229. ),
  230. ),
  231. ],
  232. ),
  233. ),
  234. ),
  235. ApprovalActions(
  236. queryId: widget.queryId,
  237. onApprove: _handleApprove,
  238. onReject: _handleReject,
  239. onReverseAudit: _handleReverseAudit,
  240. ),
  241. ],
  242. );
  243. }
  244. // ═══ 基本信息 ═══
  245. Widget _buildBasicInfoSection(
  246. ExpenseApplyModel app,
  247. AppLocalizations l10n,
  248. AppColorsExtension colors,
  249. ) {
  250. String urgencyLabel = switch (app.urgency) {
  251. 'urgent' => l10n.get('urgent'),
  252. 'normal' => l10n.get('normal'),
  253. 'critical' => l10n.get('critical'),
  254. _ => app.urgency,
  255. };
  256. return FormSection(
  257. title: l10n.get('basicInfo'),
  258. leadingIcon: Icons.info_outline,
  259. children: [
  260. FormFieldRow(label: l10n.get('expenseApplyNo'), value: app.expenseApplyNo, readOnly: true, showArrow: false),
  261. const SizedBox(height: 16),
  262. FormFieldRow(label: l10n.get('applicant'), value: app.applicantName, readOnly: true, showArrow: false),
  263. const SizedBox(height: 16),
  264. FormFieldRow(label: l10n.get('department'), value: app.deptName, readOnly: true, showArrow: false),
  265. const SizedBox(height: 16),
  266. FormFieldRow(label: l10n.get('date'), value: du.DateUtils.formatDateTime(app.createTime), readOnly: true, showArrow: false),
  267. const SizedBox(height: 16),
  268. SizedBox(
  269. height: 24,
  270. child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
  271. Text(l10n.get('emergencyLevel'), style: TextStyle(fontSize: AppFontSizes.subtitle, color: colors.textSecondary)),
  272. Text(urgencyLabel, style: TextStyle(
  273. fontSize: AppFontSizes.subtitle, fontWeight: FontWeight.w600,
  274. color: app.urgency == 'urgent' || app.urgency == 'critical' ? colors.danger : colors.textPrimary,
  275. )),
  276. ]),
  277. ),
  278. const SizedBox(height: 16),
  279. FormFieldRow(label: l10n.get('feeReason'), value: app.purpose, readOnly: true, showArrow: false),
  280. const SizedBox(height: 16),
  281. FormFieldRow(label: l10n.get('remark'), value: app.remark.isNotEmpty ? app.remark : '-', readOnly: true, showArrow: false),
  282. ],
  283. );
  284. }
  285. // ═══ 费用明细 ═══
  286. Widget _buildExpenseDetailSection(
  287. ExpenseApplyModel app,
  288. AppLocalizations l10n,
  289. AppColorsExtension colors,
  290. ) {
  291. return FormSection(
  292. title: l10n.get('expenseDetails'),
  293. leadingIcon: Icons.receipt_long_outlined,
  294. children: [
  295. if (app.details.isEmpty)
  296. Padding(
  297. padding: const EdgeInsets.symmetric(vertical: 8),
  298. child: Text(l10n.get('noDetailData'), style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder)),
  299. )
  300. else
  301. ...app.details.asMap().entries.map((e) {
  302. final d = e.value;
  303. final catLabel = d.categoryName.isNotEmpty
  304. ? '${d.expenseCategory}/${d.categoryName}'
  305. : d.expenseCategory;
  306. return Container(
  307. margin: const EdgeInsets.symmetric(vertical: 8),
  308. padding: const EdgeInsets.all(12),
  309. decoration: BoxDecoration(color: colors.bgPage, borderRadius: BorderRadius.circular(8)),
  310. child: Row(
  311. crossAxisAlignment: CrossAxisAlignment.center,
  312. children: [
  313. Expanded(
  314. child: Column(
  315. crossAxisAlignment: CrossAxisAlignment.start,
  316. children: [
  317. Row(
  318. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  319. children: [
  320. Expanded(
  321. child: Text(
  322. catLabel,
  323. maxLines: 1,
  324. overflow: TextOverflow.ellipsis,
  325. style: TextStyle(fontSize: AppFontSizes.subtitle, color: colors.textPrimary),
  326. ),
  327. ),
  328. const SizedBox(width: 12),
  329. Text(
  330. '¥${d.estimatedAmount.toStringAsFixed(2)}',
  331. style: TextStyle(fontSize: AppFontSizes.caption, fontWeight: FontWeight.w600, color: colors.amountPrimary),
  332. ),
  333. ],
  334. ),
  335. if (d.acctSubjectId.isNotEmpty && d.acctSubjectName.isNotEmpty) ...[
  336. const SizedBox(height: 4),
  337. Text(
  338. '${d.acctSubjectId}/${d.acctSubjectName}',
  339. maxLines: 1,
  340. overflow: TextOverflow.ellipsis,
  341. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  342. ),
  343. ],
  344. if (d.projectId.isNotEmpty && d.projectName.isNotEmpty) ...[
  345. const SizedBox(height: 4),
  346. Text(
  347. '${d.projectId}/${d.projectName}',
  348. maxLines: 1,
  349. overflow: TextOverflow.ellipsis,
  350. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  351. ),
  352. ],
  353. if (d.costDeptId.isNotEmpty && d.costDeptName.isNotEmpty) ...[
  354. const SizedBox(height: 4),
  355. Text(
  356. '${d.costDeptId}/${d.costDeptName}',
  357. maxLines: 1,
  358. overflow: TextOverflow.ellipsis,
  359. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  360. ),
  361. ],
  362. if (d.estimatedStartDate != null) ...[
  363. const SizedBox(height: 4),
  364. Text(
  365. '${du.DateUtils.formatDate(d.estimatedStartDate!)} ~ ${d.estimatedEndDate != null ? du.DateUtils.formatDate(d.estimatedEndDate!) : ''}',
  366. maxLines: 1,
  367. overflow: TextOverflow.ellipsis,
  368. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  369. ),
  370. ],
  371. if (d.remark.isNotEmpty) ...[
  372. const SizedBox(height: 4),
  373. Text(
  374. d.remark,
  375. maxLines: 2,
  376. overflow: TextOverflow.ellipsis,
  377. style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textSecondary),
  378. ),
  379. ],
  380. ],
  381. ),
  382. ),
  383. ],
  384. ),
  385. );
  386. }),
  387. if (app.details.isNotEmpty) ...[
  388. const SizedBox(height: 8),
  389. Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
  390. Text(l10n.get('total'), style: TextStyle(fontSize: AppFontSizes.body, fontWeight: FontWeight.w600, color: colors.textPrimary)),
  391. Text('¥${app.estimatedAmount.toStringAsFixed(2)}',
  392. style: TextStyle(fontSize: AppFontSizes.subtitle, fontWeight: FontWeight.w700, color: colors.amountPrimary)),
  393. ]),
  394. ],
  395. ],
  396. );
  397. }
  398. // ═══ 附件 ═══
  399. Widget _buildAttachmentSection(AppLocalizations l10n, AppColorsExtension colors) {
  400. return FormSection(
  401. title: l10n.get('attachments'),
  402. leadingIcon: Icons.attach_file_outlined,
  403. children: [
  404. if (_attachments.isEmpty)
  405. Text(l10n.get('noAttachment'), style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPlaceholder))
  406. else
  407. ..._attachments.map((a) => _buildAttachmentRow(a, colors)),
  408. ],
  409. );
  410. }
  411. Widget _buildAttachmentRow(BillAttachment a, AppColorsExtension colors) {
  412. return Container(
  413. margin: const EdgeInsets.symmetric(vertical: 4),
  414. padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  415. decoration: BoxDecoration(
  416. color: colors.bgPage,
  417. borderRadius: BorderRadius.circular(8),
  418. ),
  419. child: Row(children: [
  420. Icon(_fileTypeIcon(a.ext), size: 24, color: colors.primary),
  421. const SizedBox(width: 10),
  422. Expanded(
  423. child: Text(a.fileName,
  424. maxLines: 1, overflow: TextOverflow.ellipsis,
  425. style: TextStyle(fontSize: AppFontSizes.body, color: colors.textPrimary)),
  426. ),
  427. ]),
  428. );
  429. }
  430. IconData _fileTypeIcon(String ext) {
  431. switch (ext.toLowerCase()) {
  432. case 'pdf': return Icons.picture_as_pdf;
  433. case 'doc': case 'docx': return Icons.description;
  434. case 'xls': case 'xlsx': return Icons.table_chart;
  435. case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp': return Icons.image_outlined;
  436. default: return Icons.insert_drive_file;
  437. }
  438. }
  439. }