overtime_apply_edit_page.dart 33 KB

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