expense_create_page.dart 51 KB

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