expense_create_page.dart 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter/services.dart';
  5. import 'package:flutter_riverpod/flutter_riverpod.dart';
  6. import 'package:tdesign_flutter/tdesign_flutter.dart';
  7. import 'package:dio/dio.dart';
  8. import 'package:go_router/go_router.dart';
  9. import '../../core/network/api_exception.dart';
  10. import '../../core/utils/responsive.dart';
  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 'expense_api.dart';
  16. import 'expense_create_controller.dart';
  17. import '../../core/i18n/app_localizations.dart';
  18. import 'expense_model.dart';
  19. import '../../core/theme/app_colors.dart';
  20. import '../../core/theme/app_colors_extension.dart';
  21. import '../../core/navigation/host_app_channel.dart';
  22. import '../../core/data/mock_api_data.dart';
  23. import 'widgets/expense_detail_dialog.dart';
  24. import '../../shared/widgets/action_bar.dart';
  25. import '../../shared/widgets/loading_dialog.dart';
  26. import '../../shared/widgets/attachment_picker.dart';
  27. import 'expense_apply_import_page.dart';
  28. class ExpenseCreatePage extends ConsumerStatefulWidget {
  29. final String? editId;
  30. const ExpenseCreatePage({super.key, this.editId});
  31. @override
  32. ConsumerState<ExpenseCreatePage> createState() => _ExpenseCreatePageState();
  33. }
  34. class _ExpenseCreatePageState extends ConsumerState<ExpenseCreatePage> {
  35. final _purposeController = TextEditingController();
  36. final _purposeFocus = FocusNode();
  37. final _remarkController = TextEditingController();
  38. final _remarkFocus = FocusNode();
  39. final _scrollCtrl = ScrollController();
  40. final _detailsSectionKey = GlobalKey();
  41. late final AttachmentPickerController _attachmentController;
  42. bool _attachAvailable = false;
  43. late Future<bool> _draftFuture;
  44. bool _draftHandled = false;
  45. // ── 参考数据(从 API 加载) ──
  46. List<CostTypeItem> _costTypes = [];
  47. List<ProjectCodeItem> _projects = [];
  48. List<DepartmentItem> _departments = [];
  49. List<CustomerItem> _customers = [];
  50. List<CurrencyItem> _currencies = [];
  51. List<EmployeeItem> _employees = [];
  52. EmployeeItem? _selEmployee;
  53. bool _firstBuild = true;
  54. bool _refDataLoading = true;
  55. bool _addingDetail = false;
  56. // ── 已导入申请单号集合,用于申请事由去重拼接 ──
  57. final _importedAeNos = <String>{};
  58. // ── 报销部门 ──
  59. String _selectedDeptId = '';
  60. String _selectedDeptName = '';
  61. @override
  62. void initState() {
  63. super.initState();
  64. SystemChrome.setSystemUIOverlayStyle(
  65. const SystemUiOverlayStyle(
  66. statusBarColor: Colors.transparent,
  67. statusBarIconBrightness: Brightness.dark,
  68. ),
  69. );
  70. _attachmentController = AttachmentPickerController(maxCount: 9)
  71. ..addListener(() => setState(() {}));
  72. _checkAttachHealth();
  73. _purposeFocus.addListener(() => _ensureVisible(_purposeFocus));
  74. _remarkFocus.addListener(() => _ensureVisible(_remarkFocus));
  75. _costTypes = [];
  76. _projects = [];
  77. _departments = [];
  78. _customers = [];
  79. _employees = [];
  80. _refDataLoading = true;
  81. _refDataFuture = null;
  82. _draftFuture = widget.editId == null
  83. ? ExpenseCreateController.hasDraft()
  84. : Future.value(false);
  85. _loadRefData();
  86. WidgetsBinding.instance.addPostFrameCallback((_) => _checkDataReady());
  87. }
  88. void _checkDataReady() {
  89. if (!_refDataLoading && mounted) {
  90. setState(() => _firstBuild = false);
  91. WidgetsBinding.instance.addPostFrameCallback((_) {
  92. if (mounted) setState(() {});
  93. });
  94. } else if (mounted) {
  95. WidgetsBinding.instance.addPostFrameCallback((_) => _checkDataReady());
  96. }
  97. }
  98. Future<void>? _refDataFuture;
  99. Future<void> _loadRefData() async {
  100. if (_refDataFuture != null) return _refDataFuture!;
  101. final completer = Completer<void>();
  102. _refDataFuture = completer.future;
  103. try {
  104. final api = ref.read(expenseApiProvider);
  105. final results = await Future.wait([
  106. api.getCostTypes(),
  107. api.getProjectCodes(),
  108. api.getDepartments(),
  109. api.getCustomers(),
  110. api.getCurrencies(),
  111. api.getEmployees(),
  112. ]);
  113. if (!mounted) {
  114. completer.complete();
  115. return;
  116. }
  117. setState(() {
  118. _costTypes = results[0] as List<CostTypeItem>;
  119. _projects = results[1] as List<ProjectCodeItem>;
  120. _departments = results[2] as List<DepartmentItem>;
  121. _customers = results[3] as List<CustomerItem>;
  122. _currencies = results[4] as List<CurrencyItem>;
  123. _employees = results[5] as List<EmployeeItem>;
  124. _refDataLoading = false;
  125. _autoSelectDept();
  126. _autoSelectEmployee();
  127. });
  128. completer.complete();
  129. } catch (_) {
  130. if (!mounted) {
  131. completer.complete();
  132. return;
  133. }
  134. setState(() => _refDataLoading = false);
  135. completer.complete();
  136. } finally {
  137. _refDataFuture = null;
  138. }
  139. }
  140. void _scrollToDetailSection() {
  141. WidgetsBinding.instance.addPostFrameCallback((_) {
  142. if (_scrollCtrl.hasClients && _detailsSectionKey.currentContext != null) {
  143. Scrollable.ensureVisible(
  144. _detailsSectionKey.currentContext!,
  145. alignment: 0.0,
  146. duration: const Duration(milliseconds: 300),
  147. );
  148. }
  149. });
  150. }
  151. void _ensureVisible(FocusNode node) {
  152. if (!node.hasFocus) return;
  153. WidgetsBinding.instance.addPostFrameCallback((_) {
  154. if (node.hasFocus && _scrollCtrl.hasClients) {
  155. final ctx = node.context;
  156. if (ctx != null) {
  157. Scrollable.ensureVisible(
  158. ctx,
  159. alignment: 0.3,
  160. duration: const Duration(milliseconds: 300),
  161. );
  162. }
  163. }
  164. });
  165. }
  166. @override
  167. void dispose() {
  168. _purposeController.dispose();
  169. _purposeFocus.dispose();
  170. _remarkController.dispose();
  171. _remarkFocus.dispose();
  172. _scrollCtrl.dispose();
  173. _attachmentController.dispose();
  174. super.dispose();
  175. }
  176. @override
  177. Widget build(BuildContext context) {
  178. final controller = ref.watch(expenseCreateProvider(widget.editId).notifier);
  179. final state = ref.watch(expenseCreateProvider(widget.editId));
  180. final r = ResponsiveHelper.of(context);
  181. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  182. final bottomInset = MediaQuery.of(context).padding.bottom;
  183. if (_firstBuild) return const SkeletonFormPage(showImportLink: true);
  184. Future.microtask(
  185. () => ref.read(pageBackProvider.notifier).state = () => _doPop(),
  186. );
  187. Widget pageContent = PopScope(
  188. canPop: false,
  189. onPopInvokedWithResult: (didPop, _) {
  190. if (didPop) return;
  191. _doPop();
  192. },
  193. child: Column(
  194. children: [
  195. Expanded(
  196. child: Align(
  197. alignment: Alignment.topCenter,
  198. child: ConstrainedBox(
  199. constraints: BoxConstraints(maxWidth: r.formMaxWidth),
  200. child: SingleChildScrollView(
  201. controller: _scrollCtrl,
  202. padding: const EdgeInsets.all(16),
  203. child: Column(
  204. crossAxisAlignment: CrossAxisAlignment.start,
  205. children: [
  206. _buildImportLink(),
  207. const SizedBox(height: 16),
  208. _buildBasicInfoSection(controller, state),
  209. const SizedBox(height: 16),
  210. Container(
  211. key: _detailsSectionKey,
  212. child: _buildDetailSection(controller, state),
  213. ),
  214. const SizedBox(height: 16),
  215. _buildAttachmentSection(controller, state),
  216. const SizedBox(height: 24),
  217. _buildPageFooter(),
  218. ],
  219. ),
  220. ),
  221. ),
  222. ),
  223. ),
  224. ColoredBox(
  225. color: colors.bgCard,
  226. child: Column(
  227. mainAxisSize: MainAxisSize.min,
  228. children: [
  229. _buildBottomButtons(controller, state),
  230. if (bottomInset > 0) SizedBox(height: bottomInset),
  231. ],
  232. ),
  233. ),
  234. ],
  235. ),
  236. );
  237. return FutureBuilder<bool>(
  238. future: _draftFuture,
  239. builder: (ctx, snapshot) {
  240. final hasDraft = snapshot.hasData && snapshot.data == true;
  241. if (hasDraft && !_draftHandled) {
  242. _draftHandled = true;
  243. WidgetsBinding.instance.addPostFrameCallback((_) {
  244. if (mounted) _showDraftDialog();
  245. });
  246. }
  247. return pageContent;
  248. },
  249. );
  250. }
  251. void _showDraftDialog() {
  252. final l10n = AppLocalizations.of(context);
  253. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  254. FocusManager.instance.primaryFocus?.unfocus();
  255. showDialog(
  256. context: context,
  257. barrierDismissible: false,
  258. builder: (ctx) => TDAlertDialog(
  259. title: l10n.get('draftFound'),
  260. content: l10n.get('draftRestorePrompt'),
  261. leftBtn: TDDialogButtonOptions(
  262. title: l10n.get('discard'),
  263. titleColor: colors.textSecondary,
  264. action: () {
  265. Navigator.pop(ctx);
  266. ExpenseCreateController.deleteDraft();
  267. },
  268. ),
  269. rightBtn: TDDialogButtonOptions(
  270. title: l10n.get('restore'),
  271. titleColor: colors.primary,
  272. action: () async {
  273. Navigator.pop(ctx);
  274. final draft = await ExpenseCreateController.loadDraft();
  275. if (draft != null && mounted) {
  276. final api = ref.read(expenseApiProvider);
  277. ref
  278. .read(expenseCreateProvider(widget.editId).notifier)
  279. .restoreFromDraft(draft, api);
  280. _purposeController.text = draft.purpose;
  281. _remarkController.text = draft.remark;
  282. if (draft.attachments.isNotEmpty) {
  283. await _attachmentController.restoreFromPaths(draft.attachments);
  284. }
  285. }
  286. },
  287. ),
  288. ),
  289. );
  290. }
  291. // ═══ API 数据 → 弹窗类型转换 ═══
  292. List<CostCategory> get _dialogCategories => _costTypes
  293. .map(
  294. (c) => CostCategory(
  295. code: c.typeNo,
  296. nameKey: c.typeName,
  297. acctSubjectId: c.accNo,
  298. acctSubjectName: c.accName,
  299. ),
  300. )
  301. .toList();
  302. List<Project> get _dialogProjects => _projects
  303. .map((p) => Project(id: int.tryParse(p.objNo) ?? 0, name: p.name))
  304. .toList();
  305. List<CostDept> get _dialogCostDepts =>
  306. _departments.map((d) => CostDept(id: d.dep, name: d.name)).toList();
  307. String _currencyLabel(String code) {
  308. final match = _currencies.where((c) => c.curId == code);
  309. return match.isNotEmpty ? '${match.first.curId}/${match.first.name}' : code;
  310. }
  311. List<CustomerVendor> get _dialogCustomers =>
  312. _customers.map((c) => CustomerVendor(id: c.cusNo, name: c.name)).toList();
  313. List<EmployeeItem> get _dialogEmployees => _employees;
  314. void _autoSelectDept() {
  315. if (_selectedDeptId.isNotEmpty) return;
  316. final dep = HostAppChannel.dep;
  317. if (dep.isEmpty) return;
  318. final match = _departments.where((d) => d.dep == dep);
  319. if (match.isNotEmpty) {
  320. _selectedDeptId = match.first.dep;
  321. _selectedDeptName = match.first.name;
  322. }
  323. }
  324. void _autoSelectEmployee() {
  325. if (_selEmployee != null) return;
  326. final usr = HostAppChannel.usr;
  327. if (usr.isEmpty || _employees.isEmpty) return;
  328. final match = _employees.where((e) => e.salNo == usr);
  329. if (match.isNotEmpty) {
  330. setState(() => _selEmployee = match.first);
  331. }
  332. }
  333. void _showEmployeePicker() {
  334. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  335. final labels = _employees.map((e) => '${e.salNo}/${e.name}').toList();
  336. TDPicker.showMultiPicker(
  337. context,
  338. title: AppLocalizations.of(context).get('expensePersonnel'),
  339. backgroundColor: colors.bgCard,
  340. data: [labels],
  341. onConfirm: (selected) {
  342. if (selected.isNotEmpty && selected[0] is int) {
  343. final idx = selected[0] as int;
  344. if (idx >= 0 && idx < labels.length) {
  345. Navigator.of(context).pop();
  346. setState(() => _selEmployee = _employees[idx]);
  347. }
  348. }
  349. },
  350. );
  351. }
  352. void _showDeptPicker() {
  353. if (_departments.isEmpty) {
  354. TDToast.showText(
  355. AppLocalizations.of(context).get('noData'),
  356. context: context,
  357. );
  358. return;
  359. }
  360. final l10n = AppLocalizations.of(context);
  361. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  362. final labels = _departments.map((d) => '${d.dep}/${d.name}').toList();
  363. FocusManager.instance.primaryFocus?.unfocus();
  364. TDPicker.showMultiPicker(
  365. context,
  366. title: l10n.get('expenseDept'),
  367. backgroundColor: colors.bgCard,
  368. data: [labels],
  369. onConfirm: (selected) {
  370. if (selected.isNotEmpty && selected[0] is int) {
  371. final idx = selected[0] as int;
  372. if (idx >= 0 && idx < labels.length) {
  373. Navigator.of(context).pop();
  374. setState(() {
  375. _selectedDeptId = _departments[idx].dep;
  376. _selectedDeptName = _departments[idx].name;
  377. });
  378. }
  379. }
  380. },
  381. );
  382. }
  383. Map<String, dynamic> _buildSubmitData(ExpenseCreateState state) {
  384. final expense = state.expense;
  385. return {
  386. 'HeadData': {
  387. 'BX_DD': _today(),
  388. 'DEP': _selectedDeptId,
  389. 'USR_NO': _selEmployee?.salNo ?? '',
  390. 'PAY_ID': expense.paymentMethod,
  391. //'PRT_SW': 'N',
  392. 'USR': HostAppChannel.usr,
  393. 'REM': expense.remark,
  394. 'CUR_ID': expense.currencyCode,
  395. 'EXC_RTO': 1,
  396. 'REASON': expense.purpose,
  397. 'VOH_ID': expense.isGenerateVoucher ? 'T' : 'F',
  398. },
  399. 'BodyData1': expense.details.asMap().entries.map((e) {
  400. final d = e.value;
  401. return {
  402. 'BX_DD': _today(),
  403. 'ACC_NO': d.acctSubjectId,
  404. 'AMT': d.totalAmount,
  405. 'AMTN': d.amount,
  406. 'AMTN_SH': d.approvedAmount,
  407. 'REM': d.remark,
  408. 'CUST': d.customerVendorId,
  409. 'IDX_NO': d.expenseCategory,
  410. 'OBJ_NO': d.projectId.isNotEmpty ? d.projectId : '',
  411. 'TAX': d.taxAmount,
  412. 'TAX_RTO': d.taxRate,
  413. 'DEP': d.costDeptId,
  414. 'AE_NO': d.aeNo,
  415. 'AE_DD': d.aeDd,
  416. 'BNK_NO': d.bankName,
  417. 'BNK_ID': d.bankAccount,
  418. 'ACCNAME': d.bankAccountName,
  419. 'SQ_MAN': d.sqMan.isNotEmpty ? d.sqMan : HostAppChannel.usr,
  420. 'EST_ITM': d.aeNo.isNotEmpty ? d.sortOrder : 0,
  421. };
  422. }).toList(),
  423. };
  424. }
  425. Widget _buildImportLink() {
  426. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  427. final l10n = AppLocalizations.of(context);
  428. return GestureDetector(
  429. onTap: () async {
  430. final result = await GoRouter.of(
  431. context,
  432. ).push<List<ImportableItem>>('/expense/import-apply');
  433. if (result == null || result.isEmpty || !mounted) return;
  434. // 将选中的导入数据转换为明细,先移除同单号的旧数据
  435. final controller = ref.read(
  436. expenseCreateProvider(widget.editId).notifier,
  437. );
  438. final aeNos = result.map((e) => e.aeNo).toSet();
  439. for (final aeNo in aeNos) {
  440. controller.removeDetailsByAeNo(aeNo);
  441. }
  442. // 拼接申请事由到报销单头 purpose(同张单多次转入只拼一次)
  443. final newReasons = <String>[];
  444. for (final aeNo in aeNos) {
  445. if (!_importedAeNos.contains(aeNo)) {
  446. final item = result.firstWhere((e) => e.aeNo == aeNo);
  447. if (item.reason.isNotEmpty) {
  448. newReasons.add(item.reason);
  449. _importedAeNos.add(aeNo);
  450. }
  451. }
  452. }
  453. if (newReasons.isNotEmpty) {
  454. final currentPurpose = controller.currentState.expense.purpose;
  455. final joined = newReasons.join(';');
  456. final newPurpose = currentPurpose.isNotEmpty
  457. ? '$currentPurpose;$joined'
  458. : joined;
  459. controller.updatePurpose(newPurpose);
  460. _purposeController.text = newPurpose;
  461. }
  462. final now = DateTime.now();
  463. for (final item in result) {
  464. controller.addDetail(
  465. ExpenseDetailModel(
  466. id: '${now.millisecondsSinceEpoch}_${item.itm}',
  467. expenseId: '',
  468. expenseApplyId: '',
  469. expenseApplyNo: item.aeNo,
  470. expenseApplyDate: item.aeDd.isNotEmpty
  471. ? DateTime.tryParse(item.aeDd)
  472. : null,
  473. expenseCategory: item.typeNo,
  474. categoryName: item.typeName,
  475. purpose: item.rem,
  476. priority: item.priority,
  477. projectId: item.objNo,
  478. projectName: item.objName,
  479. costDeptId: item.dep,
  480. costDeptName: item.depName,
  481. acctSubjectId: item.accNo,
  482. acctSubjectName: item.accName,
  483. amount: item.amtnYj,
  484. taxRate: 0,
  485. taxAmount: 0,
  486. totalAmount: item.amtnYj,
  487. currencyCode: '',
  488. exchangeRate: 1.0,
  489. baseAmount: item.amtnYj,
  490. approvedAmount: item.amtnYj,
  491. customerVendorId: '',
  492. customerVendorName: '',
  493. bankName: '',
  494. bankAccountName: '',
  495. bankAccount: '',
  496. remark: item.rem,
  497. sortOrder: item.preItm ?? item.itm,
  498. attachments: const [],
  499. sqMan: item.sqMan,
  500. sqManName: item.sqName,
  501. aeNo: item.aeNo,
  502. aeDd: item.aeDd,
  503. createTime: now,
  504. updateTime: now,
  505. ),
  506. );
  507. }
  508. controller.recalculateAmount();
  509. TDToast.showSuccess(l10n.get('importSuccess'), context: context);
  510. _scrollToDetailSection();
  511. },
  512. child: Container(
  513. height: 44,
  514. decoration: BoxDecoration(
  515. color: colors.primaryLight,
  516. borderRadius: BorderRadius.circular(8),
  517. ),
  518. child: Row(
  519. mainAxisAlignment: MainAxisAlignment.center,
  520. children: [
  521. Icon(Icons.download, size: 14, color: colors.primary),
  522. const SizedBox(width: 8),
  523. Text(
  524. l10n.get('importApprovedPreApp'),
  525. style: TextStyle(
  526. fontSize: AppFontSizes.body,
  527. color: colors.primary,
  528. ),
  529. ),
  530. ],
  531. ),
  532. ),
  533. );
  534. }
  535. Widget _buildBasicInfoSection(
  536. ExpenseCreateController controller,
  537. ExpenseCreateState state,
  538. ) {
  539. final l10n = AppLocalizations.of(context);
  540. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  541. final expense = state.expense;
  542. return FormSection(
  543. title: l10n.get('basicInfo'),
  544. leadingIcon: Icons.info_outline,
  545. children: [
  546. FormFieldRow(
  547. label: l10n.get('date'),
  548. value: _today(),
  549. readOnly: true,
  550. showArrow: false,
  551. ),
  552. const SizedBox(height: 16),
  553. FormFieldRow(
  554. label: l10n.get('expensePersonnel'),
  555. value: _selEmployee != null
  556. ? '${_selEmployee!.salNo}/${_selEmployee!.name}'
  557. : '',
  558. hint: l10n.get('pleaseSelect'),
  559. onTap: _employees.isNotEmpty ? _showEmployeePicker : null,
  560. ),
  561. const SizedBox(height: 16),
  562. FormFieldRow(
  563. label: l10n.get('expenseDept'),
  564. value: _selectedDeptName.isNotEmpty
  565. ? '$_selectedDeptId/$_selectedDeptName'
  566. : null,
  567. hint: l10n.get('pleaseSelect'),
  568. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  569. ),
  570. const SizedBox(height: 16),
  571. _label(l10n.get('expenseReason'), required: true),
  572. const SizedBox(height: 8),
  573. TDTextarea(
  574. controller: _purposeController,
  575. focusNode: _purposeFocus,
  576. hintText: l10n.get('enterExpenseReason'),
  577. maxLines: 4,
  578. minLines: 1,
  579. maxLength: 500,
  580. indicator: true,
  581. padding: EdgeInsets.zero,
  582. bordered: true,
  583. backgroundColor: colors.bgPage,
  584. onChanged: (_) => controller.updatePurpose(_purposeController.text),
  585. ),
  586. const SizedBox(height: 16),
  587. FormFieldRow(
  588. label: l10n.get('paymentMethod'),
  589. value: expense.paymentMethod,
  590. hint: l10n.get('pleaseEnter'),
  591. onTap: () => _showTextInput(
  592. l10n.get('paymentMethod'),
  593. (v) => controller.updatePaymentMethod(v),
  594. initialText: expense.paymentMethod,
  595. ),
  596. onClear: () => controller.updatePaymentMethod(''),
  597. ),
  598. const SizedBox(height: 16),
  599. FormFieldRow(
  600. label: l10n.get('currency'),
  601. value: expense.currencyCode.isNotEmpty
  602. ? _currencyLabel(expense.currencyCode)
  603. : null,
  604. hint: l10n.get('selectCurrency'),
  605. onTap: () => _showCurrencyPicker(controller, expense.currencyCode),
  606. onClear: () => controller.updateCurrencyCode(''),
  607. ),
  608. const SizedBox(height: 16),
  609. Row(
  610. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  611. children: [
  612. Text(
  613. l10n.get('generateVoucher'),
  614. style: TextStyle(
  615. fontSize: AppFontSizes.subtitle,
  616. color: colors.textSecondary,
  617. ),
  618. ),
  619. TDSwitch(
  620. isOn: expense.isGenerateVoucher,
  621. onChanged: (v) {
  622. controller.setGenerateVoucher(v);
  623. return v;
  624. },
  625. ),
  626. ],
  627. ),
  628. const SizedBox(height: 16),
  629. _label(l10n.get('remark')),
  630. const SizedBox(height: 8),
  631. TDTextarea(
  632. controller: _remarkController,
  633. focusNode: _remarkFocus,
  634. hintText: l10n.get('enterRemark'),
  635. maxLines: 3,
  636. minLines: 1,
  637. maxLength: 500,
  638. indicator: true,
  639. padding: EdgeInsets.zero,
  640. bordered: true,
  641. backgroundColor: colors.bgPage,
  642. onChanged: (_) => controller.updateRemark(_remarkController.text),
  643. ),
  644. ],
  645. );
  646. }
  647. Widget _buildDetailSection(
  648. ExpenseCreateController controller,
  649. ExpenseCreateState state,
  650. ) {
  651. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  652. final l10n = AppLocalizations.of(context);
  653. final totalApproved = state.expense.details.fold<double>(
  654. 0,
  655. (sum, d) => sum + d.approvedAmount,
  656. );
  657. return FormSection(
  658. title: l10n.get('expenseDetails'),
  659. leadingIcon: Icons.receipt_long_outlined,
  660. showAction: true,
  661. actionText: l10n.get('add'),
  662. onActionTap: () => _showAddDetailDialog(controller),
  663. children: [
  664. if (state.expense.details.isEmpty)
  665. Padding(
  666. padding: const EdgeInsets.symmetric(vertical: 8),
  667. child: Text(
  668. l10n.get('noDetailHint'),
  669. style: TextStyle(
  670. fontSize: AppFontSizes.subtitle,
  671. color: colors.textPlaceholder,
  672. ),
  673. ),
  674. )
  675. else
  676. ...state.expense.details.asMap().entries.map((entry) {
  677. final d = entry.value;
  678. return GestureDetector(
  679. onTap: () =>
  680. _showAddDetailDialog(controller, editIndex: entry.key),
  681. child: Container(
  682. margin: const EdgeInsets.symmetric(vertical: 6),
  683. padding: const EdgeInsets.all(12),
  684. decoration: BoxDecoration(
  685. color: colors.bgPage,
  686. borderRadius: BorderRadius.circular(8),
  687. ),
  688. child: Row(
  689. children: [
  690. Expanded(
  691. child: Column(
  692. crossAxisAlignment: CrossAxisAlignment.start,
  693. children: [
  694. Row(
  695. children: [
  696. Expanded(
  697. child: Text(
  698. d.categoryName.isNotEmpty
  699. ? '${d.expenseCategory}/${d.categoryName}'
  700. : d.expenseCategory,
  701. style: TextStyle(
  702. fontSize: AppFontSizes.body,
  703. fontWeight: FontWeight.w500,
  704. color: colors.textPrimary,
  705. ),
  706. ),
  707. ),
  708. Column(
  709. crossAxisAlignment: CrossAxisAlignment.end,
  710. children: [
  711. Text(
  712. '¥${d.totalAmount.toStringAsFixed(2)}',
  713. style: TextStyle(
  714. fontSize: AppFontSizes.body,
  715. fontWeight: FontWeight.w600,
  716. color: colors.amountPrimary,
  717. ),
  718. ),
  719. if (d.approvedAmount > 0)
  720. Text(
  721. '¥${d.approvedAmount.toStringAsFixed(2)}',
  722. style: TextStyle(
  723. fontSize: AppFontSizes.body,
  724. fontWeight: FontWeight.w600,
  725. color: colors.success,
  726. ),
  727. ),
  728. ],
  729. ),
  730. ],
  731. ),
  732. const SizedBox(height: 2),
  733. Text(
  734. '${l10n.get('amountExcludingTax')}: ¥${d.amount.toStringAsFixed(2)}',
  735. style: TextStyle(
  736. fontSize: AppFontSizes.caption,
  737. color: colors.textSecondary,
  738. ),
  739. ),
  740. if (d.taxAmount > 0)
  741. Text(
  742. '${l10n.get('taxAmount')}: ¥${d.taxAmount.toStringAsFixed(2)}',
  743. style: TextStyle(
  744. fontSize: AppFontSizes.caption,
  745. color: colors.textSecondary,
  746. ),
  747. ),
  748. if (d.taxRate > 0)
  749. Text(
  750. '${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  751. style: TextStyle(
  752. fontSize: AppFontSizes.caption,
  753. color: colors.textSecondary,
  754. ),
  755. ),
  756. if (d.acctSubjectName.isNotEmpty)
  757. Text(
  758. '${l10n.get('acctSubject')}: ${d.acctSubjectId}/${d.acctSubjectName}',
  759. maxLines: 1,
  760. overflow: TextOverflow.ellipsis,
  761. style: TextStyle(
  762. fontSize: AppFontSizes.caption,
  763. color: colors.textSecondary,
  764. ),
  765. ),
  766. if (d.aeNo.isNotEmpty)
  767. Text(
  768. '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  769. maxLines: 1,
  770. overflow: TextOverflow.ellipsis,
  771. style: TextStyle(
  772. fontSize: AppFontSizes.caption,
  773. color: colors.textSecondary,
  774. ),
  775. ),
  776. if (d.aeDd.isNotEmpty)
  777. Text(
  778. '${l10n.get('applyDate')}: ${d.aeDd.length >= 10 ? d.aeDd.substring(0, 10) : d.aeDd}',
  779. style: TextStyle(
  780. fontSize: AppFontSizes.caption,
  781. color: colors.textSecondary,
  782. ),
  783. ),
  784. if (d.projectName.isNotEmpty)
  785. Text(
  786. '${l10n.get('project')}: ${d.projectId}/${d.projectName}',
  787. maxLines: 1,
  788. overflow: TextOverflow.ellipsis,
  789. style: TextStyle(
  790. fontSize: AppFontSizes.caption,
  791. color: colors.textSecondary,
  792. ),
  793. ),
  794. if (d.costDeptName.isNotEmpty)
  795. Text(
  796. '${l10n.get('costDept')}: ${d.costDeptId}/${d.costDeptName}',
  797. maxLines: 1,
  798. overflow: TextOverflow.ellipsis,
  799. style: TextStyle(
  800. fontSize: AppFontSizes.caption,
  801. color: colors.textSecondary,
  802. ),
  803. ),
  804. if (d.customerVendorName.isNotEmpty)
  805. Text(
  806. '${l10n.get('customerVendor')}: ${d.customerVendorId}/${d.customerVendorName}',
  807. maxLines: 1,
  808. overflow: TextOverflow.ellipsis,
  809. style: TextStyle(
  810. fontSize: AppFontSizes.caption,
  811. color: colors.textSecondary,
  812. ),
  813. ),
  814. if (d.sqManName.isNotEmpty)
  815. Text(
  816. '${l10n.get('applicant')}: ${d.sqMan}/${d.sqManName}',
  817. style: TextStyle(
  818. fontSize: AppFontSizes.caption,
  819. color: colors.textSecondary,
  820. ),
  821. ),
  822. if (d.bankAccountName.isNotEmpty)
  823. Text(
  824. '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  825. maxLines: 1,
  826. overflow: TextOverflow.ellipsis,
  827. style: TextStyle(
  828. fontSize: AppFontSizes.caption,
  829. color: colors.textSecondary,
  830. ),
  831. ),
  832. if (d.bankName.isNotEmpty)
  833. Text(
  834. '${l10n.get('bankName')}: ${d.bankName}',
  835. maxLines: 1,
  836. overflow: TextOverflow.ellipsis,
  837. style: TextStyle(
  838. fontSize: AppFontSizes.caption,
  839. color: colors.textSecondary,
  840. ),
  841. ),
  842. if (d.bankAccount.isNotEmpty)
  843. Text(
  844. '${l10n.get('bankAccount')}: ${d.bankAccount}',
  845. maxLines: 1,
  846. overflow: TextOverflow.ellipsis,
  847. style: TextStyle(
  848. fontSize: AppFontSizes.caption,
  849. color: colors.textSecondary,
  850. ),
  851. ),
  852. if (d.remark.isNotEmpty)
  853. Text(
  854. '${l10n.get('remark')}: ${d.remark}',
  855. maxLines: 2,
  856. overflow: TextOverflow.ellipsis,
  857. style: TextStyle(
  858. fontSize: AppFontSizes.caption,
  859. color: colors.textSecondary,
  860. ),
  861. ),
  862. ],
  863. ),
  864. ),
  865. const SizedBox(width: 8),
  866. GestureDetector(
  867. onTap: () {
  868. controller.removeDetail(entry.key);
  869. controller.recalculateAmount();
  870. },
  871. child: Icon(
  872. Icons.close,
  873. size: 18,
  874. color: colors.textSecondary,
  875. ),
  876. ),
  877. ],
  878. ),
  879. ),
  880. );
  881. }),
  882. const SizedBox(height: 8),
  883. Row(
  884. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  885. children: [
  886. Text(
  887. l10n.get('totalExpense'),
  888. style: TextStyle(
  889. fontSize: AppFontSizes.body,
  890. fontWeight: FontWeight.w600,
  891. color: colors.textPrimary,
  892. ),
  893. ),
  894. Text(
  895. '¥${state.expense.totalAmount.toStringAsFixed(2)}',
  896. style: TextStyle(
  897. fontSize: AppFontSizes.subtitle,
  898. fontWeight: FontWeight.w700,
  899. color: colors.amountPrimary,
  900. ),
  901. ),
  902. ],
  903. ),
  904. const SizedBox(height: 4),
  905. Row(
  906. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  907. children: [
  908. Text(
  909. l10n.get('approvedTotal'),
  910. style: TextStyle(
  911. fontSize: AppFontSizes.body,
  912. fontWeight: FontWeight.w600,
  913. color: colors.textPrimary,
  914. ),
  915. ),
  916. Text(
  917. '¥${totalApproved.toStringAsFixed(2)}',
  918. style: TextStyle(
  919. fontSize: AppFontSizes.subtitle,
  920. fontWeight: FontWeight.w700,
  921. color: totalApproved > 0 ? colors.success : colors.textPrimary,
  922. ),
  923. ),
  924. ],
  925. ),
  926. ],
  927. );
  928. }
  929. Future<void> _checkAttachHealth() async {
  930. if (mounted) setState(() => _attachAvailable = false);
  931. try {
  932. final api = ref.read(expenseApiProvider);
  933. final ok = await api.checkAttachHealth();
  934. if (mounted) setState(() => _attachAvailable = ok);
  935. } catch (_) {
  936. if (mounted) setState(() => _attachAvailable = false);
  937. }
  938. }
  939. Widget _buildAttachmentSection(
  940. ExpenseCreateController controller,
  941. ExpenseCreateState state,
  942. ) {
  943. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  944. final l10n = AppLocalizations.of(context);
  945. final children = <Widget>[];
  946. if (!_attachAvailable) {
  947. children.add(
  948. Text(
  949. l10n.get('attachServiceUnavailable'),
  950. style: TextStyle(
  951. fontSize: AppFontSizes.caption,
  952. color: colors.textPlaceholder,
  953. ),
  954. ),
  955. );
  956. } else {
  957. children.addAll([
  958. Text(
  959. l10n.get('maxAttachment'),
  960. style: TextStyle(
  961. fontSize: AppFontSizes.caption,
  962. color: colors.textPlaceholder,
  963. ),
  964. ),
  965. const SizedBox(height: 8),
  966. ]);
  967. }
  968. return FormSection(
  969. title: l10n.get('attachmentUpload'),
  970. leadingIcon: Icons.attach_file_outlined,
  971. children: [
  972. ...children,
  973. if (_attachAvailable)
  974. AttachmentPicker(
  975. controller: _attachmentController,
  976. maxImageSizeMB: 10,
  977. maxFileSizeMB: 20,
  978. allowedExtensions: const [
  979. 'pdf',
  980. 'doc',
  981. 'docx',
  982. 'xls',
  983. 'xlsx',
  984. 'ppt',
  985. 'pptx',
  986. 'txt',
  987. ],
  988. onFileRejected: (file, reason) {
  989. if (context.mounted) TDToast.showText(reason, context: context);
  990. },
  991. ),
  992. ],
  993. );
  994. }
  995. Widget _buildBottomButtons(
  996. ExpenseCreateController controller,
  997. ExpenseCreateState state,
  998. ) {
  999. final l10n = AppLocalizations.of(context);
  1000. return ActionBar(
  1001. showLeft: false,
  1002. centerLabel: l10n.get('saveDraft'),
  1003. rightLabel: l10n.get('submit'),
  1004. centerTextOnly: true,
  1005. onCenterTap: () async {
  1006. if (state.isSubmitting) return;
  1007. FocusScope.of(context).unfocus();
  1008. controller.updateAttachments(_attachmentController.toPathList());
  1009. controller.updateDept(_selectedDeptId, _selectedDeptName);
  1010. final ok = await controller.saveDraft();
  1011. if (mounted) {
  1012. if (ok) {
  1013. _forcePop();
  1014. } else {
  1015. TDToast.showFail(l10n.get('saveFailed'), context: context);
  1016. }
  1017. }
  1018. },
  1019. onRightTap: () async {
  1020. if (state.isSubmitting) return;
  1021. final err = _validate(l10n, state);
  1022. if (err.isNotEmpty) {
  1023. TDToast.showText(err.first, context: context);
  1024. return;
  1025. }
  1026. FocusScope.of(context).unfocus();
  1027. LoadingDialog.show(context, text: l10n.get('submitting'));
  1028. try {
  1029. final data = _buildSubmitData(state);
  1030. final api = ref.read(expenseApiProvider);
  1031. final billNo = await api.submit(data);
  1032. // 上传附件(billNo 提取失败则跳过,不影响主流程)
  1033. if (billNo != null) {
  1034. final now = DateTime.now();
  1035. final effDd =
  1036. '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} '
  1037. '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}.'
  1038. '${now.millisecond.toString().padLeft(3, '0')}';
  1039. final usr = HostAppChannel.usr;
  1040. // 表头附件
  1041. for (var i = 0; i < _attachmentController.files.length; i++) {
  1042. final file = _attachmentController.files[i];
  1043. try {
  1044. await api.uploadAttachment(file.path, {
  1045. 'BIL_ID': 'BX',
  1046. 'BIL_NO': billNo,
  1047. 'SRCITM': 0,
  1048. 'ITM': i + 1,
  1049. 'TAG': 1,
  1050. 'EFF_DD': effDd,
  1051. 'USR': usr,
  1052. 'FILENAME': file.name,
  1053. 'EXT': file.name.split('.').last,
  1054. });
  1055. } catch (_) {
  1056. // Attachment upload failure is non-fatal
  1057. }
  1058. }
  1059. // 明细附件
  1060. for (var i = 0; i < state.expense.details.length; i++) {
  1061. final detail = state.expense.details[i];
  1062. if (detail.attachments.isEmpty) continue;
  1063. for (var j = 0; j < detail.attachments.length; j++) {
  1064. final file = File(detail.attachments[j]);
  1065. try {
  1066. if (!await file.exists()) continue;
  1067. final fileName = file.path.split('/').last;
  1068. await api.uploadAttachment(file.path, {
  1069. 'BIL_ID': 'BX',
  1070. 'BIL_NO': billNo,
  1071. 'SRCITM': i + 1,
  1072. 'ITM': j + 1,
  1073. 'TAG': 1,
  1074. 'EFF_DD': effDd,
  1075. 'USR': usr,
  1076. 'FILENAME': fileName,
  1077. 'EXT': fileName.split('.').last,
  1078. });
  1079. } catch (_) {
  1080. // Detail attachment upload failure is non-fatal
  1081. }
  1082. }
  1083. }
  1084. }
  1085. await ExpenseCreateController.deleteDraft();
  1086. if (mounted) {
  1087. LoadingDialog.hide(context);
  1088. TDToast.showSuccess(
  1089. l10n.get('submittedAwaitingApproval'),
  1090. context: context,
  1091. );
  1092. GoRouter.of(context).go('/expense/list');
  1093. }
  1094. } catch (e) {
  1095. if (mounted) {
  1096. LoadingDialog.hide(context);
  1097. WidgetsBinding.instance.addPostFrameCallback((_) {
  1098. if (mounted) _showSubmitError(e, l10n);
  1099. });
  1100. }
  1101. }
  1102. },
  1103. );
  1104. }
  1105. void _showSubmitError(Object e, AppLocalizations l10n) {
  1106. final message = _extractErrorMessage(e) ?? l10n.get('submitFailedRetry');
  1107. showGeneralDialog(
  1108. context: context,
  1109. pageBuilder: (ctx, animation, secondaryAnimation) => TDConfirmDialog(
  1110. title: l10n.get('submitFailed'),
  1111. content: message,
  1112. buttonStyle: TDDialogButtonStyle.text,
  1113. ),
  1114. );
  1115. }
  1116. String? _extractErrorMessage(Object e) {
  1117. if (e is DioException) {
  1118. if (e.error is ApiException) return (e.error as ApiException).message;
  1119. if (e.error is NetworkException)
  1120. return (e.error as NetworkException).message;
  1121. }
  1122. return null;
  1123. }
  1124. Future<void> _showAddDetailDialog(
  1125. ExpenseCreateController controller, {
  1126. int? editIndex,
  1127. }) async {
  1128. if (_addingDetail) return;
  1129. _addingDetail = true;
  1130. try {
  1131. final l10n = AppLocalizations.of(context);
  1132. if (_costTypes.isEmpty) {
  1133. TDToast.showText(l10n.get('noCostTypeData'), context: context);
  1134. return;
  1135. }
  1136. final state = controller.currentState;
  1137. ExpenseDetailInputData? initialData;
  1138. if (editIndex != null) {
  1139. final d = state.expense.details[editIndex];
  1140. initialData = ExpenseDetailInputData(
  1141. category: d.expenseCategory,
  1142. categoryName: d.categoryName,
  1143. acctSubjectId: d.acctSubjectId,
  1144. acctSubjectName: d.acctSubjectName,
  1145. purpose: d.purpose,
  1146. amount: d.totalAmount,
  1147. taxRate: d.taxRate,
  1148. projectId: d.projectId,
  1149. projectName: d.projectName,
  1150. costDeptId: d.costDeptId,
  1151. costDeptName: d.costDeptName,
  1152. customerVendorId: d.customerVendorId,
  1153. customerVendorName: d.customerVendorName,
  1154. approvedAmount: d.approvedAmount,
  1155. bankName: d.bankName,
  1156. bankAccountName: d.bankAccountName,
  1157. bankAccount: d.bankAccount,
  1158. remark: d.remark,
  1159. attachmentPaths: d.attachments,
  1160. sqMan: d.sqMan,
  1161. sqManName: d.sqManName,
  1162. aeNo: d.aeNo,
  1163. aeDd: d.aeDd,
  1164. );
  1165. }
  1166. FocusManager.instance.primaryFocus?.unfocus();
  1167. final result = await ExpenseDetailDialog.show(
  1168. context,
  1169. categories: _dialogCategories,
  1170. projects: _dialogProjects,
  1171. costDepts: _dialogCostDepts,
  1172. customers: _dialogCustomers,
  1173. employees: _dialogEmployees,
  1174. l10n: l10n,
  1175. initialData: initialData,
  1176. checkAttachHealth: () =>
  1177. ref.read(expenseApiProvider).checkAttachHealth(),
  1178. );
  1179. if (result != null && mounted) {
  1180. final now = DateTime.now();
  1181. final detail = ExpenseDetailModel(
  1182. id: editIndex != null
  1183. ? state.expense.details[editIndex].id
  1184. : now.millisecondsSinceEpoch.toString(),
  1185. expenseId: '',
  1186. expenseCategory: result.category,
  1187. categoryName: result.categoryName,
  1188. purpose: result.purpose,
  1189. amount: result.taxRate > 0
  1190. ? result.amount / (1 + result.taxRate / 100)
  1191. : result.amount,
  1192. taxRate: result.taxRate,
  1193. taxAmount: result.taxRate > 0
  1194. ? result.amount - result.amount / (1 + result.taxRate / 100)
  1195. : 0,
  1196. totalAmount: result.amount,
  1197. projectId: result.projectId,
  1198. projectName: result.projectName,
  1199. costDeptId: result.costDeptId,
  1200. costDeptName: result.costDeptName,
  1201. acctSubjectId: result.acctSubjectId,
  1202. acctSubjectName: result.acctSubjectName,
  1203. customerVendorId: result.customerVendorId,
  1204. customerVendorName: result.customerVendorName,
  1205. approvedAmount: result.approvedAmount,
  1206. bankName: result.bankName,
  1207. bankAccountName: result.bankAccountName,
  1208. bankAccount: result.bankAccount,
  1209. sqMan: result.sqMan,
  1210. sqManName: result.sqManName,
  1211. aeNo: result.aeNo,
  1212. aeDd: result.aeDd,
  1213. remark: result.remark,
  1214. attachments: result.attachmentPaths,
  1215. createTime: now,
  1216. updateTime: now,
  1217. );
  1218. if (editIndex != null) {
  1219. controller.updateDetail(editIndex, detail);
  1220. } else {
  1221. controller.addDetail(detail);
  1222. }
  1223. controller.recalculateAmount();
  1224. }
  1225. } finally {
  1226. _addingDetail = false;
  1227. }
  1228. }
  1229. void _showCurrencyPicker(ExpenseCreateController controller, String cur) {
  1230. if (_currencies.isEmpty) {
  1231. TDToast.showText(
  1232. AppLocalizations.of(context).get('noData'),
  1233. context: context,
  1234. );
  1235. return;
  1236. }
  1237. final l10n = AppLocalizations.of(context);
  1238. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1239. final codes = _currencies.map((c) => c.curId).toList();
  1240. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  1241. FocusManager.instance.primaryFocus?.unfocus();
  1242. TDPicker.showMultiPicker(
  1243. context,
  1244. title: l10n.get('selectCurrency'),
  1245. backgroundColor: colors.bgCard,
  1246. data: [labels],
  1247. onConfirm: (s) {
  1248. if (s.isNotEmpty && s[0] is int) {
  1249. final i = s[0] as int;
  1250. if (i >= 0 && i < codes.length) {
  1251. Navigator.of(context).pop();
  1252. controller.updateCurrencyCode(codes[i]);
  1253. }
  1254. }
  1255. },
  1256. );
  1257. }
  1258. void _showTextInput(
  1259. String title,
  1260. Function(String) onConfirm, {
  1261. String initialText = '',
  1262. }) {
  1263. FocusScope.of(context).unfocus();
  1264. FocusManager.instance.primaryFocus?.unfocus();
  1265. final l10n = AppLocalizations.of(context);
  1266. final c = TextEditingController(text: initialText);
  1267. showGeneralDialog(
  1268. context: context,
  1269. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  1270. textEditingController: c,
  1271. title: title,
  1272. hintText: l10n.get('pleaseEnter'),
  1273. leftBtn: TDDialogButtonOptions(
  1274. title: l10n.get('cancel'),
  1275. action: () => Navigator.pop(ctx),
  1276. ),
  1277. rightBtn: TDDialogButtonOptions(
  1278. title: l10n.get('confirm'),
  1279. action: () {
  1280. onConfirm(c.text);
  1281. Navigator.pop(ctx);
  1282. },
  1283. ),
  1284. ),
  1285. );
  1286. }
  1287. Widget _label(String t, {bool required = false}) {
  1288. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1289. return Text.rich(
  1290. TextSpan(
  1291. children: [
  1292. TextSpan(
  1293. text: t,
  1294. style: TextStyle(
  1295. fontSize: AppFontSizes.subtitle,
  1296. color: colors.textSecondary,
  1297. ),
  1298. ),
  1299. if (required)
  1300. TextSpan(
  1301. text: ' *',
  1302. style: TextStyle(
  1303. fontSize: AppFontSizes.subtitle,
  1304. color: colors.danger,
  1305. ),
  1306. ),
  1307. ],
  1308. ),
  1309. );
  1310. }
  1311. List<String> _validate(AppLocalizations l10n, ExpenseCreateState state) {
  1312. final e = <String>[];
  1313. if (_purposeController.text.trim().isEmpty) {
  1314. e.add(l10n.get('enterExpenseReason'));
  1315. }
  1316. if (state.expense.details.isEmpty) {
  1317. e.add(l10n.get('addAtLeastOneDetail'));
  1318. }
  1319. return e;
  1320. }
  1321. bool _hasUnsaved(ExpenseCreateState state) =>
  1322. _purposeController.text.isNotEmpty ||
  1323. state.expense.paymentMethod.isNotEmpty ||
  1324. state.expense.currencyCode.isNotEmpty ||
  1325. _remarkController.text.isNotEmpty ||
  1326. state.expense.details.isNotEmpty ||
  1327. _attachmentController.files.isNotEmpty;
  1328. void _doPop() {
  1329. final l10n = AppLocalizations.of(context);
  1330. final state = ref.read(expenseCreateProvider(widget.editId));
  1331. if (_hasUnsaved(state)) {
  1332. _showConfirmDialog(
  1333. l10n.get('confirmExit'),
  1334. l10n.get('unsavedContentWarning'),
  1335. l10n.get('continueEditing'),
  1336. l10n.get('discardAndExit'),
  1337. () async {
  1338. try {
  1339. await ExpenseCreateController.deleteDraft();
  1340. } catch (_) {}
  1341. if (!mounted) return;
  1342. setState(() {
  1343. _selectedDeptId = '';
  1344. _selectedDeptName = '';
  1345. });
  1346. ref.read(expenseCreateProvider(widget.editId).notifier).reset();
  1347. _forcePop();
  1348. },
  1349. );
  1350. } else {
  1351. _forcePop();
  1352. }
  1353. }
  1354. void _forcePop() {
  1355. FocusManager.instance.primaryFocus?.unfocus();
  1356. final router = GoRouter.of(context);
  1357. if (router.canPop()) {
  1358. router.pop();
  1359. } else {
  1360. SystemNavigator.pop();
  1361. }
  1362. }
  1363. void _showConfirmDialog(
  1364. String title,
  1365. String content,
  1366. String leftText,
  1367. String rightText,
  1368. VoidCallback onConfirm,
  1369. ) {
  1370. FocusScope.of(context).unfocus();
  1371. FocusManager.instance.primaryFocus?.unfocus();
  1372. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1373. showDialog(
  1374. context: context,
  1375. useRootNavigator: true,
  1376. builder: (ctx) => TDAlertDialog(
  1377. title: title,
  1378. content: content,
  1379. buttonStyle: TDDialogButtonStyle.text,
  1380. leftBtn: TDDialogButtonOptions(
  1381. title: leftText,
  1382. titleColor: colors.primary,
  1383. action: () => Navigator.pop(ctx),
  1384. ),
  1385. rightBtn: TDDialogButtonOptions(
  1386. title: rightText,
  1387. titleColor: colors.danger,
  1388. action: () {
  1389. Navigator.pop(ctx);
  1390. onConfirm();
  1391. },
  1392. ),
  1393. ),
  1394. );
  1395. }
  1396. Widget _buildPageFooter() {
  1397. final l10n = AppLocalizations.of(context);
  1398. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1399. return Center(
  1400. child: Padding(
  1401. padding: const EdgeInsets.only(bottom: 16),
  1402. child: Row(
  1403. mainAxisSize: MainAxisSize.min,
  1404. children: [
  1405. Icon(
  1406. Icons.rocket_launch_outlined,
  1407. size: 16,
  1408. color: colors.textPlaceholder,
  1409. ),
  1410. const SizedBox(width: 6),
  1411. Text(
  1412. l10n.get('pageFooter'),
  1413. style: TextStyle(
  1414. fontSize: AppFontSizes.caption,
  1415. color: colors.textPlaceholder,
  1416. ),
  1417. ),
  1418. ],
  1419. ),
  1420. ),
  1421. );
  1422. }
  1423. String _today() {
  1424. final n = DateTime.now();
  1425. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1426. }
  1427. }