expense_create_page.dart 49 KB

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