expense_edit_page.dart 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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('submitSuccess'),
  1073. context: context,
  1074. );
  1075. WidgetsBinding.instance.addPostFrameCallback((_) {
  1076. if (mounted) GoRouter.of(context).pop(true);
  1077. });
  1078. }
  1079. } catch (e) {
  1080. if (mounted) {
  1081. LoadingDialog.hide(context);
  1082. WidgetsBinding.instance.addPostFrameCallback((_) {
  1083. if (mounted) _showSubmitError(e, l10n);
  1084. });
  1085. }
  1086. } finally {
  1087. _isSubmitting = false;
  1088. }
  1089. },
  1090. );
  1091. }
  1092. void _showSubmitError(Object e, AppLocalizations l10n) {
  1093. final message = _extractErrorMessage(e) ?? l10n.get('submitFailedRetry');
  1094. showGeneralDialog(
  1095. context: context,
  1096. pageBuilder: (ctx, animation, secondaryAnimation) => TDConfirmDialog(
  1097. title: l10n.get('submitFailed'),
  1098. content: message,
  1099. buttonStyle: TDDialogButtonStyle.text,
  1100. ),
  1101. );
  1102. }
  1103. String? _extractErrorMessage(Object e) {
  1104. if (e is DioException) {
  1105. if (e.error is ApiException) return (e.error as ApiException).message;
  1106. if (e.error is NetworkException) {
  1107. return (e.error as NetworkException).message;
  1108. }
  1109. }
  1110. return null;
  1111. }
  1112. List<String> _validate(AppLocalizations l10n) {
  1113. final e = <String>[];
  1114. if (_purposeController.text.trim().isEmpty) {
  1115. e.add(l10n.get('enterExpenseReason'));
  1116. }
  1117. if (_expense!.details.isEmpty) {
  1118. e.add(l10n.get('addAtLeastOneDetail'));
  1119. }
  1120. return e;
  1121. }
  1122. bool _hasUnsaved() =>
  1123. _purposeController.text.isNotEmpty ||
  1124. (_expense?.paymentMethod.isNotEmpty ?? false) ||
  1125. (_expense?.currencyCode.isNotEmpty ?? false) ||
  1126. _remarkController.text.isNotEmpty ||
  1127. (_expense?.details.isNotEmpty ?? false);
  1128. void _doPop(AppLocalizations l10n) {
  1129. if (_hasUnsaved()) {
  1130. _showConfirmDialog(
  1131. l10n.get('confirmExit'),
  1132. l10n.get('unsavedContentWarning'),
  1133. l10n.get('continueEditing'),
  1134. l10n.get('discardAndExit'),
  1135. () {
  1136. if (!mounted) return;
  1137. _forcePop();
  1138. },
  1139. );
  1140. } else {
  1141. _forcePop();
  1142. }
  1143. }
  1144. void _forcePop() {
  1145. FocusManager.instance.primaryFocus?.unfocus();
  1146. final router = GoRouter.of(context);
  1147. if (router.canPop()) {
  1148. router.pop();
  1149. } else {
  1150. SystemNavigator.pop();
  1151. }
  1152. }
  1153. void _showConfirmDialog(
  1154. String title,
  1155. String content,
  1156. String leftText,
  1157. String rightText,
  1158. VoidCallback onConfirm,
  1159. ) {
  1160. FocusScope.of(context).unfocus();
  1161. FocusManager.instance.primaryFocus?.unfocus();
  1162. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1163. showDialog(
  1164. context: context,
  1165. useRootNavigator: true,
  1166. builder: (ctx) => TDAlertDialog(
  1167. title: title,
  1168. content: content,
  1169. buttonStyle: TDDialogButtonStyle.text,
  1170. leftBtn: TDDialogButtonOptions(
  1171. title: leftText,
  1172. titleColor: colors.primary,
  1173. action: () => Navigator.pop(ctx),
  1174. ),
  1175. rightBtn: TDDialogButtonOptions(
  1176. title: rightText,
  1177. titleColor: colors.danger,
  1178. action: () {
  1179. Navigator.pop(ctx);
  1180. onConfirm();
  1181. },
  1182. ),
  1183. ),
  1184. );
  1185. }
  1186. Widget _buildPageFooter() {
  1187. final l10n = AppLocalizations.of(context);
  1188. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1189. return Center(
  1190. child: Padding(
  1191. padding: const EdgeInsets.only(bottom: 16),
  1192. child: Row(
  1193. mainAxisSize: MainAxisSize.min,
  1194. children: [
  1195. Icon(
  1196. Icons.rocket_launch_outlined,
  1197. size: 16,
  1198. color: colors.textPlaceholder,
  1199. ),
  1200. const SizedBox(width: 6),
  1201. Text(
  1202. l10n.get('pageFooter'),
  1203. style: TextStyle(
  1204. fontSize: AppFontSizes.caption,
  1205. color: colors.textPlaceholder,
  1206. ),
  1207. ),
  1208. ],
  1209. ),
  1210. ),
  1211. );
  1212. }
  1213. String _today() {
  1214. final n = DateTime.now();
  1215. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1216. }
  1217. }