expense_edit_page.dart 42 KB

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