expense_create_page.dart 50 KB

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