overtime_apply_create_page.dart 35 KB

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