| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391 |
- import 'dart:async';
- import 'dart:io';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- import 'package:flutter_riverpod/flutter_riverpod.dart';
- import 'package:tdesign_flutter/tdesign_flutter.dart';
- import 'package:go_router/go_router.dart';
- import '../../shared/widgets/nav_bar_config.dart';
- import '../../core/utils/responsive.dart';
- import '../../shared/widgets/form_section.dart';
- import '../../shared/widgets/form_field_row.dart';
- import 'expense_api.dart';
- import 'expense_create_controller.dart';
- import '../../core/i18n/app_localizations.dart';
- import 'expense_model.dart';
- import '../../core/theme/app_colors.dart';
- import '../../core/theme/app_colors_extension.dart';
- import '../../core/navigation/host_app_channel.dart';
- import '../../core/data/mock_api_data.dart';
- import 'widgets/expense_detail_dialog.dart';
- import '../../shared/widgets/action_bar.dart';
- import '../../shared/widgets/loading_dialog.dart';
- import '../../shared/widgets/attachment_picker.dart';
- import 'expense_apply_import_page.dart';
- class ExpenseCreatePage extends ConsumerStatefulWidget {
- final String? editId;
- const ExpenseCreatePage({super.key, this.editId});
- @override
- ConsumerState<ExpenseCreatePage> createState() => _ExpenseCreatePageState();
- }
- class _ExpenseCreatePageState extends ConsumerState<ExpenseCreatePage>
- with WidgetsBindingObserver {
- final _purposeController = TextEditingController();
- final _purposeFocus = FocusNode();
- final _remarkController = TextEditingController();
- final _remarkFocus = FocusNode();
- final _scrollCtrl = ScrollController();
- final _detailsSectionKey = GlobalKey();
- late final AttachmentPickerController _attachmentController;
- bool _attachAvailable = false;
- late Future<bool> _draftFuture;
- bool _draftHandled = false;
- bool _isPoppingToNative = false;
- // ── 参考数据(从 API 加载) ──
- List<CostTypeItem> _costTypes = [];
- List<ProjectCodeItem> _projects = [];
- List<DepartmentItem> _departments = [];
- List<CustomerItem> _customers = [];
- List<CurrencyItem> _currencies = [];
- List<EmployeeItem> _employees = [];
- bool _refDataLoading = true;
- bool _addingDetail = false;
- // ── 报销部门 ──
- String _selectedDeptId = '';
- String _selectedDeptName = '';
- @override
- void initState() {
- super.initState();
- WidgetsBinding.instance.addObserver(this);
- SystemChrome.setSystemUIOverlayStyle(
- const SystemUiOverlayStyle(
- statusBarColor: Colors.transparent,
- statusBarIconBrightness: Brightness.dark,
- ),
- );
- _attachmentController = AttachmentPickerController(maxCount: 9)
- ..addListener(() => setState(() {}));
- _checkAttachHealth();
- _purposeFocus.addListener(() => _ensureVisible(_purposeFocus));
- _remarkFocus.addListener(() => _ensureVisible(_remarkFocus));
- _costTypes = [];
- _projects = [];
- _departments = [];
- _customers = [];
- _employees = [];
- _refDataLoading = true;
- _refDataFuture = null;
- _draftFuture = widget.editId == null
- ? ExpenseCreateController.hasDraft()
- : Future.value(false);
- _loadRefData();
- }
- Future<void>? _refDataFuture;
- Future<void> _loadRefData() async {
- if (_refDataFuture != null) return _refDataFuture!;
- final completer = Completer<void>();
- _refDataFuture = completer.future;
- try {
- final api = ref.read(expenseApiProvider);
- final results = await Future.wait([
- api.getCostTypes(),
- api.getProjectCodes(),
- api.getDepartments(),
- api.getCustomers(),
- api.getCurrencies(),
- api.getEmployees(),
- ]);
- if (!mounted) {
- completer.complete();
- return;
- }
- setState(() {
- _costTypes = results[0] as List<CostTypeItem>;
- _projects = results[1] as List<ProjectCodeItem>;
- _departments = results[2] as List<DepartmentItem>;
- _customers = results[3] as List<CustomerItem>;
- _currencies = results[4] as List<CurrencyItem>;
- _employees = results[5] as List<EmployeeItem>;
- _refDataLoading = false;
- _autoSelectDept();
- });
- completer.complete();
- } catch (_) {
- if (!mounted) {
- completer.complete();
- return;
- }
- setState(() => _refDataLoading = false);
- completer.complete();
- } finally {
- _refDataFuture = null;
- }
- }
- void _scrollToDetailSection() {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (_scrollCtrl.hasClients && _detailsSectionKey.currentContext != null) {
- Scrollable.ensureVisible(
- _detailsSectionKey.currentContext!,
- alignment: 0.0,
- duration: const Duration(milliseconds: 300),
- );
- }
- });
- }
- void _ensureVisible(FocusNode node) {
- if (!node.hasFocus) return;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (node.hasFocus && _scrollCtrl.hasClients) {
- final ctx = node.context;
- if (ctx != null) {
- Scrollable.ensureVisible(
- ctx,
- alignment: 0.3,
- duration: const Duration(milliseconds: 300),
- );
- }
- }
- });
- }
- @override
- void dispose() {
- WidgetsBinding.instance.removeObserver(this);
- _purposeController.dispose();
- _purposeFocus.dispose();
- _remarkController.dispose();
- _remarkFocus.dispose();
- _scrollCtrl.dispose();
- _attachmentController.dispose();
- super.dispose();
- }
- @override
- void didChangeAppLifecycleState(AppLifecycleState state) {
- if (state == AppLifecycleState.resumed && _isPoppingToNative) {
- _isPoppingToNative = false;
- HostAppChannel.refresh();
- // 重置表单数据
- _purposeController.clear();
- _remarkController.clear();
- _selectedDeptId = '';
- _selectedDeptName = '';
- _attachmentController.clear();
- _attachAvailable = false;
- _addingDetail = false;
- // 重置参考数据
- _costTypes = [];
- _projects = [];
- _departments = [];
- _customers = [];
- _employees = [];
- _currencies = [];
- _refDataFuture = null;
- _refDataLoading = true;
- // 重置草稿和控制器状态
- _draftHandled = false;
- _draftFuture = widget.editId == null
- ? ExpenseCreateController.hasDraft()
- : Future.value(false);
- ref.read(expenseCreateProvider(widget.editId).notifier).reset();
- // 重新加载
- _loadRefData();
- _checkAttachHealth();
- }
- }
- @override
- Widget build(BuildContext context) {
- final controller = ref.watch(expenseCreateProvider(widget.editId).notifier);
- final state = ref.watch(expenseCreateProvider(widget.editId));
- final r = ResponsiveHelper.of(context);
- final l10n = AppLocalizations.of(context);
- setNavBarTitle(context, ref, NavBarConfig(
- title: widget.editId != null
- ? l10n.get('editExpense')
- : l10n.get('expenseApply'),
- showBack: true,
- onBack: () => _doPop(),
- ));
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final bottomInset = MediaQuery.of(context).padding.bottom;
- Widget pageContent = PopScope(
- canPop: false,
- onPopInvokedWithResult: (didPop, _) {
- if (didPop) return;
- _doPop();
- },
- child: Column(
- children: [
- Expanded(
- child: Align(
- alignment: Alignment.topCenter,
- child: ConstrainedBox(
- constraints: BoxConstraints(maxWidth: r.formMaxWidth),
- child: SingleChildScrollView(
- controller: _scrollCtrl,
- padding: const EdgeInsets.all(16),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- _buildImportLink(),
- const SizedBox(height: 16),
- _buildBasicInfoSection(controller, state),
- const SizedBox(height: 16),
- Container(
- key: _detailsSectionKey,
- child: _buildDetailSection(controller, state),
- ),
- const SizedBox(height: 16),
- _buildAttachmentSection(controller, state),
- const SizedBox(height: 24),
- _buildPageFooter(),
- ],
- ),
- ),
- ),
- ),
- ),
- ColoredBox(
- color: colors.bgCard,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- _buildBottomButtons(controller, state),
- if (bottomInset > 0) SizedBox(height: bottomInset),
- ],
- ),
- ),
- ],
- ),
- );
- return FutureBuilder<bool>(
- future: _draftFuture,
- builder: (ctx, snapshot) {
- final hasDraft = snapshot.hasData && snapshot.data == true;
- if (hasDraft && !_draftHandled) {
- _draftHandled = true;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) _showDraftDialog();
- });
- }
- return pageContent;
- },
- );
- }
- void _showDraftDialog() {
- final l10n = AppLocalizations.of(context);
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- showDialog(
- context: context,
- barrierDismissible: false,
- builder: (ctx) => TDAlertDialog(
- title: l10n.get('draftFound'),
- content: l10n.get('draftRestorePrompt'),
- leftBtn: TDDialogButtonOptions(
- title: l10n.get('discard'),
- titleColor: colors.textSecondary,
- action: () {
- Navigator.pop(ctx);
- ExpenseCreateController.deleteDraft();
- },
- ),
- rightBtn: TDDialogButtonOptions(
- title: l10n.get('restore'),
- titleColor: colors.primary,
- action: () async {
- Navigator.pop(ctx);
- final draft = await ExpenseCreateController.loadDraft();
- if (draft != null && mounted) {
- final api = ref.read(expenseApiProvider);
- ref
- .read(expenseCreateProvider(widget.editId).notifier)
- .restoreFromDraft(draft, api);
- _purposeController.text = draft.purpose;
- _remarkController.text = draft.remark;
- if (draft.attachments.isNotEmpty) {
- await _attachmentController.restoreFromPaths(draft.attachments);
- }
- }
- },
- ),
- ),
- );
- }
- // ═══ API 数据 → 弹窗类型转换 ═══
- List<CostCategory> get _dialogCategories => _costTypes
- .map(
- (c) => CostCategory(
- code: c.typeNo,
- nameKey: c.typeName,
- acctSubjectId: c.accNo,
- acctSubjectName: c.accName,
- ),
- )
- .toList();
- List<Project> get _dialogProjects => _projects
- .map((p) => Project(id: int.tryParse(p.objNo) ?? 0, name: p.name))
- .toList();
- List<CostDept> get _dialogCostDepts =>
- _departments.map((d) => CostDept(id: d.dep, name: d.name)).toList();
- String _currencyLabel(String code) {
- final match = _currencies.where((c) => c.curId == code);
- return match.isNotEmpty ? '${match.first.curId}/${match.first.name}' : code;
- }
- List<CustomerVendor> get _dialogCustomers =>
- _customers.map((c) => CustomerVendor(id: c.cusNo, name: c.name)).toList();
- List<EmployeeItem> get _dialogEmployees => _employees;
- void _autoSelectDept() {
- if (_selectedDeptId.isNotEmpty) return;
- final dep = HostAppChannel.dep;
- if (dep.isEmpty) return;
- final match = _departments.where((d) => d.dep == dep);
- if (match.isNotEmpty) {
- _selectedDeptId = match.first.dep;
- _selectedDeptName = match.first.name;
- }
- }
- void _showDeptPicker() {
- if (_departments.isEmpty) {
- TDToast.showText(
- AppLocalizations.of(context).get('noData'),
- context: context,
- );
- return;
- }
- final l10n = AppLocalizations.of(context);
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final labels = _departments.map((d) => '${d.dep}/${d.name}').toList();
- TDPicker.showMultiPicker(
- context,
- title: l10n.get('expenseDept'),
- backgroundColor: colors.bgCard,
- data: [labels],
- onConfirm: (selected) {
- if (selected.isNotEmpty && selected[0] is int) {
- final idx = selected[0] as int;
- if (idx >= 0 && idx < labels.length) {
- Navigator.of(context).pop();
- setState(() {
- _selectedDeptId = _departments[idx].dep;
- _selectedDeptName = _departments[idx].name;
- });
- }
- }
- },
- );
- }
- Map<String, dynamic> _buildSubmitData(ExpenseCreateState state) {
- final expense = state.expense;
- return {
- 'HeadData': {
- 'BX_DD': _today(),
- 'DEP': _selectedDeptId,
- 'USR_NO': HostAppChannel.usr,
- 'PAY_ID': expense.paymentMethod,
- 'PRT_SW': 'N',
- 'USR': HostAppChannel.usr,
- 'REM': expense.remark,
- 'CUR_ID': expense.currencyCode,
- 'EXC_RTO': 1,
- 'REASON': expense.purpose,
- 'VOH_ID': expense.isGenerateVoucher ? 'T' : 'F',
- },
- 'BodyData1': expense.details.asMap().entries.map((e) {
- final i = e.key;
- final d = e.value;
- return {
- 'ITM': i + 1,
- 'BX_DD': _today(),
- 'ACC_NO': d.acctSubjectId,
- 'AMT': d.totalAmount,
- 'AMTN': d.amount,
- 'AMTN_SH': d.approvedAmount > 0 ? d.approvedAmount : d.totalAmount,
- 'REM': d.remark,
- 'CUST': d.customerVendorId,
- 'IDX_NO': d.expenseCategory,
- 'OBJ_NO': d.projectId.isNotEmpty ? d.projectId : '',
- 'TAX': d.taxAmount,
- 'TAX_RTO': d.taxRate,
- 'DEP': d.costDeptId,
- 'AE_NO': d.aeNo,
- 'AE_DD': d.aeDd,
- 'BNK_NO': d.bankName,
- 'BNK_ID': d.bankAccount,
- 'ACCNAME': d.bankAccountName,
- 'SQ_MAN': d.sqMan.isNotEmpty ? d.sqMan : HostAppChannel.usr,
- };
- }).toList(),
- };
- }
- Widget _buildImportLink() {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final l10n = AppLocalizations.of(context);
- return GestureDetector(
- onTap: () async {
- final result = await GoRouter.of(
- context,
- ).push<List<ImportableItem>>('/expense/import-apply');
- if (result == null || result.isEmpty || !mounted) return;
- // 将选中的导入数据转换为明细,先移除同单号的旧数据
- final controller = ref.read(
- expenseCreateProvider(widget.editId).notifier,
- );
- final aeNos = result.map((e) => e.aeNo).toSet();
- for (final aeNo in aeNos) {
- controller.removeDetailsByAeNo(aeNo);
- }
- final now = DateTime.now();
- for (final item in result) {
- controller.addDetail(
- ExpenseDetailModel(
- id: '${now.millisecondsSinceEpoch}_${item.itm}',
- expenseId: '',
- expenseApplyId: '',
- expenseApplyNo: item.aeNo,
- expenseApplyDate: item.aeDd.isNotEmpty
- ? DateTime.tryParse(item.aeDd)
- : null,
- expenseCategory: item.typeNo,
- categoryName: item.typeName,
- purpose: item.rem,
- priority: item.priority,
- projectId: item.objNo,
- projectName: item.objName,
- costDeptId: item.dep,
- costDeptName: item.depName,
- acctSubjectId: item.accNo,
- acctSubjectName: item.accName,
- amount: item.amtnYj,
- taxRate: 0,
- taxAmount: 0,
- totalAmount: item.amtnYj,
- currencyCode: '',
- exchangeRate: 1.0,
- baseAmount: item.amtnYj,
- approvedAmount: item.amtnYj,
- customerVendorId: '',
- customerVendorName: '',
- bankName: '',
- bankAccountName: '',
- bankAccount: '',
- remark: item.rem,
- sortOrder: item.itm,
- attachments: const [],
- sqMan: item.sqMan,
- sqManName: item.sqName,
- aeNo: item.aeNo,
- aeDd: item.aeDd,
- createTime: now,
- updateTime: now,
- ),
- );
- }
- controller.recalculateAmount();
- TDToast.showSuccess(l10n.get('importSuccess'), context: context);
- _scrollToDetailSection();
- },
- child: Container(
- height: 44,
- decoration: BoxDecoration(
- color: colors.primaryLight,
- borderRadius: BorderRadius.circular(8),
- ),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Icon(Icons.download, size: 14, color: colors.primary),
- const SizedBox(width: 8),
- Text(
- l10n.get('importApprovedPreApp'),
- style: TextStyle(
- fontSize: AppFontSizes.body,
- color: colors.primary,
- ),
- ),
- ],
- ),
- ),
- );
- }
- Widget _buildBasicInfoSection(
- ExpenseCreateController controller,
- ExpenseCreateState state,
- ) {
- final l10n = AppLocalizations.of(context);
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final expense = state.expense;
- return FormSection(
- title: l10n.get('basicInfo'),
- leadingIcon: Icons.info_outline,
- children: [
- FormFieldRow(
- label: l10n.get('date'),
- value: _today(),
- readOnly: true,
- showArrow: false,
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('expensePersonnel'),
- value:
- HostAppChannel.usr.isNotEmpty && HostAppChannel.usrName.isNotEmpty
- ? '${HostAppChannel.usr}/${HostAppChannel.usrName}'
- : '--',
- readOnly: true,
- showArrow: false,
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('expenseDept'),
- value: _selectedDeptName.isNotEmpty
- ? '$_selectedDeptId/$_selectedDeptName'
- : null,
- hint: l10n.get('pleaseSelect'),
- onTap: _refDataLoading ? null : () => _showDeptPicker(),
- ),
- const SizedBox(height: 16),
- _label(l10n.get('expenseReason'), required: true),
- const SizedBox(height: 8),
- TDTextarea(
- controller: _purposeController,
- focusNode: _purposeFocus,
- hintText: l10n.get('enterExpenseReason'),
- maxLines: 4,
- minLines: 1,
- maxLength: 500,
- indicator: true,
- padding: EdgeInsets.zero,
- bordered: true,
- backgroundColor: colors.bgPage,
- onChanged: (_) => controller.updatePurpose(_purposeController.text),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('paymentMethod'),
- value: expense.paymentMethod,
- hint: l10n.get('pleaseEnter'),
- onTap: () => _showTextInput(
- l10n.get('paymentMethod'),
- (v) => controller.updatePaymentMethod(v),
- initialText: expense.paymentMethod,
- ),
- onClear: () => controller.updatePaymentMethod(''),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('currency'),
- value: expense.currencyCode.isNotEmpty
- ? _currencyLabel(expense.currencyCode)
- : null,
- hint: l10n.get('selectCurrency'),
- onTap: () => _showCurrencyPicker(controller, expense.currencyCode),
- onClear: () => controller.updateCurrencyCode(''),
- ),
- const SizedBox(height: 16),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(l10n.get('generateVoucher'), style: TextStyle(fontSize: AppFontSizes.subtitle, color: colors.textSecondary)),
- TDSwitch(
- isOn: expense.isGenerateVoucher,
- onChanged: (v) {
- controller.setGenerateVoucher(v);
- return v;
- },
- ),
- ],
- ),
- const SizedBox(height: 16),
- _label(l10n.get('remark')),
- const SizedBox(height: 8),
- TDTextarea(
- controller: _remarkController,
- focusNode: _remarkFocus,
- hintText: l10n.get('enterRemark'),
- maxLines: 3,
- minLines: 1,
- maxLength: 500,
- indicator: true,
- padding: EdgeInsets.zero,
- bordered: true,
- backgroundColor: colors.bgPage,
- onChanged: (_) => controller.updateRemark(_remarkController.text),
- ),
- ],
- );
- }
- Widget _buildDetailSection(
- ExpenseCreateController controller,
- ExpenseCreateState state,
- ) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final l10n = AppLocalizations.of(context);
- final totalApproved = state.expense.details.fold<double>(
- 0,
- (sum, d) => sum + d.approvedAmount,
- );
- return FormSection(
- title: l10n.get('expenseDetails'),
- leadingIcon: Icons.receipt_long_outlined,
- showAction: true,
- actionText: l10n.get('add'),
- onActionTap: () => _showAddDetailDialog(controller),
- children: [
- if (state.expense.details.isEmpty)
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 8),
- child: Text(
- l10n.get('noDetailHint'),
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.textPlaceholder,
- ),
- ),
- )
- else
- ...state.expense.details.asMap().entries.map((entry) {
- final d = entry.value;
- return GestureDetector(
- onTap: () =>
- _showAddDetailDialog(controller, editIndex: entry.key),
- child: Container(
- margin: const EdgeInsets.symmetric(vertical: 6),
- padding: const EdgeInsets.all(12),
- decoration: BoxDecoration(
- color: colors.bgPage,
- borderRadius: BorderRadius.circular(8),
- ),
- child: Row(
- children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Expanded(
- child: Text(
- d.categoryName.isNotEmpty
- ? '${d.expenseCategory}/${d.categoryName}'
- : d.expenseCategory,
- style: TextStyle(
- fontSize: AppFontSizes.body,
- fontWeight: FontWeight.w500,
- color: colors.textPrimary,
- ),
- ),
- ),
- Column(
- crossAxisAlignment: CrossAxisAlignment.end,
- children: [
- Text(
- '¥${d.totalAmount.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.body,
- fontWeight: FontWeight.w600,
- color: colors.amountPrimary,
- ),
- ),
- if (d.approvedAmount > 0)
- Text(
- '¥${d.approvedAmount.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.body,
- fontWeight: FontWeight.w600,
- color: colors.success,
- ),
- ),
- ],
- ),
- ],
- ),
- const SizedBox(height: 2),
- Text(
- '${l10n.get('amountExcludingTax')}: ¥${d.amount.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.taxAmount > 0)
- Text(
- '${l10n.get('taxAmount')}: ¥${d.taxAmount.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.acctSubjectName.isNotEmpty)
- Text(
- '${l10n.get('acctSubject')}: ${d.acctSubjectId}/${d.acctSubjectName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.aeNo.isNotEmpty)
- Text(
- '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.aeDd.isNotEmpty)
- Text(
- '${l10n.get('applyDate')}: ${d.aeDd}',
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.projectName.isNotEmpty)
- Text(
- '${l10n.get('project')}: ${d.projectId}/${d.projectName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.costDeptName.isNotEmpty)
- Text(
- '${l10n.get('dept')}: ${d.costDeptId}/${d.costDeptName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.customerVendorName.isNotEmpty)
- Text(
- '${l10n.get('customerVendor')}: ${d.customerVendorId}/${d.customerVendorName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.bankAccountName.isNotEmpty)
- Text(
- '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.bankName.isNotEmpty)
- Text(
- '${l10n.get('bankName')}: ${d.bankName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.bankAccount.isNotEmpty)
- Text(
- '${l10n.get('bankAccount')}: ${d.bankAccount}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.sqManName.isNotEmpty)
- Text(
- '${l10n.get('applicant')}: ${d.sqManName.isNotEmpty ? d.sqManName : d.sqMan}',
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- if (d.remark.isNotEmpty)
- Text(
- '${l10n.get('remark')}: ${d.remark}',
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- ],
- ),
- ),
- const SizedBox(width: 8),
- GestureDetector(
- onTap: () {
- controller.removeDetail(entry.key);
- controller.recalculateAmount();
- },
- child: Icon(
- Icons.close,
- size: 18,
- color: colors.textSecondary,
- ),
- ),
- ],
- ),
- ),
- );
- }),
- const SizedBox(height: 8),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l10n.get('totalExpense'),
- style: TextStyle(
- fontSize: AppFontSizes.body,
- fontWeight: FontWeight.w600,
- color: colors.textPrimary,
- ),
- ),
- Text(
- '¥${state.expense.totalAmount.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- fontWeight: FontWeight.w700,
- color: colors.amountPrimary,
- ),
- ),
- ],
- ),
- const SizedBox(height: 4),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l10n.get('approvedTotal'),
- style: TextStyle(
- fontSize: AppFontSizes.body,
- fontWeight: FontWeight.w600,
- color: colors.textPrimary,
- ),
- ),
- Text(
- '¥${totalApproved.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- fontWeight: FontWeight.w700,
- color: totalApproved > 0 ? colors.success : colors.textPrimary,
- ),
- ),
- ],
- ),
- ],
- );
- }
- Future<void> _checkAttachHealth() async {
- if (mounted) setState(() => _attachAvailable = false);
- try {
- final api = ref.read(expenseApiProvider);
- final ok = await api.checkAttachHealth();
- if (mounted) setState(() => _attachAvailable = ok);
- } catch (_) {
- if (mounted) setState(() => _attachAvailable = false);
- }
- }
- Widget _buildAttachmentSection(
- ExpenseCreateController controller,
- ExpenseCreateState state,
- ) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final l10n = AppLocalizations.of(context);
- final children = <Widget>[];
- if (!_attachAvailable) {
- children.add(Text(l10n.get('attachServiceUnavailable'),
- style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textPlaceholder)));
- } else {
- children.addAll([
- Text(l10n.get('maxAttachment'),
- style: TextStyle(fontSize: AppFontSizes.caption, color: colors.textPlaceholder)),
- const SizedBox(height: 8),
- ]);
- }
- return FormSection(
- title: l10n.get('attachmentUpload'),
- leadingIcon: Icons.attach_file_outlined,
- children: [
- ...children,
- if (_attachAvailable)
- AttachmentPicker(
- controller: _attachmentController,
- maxImageSizeMB: 10,
- maxFileSizeMB: 20,
- allowedExtensions: const [
- 'pdf',
- 'doc',
- 'docx',
- 'xls',
- 'xlsx',
- 'ppt',
- 'pptx',
- 'txt',
- ],
- onFileRejected: (file, reason) {
- if (context.mounted) TDToast.showText(reason, context: context);
- },
- ),
- ],
- );
- }
- Widget _buildBottomButtons(
- ExpenseCreateController controller,
- ExpenseCreateState state,
- ) {
- final l10n = AppLocalizations.of(context);
- return ActionBar(
- showLeft: false,
- centerLabel: l10n.get('saveDraft'),
- rightLabel: l10n.get('submit'),
- centerTextOnly: true,
- onCenterTap: () async {
- if (state.isSubmitting) return;
- controller.updateAttachments(_attachmentController.toPathList());
- controller.updateDept(_selectedDeptId, _selectedDeptName);
- final ok = await controller.saveDraft();
- if (mounted) {
- if (ok) {
- _forcePop();
- } else {
- TDToast.showFail(l10n.get('saveFailed'), context: context);
- }
- }
- },
- onRightTap: () async {
- if (state.isSubmitting) return;
- final err = _validate(l10n, state);
- if (err.isNotEmpty) {
- TDToast.showText(err.first, context: context);
- return;
- }
- LoadingDialog.show(context, text: l10n.get('submitting'));
- try {
- final data = _buildSubmitData(state);
- final api = ref.read(expenseApiProvider);
- final billNo = await api.submit(data);
- // 上传附件(billNo 提取失败则跳过,不影响主流程)
- if (billNo != null) {
- final now = DateTime.now();
- final effDd = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} '
- '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}.'
- '${now.millisecond.toString().padLeft(3, '0')}';
- final usr = HostAppChannel.usr;
- // 表头附件
- for (var i = 0; i < _attachmentController.files.length; i++) {
- final file = _attachmentController.files[i];
- try {
- await api.uploadAttachment(file.path, {
- 'BIL_ID': 'BX',
- 'BIL_NO': billNo,
- 'SRCITM': 0,
- 'ITM': i + 1,
- 'TAG': 1,
- 'EFF_DD': effDd,
- 'USR': usr,
- 'FILENAME': file.name,
- 'EXT': file.name.split('.').last,
- });
- } catch (_) {
- // Attachment upload failure is non-fatal
- }
- }
- // 明细附件
- for (var i = 0; i < state.expense.details.length; i++) {
- final detail = state.expense.details[i];
- if (detail.attachments.isEmpty) continue;
- for (var j = 0; j < detail.attachments.length; j++) {
- final file = File(detail.attachments[j]);
- try {
- if (!await file.exists()) continue;
- final fileName = file.path.split('/').last;
- await api.uploadAttachment(file.path, {
- 'BIL_ID': 'BX',
- 'BIL_NO': billNo,
- 'SRCITM': i + 1,
- 'ITM': j + 1,
- 'TAG': 1,
- 'EFF_DD': effDd,
- 'USR': usr,
- 'FILENAME': fileName,
- 'EXT': fileName.split('.').last,
- });
- } catch (_) {
- // Detail attachment upload failure is non-fatal
- }
- }
- }
- }
- await ExpenseCreateController.deleteDraft();
- if (mounted) {
- LoadingDialog.hide(context);
- TDToast.showSuccess(
- l10n.get('submittedAwaitingApproval'),
- context: context,
- );
- GoRouter.of(context).go('/expense/list');
- }
- } catch (_) {
- if (mounted) {
- LoadingDialog.hide(context);
- TDToast.showFail(l10n.get('submitFailedRetry'), context: context);
- }
- }
- },
- );
- }
- Future<void> _showAddDetailDialog(
- ExpenseCreateController controller, {
- int? editIndex,
- }) async {
- if (_addingDetail) return;
- _addingDetail = true;
- try {
- final l10n = AppLocalizations.of(context);
- if (_costTypes.isEmpty) {
- TDToast.showText(l10n.get('noCostTypeData'), context: context);
- return;
- }
- final state = controller.currentState;
- ExpenseDetailInputData? initialData;
- if (editIndex != null) {
- final d = state.expense.details[editIndex];
- initialData = ExpenseDetailInputData(
- category: d.expenseCategory,
- categoryName: d.categoryName,
- acctSubjectId: d.acctSubjectId,
- acctSubjectName: d.acctSubjectName,
- purpose: d.purpose,
- amount: d.amount,
- taxRate: d.taxRate,
- projectId: d.projectId,
- projectName: d.projectName,
- costDeptId: d.costDeptId,
- costDeptName: d.costDeptName,
- customerVendorId: d.customerVendorId,
- customerVendorName: d.customerVendorName,
- approvedAmount: d.approvedAmount,
- bankName: d.bankName,
- bankAccountName: d.bankAccountName,
- bankAccount: d.bankAccount,
- remark: d.remark,
- attachmentPaths: d.attachments,
- sqMan: d.sqMan,
- sqManName: d.sqManName,
- aeNo: d.aeNo,
- aeDd: d.aeDd,
- );
- }
- final result = await ExpenseDetailDialog.show(
- context,
- categories: _dialogCategories,
- projects: _dialogProjects,
- costDepts: _dialogCostDepts,
- customers: _dialogCustomers,
- employees: _dialogEmployees,
- l10n: l10n,
- initialData: initialData,
- checkAttachHealth: () => ref.read(expenseApiProvider).checkAttachHealth(),
- );
- if (result != null && mounted) {
- final now = DateTime.now();
- final detail = ExpenseDetailModel(
- id: editIndex != null
- ? state.expense.details[editIndex].id
- : now.millisecondsSinceEpoch.toString(),
- expenseId: '',
- expenseCategory: result.category,
- categoryName: result.categoryName,
- purpose: result.purpose,
- amount: result.taxRate > 0
- ? result.amount / (1 + result.taxRate)
- : result.amount,
- taxRate: result.taxRate,
- taxAmount: result.taxRate > 0
- ? result.amount - result.amount / (1 + result.taxRate)
- : 0,
- totalAmount: result.amount,
- projectId: result.projectId,
- projectName: result.projectName,
- costDeptId: result.costDeptId,
- costDeptName: result.costDeptName,
- acctSubjectId: result.acctSubjectId,
- acctSubjectName: result.acctSubjectName,
- customerVendorId: result.customerVendorId,
- customerVendorName: result.customerVendorName,
- approvedAmount: result.approvedAmount,
- bankName: result.bankName,
- bankAccountName: result.bankAccountName,
- bankAccount: result.bankAccount,
- sqMan: result.sqMan,
- sqManName: result.sqManName,
- aeNo: result.aeNo,
- aeDd: result.aeDd,
- remark: result.remark,
- attachments: result.attachmentPaths,
- createTime: now,
- updateTime: now,
- );
- if (editIndex != null) {
- controller.updateDetail(editIndex, detail);
- } else {
- controller.addDetail(detail);
- }
- controller.recalculateAmount();
- }
- } finally {
- _addingDetail = false;
- }
- }
- void _showCurrencyPicker(ExpenseCreateController controller, String cur) {
- if (_currencies.isEmpty) {
- TDToast.showText(
- AppLocalizations.of(context).get('noData'),
- context: context,
- );
- return;
- }
- final l10n = AppLocalizations.of(context);
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final codes = _currencies.map((c) => c.curId).toList();
- final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
- TDPicker.showMultiPicker(
- context,
- title: l10n.get('selectCurrency'),
- backgroundColor: colors.bgCard,
- data: [labels],
- onConfirm: (s) {
- if (s.isNotEmpty && s[0] is int) {
- final i = s[0] as int;
- if (i >= 0 && i < codes.length) {
- Navigator.of(context).pop();
- controller.updateCurrencyCode(codes[i]);
- }
- }
- },
- );
- }
- void _showTextInput(
- String title,
- Function(String) onConfirm, {
- String initialText = '',
- }) {
- FocusScope.of(context).unfocus();
- final l10n = AppLocalizations.of(context);
- final c = TextEditingController(text: initialText);
- showGeneralDialog(
- context: context,
- pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
- textEditingController: c,
- title: title,
- hintText: l10n.get('pleaseEnter'),
- leftBtn: TDDialogButtonOptions(
- title: l10n.get('cancel'),
- action: () => Navigator.pop(ctx),
- ),
- rightBtn: TDDialogButtonOptions(
- title: l10n.get('confirm'),
- action: () {
- onConfirm(c.text);
- Navigator.pop(ctx);
- },
- ),
- ),
- );
- }
- Widget _label(String t, {bool required = false}) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- return Text.rich(
- TextSpan(
- children: [
- TextSpan(
- text: t,
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.textSecondary,
- ),
- ),
- if (required)
- TextSpan(
- text: ' *',
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.danger,
- ),
- ),
- ],
- ),
- );
- }
- List<String> _validate(AppLocalizations l10n, ExpenseCreateState state) {
- final e = <String>[];
- if (_purposeController.text.trim().isEmpty) {
- e.add(l10n.get('enterExpenseReason'));
- }
- if (state.expense.details.isEmpty) {
- e.add(l10n.get('addAtLeastOneDetail'));
- }
- return e;
- }
- bool _hasUnsaved(ExpenseCreateState state) =>
- _purposeController.text.isNotEmpty ||
- state.expense.paymentMethod.isNotEmpty ||
- state.expense.currencyCode.isNotEmpty ||
- _remarkController.text.isNotEmpty ||
- state.expense.details.isNotEmpty ||
- _attachmentController.files.isNotEmpty ||
- _selectedDeptId.isNotEmpty;
- void _doPop() {
- final l10n = AppLocalizations.of(context);
- final state = ref.read(expenseCreateProvider(widget.editId));
- if (_hasUnsaved(state)) {
- _showConfirmDialog(
- l10n.get('confirmExit'),
- l10n.get('unsavedContentWarning'),
- l10n.get('continueEditing'),
- l10n.get('discardAndExit'),
- () async {
- try {
- await ExpenseCreateController.deleteDraft();
- } catch (_) {}
- if (!mounted) return;
- setState(() {
- _selectedDeptId = '';
- _selectedDeptName = '';
- });
- ref.read(expenseCreateProvider(widget.editId).notifier).reset();
- _forcePop();
- },
- );
- } else {
- _forcePop();
- }
- }
- void _forcePop() {
- _isPoppingToNative = true;
- SystemNavigator.pop();
- }
- void _showConfirmDialog(
- String title,
- String content,
- String leftText,
- String rightText,
- VoidCallback onConfirm,
- ) {
- FocusScope.of(context).unfocus();
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- showDialog(
- context: context,
- useRootNavigator: true,
- builder: (ctx) => TDAlertDialog(
- title: title,
- content: content,
- buttonStyle: TDDialogButtonStyle.text,
- leftBtn: TDDialogButtonOptions(
- title: leftText,
- titleColor: colors.primary,
- action: () => Navigator.pop(ctx),
- ),
- rightBtn: TDDialogButtonOptions(
- title: rightText,
- titleColor: colors.danger,
- action: () {
- Navigator.pop(ctx);
- onConfirm();
- },
- ),
- ),
- );
- }
- Widget _buildPageFooter() {
- final l10n = AppLocalizations.of(context);
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- return Center(
- child: Padding(
- padding: const EdgeInsets.only(bottom: 16),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(
- Icons.rocket_launch_outlined,
- size: 16,
- color: colors.textPlaceholder,
- ),
- const SizedBox(width: 6),
- Text(
- l10n.get('pageFooter'),
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textPlaceholder,
- ),
- ),
- ],
- ),
- ),
- );
- }
- String _today() {
- final n = DateTime.now();
- return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
- }
- }
|