Files
flutterApp/lib/features/v2/site/presentation/cubit/site_cubit.dart
2026-08-07 08:49:29 +08:00

135 lines
4.0 KiB
Dart
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it/get_it.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../../core/network/tcp/tcp_client.dart';
import '../../../home/domain/entities/site_entity.dart';
import '../../../home/domain/usecases/get_site_list_usecase.dart';
import '../../../../../core/app/app_user_cubit.dart';
class SiteState {
final List<SiteEntity> sites;
final SiteEntity? selectedSite;
final bool isLoading;
const SiteState({
this.sites = const [],
this.selectedSite,
this.isLoading = false,
});
SiteState copyWith({
List<SiteEntity>? sites,
SiteEntity? selectedSite,
bool? isLoading,
}) {
return SiteState(
sites: sites ?? this.sites,
selectedSite: selectedSite ?? this.selectedSite,
isLoading: isLoading ?? this.isLoading,
);
}
}
class SiteCubit extends Cubit<SiteState> {
final SharedPreferences sharedPreferences;
static const String _selectedSiteIdKey = 'selected_site_id';
bool _hasLoadedSites = false;
SiteCubit(this.sharedPreferences) : super(const SiteState());
/// 加载场站列表(首次调用时请求接口,之后不重复请求)
Future<void> loadSites() async {
if (_hasLoadedSites) return;
_hasLoadedSites = true;
emit(state.copyWith(isLoading: true));
try {
final userId = GetIt.I<AppUserCubit>().state.user?.userId;
if (userId == null) {
emit(state.copyWith(isLoading: false));
return;
}
final result = await GetIt.I<GetSiteListUseCase>().call(userId);
result.fold(
(failure) {
debugPrint('❌ [SiteCubit] 加载场站列表失败: ${failure.message}');
emit(state.copyWith(isLoading: false));
},
(sites) {
updateSites(sites);
emit(state.copyWith(isLoading: false));
},
);
} catch (e) {
debugPrint('❌ [SiteCubit] 加载场站列表异常: $e');
emit(state.copyWith(isLoading: false));
}
}
/// 强制重新加载场站列表
Future<void> reloadSites() async {
_hasLoadedSites = false;
await loadSites();
}
/// 更新场站列表
void updateSites(List<SiteEntity> sites) {
// 尝试恢复之前选中的场站
final savedSiteId = sharedPreferences.getInt(_selectedSiteIdKey);
SiteEntity? selectedSite;
if (savedSiteId != null && sites.isNotEmpty) {
selectedSite = sites.firstWhere(
(site) => site.id == savedSiteId,
orElse: () => sites.first,
);
} else if (sites.isNotEmpty) {
selectedSite = sites.first;
}
emit(state.copyWith(sites: sites, selectedSite: selectedSite));
}
/// 选择场站(持久化)
void selectSite(SiteEntity site) {
debugPrint('🏭 [SiteCubit] ========== 切换场站 ==========');
debugPrint(
'🏭 [SiteCubit] 从 ${state.selectedSite?.siteName ?? "无"} 切换到 ${site.siteName}',
);
// 🔥 关键修复:只有切换到不同场站时才断开TCP
if (state.selectedSite?.id != site.id) {
final tcpClient = GetIt.I<TcpClient>();
if (tcpClient.isConnected) {
debugPrint('🛑 [SiteCubit] 检测到TCP已连接,正在断开...');
tcpClient.disconnect();
debugPrint('✅ [SiteCubit] TCP已断开,防止场站间设备数据混淆');
} else {
debugPrint('ℹ️ [SiteCubit] TCP未连接,无需断开');
}
} else {
debugPrint('✅ [SiteCubit] 相同场站,保持TCP连接状态');
}
sharedPreferences.setInt(_selectedSiteIdKey, site.id);
emit(state.copyWith(selectedSite: site));
debugPrint('✅ [SiteCubit] 场站切换完成');
}
/// 清除选中场站
void clearSelectedSite() {
sharedPreferences.remove(_selectedSiteIdKey);
emit(state.copyWith(selectedSite: null));
}
/// 清空所有场站数据(退出登录时调用)
void clearAll() {
_hasLoadedSites = false;
sharedPreferences.remove(_selectedSiteIdKey);
emit(const SiteState());
}
}