| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242 |
- import 'package:flutter/material.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 '../../shared/widgets/action_bar.dart';
- import '../../shared/widgets/form_section.dart';
- import '../../shared/widgets/form_field_row.dart';
- import '../../shared/widgets/nav_bar_config.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 'widgets/expense_detail_dialog.dart';
- class ExpenseApplicationApplyPage extends ConsumerStatefulWidget {
- final String? id;
- const ExpenseApplicationApplyPage({super.key, this.id});
- @override
- ConsumerState<ExpenseApplicationApplyPage> createState() =>
- _ExpenseApplicationApplyPageState();
- }
- class _ExpenseApplicationApplyPageState
- extends ConsumerState<ExpenseApplicationApplyPage> {
- // ── 基本信息 ──
- String _urgency = Urgency.normal.value;
- final Set<String> _expenseTypes = {};
- bool _isTaxIncluded = false;
- final _purposeController = TextEditingController();
- String _validUntil = '';
- // ── 关联管控 ──
- String? _selectedProjectName;
- int? _selectedProjectId;
- String? _selectedSubjectName;
- int? _selectedSubjectId;
- double _availableBudget = 0;
- final _referenceNoController = TextEditingController();
- // ── 费用明细 ──
- final List<_DetailItem> _details = [];
- int _detailIdCounter = 1;
- // ── 附件 ──
- final List<String> _attachments = [];
- // ── 专用字段 ──
- String _estimatedStartDate = '';
- String _estimatedEndDate = '';
- bool _isOvernight = false;
- String? _transportType;
- String? _entertainmentTarget;
- String? _entertainmentLevel;
- int _guestCount = 1;
- int _companionCount = 0;
- String _entertainmentVenue = '';
- String _meetingStartDate = '';
- String _meetingEndDate = '';
- String _meetingVenue = '';
- @override
- void dispose() {
- _purposeController.dispose();
- _referenceNoController.dispose();
- super.dispose();
- }
- @override
- Widget build(BuildContext context) {
- final l10n = AppLocalizations.of(context);
- ref
- .read(navBarConfigProvider.notifier)
- .update(
- NavBarConfig(
- title: l10n.get('expenseApplyRequest'),
- showBack: true,
- onBack: () {
- if (_hasUnsaved()) {
- _showConfirmDialog(
- l10n.get('confirmExit'),
- l10n.get('unsavedContentWarning'),
- l10n.get('continueEditing'),
- l10n.get('discardAndExit'),
- () => context.pop(),
- );
- } else {
- context.pop();
- }
- },
- ),
- );
- return PopScope(
- canPop: false,
- onPopInvokedWithResult: (didPop, _) {
- if (!didPop) {
- if (_hasUnsaved()) {
- _showConfirmDialog(
- l10n.get('confirmExit'),
- l10n.get('unsavedContentWarning'),
- l10n.get('continueEditing'),
- l10n.get('discardAndExit'),
- () => context.pop(),
- );
- } else {
- context.pop();
- }
- }
- },
- child: Column(
- children: [
- Expanded(
- child: GestureDetector(
- onTap: () => FocusScope.of(context).unfocus(),
- child: SingleChildScrollView(
- padding: const EdgeInsets.all(16),
- child: Column(
- children: [
- _buildBasicInfo(l10n),
- _buildTypeSpecificFields(l10n),
- _buildControlSection(l10n),
- const SizedBox(height: 16),
- _buildDetailsSection(l10n),
- const SizedBox(height: 16),
- _buildAttachmentSection(l10n),
- const SizedBox(height: 80),
- ],
- ),
- ),
- ),
- ),
- _buildBottomBar(l10n),
- ],
- ),
- );
- }
- // ═══ 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('applicant'),
- value: '张三',
- readOnly: true,
- showArrow: false,
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('department'),
- value: '技术部',
- readOnly: true,
- showArrow: false,
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('date'),
- value: _today(),
- readOnly: true,
- showArrow: false,
- ),
- const SizedBox(height: 16),
- _label(l10n.get('emergencyLevel'), required: true),
- const SizedBox(height: 8),
- _buildUrgencyRadio(l10n),
- const SizedBox(height: 16),
- _label(l10n.get('expenseType'), required: true),
- const SizedBox(height: 8),
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: ExpenseType.values.map((opt) {
- final sel = _expenseTypes.contains(opt.value);
- return GestureDetector(
- onTap: () => setState(() {
- if (sel) {
- _expenseTypes.remove(opt.value);
- } else {
- _expenseTypes.add(opt.value);
- final hints = {
- 'travel': 'hintTravelFields',
- 'entertainment': 'hintEntertainmentFields',
- 'meeting': 'hintMeetingFields',
- };
- final hintKey = hints[opt.value];
- if (hintKey != null) {
- TDMessage.showMessage(
- context: context,
- content: l10n.get(hintKey),
- theme: MessageTheme.info,
- icon: true,
- marquee: MessageMarquee(speed: 3000, loop: 1, delay: 300),
- duration: 3000,
- );
- }
- }
- }),
- child: TDTag(
- l10n.get(opt.labelKey),
- size: TDTagSize.large,
- theme: sel ? TDTagTheme.primary : TDTagTheme.defaultTheme,
- isOutline: !sel,
- ),
- );
- }).toList(),
- ),
- const SizedBox(height: 16),
- _label(l10n.get('feeReason'), required: true),
- const SizedBox(height: 8),
- TDTextarea(
- controller: _purposeController,
- hintText: l10n.get('enterFeeReason'),
- maxLines: 4,
- minLines: 1,
- maxLength: 500,
- indicator: true,
- padding: EdgeInsets.zero,
- bordered: true,
- backgroundColor: colors.bgPage,
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('validUntil'),
- value: _validUntil,
- hint: l10n.get('pleaseSelect'),
- onTap: () => _pickDate((d) => setState(() => _validUntil = d)),
- ),
- ],
- );
- }
- Widget _buildUrgencyRadio(AppLocalizations l10n) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- return Row(
- children: Urgency.values.asMap().entries.map((e) {
- final sel = _urgency == e.value.value;
- final isCritical = e.value.value == Urgency.critical.value;
- final activeColor = isCritical ? colors.danger : colors.primary;
- return Padding(
- padding: EdgeInsets.only(right: e.key < 2 ? 24 : 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: 6),
- Text(
- l10n.get(e.value.labelKey),
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: sel ? activeColor : colors.textPrimary,
- ),
- ),
- ],
- ),
- ),
- );
- }).toList(),
- );
- }
- // ═══ 2. 类型专用字段 ═══
- Widget _buildTypeSpecificFields(AppLocalizations l10n) {
- final ws = <Widget>[];
- if (_expenseTypes.contains('travel')) ws.add(_buildTravelFields(l10n));
- if (_expenseTypes.contains('entertainment')) {
- if (ws.isNotEmpty) ws.add(const SizedBox(height: 16));
- ws.add(_buildEntertainmentFields(l10n));
- }
- if (_expenseTypes.contains('meeting')) {
- if (ws.isNotEmpty) ws.add(const SizedBox(height: 16));
- ws.add(_buildMeetingFields(l10n));
- }
- if (ws.isEmpty) return const SizedBox(height: 16);
- return Column(
- children: [const SizedBox(height: 16), ...ws, const SizedBox(height: 16)],
- );
- }
- Widget _buildTravelFields(AppLocalizations l10n) {
- return FormSection(
- title: l10n.get('travelExpense'),
- leadingIcon: Icons.flight_outlined,
- children: [
- FormFieldRow(
- label: l10n.get('estimatedStartDate'),
- value: _estimatedStartDate,
- hint: l10n.get('pleaseSelect'),
- required: true,
- onTap: () =>
- _pickDate((d) => setState(() => _estimatedStartDate = d)),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('estimatedEndDate'),
- value: _estimatedEndDate,
- hint: l10n.get('pleaseSelect'),
- required: true,
- onTap: () => _pickDate((d) {
- if (_estimatedStartDate.isNotEmpty &&
- _estimatedStartDate.compareTo(d) > 0) {
- TDToast.showText(
- l10n.get('startDateNotAfterEndDate'),
- context: context,
- );
- return;
- }
- setState(() => _estimatedEndDate = d);
- }),
- ),
- const SizedBox(height: 16),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- _label(l10n.get('isOvernight')),
- TDSwitch(
- isOn: _isOvernight,
- onChanged: (v) {
- setState(() => _isOvernight = v);
- return true;
- },
- ),
- ],
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('transportType'),
- value: _transportType != null
- ? l10n.get(
- TransportType.values
- .firstWhere((t) => t.value == _transportType)
- .labelKey,
- )
- : null,
- hint: l10n.get('pleaseSelect'),
- onTap: () => _showEnumPicker(
- l10n.get('selectTransport'),
- TransportType.values,
- (v) => setState(() => _transportType = v),
- ),
- ),
- ],
- );
- }
- Widget _buildEntertainmentFields(AppLocalizations l10n) {
- return FormSection(
- title: l10n.get('entertainmentExpense'),
- leadingIcon: Icons.people_outline,
- children: [
- FormFieldRow(
- label: l10n.get('entertainmentTargetUnit'),
- value: _entertainmentTarget,
- hint: l10n.get('pleaseEnter'),
- required: true,
- onTap: () => _showTextInput(
- l10n.get('entertainmentTargetUnit'),
- (v) => setState(() => _entertainmentTarget = v),
- initialText: _entertainmentTarget ?? '',
- ),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('entertainmentLevel'),
- value: _entertainmentLevel != null
- ? l10n.get(
- EntertainmentLevel.values
- .firstWhere((e) => e.value == _entertainmentLevel)
- .labelKey,
- )
- : null,
- hint: l10n.get('pleaseSelect'),
- onTap: () => _showEnumPicker(
- l10n.get('selectEntertainmentLevel'),
- EntertainmentLevel.values,
- (v) => setState(() => _entertainmentLevel = v),
- ),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('externalCount'),
- value: '$_guestCount',
- onTap: () => _showNumberInput(
- l10n.get('externalCount'),
- (v) => setState(() => _guestCount = v),
- initialValue: _guestCount,
- ),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('internalCount'),
- value: '$_companionCount',
- onTap: () => _showNumberInput(
- l10n.get('internalCount'),
- (v) => setState(() => _companionCount = v),
- initialValue: _companionCount,
- ),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('venue'),
- value: _entertainmentVenue,
- hint: l10n.get('pleaseEnterLocation'),
- onTap: () => _showTextInput(
- l10n.get('venue'),
- (v) => setState(() => _entertainmentVenue = v),
- initialText: _entertainmentVenue,
- ),
- ),
- ],
- );
- }
- Widget _buildMeetingFields(AppLocalizations l10n) {
- return FormSection(
- title: l10n.get('meetingExpense'),
- leadingIcon: Icons.meeting_room_outlined,
- children: [
- FormFieldRow(
- label: l10n.get('estimatedStartDate'),
- value: _meetingStartDate,
- hint: l10n.get('pleaseSelect'),
- required: true,
- onTap: () => _pickDate((d) => setState(() => _meetingStartDate = d)),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('estimatedEndDate'),
- value: _meetingEndDate,
- hint: l10n.get('pleaseSelect'),
- required: true,
- onTap: () => _pickDate((d) {
- if (_meetingStartDate.isNotEmpty &&
- _meetingStartDate.compareTo(d) > 0) {
- TDToast.showText(
- l10n.get('startDateNotAfterEndDate'),
- context: context,
- );
- return;
- }
- setState(() => _meetingEndDate = d);
- }),
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('venue'),
- value: _meetingVenue,
- hint: l10n.get('pleaseEnterMeetingLocation'),
- onTap: () => _showTextInput(
- l10n.get('meetingLocation'),
- (v) => setState(() => _meetingVenue = v),
- initialText: _meetingVenue,
- ),
- ),
- ],
- );
- }
- // ═══ 3. 关联管控 ═══
- List<Map<String, dynamic>> _buildCascadeData() {
- return mockProjects
- .map(
- (p) => <String, dynamic>{
- 'label': p.name,
- 'value': p.id.toString(),
- 'children': mockBudgetSubjects
- .map(
- (s) => <String, dynamic>{
- 'label': s.name,
- 'value': s.id.toString(),
- },
- )
- .toList(),
- },
- )
- .toList();
- }
- Widget _buildControlSection(AppLocalizations l10n) {
- final cascadeLabel = _selectedProjectName != null &&
- _selectedSubjectName != null
- ? '$_selectedProjectName / $_selectedSubjectName'
- : _selectedProjectName;
- return FormSection(
- title: l10n.get('relatedControl'),
- leadingIcon: Icons.link_outlined,
- children: [
- FormFieldRow(
- label: l10n.get('relatedProject'),
- value: cascadeLabel,
- hint: l10n.get('selectProjectAndSubject'),
- required: true,
- onTap: () {
- _unfocus();
- TDCascader.showMultiCascader(
- context,
- title: l10n.get('selectProjectAndSubject'),
- data: _buildCascadeData(),
- subTitles: [
- l10n.get('project'),
- l10n.get('budgetSubject'),
- ],
- onClose: () => Navigator.of(context).pop(),
- onChange: (selected) {
- if (selected.length >= 2) {
- final pId =
- int.tryParse(selected[0].value ?? '');
- final sId =
- int.tryParse(selected[1].value ?? '');
- if (pId != null && sId != null) {
- setState(() {
- _selectedProjectId = pId;
- _selectedProjectName =
- selected[0].label;
- _selectedSubjectId = sId;
- _selectedSubjectName =
- selected[1].label;
- _availableBudget =
- getMockBudget(pId, sId);
- });
- }
- }
- },
- );
- },
- ),
- const SizedBox(height: 16),
- _buildBudgetRow(l10n),
- 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,
- ),
- ),
- ],
- );
- }
- Widget _buildBudgetRow(AppLocalizations l10n) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final over = _availableBudget <= 0;
- return Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l10n.get('availableBudget'),
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.textSecondary,
- ),
- ),
- Text(
- '¥${_availableBudget.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- fontWeight: FontWeight.w700,
- color: over ? colors.danger : colors.amountPrimary,
- ),
- ),
- ],
- );
- }
- // ═══ 4. 费用明细 ═══
- 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: [
- Padding(
- padding: const EdgeInsets.only(bottom: 12),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- _label(l10n.get('isTaxIncluded')),
- TDSwitch(
- isOn: _isTaxIncluded,
- onChanged: (v) {
- setState(() => _isTaxIncluded = v);
- return true;
- },
- ),
- ],
- ),
- ),
- 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 Container(
- margin: const EdgeInsets.symmetric(vertical: 8),
- padding: const EdgeInsets.all(12),
- decoration: BoxDecoration(
- color: colors.bgPage,
- borderRadius: BorderRadius.circular(8),
- ),
- child: Row(
- children: [
- Expanded(
- flex: 3,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- d.categoryName,
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- color: colors.textPrimary,
- ),
- ),
- if (d.remark.isNotEmpty)
- Text(
- d.remark,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textSecondary,
- ),
- ),
- ],
- ),
- ),
- Text(
- '${d.quantity}×¥${d.unitPrice.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.body,
- color: colors.textSecondary,
- ),
- ),
- const SizedBox(width: 8),
- Text(
- '¥${d.amount.toStringAsFixed(2)}',
- style: TextStyle(
- fontSize: AppFontSizes.subtitle,
- fontWeight: FontWeight.w600,
- color: colors.amountPrimary,
- ),
- ),
- const SizedBox(width: 8),
- GestureDetector(
- onTap: () => setState(() => _details.removeAt(e.key)),
- child: Container(
- width: 24,
- height: 24,
- decoration: BoxDecoration(
- color: colors.primaryLight,
- shape: BoxShape.circle,
- ),
- child: Icon(
- Icons.close,
- size: 14,
- color: colors.primary700,
- ),
- ),
- ),
- ],
- ),
- );
- }),
- 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,
- ),
- ),
- ],
- ),
- ),
- if (_totalAmount() > _availableBudget)
- Padding(
- padding: const EdgeInsets.only(top: 8),
- child: Row(
- children: [
- Icon(Icons.warning_amber, size: 14, color: colors.danger),
- const SizedBox(width: 6),
- Expanded(
- child: Text(
- l10n.get('overBudgetTriggerApproval'),
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.danger,
- ),
- ),
- ),
- ],
- ),
- ),
- ],
- );
- }
- double _totalAmount() => _details.fold(0, (s, d) => s + d.amount);
- List<CostCategory> get _availableDetailCategories {
- if (_expenseTypes.isEmpty) return mockCostCategories;
- final codes = _expenseTypes
- .expand((et) => expenseTypeCategories[et] ?? <String>[])
- .toSet();
- return mockCostCategories.where((c) => codes.contains(c.code)).toList();
- }
- Future<void> _showDetailDialog() async {
- final l10n = AppLocalizations.of(context);
- final result = await ExpenseDetailDialog.show(
- context,
- categories: _availableDetailCategories,
- unitKeys: unitOptions,
- l10n: l10n,
- );
- if (result != null && mounted) {
- setState(
- () => _details.add(
- _DetailItem(
- id: _detailIdCounter++,
- category: result.category,
- categoryName: result.categoryName,
- quantity: result.quantity,
- unit: result.unit,
- unitPrice: result.unitPrice,
- amount: result.quantity * result.unitPrice,
- remark: result.remark,
- ),
- ),
- );
- }
- }
- // ═══ 5. 附件上传 ═══
- Widget _buildAttachmentSection(AppLocalizations l10n) {
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- return FormSection(
- title: l10n.get('attachmentUpload'),
- leadingIcon: Icons.attach_file_outlined,
- children: [
- Text(
- l10n.get('maxAttachment'),
- style: TextStyle(
- fontSize: AppFontSizes.caption,
- color: colors.textPlaceholder,
- ),
- ),
- const SizedBox(height: 8),
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- ..._attachments.asMap().entries.map(
- (e) => Stack(
- clipBehavior: Clip.none,
- children: [
- Container(
- width: 80,
- height: 80,
- decoration: BoxDecoration(
- color: colors.primaryLight,
- borderRadius: BorderRadius.circular(4),
- ),
- child: Center(
- child: Icon(Icons.image, color: colors.primary, size: 32),
- ),
- ),
- Positioned(
- right: -4,
- top: -4,
- child: GestureDetector(
- onTap: () => setState(() => _attachments.removeAt(e.key)),
- child: Container(
- width: 20,
- height: 20,
- decoration: BoxDecoration(
- color: colors.danger,
- shape: BoxShape.circle,
- ),
- child: const Icon(
- Icons.close,
- size: 12,
- color: Colors.white,
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- if (_attachments.length < 9)
- GestureDetector(
- onTap: () {
- // Mock: add attachment (支持图片/PDF/Word/Excel)
- final exts = ['.jpg', '.png', '.pdf', '.docx', '.xlsx'];
- setState(
- () => _attachments.add(
- '附件_${DateTime.now().millisecondsSinceEpoch}${exts[_attachments.length % exts.length]}',
- ),
- );
- TDToast.showText(
- l10n.get('mockAttachmentAdded'),
- context: context,
- );
- },
- child: Container(
- width: 80,
- height: 80,
- decoration: BoxDecoration(
- color: colors.bgPage,
- borderRadius: BorderRadius.circular(4),
- border: Border.all(color: colors.border, width: 1),
- ),
- child: Center(
- child: Icon(
- Icons.add,
- size: 24,
- color: colors.textPlaceholder,
- ),
- ),
- ),
- ),
- ],
- ),
- ],
- );
- }
- // ═══ 6. 底部操作栏 ═══
- Widget _buildBottomBar(AppLocalizations l10n) {
- final isDraft = widget.id != null;
- return ActionBar(
- leftLabel: isDraft ? l10n.get('reset') : null,
- centerLabel: l10n.get('saveDraft'),
- rightLabel: l10n.get('submitApproval'),
- showLeft: isDraft,
- onLeftTap: isDraft
- ? () => _showConfirmDialog(
- l10n.get('confirmReset'),
- l10n.get('resetWarning'),
- l10n.get('cancel'),
- l10n.get('confirmReset'),
- _resetAll,
- )
- : null,
- onCenterTap: () {
- TDToast.showSuccess(l10n.get('draftSavedToast'), context: context);
- context.pop();
- },
- onRightTap: () {
- final err = _validate(l10n);
- if (err.isNotEmpty) {
- TDToast.showText(err.first, context: context);
- return;
- }
- TDToast.showSuccess(
- l10n.get('submittedAwaitingApproval'),
- context: context,
- );
- context.pop();
- },
- );
- }
- List<String> _validate(AppLocalizations l10n) {
- final e = <String>[];
- if (_expenseTypes.isEmpty) e.add(l10n.get('selectAtLeastOneExpenseType'));
- if (_purposeController.text.trim().isEmpty) {
- e.add(l10n.get('enterFeeReason'));
- }
- if (_selectedProjectId == null) e.add(l10n.get('selectProject'));
- if (_selectedSubjectId == null) e.add(l10n.get('selectSubject'));
- if (_details.isEmpty) e.add(l10n.get('addAtLeastOneDetail'));
- if (_expenseTypes.contains('travel')) {
- if (_estimatedStartDate.isEmpty) {
- e.add(l10n.get('selectEstimatedStartDate'));
- }
- if (_estimatedEndDate.isEmpty) {
- e.add(l10n.get('selectEstimatedEndDate'));
- }
- if (_estimatedStartDate.isNotEmpty &&
- _estimatedEndDate.isNotEmpty &&
- _estimatedStartDate.compareTo(_estimatedEndDate) > 0) {
- e.add(l10n.get('startDateNotAfterEndDate'));
- }
- }
- if (_expenseTypes.contains('entertainment')) {
- if (_entertainmentTarget == null || _entertainmentTarget!.isEmpty) {
- e.add(l10n.get('entertainmentTargetUnit'));
- }
- if (_companionCount > _guestCount) {
- e.add(l10n.get('companionNotExceedGuest'));
- }
- }
- if (_expenseTypes.contains('meeting')) {
- if (_meetingStartDate.isEmpty) {
- e.add(l10n.get('selectEstimatedStartDate'));
- }
- if (_meetingEndDate.isEmpty) {
- e.add(l10n.get('selectEstimatedEndDate'));
- }
- if (_meetingStartDate.isNotEmpty &&
- _meetingEndDate.isNotEmpty &&
- _meetingStartDate.compareTo(_meetingEndDate) > 0) {
- e.add(l10n.get('startDateNotAfterEndDate'));
- }
- }
- return e;
- }
- void _resetAll() => setState(() {
- _purposeController.clear();
- _expenseTypes.clear();
- _urgency = Urgency.normal.value;
- _isTaxIncluded = false;
- _validUntil = '';
- _selectedProjectId = null;
- _selectedProjectName = null;
- _selectedSubjectId = null;
- _selectedSubjectName = null;
- _availableBudget = 0;
- _referenceNoController.clear();
- _details.clear();
- _attachments.clear();
- _estimatedStartDate = '';
- _estimatedEndDate = '';
- _isOvernight = false;
- _transportType = null;
- _entertainmentTarget = null;
- _entertainmentLevel = null;
- _guestCount = 1;
- _companionCount = 0;
- _entertainmentVenue = '';
- _meetingStartDate = '';
- _meetingEndDate = '';
- _meetingVenue = '';
- });
- bool _hasUnsaved() =>
- _purposeController.text.isNotEmpty ||
- _expenseTypes.isNotEmpty ||
- _details.isNotEmpty ||
- _attachments.isNotEmpty ||
- _selectedProjectId != null ||
- _estimatedStartDate.isNotEmpty ||
- _estimatedEndDate.isNotEmpty ||
- _entertainmentTarget != null ||
- _meetingStartDate.isNotEmpty;
- 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,
- 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();
- },
- ),
- ),
- );
- }
- void _showEnumPicker(
- String title,
- List<EnumEntry> entries,
- Function(String) onPick,
- ) {
- _showListPicker(
- title,
- entries.map((e) => AppLocalizations.of(context).get(e.labelKey)).toList(),
- (label) {
- final entry = entries.firstWhere(
- (e) => AppLocalizations.of(context).get(e.labelKey) == label,
- );
- onPick(entry.value);
- },
- );
- }
- void _showListPicker(
- String title,
- List<String> items,
- Function(String) onPick,
- ) {
- _unfocus();
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- TDPicker.showMultiPicker(
- context,
- title: title,
- backgroundColor: colors.bgCard,
- data: [items],
- onConfirm: (selected) {
- if (selected.isNotEmpty && selected[0] is int) {
- final idx = selected[0] as int;
- if (idx >= 0 && idx < items.length) {
- Navigator.of(context).pop();
- onPick(items[idx]);
- }
- }
- },
- );
- }
- void _showTextInput(
- String title,
- Function(String) onConfirm, {
- String initialText = '',
- }) {
- _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);
- },
- ),
- ),
- );
- }
- void _showNumberInput(
- String title,
- Function(int) onConfirm, {
- int initialValue = 0,
- }) {
- _unfocus();
- final l10n = AppLocalizations.of(context);
- final c = TextEditingController(
- text: initialValue > 0 ? '$initialValue' : '',
- );
- showGeneralDialog(
- context: context,
- pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
- textEditingController: c,
- title: title,
- hintText: l10n.get('enterNumber'),
- leftBtn: TDDialogButtonOptions(
- title: l10n.get('cancel'),
- action: () => Navigator.pop(ctx),
- ),
- rightBtn: TDDialogButtonOptions(
- title: l10n.get('confirm'),
- action: () {
- onConfirm(int.tryParse(c.text) ?? 0);
- Navigator.pop(ctx);
- },
- ),
- ),
- );
- }
- void _pickDate(Function(String) onPick) {
- _unfocus();
- final l10n = AppLocalizations.of(context);
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final theme = Theme.of(context);
- final now = DateTime.now();
- showModalBottomSheet(
- context: context,
- backgroundColor: Colors.transparent,
- builder: (ctx) => Theme(
- data: theme,
- child: TDDatePicker(
- title: l10n.get('selectDate'),
- backgroundColor: colors.bgCard,
- model: DatePickerModel(
- useYear: true,
- useMonth: true,
- useDay: true,
- useHour: false,
- useMinute: false,
- useSecond: false,
- useWeekDay: false,
- dateStart: [2020, 1, 1],
- dateEnd: [now.year + 1, 12, 31],
- dateInitial: [now.year, now.month, now.day],
- ),
- onConfirm: (selected) {
- onPick(
- '${selected['year']}-${selected['month']!.toString().padLeft(2, '0')}-${selected['day']!.toString().padLeft(2, '0')}',
- );
- Navigator.of(ctx).pop();
- },
- onCancel: (_) => Navigator.of(ctx).pop(),
- ),
- ),
- );
- }
- 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,
- ),
- ),
- ],
- ),
- );
- }
- 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 double quantity;
- final String unit;
- final double unitPrice;
- final double amount;
- final String remark;
- const _DetailItem({
- required this.id,
- required this.category,
- required this.categoryName,
- required this.quantity,
- required this.unit,
- required this.unitPrice,
- required this.amount,
- required this.remark,
- });
- }
|