远程遥控相关

This commit is contained in:
2026-11-06 08:34:19 +08:00
parent eb8dec2868
commit d882db7995
42 changed files with 5023 additions and 631 deletions

View File

@@ -304,12 +304,20 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
}
Future<bool> submitBind(String deviceId) async {
debugPrint(
'>>> [BindDevice] submitBind 入参 deviceId=$deviceId roleKey=$roleKey '
'orgId=${state.selectedOrgId} siteId=${state.selectedSiteId} '
'userId=${state.selectedUserId}',
);
if (state.selectedOrgId == null) {
debugPrint('>>> [BindDevice] 前置拦截:selectedOrgId 为空,未发请求');
emit(state.copyWith(errorMessage: '请选择所属组织'));
return false;
}
if (roleKey == 'user' && state.selectedUserId == null) {
debugPrint('>>> [BindDevice] 前置拦截:user 角色未选负责人,未发请求');
emit(state.copyWith(errorMessage: '请选择负责人'));
return false;
}
@@ -323,6 +331,10 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
);
final isAtSite = existResult.fold((failure) => false, (exists) => exists);
debugPrint(
'>>> [BindDevice] 场站查重 deviceId=$deviceId siteId=${state.selectedSiteId} '
'isAtSite=$isAtSite',
);
if (isAtSite) {
emit(
@@ -332,6 +344,7 @@ class BindDeviceCubit extends Cubit<BindDeviceState> {
}
}
debugPrint('>>> [BindDevice] 前置校验通过,开始调用绑定用例');
final result = await _bindDeviceUseCase(
deviceIds: [deviceId],
orgId: state.selectedOrgId!,

View File

@@ -0,0 +1,497 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
import '../../domain/entities/bind_device_entities.dart';
import '../../domain/usecases/bind_device_usecases.dart';
import 'device_ownership_action_state.dart';
/// 设备归属操作:转交(= 绑定接口)与解绑(= 解绑接口)共用一套流程。
///
/// 两条链路都是「扫码核验 → 按角色选择组织/场站/负责人 → 下发」,
/// 三级选择与角色规则逐行对齐绑定流程([BindDeviceCubit]),
/// 差别只在提交:转交走 [BindDeviceV2UseCase],解绑走 [UnbindDeviceV2UseCase]。
///
/// 之所以不直接复用 [BindDeviceCubit],是因为绑定页还带着"扫码即绑定"的
/// 独立页面流程,这里只借用它的层级加载与角色口径,不改动它本身。
class DeviceOwnershipActionCubit extends Cubit<DeviceOwnershipActionState> {
final GetOrgListUseCase _getOrgListUseCase;
final GetSitesByOrgUseCase _getSitesByOrgUseCase;
final GetUsersBySiteUseCase _getUsersBySiteUseCase;
final BindDeviceV2UseCase _bindDeviceUseCase;
final UnbindDeviceV2UseCase _unbindDeviceUseCase;
final AppUserCubit _appUserCubit;
DeviceOwnershipActionCubit(
this._getOrgListUseCase,
this._getSitesByOrgUseCase,
this._getUsersBySiteUseCase,
this._bindDeviceUseCase,
this._unbindDeviceUseCase,
this._appUserCubit,
) : super(const DeviceOwnershipActionState());
UserEntity? get _currentUser => _appUserCubit.state.user;
String get roleKey => state.roleKey;
/// 角色可编辑范围(与绑定页保持一致)
bool get isOrgEnabled => roleKey == 'admin';
bool get isSiteEnabled => roleKey == 'admin' || roleKey == 'manager';
/// 负责人:
/// - 普通用户 / 个人角色只能选自己,所以 UI 锁定(选中值默认就是自己);
/// - 场站负责人及以上可以选场站内的人。
bool get isUserEnabled =>
roleKey == 'admin' || roleKey == 'manager' || roleKey == 'siteManager';
/// 当前角色能触达的最深一级,口径与可编辑范围一一对应:
/// admin 可动到组织(含场站/负责人),manager 只到场站,
/// siteManager 与普通用户只到负责人(他们能动的只有人这一层)。
UnbindScope get roleMaxScope {
if (isOrgEnabled) return UnbindScope.org;
if (isSiteEnabled) return UnbindScope.site;
return UnbindScope.user;
}
/// 解绑实际下发的清除范围:所选层级不得越过角色上限。
/// UnbindScope 的值越大解绑得越彻底(1 人 < 2 站 < 3 组织),所以取较小者。
UnbindScope get effectiveScope {
final picked = state.scopePreview;
final max = roleMaxScope;
return picked.value <= max.value ? picked : max;
}
/// 能否用「不指定」把负责人清空(清空后由场站决定层级)
bool get canClearUser => roleMaxScope.value >= UnbindScope.site.value;
/// 能否用「不指定」把场站清空(清空后由组织决定层级)
bool get canClearSite => roleMaxScope.value >= UnbindScope.org.value;
// ── 去重 / 兜底辅助(与绑定页同口径)──
List<OrgEntity> _uniqueOrgs(List<OrgEntity> list) {
final seen = <int>{};
return list.where((e) => seen.add(e.id)).toList();
}
List<SiteEntity> _uniqueSites(List<SiteEntity> list) {
final seen = <int>{};
return list.where((e) => seen.add(e.id)).toList();
}
List<UserSimpleEntity> _uniqueUsers(List<UserSimpleEntity> list) {
final seen = <int>{};
return list.where((e) => seen.add(e.id)).toList();
}
int? _validSelected(int? id, List<dynamic> list) {
if (id == null) return null;
final ids = list.map((e) => e.id as int).toSet();
return ids.contains(id) ? id : null;
}
List<OrgEntity> _ensureOrgInList(List<OrgEntity> orgs, int orgId) {
if (orgs.any((e) => e.id == orgId)) return orgs;
return [...orgs, OrgEntity(id: orgId, name: '组织 #$orgId')];
}
List<SiteEntity> _ensureSiteInList(List<SiteEntity> sites, int? siteId) {
if (siteId == null) return sites;
if (sites.any((e) => e.id == siteId)) return sites;
return [...sites, SiteEntity(id: siteId, name: '场站 #$siteId')];
}
List<UserSimpleEntity> _ensureUserInList(
List<UserSimpleEntity> users,
UserEntity user,
) {
final uid = int.tryParse(user.userId) ?? 0;
if (users.any((e) => e.id == uid)) return users;
return [...users, UserSimpleEntity(id: uid, name: user.nickname)];
}
/// 按角色初始化。
///
/// - 转交(绑定):需要加载组织/场站/负责人三级列表;
/// - 解绑:不需要任何列表 —— 只选「个人 / 场站 / 组织」一级,
/// 而这一级由角色决定上限,所以直接定好默认值就能用。
Future<void> init({required OwnershipAction action}) async {
final user = _currentUser;
if (user == null) {
debugPrint(
'>>> [OwnershipAction] ERROR: _currentUser is null,无法加载归属层级',
);
return;
}
debugPrint(
'>>> [OwnershipAction] action=$action roleKey=${user.roleKey}, '
'orgId=${user.orgId}, siteId=${user.siteId}, userId=${user.userId}',
);
emit(
state.copyWith(
action: action,
isLoading: true,
roleKey: user.roleKey ?? 'user',
// 解绑默认选最轻的一级(个人),不预设更彻底的清除
selectedScope: UnbindScope.user,
),
);
// 解绑不依赖三级列表,直接结束 loading
if (action == OwnershipAction.unbind) {
debugPrint(
'>>> [OwnershipAction] 解绑模式:roleMax=${roleMaxScope.value}'
'(${roleMaxScope.label}),跳过组织/场站/人员加载',
);
emit(state.copyWith(isLoading: false));
return;
}
switch (roleKey) {
case 'admin':
await _loadAllOrgs();
break;
case 'manager':
await _loadForManager(user);
break;
case 'siteManager':
await _loadForSiteManager(user);
break;
default:
await _loadForUser(user);
}
emit(state.copyWith(isLoading: false));
}
/// 解绑:直接选清除层级(个人 / 场站 / 组织)。
/// 超出当前角色上限的层级不响应,UI 也会置灰。
void onScopeSelected(UnbindScope scope) {
if (scope.value > roleMaxScope.value) {
debugPrint(
'>>> [OwnershipAction] 拦截越权清除:picked=${scope.value} '
'roleMax=${roleMaxScope.value}',
);
return;
}
emit(state.copyWith(selectedScope: scope, clearError: true));
debugPrint(
'>>> [OwnershipAction] 清除层级选中 scope=${scope.value}(${scope.label})',
);
}
Future<void> _loadAllOrgs() async {
final result = await _getOrgListUseCase();
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(orgs) {
final unique = _uniqueOrgs(orgs);
emit(
state.copyWith(
orgList: unique,
selectedOrgId: _validSelected(state.selectedOrgId, unique),
),
);
},
);
}
Future<void> _loadForManager(UserEntity user) async {
final result = await _getOrgListUseCase();
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(orgs) async {
final unique = _ensureOrgInList(_uniqueOrgs(orgs), user.orgId);
emit(state.copyWith(orgList: unique, selectedOrgId: user.orgId));
await _loadSitesByOrgForManager(user.orgId, user.siteId);
},
);
}
Future<void> _loadForSiteManager(UserEntity user) async {
final result = await _getOrgListUseCase();
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(orgs) async {
final unique = _ensureOrgInList(_uniqueOrgs(orgs), user.orgId);
emit(state.copyWith(orgList: unique, selectedOrgId: user.orgId));
await _loadSitesAndUsers(user);
},
);
}
Future<void> _loadForUser(UserEntity user) async {
final result = await _getOrgListUseCase();
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(orgs) async {
final unique = _ensureOrgInList(_uniqueOrgs(orgs), user.orgId);
emit(state.copyWith(orgList: unique, selectedOrgId: user.orgId));
await _loadSitesAndUsers(user);
},
);
}
Future<void> _loadSitesByOrgForManager(int orgId, int? siteId) async {
final result = await _getSitesByOrgUseCase(orgId);
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(sites) {
final unique = _ensureSiteInList(_uniqueSites(sites), siteId);
emit(
state.copyWith(
siteList: unique,
selectedSiteId: siteId,
clearSite: siteId == null,
clearUser: true,
),
);
},
);
}
Future<void> _loadSitesAndUsers(UserEntity user) async {
final sitesResult = await _getSitesByOrgUseCase(user.orgId);
sitesResult.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(sites) async {
final unique = _ensureSiteInList(_uniqueSites(sites), user.siteId);
emit(state.copyWith(siteList: unique, selectedSiteId: user.siteId));
if (user.siteId != null) {
await _loadUsers(user);
} else {
final currentUser = UserSimpleEntity(
id: int.tryParse(user.userId) ?? 0,
name: user.nickname,
);
emit(
state.copyWith(
userList: [currentUser],
selectedUserId: currentUser.id,
),
);
}
},
);
}
Future<void> _loadUsers(UserEntity user) async {
final result = await _getUsersBySiteUseCase(user.siteId!);
final currentUser = UserSimpleEntity(
id: int.tryParse(user.userId) ?? 0,
name: user.nickname,
);
result.fold(
(failure) {
emit(
state.copyWith(
userList: _ensureUserInList([], user),
selectedUserId: currentUser.id,
),
);
},
(users) {
emit(
state.copyWith(
userList: _ensureUserInList(_uniqueUsers(users), user),
selectedUserId: currentUser.id,
),
);
},
);
}
/// 换组织:清空场站与负责人,重新拉场站
Future<void> onOrgChanged(int orgId) async {
emit(
state.copyWith(
selectedOrgId: orgId,
siteList: const [],
userList: const [],
clearSite: true,
clearUser: true,
clearError: true,
),
);
final result = await _getSitesByOrgUseCase(orgId);
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(sites) => emit(state.copyWith(siteList: _uniqueSites(sites))),
);
}
/// 换场站:清空负责人,重新拉人员;[siteId] 传 null 表示不限定场站
Future<void> onSiteChanged(int? siteId) async {
emit(
state.copyWith(
selectedSiteId: siteId,
clearSite: siteId == null,
userList: const [],
clearUser: true,
clearError: true,
),
);
if (siteId == null) return;
final result = await _getUsersBySiteUseCase(siteId);
result.fold(
(failure) => emit(state.copyWith(errorMessage: failure.message)),
(users) => emit(state.copyWith(userList: _uniqueUsers(users))),
);
}
void onUserChanged(int? userId) {
emit(
state.copyWith(
selectedUserId: userId,
clearUser: userId == null,
clearError: true,
),
);
}
/// 清空已消费的错误提示,避免 BlocListener 重复弹出
void clearError() {
if (state.errorMessage == null) return;
emit(state.copyWith(clearError: true));
}
/// 记录扫码值,并返回它与当前设备是否一致。
///
/// 二维码里可能是纯编码、带前缀的 URL 或一串文本,所以做宽松匹配:
/// 归一化(去空白 + 大写)后只要有一方包含另一方就算同一台设备。
bool recordScan({
required String scanned,
required String deviceCode,
required String deviceId,
}) {
final code = scanned.trim();
emit(state.copyWith(scannedValue: code));
final normalized = code.replaceAll(RegExp(r'\s'), '').toUpperCase();
if (normalized.isEmpty) return false;
final candidates = [deviceCode, deviceId]
.map((e) => e.replaceAll(RegExp(r'\s'), '').toUpperCase())
.where((e) => e.isNotEmpty);
final matched = candidates.any(
(e) => normalized == e || normalized.contains(e) || e.contains(normalized),
);
debugPrint(
'>>> [OwnershipAction] 扫码核验 scanned=$code deviceCode=$deviceCode '
'deviceId=$deviceId matched=$matched',
);
return matched;
}
/// 提交归属操作,按 [DeviceOwnershipActionState.isTransfer] 分流。
///
/// [deviceIds] 由页面决定(当前设备编码,MC700- 开头)。
Future<bool> submit({required List<String> deviceIds}) {
return state.isTransfer
? _submitTransfer(deviceIds)
: _submitUnbind(deviceIds);
}
/// 转交设备 = 绑定接口:把设备挂到选定的组织/场站/负责人下。
/// 校验口径与绑定页保持一致,不在这里额外加规则。
Future<bool> _submitTransfer(List<String> deviceIds) async {
final orgId = state.selectedOrgId;
debugPrint(
'>>> [OwnershipAction] transfer 入参 deviceIds=$deviceIds orgId=$orgId '
'siteId=${state.selectedSiteId} userId=${state.selectedUserId} '
'roleKey=$roleKey',
);
if (orgId == null || orgId <= 0) {
debugPrint('>>> [OwnershipAction] 前置拦截:组织为空,未发请求');
emit(state.copyWith(errorMessage: '请选择所属组织'));
return false;
}
// 转交只开放给「普通用户以上」的角色;普通用户 / 个人角色只能选自己,
// 入口已在归属页隐藏,这里再做一道兜底。
// 负责人不强制:只挂到组织或场站也是合法挂靠(与绑定页口径一致)。
if (!isUserEnabled) {
debugPrint('>>> [OwnershipAction] 前置拦截:$roleKey 无转交权限');
emit(state.copyWith(errorMessage: '当前角色无转交设备的权限'));
return false;
}
emit(state.copyWith(isSubmitting: true, clearError: true));
final result = await _bindDeviceUseCase(
deviceIds: deviceIds,
orgId: orgId,
siteId: state.selectedSiteId,
userId: state.selectedUserId,
);
return result.fold(
(failure) {
debugPrint('>>> [OwnershipAction] ❌ 转交失败 ${failure.message}');
emit(
state.copyWith(isSubmitting: false, errorMessage: failure.message),
);
return false;
},
(_) {
debugPrint('>>> [OwnershipAction] ✅ 转交成功');
emit(
state.copyWith(
isSubmitting: false,
isSuccess: true,
clearError: true,
),
);
return true;
},
);
}
/// 解绑设备 = 解绑接口。
///
/// 交互与绑定无关:用户只选「个人 / 场站 / 组织」一级,
/// 下发只有 deviceIds + type(见 [UnbindScope]),不需要组织/场站/负责人 ID。
Future<bool> _submitUnbind(List<String> deviceIds) async {
// 下发时一律用角色钳制后的范围,避免前端被改出越权 type
final scope = effectiveScope;
debugPrint(
'>>> [OwnershipAction] unbind 入参 deviceIds=$deviceIds '
'scope=${scope.value}(${scope.label}) roleKey=$roleKey '
'roleMax=${roleMaxScope.value}',
);
emit(state.copyWith(isSubmitting: true, clearError: true));
final result = await _unbindDeviceUseCase(
deviceIds: deviceIds,
scope: scope,
);
return result.fold(
(failure) {
debugPrint('>>> [OwnershipAction] ❌ 解绑失败 ${failure.message}');
emit(
state.copyWith(isSubmitting: false, errorMessage: failure.message),
);
return false;
},
(_) {
debugPrint('>>> [OwnershipAction] ✅ 解绑成功');
emit(
state.copyWith(
isSubmitting: false,
isSuccess: true,
clearError: true,
),
);
return true;
},
);
}
}

