expense_edit_page.dart 40 KB

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