overtime_apply_edit_page.dart 27 KB

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