expense_create_page.dart 47 KB

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