expense_create_page.dart 50 KB

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