expense_edit_page.dart 42 KB

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