vehicle_apply_edit_page.dart 37 KB

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