| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179 |
- import 'dart:async';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- import 'package:flutter_riverpod/flutter_riverpod.dart';
- import 'package:go_router/go_router.dart';
- import 'package:tdesign_flutter/tdesign_flutter.dart';
- import '../../core/i18n/app_localizations.dart';
- import '../../core/navigation/host_app_channel.dart';
- import '../../core/storage/draft_storage.dart';
- import '../../shared/widgets/action_bar.dart';
- import '../../shared/widgets/loading_dialog.dart';
- import '../../shared/widgets/form_section.dart';
- import '../../shared/widgets/form_field_row.dart';
- import '../../shared/widgets/nav_bar_config.dart';
- import '../../shared/widgets/attachment_picker.dart';
- import '../../core/theme/app_colors.dart';
- import '../../core/theme/app_colors_extension.dart';
- import '../../core/constants/enums.dart';
- import '../../core/data/mock_api_data.dart';
- import 'expense_apply_api.dart';
- import 'widgets/expense_apply_detail_dialog.dart';
- class ExpenseApplyCreatePage extends ConsumerStatefulWidget {
- final String? id;
- const ExpenseApplyCreatePage({super.key, this.id});
- @override
- ConsumerState<ExpenseApplyCreatePage> createState() =>
- _ExpenseApplyCreatePageState();
- }
- class _ExpenseApplyCreatePageState
- extends ConsumerState<ExpenseApplyCreatePage>
- with WidgetsBindingObserver {
- static const _draftKey = 'expense_apply';
- // ── 基本信息 ──
- String _urgency = Urgency.normal.value;
- final _purposeController = TextEditingController();
- final _purposeFocus = FocusNode();
- String _validUntil = '';
- final _referenceNoController = TextEditingController();
- final _remarkController = TextEditingController();
- final _remarkFocus = FocusNode();
- final _scrollCtrl = ScrollController();
- // ── 费用明细 ──
- final List<_DetailItem> _details = [];
- int _detailIdCounter = 1;
- // ── 附件 ──
- 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 = [];
- 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 = [];
- _refDataLoading = true;
- _refDataFuture = null;
- _draftFuture = DraftStorage.has(_draftKey);
- _loadRefData();
- }
- Future<void>? _refDataFuture;
- Future<void> _loadRefData({bool showLoading = false}) async {
- if (_refDataFuture != null) return _refDataFuture!;
- final completer = Completer<void>();
- _refDataFuture = completer.future;
- if (showLoading) {
- LoadingDialog.show(context, text: AppLocalizations.of(context).get('dataLoading'));
- }
- try {
- final api = ref.read(expenseApplyApiProvider);
- final results = await Future.wait([
- api.getCostTypes(),
- api.getProjectCodes(),
- api.getDepartments(),
- ]);
- if (!mounted) return;
- setState(() {
- _costTypes = results[0] as List<CostTypeItem>;
- _projects = results[1] as List<ProjectCodeItem>;
- _departments = results[2] as List<DepartmentItem>;
- _refDataLoading = false;
- _autoSelectDept();
- });
- completer.complete();
- } catch (_) {
- if (!mounted) { completer.complete(); return; }
- setState(() => _refDataLoading = false);
- completer.complete();
- } finally {
- if (showLoading && mounted) LoadingDialog.hide(context);
- _refDataFuture = null;
- }
- }
- 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 _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();
- _referenceNoController.dispose();
- _remarkController.dispose();
- _remarkFocus.dispose();
- _attachmentController.dispose();
- _scrollCtrl.dispose();
- super.dispose();
- }
- @override
- void didChangeAppLifecycleState(AppLifecycleState state) {
- if (state == AppLifecycleState.resumed && _isPoppingToNative) {
- _isPoppingToNative = false;
- HostAppChannel.refresh();
- // 重置表单数据
- _urgency = Urgency.normal.value;
- _purposeController.clear();
- _validUntil = '';
- _referenceNoController.clear();
- _remarkController.clear();
- _details.clear();
- _detailIdCounter = 1;
- _attachmentController.clear();
- _attachAvailable = false;
- _addingDetail = false;
- _selectedDeptId = '';
- _selectedDeptName = '';
- // 重置参考数据
- _costTypes = []; _projects = []; _departments = [];
- _refDataFuture = null;
- _refDataLoading = true;
- // 重置草稿状态
- _draftHandled = false;
- _draftFuture = DraftStorage.has(_draftKey);
- // 重新加载
- _loadRefData();
- _checkAttachHealth();
- }
- }
- @override
- Widget build(BuildContext context) {
- final l10n = AppLocalizations.of(context);
- setNavBarTitle(context, ref, NavBarConfig(
- title: l10n.get('expenseApplyRequest'),
- showBack: true,
- onBack: () => _doPop(),
- ));
- 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 PopScope(
- canPop: false,
- onPopInvokedWithResult: (didPop, _) {
- if (didPop) return;
- _doPop();
- },
- child: Column(
- children: [
- Expanded(
- child: GestureDetector(
- onTap: () => FocusScope.of(context).unfocus(),
- child: SingleChildScrollView(
- controller: _scrollCtrl,
- padding: const EdgeInsets.all(16),
- child: Column(
- children: [
- _buildBasicInfo(l10n),
- const SizedBox(height: 16),
- _buildDetailsSection(l10n),
- const SizedBox(height: 16),
- _buildAttachmentSection(l10n),
- const SizedBox(height: 24),
- _buildPageFooter(),
- ],
- ),
- ),
- ),
- ),
- _buildBottomBar(l10n),
- ],
- ),
- );
- },
- );
- }
- // ═══ 草稿持久化 ═══
- Future<void> _restoreDraft() async {
- final data = await DraftStorage.load(_draftKey);
- if (data == null) return;
- final attData = data['attachments'] as List<dynamic>?;
- if (attData != null) {
- await _attachmentController.restoreFromPaths(attData.cast<String>());
- }
- setState(() {
- _urgency = data['urgency'] as String? ?? Urgency.normal.value;
- _purposeController.text = data['purpose'] as String? ?? '';
- _validUntil = data['validUntil'] as String? ?? '';
- _referenceNoController.text = data['referenceNo'] as String? ?? '';
- _remarkController.text = data['remark'] as String? ?? '';
- _selectedDeptId = data['deptId'] as String? ?? '';
- _selectedDeptName = data['deptName'] as String? ?? '';
- _details.clear();
- final detailList = data['details'] as List<dynamic>?;
- if (detailList != null) {
- for (final d in detailList) {
- final m = d as Map<String, dynamic>;
- _details.add(_DetailItem(
- id: m['id'] as int? ?? _detailIdCounter++,
- category: m['category'] as String? ?? '',
- categoryName: m['categoryName'] as String? ?? '',
- acctSubjectId: m['acctSubjectId'] as String? ?? '',
- acctSubjectName: m['acctSubjectName'] as String? ?? '',
- purpose: m['purpose'] as String? ?? '',
- projectId: m['projectId'] as int? ?? 0,
- projectName: m['projectName'] as String? ?? '',
- costDeptId: m['costDeptId'] as String? ?? '',
- costDeptName: m['costDeptName'] as String? ?? '',
- startDate: m['startDate'] as String? ?? '',
- endDate: m['endDate'] as String? ?? '',
- estimatedAmount: (m['estimatedAmount'] as num?)?.toDouble() ?? 0,
- remark: m['remark'] as String? ?? '',
- ));
- }
- }
- _detailIdCounter = _details.isEmpty ? 1 : _details.map((d) => d.id).reduce((a, b) => a > b ? a : b) + 1;
- });
- }
- Future<void> _saveDraftToStorage() async {
- final detailList = _details.map((d) => {
- 'id': d.id,
- 'category': d.category,
- 'categoryName': d.categoryName,
- 'acctSubjectId': d.acctSubjectId,
- 'acctSubjectName': d.acctSubjectName,
- 'purpose': d.purpose,
- 'projectId': d.projectId,
- 'projectName': d.projectName,
- 'costDeptId': d.costDeptId,
- 'costDeptName': d.costDeptName,
- 'startDate': d.startDate,
- 'endDate': d.endDate,
- 'estimatedAmount': d.estimatedAmount,
- 'remark': d.remark,
- }).toList();
- await DraftStorage.save(_draftKey, {
- 'urgency': _urgency,
- 'purpose': _purposeController.text,
- 'deptId': _selectedDeptId,
- 'deptName': _selectedDeptName,
- 'validUntil': _validUntil,
- 'referenceNo': _referenceNoController.text,
- 'remark': _remarkController.text,
- 'attachments': _attachmentController.toPathList(),
- 'details': detailList,
- });
- }
- // ═══ 草稿弹窗 ═══
- // 使用 showDialog 而非内联渲染,确保 TDAlertDialog 获取正确的主题上下文
- 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);
- DraftStorage.delete(_draftKey);
- },
- ),
- rightBtn: TDDialogButtonOptions(
- title: l10n.get('restore'),
- titleColor: colors.primary,
- action: () {
- Navigator.pop(ctx);
- _restoreDraft();
- },
- ),
- ),
- );
- }
- // ═══ 1. 基本信息 ═══
- Widget _buildBasicInfo(AppLocalizations l10n) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- 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('applicant'),
- value: HostAppChannel.usr.isNotEmpty && HostAppChannel.usrName.isNotEmpty
- ? '${HostAppChannel.usr}/${HostAppChannel.usrName}'
- : '--',
- readOnly: true,
- showArrow: false,
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('applyDept'),
- value: _selectedDeptId.isNotEmpty ? '$_selectedDeptId/$_selectedDeptName' : '',
- hint: l10n.get('pleaseSelect'),
- onTap: _refDataLoading ? null : () => _showDeptPicker(),
- ),
- const SizedBox(height: 16),
- _buildUrgencyRow(l10n),
- const SizedBox(height: 16),
- _label(l10n.get('applyReason'), required: true),
- const SizedBox(height: 8),
- TDTextarea(
- controller: _purposeController,
- focusNode: _purposeFocus,
- hintText: l10n.get('enterApplyReason'),
- maxLines: 4,
- minLines: 1,
- maxLength: 500,
- indicator: true,
- padding: EdgeInsets.zero,
- bordered: true,
- backgroundColor: colors.bgPage,
- ),
- // TODO: 暂不支持录入,后续开放
- // const SizedBox(height: 16),
- // FormFieldRow(
- // label: l10n.get('validUntil'),
- // value: _validUntil,
- // hint: l10n.get('pleaseSelect'),
- // onTap: () => _pickDate((d) => setState(() => _validUntil = d)),
- // ),
- // const SizedBox(height: 16),
- // FormFieldRow(
- // label: l10n.get('relatedContractNo'),
- // value: _referenceNoController.text,
- // hint: l10n.get('optional'),
- // onTap: () => _showTextInput(
- // l10n.get('relatedContractNo'),
- // (v) => setState(() {
- // _referenceNoController.text = v;
- // _referenceNoController.selection = TextSelection.fromPosition(
- // TextPosition(offset: v.length),
- // );
- // }),
- // initialText: _referenceNoController.text,
- // ),
- // ),
- 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,
- ),
- ],
- );
- }
- Widget _buildUrgencyRow(AppLocalizations l10n) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- return Row(
- children: [
- Text.rich(
- TextSpan(
- children: [
- TextSpan(
- text: l10n.get('emergencyLevel'),
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.textSecondary,
- ),
- ),
- TextSpan(
- text: ' *',
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.danger,
- ),
- ),
- ],
- ),
- ),
- const Spacer(),
- Row(
- mainAxisSize: MainAxisSize.min,
- children: Urgency.values.asMap().entries.map((e) {
- final sel = _urgency == e.value.value;
- final isCritical = e.value.value == Urgency.critical.value;
- final isUrgent = e.value.value == Urgency.urgent.value;
- final activeColor = isCritical ? colors.danger : isUrgent ? colors.warning : colors.primary;
- return Padding(
- padding: EdgeInsets.only(left: e.key > 0 ? 18 : 0),
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: () => setState(() => _urgency = e.value.value),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Container(
- width: 18,
- height: 18,
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- border: Border.all(
- color: sel ? activeColor : colors.textPlaceholder,
- width: 2,
- ),
- ),
- child: sel
- ? Center(
- child: Container(
- width: 8,
- height: 8,
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- color: activeColor,
- ),
- ),
- )
- : null,
- ),
- const SizedBox(width: 5),
- Text(
- l10n.get(e.value.labelKey),
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: sel ? activeColor : colors.textPrimary,
- ),
- ),
- ],
- ),
- ),
- );
- }).toList(),
- ),
- ],
- );
- }
- // ═══ 2. 费用明细 ═══
- Widget _buildDetailsSection(AppLocalizations l10n) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- return FormSection(
- title: l10n.get('expenseDetails'),
- leadingIcon: Icons.receipt_long_outlined,
- showAction: true,
- actionText: l10n.get('add'),
- onActionTap: _showDetailDialog,
- children: [
- if (_details.isEmpty)
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 8),
- child: Text(
- l10n.get('noDetailHint'),
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.textPlaceholder,
- ),
- ),
- )
- else
- ..._details.asMap().entries.map((e) {
- final d = e.value;
- return GestureDetector(
- onTap: () => _showDetailDialog(editIndex: e.key),
- child: Container(
- margin: const EdgeInsets.symmetric(vertical: 8),
- padding: const EdgeInsets.all(12),
- decoration: BoxDecoration(
- color: colors.bgPage,
- borderRadius: BorderRadius.circular(8),
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Expanded(
- child: Text(
- '${d.category}/${d.categoryName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.textPrimary,
- ),
- ),
- ),
- const SizedBox(width: 12),
- Text(
- '¥${d.estimatedAmount.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- fontWeight: FontWeight.w600,
- color: colors.amountPrimary,
- ),
- ),
- ],
- ),
- if (d.acctSubjectId.isNotEmpty && d.acctSubjectName.isNotEmpty) ...[
- const SizedBox(height: 4),
- Text(
- '${d.acctSubjectId}/${d.acctSubjectName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- ],
- if (d.projectId > 0 && d.projectName.isNotEmpty) ...[
- const SizedBox(height: 4),
- Text(
- '${d.projectId}/${d.projectName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- ],
- if (d.costDeptId.isNotEmpty && d.costDeptName.isNotEmpty) ...[
- const SizedBox(height: 4),
- Text(
- '${d.costDeptId}/${d.costDeptName}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- ],
- if (d.startDate.isNotEmpty && d.endDate.isNotEmpty) ...[
- const SizedBox(height: 4),
- Text(
- '${d.startDate} ~ ${d.endDate}',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- ],
- if (d.remark.isNotEmpty) ...[
- const SizedBox(height: 4),
- Text(
- d.remark,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- ],
- ],
- ),
- ),
- const SizedBox(width: 8),
- GestureDetector(
- onTap: () => setState(() => _details.removeAt(e.key)),
- child: Icon(
- Icons.close,
- size: 18,
- color: colors.textSecondary,
- ),
- ),
- ],
- ),
- ),
- );
- }),
- const SizedBox(height: 8),
- Container(
- height: 36,
- padding: const EdgeInsets.symmetric(vertical: 8),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l10n.get('total'),
- style: TextStyle(
- fontSize: AppFontSizes.body,
- fontWeight: FontWeight.w600,
- color: colors.textPrimary,
- ),
- ),
- Text(
- '¥${_totalAmount().toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- fontWeight: FontWeight.w700,
- color: colors.amountPrimary,
- ),
- ),
- ],
- ),
- ),
- ],
- );
- }
- double _totalAmount() =>
- _details.fold(0, (s, d) => s + d.estimatedAmount);
- Future<void> _showDetailDialog({int? editIndex}) async {
- if (_addingDetail) return;
- _addingDetail = true;
- try {
- final l10n = AppLocalizations.of(context);
- if (_costTypes.isEmpty) {
- await _loadRefData(showLoading: true);
- if (!mounted) return;
- if (_costTypes.isEmpty) {
- TDToast.showText(l10n.get('noCostTypeData'), context: context);
- return;
- }
- }
- ExpenseDetailData? initialData;
- if (editIndex != null) {
- final d = _details[editIndex];
- initialData = ExpenseDetailData(
- category: d.category,
- categoryName: d.categoryName,
- acctSubjectId: d.acctSubjectId,
- acctSubjectName: d.acctSubjectName,
- purpose: d.purpose,
- projectId: d.projectId,
- projectName: d.projectName,
- costDeptId: d.costDeptId,
- costDeptName: d.costDeptName,
- startDate: d.startDate,
- endDate: d.endDate,
- estimatedAmount: d.estimatedAmount,
- remark: d.remark,
- );
- }
- final result = await ExpenseApplyDetailDialog.show(
- // ignore: use_build_context_synchronously
- context,
- categories: _dialogCategories,
- projects: _dialogProjects,
- costDepts: _dialogCostDepts,
- l10n: l10n,
- initialData: initialData,
- );
- if (result != null && mounted) {
- setState(() {
- final item = _DetailItem(
- id: editIndex != null ? _details[editIndex].id : _detailIdCounter++,
- category: result.category,
- categoryName: result.categoryName,
- acctSubjectId: result.acctSubjectId,
- acctSubjectName: result.acctSubjectName,
- purpose: result.purpose,
- projectId: result.projectId,
- projectName: result.projectName,
- costDeptId: result.costDeptId,
- costDeptName: result.costDeptName,
- startDate: result.startDate,
- endDate: result.endDate,
- estimatedAmount: result.estimatedAmount,
- remark: result.remark,
- );
- if (editIndex != null) {
- _details[editIndex] = item;
- } else {
- _details.add(item);
- }
- });
- }
- } finally {
- _addingDetail = false;
- }
- }
- // ═══ 3. 附件上传 ═══
- Future<void> _checkAttachHealth() async {
- // 立即设为 false,等待 API 返回后再更新,避免缓存旧值
- if (mounted) setState(() => _attachAvailable = false);
- try {
- final api = ref.read(expenseApplyApiProvider);
- final ok = await api.checkAttachHealth();
- if (mounted) setState(() => _attachAvailable = ok);
- } catch (_) {
- if (mounted) setState(() => _attachAvailable = false);
- }
- }
- Widget _buildAttachmentSection(AppLocalizations l10n) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- 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);
- }
- },
- ),
- ],
- );
- }
- 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('applyDept'),
- 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;
- });
- }
- }
- },
- );
- }
- // ═══ 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();
- // ═══ 4. 底部操作栏 ═══
- Widget _buildBottomBar(AppLocalizations l10n) {
- return ActionBar(
- showLeft: false,
- centerLabel: l10n.get('saveDraft'),
- rightLabel: l10n.get('submit'),
- centerTextOnly: true,
- onCenterTap: () async {
- FocusScope.of(context).unfocus();
- try {
- await _saveDraftToStorage();
- if (mounted) _forcePop();
- } catch (_) {
- if (mounted) {
- TDToast.showFail(l10n.get('saveFailed'), context: context);
- }
- }
- },
- onRightTap: () async {
- final err = _validate(l10n);
- if (err.isNotEmpty) {
- TDToast.showText(err.first, context: context);
- return;
- }
- FocusScope.of(context).unfocus();
- LoadingDialog.show(context, text: l10n.get('submitting'));
- try {
- final data = _buildSubmitData();
- final api = ref.read(expenseApplyApiProvider);
- final billNo = await api.submit(data);
- // 上传表头附件(billNo 提取失败则跳过,不影响主流程)
- if (billNo != null && _attachmentController.files.isNotEmpty) {
- 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': 'AE',
- '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
- }
- }
- }
- await DraftStorage.delete(_draftKey);
- if (mounted) {
- LoadingDialog.hide(context);
- TDToast.showSuccess(l10n.get('submittedAwaitingApproval'), context: context);
- GoRouter.of(context).go('/expense-apply/list');
- }
- } catch (_) {
- if (mounted) {
- LoadingDialog.hide(context);
- TDToast.showFail(l10n.get('submitFailedRetry'), context: context);
- }
- }
- },
- );
- }
- Map<String, dynamic> _buildSubmitData() {
- // 紧急程度映射:normal→1, urgent→2, critical→3
- String priority;
- switch (_urgency) {
- case 'urgent':
- priority = '2';
- break;
- case 'critical':
- priority = '3';
- break;
- default:
- priority = '1';
- }
- return {
- 'HeadData': {
- 'AE_DD': _today(),
- 'PRIORITY': priority,
- 'AMTN_YJ': _totalAmount(),
- 'REASON': _purposeController.text.trim(),
- 'REM': _remarkController.text,
- 'DEP': _selectedDeptId,
- 'USR': HostAppChannel.usr,
- },
- 'BodyData1': _details.asMap().entries.map((e) {
- final i = e.key;
- final d = e.value;
- return {
- 'ITM': i + 1,
- 'SQ_MAN': HostAppChannel.usr,
- 'TYPE_NO': d.category,
- 'AMTN_YJ': d.estimatedAmount,
- 'ACC_NO': d.acctSubjectId,
- 'ACC_NAME': d.acctSubjectName,
- 'DEP': d.costDeptId,
- 'OBJ_NO': d.projectId > 0 ? d.projectId.toString() : '',
- 'START_DD': d.startDate,
- 'END_DD': d.endDate,
- 'REM': d.remark.isNotEmpty ? d.remark : d.purpose,
- };
- }).toList(),
- };
- }
- List<String> _validate(AppLocalizations l10n) {
- final e = <String>[];
- if (_purposeController.text.trim().isEmpty) {
- e.add(l10n.get('enterApplyReason'));
- }
- if (_details.isEmpty) e.add(l10n.get('addAtLeastOneDetail'));
- return e;
- }
- void _doPop() {
- if (_hasUnsaved()) {
- final l10n = AppLocalizations.of(context);
- _showConfirmDialog(
- l10n.get('confirmExit'),
- l10n.get('unsavedContentWarning'),
- l10n.get('continueEditing'),
- l10n.get('discardAndExit'),
- () async {
- await DraftStorage.delete(_draftKey);
- if (!mounted) return;
- setState(() => _clearLocalState());
- _forcePop();
- },
- );
- } else {
- _forcePop();
- }
- }
- void _forcePop() {
- _isPoppingToNative = true;
- SystemNavigator.pop();
- }
- bool _hasUnsaved() =>
- _purposeController.text.isNotEmpty ||
- _details.isNotEmpty ||
- _attachmentController.files.isNotEmpty ||
- _referenceNoController.text.isNotEmpty ||
- _remarkController.text.isNotEmpty ||
- _urgency != Urgency.normal.value ||
- _validUntil.isNotEmpty ||
- _selectedDeptId.isNotEmpty;
- void _clearLocalState() {
- _urgency = Urgency.normal.value;
- _purposeController.clear();
- _validUntil = '';
- _referenceNoController.clear();
- _remarkController.clear();
- _details.clear();
- _detailIdCounter = 1;
- _attachmentController.clear();
- _selectedDeptId = '';
- _selectedDeptName = '';
- }
- void _unfocus() => FocusScope.of(context).unfocus();
- // ═══ 通用弹窗方法 ═══
- void _showConfirmDialog(
- String title,
- String content,
- String leftText,
- String rightText,
- VoidCallback onConfirm,
- ) {
- _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();
- },
- ),
- ),
- );
- }
- // TODO: 有效期至 / 关联合同号 暂不支持,方法暂时注释
- // void _showTextInput(
- // String title,
- // Function(String) onConfirm, {
- // String initialText = '',
- // }) {
- // ...
- // }
- // void _pickDate(Function(String) onPick) {
- // ...
- // }
- 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,
- ),
- ),
- ],
- ),
- );
- }
- 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')}';
- }
- }
- class _DetailItem {
- final int id;
- final String category;
- final String categoryName;
- final String acctSubjectId;
- final String acctSubjectName;
- final String purpose;
- final int projectId;
- final String projectName;
- final String costDeptId;
- final String costDeptName;
- final String startDate;
- final String endDate;
- final double estimatedAmount;
- final String remark;
- const _DetailItem({
- required this.id,
- required this.category,
- required this.categoryName,
- required this.acctSubjectId,
- required this.acctSubjectName,
- required this.purpose,
- required this.projectId,
- required this.projectName,
- required this.costDeptId,
- required this.costDeptName,
- required this.startDate,
- required this.endDate,
- required this.estimatedAmount,
- required this.remark,
- });
- }
|