expense_create_page.dart 51 KB

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