expense_create_page.dart 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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,
  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.taxRate > 0)
  695. Text(
  696. '${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  697. style: TextStyle(
  698. fontSize: AppFontSizes.caption,
  699. color: colors.textSecondary,
  700. ),
  701. ),
  702. if (d.acctSubjectName.isNotEmpty)
  703. Text(
  704. '${l10n.get('acctSubject')}: ${d.acctSubjectId}/${d.acctSubjectName}',
  705. maxLines: 1,
  706. overflow: TextOverflow.ellipsis,
  707. style: TextStyle(
  708. fontSize: AppFontSizes.caption,
  709. color: colors.textSecondary,
  710. ),
  711. ),
  712. if (d.aeNo.isNotEmpty)
  713. Text(
  714. '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  715. maxLines: 1,
  716. overflow: TextOverflow.ellipsis,
  717. style: TextStyle(
  718. fontSize: AppFontSizes.caption,
  719. color: colors.textSecondary,
  720. ),
  721. ),
  722. if (d.aeDd.isNotEmpty)
  723. Text(
  724. '${l10n.get('applyDate')}: ${d.aeDd}',
  725. style: TextStyle(
  726. fontSize: AppFontSizes.caption,
  727. color: colors.textSecondary,
  728. ),
  729. ),
  730. if (d.projectName.isNotEmpty)
  731. Text(
  732. '${l10n.get('project')}: ${d.projectId}/${d.projectName}',
  733. maxLines: 1,
  734. overflow: TextOverflow.ellipsis,
  735. style: TextStyle(
  736. fontSize: AppFontSizes.caption,
  737. color: colors.textSecondary,
  738. ),
  739. ),
  740. if (d.costDeptName.isNotEmpty)
  741. Text(
  742. '${l10n.get('costDept')}: ${d.costDeptId}/${d.costDeptName}',
  743. maxLines: 1,
  744. overflow: TextOverflow.ellipsis,
  745. style: TextStyle(
  746. fontSize: AppFontSizes.caption,
  747. color: colors.textSecondary,
  748. ),
  749. ),
  750. if (d.customerVendorName.isNotEmpty)
  751. Text(
  752. '${l10n.get('customerVendor')}: ${d.customerVendorId}/${d.customerVendorName}',
  753. maxLines: 1,
  754. overflow: TextOverflow.ellipsis,
  755. style: TextStyle(
  756. fontSize: AppFontSizes.caption,
  757. color: colors.textSecondary,
  758. ),
  759. ),
  760. if (d.sqManName.isNotEmpty)
  761. Text(
  762. '${l10n.get('applicant')}: ${d.sqMan}/${d.sqManName}',
  763. style: TextStyle(
  764. fontSize: AppFontSizes.caption,
  765. color: colors.textSecondary,
  766. ),
  767. ),
  768. if (d.bankAccountName.isNotEmpty)
  769. Text(
  770. '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  771. maxLines: 1,
  772. overflow: TextOverflow.ellipsis,
  773. style: TextStyle(
  774. fontSize: AppFontSizes.caption,
  775. color: colors.textSecondary,
  776. ),
  777. ),
  778. if (d.bankName.isNotEmpty)
  779. Text(
  780. '${l10n.get('bankName')}: ${d.bankName}',
  781. maxLines: 1,
  782. overflow: TextOverflow.ellipsis,
  783. style: TextStyle(
  784. fontSize: AppFontSizes.caption,
  785. color: colors.textSecondary,
  786. ),
  787. ),
  788. if (d.bankAccount.isNotEmpty)
  789. Text(
  790. '${l10n.get('bankAccount')}: ${d.bankAccount}',
  791. maxLines: 1,
  792. overflow: TextOverflow.ellipsis,
  793. style: TextStyle(
  794. fontSize: AppFontSizes.caption,
  795. color: colors.textSecondary,
  796. ),
  797. ),
  798. if (d.remark.isNotEmpty)
  799. Text(
  800. '${l10n.get('remark')}: ${d.remark}',
  801. maxLines: 2,
  802. overflow: TextOverflow.ellipsis,
  803. style: TextStyle(
  804. fontSize: AppFontSizes.caption,
  805. color: colors.textSecondary,
  806. ),
  807. ),
  808. ],
  809. ),
  810. ),
  811. const SizedBox(width: 8),
  812. GestureDetector(
  813. onTap: () {
  814. controller.removeDetail(entry.key);
  815. controller.recalculateAmount();
  816. },
  817. child: Icon(
  818. Icons.close,
  819. size: 18,
  820. color: colors.textSecondary,
  821. ),
  822. ),
  823. ],
  824. ),
  825. ),
  826. );
  827. }),
  828. const SizedBox(height: 8),
  829. Row(
  830. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  831. children: [
  832. Text(
  833. l10n.get('totalExpense'),
  834. style: TextStyle(
  835. fontSize: AppFontSizes.body,
  836. fontWeight: FontWeight.w600,
  837. color: colors.textPrimary,
  838. ),
  839. ),
  840. Text(
  841. '¥${state.expense.totalAmount.toStringAsFixed(2)}',
  842. style: TextStyle(
  843. fontSize: AppFontSizes.subtitle,
  844. fontWeight: FontWeight.w700,
  845. color: colors.amountPrimary,
  846. ),
  847. ),
  848. ],
  849. ),
  850. const SizedBox(height: 4),
  851. Row(
  852. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  853. children: [
  854. Text(
  855. l10n.get('approvedTotal'),
  856. style: TextStyle(
  857. fontSize: AppFontSizes.body,
  858. fontWeight: FontWeight.w600,
  859. color: colors.textPrimary,
  860. ),
  861. ),
  862. Text(
  863. '¥${totalApproved.toStringAsFixed(2)}',
  864. style: TextStyle(
  865. fontSize: AppFontSizes.subtitle,
  866. fontWeight: FontWeight.w700,
  867. color: totalApproved > 0 ? colors.success : colors.textPrimary,
  868. ),
  869. ),
  870. ],
  871. ),
  872. ],
  873. );
  874. }
  875. Future<void> _checkAttachHealth() async {
  876. if (mounted) setState(() => _attachAvailable = false);
  877. try {
  878. final api = ref.read(expenseApiProvider);
  879. final ok = await api.checkAttachHealth();
  880. if (mounted) setState(() => _attachAvailable = ok);
  881. } catch (_) {
  882. if (mounted) setState(() => _attachAvailable = false);
  883. }
  884. }
  885. Widget _buildAttachmentSection(
  886. ExpenseCreateController controller,
  887. ExpenseCreateState state,
  888. ) {
  889. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  890. final l10n = AppLocalizations.of(context);
  891. final children = <Widget>[];
  892. if (!_attachAvailable) {
  893. children.add(
  894. Text(
  895. l10n.get('attachServiceUnavailable'),
  896. style: TextStyle(
  897. fontSize: AppFontSizes.caption,
  898. color: colors.textPlaceholder,
  899. ),
  900. ),
  901. );
  902. } else {
  903. children.addAll([
  904. Text(
  905. l10n.get('maxAttachment'),
  906. style: TextStyle(
  907. fontSize: AppFontSizes.caption,
  908. color: colors.textPlaceholder,
  909. ),
  910. ),
  911. const SizedBox(height: 8),
  912. ]);
  913. }
  914. return FormSection(
  915. title: l10n.get('attachmentUpload'),
  916. leadingIcon: Icons.attach_file_outlined,
  917. children: [
  918. ...children,
  919. if (_attachAvailable)
  920. AttachmentPicker(
  921. controller: _attachmentController,
  922. maxImageSizeMB: 10,
  923. maxFileSizeMB: 20,
  924. allowedExtensions: const [
  925. 'pdf',
  926. 'doc',
  927. 'docx',
  928. 'xls',
  929. 'xlsx',
  930. 'ppt',
  931. 'pptx',
  932. 'txt',
  933. ],
  934. onFileRejected: (file, reason) {
  935. if (context.mounted) TDToast.showText(reason, context: context);
  936. },
  937. ),
  938. ],
  939. );
  940. }
  941. Widget _buildBottomButtons(
  942. ExpenseCreateController controller,
  943. ExpenseCreateState state,
  944. ) {
  945. final l10n = AppLocalizations.of(context);
  946. return ActionBar(
  947. showLeft: false,
  948. centerLabel: l10n.get('saveDraft'),
  949. rightLabel: l10n.get('submit'),
  950. centerTextOnly: true,
  951. onCenterTap: () async {
  952. if (state.isSubmitting) return;
  953. FocusScope.of(context).unfocus();
  954. controller.updateAttachments(_attachmentController.toPathList());
  955. controller.updateDept(_selectedDeptId, _selectedDeptName);
  956. final ok = await controller.saveDraft();
  957. if (mounted) {
  958. if (ok) {
  959. _forcePop();
  960. } else {
  961. TDToast.showFail(l10n.get('saveFailed'), context: context);
  962. }
  963. }
  964. },
  965. onRightTap: () async {
  966. if (state.isSubmitting) return;
  967. final err = _validate(l10n, state);
  968. if (err.isNotEmpty) {
  969. TDToast.showText(err.first, context: context);
  970. return;
  971. }
  972. FocusScope.of(context).unfocus();
  973. LoadingDialog.show(context, text: l10n.get('submitting'));
  974. try {
  975. final data = _buildSubmitData(state);
  976. final api = ref.read(expenseApiProvider);
  977. final billNo = await api.submit(data);
  978. // 上传附件(billNo 提取失败则跳过,不影响主流程)
  979. if (billNo != null) {
  980. final now = DateTime.now();
  981. final effDd =
  982. '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} '
  983. '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}.'
  984. '${now.millisecond.toString().padLeft(3, '0')}';
  985. final usr = HostAppChannel.usr;
  986. // 表头附件
  987. for (var i = 0; i < _attachmentController.files.length; i++) {
  988. final file = _attachmentController.files[i];
  989. try {
  990. await api.uploadAttachment(file.path, {
  991. 'BIL_ID': 'BX',
  992. 'BIL_NO': billNo,
  993. 'SRCITM': 0,
  994. 'ITM': i + 1,
  995. 'TAG': 1,
  996. 'EFF_DD': effDd,
  997. 'USR': usr,
  998. 'FILENAME': file.name,
  999. 'EXT': file.name.split('.').last,
  1000. });
  1001. } catch (_) {
  1002. // Attachment upload failure is non-fatal
  1003. }
  1004. }
  1005. // 明细附件
  1006. for (var i = 0; i < state.expense.details.length; i++) {
  1007. final detail = state.expense.details[i];
  1008. if (detail.attachments.isEmpty) continue;
  1009. for (var j = 0; j < detail.attachments.length; j++) {
  1010. final file = File(detail.attachments[j]);
  1011. try {
  1012. if (!await file.exists()) continue;
  1013. final fileName = file.path.split('/').last;
  1014. await api.uploadAttachment(file.path, {
  1015. 'BIL_ID': 'BX',
  1016. 'BIL_NO': billNo,
  1017. 'SRCITM': i + 1,
  1018. 'ITM': j + 1,
  1019. 'TAG': 1,
  1020. 'EFF_DD': effDd,
  1021. 'USR': usr,
  1022. 'FILENAME': fileName,
  1023. 'EXT': fileName.split('.').last,
  1024. });
  1025. } catch (_) {
  1026. // Detail attachment upload failure is non-fatal
  1027. }
  1028. }
  1029. }
  1030. }
  1031. await ExpenseCreateController.deleteDraft();
  1032. if (mounted) {
  1033. LoadingDialog.hide(context);
  1034. TDToast.showSuccess(
  1035. l10n.get('submittedAwaitingApproval'),
  1036. context: context,
  1037. );
  1038. GoRouter.of(context).go('/expense/list');
  1039. }
  1040. } catch (_) {
  1041. if (mounted) {
  1042. LoadingDialog.hide(context);
  1043. TDToast.showFail(l10n.get('submitFailedRetry'), context: context);
  1044. }
  1045. }
  1046. },
  1047. );
  1048. }
  1049. Future<void> _showAddDetailDialog(
  1050. ExpenseCreateController controller, {
  1051. int? editIndex,
  1052. }) async {
  1053. if (_addingDetail) return;
  1054. _addingDetail = true;
  1055. try {
  1056. final l10n = AppLocalizations.of(context);
  1057. if (_costTypes.isEmpty) {
  1058. TDToast.showText(l10n.get('noCostTypeData'), context: context);
  1059. return;
  1060. }
  1061. final state = controller.currentState;
  1062. ExpenseDetailInputData? initialData;
  1063. if (editIndex != null) {
  1064. final d = state.expense.details[editIndex];
  1065. initialData = ExpenseDetailInputData(
  1066. category: d.expenseCategory,
  1067. categoryName: d.categoryName,
  1068. acctSubjectId: d.acctSubjectId,
  1069. acctSubjectName: d.acctSubjectName,
  1070. purpose: d.purpose,
  1071. amount: d.amount,
  1072. taxRate: d.taxRate,
  1073. projectId: d.projectId,
  1074. projectName: d.projectName,
  1075. costDeptId: d.costDeptId,
  1076. costDeptName: d.costDeptName,
  1077. customerVendorId: d.customerVendorId,
  1078. customerVendorName: d.customerVendorName,
  1079. approvedAmount: d.approvedAmount,
  1080. bankName: d.bankName,
  1081. bankAccountName: d.bankAccountName,
  1082. bankAccount: d.bankAccount,
  1083. remark: d.remark,
  1084. attachmentPaths: d.attachments,
  1085. sqMan: d.sqMan,
  1086. sqManName: d.sqManName,
  1087. aeNo: d.aeNo,
  1088. aeDd: d.aeDd,
  1089. );
  1090. }
  1091. FocusManager.instance.primaryFocus?.unfocus();
  1092. final result = await ExpenseDetailDialog.show(
  1093. context,
  1094. categories: _dialogCategories,
  1095. projects: _dialogProjects,
  1096. costDepts: _dialogCostDepts,
  1097. customers: _dialogCustomers,
  1098. employees: _dialogEmployees,
  1099. l10n: l10n,
  1100. initialData: initialData,
  1101. checkAttachHealth: () =>
  1102. ref.read(expenseApiProvider).checkAttachHealth(),
  1103. );
  1104. if (result != null && mounted) {
  1105. final now = DateTime.now();
  1106. final detail = ExpenseDetailModel(
  1107. id: editIndex != null
  1108. ? state.expense.details[editIndex].id
  1109. : now.millisecondsSinceEpoch.toString(),
  1110. expenseId: '',
  1111. expenseCategory: result.category,
  1112. categoryName: result.categoryName,
  1113. purpose: result.purpose,
  1114. amount: result.taxRate > 0
  1115. ? result.amount / (1 + result.taxRate / 100)
  1116. : result.amount,
  1117. taxRate: result.taxRate,
  1118. taxAmount: result.taxRate > 0
  1119. ? result.amount - result.amount / (1 + result.taxRate / 100)
  1120. : 0,
  1121. totalAmount: result.amount,
  1122. projectId: result.projectId,
  1123. projectName: result.projectName,
  1124. costDeptId: result.costDeptId,
  1125. costDeptName: result.costDeptName,
  1126. acctSubjectId: result.acctSubjectId,
  1127. acctSubjectName: result.acctSubjectName,
  1128. customerVendorId: result.customerVendorId,
  1129. customerVendorName: result.customerVendorName,
  1130. approvedAmount: result.approvedAmount,
  1131. bankName: result.bankName,
  1132. bankAccountName: result.bankAccountName,
  1133. bankAccount: result.bankAccount,
  1134. sqMan: result.sqMan,
  1135. sqManName: result.sqManName,
  1136. aeNo: result.aeNo,
  1137. aeDd: result.aeDd,
  1138. remark: result.remark,
  1139. attachments: result.attachmentPaths,
  1140. createTime: now,
  1141. updateTime: now,
  1142. );
  1143. if (editIndex != null) {
  1144. controller.updateDetail(editIndex, detail);
  1145. } else {
  1146. controller.addDetail(detail);
  1147. }
  1148. controller.recalculateAmount();
  1149. }
  1150. } finally {
  1151. _addingDetail = false;
  1152. }
  1153. }
  1154. void _showCurrencyPicker(ExpenseCreateController controller, String cur) {
  1155. if (_currencies.isEmpty) {
  1156. TDToast.showText(
  1157. AppLocalizations.of(context).get('noData'),
  1158. context: context,
  1159. );
  1160. return;
  1161. }
  1162. final l10n = AppLocalizations.of(context);
  1163. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1164. final codes = _currencies.map((c) => c.curId).toList();
  1165. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  1166. FocusManager.instance.primaryFocus?.unfocus();
  1167. TDPicker.showMultiPicker(
  1168. context,
  1169. title: l10n.get('selectCurrency'),
  1170. backgroundColor: colors.bgCard,
  1171. data: [labels],
  1172. onConfirm: (s) {
  1173. if (s.isNotEmpty && s[0] is int) {
  1174. final i = s[0] as int;
  1175. if (i >= 0 && i < codes.length) {
  1176. Navigator.of(context).pop();
  1177. controller.updateCurrencyCode(codes[i]);
  1178. }
  1179. }
  1180. },
  1181. );
  1182. }
  1183. void _showTextInput(
  1184. String title,
  1185. Function(String) onConfirm, {
  1186. String initialText = '',
  1187. }) {
  1188. FocusScope.of(context).unfocus();
  1189. FocusManager.instance.primaryFocus?.unfocus();
  1190. final l10n = AppLocalizations.of(context);
  1191. final c = TextEditingController(text: initialText);
  1192. showGeneralDialog(
  1193. context: context,
  1194. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  1195. textEditingController: c,
  1196. title: title,
  1197. hintText: l10n.get('pleaseEnter'),
  1198. leftBtn: TDDialogButtonOptions(
  1199. title: l10n.get('cancel'),
  1200. action: () => Navigator.pop(ctx),
  1201. ),
  1202. rightBtn: TDDialogButtonOptions(
  1203. title: l10n.get('confirm'),
  1204. action: () {
  1205. onConfirm(c.text);
  1206. Navigator.pop(ctx);
  1207. },
  1208. ),
  1209. ),
  1210. );
  1211. }
  1212. Widget _label(String t, {bool required = false}) {
  1213. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1214. return Text.rich(
  1215. TextSpan(
  1216. children: [
  1217. TextSpan(
  1218. text: t,
  1219. style: TextStyle(
  1220. fontSize: AppFontSizes.subtitle,
  1221. color: colors.textSecondary,
  1222. ),
  1223. ),
  1224. if (required)
  1225. TextSpan(
  1226. text: ' *',
  1227. style: TextStyle(
  1228. fontSize: AppFontSizes.subtitle,
  1229. color: colors.danger,
  1230. ),
  1231. ),
  1232. ],
  1233. ),
  1234. );
  1235. }
  1236. List<String> _validate(AppLocalizations l10n, ExpenseCreateState state) {
  1237. final e = <String>[];
  1238. if (_purposeController.text.trim().isEmpty) {
  1239. e.add(l10n.get('enterExpenseReason'));
  1240. }
  1241. if (state.expense.details.isEmpty) {
  1242. e.add(l10n.get('addAtLeastOneDetail'));
  1243. }
  1244. return e;
  1245. }
  1246. bool _hasUnsaved(ExpenseCreateState state) =>
  1247. _purposeController.text.isNotEmpty ||
  1248. state.expense.paymentMethod.isNotEmpty ||
  1249. state.expense.currencyCode.isNotEmpty ||
  1250. _remarkController.text.isNotEmpty ||
  1251. state.expense.details.isNotEmpty ||
  1252. _attachmentController.files.isNotEmpty ||
  1253. _selectedDeptId.isNotEmpty;
  1254. void _doPop() {
  1255. final l10n = AppLocalizations.of(context);
  1256. final state = ref.read(expenseCreateProvider(widget.editId));
  1257. if (_hasUnsaved(state)) {
  1258. _showConfirmDialog(
  1259. l10n.get('confirmExit'),
  1260. l10n.get('unsavedContentWarning'),
  1261. l10n.get('continueEditing'),
  1262. l10n.get('discardAndExit'),
  1263. () async {
  1264. try {
  1265. await ExpenseCreateController.deleteDraft();
  1266. } catch (_) {}
  1267. if (!mounted) return;
  1268. setState(() {
  1269. _selectedDeptId = '';
  1270. _selectedDeptName = '';
  1271. });
  1272. ref.read(expenseCreateProvider(widget.editId).notifier).reset();
  1273. _forcePop();
  1274. },
  1275. );
  1276. } else {
  1277. _forcePop();
  1278. }
  1279. }
  1280. void _forcePop() {
  1281. FocusManager.instance.primaryFocus?.unfocus();
  1282. final router = GoRouter.of(context);
  1283. if (router.canPop()) {
  1284. router.pop();
  1285. } else {
  1286. SystemNavigator.pop();
  1287. }
  1288. }
  1289. void _showConfirmDialog(
  1290. String title,
  1291. String content,
  1292. String leftText,
  1293. String rightText,
  1294. VoidCallback onConfirm,
  1295. ) {
  1296. FocusScope.of(context).unfocus();
  1297. FocusManager.instance.primaryFocus?.unfocus();
  1298. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1299. showDialog(
  1300. context: context,
  1301. useRootNavigator: true,
  1302. builder: (ctx) => TDAlertDialog(
  1303. title: title,
  1304. content: content,
  1305. buttonStyle: TDDialogButtonStyle.text,
  1306. leftBtn: TDDialogButtonOptions(
  1307. title: leftText,
  1308. titleColor: colors.primary,
  1309. action: () => Navigator.pop(ctx),
  1310. ),
  1311. rightBtn: TDDialogButtonOptions(
  1312. title: rightText,
  1313. titleColor: colors.danger,
  1314. action: () {
  1315. Navigator.pop(ctx);
  1316. onConfirm();
  1317. },
  1318. ),
  1319. ),
  1320. );
  1321. }
  1322. Widget _buildPageFooter() {
  1323. final l10n = AppLocalizations.of(context);
  1324. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1325. return Center(
  1326. child: Padding(
  1327. padding: const EdgeInsets.only(bottom: 16),
  1328. child: Row(
  1329. mainAxisSize: MainAxisSize.min,
  1330. children: [
  1331. Icon(
  1332. Icons.rocket_launch_outlined,
  1333. size: 16,
  1334. color: colors.textPlaceholder,
  1335. ),
  1336. const SizedBox(width: 6),
  1337. Text(
  1338. l10n.get('pageFooter'),
  1339. style: TextStyle(
  1340. fontSize: AppFontSizes.caption,
  1341. color: colors.textPlaceholder,
  1342. ),
  1343. ),
  1344. ],
  1345. ),
  1346. ),
  1347. );
  1348. }
  1349. String _today() {
  1350. final n = DateTime.now();
  1351. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1352. }
  1353. }