vehicle_apply_create_page.dart 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:flutter_riverpod/flutter_riverpod.dart';
  5. import 'package:go_router/go_router.dart';
  6. import 'package:tdesign_flutter/tdesign_flutter.dart';
  7. import '../../core/i18n/app_localizations.dart';
  8. import '../../core/navigation/host_app_channel.dart';
  9. import '../../core/storage/draft_storage.dart';
  10. import '../../core/theme/app_colors.dart';
  11. import '../../core/theme/app_colors_extension.dart';
  12. import '../../shared/widgets/action_bar.dart';
  13. import '../../shared/widgets/app_skeletons.dart';
  14. import '../../shared/widgets/form_field_row.dart';
  15. import '../../shared/widgets/form_section.dart';
  16. import '../../shared/widgets/loading_dialog.dart';
  17. import '../../shared/widgets/nav_bar_config.dart';
  18. import '../../shared/widgets/app_input_dialog.dart';
  19. import '../../shared/widgets/searchable_picker_sheet.dart';
  20. import '../../shared/helpers/audit_flow_helper.dart';
  21. import 'vehicle_apply_api.dart';
  22. class VehicleApplyCreatePage extends ConsumerStatefulWidget {
  23. const VehicleApplyCreatePage({super.key});
  24. @override
  25. ConsumerState<VehicleApplyCreatePage> createState() =>
  26. _VehicleApplyCreatePageState();
  27. }
  28. class _VehicleApplyCreatePageState
  29. extends ConsumerState<VehicleApplyCreatePage> {
  30. static const _draftKey = 'vehicle_apply';
  31. // ── 基本信息 ──
  32. final _reasonController = TextEditingController();
  33. String _originAdr = '';
  34. String _destAdr = '';
  35. DateTime? _startTime;
  36. DateTime? _endTime;
  37. // ── 车辆信息 ──
  38. String _licensePlate = '';
  39. String _vehicleType = '';
  40. String _brand = '';
  41. int _seats = 0;
  42. // ── 车辆信息 ──
  43. int _odometerBegin = 0;
  44. // ── 驾驶员 ──
  45. String _driverName = '';
  46. // ── 同行信息 ──
  47. final List<EmployeeItem> _passengers = [];
  48. // ── 参考数据 ──
  49. List<DepartmentItem> _departments = [];
  50. List<EmployeeItem> _employees = [];
  51. bool _firstBuild = true;
  52. bool _refDataLoading = true;
  53. String _selectedDeptId = '';
  54. String _selectedDeptName = '';
  55. String _selectedApplicantId = '';
  56. String _selectedApplicantName = '';
  57. final _scrollCtrl = ScrollController();
  58. // Mock 车辆类型
  59. static const _mockVehicleTypes = [
  60. 'sedan',
  61. 'suv',
  62. 'mpv',
  63. 'van',
  64. 'truck',
  65. 'pickup',
  66. 'minibus',
  67. 'bus',
  68. ];
  69. @override
  70. void initState() {
  71. super.initState();
  72. SystemChrome.setSystemUIOverlayStyle(
  73. const SystemUiOverlayStyle(
  74. statusBarColor: Colors.transparent,
  75. statusBarIconBrightness: Brightness.dark,
  76. ),
  77. );
  78. _departments = [];
  79. _refDataLoading = true;
  80. _refDataFuture = null;
  81. _loadRefData();
  82. WidgetsBinding.instance.addPostFrameCallback((_) => _checkDataReady());
  83. }
  84. void _checkDataReady() {
  85. if (!_refDataLoading && mounted) {
  86. setState(() => _firstBuild = false);
  87. WidgetsBinding.instance.addPostFrameCallback((_) {
  88. if (mounted) setState(() {});
  89. });
  90. } else if (mounted) {
  91. WidgetsBinding.instance.addPostFrameCallback((_) => _checkDataReady());
  92. }
  93. }
  94. Future<void>? _refDataFuture;
  95. Future<void> _loadRefData({bool showLoading = false}) async {
  96. if (_refDataFuture != null) return _refDataFuture!;
  97. final completer = Completer<void>();
  98. _refDataFuture = completer.future;
  99. if (showLoading) {
  100. LoadingDialog.show(
  101. context,
  102. text: AppLocalizations.of(context).get('dataLoading'),
  103. );
  104. }
  105. try {
  106. final api = ref.read(vehicleApplyApiProvider);
  107. final results = await Future.wait([
  108. api.getDepartments(),
  109. api.getEmployees(),
  110. ]);
  111. if (!mounted) return;
  112. setState(() {
  113. _departments = results[0] as List<DepartmentItem>;
  114. _employees = results[1] as List<EmployeeItem>;
  115. _refDataLoading = false;
  116. _autoSelectDept();
  117. _autoSelectApplicant();
  118. _autoSelectPassenger();
  119. _autoSelectDriver();
  120. });
  121. completer.complete();
  122. } catch (_) {
  123. if (!mounted) {
  124. completer.complete();
  125. return;
  126. }
  127. setState(() => _refDataLoading = false);
  128. completer.complete();
  129. } finally {
  130. if (showLoading && mounted) LoadingDialog.hide(context);
  131. _refDataFuture = null;
  132. }
  133. }
  134. void _autoSelectDept() {
  135. if (_selectedDeptId.isNotEmpty) return;
  136. final dep = HostAppChannel.dep;
  137. if (dep.isEmpty) return;
  138. final match = _departments.where((d) => d.dep == dep);
  139. if (match.isNotEmpty) {
  140. _selectedDeptId = match.first.dep;
  141. _selectedDeptName = match.first.name;
  142. }
  143. }
  144. void _autoSelectApplicant() {
  145. if (_selectedApplicantId.isNotEmpty) return;
  146. final usr = HostAppChannel.usr;
  147. if (usr.isEmpty) return;
  148. final match = _employees.where((e) => e.salNo == usr);
  149. if (match.isNotEmpty) {
  150. _selectedApplicantId = match.first.salNo;
  151. _selectedApplicantName = match.first.name;
  152. }
  153. }
  154. void _autoSelectPassenger() {
  155. final usr = HostAppChannel.usr;
  156. if (usr.isEmpty) return;
  157. final match = _employees.where((e) => e.salNo == usr);
  158. if (match.isNotEmpty && !_passengers.any((p) => p.salNo == usr)) {
  159. _passengers.add(match.first);
  160. }
  161. }
  162. void _autoSelectDriver() {
  163. if (_driverName.isNotEmpty) return;
  164. final usr = HostAppChannel.usr;
  165. if (usr.isEmpty) return;
  166. final match = _employees.where((e) => e.salNo == usr);
  167. if (match.isNotEmpty) {
  168. _driverName = match.first.name;
  169. }
  170. }
  171. @override
  172. void dispose() {
  173. _reasonController.dispose();
  174. _scrollCtrl.dispose();
  175. super.dispose();
  176. }
  177. @override
  178. Widget build(BuildContext context) {
  179. final l10n = AppLocalizations.of(context);
  180. if (_firstBuild) {
  181. return const SkeletonFormPage(
  182. sectionRows: [4, 6, 4, 1],
  183. bottomButtonCount: 2,
  184. );
  185. }
  186. Future.microtask(
  187. () => ref.read(pageBackProvider.notifier).state = () => _doPop(),
  188. );
  189. return PopScope(
  190. canPop: false,
  191. onPopInvokedWithResult: (didPop, _) {
  192. if (didPop) return;
  193. _doPop();
  194. },
  195. child: Column(
  196. children: [
  197. Expanded(
  198. child: GestureDetector(
  199. onTap: () => FocusScope.of(context).unfocus(),
  200. child: SingleChildScrollView(
  201. controller: _scrollCtrl,
  202. padding: const EdgeInsets.all(16),
  203. child: Column(
  204. children: [
  205. _buildBasicInfo(l10n),
  206. const SizedBox(height: 16),
  207. _buildVehicleInfo(l10n),
  208. const SizedBox(height: 16),
  209. _buildTripInfo(l10n),
  210. const SizedBox(height: 16),
  211. _buildPassengerInfo(l10n),
  212. const SizedBox(height: 24),
  213. _buildPageFooter(),
  214. ],
  215. ),
  216. ),
  217. ),
  218. ),
  219. _buildBottomBar(l10n),
  220. ],
  221. ),
  222. );
  223. }
  224. // ═══ 基本信息 ═══
  225. Widget _buildBasicInfo(AppLocalizations l10n) {
  226. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  227. return FormSection(
  228. title: l10n.get('basicInfo'),
  229. leadingIcon: Icons.info_outline,
  230. children: [
  231. FormFieldRow(
  232. label: l10n.get('date'),
  233. value: _today(),
  234. readOnly: true,
  235. showArrow: false,
  236. ),
  237. const SizedBox(height: 16),
  238. FormFieldRow(
  239. label: l10n.get('dep'),
  240. value: _selectedDeptId.isNotEmpty
  241. ? '$_selectedDeptId/$_selectedDeptName'
  242. : '',
  243. hint: l10n.get('pleaseSelect'),
  244. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  245. ),
  246. const SizedBox(height: 16),
  247. FormFieldRow(
  248. label: l10n.get('applicant'),
  249. value: _selectedApplicantId.isNotEmpty
  250. ? '$_selectedApplicantId/$_selectedApplicantName'
  251. : '',
  252. hint: l10n.get('pleaseSelect'),
  253. onTap: () => _showApplicantPicker(),
  254. ),
  255. const SizedBox(height: 16),
  256. _label(l10n.get('vehicleReason'), required: true),
  257. const SizedBox(height: 8),
  258. TDTextarea(
  259. controller: _reasonController,
  260. hintText: l10n.get('enterVehicleReason'),
  261. maxLines: 4,
  262. minLines: 1,
  263. maxLength: 500,
  264. indicator: true,
  265. padding: EdgeInsets.zero,
  266. bordered: true,
  267. backgroundColor: colors.bgPage,
  268. ),
  269. ],
  270. );
  271. }
  272. // ═══ 行程信息 ═══
  273. Widget _buildTripInfo(AppLocalizations l10n) {
  274. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  275. final timeError =
  276. _startTime != null &&
  277. _endTime != null &&
  278. !_endTime!.isAfter(_startTime!);
  279. return FormSection(
  280. title: l10n.get('tripInfo'),
  281. leadingIcon: Icons.route_outlined,
  282. children: [
  283. FormFieldRow(
  284. label: l10n.get('departTime'),
  285. value: _startTime != null ? _formatDateTime(_startTime!) : null,
  286. hint: l10n.get('pleaseSelect'),
  287. required: true,
  288. onTap: () => _pickDateTime((d) {
  289. setState(() => _startTime = d);
  290. }, _startTime),
  291. onClear: _startTime != null
  292. ? () => setState(() => _startTime = null)
  293. : null,
  294. ),
  295. const SizedBox(height: 16),
  296. FormFieldRow(
  297. label: l10n.get('returnTime'),
  298. value: _endTime != null ? _formatDateTime(_endTime!) : null,
  299. hint: l10n.get('pleaseSelect'),
  300. required: true,
  301. onTap: () => _pickDateTime((d) {
  302. setState(() => _endTime = d);
  303. }, _endTime),
  304. onClear: _endTime != null
  305. ? () => setState(() => _endTime = null)
  306. : null,
  307. ),
  308. if (timeError)
  309. Padding(
  310. padding: const EdgeInsets.only(top: 8),
  311. child: Row(
  312. mainAxisAlignment: MainAxisAlignment.end,
  313. children: [
  314. Icon(
  315. Icons.warning_amber_rounded,
  316. size: 14,
  317. color: colors.danger,
  318. ),
  319. const SizedBox(width: 4),
  320. Text(
  321. l10n.get('returnTimeMustLater'),
  322. style: TextStyle(
  323. fontSize: AppFontSizes.caption,
  324. color: colors.danger,
  325. ),
  326. ),
  327. ],
  328. ),
  329. ),
  330. const SizedBox(height: 16),
  331. FormFieldRow(
  332. label: l10n.get('origin'),
  333. value: _originAdr.isNotEmpty ? _originAdr : null,
  334. hint: l10n.get('pleaseEnter'),
  335. onTap: () => _showTextInput(
  336. l10n.get('origin'),
  337. (v) => setState(() => _originAdr = v),
  338. initialText: _originAdr,
  339. ),
  340. onClear: _originAdr.isNotEmpty
  341. ? () => setState(() => _originAdr = '')
  342. : null,
  343. ),
  344. const SizedBox(height: 16),
  345. FormFieldRow(
  346. label: l10n.get('destination'),
  347. value: _destAdr.isNotEmpty ? _destAdr : null,
  348. hint: l10n.get('pleaseEnter'),
  349. onTap: () => _showTextInput(
  350. l10n.get('destination'),
  351. (v) => setState(() => _destAdr = v),
  352. initialText: _destAdr,
  353. ),
  354. onClear: _destAdr.isNotEmpty
  355. ? () => setState(() => _destAdr = '')
  356. : null,
  357. ),
  358. ],
  359. );
  360. }
  361. // ═══ 车辆信息 ═══
  362. Widget _buildVehicleInfo(AppLocalizations l10n) {
  363. return FormSection(
  364. title: l10n.get('vehicleInfo'),
  365. leadingIcon: Icons.directions_car_outlined,
  366. children: [
  367. FormFieldRow(
  368. label: l10n.get('licensePlate'),
  369. value: _licensePlate.isNotEmpty ? _licensePlate : null,
  370. hint: l10n.get('pleaseEnter'),
  371. required: true,
  372. onTap: () => _showTextInput(
  373. l10n.get('licensePlate'),
  374. (v) => setState(() => _licensePlate = v),
  375. initialText: _licensePlate,
  376. ),
  377. onClear: _licensePlate.isNotEmpty
  378. ? () => setState(() => _licensePlate = '')
  379. : null,
  380. ),
  381. const SizedBox(height: 16),
  382. FormFieldRow(
  383. label: l10n.get('vehicleType'),
  384. value: _vehicleType.isNotEmpty
  385. ? _vehicleTypeLabel(_vehicleType, l10n)
  386. : null,
  387. hint: l10n.get('pleaseSelect'),
  388. onTap: () => _showVehicleTypePicker(l10n),
  389. onClear: _vehicleType.isNotEmpty
  390. ? () => setState(() => _vehicleType = '')
  391. : null,
  392. ),
  393. const SizedBox(height: 16),
  394. FormFieldRow(
  395. label: l10n.get('brand'),
  396. value: _brand.isNotEmpty ? _brand : null,
  397. hint: l10n.get('pleaseEnter'),
  398. onTap: () => _showTextInput(
  399. l10n.get('brand'),
  400. (v) => setState(() => _brand = v),
  401. initialText: _brand,
  402. ),
  403. onClear: _brand.isNotEmpty ? () => setState(() => _brand = '') : null,
  404. ),
  405. const SizedBox(height: 16),
  406. FormFieldRow(
  407. label: l10n.get('seats'),
  408. value: _seats > 0 ? '$_seats' : null,
  409. hint: l10n.get('pleaseEnter'),
  410. onTap: () => _showNumberInput(
  411. l10n.get('seats'),
  412. (v) => setState(() => _seats = v),
  413. _seats,
  414. min: 1,
  415. ),
  416. onClear: _seats > 0 ? () => setState(() => _seats = 0) : null,
  417. ),
  418. const SizedBox(height: 16),
  419. FormFieldRow(
  420. label: l10n.get('odometerBegin'),
  421. value: _odometerBegin > 0 ? '$_odometerBegin' : null,
  422. hint: l10n.get('pleaseEnter'),
  423. onTap: () => _showNumberInput(
  424. l10n.get('odometerBegin'),
  425. (v) => setState(() => _odometerBegin = v),
  426. _odometerBegin,
  427. ),
  428. onClear: _odometerBegin > 0
  429. ? () => setState(() => _odometerBegin = 0)
  430. : null,
  431. ),
  432. const SizedBox(height: 16),
  433. FormFieldRow(
  434. label: l10n.get('driverName'),
  435. value: _driverName.isNotEmpty ? _driverName : null,
  436. hint: l10n.get('pleaseSelect'),
  437. onTap: () => _showDriverPicker(),
  438. onClear: _driverName.isNotEmpty
  439. ? () => setState(() => _driverName = '')
  440. : null,
  441. ),
  442. ],
  443. );
  444. }
  445. // ═══ 同行信息 ═══
  446. Widget _buildPassengerInfo(AppLocalizations l10n) {
  447. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  448. return FormSection(
  449. title: l10n.get('companionInfo'),
  450. leadingIcon: Icons.people_outline,
  451. showAction: true,
  452. actionText: l10n.get('add'),
  453. onActionTap: () => _showMultiEmployeePicker(l10n),
  454. children: [
  455. if (_passengers.isEmpty)
  456. Padding(
  457. padding: const EdgeInsets.symmetric(vertical: 8),
  458. child: Text(
  459. l10n.get('noPassengerHint'),
  460. style: TextStyle(
  461. fontSize: AppFontSizes.subtitle,
  462. color: colors.textPlaceholder,
  463. ),
  464. ),
  465. )
  466. else
  467. Wrap(
  468. spacing: 10,
  469. runSpacing: 10,
  470. children: _passengers.map((p) {
  471. final label =
  472. '${p.salNo}/${p.name.isNotEmpty ? p.name : p.salNo}';
  473. return Container(
  474. padding: const EdgeInsets.symmetric(
  475. horizontal: 14,
  476. vertical: 10,
  477. ),
  478. decoration: BoxDecoration(
  479. color: colors.bgCard,
  480. borderRadius: BorderRadius.circular(20),
  481. border: Border.all(color: colors.border, width: 0.5),
  482. boxShadow: [
  483. BoxShadow(
  484. color: Colors.black.withValues(alpha: 0.04),
  485. blurRadius: 4,
  486. offset: const Offset(0, 1),
  487. ),
  488. ],
  489. ),
  490. child: Row(
  491. mainAxisSize: MainAxisSize.min,
  492. children: [
  493. Icon(Icons.person_outline, size: 16, color: colors.primary),
  494. const SizedBox(width: 8),
  495. Text(
  496. label,
  497. style: TextStyle(
  498. fontSize: AppFontSizes.body,
  499. color: colors.textPrimary,
  500. ),
  501. ),
  502. const SizedBox(width: 8),
  503. GestureDetector(
  504. onTap: () {
  505. setState(() {
  506. _passengers.removeWhere((e) => e.salNo == p.salNo);
  507. });
  508. },
  509. child: Container(
  510. width: 20,
  511. height: 20,
  512. decoration: BoxDecoration(
  513. color: colors.bgPage,
  514. shape: BoxShape.circle,
  515. ),
  516. child: Icon(
  517. Icons.close,
  518. size: 12,
  519. color: colors.textSecondary,
  520. ),
  521. ),
  522. ),
  523. ],
  524. ),
  525. );
  526. }).toList(),
  527. ),
  528. const SizedBox(height: 16),
  529. Row(
  530. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  531. children: [
  532. Text(
  533. l10n.get('passengerCount'),
  534. style: TextStyle(
  535. fontSize: AppFontSizes.body,
  536. fontWeight: FontWeight.w600,
  537. color: colors.textPrimary,
  538. ),
  539. ),
  540. Text(
  541. '${_passengers.length}',
  542. style: TextStyle(
  543. fontSize: AppFontSizes.subtitle,
  544. fontWeight: FontWeight.w700,
  545. color: colors.textPrimary,
  546. ),
  547. ),
  548. ],
  549. ),
  550. ],
  551. );
  552. }
  553. // ═══ 底部操作栏 ═══
  554. Widget _buildBottomBar(AppLocalizations l10n) {
  555. return ActionBar(
  556. showLeft: false,
  557. centerLabel: l10n.get('saveDraft'),
  558. rightLabel: l10n.get('submit'),
  559. centerTextOnly: true,
  560. onCenterTap: () async {
  561. FocusScope.of(context).unfocus();
  562. try {
  563. await _saveDraftToStorage();
  564. if (mounted) _forcePop();
  565. } catch (_) {
  566. if (mounted) {
  567. TDToast.showFail(l10n.get('saveFailed'), context: context);
  568. }
  569. }
  570. },
  571. onRightTap: () async {
  572. final err = _validate(l10n);
  573. if (err.isNotEmpty) {
  574. TDToast.showText(err.first, context: context);
  575. return;
  576. }
  577. FocusScope.of(context).unfocus();
  578. LoadingDialog.show(context, text: l10n.get('submitting'));
  579. try {
  580. final data = _buildSubmitData();
  581. final api = ref.read(vehicleApplyApiProvider);
  582. final billNo = await api.submit(data);
  583. await DraftStorage.delete(_draftKey);
  584. if (!mounted) return;
  585. LoadingDialog.hide(context);
  586. if (billNo != null) {
  587. final dd = data['HeadData']['YC_DD']?.toString() ?? '';
  588. await AuditFlowHelper.handle(
  589. context: context,
  590. l10n: l10n,
  591. getConfig: () => api.getBillAuditConfig('YC'),
  592. onShSubmit: () =>
  593. api.shSubmit(bilId: 'YC', bilNo: billNo, bilDd: dd),
  594. );
  595. }
  596. if (mounted) {
  597. TDToast.showSuccess(l10n.get('billCreated'), context: context);
  598. GoRouter.of(context).go('/vehicle-apply/list');
  599. }
  600. } catch (e) {
  601. if (mounted) LoadingDialog.hide(context);
  602. }
  603. },
  604. );
  605. }
  606. Map<String, dynamic> _buildSubmitData() {
  607. return {
  608. 'HeadData': {
  609. 'YC_DD': _today(),
  610. 'SAL_NO': _selectedApplicantId.isNotEmpty
  611. ? _selectedApplicantId
  612. : HostAppChannel.usr,
  613. 'DEP': _selectedDeptId,
  614. 'REASON': _reasonController.text.trim(),
  615. 'ORIGIN_ADR': _originAdr,
  616. 'DEST_ADR': _destAdr,
  617. 'PASSENGER_COUNT': _passengers.length,
  618. 'PASSENGER_NAME': _passengers
  619. .map((p) => '${p.salNo}/${p.name.isNotEmpty ? p.name : p.salNo}')
  620. .join(';'),
  621. 'LICENSEPLATE': _licensePlate,
  622. 'VEHICLE_TYPE': _vehicleType,
  623. 'BRAND': _brand,
  624. 'ODOMETER_BEGIN': _odometerBegin,
  625. 'SEATS': _seats,
  626. 'DRIVER_NAME': _driverName,
  627. 'START_TIME': _startTime?.toIso8601String(),
  628. 'END_TIME': _endTime?.toIso8601String(),
  629. 'USR': HostAppChannel.usr,
  630. },
  631. };
  632. }
  633. List<String> _validate(AppLocalizations l10n) {
  634. final e = <String>[];
  635. if (_reasonController.text.trim().isEmpty) {
  636. e.add(l10n.get('enterVehicleReason'));
  637. }
  638. if (_licensePlate.isEmpty) e.add(l10n.get('selectLicensePlateHint'));
  639. if (_startTime == null) {
  640. e.add(l10n.get('selectDepartTime'));
  641. }
  642. if (_endTime == null) {
  643. e.add(l10n.get('selectReturnTime'));
  644. }
  645. if (_startTime != null &&
  646. _endTime != null &&
  647. !_endTime!.isAfter(_startTime!)) {
  648. e.add(l10n.get('returnTimeMustLater'));
  649. }
  650. return e;
  651. }
  652. // ═══ 草稿 ═══
  653. Future<void> _saveDraftToStorage() async {
  654. await DraftStorage.save(_draftKey, {
  655. 'reason': _reasonController.text,
  656. 'originAdr': _originAdr,
  657. 'destAdr': _destAdr,
  658. 'startTime': _startTime?.toIso8601String(),
  659. 'endTime': _endTime?.toIso8601String(),
  660. 'licensePlate': _licensePlate,
  661. 'vehicleType': _vehicleType,
  662. 'brand': _brand,
  663. 'odometerBegin': _odometerBegin,
  664. 'seats': _seats,
  665. 'driverName': _driverName,
  666. 'passengerCount': _passengers.length,
  667. 'passengerName': _passengers.map((p) => '${p.salNo}/${p.name}').join(';'),
  668. 'selectedDeptId': _selectedDeptId,
  669. 'selectedDeptName': _selectedDeptName,
  670. });
  671. }
  672. void _doPop() {
  673. if (_hasUnsaved()) {
  674. final l10n = AppLocalizations.of(context);
  675. _showConfirmDialog(
  676. l10n.get('confirmExit'),
  677. l10n.get('unsavedContentWarning'),
  678. l10n.get('continueEditing'),
  679. l10n.get('discardAndExit'),
  680. () {
  681. DraftStorage.delete(_draftKey);
  682. _forcePop();
  683. },
  684. );
  685. } else {
  686. _forcePop();
  687. }
  688. }
  689. void _forcePop() {
  690. FocusManager.instance.primaryFocus?.unfocus();
  691. final router = GoRouter.of(context);
  692. if (router.canPop()) {
  693. router.pop();
  694. } else {
  695. SystemNavigator.pop();
  696. }
  697. }
  698. bool _hasUnsaved() {
  699. // 同行人排除自动带出的当前用户
  700. final usr = HostAppChannel.usr;
  701. final hasCustomPassengers = _passengers.any((p) => p.salNo != usr);
  702. // 驾驶员排除自动带出的当前用户
  703. final selfEmployee = _employees.where((e) => e.salNo == usr);
  704. final isDefaultDriver =
  705. selfEmployee.isNotEmpty && _driverName == selfEmployee.first.name;
  706. return _reasonController.text.isNotEmpty ||
  707. _originAdr.isNotEmpty ||
  708. _destAdr.isNotEmpty ||
  709. _startTime != null ||
  710. _endTime != null ||
  711. _licensePlate.isNotEmpty ||
  712. _vehicleType.isNotEmpty ||
  713. _brand.isNotEmpty ||
  714. _seats > 0 ||
  715. (_driverName.isNotEmpty && !isDefaultDriver) ||
  716. hasCustomPassengers ||
  717. _odometerBegin > 0;
  718. }
  719. void _showConfirmDialog(
  720. String title,
  721. String content,
  722. String leftText,
  723. String rightText,
  724. VoidCallback onConfirm,
  725. ) {
  726. FocusScope.of(context).unfocus();
  727. FocusManager.instance.primaryFocus?.unfocus();
  728. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  729. showDialog(
  730. context: context,
  731. useRootNavigator: true,
  732. builder: (ctx) => TDAlertDialog(
  733. title: title,
  734. content: content,
  735. buttonStyle: TDDialogButtonStyle.text,
  736. leftBtn: TDDialogButtonOptions(
  737. title: leftText,
  738. titleColor: colors.primary,
  739. action: () => Navigator.pop(ctx),
  740. ),
  741. rightBtn: TDDialogButtonOptions(
  742. title: rightText,
  743. titleColor: colors.danger,
  744. action: () {
  745. Navigator.pop(ctx);
  746. onConfirm();
  747. },
  748. ),
  749. ),
  750. );
  751. }
  752. // ═══ 弹窗方法 ═══
  753. Future<void> _showTextInput(
  754. String title,
  755. void Function(String) onConfirm, {
  756. String initialText = '',
  757. }) async {
  758. FocusScope.of(context).unfocus();
  759. FocusManager.instance.primaryFocus?.unfocus();
  760. final result = await AppInputDialog.show(
  761. context: context,
  762. title: title,
  763. initialText: initialText,
  764. );
  765. if (result != null && mounted) {
  766. onConfirm(result);
  767. }
  768. }
  769. Future<void> _showNumberInput(
  770. String title,
  771. void Function(int) onSave,
  772. int current, {
  773. int min = 0,
  774. }) async {
  775. FocusScope.of(context).unfocus();
  776. FocusManager.instance.primaryFocus?.unfocus();
  777. final result = await AppInputDialog.show(
  778. context: context,
  779. title: title,
  780. initialText: current > 0 ? '$current' : '',
  781. inputType: AppInputType.integer,
  782. min: min,
  783. );
  784. if (result != null && mounted) {
  785. onSave(int.tryParse(result) ?? 0);
  786. }
  787. }
  788. void _pickDateTime(void Function(DateTime) onPicked, DateTime? initial) {
  789. FocusScope.of(context).unfocus();
  790. final l10n = AppLocalizations.of(context);
  791. final now = DateTime.now();
  792. final d = initial ?? now;
  793. TDPicker.showDatePicker(
  794. context,
  795. title: l10n.get('selectDateTime'),
  796. useYear: true,
  797. useMonth: true,
  798. useDay: true,
  799. useHour: true,
  800. useMinute: true,
  801. dateStart: [now.year - 1, 1, 1, 0, 0],
  802. dateEnd: [now.year + 10, 12, 31, 23, 59],
  803. initialDate: [d.year, d.month, d.day, d.hour, d.minute],
  804. onConfirm: (selected) {
  805. Navigator.of(context).pop();
  806. onPicked(
  807. DateTime(
  808. selected['year']!,
  809. selected['month']!,
  810. selected['day']!,
  811. selected['hour']!,
  812. selected['minute']!,
  813. ),
  814. );
  815. },
  816. );
  817. }
  818. Future<void> _showApplicantPicker() async {
  819. FocusScope.of(context).unfocus();
  820. FocusManager.instance.primaryFocus?.unfocus();
  821. final l10n = AppLocalizations.of(context);
  822. final api = ref.read(vehicleApplyApiProvider);
  823. final result = await showSearchablePicker<EmployeeItem>(
  824. context,
  825. title: '${l10n.get('select')}${l10n.get('applicant')}',
  826. searchHint: l10n.get('search'),
  827. loader: (keyword, page) =>
  828. api.getEmployees(keyword: keyword, page: page, size: 20),
  829. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  830. );
  831. if (result != null && mounted) {
  832. setState(() {
  833. _selectedApplicantId = result.salNo;
  834. _selectedApplicantName = result.name;
  835. });
  836. }
  837. }
  838. Future<void> _showDeptPicker() async {
  839. FocusScope.of(context).unfocus();
  840. FocusManager.instance.primaryFocus?.unfocus();
  841. final l10n = AppLocalizations.of(context);
  842. final api = ref.read(vehicleApplyApiProvider);
  843. final result = await showSearchablePicker<DepartmentItem>(
  844. context,
  845. title: '${l10n.get('select')}${l10n.get('applyDept')}',
  846. searchHint: l10n.get('search'),
  847. loader: (keyword, page) =>
  848. api.getDepartments(keyword: keyword, page: page, size: 20),
  849. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  850. );
  851. if (result != null && mounted) {
  852. setState(() {
  853. _selectedDeptId = result.dep;
  854. _selectedDeptName = result.name;
  855. });
  856. }
  857. }
  858. void _showVehicleTypePicker(AppLocalizations l10n) {
  859. FocusScope.of(context).unfocus();
  860. FocusManager.instance.primaryFocus?.unfocus();
  861. final labels = _mockVehicleTypes
  862. .map((t) => _vehicleTypeLabel(t, l10n))
  863. .toList();
  864. TDPicker.showMultiPicker(
  865. context,
  866. title: l10n.get('selectVehicleType'),
  867. data: [labels],
  868. onConfirm: (selected) {
  869. if (selected.isNotEmpty) {
  870. final idx = selected.first is int ? selected.first as int : 0;
  871. if (idx >= 0 && idx < _mockVehicleTypes.length) {
  872. setState(() => _vehicleType = _mockVehicleTypes[idx]);
  873. }
  874. }
  875. Navigator.of(context).pop();
  876. },
  877. );
  878. }
  879. Future<void> _showMultiEmployeePicker(AppLocalizations l10n) async {
  880. FocusScope.of(context).unfocus();
  881. FocusManager.instance.primaryFocus?.unfocus();
  882. final api = ref.read(vehicleApplyApiProvider);
  883. final selected = await showSearchableMultiPicker<EmployeeItem>(
  884. context,
  885. title: '${l10n.get('select')}${l10n.get('companion')}',
  886. searchHint: l10n.get('search'),
  887. loader: (keyword, page) =>
  888. api.getEmployees(keyword: keyword, page: page, size: 20),
  889. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  890. );
  891. if (mounted) {
  892. setState(() {
  893. for (final emp in selected) {
  894. if (!_passengers.any((p) => p.salNo == emp.salNo)) {
  895. _passengers.add(emp);
  896. }
  897. }
  898. });
  899. }
  900. }
  901. Future<void> _showDriverPicker() async {
  902. FocusManager.instance.primaryFocus?.unfocus();
  903. final l10n = AppLocalizations.of(context);
  904. final api = ref.read(vehicleApplyApiProvider);
  905. final result = await showSearchablePicker<EmployeeItem>(
  906. context,
  907. title: '${l10n.get('select')}${l10n.get('driverName')}',
  908. searchHint: l10n.get('search'),
  909. loader: (keyword, page) =>
  910. api.getEmployees(keyword: keyword, page: page, size: 20),
  911. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  912. );
  913. if (result != null && mounted) {
  914. setState(() {
  915. _driverName = result.name;
  916. });
  917. }
  918. }
  919. // ═══ 工具方法 ═══
  920. Widget _label(String t, {bool required = false}) {
  921. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  922. return Text.rich(
  923. TextSpan(
  924. children: [
  925. TextSpan(
  926. text: t,
  927. style: TextStyle(
  928. fontSize: AppFontSizes.subtitle,
  929. color: colors.textSecondary,
  930. ),
  931. ),
  932. if (required)
  933. TextSpan(
  934. text: ' *',
  935. style: TextStyle(
  936. fontSize: AppFontSizes.subtitle,
  937. color: colors.danger,
  938. ),
  939. ),
  940. ],
  941. ),
  942. );
  943. }
  944. Widget _buildPageFooter() {
  945. final l10n = AppLocalizations.of(context);
  946. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  947. return Center(
  948. child: Padding(
  949. padding: const EdgeInsets.only(bottom: 16),
  950. child: Row(
  951. mainAxisSize: MainAxisSize.min,
  952. children: [
  953. Icon(
  954. Icons.rocket_launch_outlined,
  955. size: 16,
  956. color: colors.textPlaceholder,
  957. ),
  958. const SizedBox(width: 6),
  959. Text(
  960. l10n.get('pageFooter'),
  961. style: TextStyle(
  962. fontSize: AppFontSizes.caption,
  963. color: colors.textPlaceholder,
  964. ),
  965. ),
  966. ],
  967. ),
  968. ),
  969. );
  970. }
  971. String _today() {
  972. final n = DateTime.now();
  973. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  974. }
  975. String _formatDateTime(DateTime d) {
  976. return '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')} ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
  977. }
  978. String _vehicleTypeLabel(String key, AppLocalizations l10n) {
  979. switch (key) {
  980. case 'sedan':
  981. return l10n.get('sedan');
  982. case 'suv':
  983. return 'SUV';
  984. case 'mpv':
  985. return l10n.get('businessVan');
  986. case 'van':
  987. return l10n.get('van');
  988. case 'truck':
  989. return l10n.get('truck');
  990. case 'pickup':
  991. return l10n.get('pickup');
  992. case 'minibus':
  993. return l10n.get('minibus');
  994. case 'bus':
  995. return l10n.get('bus');
  996. default:
  997. return key;
  998. }
  999. }
  1000. }