View File

@@ -0,0 +1,139 @@
import 'package:equatable/equatable.dart';
import '../../domain/entities/bind_device_entities.dart';
/// 设备归属操作页状态。
///
/// 转交与解绑共用一份状态,但交互完全不同:
/// - 转交(绑定):逐级选组织 → 场站 → 负责人([orgList] / [siteList] / [userList]);
/// - 解绑:不选具体对象,只选清除到哪一级([selectedScope],对应后端 type 1/2/3)。
class DeviceOwnershipActionState extends Equatable {
final OwnershipAction action;
/// 转交用:三级选择列表
final List<OrgEntity> orgList;
final List<SiteEntity> siteList;
final List<UserSimpleEntity> userList;
final int? selectedOrgId;
final int? selectedSiteId;
final int? selectedUserId;
/// 解绑用:用户选中的清除层级(个人 / 场站 / 组织)
final UnbindScope selectedScope;
final String roleKey;
final bool isLoading;
final bool isSubmitting;
final String? errorMessage;
final bool isSuccess;
/// 扫码得到的原始值;null 表示还没扫码(或扫码页被跳过)
final String? scannedValue;
const DeviceOwnershipActionState({
this.action = OwnershipAction.unbind,
this.orgList = const [],
this.siteList = const [],
this.userList = const [],
this.selectedOrgId,
this.selectedSiteId,
this.selectedUserId,
this.selectedScope = UnbindScope.user,
this.roleKey = 'user',
this.isLoading = false,
this.isSubmitting = false,
this.errorMessage,
this.isSuccess = false,
this.scannedValue,
});
bool get isTransfer => action == OwnershipAction.transfer;
/// 解绑直接返回用户选中的层级;转交按「选到哪一级」由下级往上推导,
/// 仅供结果提示条展示。
UnbindScope get scopePreview {
if (!isTransfer) return selectedScope;
final uid = selectedUserId;
if (uid != null && uid > 0) return UnbindScope.user;
final sid = selectedSiteId;
if (sid != null && sid > 0) return UnbindScope.site;
return UnbindScope.org;
}
/// 截止到 [scope] 的归属链路,用于提示条:
/// 解绑时只展示会被清除的层级,转交时展示要挂靠的完整链路。
String pathTextUpTo(UnbindScope scope) {
final orgName = orgList
.where((e) => e.id == selectedOrgId)
.fold<String?>(null, (_, e) => e.name);
final siteName = scope.value >= UnbindScope.site.value
? siteList.where((e) => e.id == selectedSiteId).fold<String?>(null, (
_,
e,
) => e.name)
: null;
final userName = scope.value >= UnbindScope.user.value
? userList.where((e) => e.id == selectedUserId).fold<String?>(null, (
_,
e,
) => e.name)
: null;
return [?orgName, ?siteName, ?userName].join(' / ');
}
DeviceOwnershipActionState copyWith({
OwnershipAction? action,
List<OrgEntity>? orgList,
List<SiteEntity>? siteList,
List<UserSimpleEntity>? userList,
int? selectedOrgId,
int? selectedSiteId,
int? selectedUserId,
UnbindScope? selectedScope,
String? roleKey,
bool? isLoading,
bool? isSubmitting,
String? errorMessage,
bool? isSuccess,
String? scannedValue,
bool clearSite = false,
bool clearUser = false,
bool clearError = false,
}) {
return DeviceOwnershipActionState(
action: action ?? this.action,
orgList: orgList ?? this.orgList,
siteList: siteList ?? this.siteList,
userList: userList ?? this.userList,
selectedOrgId: selectedOrgId ?? this.selectedOrgId,
// 换组织/换场站时必须能真正清空下级,不能用 ?? 保留旧值
selectedSiteId: clearSite ? null : (selectedSiteId ?? this.selectedSiteId),
selectedUserId: clearUser ? null : (selectedUserId ?? this.selectedUserId),
selectedScope: selectedScope ?? this.selectedScope,
roleKey: roleKey ?? this.roleKey,
isLoading: isLoading ?? this.isLoading,
isSubmitting: isSubmitting ?? this.isSubmitting,
errorMessage: clearError ? null : (errorMessage ?? this.errorMessage),
isSuccess: isSuccess ?? this.isSuccess,
scannedValue: scannedValue ?? this.scannedValue,
);
}
@override
List<Object?> get props => [
action,
orgList,
siteList,
userList,
selectedOrgId,
selectedSiteId,
selectedUserId,
selectedScope,
roleKey,
isLoading,
isSubmitting,
errorMessage,
isSuccess,
scannedValue,
];
}