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('jbDate')}: ${d.jbDate}',
  466. colors,
  467. trailing: _weekdayLabel(d.jbDate, l10n) != null
  468. ? _weekdayTag(
  469. _weekdayLabel(d.jbDate, l10n)!,
  470. )
  471. : null,
  472. ),
  473. ],
  474. if (d.startTime.isNotEmpty) ...[
  475. const SizedBox(height: 2),
  476. _detailLabel(
  477. '${l10n.get('startTime')}: ${_fmtTime(d.startTime)}',
  478. colors,
  479. ),
  480. ],
  481. if (d.endTime.isNotEmpty) ...[
  482. const SizedBox(height: 2),
  483. _detailLabel(
  484. '${l10n.get('endTime')}: ${_fmtTime(d.endTime)}',
  485. colors,
  486. ),
  487. ],
  488. // TODO: 加班天数暂时隐藏
  489. // if (d.jbDays > 0) ...[
  490. // const SizedBox(height: 2),
  491. // _detailLabel(
  492. // '${l10n.get('overtimeDays')}: ${d.jbDays.toStringAsFixed(1)}',
  493. // colors,
  494. // ),
  495. // ],
  496. if (d.attPeriod.isNotEmpty) ...[
  497. const SizedBox(height: 2),
  498. _detailLabel(
  499. '${l10n.get('attPeriod')}: ${d.attPeriod}',
  500. colors,
  501. ),
  502. ],
  503. // TODO: 补偿类型、补偿次数暂时隐藏
  504. // if (d.compensationType.isNotEmpty) ...[
  505. // const SizedBox(height: 2),
  506. // _detailLabel(
  507. // '${l10n.get('compensationType')}: ${_compensationTypeLabel(d.compensationType, l10n)}',
  508. // colors,
  509. // ),
  510. // if (d.compensationType != 'NO_COMPENSATION' &&
  511. // d.compensationCount > 0)
  512. // _detailLabel(
  513. // '${l10n.get('compensationCount')}: ${d.compensationCount.toStringAsFixed(1)}',
  514. // colors,
  515. // ),
  516. // ],
  517. if (d.adr.isNotEmpty) ...[
  518. const SizedBox(height: 2),
  519. _detailLabel(
  520. '${l10n.get('adr')}: ${d.adr}',
  521. colors,
  522. ),
  523. ],
  524. if (d.reason.isNotEmpty) ...[
  525. const SizedBox(height: 2),
  526. _detailLabel(
  527. '${l10n.get('overtimeDetailReason')}: ${d.reason}',
  528. colors,
  529. ),
  530. ],
  531. if (d.rem.isNotEmpty) ...[
  532. const SizedBox(height: 2),
  533. _detailLabel(
  534. '${l10n.get('remark')}: ${d.rem}',
  535. colors,
  536. ),
  537. ],
  538. ],
  539. ),
  540. ),
  541. const SizedBox(width: 8),
  542. GestureDetector(
  543. onTap: () => setState(() => _details.removeAt(e.key)),
  544. child: Icon(
  545. Icons.close,
  546. size: 18,
  547. color: colors.textSecondary,
  548. ),
  549. ),
  550. ],
  551. ),
  552. ),
  553. );
  554. }),
  555. const SizedBox(height: 8),
  556. Container(
  557. padding: const EdgeInsets.symmetric(vertical: 8),
  558. child: Row(
  559. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  560. children: [
  561. Text(
  562. l10n.get('totalOvertimeHours'),
  563. style: TextStyle(
  564. fontSize: AppFontSizes.body,
  565. fontWeight: FontWeight.w600,
  566. color: colors.textPrimary,
  567. ),
  568. ),
  569. Text(
  570. '${_totalHours().toStringAsFixed(1)}${l10n.get('hours')}',
  571. style: TextStyle(
  572. fontSize: AppFontSizes.subtitle,
  573. fontWeight: FontWeight.w700,
  574. color: colors.timePrimary,
  575. ),
  576. ),
  577. ],
  578. ),
  579. ),
  580. ],
  581. );
  582. }
  583. double _totalHours() => _details.fold(0.0, (s, d) => s + d.jbHours);
  584. String _jbTypeLabel(String type, AppLocalizations l10n) {
  585. switch (type) {
  586. case 'WORKING_DAY':
  587. return l10n.get('workingDay');
  588. case 'REST_DAY':
  589. return l10n.get('restDay');
  590. case 'PUBLIC_HOLIDAY':
  591. return l10n.get('publicHoliday');
  592. case 'SPECIAL_HOLIDAY':
  593. return l10n.get('specialHoliday');
  594. case 'OTHER':
  595. return l10n.get('other');
  596. default:
  597. return type;
  598. }
  599. }
  600. String _fmtTime(String dt) {
  601. if (dt.length >= 16) return dt.substring(11, 16);
  602. return dt;
  603. }
  604. String? _weekdayLabel(String dateTimeStr, AppLocalizations l10n) {
  605. final dt = DateTime.tryParse(dateTimeStr);
  606. if (dt == null) return null;
  607. switch (dt.weekday) {
  608. case 1:
  609. return l10n.get('monday');
  610. case 2:
  611. return l10n.get('tuesday');
  612. case 3:
  613. return l10n.get('wednesday');
  614. case 4:
  615. return l10n.get('thursday');
  616. case 5:
  617. return l10n.get('friday');
  618. case 6:
  619. return l10n.get('saturday');
  620. case 7:
  621. return l10n.get('sunday');
  622. default:
  623. return null;
  624. }
  625. }
  626. String _compensationTypeLabel(String type, AppLocalizations l10n) {
  627. switch (type) {
  628. case 'OVERTIME_PAY':
  629. return l10n.get('overtimePay');
  630. case 'COMPENSATORY_LEAVE':
  631. return l10n.get('compensatoryLeave');
  632. case 'NO_COMPENSATION':
  633. return l10n.get('noCompensation');
  634. case 'OTHER':
  635. return l10n.get('other');
  636. default:
  637. return type;
  638. }
  639. }
  640. Widget _detailLabel(String text, AppColorsExtension colors, {Widget? trailing}) {
  641. return Padding(
  642. padding: const EdgeInsets.only(top: 2),
  643. child: Row(
  644. children: [
  645. Flexible(
  646. child: Text(
  647. text,
  648. maxLines: 2,
  649. overflow: TextOverflow.ellipsis,
  650. style: TextStyle(
  651. fontSize: AppFontSizes.caption,
  652. color: colors.textSecondary,
  653. ),
  654. ),
  655. ),
  656. if (trailing != null) ...[
  657. const SizedBox(width: 6),
  658. trailing,
  659. ],
  660. ],
  661. ),
  662. );
  663. }
  664. Widget _weekdayTag(String label) {
  665. final tdTheme = TDTheme.of(context);
  666. return Container(
  667. padding: const EdgeInsets.symmetric(horizontal: 6),
  668. decoration: BoxDecoration(
  669. color: tdTheme.brandColor1,
  670. borderRadius: BorderRadius.circular(4),
  671. ),
  672. child: TDText(
  673. label,
  674. font: tdTheme.fontBodySmall,
  675. fontWeight: FontWeight.w500,
  676. textColor: tdTheme.brandColor7,
  677. ),
  678. );
  679. }
  680. Future<void> _showDetailDialog({int? editIndex}) async {
  681. if (_addingDetail) return;
  682. _addingDetail = true;
  683. try {
  684. final l10n = AppLocalizations.of(context);
  685. OvertimeDetailData? initialData;
  686. if (editIndex != null) {
  687. final d = _details[editIndex];
  688. initialData = OvertimeDetailData(
  689. jbNo: d.jbNo,
  690. itm: d.itm > 0 ? d.itm : null,
  691. salNo: d.salNo,
  692. salName: d.salName,
  693. dep: d.dep,
  694. depName: d.depName,
  695. jbType: d.jbType,
  696. jbDate: d.jbDate,
  697. startTime: d.startTime,
  698. endTime: d.endTime,
  699. jbHours: d.jbHours,
  700. jbDays: d.jbDays,
  701. attPeriod: d.attPeriod,
  702. reason: d.reason,
  703. compensationType: d.compensationType,
  704. compensationCount: d.compensationCount,
  705. adr: d.adr,
  706. rem: d.rem,
  707. );
  708. }
  709. FocusManager.instance.primaryFocus?.unfocus();
  710. final result = await OvertimeApplyDetailDialog.show(
  711. // ignore: use_build_context_synchronously
  712. context,
  713. api: ref.read(overtimeApplyApiProvider),
  714. l10n: l10n,
  715. initialData: initialData,
  716. );
  717. if (result != null && mounted) {
  718. setState(() {
  719. final item = _DetailItem(
  720. id: editIndex != null ? _details[editIndex].id : _detailIdCounter++,
  721. jbNo: result.jbNo,
  722. itm: result.itm ?? 0,
  723. salNo: result.salNo,
  724. salName: result.salName,
  725. dep: result.dep,
  726. depName: result.depName,
  727. jbType: result.jbType,
  728. jbDate: result.jbDate,
  729. startTime: result.startTime,
  730. endTime: result.endTime,
  731. jbHours: result.jbHours,
  732. jbDays: result.jbDays,
  733. attPeriod: result.attPeriod,
  734. reason: result.reason,
  735. compensationType: result.compensationType,
  736. compensationCount: result.compensationCount,
  737. adr: result.adr,
  738. rem: result.rem,
  739. preItm: editIndex != null ? _details[editIndex].preItm : null,
  740. );
  741. if (editIndex != null) {
  742. _details[editIndex] = item;
  743. } else {
  744. _details.add(item);
  745. }
  746. });
  747. }
  748. } finally {
  749. _addingDetail = false;
  750. }
  751. }
  752. // ═══ 3. 底部操作栏 ═══
  753. Widget _buildBottomBar(AppLocalizations l10n) {
  754. return ActionBar(
  755. showLeft: false,
  756. showCenter: false,
  757. rightLabel: l10n.get('submit'),
  758. onRightTap: () async {
  759. final err = _validate(l10n);
  760. if (err.isNotEmpty) {
  761. TDToast.showText(err.first, context: context);
  762. return;
  763. }
  764. FocusScope.of(context).unfocus();
  765. LoadingDialog.show(context, text: l10n.get('submitting'));
  766. try {
  767. final data = _buildSubmitData();
  768. final api = ref.read(overtimeApplyApiProvider);
  769. final billNo = await api.submit(data);
  770. if (!mounted) return;
  771. LoadingDialog.hide(context);
  772. if (billNo != null) {
  773. final dd = data['HeadData']['JB_DD']?.toString() ?? '';
  774. await AuditFlowHelper.handle(
  775. context: context,
  776. l10n: l10n,
  777. getConfig: () => api.getBillAuditConfig('JB'),
  778. onShSubmit: () => api.shSubmit(bilNo: billNo, bilDd: dd),
  779. );
  780. }
  781. if (mounted) {
  782. TDToast.showSuccess(l10n.get('billModified'), context: context);
  783. GoRouter.of(context).go('/overtime-apply/list');
  784. }
  785. } catch (e) {
  786. if (mounted) LoadingDialog.hide(context);
  787. }
  788. },
  789. );
  790. }
  791. Map<String, dynamic> _buildSubmitData() {
  792. return {
  793. 'HeadData': {
  794. 'JB_NO': _billNo,
  795. 'JB_DD': _applyDate,
  796. 'SAL_NO': _selectedApplicantId.isNotEmpty
  797. ? _selectedApplicantId
  798. : HostAppChannel.usr,
  799. 'DEP': _selectedDeptId,
  800. 'REASON': _reasonController.text.trim(),
  801. 'REM': _remarkController.text,
  802. 'USR': HostAppChannel.usr,
  803. },
  804. 'BodyData1': _details.asMap().entries.map((e) {
  805. final d = e.value;
  806. final item = <String, dynamic>{
  807. 'ITM': e.key + 1,
  808. 'SAL_NO': d.salNo,
  809. 'DEP': d.dep.isNotEmpty ? d.dep : _selectedDeptId,
  810. 'JB_TYPE': d.jbType,
  811. 'JB_DATE': d.jbDate,
  812. 'START_TIME': d.startTime,
  813. 'END_TIME': d.endTime,
  814. 'JB_HOURS': d.jbHours,
  815. 'JB_DAYS': d.jbDays,
  816. 'ATT_PERIOD': d.attPeriod,
  817. 'REASON': d.reason,
  818. 'COMPENSATION_TYPE': d.compensationType,
  819. 'COMPENSATION_COUNT': d.compensationCount,
  820. 'ADR': d.adr,
  821. 'REM': d.rem,
  822. };
  823. if (d.preItm != null) {
  824. item['PRE_ITM'] = d.preItm;
  825. }
  826. return item;
  827. }).toList(),
  828. };
  829. }
  830. List<String> _validate(AppLocalizations l10n) {
  831. final e = <String>[];
  832. if (_reasonController.text.trim().isEmpty) {
  833. e.add(l10n.get('enterOvertimeReason'));
  834. }
  835. if (_details.isEmpty) e.add(l10n.get('addAtLeastOneOTDetail'));
  836. if (_selectedDeptId.isEmpty) e.add(l10n.get('selectDept'));
  837. if (_selectedApplicantId.isEmpty) e.add(l10n.get('selectApplicant'));
  838. return e;
  839. }
  840. void _doPop() {
  841. if (_hasUnsaved()) {
  842. final l10n = AppLocalizations.of(context);
  843. _showConfirmDialog(
  844. l10n.get('confirmExit'),
  845. l10n.get('unsavedContentWarning'),
  846. l10n.get('continueEditing'),
  847. l10n.get('discardAndExit'),
  848. () => _forcePop(),
  849. );
  850. } else {
  851. _forcePop();
  852. }
  853. }
  854. void _forcePop() {
  855. FocusManager.instance.primaryFocus?.unfocus();
  856. final router = GoRouter.of(context);
  857. if (router.canPop()) {
  858. router.pop();
  859. } else {
  860. SystemNavigator.pop();
  861. }
  862. }
  863. bool _hasUnsaved() =>
  864. _reasonController.text.isNotEmpty ||
  865. _details.isNotEmpty ||
  866. _remarkController.text.isNotEmpty;
  867. void _showConfirmDialog(
  868. String title,
  869. String content,
  870. String leftText,
  871. String rightText,
  872. VoidCallback onConfirm,
  873. ) {
  874. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  875. showDialog(
  876. context: context,
  877. useRootNavigator: true,
  878. builder: (ctx) => TDAlertDialog(
  879. title: title,
  880. content: content,
  881. buttonStyle: TDDialogButtonStyle.text,
  882. leftBtn: TDDialogButtonOptions(
  883. title: leftText,
  884. titleColor: colors.primary,
  885. action: () => Navigator.pop(ctx),
  886. ),
  887. rightBtn: TDDialogButtonOptions(
  888. title: rightText,
  889. titleColor: colors.danger,
  890. action: () {
  891. Navigator.pop(ctx);
  892. onConfirm();
  893. },
  894. ),
  895. ),
  896. );
  897. }
  898. Widget _label(String t, {bool required = false}) {
  899. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  900. return Text.rich(
  901. TextSpan(
  902. children: [
  903. TextSpan(
  904. text: t,
  905. style: TextStyle(
  906. fontSize: AppFontSizes.subtitle,
  907. color: colors.textSecondary,
  908. ),
  909. ),
  910. if (required)
  911. TextSpan(
  912. text: ' *',
  913. style: TextStyle(
  914. fontSize: AppFontSizes.subtitle,
  915. color: colors.danger,
  916. ),
  917. ),
  918. ],
  919. ),
  920. );
  921. }
  922. Widget _buildPageFooter() {
  923. final l10n = AppLocalizations.of(context);
  924. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  925. return Center(
  926. child: Padding(
  927. padding: const EdgeInsets.only(bottom: 16),
  928. child: Row(
  929. mainAxisSize: MainAxisSize.min,
  930. children: [
  931. Icon(
  932. Icons.rocket_launch_outlined,
  933. size: 16,
  934. color: colors.textPlaceholder,
  935. ),
  936. const SizedBox(width: 6),
  937. Text(
  938. l10n.get('pageFooter'),
  939. style: TextStyle(
  940. fontSize: AppFontSizes.caption,
  941. color: colors.textPlaceholder,
  942. ),
  943. ),
  944. ],
  945. ),
  946. ),
  947. );
  948. }
  949. Future<void> _showDeptPicker() async {
  950. FocusManager.instance.primaryFocus?.unfocus();
  951. final l10n = AppLocalizations.of(context);
  952. final api = ref.read(overtimeApplyApiProvider);
  953. final result = await showSearchablePicker<DepartmentItem>(
  954. context,
  955. title: '${l10n.get('select')}${l10n.get('applyDept')}',
  956. searchHint: l10n.get('search'),
  957. loader: (keyword, page) =>
  958. api.getDepartments(keyword: keyword, page: page, size: 20),
  959. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  960. onRefresh: () => api.clearRefCache(),
  961. );
  962. if (result != null && mounted) {
  963. setState(() {
  964. _selectedDeptId = result.dep;
  965. _selectedDeptName = result.name;
  966. });
  967. }
  968. }
  969. }
  970. class _DetailItem {
  971. final int id;
  972. final String? jbNo;
  973. final int itm;
  974. final String salNo;
  975. final String salName;
  976. final String dep;
  977. final String depName;
  978. final String jbType;
  979. final String jbDate;
  980. final String startTime;
  981. final String endTime;
  982. final double jbHours;
  983. final double jbDays;
  984. final String attPeriod;
  985. final String reason;
  986. final String compensationType;
  987. final double compensationCount;
  988. final String adr;
  989. final String rem;
  990. final int? preItm;
  991. const _DetailItem({
  992. required this.id,
  993. this.jbNo,
  994. this.itm = 0,
  995. this.salNo = '',
  996. this.salName = '',
  997. this.dep = '',
  998. this.depName = '',
  999. this.jbType = 'WORKING_DAY',
  1000. this.jbDate = '',
  1001. this.startTime = '',
  1002. this.endTime = '',
  1003. this.jbHours = 0.0,
  1004. this.jbDays = 0.0,
  1005. this.attPeriod = '',
  1006. this.reason = '',
  1007. this.compensationType = '',
  1008. this.compensationCount = 0.0,
  1009. this.adr = '',
  1010. this.rem = '',
  1011. this.preItm,
  1012. });
  1013. }