overtime_apply_create_page.dart 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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. final pageContent = PopScope(
  195. canPop: false,
  196. onPopInvokedWithResult: (didPop, _) {
  197. if (didPop) return;
  198. _doPop();
  199. },
  200. child: Column(
  201. children: [
  202. Expanded(
  203. child: GestureDetector(
  204. onTap: () => FocusScope.of(context).unfocus(),
  205. child: SingleChildScrollView(
  206. controller: _scrollCtrl,
  207. padding: const EdgeInsets.all(16),
  208. child: Column(
  209. children: [
  210. _buildBasicInfo(l10n),
  211. const SizedBox(height: 16),
  212. _buildDetailsSection(l10n),
  213. const SizedBox(height: 24),
  214. _buildPageFooter(),
  215. ],
  216. ),
  217. ),
  218. ),
  219. ),
  220. _buildBottomBar(l10n),
  221. ],
  222. ),
  223. );
  224. return FutureBuilder<bool>(
  225. future: _draftFuture,
  226. builder: (ctx, snapshot) {
  227. final hasDraft = snapshot.hasData && snapshot.data == true;
  228. if (hasDraft && !_draftHandled) {
  229. _draftHandled = true;
  230. WidgetsBinding.instance.addPostFrameCallback((_) {
  231. if (mounted) _showDraftDialog();
  232. });
  233. }
  234. return pageContent;
  235. },
  236. );
  237. }
  238. // ═══ 草稿持久化 ═══
  239. Future<void> _restoreDraft() async {
  240. final data = await DraftStorage.load(_draftKey);
  241. if (data == null) return;
  242. setState(() {
  243. _reasonController.text = data['reason'] as String? ?? '';
  244. _remarkController.text = data['remark'] as String? ?? '';
  245. _selectedDeptId = data['deptId'] as String? ?? '';
  246. _selectedDeptName = data['deptName'] as String? ?? '';
  247. _selectedApplicantId = data['applicantId'] as String? ?? '';
  248. _selectedApplicantName = data['applicantName'] 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. depName: m['depName'] as String? ?? '',
  263. jbType: m['jbType'] as String? ?? 'WORKING_DAY',
  264. jbDate: m['jbDate'] as String? ?? '',
  265. startTime: m['startTime'] as String? ?? '',
  266. endTime: m['endTime'] as String? ?? '',
  267. jbHours: (m['jbHours'] as num?)?.toDouble() ?? 0.0,
  268. jbDays: (m['jbDays'] as num?)?.toDouble() ?? 0.0,
  269. attPeriod: m['attPeriod'] as String? ?? '',
  270. reason: m['detailReason'] as String? ?? '',
  271. compensationType:
  272. m['compensationType'] as String? ?? 'OVERTIME_PAY',
  273. compensationCount:
  274. (m['compensationCount'] as num?)?.toDouble() ?? 0.0,
  275. adr: m['adr'] as String? ?? '',
  276. rem: m['rem'] as String? ?? '',
  277. ),
  278. );
  279. }
  280. }
  281. _detailIdCounter = _details.isEmpty
  282. ? 1
  283. : _details.map((d) => d.id).reduce((a, b) => a > b ? a : b) + 1;
  284. });
  285. }
  286. Future<void> _saveDraftToStorage() async {
  287. final detailList = _details
  288. .map(
  289. (d) => {
  290. 'id': d.id,
  291. 'jbNo': d.jbNo,
  292. 'itm': d.itm,
  293. 'salNo': d.salNo,
  294. 'salName': d.salName,
  295. 'dep': d.dep,
  296. 'depName': d.depName,
  297. 'jbType': d.jbType,
  298. 'jbDate': d.jbDate,
  299. 'startTime': d.startTime,
  300. 'endTime': d.endTime,
  301. 'jbHours': d.jbHours,
  302. 'jbDays': d.jbDays,
  303. 'attPeriod': d.attPeriod,
  304. 'detailReason': d.reason,
  305. 'compensationType': d.compensationType,
  306. 'compensationCount': d.compensationCount,
  307. 'adr': d.adr,
  308. 'rem': d.rem,
  309. },
  310. )
  311. .toList();
  312. await DraftStorage.save(_draftKey, {
  313. 'reason': _reasonController.text,
  314. 'remark': _remarkController.text,
  315. 'deptId': _selectedDeptId,
  316. 'deptName': _selectedDeptName,
  317. 'applicantId': _selectedApplicantId,
  318. 'applicantName': _selectedApplicantName,
  319. 'details': detailList,
  320. });
  321. }
  322. // ═══ 草稿弹窗 ═══
  323. void _showDraftDialog() {
  324. final l10n = AppLocalizations.of(context);
  325. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  326. FocusManager.instance.primaryFocus?.unfocus();
  327. showDialog(
  328. context: context,
  329. barrierDismissible: false,
  330. builder: (ctx) => TDAlertDialog(
  331. title: l10n.get('draftFound'),
  332. content: l10n.get('draftRestorePrompt'),
  333. buttonStyle: TDDialogButtonStyle.text,
  334. leftBtn: TDDialogButtonOptions(
  335. title: l10n.get('discard'),
  336. titleColor: colors.danger,
  337. action: () {
  338. Navigator.pop(ctx);
  339. DraftStorage.delete(_draftKey);
  340. },
  341. ),
  342. rightBtn: TDDialogButtonOptions(
  343. title: l10n.get('restore'),
  344. titleColor: colors.primary,
  345. action: () {
  346. Navigator.pop(ctx);
  347. _restoreDraft();
  348. },
  349. ),
  350. ),
  351. );
  352. }
  353. // ═══ 1. 基本信息 ═══
  354. Widget _buildBasicInfo(AppLocalizations l10n) {
  355. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  356. final now = DateTime.now();
  357. final todayStr =
  358. '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
  359. return FormSection(
  360. title: l10n.get('basicInfo'),
  361. leadingIcon: Icons.info_outline,
  362. children: [
  363. FormFieldRow(
  364. label: l10n.get('date'),
  365. value: todayStr,
  366. readOnly: true,
  367. showArrow: false,
  368. ),
  369. const SizedBox(height: 16),
  370. FormFieldRow(
  371. label: l10n.get('dep'),
  372. value: _selectedDeptId.isNotEmpty
  373. ? '$_selectedDeptId/$_selectedDeptName'
  374. : '',
  375. hint: l10n.get('pleaseSelect'),
  376. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  377. ),
  378. const SizedBox(height: 16),
  379. FormFieldRow(
  380. label: l10n.get('applicant'),
  381. required: true,
  382. value: _selectedApplicantId.isNotEmpty
  383. ? '$_selectedApplicantId/$_selectedApplicantName'
  384. : '',
  385. hint: l10n.get('pleaseSelect'),
  386. onTap: () => _showApplicantPicker(),
  387. ),
  388. const SizedBox(height: 16),
  389. _label(l10n.get('overtimeReason'), required: true),
  390. const SizedBox(height: 8),
  391. TDTextarea(
  392. controller: _reasonController,
  393. focusNode: _reasonFocus,
  394. hintText: l10n.get('enterOvertimeReason'),
  395. maxLines: 4,
  396. minLines: 1,
  397. maxLength: 1000,
  398. indicator: true,
  399. padding: EdgeInsets.zero,
  400. bordered: true,
  401. backgroundColor: colors.bgPage,
  402. ),
  403. const SizedBox(height: 16),
  404. _label(l10n.get('remark')),
  405. const SizedBox(height: 8),
  406. TDTextarea(
  407. controller: _remarkController,
  408. focusNode: _remarkFocus,
  409. hintText: l10n.get('enterRemark'),
  410. maxLines: 3,
  411. minLines: 1,
  412. maxLength: 500,
  413. indicator: true,
  414. padding: EdgeInsets.zero,
  415. bordered: true,
  416. backgroundColor: colors.bgPage,
  417. ),
  418. ],
  419. );
  420. }
  421. // ═══ 2. 加班明细 ═══
  422. Widget _buildDetailsSection(AppLocalizations l10n) {
  423. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  424. return FormSection(
  425. title: l10n.get('overtimeDetails'),
  426. leadingIcon: Icons.access_time_outlined,
  427. showAction: true,
  428. actionText: l10n.get('add'),
  429. onActionTap: _showDetailDialog,
  430. children: [
  431. if (_details.isEmpty)
  432. Padding(
  433. padding: const EdgeInsets.symmetric(vertical: 8),
  434. child: Text(
  435. l10n.get('noDetailHint'),
  436. style: TextStyle(
  437. fontSize: AppFontSizes.subtitle,
  438. color: colors.textPlaceholder,
  439. ),
  440. ),
  441. )
  442. else
  443. ..._details.asMap().entries.map((e) {
  444. final d = e.value;
  445. return GestureDetector(
  446. onTap: () => _showDetailDialog(editIndex: e.key),
  447. child: Container(
  448. margin: const EdgeInsets.symmetric(vertical: 6),
  449. padding: const EdgeInsets.all(12),
  450. decoration: BoxDecoration(
  451. color: colors.bgPage,
  452. borderRadius: BorderRadius.circular(8),
  453. ),
  454. child: Row(
  455. children: [
  456. Expanded(
  457. child: Column(
  458. crossAxisAlignment: CrossAxisAlignment.start,
  459. children: [
  460. Row(
  461. children: [
  462. Expanded(
  463. child: Text(
  464. '${d.salNo}${d.salName.isNotEmpty ? '/${d.salName}' : ''}',
  465. maxLines: 1,
  466. overflow: TextOverflow.ellipsis,
  467. style: TextStyle(
  468. fontSize: AppFontSizes.body,
  469. fontWeight: FontWeight.w500,
  470. color: colors.textPrimary,
  471. ),
  472. ),
  473. ),
  474. Text(
  475. '${d.jbHours.toStringAsFixed(1)}${l10n.get('hours')}',
  476. style: TextStyle(
  477. fontSize: AppFontSizes.body,
  478. fontWeight: FontWeight.w600,
  479. color: colors.timePrimary,
  480. ),
  481. ),
  482. ],
  483. ),
  484. if (d.jbType.isNotEmpty) ...[
  485. const SizedBox(height: 2),
  486. _detailLabel(
  487. '${l10n.get('jbType')}: ${_jbTypeLabel(d.jbType, l10n)}',
  488. colors,
  489. ),
  490. _detailLabel(
  491. '${l10n.get('applyDate')}: ${d.jbDate}',
  492. colors,
  493. ),
  494. ],
  495. if (d.startTime.isNotEmpty) ...[
  496. const SizedBox(height: 2),
  497. Row(
  498. crossAxisAlignment: CrossAxisAlignment.center,
  499. children: [
  500. Expanded(
  501. child: _detailLabel(
  502. '${l10n.get('startTime')}: ${d.startTime}',
  503. colors,
  504. ),
  505. ),
  506. if (_dayOfWeekLabel(d.startTime, l10n) != null)
  507. _dayOfWeekTag(
  508. _dayOfWeekLabel(d.startTime, l10n)!,
  509. ),
  510. ],
  511. ),
  512. ],
  513. if (d.endTime.isNotEmpty) ...[
  514. const SizedBox(height: 2),
  515. Row(
  516. crossAxisAlignment: CrossAxisAlignment.center,
  517. children: [
  518. Expanded(
  519. child: _detailLabel(
  520. '${l10n.get('endTime')}: ${d.endTime}',
  521. colors,
  522. ),
  523. ),
  524. if (_dayOfWeekLabel(d.endTime, l10n) != null)
  525. _dayOfWeekTag(
  526. _dayOfWeekLabel(d.endTime, l10n)!,
  527. ),
  528. ],
  529. ),
  530. ],
  531. if (d.jbDays > 0) ...[
  532. const SizedBox(height: 2),
  533. _detailLabel(
  534. '${l10n.get('overtimeDays')}: ${d.jbDays.toStringAsFixed(1)}',
  535. colors,
  536. ),
  537. ],
  538. if (d.attPeriod.isNotEmpty) ...[
  539. const SizedBox(height: 2),
  540. _detailLabel(
  541. '${l10n.get('attPeriod')}: ${d.attPeriod}',
  542. colors,
  543. ),
  544. ],
  545. if (d.compensationType.isNotEmpty) ...[
  546. const SizedBox(height: 2),
  547. _detailLabel(
  548. '${l10n.get('compensationType')}: ${_compensationTypeLabel(d.compensationType, l10n)}',
  549. colors,
  550. ),
  551. if (d.compensationType != 'NO_COMPENSATION' &&
  552. d.compensationCount > 0)
  553. _detailLabel(
  554. '${l10n.get('compensationCount')}: ${d.compensationCount.toStringAsFixed(1)}',
  555. colors,
  556. ),
  557. ],
  558. if (d.adr.isNotEmpty) ...[
  559. const SizedBox(height: 2),
  560. _detailLabel(
  561. '${l10n.get('adr')}: ${d.adr}',
  562. colors,
  563. ),
  564. ],
  565. if (d.reason.isNotEmpty) ...[
  566. const SizedBox(height: 2),
  567. _detailLabel(
  568. '${l10n.get('overtimeDetailReason')}: ${d.reason}',
  569. colors,
  570. ),
  571. ],
  572. if (d.rem.isNotEmpty) ...[
  573. const SizedBox(height: 2),
  574. _detailLabel(
  575. '${l10n.get('remark')}: ${d.rem}',
  576. colors,
  577. ),
  578. ],
  579. ],
  580. ),
  581. ),
  582. const SizedBox(width: 8),
  583. GestureDetector(
  584. onTap: () => setState(() => _details.removeAt(e.key)),
  585. child: Icon(
  586. Icons.close,
  587. size: 18,
  588. color: colors.textSecondary,
  589. ),
  590. ),
  591. ],
  592. ),
  593. ),
  594. );
  595. }),
  596. const SizedBox(height: 8),
  597. Container(
  598. padding: const EdgeInsets.symmetric(vertical: 8),
  599. child: Row(
  600. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  601. children: [
  602. Text(
  603. l10n.get('totalOvertimeHours'),
  604. style: TextStyle(
  605. fontSize: AppFontSizes.body,
  606. fontWeight: FontWeight.w600,
  607. color: colors.textPrimary,
  608. ),
  609. ),
  610. Text(
  611. '${_totalHours().toStringAsFixed(1)}${l10n.get('hours')}',
  612. style: TextStyle(
  613. fontSize: AppFontSizes.subtitle,
  614. fontWeight: FontWeight.w700,
  615. color: colors.timePrimary,
  616. ),
  617. ),
  618. ],
  619. ),
  620. ),
  621. ],
  622. );
  623. }
  624. double _totalHours() => _details.fold(0.0, (s, d) => s + d.jbHours);
  625. String _jbTypeLabel(String type, AppLocalizations l10n) {
  626. switch (type) {
  627. case 'WORKING_DAY':
  628. return l10n.get('workingDay');
  629. case 'REST_DAY':
  630. return l10n.get('restDay');
  631. case 'PUBLIC_HOLIDAY':
  632. return l10n.get('publicHoliday');
  633. case 'SPECIAL_HOLIDAY':
  634. return l10n.get('specialHoliday');
  635. case 'OTHER':
  636. return l10n.get('other');
  637. default:
  638. return type;
  639. }
  640. }
  641. String? _dayOfWeekLabel(String dateTimeStr, AppLocalizations l10n) {
  642. final dt = DateTime.tryParse(dateTimeStr);
  643. if (dt == null) return null;
  644. switch (dt.weekday) {
  645. case 1:
  646. return l10n.get('monday');
  647. case 2:
  648. return l10n.get('tuesday');
  649. case 3:
  650. return l10n.get('wednesday');
  651. case 4:
  652. return l10n.get('thursday');
  653. case 5:
  654. return l10n.get('friday');
  655. case 6:
  656. return l10n.get('saturday');
  657. case 7:
  658. return l10n.get('sunday');
  659. default:
  660. return null;
  661. }
  662. }
  663. String _compensationTypeLabel(String type, AppLocalizations l10n) {
  664. switch (type) {
  665. case 'OVERTIME_PAY':
  666. return l10n.get('overtimePay');
  667. case 'COMPENSATORY_LEAVE':
  668. return l10n.get('compensatoryLeave');
  669. case 'NO_COMPENSATION':
  670. return l10n.get('noCompensation');
  671. case 'OTHER':
  672. return l10n.get('other');
  673. default:
  674. return type;
  675. }
  676. }
  677. Widget _detailLabel(String text, AppColorsExtension colors) {
  678. return Padding(
  679. padding: const EdgeInsets.only(top: 2),
  680. child: Text(
  681. text,
  682. maxLines: 2,
  683. overflow: TextOverflow.ellipsis,
  684. style: TextStyle(
  685. fontSize: AppFontSizes.caption,
  686. color: colors.textSecondary,
  687. ),
  688. ),
  689. );
  690. }
  691. Widget _dayOfWeekTag(String label) {
  692. final tdTheme = TDTheme.of(context);
  693. return Container(
  694. padding: const EdgeInsets.symmetric(horizontal: 6),
  695. decoration: BoxDecoration(
  696. color: tdTheme.brandColor1,
  697. borderRadius: BorderRadius.circular(4),
  698. ),
  699. child: TDText(
  700. label,
  701. font: tdTheme.fontBodySmall,
  702. fontWeight: FontWeight.w500,
  703. textColor: tdTheme.brandColor7,
  704. ),
  705. );
  706. }
  707. Future<void> _showDetailDialog({int? editIndex}) async {
  708. if (_addingDetail) return;
  709. _addingDetail = true;
  710. try {
  711. final l10n = AppLocalizations.of(context);
  712. OvertimeDetailData? initialData;
  713. if (editIndex != null) {
  714. final d = _details[editIndex];
  715. initialData = OvertimeDetailData(
  716. jbNo: d.jbNo,
  717. itm: d.itm > 0 ? d.itm : null,
  718. salNo: d.salNo,
  719. salName: d.salName,
  720. dep: d.dep,
  721. depName: d.depName,
  722. jbType: d.jbType,
  723. jbDate: d.jbDate,
  724. startTime: d.startTime,
  725. endTime: d.endTime,
  726. jbHours: d.jbHours,
  727. jbDays: d.jbDays,
  728. attPeriod: d.attPeriod,
  729. reason: d.reason,
  730. compensationType: d.compensationType,
  731. compensationCount: d.compensationCount,
  732. adr: d.adr,
  733. rem: d.rem,
  734. );
  735. }
  736. FocusManager.instance.primaryFocus?.unfocus();
  737. final result = await OvertimeApplyDetailDialog.show(
  738. // ignore: use_build_context_synchronously
  739. context,
  740. api: ref.read(overtimeApplyApiProvider),
  741. l10n: l10n,
  742. initialData: initialData,
  743. );
  744. if (result != null && mounted) {
  745. setState(() {
  746. final item = _DetailItem(
  747. id: editIndex != null ? _details[editIndex].id : _detailIdCounter++,
  748. jbNo: result.jbNo,
  749. itm: result.itm ?? 0,
  750. salNo: result.salNo,
  751. salName: result.salName,
  752. dep: result.dep,
  753. depName: result.depName,
  754. jbType: result.jbType,
  755. jbDate: result.jbDate,
  756. startTime: result.startTime,
  757. endTime: result.endTime,
  758. jbHours: result.jbHours,
  759. jbDays: result.jbDays,
  760. attPeriod: result.attPeriod,
  761. reason: result.reason,
  762. compensationType: result.compensationType,
  763. compensationCount: result.compensationCount,
  764. adr: result.adr,
  765. rem: result.rem,
  766. );
  767. if (editIndex != null) {
  768. _details[editIndex] = item;
  769. } else {
  770. _details.add(item);
  771. }
  772. });
  773. }
  774. } finally {
  775. _addingDetail = false;
  776. }
  777. }
  778. // ═══ 3. 底部操作栏 ═══
  779. Widget _buildBottomBar(AppLocalizations l10n) {
  780. return ActionBar(
  781. showLeft: false,
  782. centerLabel: l10n.get('saveDraft'),
  783. rightLabel: l10n.get('submit'),
  784. centerTextOnly: true,
  785. onCenterTap: () async {
  786. FocusScope.of(context).unfocus();
  787. try {
  788. await _saveDraftToStorage();
  789. if (mounted) _forcePop();
  790. } catch (_) {
  791. if (mounted) {
  792. TDToast.showFail(l10n.get('saveFailed'), context: context);
  793. }
  794. }
  795. },
  796. onRightTap: () async {
  797. final err = _validate(l10n);
  798. if (err.isNotEmpty) {
  799. TDToast.showText(err.first, context: context);
  800. return;
  801. }
  802. FocusScope.of(context).unfocus();
  803. LoadingDialog.show(context, text: l10n.get('submitting'));
  804. try {
  805. final data = _buildSubmitData();
  806. final api = ref.read(overtimeApplyApiProvider);
  807. await api.submit(data);
  808. await DraftStorage.delete(_draftKey);
  809. if (mounted) {
  810. LoadingDialog.hide(context);
  811. TDToast.showSuccess(l10n.get('submitSuccess'), context: context);
  812. GoRouter.of(context).go('/overtime-apply/list');
  813. }
  814. } catch (e) {
  815. if (mounted) {
  816. LoadingDialog.hide(context);
  817. WidgetsBinding.instance.addPostFrameCallback((_) {
  818. if (mounted) _showSubmitError(e, l10n);
  819. });
  820. }
  821. }
  822. },
  823. );
  824. }
  825. void _showSubmitError(Object e, AppLocalizations l10n) {
  826. final message = _extractErrorMessage(e) ?? l10n.get('submitFailedRetry');
  827. showGeneralDialog(
  828. context: context,
  829. pageBuilder: (ctx, animation, secondaryAnimation) => TDConfirmDialog(
  830. title: l10n.get('submitFailed'),
  831. content: message,
  832. buttonStyle: TDDialogButtonStyle.text,
  833. ),
  834. );
  835. }
  836. String? _extractErrorMessage(Object e) {
  837. if (e is DioException) {
  838. if (e.error is ApiException) return (e.error as ApiException).message;
  839. if (e.error is NetworkException) {
  840. return (e.error as NetworkException).message;
  841. }
  842. }
  843. return null;
  844. }
  845. Map<String, dynamic> _buildSubmitData() {
  846. final now = DateTime.now();
  847. final jbDd =
  848. '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
  849. return {
  850. 'HeadData': {
  851. 'JB_DD': jbDd,
  852. 'SAL_NO': _selectedApplicantId.isNotEmpty
  853. ? _selectedApplicantId
  854. : HostAppChannel.usr,
  855. 'DEP': _selectedDeptId,
  856. 'REASON': _reasonController.text.trim(),
  857. 'REM': _remarkController.text,
  858. 'USR': HostAppChannel.usr,
  859. },
  860. 'BodyData1': _details.asMap().entries.map((e) {
  861. final d = e.value;
  862. return {
  863. 'ITM': e.key + 1,
  864. 'SAL_NO': d.salNo,
  865. 'DEP': d.dep.isNotEmpty ? d.dep : _selectedDeptId,
  866. 'JB_TYPE': d.jbType,
  867. 'JB_DATE': d.jbDate,
  868. 'START_TIME': d.startTime,
  869. 'END_TIME': d.endTime,
  870. 'JB_HOURS': d.jbHours,
  871. 'JB_DAYS': d.jbDays,
  872. 'ATT_PERIOD': d.attPeriod,
  873. 'REASON': d.reason,
  874. 'COMPENSATION_TYPE': d.compensationType,
  875. 'COMPENSATION_COUNT': d.compensationCount,
  876. 'ADR': d.adr,
  877. 'REM': d.rem,
  878. };
  879. }).toList(),
  880. };
  881. }
  882. List<String> _validate(AppLocalizations l10n) {
  883. final e = <String>[];
  884. if (_reasonController.text.trim().isEmpty) {
  885. e.add(l10n.get('enterOvertimeReason'));
  886. }
  887. if (_details.isEmpty) e.add(l10n.get('addAtLeastOneDetail'));
  888. if (_selectedDeptId.isEmpty) e.add(l10n.get('selectDept'));
  889. if (_selectedApplicantId.isEmpty) e.add(l10n.get('selectApplicant'));
  890. return e;
  891. }
  892. void _doPop() {
  893. if (_hasUnsaved()) {
  894. final l10n = AppLocalizations.of(context);
  895. _showConfirmDialog(
  896. l10n.get('confirmExit'),
  897. l10n.get('unsavedContentWarning'),
  898. l10n.get('continueEditing'),
  899. l10n.get('discardAndExit'),
  900. () async {
  901. await DraftStorage.delete(_draftKey);
  902. if (!mounted) return;
  903. setState(() => _clearLocalState());
  904. _forcePop();
  905. },
  906. );
  907. } else {
  908. _forcePop();
  909. }
  910. }
  911. void _forcePop() {
  912. FocusManager.instance.primaryFocus?.unfocus();
  913. final router = GoRouter.of(context);
  914. if (router.canPop()) {
  915. router.pop();
  916. } else {
  917. SystemNavigator.pop();
  918. }
  919. }
  920. bool _hasUnsaved() =>
  921. _reasonController.text.isNotEmpty ||
  922. _details.isNotEmpty ||
  923. _remarkController.text.isNotEmpty;
  924. void _clearLocalState() {
  925. _reasonController.clear();
  926. _remarkController.clear();
  927. _details.clear();
  928. _detailIdCounter = 1;
  929. _selectedDeptId = '';
  930. _selectedDeptName = '';
  931. _selectedApplicantId = '';
  932. _selectedApplicantName = '';
  933. }
  934. void _unfocus() => FocusScope.of(context).unfocus();
  935. void _showConfirmDialog(
  936. String title,
  937. String content,
  938. String leftText,
  939. String rightText,
  940. VoidCallback onConfirm,
  941. ) {
  942. _unfocus();
  943. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  944. showDialog(
  945. context: context,
  946. useRootNavigator: true,
  947. builder: (ctx) => TDAlertDialog(
  948. title: title,
  949. content: content,
  950. buttonStyle: TDDialogButtonStyle.text,
  951. leftBtn: TDDialogButtonOptions(
  952. title: leftText,
  953. titleColor: colors.primary,
  954. action: () => Navigator.pop(ctx),
  955. ),
  956. rightBtn: TDDialogButtonOptions(
  957. title: rightText,
  958. titleColor: colors.danger,
  959. action: () {
  960. Navigator.pop(ctx);
  961. onConfirm();
  962. },
  963. ),
  964. ),
  965. );
  966. }
  967. Widget _label(String t, {bool required = false}) {
  968. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  969. return Text.rich(
  970. TextSpan(
  971. children: [
  972. TextSpan(
  973. text: t,
  974. style: TextStyle(
  975. fontSize: AppFontSizes.subtitle,
  976. color: colors.textSecondary,
  977. ),
  978. ),
  979. if (required)
  980. TextSpan(
  981. text: ' *',
  982. style: TextStyle(
  983. fontSize: AppFontSizes.subtitle,
  984. color: colors.danger,
  985. ),
  986. ),
  987. ],
  988. ),
  989. );
  990. }
  991. Widget _buildPageFooter() {
  992. final l10n = AppLocalizations.of(context);
  993. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  994. return Center(
  995. child: Padding(
  996. padding: const EdgeInsets.only(bottom: 16),
  997. child: Row(
  998. mainAxisSize: MainAxisSize.min,
  999. children: [
  1000. Icon(
  1001. Icons.rocket_launch_outlined,
  1002. size: 16,
  1003. color: colors.textPlaceholder,
  1004. ),
  1005. const SizedBox(width: 6),
  1006. Text(
  1007. l10n.get('pageFooter'),
  1008. style: TextStyle(
  1009. fontSize: AppFontSizes.caption,
  1010. color: colors.textPlaceholder,
  1011. ),
  1012. ),
  1013. ],
  1014. ),
  1015. ),
  1016. );
  1017. }
  1018. Future<void> _showDeptPicker() async {
  1019. FocusManager.instance.primaryFocus?.unfocus();
  1020. final l10n = AppLocalizations.of(context);
  1021. final api = ref.read(overtimeApplyApiProvider);
  1022. final result = await showSearchablePicker<DepartmentItem>(
  1023. context,
  1024. title: '${l10n.get('select')}${l10n.get('applyDept')}',
  1025. searchHint: l10n.get('search'),
  1026. loader: (keyword, page) =>
  1027. api.getDepartments(keyword: keyword, page: page, size: 20),
  1028. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  1029. onRefresh: () => api.clearRefCache(),
  1030. );
  1031. if (result != null && mounted) {
  1032. setState(() {
  1033. _selectedDeptId = result.dep;
  1034. _selectedDeptName = result.name;
  1035. });
  1036. }
  1037. }
  1038. }
  1039. class _DetailItem {
  1040. final int id;
  1041. final String? jbNo;
  1042. final int itm;
  1043. final String salNo;
  1044. final String salName;
  1045. final String dep;
  1046. final String depName;
  1047. final String jbType;
  1048. final String jbDate;
  1049. final String startTime;
  1050. final String endTime;
  1051. final double jbHours;
  1052. final double jbDays;
  1053. final String attPeriod;
  1054. final String reason;
  1055. final String compensationType;
  1056. final double compensationCount;
  1057. final String adr;
  1058. final String rem;
  1059. const _DetailItem({
  1060. required this.id,
  1061. this.jbNo,
  1062. this.itm = 0,
  1063. this.salNo = '',
  1064. this.salName = '',
  1065. this.dep = '',
  1066. this.depName = '',
  1067. this.jbType = 'WORKING_DAY',
  1068. this.jbDate = '',
  1069. this.startTime = '',
  1070. this.endTime = '',
  1071. this.jbHours = 0.0,
  1072. this.jbDays = 0.0,
  1073. this.attPeriod = '',
  1074. this.reason = '',
  1075. this.compensationType = '',
  1076. this.compensationCount = 0.0,
  1077. this.adr = '',
  1078. this.rem = '',
  1079. });
  1080. }