expense_create_page.dart 52 KB

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