expense_edit_page.dart 40 KB

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