expense_edit_page.dart 41 KB

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