expense_create_page.dart 51 KB

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