expense_create_page.dart 50 KB

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