vehicle_apply_create_page.dart 36 KB

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