vehicle_apply_edit_page.dart 35 KB

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