app-starlock/lib/main/lockMian/lockList/lockList_logic.dart
2025-10-27 09:27:37 +08:00

337 lines
13 KiB
Dart
Executable File

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:star_lock/app_settings/app_settings.dart';
import 'package:star_lock/talk/starChart/star_chart_manage.dart';
import 'package:star_lock/tools/baseGetXController.dart';
import '../../../blue/blue_manage.dart';
import '../../../blue/io_protocol/io_factoryDataReset.dart';
import '../../../blue/io_reply.dart';
import '../../../blue/io_tool/io_tool.dart';
import '../../../blue/io_tool/manager_event_bus.dart';
import '../../../blue/sender_manage.dart';
import '../../../common/XSConstantMacro/XSConstantMacro.dart';
import '../../../network/api_repository.dart';
import '../../../tools/dateTool.dart';
import '../../../tools/eventBusEventManage.dart';
import '../../../tools/showTipView.dart';
import '../../../tools/storage.dart';
import '../entity/lockListInfo_entity.dart';
import 'lockList_state.dart';
class LockListLogic extends BaseGetXController {
LockListLogic(this.entity) {}
LockListState state = LockListState();
final RxList<GroupList> groupDataList = <GroupList>[].obs;
LockListInfoGroupEntity? entity;
final ShowTipView showTipView = ShowTipView();
List<GroupList> get groupDataListFiltered {
final List<GroupList> list = groupDataList.map((GroupList e) => e.copy()).toList();
if (state.searchStr.value != '' && state.showSearch.value) {
list.forEach((GroupList element) {
element.lockList?.removeWhere((LockListInfoItemEntity element) => !(element.lockAlias?.contains(state.searchStr.value) ?? true));
});
}
if (list.length > 0) {
StartChartManage().lockListPeerId.clear();
list.forEach((element) {
final lockList = element.lockList;
if (lockList != null && lockList.length > 0) {
lockList.forEach((element) {
if (element.network?.peerId != null && element.network?.peerId != '') {
StartChartManage().lockListPeerId.add(element);
}
});
}
});
}
return list;
}
//设置数据
void setLockListInfoGroupEntity(LockListInfoGroupEntity entity) {
this.entity = entity;
groupDataList.value = entity.groupList!;
}
// 监听蓝牙协议返回结果
late StreamSubscription<Reply> _replySubscription;
late StreamSubscription _setLockListInfoGroupEntity;
void _initReplySubscription() {
_replySubscription = EventBusManager().eventBus!.on<Reply>().listen((Reply reply) async {
// 恢复出厂设置
if ((reply is FactoryDataResetReply)) {
_replyFactoryDataResetKey(reply);
}
});
}
Future<void> _replyFactoryDataResetKey(Reply reply) async {
final List<int> token = reply.data.sublist(2, 6);
final List<String> saveStrList = changeIntListToStringList(token);
Storage.setStringList(saveBlueToken, saveStrList);
final int status = reply.data[6];
switch (status) {
case 0x00:
//成功
dismissEasyLoading();
cancelBlueConnetctToastTimer();
deletLockInfoData();
break;
case 0x06:
//无权限
final List<int> tokenData = reply.data.sublist(2, 6);
final List<String> saveStrList = changeIntListToStringList(tokenData);
Storage.setStringList(saveBlueToken, saveStrList);
IoSenderManage.senderFactoryDataReset(
lockID: BlueManage().connectDeviceName,
userID: await Storage.getUid(),
keyID: '1',
needAuthor: 1,
publicKey: state.publicKey,
privateKey: state.privateKey,
token: tokenData,
);
break;
case 0x07:
//无权限
dismissEasyLoading();
showToast('用户无权限'.tr);
break;
case 0x09:
// 权限校验错误
dismissEasyLoading();
// showToast("权限校验错误");
break;
default:
//失败
dismissEasyLoading();
// showToast("权限校验错误");
break;
}
}
String showElectricIcon(int electricnumber) {
if (electricnumber >= 100) {
return 'images/main/icon_lockElectricLevel_5.png';
} else if ((electricnumber > 50) && (electricnumber < 100)) {
return 'images/main/icon_lockElectricLevel_4.png';
} else if ((electricnumber > 25) && (electricnumber <= 50)) {
return 'images/main/icon_lockElectricLevel_3.png';
} else if ((electricnumber > 5) && (electricnumber <= 25)) {
return 'images/main/icon_lockElectricLevel_2.png';
} else if (electricnumber <= 5) {
return 'images/main/icon_lockElectricLevel_1.png';
}
return 'images/main/icon_lockElectricLevel_5.png';
}
String getKeyEffective(LockListInfoItemEntity keyInfo) {
// 当是限时、循环的时候
if (keyInfo.keyType == XSConstantMacro.keyTypeTime ||
keyInfo.keyType == XSConstantMacro.keyTypeLong ||
keyInfo.keyType == XSConstantMacro.keyTypeLoop) {
// 当是正常使用跟待接收状态的时候
if (keyInfo.keyStatus == XSConstantMacro.keyStatusNormalUse || keyInfo.keyStatus == XSConstantMacro.keyStatusWaitReceive) {
return "${"".tr}${DateTool().compareTimeGetDaysFromNow(keyInfo.endDate!)}${"".tr}";
} else {
return XSConstantMacro.getKeyStatusStr(keyInfo.keyStatus!);
}
} else if (keyInfo.keyType == XSConstantMacro.keyTypeOnce) {
return XSConstantMacro.getKeyStatusStr(keyInfo.keyStatus!);
}
return '';
}
//判断是否要显示提示
bool getShowType(LockListInfoItemEntity keyInfo) {
final List<int> keyTypes = <int>[XSConstantMacro.keyTypeTime, XSConstantMacro.keyTypeOnce, XSConstantMacro.keyTypeLoop];
final List<int> keyStatus = <int>[
XSConstantMacro.keyStatusWaitIneffective,
XSConstantMacro.keyStatusFrozen,
XSConstantMacro.keyStatusExpired,
];
//新增以上组合未包含--永久&&冻结状态 显示
final bool isLongFrozenStatus = keyInfo.keyType == XSConstantMacro.keyTypeLong && keyInfo.keyStatus == XSConstantMacro.keyStatusFrozen;
final DateTime endDate = DateTime.fromMillisecondsSinceEpoch(keyInfo.endDate ?? 0);
final DateTime now = DateTime.now();
final bool isKeyType = keyTypes.contains(keyInfo.keyType);
final bool isKeyStatus = keyStatus.contains(keyInfo.keyStatus);
final Duration difference = endDate.difference(now);
final bool isExpirationSoon = isKeyType && difference.inDays <= 15;
final bool isShow = isKeyType && isKeyStatus || isExpirationSoon || isLongFrozenStatus;
return isShow;
}
/// 以下为删除逻辑
void deleyLockLogicOfRoles(LockListInfoItemEntity keyInfo) {
if (state.lockListInfoItemEntity.value.isLockOwner == 1) {
// 超级管理员必须通过连接蓝牙删除
showTipView.showIosTipWithContentDialog('删除锁后,所有信息都会一起删除,确定删除锁吗?'.tr, () {
// 删除锁
AppLog.log('调用了删除锁');
showTipView.resetGetController();
showTipView.showTFViewAlertDialog(state.passwordTF, '请输入登录密码'.tr, '请输入登录密码'.tr, () => checkLoginPassword(keyInfo));
});
} else if (state.lockListInfoItemEntity.value.keyRight == 1) {
// 授权管理员弹框提示
showTipView.showDeleteAdministratorIsHaveAllDataDialog('同时删除其发送的所有钥匙,钥匙删除后不能恢复'.tr, (bool a) {
// 授权管理员删除
state.deleteAdministratorIsHaveAllData.value = a;
deletKeyData();
});
} else {
// 普通用户直接删除
showTipView.showIosTipWithContentDialog('是否删除钥匙?'.tr, deletKeyData);
}
}
// 查询账户密码
Future<void> checkLoginPassword(LockListInfoItemEntity keyInfo) async {
final LockListInfoEntity entity = await ApiRepository.to.checkLoginPassword(
password: state.passwordTF.text,
);
if (entity.errorCode!.codeIsSuccessful) {
Get.back();
factoryDataResetAction(keyInfo);
}
}
// 当是锁拥有者的时候,删除锁
Future<void> deletLockInfoData() async {
final LockListInfoEntity entity = await ApiRepository.to.deletOwnerLockData(
lockId: state.lockListInfoItemEntity.value.lockId!,
);
if (entity.errorCode!.codeIsSuccessful) {
BlueManage().connectDeviceMacAddress = '';
SchedulerBinding.instance.addPostFrameCallback((_) {
eventBus.fire(RefreshLockListInfoDataEvent());
});
}
}
// 普通用户或者授权管理员删除钥匙
Future<void> deletKeyData() async {
final LockListInfoEntity entity = await ApiRepository.to.deletOwnerKeyData(
lockId: state.lockListInfoItemEntity.value.lockId.toString(),
keyId: state.lockListInfoItemEntity.value.keyId.toString(),
includeUnderlings: state.deleteAdministratorIsHaveAllData.value == true ? 1 : 0);
if (entity.errorCode!.codeIsSuccessful) {
BlueManage().connectDeviceMacAddress = '';
SchedulerBinding.instance.addPostFrameCallback((_) {
eventBus.fire(RefreshLockListInfoDataEvent());
});
}
}
// 恢复出厂设置
Future<void> factoryDataResetAction(LockListInfoItemEntity keyInfo) async {
showEasyLoading();
showBlueConnetctToastTimer(
isShowBlueConnetctToast: false,
action: () {
dismissEasyLoading();
showDeletAlertTipDialog();
});
BlueManage().blueSendData(state.lockListInfoItemEntity.value.lockName!, (BluetoothConnectionState connectionState) async {
if (connectionState == BluetoothConnectionState.connected) {
final List<int> publicKeyData = state.lockListInfoItemEntity.value.bluetooth!.publicKey!.cast<int>();
final List<String> saveStrList = changeIntListToStringList(publicKeyData);
await Storage.setStringList(saveBluePublicKey, saveStrList);
// 私钥
final List<int> privateKeyData = state.lockListInfoItemEntity.value.bluetooth!.privateKey!.cast<int>();
final List<String> savePrivateKeyList = changeIntListToStringList(privateKeyData);
await Storage.setStringList(saveBluePrivateKey, savePrivateKeyList);
// signKey
final List<int> signKeyData = state.lockListInfoItemEntity.value.bluetooth!.signKey!.cast<int>();
final List<String> saveSignKeyList = changeIntListToStringList(signKeyData);
await Storage.setStringList(saveBlueSignKey, saveSignKeyList);
final List<String> saveTokenList = changeIntListToStringList(<int>[0, 0, 0, 0]);
await Storage.setStringList(saveBlueToken, saveTokenList);
IoSenderManage.senderFactoryDataReset(
lockID: BlueManage().connectDeviceName,
userID: await Storage.getUid(),
keyID: '1',
needAuthor: 1,
publicKey: keyInfo.bluetooth?.publicKey ?? [],
privateKey: keyInfo.bluetooth?.privateKey ?? [],
token: <int>[0, 0, 0, 0]);
state.publicKey.value = keyInfo.bluetooth?.publicKey ?? [];
state.privateKey.value = keyInfo.bluetooth?.privateKey ?? [];
state.publicKey.refresh();
state.privateKey.refresh();
} else if (connectionState == BluetoothConnectionState.disconnected) {
dismissEasyLoading();
cancelBlueConnetctToastTimer();
if (state.ifCurrentScreen.value == true) {
showDeletAlertTipDialog();
}
}
});
}
void showDeletAlertTipDialog({String? showContent = ''}) {
// bool isContains = BlueManage().connectDeviceName!.contains("T9A");
final String content = showContent!.isEmpty
? "${"删除设备失败,请确保在设备附近,设备未被连接,设备已打开".tr}${BlueManage().connectDeviceName.contains("T9A") == true ? "如果是全自动锁,请使屏幕变亮".tr : ""}"
: showContent;
showCupertinoDialog(
context: Get.context!,
builder: (BuildContext context) {
return CupertinoAlertDialog(
title: Text('提示'.tr),
content: Text(content),
actions: <Widget>[
CupertinoDialogAction(
child: Text('确定'.tr),
onPressed: Get.back,
),
],
);
},
);
}
@override
void onReady() {
super.onReady();
_initReplySubscription();
_initEventHandler();
}
@override
void onInit() {
super.onInit();
AppLog.log('[onInit] entity: \\${entity?.toString()}');
if (entity != null) {
setLockListInfoGroupEntity(entity!);
}
_initEventHandler();
}
@override
void onClose() {
_replySubscription.cancel();
_setLockListInfoGroupEntity.cancel();
}
void _initEventHandler() {
_setLockListInfoGroupEntity = eventBus.on<SetLockListInfoGroupEntity>().listen((SetLockListInfoGroupEntity event) async {
setLockListInfoGroupEntity(event.lockListInfoGroupEntity);
});
}
}