expense_edit_page.dart 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:flutter_riverpod/flutter_riverpod.dart';
  5. import 'package:tdesign_flutter/tdesign_flutter.dart';
  6. import 'package:go_router/go_router.dart';
  7. import '../../core/utils/responsive.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 '../../shared/widgets/app_skeletons.dart';
  12. import '../../shared/widgets/nav_bar_config.dart';
  13. import 'widgets/expense_detail_dialog.dart';
  14. import '../../shared/widgets/searchable_picker_sheet.dart';
  15. import '../../shared/widgets/loading_dialog.dart';
  16. import '../../shared/widgets/action_bar.dart';
  17. import 'expense_api.dart';
  18. import '../../core/i18n/app_localizations.dart';
  19. import 'expense_model.dart';
  20. import '../../core/theme/app_colors.dart';
  21. import '../../core/theme/app_colors_extension.dart';
  22. import '../../core/navigation/host_app_channel.dart';
  23. import '../../core/utils/amount_utils.dart';
  24. /// 费用报销修改页
  25. ///
  26. /// 完全参考 [ExpenseCreatePage] 创建页,但:
  27. /// - 无草稿功能
  28. /// - 无附件上传区
  29. /// - 无从申请单导入链接
  30. /// - initState 中加载原单数据并回填
  31. /// - 基本信息区顶部加单号、日期只读行
  32. /// - ActionBar 仅含提交按钮
  33. /// - 提交时 HeadData 加 BX_NO,成功 pop(true) 返回详情页
  34. class ExpenseEditPage extends ConsumerStatefulWidget {
  35. final String billNo;
  36. const ExpenseEditPage({super.key, required this.billNo});
  37. @override
  38. ConsumerState<ExpenseEditPage> createState() => _ExpenseEditPageState();
  39. }
  40. class _ExpenseEditPageState extends ConsumerState<ExpenseEditPage> {
  41. final _purposeController = TextEditingController();
  42. final _purposeFocus = FocusNode();
  43. final _remarkController = TextEditingController();
  44. final _remarkFocus = FocusNode();
  45. final _scrollCtrl = ScrollController();
  46. final _detailsSectionKey = GlobalKey();
  47. // ── 参考数据(从 API 加载) ──
  48. List<CurrencyItem> _currencies = [];
  49. EmployeeItem? _selEmployee;
  50. EmployeeItem? _currentUserForDialog;
  51. dynamic _acctTree;
  52. bool _firstBuild = true;
  53. bool _refDataLoading = true;
  54. bool _addingDetail = false;
  55. bool _isSubmitting = false;
  56. bool _canEditApprovedAmount = false;
  57. String? _loadingError;
  58. // ── 原单数据 ──
  59. ExpenseModel? _expense;
  60. ExpenseModel? _originalExpense; // 用于 _hasUnsaved 对比
  61. String _billNo = '';
  62. String _expenseDate = '';
  63. // ── 报销部门 ──
  64. String _selectedDeptId = '';
  65. String _selectedDeptName = '';
  66. @override
  67. void initState() {
  68. super.initState();
  69. SystemChrome.setSystemUIOverlayStyle(
  70. const SystemUiOverlayStyle(
  71. statusBarColor: Colors.transparent,
  72. statusBarIconBrightness: Brightness.dark,
  73. ),
  74. );
  75. _purposeFocus.addListener(() => _ensureVisible(_purposeFocus));
  76. _remarkFocus.addListener(() => _ensureVisible(_remarkFocus));
  77. _billNo = widget.billNo;
  78. _loadData();
  79. _checkApprovedAmountRight();
  80. }
  81. Future<void> _checkApprovedAmountRight() async {
  82. try {
  83. final api = ref.read(expenseApiProvider);
  84. final ok = await api.checkSpcRight('MONCJ_AMTN_SH');
  85. if (mounted) setState(() => _canEditApprovedAmount = ok);
  86. } catch (_) {
  87. if (mounted) setState(() => _canEditApprovedAmount = false);
  88. }
  89. }
  90. Future<void> _loadData() async {
  91. try {
  92. final api = ref.read(expenseApiProvider);
  93. final results = await Future.wait([
  94. api.getCurrencies(),
  95. api.fetchDetail(widget.billNo),
  96. api.getAcctSubjects(),
  97. api.getEmployees(salNo: HostAppChannel.usr, size: 1),
  98. ]);
  99. if (!mounted) return;
  100. final expense = results[1] as ExpenseModel;
  101. setState(() {
  102. _currencies = results[0] as List<CurrencyItem>;
  103. _acctTree = _convertAcctTree(results[2]);
  104. final currentUserCheck = results[3] as List<EmployeeItem>;
  105. if (currentUserCheck.isNotEmpty) {
  106. _currentUserForDialog = currentUserCheck.first;
  107. }
  108. _expense = expense;
  109. _expenseDate = expense.expenseDate != null
  110. ? du.DateUtils.formatDate(expense.expenseDate!)
  111. : _today();
  112. _selectedDeptId = expense.deptId;
  113. _selectedDeptName = expense.deptName;
  114. _selEmployee = expense.applicantId.isNotEmpty
  115. ? EmployeeItem(
  116. salNo: expense.applicantId,
  117. name: expense.applicantName,
  118. )
  119. : null;
  120. _purposeController.text = expense.purpose;
  121. _remarkController.text = expense.remark;
  122. _refDataLoading = false;
  123. _firstBuild = false;
  124. _recalculateAmount();
  125. _originalExpense = _expense;
  126. });
  127. } catch (e) {
  128. if (!mounted) return;
  129. setState(() {
  130. _refDataLoading = false;
  131. _firstBuild = false;
  132. _loadingError = e.toString();
  133. });
  134. }
  135. }
  136. Future<void> _showEmployeePicker() async {
  137. FocusManager.instance.primaryFocus?.unfocus();
  138. final l10n = AppLocalizations.of(context);
  139. final api = ref.read(expenseApiProvider);
  140. final result = await showSearchablePicker<EmployeeItem>(
  141. context,
  142. title: '${l10n.get('select')}${l10n.get('expensePersonnel')}',
  143. searchHint: l10n.get('search'),
  144. loader: (keyword, page) =>
  145. api.getEmployees(keyword: keyword, page: page, size: 20),
  146. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  147. onRefresh: () => api.clearRefCache(),
  148. );
  149. if (result != null && mounted) {
  150. setState(() {
  151. _selEmployee = result;
  152. _expense = _expense!.copyWith(
  153. applicantId: result.salNo,
  154. applicantName: result.name,
  155. );
  156. });
  157. }
  158. }
  159. void _ensureVisible(FocusNode node) {
  160. if (!node.hasFocus) return;
  161. WidgetsBinding.instance.addPostFrameCallback((_) {
  162. if (node.hasFocus && _scrollCtrl.hasClients) {
  163. final ctx = node.context;
  164. if (ctx != null) {
  165. Scrollable.ensureVisible(
  166. ctx,
  167. alignment: 0.3,
  168. duration: const Duration(milliseconds: 300),
  169. );
  170. }
  171. }
  172. });
  173. }
  174. @override
  175. void dispose() {
  176. _purposeController.dispose();
  177. _purposeFocus.dispose();
  178. _remarkController.dispose();
  179. _remarkFocus.dispose();
  180. _scrollCtrl.dispose();
  181. super.dispose();
  182. }
  183. // ═══ 状态更新助手(替代 Riverpod controller) ═══
  184. void _updatePurpose(String purpose) {
  185. if (_expense == null) return;
  186. setState(() {
  187. _expense = _expense!.copyWith(purpose: purpose);
  188. });
  189. }
  190. void _updateRemark(String remark) {
  191. if (_expense == null) return;
  192. setState(() {
  193. _expense = _expense!.copyWith(remark: remark);
  194. });
  195. }
  196. void _updatePaymentMethod(String method) {
  197. if (_expense == null) return;
  198. setState(() {
  199. _expense = _expense!.copyWith(paymentMethod: method);
  200. });
  201. }
  202. void _updateCurrencyCode(String code, [double excRto = 1.0]) {
  203. if (_expense == null) return;
  204. setState(() {
  205. _expense = _expense!.copyWith(currencyCode: code, excRto: excRto);
  206. });
  207. }
  208. void _setGenerateVoucher(bool value) {
  209. if (_expense == null) return;
  210. setState(() {
  211. _expense = _expense!.copyWith(isGenerateVoucher: value);
  212. });
  213. }
  214. void _addDetail(ExpenseDetailModel detail) {
  215. if (_expense == null) return;
  216. setState(() {
  217. _expense = _expense!.copyWith(details: [..._expense!.details, detail]);
  218. });
  219. _recalculateAmount();
  220. }
  221. void _updateDetail(int index, ExpenseDetailModel detail) {
  222. if (_expense == null) return;
  223. final details = [..._expense!.details];
  224. details[index] = detail;
  225. setState(() {
  226. _expense = _expense!.copyWith(details: details);
  227. });
  228. _recalculateAmount();
  229. }
  230. void _removeDetail(int index) {
  231. if (_expense == null) return;
  232. final details = [..._expense!.details]..removeAt(index);
  233. setState(() {
  234. _expense = _expense!.copyWith(details: details);
  235. });
  236. _recalculateAmount();
  237. }
  238. List<Map<String, dynamic>> _convertAcctTree(dynamic tree) {
  239. if (tree is! List) return [];
  240. return tree.map<Map<String, dynamic>>((item) {
  241. final map = Map<String, dynamic>.from(item is Map ? item : {});
  242. if (map.containsKey('children') && map['children'] != null) {
  243. map['children'] = _convertAcctTree(map['children']);
  244. }
  245. return map;
  246. }).toList();
  247. }
  248. void _recalculateAmount() {
  249. if (_expense == null) return;
  250. var totalAmount = 0.0;
  251. var approvedAmount = 0.0;
  252. for (final d in _expense!.details) {
  253. totalAmount += d.totalAmount;
  254. approvedAmount += d.approvedAmount;
  255. }
  256. setState(() {
  257. _expense = _expense!.copyWith(
  258. totalAmount: totalAmount,
  259. approvedAmount: approvedAmount,
  260. );
  261. });
  262. }
  263. String _currencyLabel(String code) {
  264. final match = _currencies.where((c) => c.curId == code);
  265. return match.isNotEmpty ? '${match.first.curId}/${match.first.name}' : code;
  266. }
  267. Future<void> _showDeptPicker() async {
  268. FocusManager.instance.primaryFocus?.unfocus();
  269. final l10n = AppLocalizations.of(context);
  270. final api = ref.read(expenseApiProvider);
  271. final result = await showSearchablePicker<DepartmentItem>(
  272. context,
  273. title: '${l10n.get('select')}${l10n.get('expenseDept')}',
  274. searchHint: l10n.get('search'),
  275. loader: (keyword, page) =>
  276. api.getDepartments(keyword: keyword, page: page, size: 20),
  277. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  278. onRefresh: () => api.clearRefCache(),
  279. );
  280. if (result != null && mounted) {
  281. setState(() {
  282. _selectedDeptId = result.dep;
  283. _selectedDeptName = result.name;
  284. _expense = _expense!.copyWith(
  285. deptId: result.dep,
  286. deptName: result.name,
  287. );
  288. });
  289. }
  290. }
  291. Map<String, dynamic> _buildSubmitData() {
  292. final expense = _expense!;
  293. return {
  294. 'HeadData': {
  295. 'BX_NO': _billNo,
  296. 'BX_DD': _today(),
  297. 'DEP': _selectedDeptId,
  298. 'USR_NO': _selEmployee?.salNo ?? '',
  299. 'PAY_ID': expense.paymentMethod,
  300. 'USR': HostAppChannel.usr,
  301. 'REM': expense.remark,
  302. 'CUR_ID': expense.currencyCode,
  303. 'EXC_RTO': expense.excRto,
  304. 'REASON': expense.purpose,
  305. 'VOH_ID': expense.isGenerateVoucher ? 'T' : 'F',
  306. },
  307. 'BodyData1': expense.details.asMap().entries.map((e) {
  308. final d = e.value;
  309. final item = <String, dynamic>{
  310. 'BX_NO': _billNo,
  311. 'BX_DD': _today(),
  312. 'ACC_NO': d.acctSubjectId,
  313. 'AMT': d.totalAmount,
  314. 'AMTN': d.amount,
  315. 'AMTN_SH': d.approvedAmount,
  316. 'REM': d.remark,
  317. 'CUST': d.customerVendorId,
  318. 'IDX_NO': d.expenseCategory,
  319. 'OBJ_NO': d.projectId.isNotEmpty ? d.projectId : '',
  320. 'TAX': d.taxAmount,
  321. 'TAX_RTO': d.taxRate,
  322. 'DEP': d.costDeptId,
  323. 'AE_NO': d.aeNo,
  324. 'AE_DD': d.aeDd,
  325. 'BNK_NO': d.bankName,
  326. 'BNK_ID': d.bankAccount,
  327. 'ACCNAME': d.bankAccountName,
  328. 'SQ_MAN': d.sqMan.isNotEmpty ? d.sqMan : HostAppChannel.usr,
  329. 'EST_ITM': d.aeNo.isNotEmpty ? d.sortOrder : 0,
  330. };
  331. if (d.preItm != null) {
  332. item['PRE_ITM'] = d.preItm;
  333. }
  334. return item;
  335. }).toList(),
  336. };
  337. }
  338. // ═══ Build ═══
  339. @override
  340. Widget build(BuildContext context) {
  341. final r = ResponsiveHelper.of(context);
  342. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  343. final l10n = AppLocalizations.of(context);
  344. final bottomInset = MediaQuery.of(context).padding.bottom;
  345. if (_loadingError != null) {
  346. return Center(
  347. child: Column(
  348. mainAxisSize: MainAxisSize.min,
  349. children: [
  350. Icon(Icons.error_outline, size: 48, color: colors.danger),
  351. const SizedBox(height: 16),
  352. Padding(
  353. padding: const EdgeInsets.symmetric(horizontal: 32),
  354. child: Text(
  355. _loadingError!,
  356. textAlign: TextAlign.center,
  357. style: TextStyle(
  358. fontSize: AppFontSizes.body,
  359. color: colors.textSecondary,
  360. ),
  361. ),
  362. ),
  363. const SizedBox(height: 16),
  364. TDButton(
  365. text: l10n.get('retry'),
  366. size: TDButtonSize.medium,
  367. onTap: () {
  368. setState(() {
  369. _loadingError = null;
  370. _firstBuild = true;
  371. _refDataLoading = true;
  372. });
  373. _loadData();
  374. },
  375. ),
  376. ],
  377. ),
  378. );
  379. }
  380. if (_firstBuild || _expense == null) {
  381. return const SkeletonFormPage(showImportLink: false);
  382. }
  383. Future.microtask(
  384. () => ref.read(pageBackProvider.notifier).state = () => _doPop(l10n),
  385. );
  386. Widget pageContent = PopScope(
  387. canPop: false,
  388. onPopInvokedWithResult: (didPop, _) {
  389. if (didPop) return;
  390. _doPop(l10n);
  391. },
  392. child: Column(
  393. children: [
  394. Expanded(
  395. child: Align(
  396. alignment: Alignment.topCenter,
  397. child: ConstrainedBox(
  398. constraints: BoxConstraints(maxWidth: r.formMaxWidth),
  399. child: SingleChildScrollView(
  400. controller: _scrollCtrl,
  401. padding: const EdgeInsets.all(16),
  402. child: Column(
  403. crossAxisAlignment: CrossAxisAlignment.start,
  404. children: [
  405. _buildBasicInfoSection(l10n, colors),
  406. const SizedBox(height: 16),
  407. Container(
  408. key: _detailsSectionKey,
  409. child: _buildDetailSection(l10n, colors),
  410. ),
  411. const SizedBox(height: 24),
  412. _buildPageFooter(),
  413. ],
  414. ),
  415. ),
  416. ),
  417. ),
  418. ),
  419. ColoredBox(
  420. color: colors.bgCard,
  421. child: Column(
  422. mainAxisSize: MainAxisSize.min,
  423. children: [
  424. _buildBottomButtons(l10n),
  425. if (bottomInset > 0) SizedBox(height: bottomInset),
  426. ],
  427. ),
  428. ),
  429. ],
  430. ),
  431. );
  432. return pageContent;
  433. }
  434. Widget _buildBasicInfoSection(
  435. AppLocalizations l10n,
  436. AppColorsExtension colors,
  437. ) {
  438. final expense = _expense!;
  439. return FormSection(
  440. title: l10n.get('basicInfo'),
  441. leadingIcon: Icons.info_outline,
  442. children: [
  443. FormFieldRow(
  444. label: l10n.get('expenseNo'),
  445. value: _billNo,
  446. readOnly: true,
  447. showArrow: false,
  448. ),
  449. const SizedBox(height: 16),
  450. FormFieldRow(
  451. label: l10n.get('date'),
  452. value: _expenseDate,
  453. readOnly: true,
  454. showArrow: false,
  455. ),
  456. const SizedBox(height: 16),
  457. FormFieldRow(
  458. label: l10n.get('expensePersonnel'),
  459. value: _selEmployee != null
  460. ? '${_selEmployee!.salNo}/${_selEmployee!.name}'
  461. : '',
  462. hint: l10n.get('pleaseSelect'),
  463. onTap: _showEmployeePicker,
  464. ),
  465. const SizedBox(height: 16),
  466. FormFieldRow(
  467. label: l10n.get('expenseDept'),
  468. value: _selectedDeptName.isNotEmpty
  469. ? '$_selectedDeptId/$_selectedDeptName'
  470. : null,
  471. hint: l10n.get('pleaseSelect'),
  472. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  473. ),
  474. const SizedBox(height: 16),
  475. _label(l10n.get('expenseReason'), required: true),
  476. const SizedBox(height: 8),
  477. TDTextarea(
  478. controller: _purposeController,
  479. focusNode: _purposeFocus,
  480. hintText: l10n.get('enterExpenseReason'),
  481. maxLines: 4,
  482. minLines: 1,
  483. maxLength: 500,
  484. indicator: true,
  485. padding: EdgeInsets.zero,
  486. bordered: true,
  487. backgroundColor: colors.bgPage,
  488. onChanged: (_) => _updatePurpose(_purposeController.text),
  489. ),
  490. const SizedBox(height: 16),
  491. FormFieldRow(
  492. label: l10n.get('paymentMethod'),
  493. value: expense.paymentMethod,
  494. hint: l10n.get('pleaseEnter'),
  495. onTap: () => _showTextInput(
  496. l10n.get('paymentMethod'),
  497. (v) => _updatePaymentMethod(v),
  498. initialText: expense.paymentMethod,
  499. ),
  500. onClear: () => _updatePaymentMethod(''),
  501. ),
  502. const SizedBox(height: 16),
  503. FormFieldRow(
  504. label: l10n.get('currency'),
  505. value: expense.currencyCode.isNotEmpty
  506. ? _currencyLabel(expense.currencyCode)
  507. : null,
  508. hint: l10n.get('selectCurrency'),
  509. onTap: () => _showCurrencyPicker(expense.currencyCode),
  510. onClear: () => _updateCurrencyCode(''),
  511. ),
  512. const SizedBox(height: 16),
  513. Row(
  514. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  515. children: [
  516. Text(
  517. l10n.get('generateVoucher'),
  518. style: TextStyle(
  519. fontSize: AppFontSizes.subtitle,
  520. color: colors.textSecondary,
  521. ),
  522. ),
  523. TDSwitch(
  524. isOn: expense.isGenerateVoucher,
  525. onChanged: (v) {
  526. _setGenerateVoucher(v);
  527. return v;
  528. },
  529. ),
  530. ],
  531. ),
  532. const SizedBox(height: 16),
  533. _label(l10n.get('remark')),
  534. const SizedBox(height: 8),
  535. TDTextarea(
  536. controller: _remarkController,
  537. focusNode: _remarkFocus,
  538. hintText: l10n.get('enterRemark'),
  539. maxLines: 3,
  540. minLines: 1,
  541. maxLength: 500,
  542. indicator: true,
  543. padding: EdgeInsets.zero,
  544. bordered: true,
  545. backgroundColor: colors.bgPage,
  546. onChanged: (_) => _updateRemark(_remarkController.text),
  547. ),
  548. ],
  549. );
  550. }
  551. Widget _buildDetailSection(AppLocalizations l10n, AppColorsExtension colors) {
  552. final expense = _expense!;
  553. final totalAmount = expense.details.fold<double>(
  554. 0,
  555. (sum, d) => sum + d.totalAmount,
  556. );
  557. final totalApproved = expense.details.fold<double>(
  558. 0,
  559. (sum, d) => sum + d.approvedAmount,
  560. );
  561. return FormSection(
  562. title: l10n.get('expenseDetails'),
  563. leadingIcon: Icons.receipt_long_outlined,
  564. showAction: true,
  565. actionText: l10n.get('add'),
  566. onActionTap: () => _showAddDetailDialog(),
  567. children: [
  568. if (expense.details.isEmpty)
  569. Padding(
  570. padding: const EdgeInsets.symmetric(vertical: 8),
  571. child: Text(
  572. l10n.get('noDetailHint'),
  573. style: TextStyle(
  574. fontSize: AppFontSizes.subtitle,
  575. color: colors.textPlaceholder,
  576. ),
  577. ),
  578. )
  579. else
  580. ...expense.details.asMap().entries.map((entry) {
  581. final d = entry.value;
  582. return GestureDetector(
  583. onTap: () => _showAddDetailDialog(editIndex: entry.key),
  584. child: Container(
  585. margin: const EdgeInsets.symmetric(vertical: 6),
  586. padding: const EdgeInsets.all(12),
  587. decoration: BoxDecoration(
  588. color: colors.bgPage,
  589. borderRadius: BorderRadius.circular(8),
  590. ),
  591. child: Row(
  592. children: [
  593. Expanded(
  594. child: Column(
  595. crossAxisAlignment: CrossAxisAlignment.start,
  596. children: [
  597. Row(
  598. children: [
  599. Expanded(
  600. child: Text(
  601. d.categoryName.isNotEmpty
  602. ? '${d.expenseCategory}/${d.categoryName}'
  603. : d.expenseCategory,
  604. style: TextStyle(
  605. fontSize: AppFontSizes.body,
  606. fontWeight: FontWeight.w500,
  607. color: colors.textPrimary,
  608. ),
  609. ),
  610. ),
  611. Column(
  612. crossAxisAlignment: CrossAxisAlignment.end,
  613. children: [
  614. Text(
  615. formatAmount(d.totalAmount),
  616. style: TextStyle(
  617. fontSize: AppFontSizes.body,
  618. fontWeight: FontWeight.w600,
  619. color: colors.amountPrimary,
  620. ),
  621. ),
  622. if (d.approvedAmount > 0)
  623. Text(
  624. formatAmount(d.approvedAmount),
  625. style: TextStyle(
  626. fontSize: AppFontSizes.body,
  627. fontWeight: FontWeight.w600,
  628. color: colors.success,
  629. ),
  630. ),
  631. ],
  632. ),
  633. ],
  634. ),
  635. const SizedBox(height: 2),
  636. Text(
  637. '${l10n.get('amountExcludingTax')}: ${formatAmount(d.amount)}',
  638. style: TextStyle(
  639. fontSize: AppFontSizes.caption,
  640. color: colors.textSecondary,
  641. ),
  642. ),
  643. if (d.taxAmount > 0)
  644. Text(
  645. '${l10n.get('taxAmount')}: ${formatAmount(d.taxAmount)}',
  646. style: TextStyle(
  647. fontSize: AppFontSizes.caption,
  648. color: colors.textSecondary,
  649. ),
  650. ),
  651. if (d.taxRate > 0)
  652. Text(
  653. '${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  654. style: TextStyle(
  655. fontSize: AppFontSizes.caption,
  656. color: colors.textSecondary,
  657. ),
  658. ),
  659. if (d.acctSubjectId.isNotEmpty)
  660. Text(
  661. '${l10n.get('acctSubject')}: ${d.acctSubjectId}${d.acctSubjectName.isNotEmpty ? '/${d.acctSubjectName}' : ''}',
  662. maxLines: 1,
  663. overflow: TextOverflow.ellipsis,
  664. style: TextStyle(
  665. fontSize: AppFontSizes.caption,
  666. color: colors.textSecondary,
  667. ),
  668. ),
  669. if (d.aeNo.isNotEmpty)
  670. Text(
  671. '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  672. maxLines: 1,
  673. overflow: TextOverflow.ellipsis,
  674. style: TextStyle(
  675. fontSize: AppFontSizes.caption,
  676. color: colors.textSecondary,
  677. ),
  678. ),
  679. if (d.aeDd.isNotEmpty)
  680. Text(
  681. '${l10n.get('applyDate')}: ${d.aeDd.length >= 10 ? d.aeDd.substring(0, 10) : d.aeDd}',
  682. style: TextStyle(
  683. fontSize: AppFontSizes.caption,
  684. color: colors.textSecondary,
  685. ),
  686. ),
  687. if (d.projectId.isNotEmpty)
  688. Text(
  689. '${l10n.get('project')}: ${d.projectId}${d.projectName.isNotEmpty ? '/${d.projectName}' : ''}',
  690. maxLines: 1,
  691. overflow: TextOverflow.ellipsis,
  692. style: TextStyle(
  693. fontSize: AppFontSizes.caption,
  694. color: colors.textSecondary,
  695. ),
  696. ),
  697. if (d.costDeptId.isNotEmpty)
  698. Text(
  699. '${l10n.get('costDept')}: ${d.costDeptId}${d.costDeptName.isNotEmpty ? '/${d.costDeptName}' : ''}',
  700. maxLines: 1,
  701. overflow: TextOverflow.ellipsis,
  702. style: TextStyle(
  703. fontSize: AppFontSizes.caption,
  704. color: colors.textSecondary,
  705. ),
  706. ),
  707. if (d.customerVendorId.isNotEmpty)
  708. Text(
  709. '${l10n.get('customerVendor')}: ${d.customerVendorId}${d.customerVendorName.isNotEmpty ? '/${d.customerVendorName}' : ''}',
  710. maxLines: 1,
  711. overflow: TextOverflow.ellipsis,
  712. style: TextStyle(
  713. fontSize: AppFontSizes.caption,
  714. color: colors.textSecondary,
  715. ),
  716. ),
  717. if (d.sqMan.isNotEmpty)
  718. Text(
  719. '${l10n.get('applicant')}: ${d.sqMan}${d.sqManName.isNotEmpty ? '/${d.sqManName}' : ''}',
  720. style: TextStyle(
  721. fontSize: AppFontSizes.caption,
  722. color: colors.textSecondary,
  723. ),
  724. ),
  725. if (d.bankAccountName.isNotEmpty)
  726. Text(
  727. '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  728. maxLines: 1,
  729. overflow: TextOverflow.ellipsis,
  730. style: TextStyle(
  731. fontSize: AppFontSizes.caption,
  732. color: colors.textSecondary,
  733. ),
  734. ),
  735. if (d.bankName.isNotEmpty)
  736. Text(
  737. '${l10n.get('bankName')}: ${d.bankName}',
  738. maxLines: 1,
  739. overflow: TextOverflow.ellipsis,
  740. style: TextStyle(
  741. fontSize: AppFontSizes.caption,
  742. color: colors.textSecondary,
  743. ),
  744. ),
  745. if (d.bankAccount.isNotEmpty)
  746. Text(
  747. '${l10n.get('bankAccount')}: ${d.bankAccount}',
  748. maxLines: 1,
  749. overflow: TextOverflow.ellipsis,
  750. style: TextStyle(
  751. fontSize: AppFontSizes.caption,
  752. color: colors.textSecondary,
  753. ),
  754. ),
  755. if (d.remark.isNotEmpty)
  756. Text(
  757. '${l10n.get('remark')}: ${d.remark}',
  758. maxLines: 2,
  759. overflow: TextOverflow.ellipsis,
  760. style: TextStyle(
  761. fontSize: AppFontSizes.caption,
  762. color: colors.textSecondary,
  763. ),
  764. ),
  765. ],
  766. ),
  767. ),
  768. const SizedBox(width: 8),
  769. GestureDetector(
  770. onTap: () => _removeDetail(entry.key),
  771. child: Icon(
  772. Icons.close,
  773. size: 18,
  774. color: colors.textSecondary,
  775. ),
  776. ),
  777. ],
  778. ),
  779. ),
  780. );
  781. }),
  782. const SizedBox(height: 8),
  783. Row(
  784. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  785. children: [
  786. Text(
  787. l10n.get('totalExpense'),
  788. style: TextStyle(
  789. fontSize: AppFontSizes.body,
  790. fontWeight: FontWeight.w600,
  791. color: colors.textPrimary,
  792. ),
  793. ),
  794. Text(
  795. formatAmount(totalAmount),
  796. style: TextStyle(
  797. fontSize: AppFontSizes.subtitle,
  798. fontWeight: FontWeight.w700,
  799. color: colors.amountPrimary,
  800. ),
  801. ),
  802. ],
  803. ),
  804. const SizedBox(height: 4),
  805. Row(
  806. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  807. children: [
  808. Text(
  809. l10n.get('approvedTotal'),
  810. style: TextStyle(
  811. fontSize: AppFontSizes.body,
  812. fontWeight: FontWeight.w600,
  813. color: colors.textPrimary,
  814. ),
  815. ),
  816. Text(
  817. formatAmount(totalApproved),
  818. style: TextStyle(
  819. fontSize: AppFontSizes.subtitle,
  820. fontWeight: FontWeight.w700,
  821. color: totalApproved > 0 ? colors.success : colors.textPrimary,
  822. ),
  823. ),
  824. ],
  825. ),
  826. ],
  827. );
  828. }
  829. Future<void> _showAddDetailDialog({int? editIndex}) async {
  830. if (_addingDetail) return;
  831. _addingDetail = true;
  832. try {
  833. final l10n = AppLocalizations.of(context);
  834. final expense = _expense!;
  835. ExpenseDetailInputData? initialData;
  836. if (editIndex != null) {
  837. final d = expense.details[editIndex];
  838. initialData = ExpenseDetailInputData(
  839. category: d.expenseCategory,
  840. categoryName: d.categoryName,
  841. acctSubjectId: d.acctSubjectId,
  842. acctSubjectName: d.acctSubjectName,
  843. purpose: d.purpose,
  844. amount: d.totalAmount,
  845. taxRate: d.taxRate,
  846. projectId: d.projectId,
  847. projectName: d.projectName,
  848. costDeptId: d.costDeptId,
  849. costDeptName: d.costDeptName,
  850. customerVendorId: d.customerVendorId,
  851. customerVendorName: d.customerVendorName,
  852. approvedAmount: d.approvedAmount,
  853. bankName: d.bankName,
  854. bankAccountName: d.bankAccountName,
  855. bankAccount: d.bankAccount,
  856. remark: d.remark,
  857. attachmentPaths: d.attachments,
  858. sqMan: d.sqMan,
  859. sqManName: d.sqManName,
  860. aeNo: d.aeNo,
  861. aeDd: d.aeDd,
  862. );
  863. }
  864. FocusManager.instance.primaryFocus?.unfocus();
  865. final result = await ExpenseDetailDialog.show(
  866. context,
  867. api: ref.read(expenseApiProvider),
  868. l10n: l10n,
  869. initialData: initialData,
  870. checkAttachHealth: () =>
  871. ref.read(expenseApiProvider).checkAttachHealth(),
  872. showAttachments: false,
  873. canEditApprovedAmount: _canEditApprovedAmount,
  874. acctTree: _acctTree,
  875. defaultSqMan: _currentUserForDialog?.salNo,
  876. defaultSqManName: _currentUserForDialog?.name,
  877. );
  878. if (result != null && mounted) {
  879. final now = DateTime.now();
  880. final detail = ExpenseDetailModel(
  881. id: editIndex != null
  882. ? expense.details[editIndex].id
  883. : now.millisecondsSinceEpoch.toString(),
  884. expenseId: '',
  885. expenseCategory: result.category,
  886. categoryName: result.categoryName,
  887. purpose: result.purpose,
  888. amount: result.taxRate > 0
  889. ? result.amount / (1 + result.taxRate / 100)
  890. : result.amount,
  891. taxRate: result.taxRate,
  892. taxAmount: result.taxRate > 0
  893. ? result.amount - result.amount / (1 + result.taxRate / 100)
  894. : 0,
  895. totalAmount: result.amount,
  896. projectId: result.projectId,
  897. projectName: result.projectName,
  898. costDeptId: result.costDeptId,
  899. costDeptName: result.costDeptName,
  900. acctSubjectId: result.acctSubjectId,
  901. acctSubjectName: result.acctSubjectName,
  902. customerVendorId: result.customerVendorId,
  903. customerVendorName: result.customerVendorName,
  904. approvedAmount: result.approvedAmount,
  905. bankName: result.bankName,
  906. bankAccountName: result.bankAccountName,
  907. bankAccount: result.bankAccount,
  908. sqMan: result.sqMan,
  909. sqManName: result.sqManName,
  910. aeNo: result.aeNo,
  911. aeDd: result.aeDd,
  912. remark: result.remark,
  913. sortOrder: editIndex != null
  914. ? expense.details[editIndex].sortOrder
  915. : 1,
  916. preItm: editIndex != null ? expense.details[editIndex].preItm : null,
  917. attachments: result.attachmentPaths,
  918. createTime: now,
  919. updateTime: now,
  920. );
  921. if (editIndex != null) {
  922. _updateDetail(editIndex, detail);
  923. } else {
  924. _addDetail(detail);
  925. }
  926. }
  927. } finally {
  928. _addingDetail = false;
  929. }
  930. }
  931. void _showCurrencyPicker(String cur) {
  932. if (_currencies.isEmpty) {
  933. TDToast.showText(
  934. AppLocalizations.of(context).get('noData'),
  935. context: context,
  936. );
  937. return;
  938. }
  939. final l10n = AppLocalizations.of(context);
  940. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  941. final codes = _currencies.map((c) => c.curId).toList();
  942. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  943. FocusManager.instance.primaryFocus?.unfocus();
  944. TDPicker.showMultiPicker(
  945. context,
  946. title: l10n.get('selectCurrency'),
  947. backgroundColor: colors.bgCard,
  948. data: [labels],
  949. onConfirm: (s) {
  950. if (s.isNotEmpty && s[0] is int) {
  951. final i = s[0] as int;
  952. if (i >= 0 && i < codes.length) {
  953. Navigator.of(context).pop();
  954. _updateCurrencyCode(codes[i], _currencies[i].excRto);
  955. }
  956. }
  957. },
  958. );
  959. }
  960. void _showTextInput(
  961. String title,
  962. Function(String) onConfirm, {
  963. String initialText = '',
  964. }) {
  965. FocusScope.of(context).unfocus();
  966. FocusManager.instance.primaryFocus?.unfocus();
  967. final l10n = AppLocalizations.of(context);
  968. final c = TextEditingController(text: initialText);
  969. showGeneralDialog(
  970. context: context,
  971. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  972. textEditingController: c,
  973. title: title,
  974. hintText: l10n.get('pleaseEnter'),
  975. leftBtn: TDDialogButtonOptions(
  976. title: l10n.get('cancel'),
  977. action: () => Navigator.pop(ctx),
  978. ),
  979. rightBtn: TDDialogButtonOptions(
  980. title: l10n.get('confirm'),
  981. action: () {
  982. onConfirm(c.text);
  983. Navigator.pop(ctx);
  984. },
  985. ),
  986. ),
  987. );
  988. }
  989. Widget _label(String t, {bool required = false}) {
  990. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  991. return Text.rich(
  992. TextSpan(
  993. children: [
  994. TextSpan(
  995. text: t,
  996. style: TextStyle(
  997. fontSize: AppFontSizes.subtitle,
  998. color: colors.textSecondary,
  999. ),
  1000. ),
  1001. if (required)
  1002. TextSpan(
  1003. text: ' *',
  1004. style: TextStyle(
  1005. fontSize: AppFontSizes.subtitle,
  1006. color: colors.danger,
  1007. ),
  1008. ),
  1009. ],
  1010. ),
  1011. );
  1012. }
  1013. Widget _buildBottomButtons(AppLocalizations l10n) {
  1014. return ActionBar(
  1015. showLeft: false,
  1016. showCenter: false,
  1017. rightLabel: l10n.get('submit'),
  1018. onRightTap: () async {
  1019. if (_isSubmitting) return;
  1020. final err = _validate(l10n);
  1021. if (err.isNotEmpty) {
  1022. TDToast.showText(err.first, context: context);
  1023. return;
  1024. }
  1025. FocusScope.of(context).unfocus();
  1026. _isSubmitting = true;
  1027. LoadingDialog.show(context, text: l10n.get('submitting'));
  1028. try {
  1029. final data = _buildSubmitData();
  1030. final api = ref.read(expenseApiProvider);
  1031. final billNo = await api.submit(data);
  1032. if (mounted) {
  1033. LoadingDialog.hide(context);
  1034. TDToast.showSuccess(l10n.get('submitSuccess'), context: context);
  1035. // BillSave 成功后异步提交审核流,不阻塞不弹窗
  1036. if (billNo != null) {
  1037. api.shSubmit(
  1038. bilNo: billNo,
  1039. bilDd: data['HeadData']['BX_DD']?.toString() ?? '',
  1040. );
  1041. }
  1042. WidgetsBinding.instance.addPostFrameCallback((_) {
  1043. if (mounted) GoRouter.of(context).pop(true);
  1044. });
  1045. }
  1046. } catch (e) {
  1047. if (mounted) LoadingDialog.hide(context);
  1048. } finally {
  1049. _isSubmitting = false;
  1050. }
  1051. },
  1052. );
  1053. }
  1054. List<String> _validate(AppLocalizations l10n) {
  1055. final e = <String>[];
  1056. if (_purposeController.text.trim().isEmpty) {
  1057. e.add(l10n.get('enterExpenseReason'));
  1058. }
  1059. if (_expense!.details.isEmpty) {
  1060. e.add(l10n.get('addAtLeastOneDetail'));
  1061. }
  1062. return e;
  1063. }
  1064. bool _hasUnsaved() {
  1065. if (_expense == null || _originalExpense == null) return false;
  1066. final e = _expense!;
  1067. final o = _originalExpense!;
  1068. if (e.purpose != o.purpose) return true;
  1069. if (e.remark != o.remark) return true;
  1070. if (e.paymentMethod != o.paymentMethod) return true;
  1071. if (e.currencyCode != o.currencyCode) return true;
  1072. if (e.details.length != o.details.length) return true;
  1073. for (var i = 0; i < e.details.length; i++) {
  1074. if (i >= o.details.length) return true;
  1075. final d = e.details[i];
  1076. final od = o.details[i];
  1077. if (d.expenseCategory != od.expenseCategory ||
  1078. d.acctSubjectId != od.acctSubjectId ||
  1079. d.amount != od.amount ||
  1080. d.taxRate != od.taxRate ||
  1081. d.totalAmount != od.totalAmount ||
  1082. d.approvedAmount != od.approvedAmount ||
  1083. d.projectId != od.projectId ||
  1084. d.costDeptId != od.costDeptId ||
  1085. d.customerVendorId != od.customerVendorId ||
  1086. d.remark != od.remark ||
  1087. d.bankName != od.bankName ||
  1088. d.bankAccount != od.bankAccount ||
  1089. d.bankAccountName != od.bankAccountName ||
  1090. d.sqMan != od.sqMan ||
  1091. d.aeNo != od.aeNo ||
  1092. d.aeDd != od.aeDd) {
  1093. return true;
  1094. }
  1095. }
  1096. return false;
  1097. }
  1098. void _doPop(AppLocalizations l10n) {
  1099. if (_hasUnsaved()) {
  1100. _showConfirmDialog(
  1101. l10n.get('confirmExit'),
  1102. l10n.get('unsavedContentWarning'),
  1103. l10n.get('continueEditing'),
  1104. l10n.get('discardAndExit'),
  1105. () {
  1106. if (!mounted) return;
  1107. _forcePop();
  1108. },
  1109. );
  1110. } else {
  1111. _forcePop();
  1112. }
  1113. }
  1114. void _forcePop() {
  1115. FocusManager.instance.primaryFocus?.unfocus();
  1116. final router = GoRouter.of(context);
  1117. if (router.canPop()) {
  1118. router.pop();
  1119. } else {
  1120. SystemNavigator.pop();
  1121. }
  1122. }
  1123. void _showConfirmDialog(
  1124. String title,
  1125. String content,
  1126. String leftText,
  1127. String rightText,
  1128. VoidCallback onConfirm,
  1129. ) {
  1130. FocusScope.of(context).unfocus();
  1131. FocusManager.instance.primaryFocus?.unfocus();
  1132. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1133. showDialog(
  1134. context: context,
  1135. useRootNavigator: true,
  1136. builder: (ctx) => TDAlertDialog(
  1137. title: title,
  1138. content: content,
  1139. buttonStyle: TDDialogButtonStyle.text,
  1140. leftBtn: TDDialogButtonOptions(
  1141. title: leftText,
  1142. titleColor: colors.primary,
  1143. action: () => Navigator.pop(ctx),
  1144. ),
  1145. rightBtn: TDDialogButtonOptions(
  1146. title: rightText,
  1147. titleColor: colors.danger,
  1148. action: () {
  1149. Navigator.pop(ctx);
  1150. onConfirm();
  1151. },
  1152. ),
  1153. ),
  1154. );
  1155. }
  1156. Widget _buildPageFooter() {
  1157. final l10n = AppLocalizations.of(context);
  1158. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1159. return Center(
  1160. child: Padding(
  1161. padding: const EdgeInsets.only(bottom: 16),
  1162. child: Row(
  1163. mainAxisSize: MainAxisSize.min,
  1164. children: [
  1165. Icon(
  1166. Icons.rocket_launch_outlined,
  1167. size: 16,
  1168. color: colors.textPlaceholder,
  1169. ),
  1170. const SizedBox(width: 6),
  1171. Text(
  1172. l10n.get('pageFooter'),
  1173. style: TextStyle(
  1174. fontSize: AppFontSizes.caption,
  1175. color: colors.textPlaceholder,
  1176. ),
  1177. ),
  1178. ],
  1179. ),
  1180. ),
  1181. );
  1182. }
  1183. String _today() {
  1184. final n = DateTime.now();
  1185. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1186. }
  1187. }