expense_create_page.dart 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  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:go_router/go_router.dart';
  8. import '../../core/utils/responsive.dart';
  9. import '../../shared/widgets/form_section.dart';
  10. import '../../shared/widgets/form_field_row.dart';
  11. import '../../shared/widgets/app_skeletons.dart';
  12. import '../../shared/widgets/nav_bar_config.dart';
  13. import '../../shared/widgets/searchable_picker_sheet.dart';
  14. import 'expense_api.dart';
  15. import 'expense_create_controller.dart';
  16. import '../../core/i18n/app_localizations.dart';
  17. import 'expense_model.dart';
  18. import '../../core/theme/app_colors.dart';
  19. import '../../core/theme/app_colors_extension.dart';
  20. import '../../core/navigation/host_app_channel.dart';
  21. import '../../core/utils/amount_utils.dart';
  22. import 'widgets/expense_detail_dialog.dart';
  23. import '../../shared/models/bill_file_rights.dart';
  24. import '../../shared/widgets/action_bar.dart';
  25. import '../../shared/widgets/loading_dialog.dart';
  26. import '../../shared/widgets/attachment_picker.dart';
  27. import 'expense_apply_import_page.dart';
  28. class ExpenseCreatePage extends ConsumerStatefulWidget {
  29. final String? editId;
  30. const ExpenseCreatePage({super.key, this.editId});
  31. @override
  32. ConsumerState<ExpenseCreatePage> createState() => _ExpenseCreatePageState();
  33. }
  34. class _ExpenseCreatePageState extends ConsumerState<ExpenseCreatePage> {
  35. final _purposeController = TextEditingController();
  36. final _purposeFocus = FocusNode();
  37. final _remarkController = TextEditingController();
  38. final _remarkFocus = FocusNode();
  39. final _scrollCtrl = ScrollController();
  40. final _detailsSectionKey = GlobalKey();
  41. late final AttachmentPickerController _attachmentController;
  42. bool _attachAvailable = false;
  43. BillFileRights _billFileRights = BillFileRights.none;
  44. late Future<bool> _draftFuture;
  45. bool _draftHandled = false;
  46. // ── 参考数据(从 API 加载) ──
  47. List<DepartmentItem> _departments = [];
  48. List<CurrencyItem> _currencies = [];
  49. List<EmployeeItem> _employees = [];
  50. EmployeeItem? _selEmployee;
  51. EmployeeItem? _currentUserForDialog;
  52. dynamic _acctTree;
  53. bool _firstBuild = true;
  54. bool _refDataLoading = true;
  55. bool _addingDetail = false;
  56. bool _canEditApprovedAmount = false;
  57. // ── 已导入申请单号集合,用于申请事由去重拼接 ──
  58. final _importedAeNos = <String>{};
  59. // ── 报销部门 ──
  60. String _selectedDeptId = '';
  61. String _selectedDeptName = '';
  62. @override
  63. void initState() {
  64. super.initState();
  65. SystemChrome.setSystemUIOverlayStyle(
  66. const SystemUiOverlayStyle(
  67. statusBarColor: Colors.transparent,
  68. statusBarIconBrightness: Brightness.dark,
  69. ),
  70. );
  71. _attachmentController = AttachmentPickerController(maxCount: 9)
  72. ..addListener(() => setState(() {}));
  73. _checkAttachHealth();
  74. _checkApprovedAmountRight();
  75. _checkBillFileRights();
  76. _purposeFocus.addListener(() => _ensureVisible(_purposeFocus));
  77. _remarkFocus.addListener(() => _ensureVisible(_remarkFocus));
  78. _departments = [];
  79. _employees = [];
  80. _refDataLoading = true;
  81. _refDataFuture = null;
  82. _draftFuture = widget.editId == null
  83. ? ExpenseCreateController.hasDraft()
  84. : Future.value(false);
  85. _loadRefData();
  86. WidgetsBinding.instance.addPostFrameCallback((_) => _checkDataReady());
  87. }
  88. void _checkDataReady() {
  89. if (!_refDataLoading && mounted) {
  90. setState(() => _firstBuild = false);
  91. WidgetsBinding.instance.addPostFrameCallback((_) {
  92. if (mounted) setState(() {});
  93. });
  94. } else if (mounted) {
  95. WidgetsBinding.instance.addPostFrameCallback((_) => _checkDataReady());
  96. }
  97. }
  98. Future<void>? _refDataFuture;
  99. Future<void> _loadRefData() async {
  100. if (_refDataFuture != null) return _refDataFuture!;
  101. final completer = Completer<void>();
  102. _refDataFuture = completer.future;
  103. try {
  104. final api = ref.read(expenseApiProvider);
  105. final results = await Future.wait([
  106. api.getDepartments(),
  107. api.getCurrencies(),
  108. api.getEmployees(),
  109. api.getEmployees(salNo: HostAppChannel.usr, size: 1),
  110. api.getAcctSubjects(),
  111. ]);
  112. if (!mounted) {
  113. completer.complete();
  114. return;
  115. }
  116. setState(() {
  117. _departments = results[0] as List<DepartmentItem>;
  118. _currencies = results[1] as List<CurrencyItem>;
  119. _employees = results[2] as List<EmployeeItem>;
  120. final currentUserCheck = results[3] as List<EmployeeItem>;
  121. if (currentUserCheck.isNotEmpty) {
  122. _selEmployee = currentUserCheck.first;
  123. _currentUserForDialog = currentUserCheck.first;
  124. }
  125. _acctTree = _convertAcctTree(results[4]);
  126. _refDataLoading = false;
  127. _autoSelectDept();
  128. _autoSelectEmployee();
  129. });
  130. completer.complete();
  131. } catch (_) {
  132. if (!mounted) {
  133. completer.complete();
  134. return;
  135. }
  136. setState(() => _refDataLoading = false);
  137. completer.complete();
  138. } finally {
  139. _refDataFuture = null;
  140. }
  141. }
  142. void _scrollToDetailSection() {
  143. WidgetsBinding.instance.addPostFrameCallback((_) {
  144. if (_scrollCtrl.hasClients && _detailsSectionKey.currentContext != null) {
  145. Scrollable.ensureVisible(
  146. _detailsSectionKey.currentContext!,
  147. alignment: 0.0,
  148. duration: const Duration(milliseconds: 300),
  149. );
  150. }
  151. });
  152. }
  153. void _ensureVisible(FocusNode node) {
  154. if (!node.hasFocus) return;
  155. WidgetsBinding.instance.addPostFrameCallback((_) {
  156. if (node.hasFocus && _scrollCtrl.hasClients) {
  157. final ctx = node.context;
  158. if (ctx != null) {
  159. Scrollable.ensureVisible(
  160. ctx,
  161. alignment: 0.3,
  162. duration: const Duration(milliseconds: 300),
  163. );
  164. }
  165. }
  166. });
  167. }
  168. @override
  169. void dispose() {
  170. _purposeController.dispose();
  171. _purposeFocus.dispose();
  172. _remarkController.dispose();
  173. _remarkFocus.dispose();
  174. _scrollCtrl.dispose();
  175. _attachmentController.dispose();
  176. super.dispose();
  177. }
  178. @override
  179. Widget build(BuildContext context) {
  180. final controller = ref.watch(expenseCreateProvider(widget.editId).notifier);
  181. final state = ref.watch(expenseCreateProvider(widget.editId));
  182. final r = ResponsiveHelper.of(context);
  183. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  184. final bottomInset = MediaQuery.of(context).padding.bottom;
  185. if (_firstBuild) return const SkeletonFormPage(showImportLink: true);
  186. Future.microtask(
  187. () => ref.read(pageBackProvider.notifier).state = () => _doPop(),
  188. );
  189. Widget pageContent = PopScope(
  190. canPop: false,
  191. onPopInvokedWithResult: (didPop, _) {
  192. if (didPop) return;
  193. _doPop();
  194. },
  195. child: Column(
  196. children: [
  197. Expanded(
  198. child: Align(
  199. alignment: Alignment.topCenter,
  200. child: ConstrainedBox(
  201. constraints: BoxConstraints(maxWidth: r.formMaxWidth),
  202. child: SingleChildScrollView(
  203. controller: _scrollCtrl,
  204. padding: const EdgeInsets.all(16),
  205. child: Column(
  206. crossAxisAlignment: CrossAxisAlignment.start,
  207. children: [
  208. _buildImportLink(),
  209. const SizedBox(height: 16),
  210. _buildBasicInfoSection(controller, state),
  211. const SizedBox(height: 16),
  212. Container(
  213. key: _detailsSectionKey,
  214. child: _buildDetailSection(controller, state),
  215. ),
  216. const SizedBox(height: 16),
  217. _buildAttachmentSection(controller, state),
  218. const SizedBox(height: 24),
  219. _buildPageFooter(),
  220. ],
  221. ),
  222. ),
  223. ),
  224. ),
  225. ),
  226. ColoredBox(
  227. color: colors.bgCard,
  228. child: Column(
  229. mainAxisSize: MainAxisSize.min,
  230. children: [
  231. _buildBottomButtons(controller, state),
  232. if (bottomInset > 0) SizedBox(height: bottomInset),
  233. ],
  234. ),
  235. ),
  236. ],
  237. ),
  238. );
  239. return FutureBuilder<bool>(
  240. future: _draftFuture,
  241. builder: (ctx, snapshot) {
  242. final hasDraft = snapshot.hasData && snapshot.data == true;
  243. if (hasDraft && !_draftHandled) {
  244. _draftHandled = true;
  245. WidgetsBinding.instance.addPostFrameCallback((_) {
  246. if (mounted) _showDraftDialog();
  247. });
  248. }
  249. return pageContent;
  250. },
  251. );
  252. }
  253. void _showDraftDialog() {
  254. final l10n = AppLocalizations.of(context);
  255. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  256. FocusManager.instance.primaryFocus?.unfocus();
  257. showDialog(
  258. context: context,
  259. barrierDismissible: false,
  260. builder: (ctx) => TDAlertDialog(
  261. title: l10n.get('draftFound'),
  262. content: l10n.get('draftRestorePrompt'),
  263. leftBtn: TDDialogButtonOptions(
  264. title: l10n.get('discard'),
  265. titleColor: colors.textSecondary,
  266. action: () {
  267. Navigator.pop(ctx);
  268. ExpenseCreateController.deleteDraft();
  269. },
  270. ),
  271. rightBtn: TDDialogButtonOptions(
  272. title: l10n.get('restore'),
  273. titleColor: colors.primary,
  274. action: () async {
  275. final navigator = Navigator.of(ctx);
  276. final draft = await ExpenseCreateController.loadDraft();
  277. if (draft != null && mounted) {
  278. final api = ref.read(expenseApiProvider);
  279. ref
  280. .read(expenseCreateProvider(widget.editId).notifier)
  281. .restoreFromDraft(draft, api);
  282. _purposeController.text = draft.purpose;
  283. _remarkController.text = draft.remark;
  284. if (draft.attachments.isNotEmpty) {
  285. await _attachmentController.restoreFromPaths(draft.attachments);
  286. }
  287. }
  288. navigator.pop();
  289. },
  290. ),
  291. ),
  292. );
  293. }
  294. String _currencyLabel(String code) {
  295. final match = _currencies.where((c) => c.curId == code);
  296. return match.isNotEmpty ? '${match.first.curId}/${match.first.name}' : code;
  297. }
  298. List<Map<String, dynamic>> _convertAcctTree(dynamic tree) {
  299. final list = tree is List ? tree : <dynamic>[];
  300. if (list.isEmpty) return [];
  301. return list.map<Map<String, dynamic>>((item) {
  302. final map = Map<String, dynamic>.from(item is Map ? item : {});
  303. if (map.containsKey('children') && map['children'] != null) {
  304. map['children'] = _convertAcctTree(map['children']);
  305. }
  306. return map;
  307. }).toList();
  308. }
  309. void _autoSelectDept() {
  310. if (_selectedDeptId.isNotEmpty) return;
  311. final dep = HostAppChannel.dep;
  312. if (dep.isEmpty) return;
  313. final match = _departments.where((d) => d.dep == dep);
  314. if (match.isNotEmpty) {
  315. _selectedDeptId = match.first.dep;
  316. _selectedDeptName = match.first.name;
  317. }
  318. }
  319. void _autoSelectEmployee() {
  320. if (_selEmployee != null) return;
  321. final usr = HostAppChannel.usr;
  322. if (usr.isEmpty || _employees.isEmpty) return;
  323. final match = _employees.where((e) => e.salNo == usr);
  324. if (match.isNotEmpty) {
  325. setState(() => _selEmployee = match.first);
  326. ref
  327. .read(expenseCreateProvider(widget.editId).notifier)
  328. .updateEmployee(match.first.salNo, match.first.name);
  329. }
  330. }
  331. Future<void> _showEmployeePicker() async {
  332. FocusManager.instance.primaryFocus?.unfocus();
  333. final l10n = AppLocalizations.of(context);
  334. final api = ref.read(expenseApiProvider);
  335. final result = await showSearchablePicker<EmployeeItem>(
  336. context,
  337. title: '${l10n.get('select')}${l10n.get('expensePersonnel')}',
  338. searchHint: l10n.get('search'),
  339. loader: (keyword, page) =>
  340. api.getEmployees(keyword: keyword, page: page, size: 20),
  341. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  342. onRefresh: () => api.clearRefCache(),
  343. );
  344. if (result != null && mounted) {
  345. setState(() => _selEmployee = result);
  346. ref
  347. .read(expenseCreateProvider(widget.editId).notifier)
  348. .updateEmployee(_selEmployee!.salNo, _selEmployee!.name);
  349. }
  350. }
  351. Future<void> _showDeptPicker() async {
  352. FocusManager.instance.primaryFocus?.unfocus();
  353. final l10n = AppLocalizations.of(context);
  354. final api = ref.read(expenseApiProvider);
  355. final result = await showSearchablePicker<DepartmentItem>(
  356. context,
  357. title: '${l10n.get('select')}${l10n.get('expenseDept')}',
  358. searchHint: l10n.get('search'),
  359. loader: (keyword, page) =>
  360. api.getDepartments(keyword: keyword, page: page, size: 20),
  361. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  362. onRefresh: () => api.clearRefCache(),
  363. );
  364. if (result != null && mounted) {
  365. setState(() {
  366. _selectedDeptId = result.dep;
  367. _selectedDeptName = result.name;
  368. });
  369. }
  370. }
  371. Map<String, dynamic> _buildSubmitData(ExpenseCreateState state) {
  372. final expense = state.expense;
  373. return {
  374. 'HeadData': {
  375. 'BX_DD': _today(),
  376. 'DEP': _selectedDeptId,
  377. 'USR_NO': _selEmployee?.salNo ?? '',
  378. // TODO: 支付方式、币别暂时隐藏
  379. //'PAY_ID': expense.paymentMethod,
  380. //'PRT_SW': 'N',
  381. 'USR': HostAppChannel.usr,
  382. 'REM': expense.remark,
  383. //'CUR_ID': expense.currencyCode,
  384. //'EXC_RTO': expense.excRto,
  385. 'REASON': expense.purpose,
  386. 'VOH_ID': expense.isGenerateVoucher ? 'T' : 'F',
  387. },
  388. 'BodyData1': expense.details.asMap().entries.map((e) {
  389. final d = e.value;
  390. return {
  391. 'BX_DD': _today(),
  392. 'ACC_NO': d.acctSubjectId,
  393. 'AMT': d.totalAmount,
  394. 'AMTN': d.amount,
  395. 'AMTN_SH': d.approvedAmount,
  396. 'REM': d.remark,
  397. 'CUST': d.customerVendorId,
  398. 'IDX_NO': d.expenseCategory,
  399. 'OBJ_NO': d.projectId.isNotEmpty ? d.projectId : '',
  400. 'TAX': d.taxAmount,
  401. 'TAX_RTO': d.taxRate,
  402. 'DEP': d.costDeptId,
  403. 'AE_NO': d.aeNo,
  404. 'AE_DD': d.aeDd,
  405. 'BNK_NO': d.bankName,
  406. 'BNK_ID': d.bankAccount,
  407. 'ACCNAME': d.bankAccountName,
  408. 'SQ_MAN': d.sqMan.isNotEmpty ? d.sqMan : HostAppChannel.usr,
  409. 'EST_ITM': d.aeNo.isNotEmpty ? d.sortOrder : 0,
  410. };
  411. }).toList(),
  412. };
  413. }
  414. Widget _buildImportLink() {
  415. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  416. final l10n = AppLocalizations.of(context);
  417. return GestureDetector(
  418. onTap: () async {
  419. final result = await GoRouter.of(
  420. context,
  421. ).push<List<ImportableItem>>('/expense/import-apply');
  422. if (result == null || result.isEmpty || !mounted) return;
  423. // 将选中的导入数据转换为明细,先移除同单号的旧数据
  424. final controller = ref.read(
  425. expenseCreateProvider(widget.editId).notifier,
  426. );
  427. final aeNos = result.map((e) => e.aeNo).toSet();
  428. for (final aeNo in aeNos) {
  429. controller.removeDetailsByAeNo(aeNo);
  430. }
  431. // 拼接申请事由到报销单头 purpose(同张单多次转入只拼一次)
  432. final newReasons = <String>[];
  433. for (final aeNo in aeNos) {
  434. if (!_importedAeNos.contains(aeNo)) {
  435. final item = result.firstWhere((e) => e.aeNo == aeNo);
  436. if (item.reason.isNotEmpty) {
  437. newReasons.add(item.reason);
  438. _importedAeNos.add(aeNo);
  439. }
  440. }
  441. }
  442. if (newReasons.isNotEmpty) {
  443. final currentPurpose = controller.currentState.expense.purpose;
  444. final joined = newReasons.join(';');
  445. final newPurpose = currentPurpose.isNotEmpty
  446. ? '$currentPurpose;$joined'
  447. : joined;
  448. controller.updatePurpose(newPurpose);
  449. _purposeController.text = newPurpose;
  450. }
  451. final now = DateTime.now();
  452. for (final item in result) {
  453. controller.addDetail(
  454. ExpenseDetailModel(
  455. id: '${now.millisecondsSinceEpoch}_${item.itm}',
  456. expenseId: '',
  457. expenseApplyId: '',
  458. expenseApplyNo: item.aeNo,
  459. expenseApplyDate: item.aeDd.isNotEmpty
  460. ? DateTime.tryParse(item.aeDd)
  461. : null,
  462. expenseCategory: item.typeNo,
  463. categoryName: item.typeName,
  464. purpose: item.rem,
  465. priority: item.priority,
  466. projectId: item.objNo,
  467. projectName: item.objName,
  468. costDeptId: item.dep,
  469. costDeptName: item.depName,
  470. acctSubjectId: item.accNo,
  471. acctSubjectName: item.accName,
  472. amount: item.amtnYj,
  473. taxRate: 0,
  474. taxAmount: 0,
  475. totalAmount: item.amtnYj,
  476. currencyCode: '',
  477. exchangeRate: 1.0,
  478. baseAmount: item.amtnYj,
  479. approvedAmount: item.amtnYj,
  480. customerVendorId: '',
  481. customerVendorName: '',
  482. bankName: '',
  483. bankAccountName: '',
  484. bankAccount: '',
  485. remark: item.rem,
  486. sortOrder: item.preItm ?? item.itm,
  487. attachments: const [],
  488. sqMan: item.sqMan,
  489. sqManName: item.sqName,
  490. aeNo: item.aeNo,
  491. aeDd: item.aeDd,
  492. createTime: now,
  493. updateTime: now,
  494. ),
  495. );
  496. }
  497. controller.recalculateAmount();
  498. TDToast.showSuccess(l10n.get('importSuccess'), context: context);
  499. _scrollToDetailSection();
  500. },
  501. child: Container(
  502. height: 44,
  503. decoration: BoxDecoration(
  504. color: colors.primaryLight,
  505. borderRadius: BorderRadius.circular(8),
  506. ),
  507. child: Row(
  508. mainAxisAlignment: MainAxisAlignment.center,
  509. children: [
  510. Icon(Icons.download, size: 14, color: colors.primary),
  511. const SizedBox(width: 8),
  512. Text(
  513. l10n.get('importApprovedPreApp'),
  514. style: TextStyle(
  515. fontSize: AppFontSizes.body,
  516. color: colors.primary,
  517. ),
  518. ),
  519. ],
  520. ),
  521. ),
  522. );
  523. }
  524. Widget _buildBasicInfoSection(
  525. ExpenseCreateController controller,
  526. ExpenseCreateState state,
  527. ) {
  528. final l10n = AppLocalizations.of(context);
  529. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  530. final expense = state.expense;
  531. return FormSection(
  532. title: l10n.get('basicInfo'),
  533. leadingIcon: Icons.info_outline,
  534. children: [
  535. FormFieldRow(
  536. label: l10n.get('date'),
  537. value: _today(),
  538. readOnly: true,
  539. showArrow: false,
  540. ),
  541. const SizedBox(height: 16),
  542. FormFieldRow(
  543. label: l10n.get('expensePersonnel'),
  544. value: _selEmployee != null
  545. ? '${_selEmployee!.salNo}/${_selEmployee!.name}'
  546. : '',
  547. hint: l10n.get('pleaseSelect'),
  548. onTap: _employees.isNotEmpty ? _showEmployeePicker : null,
  549. ),
  550. const SizedBox(height: 16),
  551. FormFieldRow(
  552. label: l10n.get('expenseDept'),
  553. value: _selectedDeptName.isNotEmpty
  554. ? '$_selectedDeptId/$_selectedDeptName'
  555. : null,
  556. hint: l10n.get('pleaseSelect'),
  557. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  558. ),
  559. const SizedBox(height: 16),
  560. _label(l10n.get('expenseReason'), required: true),
  561. const SizedBox(height: 8),
  562. TDTextarea(
  563. controller: _purposeController,
  564. focusNode: _purposeFocus,
  565. hintText: l10n.get('enterExpenseReason'),
  566. maxLines: 4,
  567. minLines: 1,
  568. maxLength: 500,
  569. indicator: true,
  570. padding: EdgeInsets.zero,
  571. bordered: true,
  572. backgroundColor: colors.bgPage,
  573. onChanged: (_) => controller.updatePurpose(_purposeController.text),
  574. ),
  575. // TODO: 支付方式、币别暂时隐藏
  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) LoadingDialog.hide(context);
  1118. }
  1119. },
  1120. );
  1121. }
  1122. Future<void> _showAddDetailDialog(
  1123. ExpenseCreateController controller, {
  1124. int? editIndex,
  1125. }) async {
  1126. if (_addingDetail) return;
  1127. _addingDetail = true;
  1128. try {
  1129. final l10n = AppLocalizations.of(context);
  1130. final state = controller.currentState;
  1131. ExpenseDetailInputData? initialData;
  1132. if (editIndex != null) {
  1133. final d = state.expense.details[editIndex];
  1134. initialData = ExpenseDetailInputData(
  1135. category: d.expenseCategory,
  1136. categoryName: d.categoryName,
  1137. acctSubjectId: d.acctSubjectId,
  1138. acctSubjectName: d.acctSubjectName,
  1139. purpose: d.purpose,
  1140. amount: d.totalAmount,
  1141. taxRate: d.taxRate,
  1142. projectId: d.projectId,
  1143. projectName: d.projectName,
  1144. costDeptId: d.costDeptId,
  1145. costDeptName: d.costDeptName,
  1146. customerVendorId: d.customerVendorId,
  1147. customerVendorName: d.customerVendorName,
  1148. approvedAmount: d.approvedAmount,
  1149. bankName: d.bankName,
  1150. bankAccountName: d.bankAccountName,
  1151. bankAccount: d.bankAccount,
  1152. remark: d.remark,
  1153. attachmentPaths: d.attachments,
  1154. sqMan: d.sqMan,
  1155. sqManName: d.sqManName,
  1156. aeNo: d.aeNo,
  1157. aeDd: d.aeDd,
  1158. );
  1159. }
  1160. FocusManager.instance.primaryFocus?.unfocus();
  1161. final result = await ExpenseDetailDialog.show(
  1162. context,
  1163. api: ref.read(expenseApiProvider),
  1164. l10n: l10n,
  1165. initialData: initialData,
  1166. checkAttachHealth: () =>
  1167. ref.read(expenseApiProvider).checkAttachHealth(),
  1168. canEditApprovedAmount: _canEditApprovedAmount,
  1169. billFileRights: _billFileRights,
  1170. acctTree: _acctTree,
  1171. defaultSqMan: _currentUserForDialog?.salNo,
  1172. defaultSqManName: _currentUserForDialog?.name,
  1173. );
  1174. if (result != null && mounted) {
  1175. final now = DateTime.now();
  1176. final detail = ExpenseDetailModel(
  1177. id: editIndex != null
  1178. ? state.expense.details[editIndex].id
  1179. : now.millisecondsSinceEpoch.toString(),
  1180. expenseId: '',
  1181. expenseCategory: result.category,
  1182. categoryName: result.categoryName,
  1183. purpose: result.purpose,
  1184. amount: result.taxRate > 0
  1185. ? result.amount / (1 + result.taxRate / 100)
  1186. : result.amount,
  1187. taxRate: result.taxRate,
  1188. taxAmount: result.taxRate > 0
  1189. ? result.amount - result.amount / (1 + result.taxRate / 100)
  1190. : 0,
  1191. totalAmount: result.amount,
  1192. projectId: result.projectId,
  1193. projectName: result.projectName,
  1194. costDeptId: result.costDeptId,
  1195. costDeptName: result.costDeptName,
  1196. acctSubjectId: result.acctSubjectId,
  1197. acctSubjectName: result.acctSubjectName,
  1198. customerVendorId: result.customerVendorId,
  1199. customerVendorName: result.customerVendorName,
  1200. approvedAmount: result.approvedAmount,
  1201. bankName: result.bankName,
  1202. bankAccountName: result.bankAccountName,
  1203. bankAccount: result.bankAccount,
  1204. sqMan: result.sqMan,
  1205. sqManName: result.sqManName,
  1206. aeNo: result.aeNo,
  1207. aeDd: result.aeDd,
  1208. remark: result.remark,
  1209. sortOrder: editIndex != null
  1210. ? state.expense.details[editIndex].sortOrder
  1211. : 1,
  1212. preItm: editIndex != null
  1213. ? state.expense.details[editIndex].preItm
  1214. : null,
  1215. attachments: result.attachmentPaths,
  1216. createTime: now,
  1217. updateTime: now,
  1218. );
  1219. if (editIndex != null) {
  1220. controller.updateDetail(editIndex, detail);
  1221. } else {
  1222. controller.addDetail(detail);
  1223. }
  1224. controller.recalculateAmount();
  1225. }
  1226. } finally {
  1227. _addingDetail = false;
  1228. }
  1229. }
  1230. void _showCurrencyPicker(ExpenseCreateController controller, String cur) {
  1231. if (_currencies.isEmpty) {
  1232. TDToast.showText(
  1233. AppLocalizations.of(context).get('noData'),
  1234. context: context,
  1235. );
  1236. return;
  1237. }
  1238. final l10n = AppLocalizations.of(context);
  1239. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1240. final codes = _currencies.map((c) => c.curId).toList();
  1241. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  1242. FocusManager.instance.primaryFocus?.unfocus();
  1243. TDPicker.showMultiPicker(
  1244. context,
  1245. title: l10n.get('selectCurrency'),
  1246. backgroundColor: colors.bgCard,
  1247. data: [labels],
  1248. onConfirm: (s) {
  1249. if (s.isNotEmpty && s[0] is int) {
  1250. final i = s[0] as int;
  1251. if (i >= 0 && i < codes.length) {
  1252. Navigator.of(context).pop();
  1253. controller.updateCurrencyCode(codes[i], _currencies[i].excRto);
  1254. }
  1255. }
  1256. },
  1257. );
  1258. }
  1259. void _showTextInput(
  1260. String title,
  1261. Function(String) onConfirm, {
  1262. String initialText = '',
  1263. }) {
  1264. FocusScope.of(context).unfocus();
  1265. FocusManager.instance.primaryFocus?.unfocus();
  1266. final l10n = AppLocalizations.of(context);
  1267. final c = TextEditingController(text: initialText);
  1268. showGeneralDialog(
  1269. context: context,
  1270. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  1271. textEditingController: c,
  1272. title: title,
  1273. hintText: l10n.get('pleaseEnter'),
  1274. leftBtn: TDDialogButtonOptions(
  1275. title: l10n.get('cancel'),
  1276. action: () => Navigator.pop(ctx),
  1277. ),
  1278. rightBtn: TDDialogButtonOptions(
  1279. title: l10n.get('confirm'),
  1280. action: () {
  1281. onConfirm(c.text);
  1282. Navigator.pop(ctx);
  1283. },
  1284. ),
  1285. ),
  1286. );
  1287. }
  1288. Widget _label(String t, {bool required = false}) {
  1289. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1290. return Text.rich(
  1291. TextSpan(
  1292. children: [
  1293. TextSpan(
  1294. text: t,
  1295. style: TextStyle(
  1296. fontSize: AppFontSizes.subtitle,
  1297. color: colors.textSecondary,
  1298. ),
  1299. ),
  1300. if (required)
  1301. TextSpan(
  1302. text: ' *',
  1303. style: TextStyle(
  1304. fontSize: AppFontSizes.subtitle,
  1305. color: colors.danger,
  1306. ),
  1307. ),
  1308. ],
  1309. ),
  1310. );
  1311. }
  1312. List<String> _validate(AppLocalizations l10n, ExpenseCreateState state) {
  1313. final e = <String>[];
  1314. if (_purposeController.text.trim().isEmpty) {
  1315. e.add(l10n.get('enterExpenseReason'));
  1316. }
  1317. if (state.expense.details.isEmpty) {
  1318. e.add(l10n.get('addAtLeastOneDetail'));
  1319. }
  1320. return e;
  1321. }
  1322. bool _hasUnsaved(ExpenseCreateState state) =>
  1323. _purposeController.text.isNotEmpty ||
  1324. state.expense.paymentMethod.isNotEmpty ||
  1325. state.expense.currencyCode.isNotEmpty ||
  1326. _remarkController.text.isNotEmpty ||
  1327. state.expense.details.isNotEmpty ||
  1328. _attachmentController.files.isNotEmpty;
  1329. void _doPop() {
  1330. final l10n = AppLocalizations.of(context);
  1331. final state = ref.read(expenseCreateProvider(widget.editId));
  1332. if (_hasUnsaved(state)) {
  1333. _showConfirmDialog(
  1334. l10n.get('confirmExit'),
  1335. l10n.get('unsavedContentWarning'),
  1336. l10n.get('continueEditing'),
  1337. l10n.get('discardAndExit'),
  1338. () async {
  1339. try {
  1340. await ExpenseCreateController.deleteDraft();
  1341. } catch (_) {}
  1342. if (!mounted) return;
  1343. setState(() {
  1344. _selectedDeptId = '';
  1345. _selectedDeptName = '';
  1346. });
  1347. ref.read(expenseCreateProvider(widget.editId).notifier).reset();
  1348. _forcePop();
  1349. },
  1350. );
  1351. } else {
  1352. _forcePop();
  1353. }
  1354. }
  1355. void _forcePop() {
  1356. FocusManager.instance.primaryFocus?.unfocus();
  1357. final router = GoRouter.of(context);
  1358. if (router.canPop()) {
  1359. router.pop();
  1360. } else {
  1361. SystemNavigator.pop();
  1362. }
  1363. }
  1364. void _showConfirmDialog(
  1365. String title,
  1366. String content,
  1367. String leftText,
  1368. String rightText,
  1369. VoidCallback onConfirm,
  1370. ) {
  1371. FocusScope.of(context).unfocus();
  1372. FocusManager.instance.primaryFocus?.unfocus();
  1373. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1374. showDialog(
  1375. context: context,
  1376. useRootNavigator: true,
  1377. builder: (ctx) => TDAlertDialog(
  1378. title: title,
  1379. content: content,
  1380. buttonStyle: TDDialogButtonStyle.text,
  1381. leftBtn: TDDialogButtonOptions(
  1382. title: leftText,
  1383. titleColor: colors.primary,
  1384. action: () => Navigator.pop(ctx),
  1385. ),
  1386. rightBtn: TDDialogButtonOptions(
  1387. title: rightText,
  1388. titleColor: colors.danger,
  1389. action: () {
  1390. Navigator.pop(ctx);
  1391. onConfirm();
  1392. },
  1393. ),
  1394. ),
  1395. );
  1396. }
  1397. Widget _buildPageFooter() {
  1398. final l10n = AppLocalizations.of(context);
  1399. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1400. return Center(
  1401. child: Padding(
  1402. padding: const EdgeInsets.only(bottom: 16),
  1403. child: Row(
  1404. mainAxisSize: MainAxisSize.min,
  1405. children: [
  1406. Icon(
  1407. Icons.rocket_launch_outlined,
  1408. size: 16,
  1409. color: colors.textPlaceholder,
  1410. ),
  1411. const SizedBox(width: 6),
  1412. Text(
  1413. l10n.get('pageFooter'),
  1414. style: TextStyle(
  1415. fontSize: AppFontSizes.caption,
  1416. color: colors.textPlaceholder,
  1417. ),
  1418. ),
  1419. ],
  1420. ),
  1421. ),
  1422. );
  1423. }
  1424. String _today() {
  1425. final n = DateTime.now();
  1426. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1427. }
  1428. }