| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379 |
- 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';
- 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) => 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) => 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. 关联管控 ═══
- Widget _buildControlSection(AppLocalizations l10n) {
- return FormSection(
- title: l10n.get('relatedControl'),
- leadingIcon: Icons.link_outlined,
- children: [
- FormFieldRow(
- label: l10n.get('relatedProject'),
- value: _selectedProjectName,
- hint: l10n.get('selectProject'),
- required: true,
- onTap: () {
- _showListPicker(
- l10n.get('selectProject'),
- mockProjects.map((p) => p.name).toList(),
- (v) {
- final p = mockProjects.firstWhere((x) => x.name == v);
- setState(() {
- _selectedProjectId = p.id;
- _selectedProjectName = p.name;
- _selectedSubjectName = null;
- _selectedSubjectId = null;
- _availableBudget = 0;
- });
- },
- );
- },
- ),
- const SizedBox(height: 16),
- FormFieldRow(
- label: l10n.get('budgetSubject'),
- value: _selectedSubjectName,
- hint: l10n.get('selectSubject'),
- required: true,
- onTap: _selectedProjectId != null
- ? () {
- _showListPicker(
- l10n.get('selectSubject'),
- mockBudgetSubjects.map((s) => s.name).toList(),
- (v) {
- final s = mockBudgetSubjects.firstWhere(
- (x) => x.name == v,
- );
- setState(() {
- _selectedSubjectId = s.id;
- _selectedSubjectName = s.name;
- _availableBudget = getMockBudget(
- _selectedProjectId!,
- s.id,
- );
- });
- },
- );
- }
- : null,
- ),
- 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();
- }
- void _showDetailDialog() {
- _unfocus();
- final l10n = AppLocalizations.of(context);
- final colors = Theme.of(context).extension<AppColorsExtension>()!;
- final cats = _availableDetailCategories;
- String cat = cats.isNotEmpty ? cats.first.code : 'other';
- String unit = l10n.get('unitPiece');
- final qtyCtrl = TextEditingController(text: '1');
- final priceCtrl = TextEditingController();
- final remarkCtrl = TextEditingController();
- showModalBottomSheet(
- context: context,
- isScrollControlled: true,
- backgroundColor: colors.bgCard,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
- ),
- builder: (ctx) => StatefulBuilder(
- builder: (ctx, setDlg) => Padding(
- padding: EdgeInsets.only(
- left: 16,
- right: 16,
- top: 16,
- bottom: 16 + MediaQuery.of(ctx).viewInsets.bottom,
- ),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Center(
- child: Text(
- l10n.get('addExpenseDetail'),
- style: TextStyle(
- fontSize: 18,
- fontWeight: FontWeight.w600,
- color: colors.textPrimary,
- ),
- ),
- ),
- const SizedBox(height: 16),
- // 费用类别 — 左右布局,必填
- Row(
- children: [
- SizedBox(
- width: 80,
- child: _label(l10n.get('expenseCategory'), required: true),
- ),
- const SizedBox(width: 8),
- Expanded(
- child: TDDropdownMenu(
- items: [
- TDDropdownItem(
- label: l10n.get(
- cats.firstWhere((c) => c.code == cat).nameKey,
- ),
- options: cats
- .map(
- (c) => TDDropdownItemOption(
- value: c.code,
- label: l10n.get(c.nameKey),
- ),
- )
- .toList(),
- ),
- ],
- closeOnClickOverlay: true,
- onMenuClosed: (index) {
- if (index >= 0 && index < cats.length) {
- cat = cats[index].code;
- setDlg(() {});
- }
- },
- ),
- ),
- ],
- ),
- const SizedBox(height: 12),
- // 数量 — 左右布局,必填
- Row(
- children: [
- SizedBox(
- width: 80,
- child: _label(l10n.get('quantity'), required: true),
- ),
- const SizedBox(width: 8),
- Expanded(
- child: TDInput(controller: qtyCtrl, hintText: '>0'),
- ),
- ],
- ),
- const SizedBox(height: 12),
- // 单位 — 左右布局
- Row(
- children: [
- SizedBox(width: 80, child: _label(l10n.get('unit'))),
- const SizedBox(width: 8),
- Expanded(
- child: TDDropdownMenu(
- items: [
- TDDropdownItem(
- label: unit,
- options: unitOptions
- .map(
- (u) => TDDropdownItemOption(
- value: u,
- label: l10n.get(u),
- ),
- )
- .toList(),
- ),
- ],
- closeOnClickOverlay: true,
- onMenuClosed: (index) {
- if (index >= 0 && index < unitOptions.length) {
- unit = l10n.get(unitOptions[index]);
- setDlg(() {});
- }
- },
- ),
- ),
- ],
- ),
- const SizedBox(height: 12),
- // 单价 — 左右布局,必填
- Row(
- children: [
- SizedBox(
- width: 80,
- child: _label(l10n.get('unitPrice'), required: true),
- ),
- const SizedBox(width: 8),
- Expanded(
- child: TDInput(controller: priceCtrl, hintText: '>0'),
- ),
- ],
- ),
- const SizedBox(height: 12),
- _label(l10n.get('detailRemark')),
- const SizedBox(height: 8),
- TDTextarea(
- controller: remarkCtrl,
- hintText: l10n.get('optional'),
- maxLines: 3,
- minLines: 1,
- maxLength: 200,
- indicator: true,
- padding: EdgeInsets.zero,
- bordered: true,
- backgroundColor: colors.bgPage,
- ),
- const SizedBox(height: 16),
- Row(
- children: [
- Expanded(
- child: TDButton(
- text: l10n.get('cancel'),
- size: TDButtonSize.medium,
- type: TDButtonType.outline,
- shape: TDButtonShape.rectangle,
- theme: TDButtonTheme.defaultTheme,
- onTap: () => Navigator.pop(ctx),
- ),
- ),
- const SizedBox(width: 12),
- Expanded(
- child: TDButton(
- text: l10n.get('confirm'),
- size: TDButtonSize.medium,
- type: TDButtonType.fill,
- shape: TDButtonShape.rectangle,
- theme: TDButtonTheme.primary,
- onTap: () {
- final q = int.tryParse(qtyCtrl.text) ?? 0;
- final p = double.tryParse(priceCtrl.text) ?? 0;
- if (q <= 0 || p <= 0) {
- TDToast.showText(
- l10n.get('quantityPricePositive'),
- context: context,
- );
- return;
- }
- setState(
- () => _details.add(
- _DetailItem(
- id: _detailIdCounter++,
- category: cat,
- categoryName: l10n.get(
- cats.firstWhere((c) => c.code == cat).nameKey,
- ),
- quantity: q,
- unit: unit,
- unitPrice: p,
- amount: q * p.toDouble(),
- remark: remarkCtrl.text,
- ),
- ),
- );
- Navigator.pop(ctx);
- },
- ),
- ),
- ],
- ),
- ],
- ),
- ),
- ),
- );
- }
- // ═══ 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),
- ),
- 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 (_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'));
- }
- 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,
- 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 int 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,
- });
- }
|