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 groupDataList = [].obs; LockListInfoGroupEntity? entity; final ShowTipView showTipView = ShowTipView(); List get groupDataListFiltered { final List 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 _replySubscription; late StreamSubscription _setLockListInfoGroupEntity; void _initReplySubscription() { _replySubscription = EventBusManager().eventBus!.on().listen((Reply reply) async { // 恢复出厂设置 if ((reply is FactoryDataResetReply)) { _replyFactoryDataResetKey(reply); } }); } Future _replyFactoryDataResetKey(Reply reply) async { final List token = reply.data.sublist(2, 6); final List 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 tokenData = reply.data.sublist(2, 6); final List 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 keyTypes = [XSConstantMacro.keyTypeTime, XSConstantMacro.keyTypeOnce, XSConstantMacro.keyTypeLoop]; final List keyStatus = [ 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 checkLoginPassword(LockListInfoItemEntity keyInfo) async { final LockListInfoEntity entity = await ApiRepository.to.checkLoginPassword( password: state.passwordTF.text, ); if (entity.errorCode!.codeIsSuccessful) { Get.back(); factoryDataResetAction(keyInfo); } } // 当是锁拥有者的时候,删除锁 Future 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 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 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 publicKeyData = state.lockListInfoItemEntity.value.bluetooth!.publicKey!.cast(); final List saveStrList = changeIntListToStringList(publicKeyData); await Storage.setStringList(saveBluePublicKey, saveStrList); // 私钥 final List privateKeyData = state.lockListInfoItemEntity.value.bluetooth!.privateKey!.cast(); final List savePrivateKeyList = changeIntListToStringList(privateKeyData); await Storage.setStringList(saveBluePrivateKey, savePrivateKeyList); // signKey final List signKeyData = state.lockListInfoItemEntity.value.bluetooth!.signKey!.cast(); final List saveSignKeyList = changeIntListToStringList(signKeyData); await Storage.setStringList(saveBlueSignKey, saveSignKeyList); final List saveTokenList = changeIntListToStringList([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: [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: [ 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().listen((SetLockListInfoGroupEntity event) async { setLockListInfoGroupEntity(event.lockListInfoGroupEntity); }); } }