expense_create_page.dart 51 KB

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