overtime_apply_edit_page.dart 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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 'package:dio/dio.dart';
  10. import '../../core/network/api_exception.dart';
  11. import '../../shared/widgets/action_bar.dart';
  12. import '../../shared/widgets/loading_dialog.dart';
  13. import '../../shared/widgets/form_section.dart';
  14. import '../../shared/widgets/form_field_row.dart';
  15. import '../../shared/widgets/app_skeletons.dart';
  16. import '../../shared/widgets/nav_bar_config.dart';
  17. import '../../core/theme/app_colors.dart';
  18. import '../../core/theme/app_colors_extension.dart';
  19. import 'overtime_apply_api.dart';
  20. import 'widgets/overtime_apply_detail_dialog.dart';
  21. import '../../shared/widgets/searchable_picker_sheet.dart';
  22. import '../expense_apply/expense_apply_api.dart';
  23. class OvertimeApplyEditPage extends ConsumerStatefulWidget {
  24. final String billNo;
  25. const OvertimeApplyEditPage({super.key, required this.billNo});
  26. @override
  27. ConsumerState<OvertimeApplyEditPage> createState() =>
  28. _OvertimeApplyEditPageState();
  29. }
  30. class _OvertimeApplyEditPageState extends ConsumerState<OvertimeApplyEditPage> {
  31. // ── 原单数据 ──
  32. String _billNo = '';
  33. String _applyDate = '';
  34. // ── 基本信息 ──
  35. final _reasonController = TextEditingController();
  36. final _reasonFocus = FocusNode();
  37. final _remarkController = TextEditingController();
  38. final _remarkFocus = FocusNode();
  39. final _scrollCtrl = ScrollController();
  40. // ── 加班明细 ──
  41. final List<_DetailItem> _details = [];
  42. int _detailIdCounter = 1;
  43. // ── 参考数据(从 API 加载) ──
  44. bool _firstBuild = true;
  45. bool _refDataLoading = true;
  46. bool _loadingBill = true;
  47. String? _loadingError;
  48. bool _addingDetail = false;
  49. // ── 申请部门 ──
  50. String _selectedDeptId = '';
  51. String _selectedDeptName = '';
  52. // ── 申请人 ──
  53. String _selectedApplicantId = '';
  54. String _selectedApplicantName = '';
  55. List<EmployeeItem> _employees = [];
  56. @override
  57. void initState() {
  58. super.initState();
  59. SystemChrome.setSystemUIOverlayStyle(
  60. const SystemUiOverlayStyle(
  61. statusBarColor: Colors.transparent,
  62. statusBarIconBrightness: Brightness.dark,
  63. ),
  64. );
  65. _reasonFocus.addListener(() => _ensureVisible(_reasonFocus));
  66. _remarkFocus.addListener(() => _ensureVisible(_remarkFocus));
  67. _refDataLoading = true;
  68. _loadingBill = true;
  69. _loadRefData();
  70. _loadBillData();
  71. WidgetsBinding.instance.addPostFrameCallback((_) => _checkDataReady());
  72. }
  73. void _checkDataReady() {
  74. if (!_refDataLoading && !_loadingBill && mounted) {
  75. setState(() => _firstBuild = false);
  76. WidgetsBinding.instance.addPostFrameCallback((_) {
  77. if (mounted) setState(() {});
  78. });
  79. } else if (mounted) {
  80. WidgetsBinding.instance.addPostFrameCallback((_) => _checkDataReady());
  81. }
  82. }
  83. Future<void>? _refDataFuture;
  84. Future<void> _loadRefData({bool showLoading = false}) async {
  85. if (_refDataFuture != null) return _refDataFuture!;
  86. final completer = Completer<void>();
  87. _refDataFuture = completer.future;
  88. if (showLoading) {
  89. LoadingDialog.show(
  90. context,
  91. text: AppLocalizations.of(context).get('dataLoading'),
  92. );
  93. }
  94. try {
  95. final api = ref.read(overtimeApplyApiProvider);
  96. final results = await Future.wait([
  97. api.getDepartments(),
  98. api.getEmployees(),
  99. ]);
  100. if (!mounted) return;
  101. setState(() {
  102. _employees = results[1] as List<EmployeeItem>;
  103. _refDataLoading = false;
  104. _autoSelectApplicant();
  105. });
  106. completer.complete();
  107. } catch (_) {
  108. if (!mounted) {
  109. completer.complete();
  110. return;
  111. }
  112. setState(() => _refDataLoading = false);
  113. completer.complete();
  114. } finally {
  115. if (showLoading && mounted) LoadingDialog.hide(context);
  116. _refDataFuture = null;
  117. }
  118. }
  119. Future<void> _loadBillData() async {
  120. try {
  121. final api = ref.read(overtimeApplyApiProvider);
  122. final detail = await api.fetchDetail(widget.billNo);
  123. if (!mounted) return;
  124. final n = detail.jbDd ?? DateTime.now();
  125. final applyDate =
  126. '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  127. setState(() {
  128. _billNo = detail.jbNo;
  129. _applyDate = applyDate;
  130. _selectedDeptId = detail.dep;
  131. _selectedDeptName = detail.depName;
  132. _selectedApplicantId = detail.salNo;
  133. _selectedApplicantName = detail.salName;
  134. _reasonController.text = detail.reason;
  135. _remarkController.text = detail.rem;
  136. // 加班明细回填
  137. _details.clear();
  138. _detailIdCounter = 1;
  139. for (final d in detail.details) {
  140. String jbDateStr = '';
  141. String startTimeStr = '';
  142. String endTimeStr = '';
  143. if (d.jbDate != null) {
  144. final s = d.jbDate!;
  145. jbDateStr =
  146. '${s.year}-${s.month.toString().padLeft(2, '0')}-${s.day.toString().padLeft(2, '0')}';
  147. }
  148. if (d.startTime != null) {
  149. final st = d.startTime!;
  150. startTimeStr =
  151. '${st.year}-${st.month.toString().padLeft(2, '0')}-${st.day.toString().padLeft(2, '0')} '
  152. '${st.hour.toString().padLeft(2, '0')}:${st.minute.toString().padLeft(2, '0')}';
  153. }
  154. if (d.endTime != null) {
  155. final et = d.endTime!;
  156. endTimeStr =
  157. '${et.year}-${et.month.toString().padLeft(2, '0')}-${et.day.toString().padLeft(2, '0')} '
  158. '${et.hour.toString().padLeft(2, '0')}:${et.minute.toString().padLeft(2, '0')}';
  159. }
  160. _details.add(
  161. _DetailItem(
  162. id: _detailIdCounter++,
  163. jbNo: d.jbNo,
  164. itm: d.itm,
  165. salNo: d.salNo,
  166. salName: d.salName,
  167. dep: d.dep,
  168. depName: d.depName,
  169. jbType: d.jbType,
  170. jbDate: jbDateStr,
  171. startTime: startTimeStr,
  172. endTime: endTimeStr,
  173. jbHours: d.jbHours,
  174. jbDays: d.jbDays,
  175. attPeriod: d.attPeriod,
  176. reason: d.reason,
  177. compensationType: d.compensationType,
  178. compensationCount: d.compensationCount,
  179. adr: d.adr,
  180. rem: d.rem,
  181. preItm: d.itm > 0 ? d.itm : null,
  182. ),
  183. );
  184. }
  185. _loadingBill = false;
  186. });
  187. } catch (e) {
  188. if (!mounted) return;
  189. setState(() {
  190. _loadingBill = false;
  191. _loadingError = e.toString();
  192. });
  193. }
  194. }
  195. void _autoSelectApplicant() {
  196. if (_selectedApplicantId.isNotEmpty) return;
  197. final usr = HostAppChannel.usr;
  198. if (usr.isEmpty) return;
  199. final match = _employees.where((e) => e.salNo == usr);
  200. if (match.isNotEmpty) {
  201. _selectedApplicantId = match.first.salNo;
  202. _selectedApplicantName = match.first.name;
  203. }
  204. }
  205. Future<void> _showApplicantPicker() async {
  206. FocusScope.of(context).unfocus();
  207. FocusManager.instance.primaryFocus?.unfocus();
  208. final l10n = AppLocalizations.of(context);
  209. final api = ref.read(overtimeApplyApiProvider);
  210. final result = await showSearchablePicker<EmployeeItem>(
  211. context,
  212. title: '${l10n.get('select')}${l10n.get('applicant')}',
  213. searchHint: l10n.get('search'),
  214. loader: (keyword, page) =>
  215. api.getEmployees(keyword: keyword, page: page, size: 20),
  216. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  217. );
  218. if (result != null && mounted) {
  219. setState(() {
  220. _selectedApplicantId = result.salNo;
  221. _selectedApplicantName = result.name;
  222. });
  223. }
  224. }
  225. void _ensureVisible(FocusNode node) {
  226. if (!node.hasFocus) return;
  227. WidgetsBinding.instance.addPostFrameCallback((_) {
  228. if (node.hasFocus && _scrollCtrl.hasClients) {
  229. final ctx = node.context;
  230. if (ctx != null) {
  231. Scrollable.ensureVisible(
  232. ctx,
  233. alignment: 0.3,
  234. duration: const Duration(milliseconds: 300),
  235. );
  236. }
  237. }
  238. });
  239. }
  240. @override
  241. void dispose() {
  242. _reasonController.dispose();
  243. _reasonFocus.dispose();
  244. _remarkController.dispose();
  245. _remarkFocus.dispose();
  246. _scrollCtrl.dispose();
  247. super.dispose();
  248. }
  249. @override
  250. Widget build(BuildContext context) {
  251. final l10n = AppLocalizations.of(context);
  252. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  253. if (_loadingError != null) {
  254. return Center(
  255. child: Column(
  256. mainAxisSize: MainAxisSize.min,
  257. children: [
  258. Icon(Icons.error_outline, size: 48, color: colors.danger),
  259. const SizedBox(height: 16),
  260. Padding(
  261. padding: const EdgeInsets.symmetric(horizontal: 32),
  262. child: Text(
  263. _loadingError!,
  264. textAlign: TextAlign.center,
  265. style: TextStyle(
  266. fontSize: AppFontSizes.body,
  267. color: colors.textSecondary,
  268. ),
  269. ),
  270. ),
  271. const SizedBox(height: 16),
  272. TDButton(
  273. text: l10n.get('retry'),
  274. size: TDButtonSize.medium,
  275. onTap: () {
  276. setState(() {
  277. _loadingError = null;
  278. _loadingBill = true;
  279. });
  280. _loadBillData();
  281. },
  282. ),
  283. ],
  284. ),
  285. );
  286. }
  287. if (_firstBuild) {
  288. return const SkeletonFormPage(sectionRows: [5, 3], bottomButtonCount: 1);
  289. }
  290. Future.microtask(
  291. () => ref.read(pageBackProvider.notifier).state = () => _doPop(),
  292. );
  293. return PopScope(
  294. canPop: false,
  295. onPopInvokedWithResult: (didPop, _) {
  296. if (didPop) return;
  297. _doPop();
  298. },
  299. child: Column(
  300. children: [
  301. Expanded(
  302. child: GestureDetector(
  303. onTap: () => FocusScope.of(context).unfocus(),
  304. child: SingleChildScrollView(
  305. controller: _scrollCtrl,
  306. padding: const EdgeInsets.all(16),
  307. child: Column(
  308. children: [
  309. _buildBasicInfo(l10n),
  310. const SizedBox(height: 16),
  311. _buildDetailsSection(l10n),
  312. const SizedBox(height: 24),
  313. _buildPageFooter(),
  314. ],
  315. ),
  316. ),
  317. ),
  318. ),
  319. _buildBottomBar(l10n),
  320. ],
  321. ),
  322. );
  323. }
  324. // ═══ 1. 基本信息 ═══
  325. Widget _buildBasicInfo(AppLocalizations l10n) {
  326. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  327. return FormSection(
  328. title: l10n.get('basicInfo'),
  329. leadingIcon: Icons.info_outline,
  330. children: [
  331. FormFieldRow(
  332. label: l10n.get('overtimeApplyNo'),
  333. value: _billNo,
  334. readOnly: true,
  335. showArrow: false,
  336. ),
  337. const SizedBox(height: 16),
  338. FormFieldRow(
  339. label: l10n.get('date'),
  340. value: _applyDate,
  341. readOnly: true,
  342. showArrow: false,
  343. ),
  344. const SizedBox(height: 16),
  345. FormFieldRow(
  346. label: l10n.get('dep'),
  347. value: _selectedDeptId.isNotEmpty
  348. ? '$_selectedDeptId/$_selectedDeptName'
  349. : '',
  350. hint: l10n.get('pleaseSelect'),
  351. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  352. ),
  353. const SizedBox(height: 16),
  354. FormFieldRow(
  355. label: l10n.get('applicant'),
  356. required: true,
  357. value: _selectedApplicantId.isNotEmpty
  358. ? '$_selectedApplicantId/$_selectedApplicantName'
  359. : '',
  360. hint: l10n.get('pleaseSelect'),
  361. onTap: () => _showApplicantPicker(),
  362. ),
  363. const SizedBox(height: 16),
  364. _label(l10n.get('overtimeReason'), required: true),
  365. const SizedBox(height: 8),
  366. TDTextarea(
  367. controller: _reasonController,
  368. focusNode: _reasonFocus,
  369. hintText: l10n.get('enterOvertimeReason'),
  370. maxLines: 4,
  371. minLines: 1,
  372. maxLength: 1000,
  373. indicator: true,
  374. padding: EdgeInsets.zero,
  375. bordered: true,
  376. backgroundColor: colors.bgPage,
  377. ),
  378. const SizedBox(height: 16),
  379. _label(l10n.get('remark')),
  380. const SizedBox(height: 8),
  381. TDTextarea(
  382. controller: _remarkController,
  383. focusNode: _remarkFocus,
  384. hintText: l10n.get('enterRemark'),
  385. maxLines: 3,
  386. minLines: 1,
  387. maxLength: 500,
  388. indicator: true,
  389. padding: EdgeInsets.zero,
  390. bordered: true,
  391. backgroundColor: colors.bgPage,
  392. ),
  393. ],
  394. );
  395. }
  396. // ═══ 2. 加班明细 ═══
  397. Widget _buildDetailsSection(AppLocalizations l10n) {
  398. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  399. return FormSection(
  400. title: l10n.get('overtimeDetails'),
  401. leadingIcon: Icons.access_time_outlined,
  402. showAction: true,
  403. actionText: l10n.get('add'),
  404. onActionTap: _showDetailDialog,
  405. children: [
  406. if (_details.isEmpty)
  407. Padding(
  408. padding: const EdgeInsets.symmetric(vertical: 8),
  409. child: Text(
  410. l10n.get('noDetailHint'),
  411. style: TextStyle(
  412. fontSize: AppFontSizes.subtitle,
  413. color: colors.textPlaceholder,
  414. ),
  415. ),
  416. )
  417. else
  418. ..._details.asMap().entries.map((e) {
  419. final d = e.value;
  420. return GestureDetector(
  421. onTap: () => _showDetailDialog(editIndex: e.key),
  422. child: Container(
  423. margin: const EdgeInsets.symmetric(vertical: 6),
  424. padding: const EdgeInsets.all(12),
  425. decoration: BoxDecoration(
  426. color: colors.bgPage,
  427. borderRadius: BorderRadius.circular(8),
  428. ),
  429. child: Row(
  430. children: [
  431. Expanded(
  432. child: Column(
  433. crossAxisAlignment: CrossAxisAlignment.start,
  434. children: [
  435. Row(
  436. children: [
  437. Expanded(
  438. child: Text(
  439. '${d.salNo}${d.salName.isNotEmpty ? '/${d.salName}' : ''}',
  440. maxLines: 1,
  441. overflow: TextOverflow.ellipsis,
  442. style: TextStyle(
  443. fontSize: AppFontSizes.body,
  444. fontWeight: FontWeight.w500,
  445. color: colors.textPrimary,
  446. ),
  447. ),
  448. ),
  449. Text(
  450. '${d.jbHours.toStringAsFixed(1)}${l10n.get('hours')}',
  451. style: TextStyle(
  452. fontSize: AppFontSizes.body,
  453. fontWeight: FontWeight.w600,
  454. color: colors.timePrimary,
  455. ),
  456. ),
  457. ],
  458. ),
  459. if (d.jbType.isNotEmpty) ...[
  460. const SizedBox(height: 2),
  461. _detailLabel(
  462. '${l10n.get('jbType')}: ${_jbTypeLabel(d.jbType, l10n)}',
  463. colors,
  464. ),
  465. _detailLabel(
  466. '${l10n.get('applyDate')}: ${d.jbDate}',
  467. colors,
  468. ),
  469. ],
  470. if (d.startTime.isNotEmpty) ...[
  471. const SizedBox(height: 2),
  472. Row(
  473. crossAxisAlignment: CrossAxisAlignment.center,
  474. children: [
  475. Expanded(
  476. child: _detailLabel(
  477. '${l10n.get('startTime')}: ${d.startTime}',
  478. colors,
  479. ),
  480. ),
  481. if (_dayOfWeekLabel(d.startTime, l10n) != null)
  482. _dayOfWeekTag(
  483. _dayOfWeekLabel(d.startTime, l10n)!,
  484. ),
  485. ],
  486. ),
  487. ],
  488. if (d.endTime.isNotEmpty) ...[
  489. const SizedBox(height: 2),
  490. Row(
  491. crossAxisAlignment: CrossAxisAlignment.center,
  492. children: [
  493. Expanded(
  494. child: _detailLabel(
  495. '${l10n.get('endTime')}: ${d.endTime}',
  496. colors,
  497. ),
  498. ),
  499. if (_dayOfWeekLabel(d.endTime, l10n) != null)
  500. _dayOfWeekTag(
  501. _dayOfWeekLabel(d.endTime, l10n)!,
  502. ),
  503. ],
  504. ),
  505. ],
  506. if (d.jbDays > 0) ...[
  507. const SizedBox(height: 2),
  508. _detailLabel(
  509. '${l10n.get('overtimeDays')}: ${d.jbDays.toStringAsFixed(1)}',
  510. colors,
  511. ),
  512. ],
  513. if (d.attPeriod.isNotEmpty) ...[
  514. const SizedBox(height: 2),
  515. _detailLabel(
  516. '${l10n.get('attPeriod')}: ${d.attPeriod}',
  517. colors,
  518. ),
  519. ],
  520. if (d.compensationType.isNotEmpty) ...[
  521. const SizedBox(height: 2),
  522. _detailLabel(
  523. '${l10n.get('compensationType')}: ${_compensationTypeLabel(d.compensationType, l10n)}',
  524. colors,
  525. ),
  526. if (d.compensationType != 'NO_COMPENSATION' &&
  527. d.compensationCount > 0)
  528. _detailLabel(
  529. '${l10n.get('compensationCount')}: ${d.compensationCount.toStringAsFixed(1)}',
  530. colors,
  531. ),
  532. ],
  533. if (d.adr.isNotEmpty) ...[
  534. const SizedBox(height: 2),
  535. _detailLabel(
  536. '${l10n.get('adr')}: ${d.adr}',
  537. colors,
  538. ),
  539. ],
  540. if (d.reason.isNotEmpty) ...[
  541. const SizedBox(height: 2),
  542. _detailLabel(
  543. '${l10n.get('overtimeDetailReason')}: ${d.reason}',
  544. colors,
  545. ),
  546. ],
  547. if (d.rem.isNotEmpty) ...[
  548. const SizedBox(height: 2),
  549. _detailLabel(
  550. '${l10n.get('remark')}: ${d.rem}',
  551. colors,
  552. ),
  553. ],
  554. ],
  555. ),
  556. ),
  557. const SizedBox(width: 8),
  558. GestureDetector(
  559. onTap: () => setState(() => _details.removeAt(e.key)),
  560. child: Icon(
  561. Icons.close,
  562. size: 18,
  563. color: colors.textSecondary,
  564. ),
  565. ),
  566. ],
  567. ),
  568. ),
  569. );
  570. }),
  571. const SizedBox(height: 8),
  572. Container(
  573. padding: const EdgeInsets.symmetric(vertical: 8),
  574. child: Row(
  575. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  576. children: [
  577. Text(
  578. l10n.get('totalOvertimeHours'),
  579. style: TextStyle(
  580. fontSize: AppFontSizes.body,
  581. fontWeight: FontWeight.w600,
  582. color: colors.textPrimary,
  583. ),
  584. ),
  585. Text(
  586. '${_totalHours().toStringAsFixed(1)}${l10n.get('hours')}',
  587. style: TextStyle(
  588. fontSize: AppFontSizes.subtitle,
  589. fontWeight: FontWeight.w700,
  590. color: colors.timePrimary,
  591. ),
  592. ),
  593. ],
  594. ),
  595. ),
  596. ],
  597. );
  598. }
  599. double _totalHours() => _details.fold(0.0, (s, d) => s + d.jbHours);
  600. String _jbTypeLabel(String type, AppLocalizations l10n) {
  601. switch (type) {
  602. case 'WORKING_DAY':
  603. return l10n.get('workingDay');
  604. case 'REST_DAY':
  605. return l10n.get('restDay');
  606. case 'PUBLIC_HOLIDAY':
  607. return l10n.get('publicHoliday');
  608. case 'SPECIAL_HOLIDAY':
  609. return l10n.get('specialHoliday');
  610. case 'OTHER':
  611. return l10n.get('other');
  612. default:
  613. return type;
  614. }
  615. }
  616. String? _dayOfWeekLabel(String dateTimeStr, AppLocalizations l10n) {
  617. final dt = DateTime.tryParse(dateTimeStr);
  618. if (dt == null) return null;
  619. switch (dt.weekday) {
  620. case 1:
  621. return l10n.get('monday');
  622. case 2:
  623. return l10n.get('tuesday');
  624. case 3:
  625. return l10n.get('wednesday');
  626. case 4:
  627. return l10n.get('thursday');
  628. case 5:
  629. return l10n.get('friday');
  630. case 6:
  631. return l10n.get('saturday');
  632. case 7:
  633. return l10n.get('sunday');
  634. default:
  635. return null;
  636. }
  637. }
  638. String _compensationTypeLabel(String type, AppLocalizations l10n) {
  639. switch (type) {
  640. case 'OVERTIME_PAY':
  641. return l10n.get('overtimePay');
  642. case 'COMPENSATORY_LEAVE':
  643. return l10n.get('compensatoryLeave');
  644. case 'NO_COMPENSATION':
  645. return l10n.get('noCompensation');
  646. case 'OTHER':
  647. return l10n.get('other');
  648. default:
  649. return type;
  650. }
  651. }
  652. Widget _detailLabel(String text, AppColorsExtension colors) {
  653. return Padding(
  654. padding: const EdgeInsets.only(top: 2),
  655. child: Text(
  656. text,
  657. maxLines: 2,
  658. overflow: TextOverflow.ellipsis,
  659. style: TextStyle(
  660. fontSize: AppFontSizes.caption,
  661. color: colors.textSecondary,
  662. ),
  663. ),
  664. );
  665. }
  666. Widget _dayOfWeekTag(String label) {
  667. final tdTheme = TDTheme.of(context);
  668. return Container(
  669. padding: const EdgeInsets.symmetric(horizontal: 6),
  670. decoration: BoxDecoration(
  671. color: tdTheme.brandColor1,
  672. borderRadius: BorderRadius.circular(4),
  673. ),
  674. child: TDText(
  675. label,
  676. font: tdTheme.fontBodySmall,
  677. fontWeight: FontWeight.w500,
  678. textColor: tdTheme.brandColor7,
  679. ),
  680. );
  681. }
  682. Future<void> _showDetailDialog({int? editIndex}) async {
  683. if (_addingDetail) return;
  684. _addingDetail = true;
  685. try {
  686. final l10n = AppLocalizations.of(context);
  687. OvertimeDetailData? initialData;
  688. if (editIndex != null) {
  689. final d = _details[editIndex];
  690. initialData = OvertimeDetailData(
  691. jbNo: d.jbNo,
  692. itm: d.itm > 0 ? d.itm : null,
  693. salNo: d.salNo,
  694. salName: d.salName,
  695. dep: d.dep,
  696. depName: d.depName,
  697. jbType: d.jbType,
  698. jbDate: d.jbDate,
  699. startTime: d.startTime,
  700. endTime: d.endTime,
  701. jbHours: d.jbHours,
  702. jbDays: d.jbDays,
  703. attPeriod: d.attPeriod,
  704. reason: d.reason,
  705. compensationType: d.compensationType,
  706. compensationCount: d.compensationCount,
  707. adr: d.adr,
  708. rem: d.rem,
  709. );
  710. }
  711. FocusManager.instance.primaryFocus?.unfocus();
  712. final result = await OvertimeApplyDetailDialog.show(
  713. // ignore: use_build_context_synchronously
  714. context,
  715. api: ref.read(overtimeApplyApiProvider),
  716. l10n: l10n,
  717. initialData: initialData,
  718. );
  719. if (result != null && mounted) {
  720. setState(() {
  721. final item = _DetailItem(
  722. id: editIndex != null ? _details[editIndex].id : _detailIdCounter++,
  723. jbNo: result.jbNo,
  724. itm: result.itm ?? 0,
  725. salNo: result.salNo,
  726. salName: result.salName,
  727. dep: result.dep,
  728. depName: result.depName,
  729. jbType: result.jbType,
  730. jbDate: result.jbDate,
  731. startTime: result.startTime,
  732. endTime: result.endTime,
  733. jbHours: result.jbHours,
  734. jbDays: result.jbDays,
  735. attPeriod: result.attPeriod,
  736. reason: result.reason,
  737. compensationType: result.compensationType,
  738. compensationCount: result.compensationCount,
  739. adr: result.adr,
  740. rem: result.rem,
  741. preItm: editIndex != null ? _details[editIndex].preItm : null,
  742. );
  743. if (editIndex != null) {
  744. _details[editIndex] = item;
  745. } else {
  746. _details.add(item);
  747. }
  748. });
  749. }
  750. } finally {
  751. _addingDetail = false;
  752. }
  753. }
  754. // ═══ 3. 底部操作栏 ═══
  755. Widget _buildBottomBar(AppLocalizations l10n) {
  756. return ActionBar(
  757. showLeft: false,
  758. showCenter: false,
  759. rightLabel: l10n.get('submit'),
  760. onRightTap: () async {
  761. final err = _validate(l10n);
  762. if (err.isNotEmpty) {
  763. TDToast.showText(err.first, context: context);
  764. return;
  765. }
  766. FocusScope.of(context).unfocus();
  767. LoadingDialog.show(context, text: l10n.get('submitting'));
  768. try {
  769. final data = _buildSubmitData();
  770. final api = ref.read(overtimeApplyApiProvider);
  771. final billNo = await api.submit(data);
  772. if (mounted) {
  773. LoadingDialog.hide(context);
  774. TDToast.showSuccess(l10n.get('submitSuccess'), context: context);
  775. // BillSave 成功后异步提交审核流,不阻塞不弹窗
  776. if (billNo != null) {
  777. api.shSubmit(
  778. bilNo: billNo,
  779. bilDd: data['HeadData']['JB_DD']?.toString() ?? '',
  780. );
  781. }
  782. GoRouter.of(context).go('/overtime-apply/list');
  783. }
  784. } catch (e) {
  785. if (mounted) {
  786. LoadingDialog.hide(context);
  787. WidgetsBinding.instance.addPostFrameCallback((_) {
  788. if (mounted) _showSubmitError(e, l10n);
  789. });
  790. }
  791. }
  792. },
  793. );
  794. }
  795. void _showSubmitError(Object e, AppLocalizations l10n) {
  796. final message = _extractErrorMessage(e) ?? l10n.get('submitFailedRetry');
  797. showGeneralDialog(
  798. context: context,
  799. pageBuilder: (ctx, animation, secondaryAnimation) => TDConfirmDialog(
  800. title: l10n.get('submitFailed'),
  801. content: message,
  802. buttonStyle: TDDialogButtonStyle.text,
  803. ),
  804. );
  805. }
  806. String? _extractErrorMessage(Object e) {
  807. if (e is DioException) {
  808. if (e.error is ApiException) return (e.error as ApiException).message;
  809. if (e.error is NetworkException) {
  810. return (e.error as NetworkException).message;
  811. }
  812. }
  813. return null;
  814. }
  815. Map<String, dynamic> _buildSubmitData() {
  816. return {
  817. 'HeadData': {
  818. 'JB_NO': _billNo,
  819. 'JB_DD': _applyDate,
  820. 'SAL_NO': _selectedApplicantId.isNotEmpty
  821. ? _selectedApplicantId
  822. : HostAppChannel.usr,
  823. 'DEP': _selectedDeptId,
  824. 'REASON': _reasonController.text.trim(),
  825. 'REM': _remarkController.text,
  826. 'USR': HostAppChannel.usr,
  827. },
  828. 'BodyData1': _details.asMap().entries.map((e) {
  829. final d = e.value;
  830. final item = <String, dynamic>{
  831. 'ITM': e.key + 1,
  832. 'SAL_NO': d.salNo,
  833. 'DEP': d.dep.isNotEmpty ? d.dep : _selectedDeptId,
  834. 'JB_TYPE': d.jbType,
  835. 'JB_DATE': d.jbDate,
  836. 'START_TIME': d.startTime,
  837. 'END_TIME': d.endTime,
  838. 'JB_HOURS': d.jbHours,
  839. 'JB_DAYS': d.jbDays,
  840. 'ATT_PERIOD': d.attPeriod,
  841. 'REASON': d.reason,
  842. 'COMPENSATION_TYPE': d.compensationType,
  843. 'COMPENSATION_COUNT': d.compensationCount,
  844. 'ADR': d.adr,
  845. 'REM': d.rem,
  846. };
  847. if (d.preItm != null) {
  848. item['PRE_ITM'] = d.preItm;
  849. }
  850. return item;
  851. }).toList(),
  852. };
  853. }
  854. List<String> _validate(AppLocalizations l10n) {
  855. final e = <String>[];
  856. if (_reasonController.text.trim().isEmpty) {
  857. e.add(l10n.get('enterOvertimeReason'));
  858. }
  859. if (_details.isEmpty) e.add(l10n.get('addAtLeastOneDetail'));
  860. if (_selectedDeptId.isEmpty) e.add(l10n.get('selectDept'));
  861. if (_selectedApplicantId.isEmpty) e.add(l10n.get('selectApplicant'));
  862. return e;
  863. }
  864. void _doPop() {
  865. if (_hasUnsaved()) {
  866. final l10n = AppLocalizations.of(context);
  867. _showConfirmDialog(
  868. l10n.get('confirmExit'),
  869. l10n.get('unsavedContentWarning'),
  870. l10n.get('continueEditing'),
  871. l10n.get('discardAndExit'),
  872. () => _forcePop(),
  873. );
  874. } else {
  875. _forcePop();
  876. }
  877. }
  878. void _forcePop() {
  879. FocusManager.instance.primaryFocus?.unfocus();
  880. final router = GoRouter.of(context);
  881. if (router.canPop()) {
  882. router.pop();
  883. } else {
  884. SystemNavigator.pop();
  885. }
  886. }
  887. bool _hasUnsaved() =>
  888. _reasonController.text.isNotEmpty ||
  889. _details.isNotEmpty ||
  890. _remarkController.text.isNotEmpty;
  891. void _showConfirmDialog(
  892. String title,
  893. String content,
  894. String leftText,
  895. String rightText,
  896. VoidCallback onConfirm,
  897. ) {
  898. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  899. showDialog(
  900. context: context,
  901. useRootNavigator: true,
  902. builder: (ctx) => TDAlertDialog(
  903. title: title,
  904. content: content,
  905. buttonStyle: TDDialogButtonStyle.text,
  906. leftBtn: TDDialogButtonOptions(
  907. title: leftText,
  908. titleColor: colors.primary,
  909. action: () => Navigator.pop(ctx),
  910. ),
  911. rightBtn: TDDialogButtonOptions(
  912. title: rightText,
  913. titleColor: colors.danger,
  914. action: () {
  915. Navigator.pop(ctx);
  916. onConfirm();
  917. },
  918. ),
  919. ),
  920. );
  921. }
  922. Widget _label(String t, {bool required = false}) {
  923. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  924. return Text.rich(
  925. TextSpan(
  926. children: [
  927. TextSpan(
  928. text: t,
  929. style: TextStyle(
  930. fontSize: AppFontSizes.subtitle,
  931. color: colors.textSecondary,
  932. ),
  933. ),
  934. if (required)
  935. TextSpan(
  936. text: ' *',
  937. style: TextStyle(
  938. fontSize: AppFontSizes.subtitle,
  939. color: colors.danger,
  940. ),
  941. ),
  942. ],
  943. ),
  944. );
  945. }
  946. Widget _buildPageFooter() {
  947. final l10n = AppLocalizations.of(context);
  948. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  949. return Center(
  950. child: Padding(
  951. padding: const EdgeInsets.only(bottom: 16),
  952. child: Row(
  953. mainAxisSize: MainAxisSize.min,
  954. children: [
  955. Icon(
  956. Icons.rocket_launch_outlined,
  957. size: 16,
  958. color: colors.textPlaceholder,
  959. ),
  960. const SizedBox(width: 6),
  961. Text(
  962. l10n.get('pageFooter'),
  963. style: TextStyle(
  964. fontSize: AppFontSizes.caption,
  965. color: colors.textPlaceholder,
  966. ),
  967. ),
  968. ],
  969. ),
  970. ),
  971. );
  972. }
  973. Future<void> _showDeptPicker() async {
  974. FocusManager.instance.primaryFocus?.unfocus();
  975. final l10n = AppLocalizations.of(context);
  976. final api = ref.read(overtimeApplyApiProvider);
  977. final result = await showSearchablePicker<DepartmentItem>(
  978. context,
  979. title: '${l10n.get('select')}${l10n.get('applyDept')}',
  980. searchHint: l10n.get('search'),
  981. loader: (keyword, page) =>
  982. api.getDepartments(keyword: keyword, page: page, size: 20),
  983. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  984. onRefresh: () => api.clearRefCache(),
  985. );
  986. if (result != null && mounted) {
  987. setState(() {
  988. _selectedDeptId = result.dep;
  989. _selectedDeptName = result.name;
  990. });
  991. }
  992. }
  993. }
  994. class _DetailItem {
  995. final int id;
  996. final String? jbNo;
  997. final int itm;
  998. final String salNo;
  999. final String salName;
  1000. final String dep;
  1001. final String depName;
  1002. final String jbType;
  1003. final String jbDate;
  1004. final String startTime;
  1005. final String endTime;
  1006. final double jbHours;
  1007. final double jbDays;
  1008. final String attPeriod;
  1009. final String reason;
  1010. final String compensationType;
  1011. final double compensationCount;
  1012. final String adr;
  1013. final String rem;
  1014. final int? preItm;
  1015. const _DetailItem({
  1016. required this.id,
  1017. this.jbNo,
  1018. this.itm = 0,
  1019. this.salNo = '',
  1020. this.salName = '',
  1021. this.dep = '',
  1022. this.depName = '',
  1023. this.jbType = 'WORKING_DAY',
  1024. this.jbDate = '',
  1025. this.startTime = '',
  1026. this.endTime = '',
  1027. this.jbHours = 0.0,
  1028. this.jbDays = 0.0,
  1029. this.attPeriod = '',
  1030. this.reason = '',
  1031. this.compensationType = '',
  1032. this.compensationCount = 0.0,
  1033. this.adr = '',
  1034. this.rem = '',
  1035. this.preItm,
  1036. });
  1037. }