overtime_apply_controller.dart 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import 'package:flutter_riverpod/flutter_riverpod.dart';
  2. import 'overtime_model.dart';
  3. import 'overtime_api.dart';
  4. class OvertimeApplyState {
  5. final OvertimeModel overtime;
  6. final bool isSubmitting;
  7. const OvertimeApplyState({required this.overtime, this.isSubmitting = false});
  8. OvertimeApplyState copyWith({OvertimeModel? overtime, bool? isSubmitting}) =>
  9. OvertimeApplyState(overtime: overtime ?? this.overtime, isSubmitting: isSubmitting ?? this.isSubmitting);
  10. }
  11. class OvertimeApplyController extends StateNotifier<OvertimeApplyState> {
  12. final OvertimeApi _api;
  13. OvertimeApplyController(this._api)
  14. : super(OvertimeApplyState(overtime: OvertimeModel(
  15. id: '', applicationNo: '', applicantId: '', applicantName: '',
  16. deptId: '', deptName: '', otDate: DateTime.now(),
  17. startTime: DateTime.now(), endTime: DateTime.now().add(const Duration(hours: 2)),
  18. otHours: 2.0, otType: '工作日加班', compensationType: '加班费',
  19. reason: '', createTime: DateTime.now(), updateTime: DateTime.now(),
  20. )));
  21. void updateType(String t) => state = state.copyWith(overtime: state.overtime.copyWith(otType: t));
  22. void updateCompensation(String c) => state = state.copyWith(overtime: state.overtime.copyWith(compensationType: c));
  23. void updateStartTime(DateTime t) { state = state.copyWith(overtime: state.overtime.copyWith(startTime: t)); _recalc(); }
  24. void updateEndTime(DateTime t) { state = state.copyWith(overtime: state.overtime.copyWith(endTime: t)); _recalc(); }
  25. void updateReason(String r) => state = state.copyWith(overtime: state.overtime.copyWith(reason: r));
  26. void _recalc() {
  27. final d = state.overtime.endTime.difference(state.overtime.startTime).inMinutes / 60.0;
  28. state = state.copyWith(overtime: state.overtime.copyWith(otHours: d));
  29. }
  30. Future<bool> submit() async {
  31. state = state.copyWith(isSubmitting: true);
  32. try { await _api.submit(state.overtime.copyWith(status: 'pending')); return true; }
  33. catch (_) { return false; }
  34. finally { state = state.copyWith(isSubmitting: false); }
  35. }
  36. Future<bool> saveDraft() async {
  37. state = state.copyWith(isSubmitting: true);
  38. try { await _api.saveDraft(state.overtime); return true; }
  39. catch (_) { return false; }
  40. finally { state = state.copyWith(isSubmitting: false); }
  41. }
  42. }
  43. final overtimeApplyProvider = StateNotifierProvider.autoDispose.family<OvertimeApplyController, OvertimeApplyState, String?>((ref, editId) {
  44. return OvertimeApplyController(ref.read(overtimeApiProvider));
  45. });