expense_create_page.dart 48 KB

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