vehicle_apply_edit_page.dart 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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(bilId: 'YC', bilNo: billNo, bilDd: dd),
  773. );
  774. }
  775. if (mounted) {
  776. TDToast.showSuccess(l10n.get('billModified'), context: context);
  777. GoRouter.of(context).go('/vehicle-apply/list');
  778. }
  779. } catch (e) {
  780. if (mounted) LoadingDialog.hide(context);
  781. }
  782. },
  783. );
  784. }
  785. Map<String, dynamic> _buildSubmitData() {
  786. return {
  787. 'HeadData': {
  788. 'YC_NO': _billNo,
  789. 'YC_DD': _applyDate,
  790. 'SAL_NO': _selectedApplicantId.isNotEmpty
  791. ? _selectedApplicantId
  792. : HostAppChannel.usr,
  793. 'DEP': _selectedDeptId,
  794. 'REASON': _reasonController.text.trim(),
  795. 'ORIGIN_ADR': _originAdr,
  796. 'ORIGIN_LONGITUDE': _originLng,
  797. 'ORIGIN_LATITUDE': _originLat,
  798. 'DEST_ADR': _destAdr,
  799. 'DEST_LONGITUDE': _destLng,
  800. 'DEST_LATITUDE': _destLat,
  801. 'PASSENGER_COUNT': _passengers.length,
  802. 'PASSENGER_NAME': _passengers
  803. .map((p) => '${p.salNo}/${p.name.isNotEmpty ? p.name : p.salNo}')
  804. .join(';'),
  805. 'LICENSEPLATE': _licensePlate,
  806. 'VEHICLE_TYPE': _vehicleType,
  807. 'BRAND': _brand,
  808. 'ODOMETER_BEGIN': _odometerBegin,
  809. 'SEATS': _seats,
  810. 'DRIVER_NAME': _driverName,
  811. 'START_TIME': _startTime?.toIso8601String(),
  812. 'END_TIME': _endTime?.toIso8601String(),
  813. 'USR': HostAppChannel.usr,
  814. },
  815. };
  816. }
  817. List<String> _validate(AppLocalizations l10n) {
  818. final e = <String>[];
  819. if (_selectedApplicantId.isEmpty) {
  820. e.add(l10n.get('selectApplicantHint'));
  821. }
  822. if (_reasonController.text.trim().isEmpty) {
  823. e.add(l10n.get('enterVehicleReason'));
  824. }
  825. if (_licensePlate.isEmpty) e.add(l10n.get('selectLicensePlateHint'));
  826. if (_startTime == null) {
  827. e.add(l10n.get('selectDepartTime'));
  828. }
  829. if (_endTime == null) {
  830. e.add(l10n.get('selectReturnTime'));
  831. }
  832. if (_startTime != null &&
  833. _endTime != null &&
  834. !_endTime!.isAfter(_startTime!)) {
  835. e.add(l10n.get('returnTimeMustLater'));
  836. }
  837. return e;
  838. }
  839. // ═══ 弹窗方法 ═══
  840. Future<void> _showTextInput(
  841. String title,
  842. void Function(String) onConfirm, {
  843. String initialText = '',
  844. }) async {
  845. FocusScope.of(context).unfocus();
  846. FocusManager.instance.primaryFocus?.unfocus();
  847. final result = await AppInputDialog.show(
  848. context: context,
  849. title: title,
  850. initialText: initialText,
  851. );
  852. if (result != null && mounted) {
  853. onConfirm(result);
  854. }
  855. }
  856. Future<void> _showNumberInput(
  857. String title,
  858. void Function(int) onSave,
  859. int current, {
  860. int min = 0,
  861. }) async {
  862. FocusScope.of(context).unfocus();
  863. FocusManager.instance.primaryFocus?.unfocus();
  864. final result = await AppInputDialog.show(
  865. context: context,
  866. title: title,
  867. initialText: current > 0 ? '$current' : '',
  868. inputType: AppInputType.integer,
  869. min: min,
  870. );
  871. if (result != null && mounted) {
  872. onSave(int.tryParse(result) ?? 0);
  873. }
  874. }
  875. void _pickDateTime(void Function(DateTime) onPicked, DateTime? initial) {
  876. FocusScope.of(context).unfocus();
  877. final l10n = AppLocalizations.of(context);
  878. final now = DateTime.now();
  879. final d = initial ?? now;
  880. TDPicker.showDatePicker(
  881. context,
  882. title: l10n.get('selectDateTime'),
  883. useYear: true,
  884. useMonth: true,
  885. useDay: true,
  886. useHour: true,
  887. useMinute: true,
  888. dateStart: [now.year - 1, 1, 1, 0, 0],
  889. dateEnd: [now.year + 10, 12, 31, 23, 59],
  890. initialDate: [d.year, d.month, d.day, d.hour, d.minute],
  891. onConfirm: (selected) {
  892. Navigator.of(context).pop();
  893. onPicked(
  894. DateTime(
  895. selected['year']!,
  896. selected['month']!,
  897. selected['day']!,
  898. selected['hour']!,
  899. selected['minute']!,
  900. ),
  901. );
  902. },
  903. );
  904. }
  905. Future<void> _showApplicantPicker() async {
  906. FocusScope.of(context).unfocus();
  907. FocusManager.instance.primaryFocus?.unfocus();
  908. final l10n = AppLocalizations.of(context);
  909. final api = ref.read(vehicleApplyApiProvider);
  910. final result = await showSearchablePicker<EmployeeItem>(
  911. context,
  912. title: '${l10n.get('select')}${l10n.get('applicant')}',
  913. searchHint: l10n.get('search'),
  914. loader: (keyword, page) =>
  915. api.getEmployees(keyword: keyword, page: page, size: 20),
  916. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  917. );
  918. if (result != null && mounted) {
  919. setState(() {
  920. _selectedApplicantId = result.salNo;
  921. _selectedApplicantName = result.name;
  922. });
  923. }
  924. }
  925. Future<void> _showDeptPicker() async {
  926. FocusManager.instance.primaryFocus?.unfocus();
  927. final l10n = AppLocalizations.of(context);
  928. final api = ref.read(vehicleApplyApiProvider);
  929. final result = await showSearchablePicker<DepartmentItem>(
  930. context,
  931. title: '${l10n.get('select')}${l10n.get('applyDept')}',
  932. searchHint: l10n.get('search'),
  933. loader: (keyword, page) =>
  934. api.getDepartments(keyword: keyword, page: page, size: 20),
  935. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  936. );
  937. if (result != null && mounted) {
  938. setState(() {
  939. _selectedDeptId = result.dep;
  940. _selectedDeptName = result.name;
  941. });
  942. }
  943. }
  944. void _showVehicleTypePicker(AppLocalizations l10n) {
  945. FocusScope.of(context).unfocus();
  946. final labels = _mockVehicleTypes
  947. .map((t) => _vehicleTypeLabel(t, l10n))
  948. .toList();
  949. TDPicker.showMultiPicker(
  950. context,
  951. title: l10n.get('selectVehicleType'),
  952. data: [labels],
  953. onConfirm: (selected) {
  954. final idx = labels.indexOf(selected.first);
  955. if (idx >= 0) setState(() => _vehicleType = _mockVehicleTypes[idx]);
  956. },
  957. );
  958. }
  959. Future<void> _showMultiEmployeePicker(AppLocalizations l10n) async {
  960. FocusScope.of(context).unfocus();
  961. FocusManager.instance.primaryFocus?.unfocus();
  962. final api = ref.read(vehicleApplyApiProvider);
  963. final selected = await showSearchableMultiPicker<EmployeeItem>(
  964. context,
  965. title: '${l10n.get('select')}${l10n.get('companion')}',
  966. searchHint: l10n.get('search'),
  967. loader: (keyword, page) =>
  968. api.getEmployees(keyword: keyword, page: page, size: 20),
  969. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  970. );
  971. if (mounted) {
  972. setState(() {
  973. for (final emp in selected) {
  974. if (!_passengers.any((p) => p.salNo == emp.salNo)) {
  975. _passengers.add(emp);
  976. }
  977. }
  978. });
  979. }
  980. }
  981. Future<void> _showDriverPicker() async {
  982. FocusManager.instance.primaryFocus?.unfocus();
  983. final l10n = AppLocalizations.of(context);
  984. final api = ref.read(vehicleApplyApiProvider);
  985. final result = await showSearchablePicker<EmployeeItem>(
  986. context,
  987. title: '${l10n.get('select')}${l10n.get('driverName')}',
  988. searchHint: l10n.get('search'),
  989. loader: (keyword, page) =>
  990. api.getEmployees(keyword: keyword, page: page, size: 20),
  991. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  992. );
  993. if (result != null && mounted) {
  994. setState(() {
  995. _driverName = result.name;
  996. });
  997. }
  998. }
  999. // ═══ 对话框 ═══
  1000. void _doPop() {
  1001. if (_hasUnsaved()) {
  1002. final l10n = AppLocalizations.of(context);
  1003. _showConfirmDialog(
  1004. l10n.get('confirmExit'),
  1005. l10n.get('unsavedContentWarning'),
  1006. l10n.get('continueEditing'),
  1007. l10n.get('discardAndExit'),
  1008. _forcePop,
  1009. );
  1010. } else {
  1011. _forcePop();
  1012. }
  1013. }
  1014. void _forcePop() {
  1015. FocusManager.instance.primaryFocus?.unfocus();
  1016. final router = GoRouter.of(context);
  1017. if (router.canPop()) {
  1018. router.pop();
  1019. } else {
  1020. SystemNavigator.pop();
  1021. }
  1022. }
  1023. bool _hasUnsaved() {
  1024. final usr = HostAppChannel.usr;
  1025. final hasCustomPassengers = _passengers.any((p) => p.salNo != usr);
  1026. final selfEmployee = _employees.where((e) => e.salNo == usr);
  1027. final isDefaultDriver =
  1028. selfEmployee.isNotEmpty && _driverName == selfEmployee.first.name;
  1029. return _reasonController.text.isNotEmpty ||
  1030. _originAdr.isNotEmpty ||
  1031. _destAdr.isNotEmpty ||
  1032. _startTime != null ||
  1033. _endTime != null ||
  1034. _licensePlate.isNotEmpty ||
  1035. _vehicleType.isNotEmpty ||
  1036. _brand.isNotEmpty ||
  1037. _seats > 0 ||
  1038. (_driverName.isNotEmpty && !isDefaultDriver) ||
  1039. hasCustomPassengers ||
  1040. _odometerBegin > 0;
  1041. }
  1042. void _showConfirmDialog(
  1043. String title,
  1044. String content,
  1045. String leftText,
  1046. String rightText,
  1047. VoidCallback onConfirm,
  1048. ) {
  1049. FocusScope.of(context).unfocus();
  1050. FocusManager.instance.primaryFocus?.unfocus();
  1051. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1052. showDialog(
  1053. context: context,
  1054. useRootNavigator: true,
  1055. builder: (ctx) => TDAlertDialog(
  1056. title: title,
  1057. content: content,
  1058. buttonStyle: TDDialogButtonStyle.text,
  1059. leftBtn: TDDialogButtonOptions(
  1060. title: leftText,
  1061. titleColor: colors.primary,
  1062. action: () => Navigator.pop(ctx),
  1063. ),
  1064. rightBtn: TDDialogButtonOptions(
  1065. title: rightText,
  1066. titleColor: colors.danger,
  1067. action: () {
  1068. Navigator.pop(ctx);
  1069. onConfirm();
  1070. },
  1071. ),
  1072. ),
  1073. );
  1074. }
  1075. // ═══ 工具方法 ═══
  1076. Widget _label(String t, {bool required = false}) {
  1077. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1078. return Text.rich(
  1079. TextSpan(
  1080. children: [
  1081. TextSpan(
  1082. text: t,
  1083. style: TextStyle(
  1084. fontSize: AppFontSizes.subtitle,
  1085. color: colors.textSecondary,
  1086. ),
  1087. ),
  1088. if (required)
  1089. TextSpan(
  1090. text: ' *',
  1091. style: TextStyle(
  1092. fontSize: AppFontSizes.subtitle,
  1093. color: colors.danger,
  1094. ),
  1095. ),
  1096. ],
  1097. ),
  1098. );
  1099. }
  1100. Widget _buildPageFooter() {
  1101. final l10n = AppLocalizations.of(context);
  1102. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1103. return Center(
  1104. child: Padding(
  1105. padding: const EdgeInsets.only(bottom: 16),
  1106. child: Row(
  1107. mainAxisSize: MainAxisSize.min,
  1108. children: [
  1109. Icon(
  1110. Icons.rocket_launch_outlined,
  1111. size: 16,
  1112. color: colors.textPlaceholder,
  1113. ),
  1114. const SizedBox(width: 6),
  1115. Text(
  1116. l10n.get('pageFooter'),
  1117. style: TextStyle(
  1118. fontSize: AppFontSizes.caption,
  1119. color: colors.textPlaceholder,
  1120. ),
  1121. ),
  1122. ],
  1123. ),
  1124. ),
  1125. );
  1126. }
  1127. String _formatDateTime(DateTime d) {
  1128. 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')}';
  1129. }
  1130. String _vehicleTypeLabel(String key, AppLocalizations l10n) {
  1131. switch (key) {
  1132. case 'sedan':
  1133. return l10n.get('sedan');
  1134. case 'suv':
  1135. return 'SUV';
  1136. case 'mpv':
  1137. return l10n.get('businessVan');
  1138. case 'van':
  1139. return l10n.get('van');
  1140. case 'truck':
  1141. return l10n.get('truck');
  1142. case 'pickup':
  1143. return l10n.get('pickup');
  1144. case 'minibus':
  1145. return l10n.get('minibus');
  1146. case 'bus':
  1147. return l10n.get('bus');
  1148. default:
  1149. return key;
  1150. }
  1151. }
  1152. }