vehicle_apply_create_page.dart 33 KB

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