Files
school-attendance/lib/function/teacher_location_controller.dart
T

98 lines
2.8 KiB
Dart
Raw Normal View History

// 📍 선생님 위치 등록(교사용) 화면의 기능(서버 통신/상태) 담당 컨트롤러.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import '../config.dart';
class TeacherLocationController extends ChangeNotifier {
final String teacherId;
TeacherLocationController({required this.teacherId});
bool _isLoading = true;
bool _isSaving = false;
String _currentLocation = "교무실";
List<dynamic> _receivedCalls = [];
bool _disposed = false;
bool get isLoading => _isLoading;
bool get isSaving => _isSaving;
String get currentLocation => _currentLocation;
List<dynamic> get receivedCalls => _receivedCalls;
void _safeNotify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
Future<void> init() async {
await Future.wait([_fetchMyLocation(), fetchReceivedCalls()]);
_isLoading = false;
_safeNotify();
}
Future<void> _fetchMyLocation() async {
try {
final response = await http.get(
Uri.parse('$baseUrl/api/teacher-call/teachers'),
);
if (response.statusCode == 200) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
final List<dynamic> list = data['teachers'] ?? [];
final mine = list.firstWhere(
(t) => t['teacherId'] == teacherId,
orElse: () => null,
);
if (mine != null) _currentLocation = mine['location'] ?? '교무실';
}
} catch (_) {
// 조용히 무시
}
}
Future<void> fetchReceivedCalls() async {
try {
final response = await http.get(
Uri.parse(
'$baseUrl/api/teacher-call/received-calls?teacherId=$teacherId',
),
);
if (response.statusCode == 200) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
_receivedCalls = data['calls'] ?? [];
_safeNotify();
}
} catch (_) {
// 조용히 무시
}
}
Future<(bool success, String message)> updateLocation(String location) async {
_isSaving = true;
_safeNotify();
try {
final response = await http.post(
Uri.parse('$baseUrl/api/teacher-call/location'),
headers: {"Content-Type": "application/json"},
body: jsonEncode({"teacherId": teacherId, "location": location}),
);
final result = jsonDecode(utf8.decode(response.bodyBytes));
if (response.statusCode == 200 && result['status'] == 'success') {
_currentLocation = location;
return (true, '${result['message'] ?? '위치가 업데이트되었습니다.'}');
}
return (false, '${result['message'] ?? '업데이트 실패'}');
} catch (e) {
return (false, '네트워크 에러: $e');
} finally {
_isSaving = false;
_safeNotify();
}
}
}