vehicle_apply_create_page.dart 32 KB

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