vehicle_apply_create_page.dart 32 KB

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