overtime_apply_create_page.dart 36 KB

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