vehicle_apply_create_page.dart 36 KB

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