overtime_apply_edit_page.dart 33 KB

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