vehicle_apply_create_page.dart 37 KB

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