overtime_apply_create_page.dart 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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('jbDate')}: ${d.jbDate}',
  494. colors,
  495. ),
  496. ],
  497. if (d.startTime.isNotEmpty) ...[
  498. const SizedBox(height: 2),
  499. _detailLabel(
  500. '${l10n.get('startTime')}: ${_fmtTime(d.startTime)}',
  501. colors,
  502. ),
  503. ],
  504. if (d.endTime.isNotEmpty) ...[
  505. const SizedBox(height: 2),
  506. _detailLabel(
  507. '${l10n.get('endTime')}: ${_fmtTime(d.endTime)}',
  508. colors,
  509. ),
  510. ],
  511. // TODO: 加班天数暂时隐藏
  512. // if (d.jbDays > 0) ...[
  513. // const SizedBox(height: 2),
  514. // _detailLabel(
  515. // '${l10n.get('overtimeDays')}: ${d.jbDays.toStringAsFixed(1)}',
  516. // colors,
  517. // ),
  518. // ],
  519. if (d.attPeriod.isNotEmpty) ...[
  520. const SizedBox(height: 2),
  521. _detailLabel(
  522. '${l10n.get('attPeriod')}: ${d.attPeriod}',
  523. colors,
  524. ),
  525. ],
  526. // TODO: 补偿类型、补偿次数暂时隐藏
  527. // if (d.compensationType.isNotEmpty) ...[
  528. // const SizedBox(height: 2),
  529. // _detailLabel(
  530. // '${l10n.get('compensationType')}: ${_compensationTypeLabel(d.compensationType, l10n)}',
  531. // colors,
  532. // ),
  533. // if (d.compensationType != 'NO_COMPENSATION' &&
  534. // d.compensationCount > 0)
  535. // _detailLabel(
  536. // '${l10n.get('compensationCount')}: ${d.compensationCount.toStringAsFixed(1)}',
  537. // colors,
  538. // ),
  539. // ],
  540. if (d.adr.isNotEmpty) ...[
  541. const SizedBox(height: 2),
  542. _detailLabel(
  543. '${l10n.get('adr')}: ${d.adr}',
  544. colors,
  545. ),
  546. ],
  547. if (d.reason.isNotEmpty) ...[
  548. const SizedBox(height: 2),
  549. _detailLabel(
  550. '${l10n.get('overtimeDetailReason')}: ${d.reason}',
  551. colors,
  552. ),
  553. ],
  554. if (d.rem.isNotEmpty) ...[
  555. const SizedBox(height: 2),
  556. _detailLabel(
  557. '${l10n.get('remark')}: ${d.rem}',
  558. colors,
  559. ),
  560. ],
  561. ],
  562. ),
  563. ),
  564. const SizedBox(width: 8),
  565. GestureDetector(
  566. onTap: () => setState(() => _details.removeAt(e.key)),
  567. child: Icon(
  568. Icons.close,
  569. size: 18,
  570. color: colors.textSecondary,
  571. ),
  572. ),
  573. ],
  574. ),
  575. ),
  576. );
  577. }),
  578. const SizedBox(height: 8),
  579. Container(
  580. padding: const EdgeInsets.symmetric(vertical: 8),
  581. child: Row(
  582. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  583. children: [
  584. Text(
  585. l10n.get('totalOvertimeHours'),
  586. style: TextStyle(
  587. fontSize: AppFontSizes.body,
  588. fontWeight: FontWeight.w600,
  589. color: colors.textPrimary,
  590. ),
  591. ),
  592. Text(
  593. '${_totalHours().toStringAsFixed(1)}${l10n.get('hours')}',
  594. style: TextStyle(
  595. fontSize: AppFontSizes.subtitle,
  596. fontWeight: FontWeight.w700,
  597. color: colors.timePrimary,
  598. ),
  599. ),
  600. ],
  601. ),
  602. ),
  603. ],
  604. );
  605. }
  606. double _totalHours() => _details.fold(0.0, (s, d) => s + d.jbHours);
  607. String _jbTypeLabel(String type, AppLocalizations l10n) {
  608. switch (type) {
  609. case 'WORKING_DAY':
  610. return l10n.get('workingDay');
  611. case 'REST_DAY':
  612. return l10n.get('restDay');
  613. case 'PUBLIC_HOLIDAY':
  614. return l10n.get('publicHoliday');
  615. case 'SPECIAL_HOLIDAY':
  616. return l10n.get('specialHoliday');
  617. case 'OTHER':
  618. return l10n.get('other');
  619. default:
  620. return type;
  621. }
  622. }
  623. String _fmtTime(String dt) {
  624. if (dt.length >= 16) return dt.substring(11, 16);
  625. return dt;
  626. }
  627. String? _dayOfWeekLabel(String dateTimeStr, AppLocalizations l10n) {
  628. final dt = DateTime.tryParse(dateTimeStr);
  629. if (dt == null) return null;
  630. switch (dt.weekday) {
  631. case 1:
  632. return l10n.get('monday');
  633. case 2:
  634. return l10n.get('tuesday');
  635. case 3:
  636. return l10n.get('wednesday');
  637. case 4:
  638. return l10n.get('thursday');
  639. case 5:
  640. return l10n.get('friday');
  641. case 6:
  642. return l10n.get('saturday');
  643. case 7:
  644. return l10n.get('sunday');
  645. default:
  646. return null;
  647. }
  648. }
  649. String _compensationTypeLabel(String type, AppLocalizations l10n) {
  650. switch (type) {
  651. case 'OVERTIME_PAY':
  652. return l10n.get('overtimePay');
  653. case 'COMPENSATORY_LEAVE':
  654. return l10n.get('compensatoryLeave');
  655. case 'NO_COMPENSATION':
  656. return l10n.get('noCompensation');
  657. case 'OTHER':
  658. return l10n.get('other');
  659. default:
  660. return type;
  661. }
  662. }
  663. Widget _detailLabel(String text, AppColorsExtension colors) {
  664. return Padding(
  665. padding: const EdgeInsets.only(top: 2),
  666. child: Text(
  667. text,
  668. maxLines: 2,
  669. overflow: TextOverflow.ellipsis,
  670. style: TextStyle(
  671. fontSize: AppFontSizes.caption,
  672. color: colors.textSecondary,
  673. ),
  674. ),
  675. );
  676. }
  677. Widget _dayOfWeekTag(String label) {
  678. final tdTheme = TDTheme.of(context);
  679. return Container(
  680. padding: const EdgeInsets.symmetric(horizontal: 6),
  681. decoration: BoxDecoration(
  682. color: tdTheme.brandColor1,
  683. borderRadius: BorderRadius.circular(4),
  684. ),
  685. child: TDText(
  686. label,
  687. font: tdTheme.fontBodySmall,
  688. fontWeight: FontWeight.w500,
  689. textColor: tdTheme.brandColor7,
  690. ),
  691. );
  692. }
  693. Future<void> _showDetailDialog({int? editIndex}) async {
  694. if (_addingDetail) return;
  695. _addingDetail = true;
  696. try {
  697. final l10n = AppLocalizations.of(context);
  698. OvertimeDetailData? initialData;
  699. if (editIndex != null) {
  700. final d = _details[editIndex];
  701. initialData = OvertimeDetailData(
  702. jbNo: d.jbNo,
  703. itm: d.itm > 0 ? d.itm : null,
  704. salNo: d.salNo,
  705. salName: d.salName,
  706. dep: d.dep,
  707. depName: d.depName,
  708. jbType: d.jbType,
  709. jbDate: d.jbDate,
  710. startTime: d.startTime,
  711. endTime: d.endTime,
  712. jbHours: d.jbHours,
  713. jbDays: d.jbDays,
  714. attPeriod: d.attPeriod,
  715. reason: d.reason,
  716. compensationType: d.compensationType,
  717. compensationCount: d.compensationCount,
  718. adr: d.adr,
  719. rem: d.rem,
  720. );
  721. }
  722. FocusManager.instance.primaryFocus?.unfocus();
  723. final result = await OvertimeApplyDetailDialog.show(
  724. // ignore: use_build_context_synchronously
  725. context,
  726. api: ref.read(overtimeApplyApiProvider),
  727. l10n: l10n,
  728. initialData: initialData,
  729. );
  730. if (result != null && mounted) {
  731. setState(() {
  732. final item = _DetailItem(
  733. id: editIndex != null ? _details[editIndex].id : _detailIdCounter++,
  734. jbNo: result.jbNo,
  735. itm: result.itm ?? 0,
  736. salNo: result.salNo,
  737. salName: result.salName,
  738. dep: result.dep,
  739. depName: result.depName,
  740. jbType: result.jbType,
  741. jbDate: result.jbDate,
  742. startTime: result.startTime,
  743. endTime: result.endTime,
  744. jbHours: result.jbHours,
  745. jbDays: result.jbDays,
  746. attPeriod: result.attPeriod,
  747. reason: result.reason,
  748. compensationType: result.compensationType,
  749. compensationCount: result.compensationCount,
  750. adr: result.adr,
  751. rem: result.rem,
  752. );
  753. if (editIndex != null) {
  754. _details[editIndex] = item;
  755. } else {
  756. _details.add(item);
  757. }
  758. });
  759. }
  760. } finally {
  761. _addingDetail = false;
  762. }
  763. }
  764. // ═══ 3. 底部操作栏 ═══
  765. Widget _buildBottomBar(AppLocalizations l10n) {
  766. return ActionBar(
  767. showLeft: false,
  768. centerLabel: l10n.get('saveDraft'),
  769. rightLabel: l10n.get('submit'),
  770. centerTextOnly: true,
  771. onCenterTap: () async {
  772. FocusScope.of(context).unfocus();
  773. try {
  774. await _saveDraftToStorage();
  775. if (mounted) _forcePop();
  776. } catch (_) {
  777. if (mounted) {
  778. TDToast.showFail(l10n.get('saveFailed'), context: context);
  779. }
  780. }
  781. },
  782. onRightTap: () async {
  783. final err = _validate(l10n);
  784. if (err.isNotEmpty) {
  785. TDToast.showText(err.first, context: context);
  786. return;
  787. }
  788. FocusScope.of(context).unfocus();
  789. LoadingDialog.show(context, text: l10n.get('submitting'));
  790. try {
  791. final data = _buildSubmitData();
  792. final api = ref.read(overtimeApplyApiProvider);
  793. final billNo = await api.submit(data);
  794. await DraftStorage.delete(_draftKey);
  795. if (!mounted) return;
  796. LoadingDialog.hide(context);
  797. if (billNo != null) {
  798. final dd = data['HeadData']['JB_DD']?.toString() ?? '';
  799. await AuditFlowHelper.handle(
  800. context: context,
  801. l10n: l10n,
  802. getConfig: () => api.getBillAuditConfig('JB'),
  803. onShSubmit: () => api.shSubmit(bilNo: billNo, bilDd: dd),
  804. );
  805. }
  806. if (mounted) {
  807. TDToast.showSuccess(l10n.get('billCreated'), context: context);
  808. GoRouter.of(context).go('/overtime-apply/list');
  809. }
  810. } catch (e) {
  811. if (mounted) LoadingDialog.hide(context);
  812. }
  813. },
  814. );
  815. }
  816. Map<String, dynamic> _buildSubmitData() {
  817. final now = DateTime.now();
  818. final jbDd =
  819. '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
  820. return {
  821. 'HeadData': {
  822. 'JB_DD': jbDd,
  823. 'SAL_NO': _selectedApplicantId.isNotEmpty
  824. ? _selectedApplicantId
  825. : HostAppChannel.usr,
  826. 'DEP': _selectedDeptId,
  827. 'REASON': _reasonController.text.trim(),
  828. 'REM': _remarkController.text,
  829. 'USR': HostAppChannel.usr,
  830. },
  831. 'BodyData1': _details.asMap().entries.map((e) {
  832. final d = e.value;
  833. return {
  834. 'ITM': e.key + 1,
  835. 'SAL_NO': d.salNo,
  836. 'DEP': d.dep.isNotEmpty ? d.dep : _selectedDeptId,
  837. 'JB_TYPE': d.jbType,
  838. 'JB_DATE': d.jbDate,
  839. 'START_TIME': d.startTime,
  840. 'END_TIME': d.endTime,
  841. 'JB_HOURS': d.jbHours,
  842. 'JB_DAYS': d.jbDays,
  843. 'ATT_PERIOD': d.attPeriod,
  844. 'REASON': d.reason,
  845. 'COMPENSATION_TYPE': d.compensationType,
  846. 'COMPENSATION_COUNT': d.compensationCount,
  847. 'ADR': d.adr,
  848. 'REM': d.rem,
  849. };
  850. }).toList(),
  851. };
  852. }
  853. List<String> _validate(AppLocalizations l10n) {
  854. final e = <String>[];
  855. if (_reasonController.text.trim().isEmpty) {
  856. e.add(l10n.get('enterOvertimeReason'));
  857. }
  858. if (_details.isEmpty) e.add(l10n.get('addAtLeastOneOTDetail'));
  859. if (_selectedDeptId.isEmpty) e.add(l10n.get('selectDept'));
  860. if (_selectedApplicantId.isEmpty) e.add(l10n.get('selectApplicant'));
  861. return e;
  862. }
  863. void _doPop() {
  864. if (_hasUnsaved()) {
  865. final l10n = AppLocalizations.of(context);
  866. _showConfirmDialog(
  867. l10n.get('confirmExit'),
  868. l10n.get('unsavedContentWarning'),
  869. l10n.get('continueEditing'),
  870. l10n.get('discardAndExit'),
  871. () async {
  872. await DraftStorage.delete(_draftKey);
  873. if (!mounted) return;
  874. setState(() => _clearLocalState());
  875. _forcePop();
  876. },
  877. );
  878. } else {
  879. _forcePop();
  880. }
  881. }
  882. void _forcePop() {
  883. FocusManager.instance.primaryFocus?.unfocus();
  884. final router = GoRouter.of(context);
  885. if (router.canPop()) {
  886. router.pop();
  887. } else {
  888. SystemNavigator.pop();
  889. }
  890. }
  891. bool _hasUnsaved() =>
  892. _reasonController.text.isNotEmpty ||
  893. _details.isNotEmpty ||
  894. _remarkController.text.isNotEmpty;
  895. void _clearLocalState() {
  896. _reasonController.clear();
  897. _remarkController.clear();
  898. _details.clear();
  899. _detailIdCounter = 1;
  900. _selectedDeptId = '';
  901. _selectedDeptName = '';
  902. _selectedApplicantId = '';
  903. _selectedApplicantName = '';
  904. }
  905. void _unfocus() => FocusScope.of(context).unfocus();
  906. void _showConfirmDialog(
  907. String title,
  908. String content,
  909. String leftText,
  910. String rightText,
  911. VoidCallback onConfirm,
  912. ) {
  913. _unfocus();
  914. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  915. showDialog(
  916. context: context,
  917. useRootNavigator: true,
  918. builder: (ctx) => TDAlertDialog(
  919. title: title,
  920. content: content,
  921. buttonStyle: TDDialogButtonStyle.text,
  922. leftBtn: TDDialogButtonOptions(
  923. title: leftText,
  924. titleColor: colors.primary,
  925. action: () => Navigator.pop(ctx),
  926. ),
  927. rightBtn: TDDialogButtonOptions(
  928. title: rightText,
  929. titleColor: colors.danger,
  930. action: () {
  931. Navigator.pop(ctx);
  932. onConfirm();
  933. },
  934. ),
  935. ),
  936. );
  937. }
  938. Widget _label(String t, {bool required = false}) {
  939. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  940. return Text.rich(
  941. TextSpan(
  942. children: [
  943. TextSpan(
  944. text: t,
  945. style: TextStyle(
  946. fontSize: AppFontSizes.subtitle,
  947. color: colors.textSecondary,
  948. ),
  949. ),
  950. if (required)
  951. TextSpan(
  952. text: ' *',
  953. style: TextStyle(
  954. fontSize: AppFontSizes.subtitle,
  955. color: colors.danger,
  956. ),
  957. ),
  958. ],
  959. ),
  960. );
  961. }
  962. Widget _buildPageFooter() {
  963. final l10n = AppLocalizations.of(context);
  964. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  965. return Center(
  966. child: Padding(
  967. padding: const EdgeInsets.only(bottom: 16),
  968. child: Row(
  969. mainAxisSize: MainAxisSize.min,
  970. children: [
  971. Icon(
  972. Icons.rocket_launch_outlined,
  973. size: 16,
  974. color: colors.textPlaceholder,
  975. ),
  976. const SizedBox(width: 6),
  977. Text(
  978. l10n.get('pageFooter'),
  979. style: TextStyle(
  980. fontSize: AppFontSizes.caption,
  981. color: colors.textPlaceholder,
  982. ),
  983. ),
  984. ],
  985. ),
  986. ),
  987. );
  988. }
  989. Future<void> _showDeptPicker() async {
  990. FocusManager.instance.primaryFocus?.unfocus();
  991. final l10n = AppLocalizations.of(context);
  992. final api = ref.read(overtimeApplyApiProvider);
  993. final result = await showSearchablePicker<DepartmentItem>(
  994. context,
  995. title: '${l10n.get('select')}${l10n.get('applyDept')}',
  996. searchHint: l10n.get('search'),
  997. loader: (keyword, page) =>
  998. api.getDepartments(keyword: keyword, page: page, size: 20),
  999. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  1000. onRefresh: () => api.clearRefCache(),
  1001. );
  1002. if (result != null && mounted) {
  1003. setState(() {
  1004. _selectedDeptId = result.dep;
  1005. _selectedDeptName = result.name;
  1006. });
  1007. }
  1008. }
  1009. }
  1010. class _DetailItem {
  1011. final int id;
  1012. final String? jbNo;
  1013. final int itm;
  1014. final String salNo;
  1015. final String salName;
  1016. final String dep;
  1017. final String depName;
  1018. final String jbType;
  1019. final String jbDate;
  1020. final String startTime;
  1021. final String endTime;
  1022. final double jbHours;
  1023. final double jbDays;
  1024. final String attPeriod;
  1025. final String reason;
  1026. final String compensationType;
  1027. final double compensationCount;
  1028. final String adr;
  1029. final String rem;
  1030. const _DetailItem({
  1031. required this.id,
  1032. this.jbNo,
  1033. this.itm = 0,
  1034. this.salNo = '',
  1035. this.salName = '',
  1036. this.dep = '',
  1037. this.depName = '',
  1038. this.jbType = 'WORKING_DAY',
  1039. this.jbDate = '',
  1040. this.startTime = '',
  1041. this.endTime = '',
  1042. this.jbHours = 0.0,
  1043. this.jbDays = 0.0,
  1044. this.attPeriod = '',
  1045. this.reason = '',
  1046. this.compensationType = '',
  1047. this.compensationCount = 0.0,
  1048. this.adr = '',
  1049. this.rem = '',
  1050. });
  1051. }