overtime_apply_create_page.dart 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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 'overtime_apply_model.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. try {
  246. final model = OvertimeApplyModel.fromJson(data);
  247. setState(() {
  248. _reasonController.text = model.reason;
  249. _remarkController.text = model.rem;
  250. _selectedDeptId = model.dep;
  251. _selectedDeptName = model.depName;
  252. _selectedApplicantId = model.salNo;
  253. _selectedApplicantName = model.salName;
  254. _details.clear();
  255. for (final d in model.details) {
  256. _details.add(
  257. _DetailItem(
  258. id: _detailIdCounter++,
  259. jbNo: d.jbNo,
  260. itm: d.itm,
  261. salNo: d.salNo,
  262. salName: d.salName,
  263. dep: d.dep,
  264. depName: d.depName,
  265. jbType: d.jbType,
  266. jbDate: d.jbDate != null
  267. ? '${d.jbDate!.year}-${d.jbDate!.month.toString().padLeft(2, '0')}-${d.jbDate!.day.toString().padLeft(2, '0')}'
  268. : '',
  269. startTime: d.startTime != null
  270. ? '${d.startTime!.year}-${d.startTime!.month.toString().padLeft(2, '0')}-${d.startTime!.day.toString().padLeft(2, '0')} '
  271. '${d.startTime!.hour.toString().padLeft(2, '0')}:${d.startTime!.minute.toString().padLeft(2, '0')}'
  272. : '',
  273. endTime: d.endTime != null
  274. ? '${d.endTime!.year}-${d.endTime!.month.toString().padLeft(2, '0')}-${d.endTime!.day.toString().padLeft(2, '0')} '
  275. '${d.endTime!.hour.toString().padLeft(2, '0')}:${d.endTime!.minute.toString().padLeft(2, '0')}'
  276. : '',
  277. jbHours: d.jbHours,
  278. jbDays: d.jbDays,
  279. attPeriod: d.attPeriod,
  280. reason: d.reason,
  281. compensationType: d.compensationType,
  282. compensationCount: d.compensationCount,
  283. adr: d.adr,
  284. rem: d.rem,
  285. ),
  286. );
  287. }
  288. _detailIdCounter = _details.isEmpty
  289. ? 1
  290. : _details.map((d) => d.id).reduce((a, b) => a > b ? a : b) + 1;
  291. });
  292. } catch (_) {
  293. // 旧格式草稿兼容
  294. }
  295. }
  296. Future<void> _saveDraftToStorage() async {
  297. final now = DateTime.now();
  298. final model = OvertimeApplyModel(
  299. jbNo: '',
  300. jbDd: now,
  301. salNo: _selectedApplicantId,
  302. salName: _selectedApplicantName,
  303. dep: _selectedDeptId,
  304. depName: _selectedDeptName,
  305. reason: _reasonController.text,
  306. rem: _remarkController.text,
  307. usr: HostAppChannel.usr,
  308. recordDd: now,
  309. details: _details
  310. .map(
  311. (d) => OvertimeApplyDetailModel(
  312. itm: d.itm,
  313. jbNo: d.jbNo,
  314. salNo: d.salNo,
  315. salName: d.salName,
  316. dep: d.dep,
  317. depName: d.depName,
  318. jbType: d.jbType,
  319. jbDate: d.jbDate.isNotEmpty
  320. ? DateTime.tryParse(d.jbDate)
  321. : null,
  322. startTime: d.startTime.isNotEmpty
  323. ? DateTime.tryParse(d.startTime)
  324. : null,
  325. endTime: d.endTime.isNotEmpty
  326. ? DateTime.tryParse(d.endTime)
  327. : null,
  328. jbHours: d.jbHours,
  329. jbDays: d.jbDays,
  330. attPeriod: d.attPeriod,
  331. reason: d.reason,
  332. compensationType: d.compensationType,
  333. compensationCount: d.compensationCount,
  334. adr: d.adr,
  335. rem: d.rem,
  336. ),
  337. )
  338. .toList(),
  339. );
  340. await DraftStorage.save(_draftKey, model.toJson());
  341. }
  342. // ═══ 草稿弹窗 ═══
  343. void _showDraftDialog() {
  344. final l10n = AppLocalizations.of(context);
  345. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  346. FocusManager.instance.primaryFocus?.unfocus();
  347. showDialog(
  348. context: context,
  349. barrierDismissible: false,
  350. builder: (ctx) => TDAlertDialog(
  351. title: l10n.get('draftFound'),
  352. content: l10n.get('draftRestorePrompt'),
  353. buttonStyle: TDDialogButtonStyle.text,
  354. leftBtn: TDDialogButtonOptions(
  355. title: l10n.get('discard'),
  356. titleColor: colors.textSecondary,
  357. action: () {
  358. Navigator.pop(ctx);
  359. DraftStorage.delete(_draftKey);
  360. },
  361. ),
  362. rightBtn: TDDialogButtonOptions(
  363. title: l10n.get('restore'),
  364. titleColor: colors.primary,
  365. action: () {
  366. Navigator.pop(ctx);
  367. _restoreDraft();
  368. },
  369. ),
  370. ),
  371. );
  372. }
  373. // ═══ 1. 基本信息 ═══
  374. Widget _buildBasicInfo(AppLocalizations l10n) {
  375. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  376. final now = DateTime.now();
  377. final todayStr =
  378. '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
  379. return FormSection(
  380. title: l10n.get('basicInfo'),
  381. leadingIcon: Icons.info_outline,
  382. children: [
  383. FormFieldRow(
  384. label: l10n.get('date'),
  385. value: todayStr,
  386. readOnly: true,
  387. showArrow: false,
  388. ),
  389. const SizedBox(height: 16),
  390. FormFieldRow(
  391. label: l10n.get('dep'),
  392. value: _selectedDeptId.isNotEmpty
  393. ? '$_selectedDeptId/$_selectedDeptName'
  394. : '',
  395. hint: l10n.get('pleaseSelect'),
  396. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  397. ),
  398. const SizedBox(height: 16),
  399. FormFieldRow(
  400. label: l10n.get('applicant'),
  401. required: true,
  402. value: _selectedApplicantId.isNotEmpty
  403. ? '$_selectedApplicantId/$_selectedApplicantName'
  404. : '',
  405. hint: l10n.get('pleaseSelect'),
  406. onTap: () => _showApplicantPicker(),
  407. ),
  408. const SizedBox(height: 16),
  409. _label(l10n.get('overtimeReason'), required: true),
  410. const SizedBox(height: 8),
  411. TDTextarea(
  412. controller: _reasonController,
  413. focusNode: _reasonFocus,
  414. hintText: l10n.get('enterOvertimeReason'),
  415. maxLines: 4,
  416. minLines: 1,
  417. maxLength: 1000,
  418. indicator: true,
  419. padding: EdgeInsets.zero,
  420. bordered: true,
  421. backgroundColor: colors.bgPage,
  422. ),
  423. const SizedBox(height: 16),
  424. _label(l10n.get('remark')),
  425. const SizedBox(height: 8),
  426. TDTextarea(
  427. controller: _remarkController,
  428. focusNode: _remarkFocus,
  429. hintText: l10n.get('enterRemark'),
  430. maxLines: 3,
  431. minLines: 1,
  432. maxLength: 500,
  433. indicator: true,
  434. padding: EdgeInsets.zero,
  435. bordered: true,
  436. backgroundColor: colors.bgPage,
  437. ),
  438. ],
  439. );
  440. }
  441. // ═══ 2. 加班明细 ═══
  442. Widget _buildDetailsSection(AppLocalizations l10n) {
  443. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  444. return FormSection(
  445. title: l10n.get('overtimeDetails'),
  446. leadingIcon: Icons.access_time_outlined,
  447. showAction: true,
  448. actionText: l10n.get('add'),
  449. onActionTap: _showDetailDialog,
  450. children: [
  451. if (_details.isEmpty)
  452. Padding(
  453. padding: const EdgeInsets.symmetric(vertical: 8),
  454. child: Text(
  455. l10n.get('noDetailHint'),
  456. style: TextStyle(
  457. fontSize: AppFontSizes.subtitle,
  458. color: colors.textPlaceholder,
  459. ),
  460. ),
  461. )
  462. else
  463. ..._details.asMap().entries.map((e) {
  464. final d = e.value;
  465. return GestureDetector(
  466. onTap: () => _showDetailDialog(editIndex: e.key),
  467. child: Container(
  468. margin: const EdgeInsets.symmetric(vertical: 6),
  469. padding: const EdgeInsets.all(12),
  470. decoration: BoxDecoration(
  471. color: colors.bgPage,
  472. borderRadius: BorderRadius.circular(8),
  473. ),
  474. child: Row(
  475. children: [
  476. Expanded(
  477. child: Column(
  478. crossAxisAlignment: CrossAxisAlignment.start,
  479. children: [
  480. Row(
  481. children: [
  482. Expanded(
  483. child: Text(
  484. '${d.salNo}${d.salName.isNotEmpty ? '/${d.salName}' : ''}',
  485. maxLines: 1,
  486. overflow: TextOverflow.ellipsis,
  487. style: TextStyle(
  488. fontSize: AppFontSizes.body,
  489. fontWeight: FontWeight.w500,
  490. color: colors.textPrimary,
  491. ),
  492. ),
  493. ),
  494. Text(
  495. '${d.jbHours.toStringAsFixed(1)}${l10n.get('hours')}',
  496. style: TextStyle(
  497. fontSize: AppFontSizes.body,
  498. fontWeight: FontWeight.w600,
  499. color: colors.timePrimary,
  500. ),
  501. ),
  502. ],
  503. ),
  504. if (d.jbType.isNotEmpty) ...[
  505. const SizedBox(height: 2),
  506. _detailLabel(
  507. '${l10n.get('jbType')}: ${_jbTypeLabel(d.jbType, l10n)}',
  508. colors,
  509. ),
  510. _detailLabel(
  511. '${l10n.get('jbDate')}: ${d.jbDate}',
  512. colors,
  513. trailing: _weekdayLabel(d.jbDate, l10n) != null
  514. ? _weekdayTag(
  515. _weekdayLabel(d.jbDate, l10n)!,
  516. )
  517. : null,
  518. ),
  519. ],
  520. if (d.startTime.isNotEmpty) ...[
  521. const SizedBox(height: 2),
  522. _detailLabel(
  523. '${l10n.get('startTime')}: ${_fmtTime(d.startTime)}',
  524. colors,
  525. ),
  526. ],
  527. if (d.endTime.isNotEmpty) ...[
  528. const SizedBox(height: 2),
  529. _detailLabel(
  530. '${l10n.get('endTime')}: ${_fmtTime(d.endTime)}',
  531. colors,
  532. ),
  533. ],
  534. // TODO: 加班天数暂时隐藏
  535. // if (d.jbDays > 0) ...[
  536. // const SizedBox(height: 2),
  537. // _detailLabel(
  538. // '${l10n.get('overtimeDays')}: ${d.jbDays.toStringAsFixed(1)}',
  539. // colors,
  540. // ),
  541. // ],
  542. if (d.attPeriod.isNotEmpty) ...[
  543. const SizedBox(height: 2),
  544. _detailLabel(
  545. '${l10n.get('attPeriod')}: ${d.attPeriod}',
  546. colors,
  547. ),
  548. ],
  549. // TODO: 补偿类型、补偿次数暂时隐藏
  550. // if (d.compensationType.isNotEmpty) ...[
  551. // const SizedBox(height: 2),
  552. // _detailLabel(
  553. // '${l10n.get('compensationType')}: ${_compensationTypeLabel(d.compensationType, l10n)}',
  554. // colors,
  555. // ),
  556. // if (d.compensationType != 'NO_COMPENSATION' &&
  557. // d.compensationCount > 0)
  558. // _detailLabel(
  559. // '${l10n.get('compensationCount')}: ${d.compensationCount.toStringAsFixed(1)}',
  560. // colors,
  561. // ),
  562. // ],
  563. if (d.adr.isNotEmpty) ...[
  564. const SizedBox(height: 2),
  565. _detailLabel(
  566. '${l10n.get('adr')}: ${d.adr}',
  567. colors,
  568. ),
  569. ],
  570. if (d.reason.isNotEmpty) ...[
  571. const SizedBox(height: 2),
  572. _detailLabel(
  573. '${l10n.get('overtimeDetailReason')}: ${d.reason}',
  574. colors,
  575. ),
  576. ],
  577. if (d.rem.isNotEmpty) ...[
  578. const SizedBox(height: 2),
  579. _detailLabel(
  580. '${l10n.get('remark')}: ${d.rem}',
  581. colors,
  582. ),
  583. ],
  584. ],
  585. ),
  586. ),
  587. const SizedBox(width: 8),
  588. GestureDetector(
  589. onTap: () => setState(() => _details.removeAt(e.key)),
  590. child: Icon(
  591. Icons.close,
  592. size: 18,
  593. color: colors.textSecondary,
  594. ),
  595. ),
  596. ],
  597. ),
  598. ),
  599. );
  600. }),
  601. const SizedBox(height: 8),
  602. Container(
  603. padding: const EdgeInsets.symmetric(vertical: 8),
  604. child: Row(
  605. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  606. children: [
  607. Text(
  608. l10n.get('totalOvertimeHours'),
  609. style: TextStyle(
  610. fontSize: AppFontSizes.body,
  611. fontWeight: FontWeight.w600,
  612. color: colors.textPrimary,
  613. ),
  614. ),
  615. Text(
  616. '${_totalHours().toStringAsFixed(1)}${l10n.get('hours')}',
  617. style: TextStyle(
  618. fontSize: AppFontSizes.subtitle,
  619. fontWeight: FontWeight.w700,
  620. color: colors.timePrimary,
  621. ),
  622. ),
  623. ],
  624. ),
  625. ),
  626. ],
  627. );
  628. }
  629. double _totalHours() => _details.fold(0.0, (s, d) => s + d.jbHours);
  630. String _jbTypeLabel(String type, AppLocalizations l10n) {
  631. switch (type) {
  632. case 'WORKING_DAY':
  633. return l10n.get('workingDay');
  634. case 'REST_DAY':
  635. return l10n.get('restDay');
  636. case 'PUBLIC_HOLIDAY':
  637. return l10n.get('publicHoliday');
  638. case 'SPECIAL_HOLIDAY':
  639. return l10n.get('specialHoliday');
  640. case 'OTHER':
  641. return l10n.get('other');
  642. default:
  643. return type;
  644. }
  645. }
  646. String _fmtTime(String dt) {
  647. if (dt.length >= 16) return dt.substring(11, 16);
  648. return dt;
  649. }
  650. String? _weekdayLabel(String dateTimeStr, AppLocalizations l10n) {
  651. final dt = DateTime.tryParse(dateTimeStr);
  652. if (dt == null) return null;
  653. switch (dt.weekday) {
  654. case 1:
  655. return l10n.get('monday');
  656. case 2:
  657. return l10n.get('tuesday');
  658. case 3:
  659. return l10n.get('wednesday');
  660. case 4:
  661. return l10n.get('thursday');
  662. case 5:
  663. return l10n.get('friday');
  664. case 6:
  665. return l10n.get('saturday');
  666. case 7:
  667. return l10n.get('sunday');
  668. default:
  669. return null;
  670. }
  671. }
  672. String _compensationTypeLabel(String type, AppLocalizations l10n) {
  673. switch (type) {
  674. case 'OVERTIME_PAY':
  675. return l10n.get('overtimePay');
  676. case 'COMPENSATORY_LEAVE':
  677. return l10n.get('compensatoryLeave');
  678. case 'NO_COMPENSATION':
  679. return l10n.get('noCompensation');
  680. case 'OTHER':
  681. return l10n.get('other');
  682. default:
  683. return type;
  684. }
  685. }
  686. Widget _detailLabel(String text, AppColorsExtension colors, {Widget? trailing}) {
  687. return Padding(
  688. padding: const EdgeInsets.only(top: 2),
  689. child: Row(
  690. children: [
  691. Flexible(
  692. child: Text(
  693. text,
  694. maxLines: 2,
  695. overflow: TextOverflow.ellipsis,
  696. style: TextStyle(
  697. fontSize: AppFontSizes.caption,
  698. color: colors.textSecondary,
  699. ),
  700. ),
  701. ),
  702. if (trailing != null) ...[
  703. const SizedBox(width: 6),
  704. trailing,
  705. ],
  706. ],
  707. ),
  708. );
  709. }
  710. Widget _weekdayTag(String label) {
  711. final tdTheme = TDTheme.of(context);
  712. return Container(
  713. padding: const EdgeInsets.symmetric(horizontal: 6),
  714. decoration: BoxDecoration(
  715. color: tdTheme.brandColor1,
  716. borderRadius: BorderRadius.circular(4),
  717. ),
  718. child: TDText(
  719. label,
  720. font: tdTheme.fontBodySmall,
  721. fontWeight: FontWeight.w500,
  722. textColor: tdTheme.brandColor7,
  723. ),
  724. );
  725. }
  726. Future<void> _showDetailDialog({int? editIndex}) async {
  727. if (_addingDetail) return;
  728. _addingDetail = true;
  729. try {
  730. final l10n = AppLocalizations.of(context);
  731. OvertimeDetailData? initialData;
  732. if (editIndex != null) {
  733. final d = _details[editIndex];
  734. initialData = OvertimeDetailData(
  735. jbNo: d.jbNo,
  736. itm: d.itm > 0 ? d.itm : null,
  737. salNo: d.salNo,
  738. salName: d.salName,
  739. dep: d.dep,
  740. depName: d.depName,
  741. jbType: d.jbType,
  742. jbDate: d.jbDate,
  743. startTime: d.startTime,
  744. endTime: d.endTime,
  745. jbHours: d.jbHours,
  746. jbDays: d.jbDays,
  747. attPeriod: d.attPeriod,
  748. reason: d.reason,
  749. compensationType: d.compensationType,
  750. compensationCount: d.compensationCount,
  751. adr: d.adr,
  752. rem: d.rem,
  753. );
  754. }
  755. FocusManager.instance.primaryFocus?.unfocus();
  756. final result = await OvertimeApplyDetailDialog.show(
  757. // ignore: use_build_context_synchronously
  758. context,
  759. api: ref.read(overtimeApplyApiProvider),
  760. l10n: l10n,
  761. initialData: initialData,
  762. );
  763. if (result != null && mounted) {
  764. setState(() {
  765. final item = _DetailItem(
  766. id: editIndex != null ? _details[editIndex].id : _detailIdCounter++,
  767. jbNo: result.jbNo,
  768. itm: result.itm ?? 0,
  769. salNo: result.salNo,
  770. salName: result.salName,
  771. dep: result.dep,
  772. depName: result.depName,
  773. jbType: result.jbType,
  774. jbDate: result.jbDate,
  775. startTime: result.startTime,
  776. endTime: result.endTime,
  777. jbHours: result.jbHours,
  778. jbDays: result.jbDays,
  779. attPeriod: result.attPeriod,
  780. reason: result.reason,
  781. compensationType: result.compensationType,
  782. compensationCount: result.compensationCount,
  783. adr: result.adr,
  784. rem: result.rem,
  785. );
  786. if (editIndex != null) {
  787. _details[editIndex] = item;
  788. } else {
  789. _details.add(item);
  790. }
  791. });
  792. }
  793. } finally {
  794. _addingDetail = false;
  795. }
  796. }
  797. // ═══ 3. 底部操作栏 ═══
  798. Widget _buildBottomBar(AppLocalizations l10n) {
  799. return ActionBar(
  800. showLeft: false,
  801. centerLabel: l10n.get('saveDraft'),
  802. rightLabel: l10n.get('submit'),
  803. centerTextOnly: true,
  804. onCenterTap: () async {
  805. FocusScope.of(context).unfocus();
  806. try {
  807. await _saveDraftToStorage();
  808. if (mounted) _forcePop();
  809. } catch (_) {
  810. if (mounted) {
  811. TDToast.showFail(l10n.get('saveFailed'), context: context);
  812. }
  813. }
  814. },
  815. onRightTap: () async {
  816. final err = _validate(l10n);
  817. if (err.isNotEmpty) {
  818. TDToast.showText(err.first, context: context);
  819. return;
  820. }
  821. FocusScope.of(context).unfocus();
  822. LoadingDialog.show(context, text: l10n.get('submitting'));
  823. try {
  824. final data = _buildSubmitData();
  825. final api = ref.read(overtimeApplyApiProvider);
  826. final billNo = await api.submit(data);
  827. await DraftStorage.delete(_draftKey);
  828. if (!mounted) return;
  829. LoadingDialog.hide(context);
  830. if (billNo != null) {
  831. final dd = data['HeadData']['JB_DD']?.toString() ?? '';
  832. await AuditFlowHelper.handle(
  833. context: context,
  834. l10n: l10n,
  835. getConfig: () => api.getBillAuditConfig('JB'),
  836. onShSubmit: () => api.shSubmit(bilNo: billNo, bilDd: dd),
  837. );
  838. }
  839. if (mounted) {
  840. TDToast.showSuccess(l10n.get('billCreated'), context: context);
  841. GoRouter.of(context).go('/overtime-apply/list');
  842. }
  843. } catch (e) {
  844. if (mounted) LoadingDialog.hide(context);
  845. }
  846. },
  847. );
  848. }
  849. Map<String, dynamic> _buildSubmitData() {
  850. final now = DateTime.now();
  851. final jbDd =
  852. '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
  853. return {
  854. 'HeadData': {
  855. 'JB_DD': jbDd,
  856. 'SAL_NO': _selectedApplicantId.isNotEmpty
  857. ? _selectedApplicantId
  858. : HostAppChannel.usr,
  859. 'DEP': _selectedDeptId,
  860. 'REASON': _reasonController.text.trim(),
  861. 'REM': _remarkController.text,
  862. 'USR': HostAppChannel.usr,
  863. },
  864. 'BodyData1': _details.asMap().entries.map((e) {
  865. final d = e.value;
  866. return {
  867. 'ITM': e.key + 1,
  868. 'SAL_NO': d.salNo,
  869. 'DEP': d.dep.isNotEmpty ? d.dep : _selectedDeptId,
  870. 'JB_TYPE': d.jbType,
  871. 'JB_DATE': d.jbDate,
  872. 'START_TIME': d.startTime,
  873. 'END_TIME': d.endTime,
  874. 'JB_HOURS': d.jbHours,
  875. 'JB_DAYS': d.jbDays,
  876. 'ATT_PERIOD': d.attPeriod,
  877. 'REASON': d.reason,
  878. 'COMPENSATION_TYPE': d.compensationType,
  879. 'COMPENSATION_COUNT': d.compensationCount,
  880. 'ADR': d.adr,
  881. 'REM': d.rem,
  882. };
  883. }).toList(),
  884. };
  885. }
  886. List<String> _validate(AppLocalizations l10n) {
  887. final e = <String>[];
  888. if (_reasonController.text.trim().isEmpty) {
  889. e.add(l10n.get('enterOvertimeReason'));
  890. }
  891. if (_details.isEmpty) e.add(l10n.get('addAtLeastOneOTDetail'));
  892. if (_selectedDeptId.isEmpty) e.add(l10n.get('selectDept'));
  893. if (_selectedApplicantId.isEmpty) e.add(l10n.get('selectApplicant'));
  894. return e;
  895. }
  896. void _doPop() {
  897. if (_hasUnsaved()) {
  898. final l10n = AppLocalizations.of(context);
  899. _showConfirmDialog(
  900. l10n.get('confirmExit'),
  901. l10n.get('unsavedContentWarning'),
  902. l10n.get('continueEditing'),
  903. l10n.get('discardAndExit'),
  904. () async {
  905. await DraftStorage.delete(_draftKey);
  906. if (!mounted) return;
  907. setState(() => _clearLocalState());
  908. _forcePop();
  909. },
  910. );
  911. } else {
  912. _forcePop();
  913. }
  914. }
  915. void _forcePop() {
  916. FocusManager.instance.primaryFocus?.unfocus();
  917. final router = GoRouter.of(context);
  918. if (router.canPop()) {
  919. router.pop();
  920. } else {
  921. SystemNavigator.pop();
  922. }
  923. }
  924. bool _hasUnsaved() =>
  925. _reasonController.text.isNotEmpty ||
  926. _details.isNotEmpty ||
  927. _remarkController.text.isNotEmpty;
  928. void _clearLocalState() {
  929. _reasonController.clear();
  930. _remarkController.clear();
  931. _details.clear();
  932. _detailIdCounter = 1;
  933. _selectedDeptId = '';
  934. _selectedDeptName = '';
  935. _selectedApplicantId = '';
  936. _selectedApplicantName = '';
  937. }
  938. void _unfocus() => FocusScope.of(context).unfocus();
  939. void _showConfirmDialog(
  940. String title,
  941. String content,
  942. String leftText,
  943. String rightText,
  944. VoidCallback onConfirm,
  945. ) {
  946. _unfocus();
  947. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  948. showDialog(
  949. context: context,
  950. useRootNavigator: true,
  951. builder: (ctx) => TDAlertDialog(
  952. title: title,
  953. content: content,
  954. buttonStyle: TDDialogButtonStyle.text,
  955. leftBtn: TDDialogButtonOptions(
  956. title: leftText,
  957. titleColor: colors.primary,
  958. action: () => Navigator.pop(ctx),
  959. ),
  960. rightBtn: TDDialogButtonOptions(
  961. title: rightText,
  962. titleColor: colors.danger,
  963. action: () {
  964. Navigator.pop(ctx);
  965. onConfirm();
  966. },
  967. ),
  968. ),
  969. );
  970. }
  971. Widget _label(String t, {bool required = false}) {
  972. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  973. return Text.rich(
  974. TextSpan(
  975. children: [
  976. TextSpan(
  977. text: t,
  978. style: TextStyle(
  979. fontSize: AppFontSizes.subtitle,
  980. color: colors.textSecondary,
  981. ),
  982. ),
  983. if (required)
  984. TextSpan(
  985. text: ' *',
  986. style: TextStyle(
  987. fontSize: AppFontSizes.subtitle,
  988. color: colors.danger,
  989. ),
  990. ),
  991. ],
  992. ),
  993. );
  994. }
  995. Widget _buildPageFooter() {
  996. final l10n = AppLocalizations.of(context);
  997. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  998. return Center(
  999. child: Padding(
  1000. padding: const EdgeInsets.only(bottom: 16),
  1001. child: Row(
  1002. mainAxisSize: MainAxisSize.min,
  1003. children: [
  1004. Icon(
  1005. Icons.rocket_launch_outlined,
  1006. size: 16,
  1007. color: colors.textPlaceholder,
  1008. ),
  1009. const SizedBox(width: 6),
  1010. Text(
  1011. l10n.get('pageFooter'),
  1012. style: TextStyle(
  1013. fontSize: AppFontSizes.caption,
  1014. color: colors.textPlaceholder,
  1015. ),
  1016. ),
  1017. ],
  1018. ),
  1019. ),
  1020. );
  1021. }
  1022. Future<void> _showDeptPicker() async {
  1023. FocusManager.instance.primaryFocus?.unfocus();
  1024. final l10n = AppLocalizations.of(context);
  1025. final api = ref.read(overtimeApplyApiProvider);
  1026. final result = await showSearchablePicker<DepartmentItem>(
  1027. context,
  1028. title: '${l10n.get('select')}${l10n.get('applyDept')}',
  1029. searchHint: l10n.get('search'),
  1030. loader: (keyword, page) =>
  1031. api.getDepartments(keyword: keyword, page: page, size: 20),
  1032. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  1033. onRefresh: () => api.clearRefCache(),
  1034. );
  1035. if (result != null && mounted) {
  1036. setState(() {
  1037. _selectedDeptId = result.dep;
  1038. _selectedDeptName = result.name;
  1039. });
  1040. }
  1041. }
  1042. }
  1043. class _DetailItem {
  1044. final int id;
  1045. final String? jbNo;
  1046. final int itm;
  1047. final String salNo;
  1048. final String salName;
  1049. final String dep;
  1050. final String depName;
  1051. final String jbType;
  1052. final String jbDate;
  1053. final String startTime;
  1054. final String endTime;
  1055. final double jbHours;
  1056. final double jbDays;
  1057. final String attPeriod;
  1058. final String reason;
  1059. final String compensationType;
  1060. final double compensationCount;
  1061. final String adr;
  1062. final String rem;
  1063. const _DetailItem({
  1064. required this.id,
  1065. this.jbNo,
  1066. this.itm = 0,
  1067. this.salNo = '',
  1068. this.salName = '',
  1069. this.dep = '',
  1070. this.depName = '',
  1071. this.jbType = 'WORKING_DAY',
  1072. this.jbDate = '',
  1073. this.startTime = '',
  1074. this.endTime = '',
  1075. this.jbHours = 0.0,
  1076. this.jbDays = 0.0,
  1077. this.attPeriod = '',
  1078. this.reason = '',
  1079. this.compensationType = '',
  1080. this.compensationCount = 0.0,
  1081. this.adr = '',
  1082. this.rem = '',
  1083. });
  1084. }