overtime_apply_controller.dart 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 updateOtDate(DateTime d) => state = state.copyWith(overtime: state.overtime.copyWith(otDate: d));
  22. void updateType(String t) => state = state.copyWith(overtime: state.overtime.copyWith(otType: t));
  23. void updateCompensation(String c) => state = state.copyWith(overtime: state.overtime.copyWith(compensationType: c));
  24. void updateStartTime(DateTime t) { state = state.copyWith(overtime: state.overtime.copyWith(startTime: t)); _recalc(); }
  25. void updateEndTime(DateTime t) { state = state.copyWith(overtime: state.overtime.copyWith(endTime: t)); _recalc(); }
  26. void updateReason(String r) => state = state.copyWith(overtime: state.overtime.copyWith(reason: r));
  27. void _recalc() {
  28. final d = state.overtime.endTime.difference(state.overtime.startTime).inMinutes / 60.0;
  29. state = state.copyWith(overtime: state.overtime.copyWith(otHours: d));
  30. }
  31. Future<bool> submit() async {
  32. state = state.copyWith(isSubmitting: true);
  33. try { await _api.submit(state.overtime.copyWith(status: 'pending')); return true; }
  34. catch (_) { return false; }
  35. finally { state = state.copyWith(isSubmitting: false); }
  36. }
  37. Future<bool> saveDraft() async {
  38. state = state.copyWith(isSubmitting: true);
  39. try { await _api.saveDraft(state.overtime); return true; }
  40. catch (_) { return false; }
  41. finally { state = state.copyWith(isSubmitting: false); }
  42. }
  43. }
  44. final overtimeApplyProvider = StateNotifierProvider.autoDispose.family<OvertimeApplyController, OvertimeApplyState, String?>((ref, editId) {
  45. return OvertimeApplyController(ref.read(overtimeApiProvider));
  46. });