vehicle_apply_create_page.dart 33 KB

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