expense_create_page.dart 51 KB

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