vehicle_apply_edit_page.dart 36 KB

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