overtime_apply_create_page.dart 32 KB

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