expense_edit_page.dart 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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 i = e.key;
  329. final d = e.value;
  330. return {
  331. 'ITM': i + 1,
  332. 'BX_DD': _today(),
  333. 'ACC_NO': d.acctSubjectId,
  334. 'AMT': d.totalAmount,
  335. 'AMTN': d.amount,
  336. 'AMTN_SH': d.approvedAmount,
  337. 'REM': d.remark,
  338. 'CUST': d.customerVendorId,
  339. 'IDX_NO': d.expenseCategory,
  340. 'OBJ_NO': d.projectId.isNotEmpty ? d.projectId : '',
  341. 'TAX': d.taxAmount,
  342. 'TAX_RTO': d.taxRate,
  343. 'DEP': d.costDeptId,
  344. 'AE_NO': d.aeNo,
  345. 'AE_DD': d.aeDd,
  346. 'BNK_NO': d.bankName,
  347. 'BNK_ID': d.bankAccount,
  348. 'ACCNAME': d.bankAccountName,
  349. 'SQ_MAN': d.sqMan.isNotEmpty ? d.sqMan : HostAppChannel.usr,
  350. 'EST_ITM': d.aeNo.isNotEmpty ? d.sortOrder : 0,
  351. };
  352. }).toList(),
  353. };
  354. }
  355. // ═══ Build ═══
  356. @override
  357. Widget build(BuildContext context) {
  358. final r = ResponsiveHelper.of(context);
  359. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  360. final l10n = AppLocalizations.of(context);
  361. final bottomInset = MediaQuery.of(context).padding.bottom;
  362. if (_loadingError != null) {
  363. return Center(
  364. child: Column(
  365. mainAxisSize: MainAxisSize.min,
  366. children: [
  367. Icon(Icons.error_outline, size: 48, color: colors.danger),
  368. const SizedBox(height: 16),
  369. Padding(
  370. padding: const EdgeInsets.symmetric(horizontal: 32),
  371. child: Text(
  372. _loadingError!,
  373. textAlign: TextAlign.center,
  374. style: TextStyle(
  375. fontSize: AppFontSizes.body,
  376. color: colors.textSecondary,
  377. ),
  378. ),
  379. ),
  380. const SizedBox(height: 16),
  381. TDButton(
  382. text: l10n.get('retry'),
  383. size: TDButtonSize.medium,
  384. onTap: () {
  385. setState(() {
  386. _loadingError = null;
  387. _firstBuild = true;
  388. _refDataLoading = true;
  389. });
  390. _loadData();
  391. },
  392. ),
  393. ],
  394. ),
  395. );
  396. }
  397. if (_firstBuild || _expense == null) {
  398. return const SkeletonFormPage(showImportLink: false);
  399. }
  400. Future.microtask(
  401. () => ref.read(pageBackProvider.notifier).state = () => _doPop(l10n),
  402. );
  403. Widget pageContent = PopScope(
  404. canPop: false,
  405. onPopInvokedWithResult: (didPop, _) {
  406. if (didPop) return;
  407. _doPop(l10n);
  408. },
  409. child: Column(
  410. children: [
  411. Expanded(
  412. child: Align(
  413. alignment: Alignment.topCenter,
  414. child: ConstrainedBox(
  415. constraints: BoxConstraints(maxWidth: r.formMaxWidth),
  416. child: SingleChildScrollView(
  417. controller: _scrollCtrl,
  418. padding: const EdgeInsets.all(16),
  419. child: Column(
  420. crossAxisAlignment: CrossAxisAlignment.start,
  421. children: [
  422. _buildBasicInfoSection(l10n, colors),
  423. const SizedBox(height: 16),
  424. Container(
  425. key: _detailsSectionKey,
  426. child: _buildDetailSection(l10n, colors),
  427. ),
  428. const SizedBox(height: 24),
  429. _buildPageFooter(),
  430. ],
  431. ),
  432. ),
  433. ),
  434. ),
  435. ),
  436. ColoredBox(
  437. color: colors.bgCard,
  438. child: Column(
  439. mainAxisSize: MainAxisSize.min,
  440. children: [
  441. _buildBottomButtons(l10n),
  442. if (bottomInset > 0) SizedBox(height: bottomInset),
  443. ],
  444. ),
  445. ),
  446. ],
  447. ),
  448. );
  449. return pageContent;
  450. }
  451. Widget _buildBasicInfoSection(
  452. AppLocalizations l10n,
  453. AppColorsExtension colors,
  454. ) {
  455. final expense = _expense!;
  456. return FormSection(
  457. title: l10n.get('basicInfo'),
  458. leadingIcon: Icons.info_outline,
  459. children: [
  460. FormFieldRow(
  461. label: l10n.get('expenseNo'),
  462. value: _billNo,
  463. readOnly: true,
  464. showArrow: false,
  465. ),
  466. const SizedBox(height: 16),
  467. FormFieldRow(
  468. label: l10n.get('date'),
  469. value: _expenseDate,
  470. readOnly: true,
  471. showArrow: false,
  472. ),
  473. const SizedBox(height: 16),
  474. FormFieldRow(
  475. label: l10n.get('expensePersonnel'),
  476. value: _selEmployee != null
  477. ? '${_selEmployee!.salNo}/${_selEmployee!.name}'
  478. : '',
  479. hint: l10n.get('pleaseSelect'),
  480. onTap: _employees.isNotEmpty ? _showEmployeePicker : null,
  481. ),
  482. const SizedBox(height: 16),
  483. FormFieldRow(
  484. label: l10n.get('expenseDept'),
  485. value: _selectedDeptName.isNotEmpty
  486. ? '$_selectedDeptId/$_selectedDeptName'
  487. : null,
  488. hint: l10n.get('pleaseSelect'),
  489. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  490. ),
  491. const SizedBox(height: 16),
  492. _label(l10n.get('expenseReason'), required: true),
  493. const SizedBox(height: 8),
  494. TDTextarea(
  495. controller: _purposeController,
  496. focusNode: _purposeFocus,
  497. hintText: l10n.get('enterExpenseReason'),
  498. maxLines: 4,
  499. minLines: 1,
  500. maxLength: 500,
  501. indicator: true,
  502. padding: EdgeInsets.zero,
  503. bordered: true,
  504. backgroundColor: colors.bgPage,
  505. onChanged: (_) => _updatePurpose(_purposeController.text),
  506. ),
  507. const SizedBox(height: 16),
  508. FormFieldRow(
  509. label: l10n.get('paymentMethod'),
  510. value: expense.paymentMethod,
  511. hint: l10n.get('pleaseEnter'),
  512. onTap: () => _showTextInput(
  513. l10n.get('paymentMethod'),
  514. (v) => _updatePaymentMethod(v),
  515. initialText: expense.paymentMethod,
  516. ),
  517. onClear: () => _updatePaymentMethod(''),
  518. ),
  519. const SizedBox(height: 16),
  520. FormFieldRow(
  521. label: l10n.get('currency'),
  522. value: expense.currencyCode.isNotEmpty
  523. ? _currencyLabel(expense.currencyCode)
  524. : null,
  525. hint: l10n.get('selectCurrency'),
  526. onTap: () => _showCurrencyPicker(expense.currencyCode),
  527. onClear: () => _updateCurrencyCode(''),
  528. ),
  529. const SizedBox(height: 16),
  530. Row(
  531. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  532. children: [
  533. Text(
  534. l10n.get('generateVoucher'),
  535. style: TextStyle(
  536. fontSize: AppFontSizes.subtitle,
  537. color: colors.textSecondary,
  538. ),
  539. ),
  540. TDSwitch(
  541. isOn: expense.isGenerateVoucher,
  542. onChanged: (v) {
  543. _setGenerateVoucher(v);
  544. return v;
  545. },
  546. ),
  547. ],
  548. ),
  549. const SizedBox(height: 16),
  550. _label(l10n.get('remark')),
  551. const SizedBox(height: 8),
  552. TDTextarea(
  553. controller: _remarkController,
  554. focusNode: _remarkFocus,
  555. hintText: l10n.get('enterRemark'),
  556. maxLines: 3,
  557. minLines: 1,
  558. maxLength: 500,
  559. indicator: true,
  560. padding: EdgeInsets.zero,
  561. bordered: true,
  562. backgroundColor: colors.bgPage,
  563. onChanged: (_) => _updateRemark(_remarkController.text),
  564. ),
  565. ],
  566. );
  567. }
  568. Widget _buildDetailSection(AppLocalizations l10n, AppColorsExtension colors) {
  569. final expense = _expense!;
  570. final totalApproved = expense.details.fold<double>(
  571. 0,
  572. (sum, d) => sum + d.approvedAmount,
  573. );
  574. return FormSection(
  575. title: l10n.get('expenseDetails'),
  576. leadingIcon: Icons.receipt_long_outlined,
  577. showAction: true,
  578. actionText: l10n.get('add'),
  579. onActionTap: () => _showAddDetailDialog(),
  580. children: [
  581. if (expense.details.isEmpty)
  582. Padding(
  583. padding: const EdgeInsets.symmetric(vertical: 8),
  584. child: Text(
  585. l10n.get('noDetailHint'),
  586. style: TextStyle(
  587. fontSize: AppFontSizes.subtitle,
  588. color: colors.textPlaceholder,
  589. ),
  590. ),
  591. )
  592. else
  593. ...expense.details.asMap().entries.map((entry) {
  594. final d = entry.value;
  595. return GestureDetector(
  596. onTap: () => _showAddDetailDialog(editIndex: entry.key),
  597. child: Container(
  598. margin: const EdgeInsets.symmetric(vertical: 6),
  599. padding: const EdgeInsets.all(12),
  600. decoration: BoxDecoration(
  601. color: colors.bgPage,
  602. borderRadius: BorderRadius.circular(8),
  603. ),
  604. child: Row(
  605. children: [
  606. Expanded(
  607. child: Column(
  608. crossAxisAlignment: CrossAxisAlignment.start,
  609. children: [
  610. Row(
  611. children: [
  612. Expanded(
  613. child: Text(
  614. d.categoryName.isNotEmpty
  615. ? '${d.expenseCategory}/${d.categoryName}'
  616. : d.expenseCategory,
  617. style: TextStyle(
  618. fontSize: AppFontSizes.body,
  619. fontWeight: FontWeight.w500,
  620. color: colors.textPrimary,
  621. ),
  622. ),
  623. ),
  624. Column(
  625. crossAxisAlignment: CrossAxisAlignment.end,
  626. children: [
  627. Text(
  628. '¥${d.totalAmount.toStringAsFixed(2)}',
  629. style: TextStyle(
  630. fontSize: AppFontSizes.body,
  631. fontWeight: FontWeight.w600,
  632. color: colors.amountPrimary,
  633. ),
  634. ),
  635. if (d.approvedAmount > 0)
  636. Text(
  637. '¥${d.approvedAmount.toStringAsFixed(2)}',
  638. style: TextStyle(
  639. fontSize: AppFontSizes.body,
  640. fontWeight: FontWeight.w600,
  641. color: colors.success,
  642. ),
  643. ),
  644. ],
  645. ),
  646. ],
  647. ),
  648. const SizedBox(height: 2),
  649. Text(
  650. '${l10n.get('amountExcludingTax')}: ¥${d.amount.toStringAsFixed(2)}',
  651. style: TextStyle(
  652. fontSize: AppFontSizes.caption,
  653. color: colors.textSecondary,
  654. ),
  655. ),
  656. if (d.taxAmount > 0)
  657. Text(
  658. '${l10n.get('taxAmount')}: ¥${d.taxAmount.toStringAsFixed(2)}',
  659. style: TextStyle(
  660. fontSize: AppFontSizes.caption,
  661. color: colors.textSecondary,
  662. ),
  663. ),
  664. if (d.taxRate > 0)
  665. Text(
  666. '${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  667. style: TextStyle(
  668. fontSize: AppFontSizes.caption,
  669. color: colors.textSecondary,
  670. ),
  671. ),
  672. if (d.acctSubjectName.isNotEmpty)
  673. Text(
  674. '${l10n.get('acctSubject')}: ${d.acctSubjectId}/${d.acctSubjectName}',
  675. maxLines: 1,
  676. overflow: TextOverflow.ellipsis,
  677. style: TextStyle(
  678. fontSize: AppFontSizes.caption,
  679. color: colors.textSecondary,
  680. ),
  681. ),
  682. if (d.aeNo.isNotEmpty)
  683. Text(
  684. '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  685. maxLines: 1,
  686. overflow: TextOverflow.ellipsis,
  687. style: TextStyle(
  688. fontSize: AppFontSizes.caption,
  689. color: colors.textSecondary,
  690. ),
  691. ),
  692. if (d.aeDd.isNotEmpty)
  693. Text(
  694. '${l10n.get('applyDate')}: ${d.aeDd.length >= 10 ? d.aeDd.substring(0, 10) : d.aeDd}',
  695. style: TextStyle(
  696. fontSize: AppFontSizes.caption,
  697. color: colors.textSecondary,
  698. ),
  699. ),
  700. if (d.projectName.isNotEmpty)
  701. Text(
  702. '${l10n.get('project')}: ${d.projectId}/${d.projectName}',
  703. maxLines: 1,
  704. overflow: TextOverflow.ellipsis,
  705. style: TextStyle(
  706. fontSize: AppFontSizes.caption,
  707. color: colors.textSecondary,
  708. ),
  709. ),
  710. if (d.costDeptName.isNotEmpty)
  711. Text(
  712. '${l10n.get('costDept')}: ${d.costDeptId}/${d.costDeptName}',
  713. maxLines: 1,
  714. overflow: TextOverflow.ellipsis,
  715. style: TextStyle(
  716. fontSize: AppFontSizes.caption,
  717. color: colors.textSecondary,
  718. ),
  719. ),
  720. if (d.customerVendorName.isNotEmpty)
  721. Text(
  722. '${l10n.get('customerVendor')}: ${d.customerVendorId}/${d.customerVendorName}',
  723. maxLines: 1,
  724. overflow: TextOverflow.ellipsis,
  725. style: TextStyle(
  726. fontSize: AppFontSizes.caption,
  727. color: colors.textSecondary,
  728. ),
  729. ),
  730. if (d.sqManName.isNotEmpty)
  731. Text(
  732. '${l10n.get('applicant')}: ${d.sqMan}/${d.sqManName}',
  733. style: TextStyle(
  734. fontSize: AppFontSizes.caption,
  735. color: colors.textSecondary,
  736. ),
  737. ),
  738. if (d.bankAccountName.isNotEmpty)
  739. Text(
  740. '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  741. maxLines: 1,
  742. overflow: TextOverflow.ellipsis,
  743. style: TextStyle(
  744. fontSize: AppFontSizes.caption,
  745. color: colors.textSecondary,
  746. ),
  747. ),
  748. if (d.bankName.isNotEmpty)
  749. Text(
  750. '${l10n.get('bankName')}: ${d.bankName}',
  751. maxLines: 1,
  752. overflow: TextOverflow.ellipsis,
  753. style: TextStyle(
  754. fontSize: AppFontSizes.caption,
  755. color: colors.textSecondary,
  756. ),
  757. ),
  758. if (d.bankAccount.isNotEmpty)
  759. Text(
  760. '${l10n.get('bankAccount')}: ${d.bankAccount}',
  761. maxLines: 1,
  762. overflow: TextOverflow.ellipsis,
  763. style: TextStyle(
  764. fontSize: AppFontSizes.caption,
  765. color: colors.textSecondary,
  766. ),
  767. ),
  768. if (d.remark.isNotEmpty)
  769. Text(
  770. '${l10n.get('remark')}: ${d.remark}',
  771. maxLines: 2,
  772. overflow: TextOverflow.ellipsis,
  773. style: TextStyle(
  774. fontSize: AppFontSizes.caption,
  775. color: colors.textSecondary,
  776. ),
  777. ),
  778. ],
  779. ),
  780. ),
  781. const SizedBox(width: 8),
  782. GestureDetector(
  783. onTap: () => _removeDetail(entry.key),
  784. child: Icon(
  785. Icons.close,
  786. size: 18,
  787. color: colors.textSecondary,
  788. ),
  789. ),
  790. ],
  791. ),
  792. ),
  793. );
  794. }),
  795. const SizedBox(height: 8),
  796. Row(
  797. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  798. children: [
  799. Text(
  800. l10n.get('totalExpense'),
  801. style: TextStyle(
  802. fontSize: AppFontSizes.body,
  803. fontWeight: FontWeight.w600,
  804. color: colors.textPrimary,
  805. ),
  806. ),
  807. Text(
  808. '¥${expense.totalAmount.toStringAsFixed(2)}',
  809. style: TextStyle(
  810. fontSize: AppFontSizes.subtitle,
  811. fontWeight: FontWeight.w700,
  812. color: colors.amountPrimary,
  813. ),
  814. ),
  815. ],
  816. ),
  817. const SizedBox(height: 4),
  818. Row(
  819. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  820. children: [
  821. Text(
  822. l10n.get('approvedTotal'),
  823. style: TextStyle(
  824. fontSize: AppFontSizes.body,
  825. fontWeight: FontWeight.w600,
  826. color: colors.textPrimary,
  827. ),
  828. ),
  829. Text(
  830. '¥${totalApproved.toStringAsFixed(2)}',
  831. style: TextStyle(
  832. fontSize: AppFontSizes.subtitle,
  833. fontWeight: FontWeight.w700,
  834. color: totalApproved > 0 ? colors.success : colors.textPrimary,
  835. ),
  836. ),
  837. ],
  838. ),
  839. ],
  840. );
  841. }
  842. Future<void> _showAddDetailDialog({int? editIndex}) async {
  843. if (_addingDetail) return;
  844. _addingDetail = true;
  845. try {
  846. final l10n = AppLocalizations.of(context);
  847. if (_costTypes.isEmpty) {
  848. TDToast.showText(l10n.get('noCostTypeData'), context: context);
  849. return;
  850. }
  851. final expense = _expense!;
  852. ExpenseDetailInputData? initialData;
  853. if (editIndex != null) {
  854. final d = expense.details[editIndex];
  855. initialData = ExpenseDetailInputData(
  856. category: d.expenseCategory,
  857. categoryName: d.categoryName,
  858. acctSubjectId: d.acctSubjectId,
  859. acctSubjectName: d.acctSubjectName,
  860. purpose: d.purpose,
  861. amount: d.totalAmount,
  862. taxRate: d.taxRate,
  863. projectId: d.projectId,
  864. projectName: d.projectName,
  865. costDeptId: d.costDeptId,
  866. costDeptName: d.costDeptName,
  867. customerVendorId: d.customerVendorId,
  868. customerVendorName: d.customerVendorName,
  869. approvedAmount: d.approvedAmount,
  870. bankName: d.bankName,
  871. bankAccountName: d.bankAccountName,
  872. bankAccount: d.bankAccount,
  873. remark: d.remark,
  874. attachmentPaths: d.attachments,
  875. sqMan: d.sqMan,
  876. sqManName: d.sqManName,
  877. aeNo: d.aeNo,
  878. aeDd: d.aeDd,
  879. );
  880. }
  881. FocusManager.instance.primaryFocus?.unfocus();
  882. final result = await ExpenseDetailDialog.show(
  883. context,
  884. categories: _dialogCategories,
  885. projects: _dialogProjects,
  886. costDepts: _dialogCostDepts,
  887. customers: _dialogCustomers,
  888. employees: _dialogEmployees,
  889. l10n: l10n,
  890. initialData: initialData,
  891. checkAttachHealth: () =>
  892. ref.read(expenseApiProvider).checkAttachHealth(),
  893. );
  894. if (result != null && mounted) {
  895. final now = DateTime.now();
  896. final detail = ExpenseDetailModel(
  897. id: editIndex != null
  898. ? expense.details[editIndex].id
  899. : now.millisecondsSinceEpoch.toString(),
  900. expenseId: '',
  901. expenseCategory: result.category,
  902. categoryName: result.categoryName,
  903. purpose: result.purpose,
  904. amount: result.taxRate > 0
  905. ? result.amount / (1 + result.taxRate / 100)
  906. : result.amount,
  907. taxRate: result.taxRate,
  908. taxAmount: result.taxRate > 0
  909. ? result.amount - result.amount / (1 + result.taxRate / 100)
  910. : 0,
  911. totalAmount: result.amount,
  912. projectId: result.projectId,
  913. projectName: result.projectName,
  914. costDeptId: result.costDeptId,
  915. costDeptName: result.costDeptName,
  916. acctSubjectId: result.acctSubjectId,
  917. acctSubjectName: result.acctSubjectName,
  918. customerVendorId: result.customerVendorId,
  919. customerVendorName: result.customerVendorName,
  920. approvedAmount: result.approvedAmount,
  921. bankName: result.bankName,
  922. bankAccountName: result.bankAccountName,
  923. bankAccount: result.bankAccount,
  924. sqMan: result.sqMan,
  925. sqManName: result.sqManName,
  926. aeNo: result.aeNo,
  927. aeDd: result.aeDd,
  928. remark: result.remark,
  929. attachments: result.attachmentPaths,
  930. createTime: now,
  931. updateTime: now,
  932. );
  933. if (editIndex != null) {
  934. _updateDetail(editIndex, detail);
  935. } else {
  936. _addDetail(detail);
  937. }
  938. }
  939. } finally {
  940. _addingDetail = false;
  941. }
  942. }
  943. void _showCurrencyPicker(String cur) {
  944. if (_currencies.isEmpty) {
  945. TDToast.showText(
  946. AppLocalizations.of(context).get('noData'),
  947. context: context,
  948. );
  949. return;
  950. }
  951. final l10n = AppLocalizations.of(context);
  952. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  953. final codes = _currencies.map((c) => c.curId).toList();
  954. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  955. FocusManager.instance.primaryFocus?.unfocus();
  956. TDPicker.showMultiPicker(
  957. context,
  958. title: l10n.get('selectCurrency'),
  959. backgroundColor: colors.bgCard,
  960. data: [labels],
  961. onConfirm: (s) {
  962. if (s.isNotEmpty && s[0] is int) {
  963. final i = s[0] as int;
  964. if (i >= 0 && i < codes.length) {
  965. Navigator.of(context).pop();
  966. _updateCurrencyCode(codes[i]);
  967. }
  968. }
  969. },
  970. );
  971. }
  972. void _showTextInput(
  973. String title,
  974. Function(String) onConfirm, {
  975. String initialText = '',
  976. }) {
  977. FocusScope.of(context).unfocus();
  978. FocusManager.instance.primaryFocus?.unfocus();
  979. final l10n = AppLocalizations.of(context);
  980. final c = TextEditingController(text: initialText);
  981. showGeneralDialog(
  982. context: context,
  983. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  984. textEditingController: c,
  985. title: title,
  986. hintText: l10n.get('pleaseEnter'),
  987. leftBtn: TDDialogButtonOptions(
  988. title: l10n.get('cancel'),
  989. action: () => Navigator.pop(ctx),
  990. ),
  991. rightBtn: TDDialogButtonOptions(
  992. title: l10n.get('confirm'),
  993. action: () {
  994. onConfirm(c.text);
  995. Navigator.pop(ctx);
  996. },
  997. ),
  998. ),
  999. );
  1000. }
  1001. Widget _label(String t, {bool required = false}) {
  1002. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1003. return Text.rich(
  1004. TextSpan(
  1005. children: [
  1006. TextSpan(
  1007. text: t,
  1008. style: TextStyle(
  1009. fontSize: AppFontSizes.subtitle,
  1010. color: colors.textSecondary,
  1011. ),
  1012. ),
  1013. if (required)
  1014. TextSpan(
  1015. text: ' *',
  1016. style: TextStyle(
  1017. fontSize: AppFontSizes.subtitle,
  1018. color: colors.danger,
  1019. ),
  1020. ),
  1021. ],
  1022. ),
  1023. );
  1024. }
  1025. Widget _buildBottomButtons(AppLocalizations l10n) {
  1026. return ActionBar(
  1027. showLeft: false,
  1028. showCenter: false,
  1029. rightLabel: l10n.get('submit'),
  1030. onRightTap: () async {
  1031. if (_isSubmitting) return;
  1032. final err = _validate(l10n);
  1033. if (err.isNotEmpty) {
  1034. TDToast.showText(err.first, context: context);
  1035. return;
  1036. }
  1037. FocusScope.of(context).unfocus();
  1038. _isSubmitting = true;
  1039. LoadingDialog.show(context, text: l10n.get('submitting'));
  1040. try {
  1041. final data = _buildSubmitData();
  1042. final api = ref.read(expenseApiProvider);
  1043. await api.submit(data);
  1044. if (mounted) {
  1045. LoadingDialog.hide(context);
  1046. TDToast.showSuccess(
  1047. l10n.get('submittedAwaitingApproval'),
  1048. context: context,
  1049. );
  1050. GoRouter.of(context).pop(true);
  1051. }
  1052. } catch (e) {
  1053. if (mounted) {
  1054. LoadingDialog.hide(context);
  1055. WidgetsBinding.instance.addPostFrameCallback((_) {
  1056. if (mounted) _showSubmitError(e, l10n);
  1057. });
  1058. }
  1059. } finally {
  1060. _isSubmitting = false;
  1061. }
  1062. },
  1063. );
  1064. }
  1065. void _showSubmitError(Object e, AppLocalizations l10n) {
  1066. final message = _extractErrorMessage(e) ?? l10n.get('submitFailedRetry');
  1067. showGeneralDialog(
  1068. context: context,
  1069. pageBuilder: (ctx, animation, secondaryAnimation) => TDConfirmDialog(
  1070. title: l10n.get('submitFailed'),
  1071. content: message,
  1072. buttonStyle: TDDialogButtonStyle.text,
  1073. ),
  1074. );
  1075. }
  1076. String? _extractErrorMessage(Object e) {
  1077. if (e is DioException) {
  1078. if (e.error is ApiException) return (e.error as ApiException).message;
  1079. if (e.error is NetworkException) {
  1080. return (e.error as NetworkException).message;
  1081. }
  1082. }
  1083. return null;
  1084. }
  1085. List<String> _validate(AppLocalizations l10n) {
  1086. final e = <String>[];
  1087. if (_purposeController.text.trim().isEmpty) {
  1088. e.add(l10n.get('enterExpenseReason'));
  1089. }
  1090. if (_expense!.details.isEmpty) {
  1091. e.add(l10n.get('addAtLeastOneDetail'));
  1092. }
  1093. return e;
  1094. }
  1095. bool _hasUnsaved() =>
  1096. _purposeController.text.isNotEmpty ||
  1097. (_expense?.paymentMethod.isNotEmpty ?? false) ||
  1098. (_expense?.currencyCode.isNotEmpty ?? false) ||
  1099. _remarkController.text.isNotEmpty ||
  1100. (_expense?.details.isNotEmpty ?? false);
  1101. void _doPop(AppLocalizations l10n) {
  1102. if (_hasUnsaved()) {
  1103. _showConfirmDialog(
  1104. l10n.get('confirmExit'),
  1105. l10n.get('unsavedContentWarning'),
  1106. l10n.get('continueEditing'),
  1107. l10n.get('discardAndExit'),
  1108. () {
  1109. if (!mounted) return;
  1110. _forcePop();
  1111. },
  1112. );
  1113. } else {
  1114. _forcePop();
  1115. }
  1116. }
  1117. void _forcePop() {
  1118. FocusManager.instance.primaryFocus?.unfocus();
  1119. final router = GoRouter.of(context);
  1120. if (router.canPop()) {
  1121. router.pop();
  1122. } else {
  1123. SystemNavigator.pop();
  1124. }
  1125. }
  1126. void _showConfirmDialog(
  1127. String title,
  1128. String content,
  1129. String leftText,
  1130. String rightText,
  1131. VoidCallback onConfirm,
  1132. ) {
  1133. FocusScope.of(context).unfocus();
  1134. FocusManager.instance.primaryFocus?.unfocus();
  1135. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1136. showDialog(
  1137. context: context,
  1138. useRootNavigator: true,
  1139. builder: (ctx) => TDAlertDialog(
  1140. title: title,
  1141. content: content,
  1142. buttonStyle: TDDialogButtonStyle.text,
  1143. leftBtn: TDDialogButtonOptions(
  1144. title: leftText,
  1145. titleColor: colors.primary,
  1146. action: () => Navigator.pop(ctx),
  1147. ),
  1148. rightBtn: TDDialogButtonOptions(
  1149. title: rightText,
  1150. titleColor: colors.danger,
  1151. action: () {
  1152. Navigator.pop(ctx);
  1153. onConfirm();
  1154. },
  1155. ),
  1156. ),
  1157. );
  1158. }
  1159. Widget _buildPageFooter() {
  1160. final l10n = AppLocalizations.of(context);
  1161. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1162. return Center(
  1163. child: Padding(
  1164. padding: const EdgeInsets.only(bottom: 16),
  1165. child: Row(
  1166. mainAxisSize: MainAxisSize.min,
  1167. children: [
  1168. Icon(
  1169. Icons.rocket_launch_outlined,
  1170. size: 16,
  1171. color: colors.textPlaceholder,
  1172. ),
  1173. const SizedBox(width: 6),
  1174. Text(
  1175. l10n.get('pageFooter'),
  1176. style: TextStyle(
  1177. fontSize: AppFontSizes.caption,
  1178. color: colors.textPlaceholder,
  1179. ),
  1180. ),
  1181. ],
  1182. ),
  1183. ),
  1184. );
  1185. }
  1186. String _today() {
  1187. final n = DateTime.now();
  1188. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1189. }
  1190. }