overtime_apply_edit_page.dart 33 KB

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