expense_edit_page.dart 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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. );
  897. if (result != null && mounted) {
  898. final now = DateTime.now();
  899. final detail = ExpenseDetailModel(
  900. id: editIndex != null
  901. ? expense.details[editIndex].id
  902. : now.millisecondsSinceEpoch.toString(),
  903. expenseId: '',
  904. expenseCategory: result.category,
  905. categoryName: result.categoryName,
  906. purpose: result.purpose,
  907. amount: result.taxRate > 0
  908. ? result.amount / (1 + result.taxRate / 100)
  909. : result.amount,
  910. taxRate: result.taxRate,
  911. taxAmount: result.taxRate > 0
  912. ? result.amount - result.amount / (1 + result.taxRate / 100)
  913. : 0,
  914. totalAmount: result.amount,
  915. projectId: result.projectId,
  916. projectName: result.projectName,
  917. costDeptId: result.costDeptId,
  918. costDeptName: result.costDeptName,
  919. acctSubjectId: result.acctSubjectId,
  920. acctSubjectName: result.acctSubjectName,
  921. customerVendorId: result.customerVendorId,
  922. customerVendorName: result.customerVendorName,
  923. approvedAmount: result.approvedAmount,
  924. bankName: result.bankName,
  925. bankAccountName: result.bankAccountName,
  926. bankAccount: result.bankAccount,
  927. sqMan: result.sqMan,
  928. sqManName: result.sqManName,
  929. aeNo: result.aeNo,
  930. aeDd: result.aeDd,
  931. remark: result.remark,
  932. preItm: editIndex != null
  933. ? expense.details[editIndex].preItm
  934. : null,
  935. attachments: result.attachmentPaths,
  936. createTime: now,
  937. updateTime: now,
  938. );
  939. if (editIndex != null) {
  940. _updateDetail(editIndex, detail);
  941. } else {
  942. _addDetail(detail);
  943. }
  944. }
  945. } finally {
  946. _addingDetail = false;
  947. }
  948. }
  949. void _showCurrencyPicker(String cur) {
  950. if (_currencies.isEmpty) {
  951. TDToast.showText(
  952. AppLocalizations.of(context).get('noData'),
  953. context: context,
  954. );
  955. return;
  956. }
  957. final l10n = AppLocalizations.of(context);
  958. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  959. final codes = _currencies.map((c) => c.curId).toList();
  960. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  961. FocusManager.instance.primaryFocus?.unfocus();
  962. TDPicker.showMultiPicker(
  963. context,
  964. title: l10n.get('selectCurrency'),
  965. backgroundColor: colors.bgCard,
  966. data: [labels],
  967. onConfirm: (s) {
  968. if (s.isNotEmpty && s[0] is int) {
  969. final i = s[0] as int;
  970. if (i >= 0 && i < codes.length) {
  971. Navigator.of(context).pop();
  972. _updateCurrencyCode(codes[i]);
  973. }
  974. }
  975. },
  976. );
  977. }
  978. void _showTextInput(
  979. String title,
  980. Function(String) onConfirm, {
  981. String initialText = '',
  982. }) {
  983. FocusScope.of(context).unfocus();
  984. FocusManager.instance.primaryFocus?.unfocus();
  985. final l10n = AppLocalizations.of(context);
  986. final c = TextEditingController(text: initialText);
  987. showGeneralDialog(
  988. context: context,
  989. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  990. textEditingController: c,
  991. title: title,
  992. hintText: l10n.get('pleaseEnter'),
  993. leftBtn: TDDialogButtonOptions(
  994. title: l10n.get('cancel'),
  995. action: () => Navigator.pop(ctx),
  996. ),
  997. rightBtn: TDDialogButtonOptions(
  998. title: l10n.get('confirm'),
  999. action: () {
  1000. onConfirm(c.text);
  1001. Navigator.pop(ctx);
  1002. },
  1003. ),
  1004. ),
  1005. );
  1006. }
  1007. Widget _label(String t, {bool required = false}) {
  1008. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1009. return Text.rich(
  1010. TextSpan(
  1011. children: [
  1012. TextSpan(
  1013. text: t,
  1014. style: TextStyle(
  1015. fontSize: AppFontSizes.subtitle,
  1016. color: colors.textSecondary,
  1017. ),
  1018. ),
  1019. if (required)
  1020. TextSpan(
  1021. text: ' *',
  1022. style: TextStyle(
  1023. fontSize: AppFontSizes.subtitle,
  1024. color: colors.danger,
  1025. ),
  1026. ),
  1027. ],
  1028. ),
  1029. );
  1030. }
  1031. Widget _buildBottomButtons(AppLocalizations l10n) {
  1032. return ActionBar(
  1033. showLeft: false,
  1034. showCenter: false,
  1035. rightLabel: l10n.get('submit'),
  1036. onRightTap: () async {
  1037. if (_isSubmitting) return;
  1038. final err = _validate(l10n);
  1039. if (err.isNotEmpty) {
  1040. TDToast.showText(err.first, context: context);
  1041. return;
  1042. }
  1043. FocusScope.of(context).unfocus();
  1044. _isSubmitting = true;
  1045. LoadingDialog.show(context, text: l10n.get('submitting'));
  1046. try {
  1047. final data = _buildSubmitData();
  1048. final api = ref.read(expenseApiProvider);
  1049. await api.submit(data);
  1050. if (mounted) {
  1051. LoadingDialog.hide(context);
  1052. TDToast.showSuccess(
  1053. l10n.get('submittedAwaitingApproval'),
  1054. context: context,
  1055. );
  1056. GoRouter.of(context).pop(true);
  1057. }
  1058. } catch (e) {
  1059. if (mounted) {
  1060. LoadingDialog.hide(context);
  1061. WidgetsBinding.instance.addPostFrameCallback((_) {
  1062. if (mounted) _showSubmitError(e, l10n);
  1063. });
  1064. }
  1065. } finally {
  1066. _isSubmitting = false;
  1067. }
  1068. },
  1069. );
  1070. }
  1071. void _showSubmitError(Object e, AppLocalizations l10n) {
  1072. final message = _extractErrorMessage(e) ?? l10n.get('submitFailedRetry');
  1073. showGeneralDialog(
  1074. context: context,
  1075. pageBuilder: (ctx, animation, secondaryAnimation) => TDConfirmDialog(
  1076. title: l10n.get('submitFailed'),
  1077. content: message,
  1078. buttonStyle: TDDialogButtonStyle.text,
  1079. ),
  1080. );
  1081. }
  1082. String? _extractErrorMessage(Object e) {
  1083. if (e is DioException) {
  1084. if (e.error is ApiException) return (e.error as ApiException).message;
  1085. if (e.error is NetworkException) {
  1086. return (e.error as NetworkException).message;
  1087. }
  1088. }
  1089. return null;
  1090. }
  1091. List<String> _validate(AppLocalizations l10n) {
  1092. final e = <String>[];
  1093. if (_purposeController.text.trim().isEmpty) {
  1094. e.add(l10n.get('enterExpenseReason'));
  1095. }
  1096. if (_expense!.details.isEmpty) {
  1097. e.add(l10n.get('addAtLeastOneDetail'));
  1098. }
  1099. return e;
  1100. }
  1101. bool _hasUnsaved() =>
  1102. _purposeController.text.isNotEmpty ||
  1103. (_expense?.paymentMethod.isNotEmpty ?? false) ||
  1104. (_expense?.currencyCode.isNotEmpty ?? false) ||
  1105. _remarkController.text.isNotEmpty ||
  1106. (_expense?.details.isNotEmpty ?? false);
  1107. void _doPop(AppLocalizations l10n) {
  1108. if (_hasUnsaved()) {
  1109. _showConfirmDialog(
  1110. l10n.get('confirmExit'),
  1111. l10n.get('unsavedContentWarning'),
  1112. l10n.get('continueEditing'),
  1113. l10n.get('discardAndExit'),
  1114. () {
  1115. if (!mounted) return;
  1116. _forcePop();
  1117. },
  1118. );
  1119. } else {
  1120. _forcePop();
  1121. }
  1122. }
  1123. void _forcePop() {
  1124. FocusManager.instance.primaryFocus?.unfocus();
  1125. final router = GoRouter.of(context);
  1126. if (router.canPop()) {
  1127. router.pop();
  1128. } else {
  1129. SystemNavigator.pop();
  1130. }
  1131. }
  1132. void _showConfirmDialog(
  1133. String title,
  1134. String content,
  1135. String leftText,
  1136. String rightText,
  1137. VoidCallback onConfirm,
  1138. ) {
  1139. FocusScope.of(context).unfocus();
  1140. FocusManager.instance.primaryFocus?.unfocus();
  1141. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1142. showDialog(
  1143. context: context,
  1144. useRootNavigator: true,
  1145. builder: (ctx) => TDAlertDialog(
  1146. title: title,
  1147. content: content,
  1148. buttonStyle: TDDialogButtonStyle.text,
  1149. leftBtn: TDDialogButtonOptions(
  1150. title: leftText,
  1151. titleColor: colors.primary,
  1152. action: () => Navigator.pop(ctx),
  1153. ),
  1154. rightBtn: TDDialogButtonOptions(
  1155. title: rightText,
  1156. titleColor: colors.danger,
  1157. action: () {
  1158. Navigator.pop(ctx);
  1159. onConfirm();
  1160. },
  1161. ),
  1162. ),
  1163. );
  1164. }
  1165. Widget _buildPageFooter() {
  1166. final l10n = AppLocalizations.of(context);
  1167. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1168. return Center(
  1169. child: Padding(
  1170. padding: const EdgeInsets.only(bottom: 16),
  1171. child: Row(
  1172. mainAxisSize: MainAxisSize.min,
  1173. children: [
  1174. Icon(
  1175. Icons.rocket_launch_outlined,
  1176. size: 16,
  1177. color: colors.textPlaceholder,
  1178. ),
  1179. const SizedBox(width: 6),
  1180. Text(
  1181. l10n.get('pageFooter'),
  1182. style: TextStyle(
  1183. fontSize: AppFontSizes.caption,
  1184. color: colors.textPlaceholder,
  1185. ),
  1186. ),
  1187. ],
  1188. ),
  1189. ),
  1190. );
  1191. }
  1192. String _today() {
  1193. final n = DateTime.now();
  1194. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1195. }
  1196. }