expense_create_page.dart 51 KB

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