mirror of
https://github.com/SyncrowIOT/web.git
synced 2025-07-09 22:57:21 +00:00
596 lines
19 KiB
Dart
596 lines
19 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:bloc/bloc.dart';
|
|
import 'package:equatable/equatable.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:syncrow_web/pages/routiens/models/create_scene_and_autoamtion/create_automation_model.dart';
|
|
import 'package:syncrow_web/pages/routiens/models/create_scene_and_autoamtion/create_scene_model.dart';
|
|
import 'package:syncrow_web/pages/routiens/models/device_functions.dart';
|
|
import 'package:syncrow_web/pages/routiens/models/routine_details_model.dart';
|
|
import 'package:syncrow_web/pages/routiens/models/routine_model.dart';
|
|
import 'package:syncrow_web/services/routines_api.dart';
|
|
|
|
part 'routine_event.dart';
|
|
part 'routine_state.dart';
|
|
|
|
const spaceId = '25c96044-fadf-44bb-93c7-3c079e527ce6';
|
|
const communityId = 'aff21a57-2f91-4e5c-b99b-0182c3ab65a9';
|
|
|
|
class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
|
|
RoutineBloc() : super(const RoutineState()) {
|
|
on<AddToIfContainer>(_onAddToIfContainer);
|
|
on<AddToThenContainer>(_onAddToThenContainer);
|
|
on<LoadScenes>(_onLoadScenes);
|
|
on<LoadAutomation>(_onLoadAutomation);
|
|
on<AddFunctionToRoutine>(_onAddFunctionsToRoutine);
|
|
on<SearchRoutines>(_onSearchRoutines);
|
|
on<AddSelectedIcon>(_onAddSelectedIcon);
|
|
on<CreateSceneEvent>(_onCreateScene);
|
|
on<RemoveDragCard>(_onRemoveDragCard);
|
|
on<ChangeAutomationOperator>(_changeOperatorOperator);
|
|
on<EffectiveTimePeriodEvent>(_onEffectiveTimeEvent);
|
|
on<CreateAutomationEvent>(_onCreateAutomation);
|
|
on<SetRoutineName>(_onSetRoutineName);
|
|
on<ResetRoutineState>(_onResetRoutineState);
|
|
on<GetSceneDetails>(_onGetSceneDetails);
|
|
on<GetAutomationDetails>(_onGetAutomationDetails);
|
|
// on<InitializeRoutineState>(_onInitializeRoutineState);
|
|
on<DeleteScene>(_deleteScene);
|
|
on<DeleteAutomation>(_deleteAutomation);
|
|
// on<RemoveFunction>(_onRemoveFunction);
|
|
// on<ClearFunctions>(_onClearFunctions);
|
|
}
|
|
|
|
void _onAddToIfContainer(AddToIfContainer event, Emitter<RoutineState> emit) {
|
|
final updatedIfItems = List<Map<String, dynamic>>.from(state.ifItems);
|
|
|
|
// Find the index of the item in teh current itemsList
|
|
int index = updatedIfItems.indexWhere(
|
|
(map) => map['uniqueCustomId'] == event.item['uniqueCustomId']);
|
|
// Replace the map if the index is valid
|
|
if (index != -1) {
|
|
updatedIfItems[index] = event.item;
|
|
} else {
|
|
updatedIfItems.add(event.item);
|
|
}
|
|
|
|
if (event.isTabToRun) {
|
|
emit(state.copyWith(
|
|
ifItems: updatedIfItems, isTabToRun: true, isAutomation: false));
|
|
} else {
|
|
emit(state.copyWith(
|
|
ifItems: updatedIfItems, isTabToRun: false, isAutomation: true));
|
|
}
|
|
}
|
|
|
|
void _onAddToThenContainer(
|
|
AddToThenContainer event, Emitter<RoutineState> emit) {
|
|
final currentItems = List<Map<String, dynamic>>.from(state.thenItems);
|
|
|
|
// Find the index of the item in teh current itemsList
|
|
int index = currentItems.indexWhere(
|
|
(map) => map['uniqueCustomId'] == event.item['uniqueCustomId']);
|
|
// Replace the map if the index is valid
|
|
if (index != -1) {
|
|
currentItems[index] = event.item;
|
|
} else {
|
|
currentItems.add(event.item);
|
|
}
|
|
|
|
emit(state.copyWith(thenItems: currentItems));
|
|
}
|
|
|
|
void _onAddFunctionsToRoutine(
|
|
AddFunctionToRoutine event, Emitter<RoutineState> emit) {
|
|
try {
|
|
if (event.functions.isEmpty) return;
|
|
|
|
List<DeviceFunctionData> selectedFunction =
|
|
List<DeviceFunctionData>.from(event.functions);
|
|
|
|
Map<String, List<DeviceFunctionData>> currentSelectedFunctions =
|
|
Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions);
|
|
if (currentSelectedFunctions.containsKey(event.uniqueCustomId)) {
|
|
List<DeviceFunctionData> currentFunctions =
|
|
List<DeviceFunctionData>.from(
|
|
currentSelectedFunctions[event.uniqueCustomId] ?? []);
|
|
|
|
List<String> functionCode = [];
|
|
for (int i = 0; i < selectedFunction.length; i++) {
|
|
for (int j = 0; j < currentFunctions.length; j++) {
|
|
if (selectedFunction[i].functionCode ==
|
|
currentFunctions[j].functionCode) {
|
|
currentFunctions[j] = selectedFunction[i];
|
|
if (!functionCode.contains(currentFunctions[j].functionCode)) {
|
|
functionCode.add(currentFunctions[j].functionCode);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (int i = 0; i < functionCode.length; i++) {
|
|
selectedFunction
|
|
.removeWhere((code) => code.functionCode == functionCode[i]);
|
|
}
|
|
|
|
currentSelectedFunctions[event.uniqueCustomId] =
|
|
List.from(currentFunctions)..addAll(selectedFunction);
|
|
} else {
|
|
currentSelectedFunctions[event.uniqueCustomId] =
|
|
List.from(event.functions);
|
|
}
|
|
|
|
emit(state.copyWith(selectedFunctions: currentSelectedFunctions));
|
|
} catch (e) {
|
|
debugPrint('Error adding functions: $e');
|
|
}
|
|
}
|
|
|
|
Future<void> _onLoadScenes(
|
|
LoadScenes event, Emitter<RoutineState> emit) async {
|
|
emit(state.copyWith(isLoading: true, errorMessage: null));
|
|
|
|
try {
|
|
final scenes =
|
|
await SceneApi.getScenesByUnitId(event.unitId, event.communityId);
|
|
emit(state.copyWith(
|
|
scenes: scenes,
|
|
isLoading: false,
|
|
));
|
|
} catch (e) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
loadScenesErrorMessage: 'Failed to load scenes',
|
|
errorMessage: '',
|
|
loadAutomationErrorMessage: '',
|
|
));
|
|
}
|
|
}
|
|
|
|
Future<void> _onLoadAutomation(
|
|
LoadAutomation event, Emitter<RoutineState> emit) async {
|
|
emit(state.copyWith(isLoading: true, errorMessage: null));
|
|
|
|
try {
|
|
final automations = await SceneApi.getAutomationByUnitId(event.unitId);
|
|
if (automations.isNotEmpty) {
|
|
emit(state.copyWith(
|
|
automations: automations,
|
|
isLoading: false,
|
|
));
|
|
} else {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
loadAutomationErrorMessage: 'Failed to load automations',
|
|
errorMessage: '',
|
|
loadScenesErrorMessage: '',
|
|
));
|
|
}
|
|
} catch (e) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
loadAutomationErrorMessage: 'Failed to load automations',
|
|
errorMessage: '',
|
|
loadScenesErrorMessage: '',
|
|
));
|
|
}
|
|
}
|
|
|
|
FutureOr<void> _onSearchRoutines(
|
|
SearchRoutines event, Emitter<RoutineState> emit) async {
|
|
emit(state.copyWith(isLoading: true, errorMessage: null));
|
|
await Future.delayed(const Duration(seconds: 1));
|
|
emit(state.copyWith(isLoading: false, errorMessage: null));
|
|
emit(state.copyWith(searchText: event.query));
|
|
}
|
|
|
|
FutureOr<void> _onAddSelectedIcon(
|
|
AddSelectedIcon event, Emitter<RoutineState> emit) {
|
|
emit(state.copyWith(selectedIcon: event.icon));
|
|
}
|
|
|
|
bool _isFirstActionDelay(List<Map<String, dynamic>> actions) {
|
|
if (actions.isEmpty) return false;
|
|
return actions.first['deviceId'] == 'delay';
|
|
}
|
|
|
|
Future<void> _onCreateScene(
|
|
CreateSceneEvent event, Emitter<RoutineState> emit) async {
|
|
try {
|
|
// Check if first action is delay
|
|
if (_isFirstActionDelay(state.thenItems)) {
|
|
emit(state.copyWith(
|
|
errorMessage: 'Cannot have delay as the first action',
|
|
isLoading: false,
|
|
));
|
|
return;
|
|
}
|
|
|
|
emit(state.copyWith(isLoading: true));
|
|
|
|
final actions = state.thenItems.expand((item) {
|
|
final functions = state.selectedFunctions[item['uniqueCustomId']] ?? [];
|
|
return functions.map((function) {
|
|
if (function.functionCode == 'automation') {
|
|
return CreateSceneAction(
|
|
entityId: function.entityId,
|
|
actionExecutor: function.value,
|
|
executorProperty: null,
|
|
);
|
|
}
|
|
|
|
if (item['deviceId'] == 'delay') {
|
|
return CreateSceneAction(
|
|
entityId: function.entityId,
|
|
actionExecutor: 'delay',
|
|
executorProperty: CreateSceneExecutorProperty(
|
|
functionCode: '',
|
|
functionValue: '',
|
|
delaySeconds: int.tryParse(function.value.toString()) ?? 0,
|
|
),
|
|
);
|
|
}
|
|
|
|
return CreateSceneAction(
|
|
entityId: function.entityId,
|
|
actionExecutor: 'device_issue',
|
|
executorProperty: CreateSceneExecutorProperty(
|
|
functionCode: function.functionCode,
|
|
functionValue: function.value,
|
|
delaySeconds: 0,
|
|
),
|
|
);
|
|
});
|
|
}).toList();
|
|
|
|
final createSceneModel = CreateSceneModel(
|
|
spaceUuid: spaceId,
|
|
iconId: state.selectedIcon ?? '',
|
|
showInDevice: true,
|
|
sceneName: state.routineName!,
|
|
decisionExpr: 'and',
|
|
actions: actions,
|
|
);
|
|
|
|
final result = await SceneApi.createScene(createSceneModel);
|
|
if (result['success']) {
|
|
emit(_resetState());
|
|
add(const LoadScenes(spaceId, communityId));
|
|
} else {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: result['message'],
|
|
));
|
|
}
|
|
} catch (e) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: 'Something went wrong',
|
|
));
|
|
}
|
|
}
|
|
|
|
Future<void> _onCreateAutomation(
|
|
CreateAutomationEvent event, Emitter<RoutineState> emit) async {
|
|
try {
|
|
if (state.routineName == null || state.routineName!.isEmpty) {
|
|
emit(state.copyWith(
|
|
errorMessage: 'Automation name is required',
|
|
));
|
|
return;
|
|
}
|
|
|
|
emit(state.copyWith(isLoading: true));
|
|
|
|
final conditions = state.ifItems.expand((item) {
|
|
final functions = state.selectedFunctions[item['uniqueCustomId']] ?? [];
|
|
return functions.map((function) {
|
|
return Condition(
|
|
code: state.selectedFunctions[item['uniqueCustomId']]!.indexOf(
|
|
function,
|
|
) +
|
|
1,
|
|
entityId: function.entityId,
|
|
entityType: 'device_report',
|
|
expr: ConditionExpr(
|
|
statusCode: function.functionCode,
|
|
comparator: function.condition ?? '==',
|
|
statusValue: function.value,
|
|
),
|
|
);
|
|
});
|
|
}).toList();
|
|
|
|
if (conditions.isEmpty) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: 'At least one condition is required',
|
|
));
|
|
return;
|
|
}
|
|
|
|
final actions = state.thenItems.expand((item) {
|
|
final functions = state.selectedFunctions[item['uniqueCustomId']] ?? [];
|
|
return functions.map((function) {
|
|
if (function.functionCode == 'automation') {
|
|
return AutomationAction(
|
|
entityId: function.entityId,
|
|
actionExecutor: function.value,
|
|
);
|
|
}
|
|
|
|
if (item['deviceId'] == 'delay') {
|
|
return AutomationAction(
|
|
entityId: function.entityId,
|
|
actionExecutor: 'delay',
|
|
executorProperty: ExecutorProperty(
|
|
delaySeconds: int.tryParse(function.value.toString()) ?? 0,
|
|
),
|
|
);
|
|
}
|
|
|
|
return AutomationAction(
|
|
entityId: function.entityId,
|
|
actionExecutor: 'device_issue',
|
|
executorProperty: ExecutorProperty(
|
|
functionCode: function.functionCode,
|
|
functionValue: function.value,
|
|
),
|
|
);
|
|
});
|
|
}).toList();
|
|
|
|
final createAutomationModel = CreateAutomationModel(
|
|
spaceUuid: spaceId,
|
|
automationName: state.routineName!,
|
|
decisionExpr: state.selectedAutomationOperator,
|
|
effectiveTime: EffectiveTime(
|
|
start: state.effectiveTime?.start ?? '00:00',
|
|
end: state.effectiveTime?.end ?? '23:59',
|
|
loops: state.effectiveTime?.loops ?? '1111111',
|
|
),
|
|
conditions: conditions,
|
|
actions: actions,
|
|
);
|
|
|
|
final result = await SceneApi.createAutomation(createAutomationModel);
|
|
if (result['success']) {
|
|
emit(_resetState());
|
|
add(const LoadAutomation(spaceId));
|
|
} else {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: result['message'],
|
|
));
|
|
}
|
|
} catch (e) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: 'Something went wrong',
|
|
));
|
|
}
|
|
}
|
|
|
|
FutureOr<void> _onRemoveDragCard(
|
|
RemoveDragCard event, Emitter<RoutineState> emit) {
|
|
if (event.isFromThen) {
|
|
final thenItems = List<Map<String, dynamic>>.from(state.thenItems);
|
|
final selectedFunctions =
|
|
Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions);
|
|
|
|
thenItems.removeAt(event.index);
|
|
selectedFunctions.remove(event.key);
|
|
emit(state.copyWith(
|
|
thenItems: thenItems, selectedFunctions: selectedFunctions));
|
|
} else {
|
|
final ifItems = List<Map<String, dynamic>>.from(state.ifItems);
|
|
final selectedFunctions =
|
|
Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions);
|
|
|
|
ifItems.removeAt(event.index);
|
|
selectedFunctions.remove(event.key);
|
|
if (ifItems.isEmpty && state.thenItems.isEmpty) {
|
|
emit(state.copyWith(
|
|
ifItems: ifItems,
|
|
selectedFunctions: selectedFunctions,
|
|
isAutomation: false,
|
|
isTabToRun: false));
|
|
} else {
|
|
emit(state.copyWith(
|
|
ifItems: ifItems, selectedFunctions: selectedFunctions));
|
|
}
|
|
}
|
|
}
|
|
|
|
FutureOr<void> _changeOperatorOperator(
|
|
ChangeAutomationOperator event, Emitter<RoutineState> emit) {
|
|
emit(state.copyWith(
|
|
selectedAutomationOperator: event.operator,
|
|
));
|
|
}
|
|
|
|
FutureOr<void> _onEffectiveTimeEvent(
|
|
EffectiveTimePeriodEvent event, Emitter<RoutineState> emit) {
|
|
emit(state.copyWith(effectiveTime: event.effectiveTime));
|
|
}
|
|
|
|
FutureOr<void> _onSetRoutineName(
|
|
SetRoutineName event, Emitter<RoutineState> emit) {
|
|
emit(state.copyWith(routineName: event.name));
|
|
}
|
|
|
|
Future<void> _onGetSceneDetails(
|
|
GetSceneDetails event, Emitter<RoutineState> emit) async {
|
|
try {
|
|
emit(state.copyWith(
|
|
isLoading: true,
|
|
isTabToRun: event.isTabToRun,
|
|
isUpdate: true,
|
|
sceneId: event.sceneId,
|
|
isAutomation: false));
|
|
final sceneDetails = await SceneApi.getSceneDetails(event.sceneId);
|
|
add(InitializeRoutineState(sceneDetails));
|
|
} catch (e) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: 'Failed to load scene details',
|
|
));
|
|
}
|
|
}
|
|
|
|
Future<void> _onGetAutomationDetails(
|
|
GetAutomationDetails event, Emitter<RoutineState> emit) async {
|
|
try {
|
|
emit(state.copyWith(
|
|
isLoading: true,
|
|
isAutomation: event.isAutomation,
|
|
automationId: event.automationId,
|
|
isTabToRun: false,
|
|
isUpdate: true,
|
|
));
|
|
final automationDetails =
|
|
await SceneApi.getAutomationDetails(event.automationId);
|
|
add(InitializeRoutineState(automationDetails));
|
|
} catch (e) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: 'Failed to load automation details',
|
|
));
|
|
}
|
|
}
|
|
|
|
// void _onInitializeRoutineState(
|
|
// InitializeRoutineState event, Emitter<RoutineState> emit) {
|
|
// final routineDetails = event.routineDetails;
|
|
|
|
// // Convert actions to draggable cards for the THEN container
|
|
// final thenItems = routineDetails.actions.map((action) {
|
|
// final Map<String, dynamic> cardData = {
|
|
// 'entityId': action.entityId,
|
|
// 'uniqueCustomId': const Uuid().v4(),
|
|
// 'deviceId':
|
|
// action.actionExecutor == 'delay' ? 'delay' : action.entityId,
|
|
// 'title': action.actionExecutor == 'delay' ? 'Delay' : 'Device',
|
|
// // fix this
|
|
// 'imagePath':
|
|
// action.actionExecutor == 'delay' ? Assets.delay : Assets.logo,
|
|
// };
|
|
|
|
// // Add functions to selectedFunctions
|
|
// if (action.executorProperty != null) {
|
|
// final functions = <DeviceFunctionData>[
|
|
// DeviceFunctionData(
|
|
// entityId: action.entityId,
|
|
// functionCode: action.executorProperty!.functionCode ?? '',
|
|
// value: action.executorProperty!.functionValue,
|
|
|
|
// /// fix this
|
|
// operationName: action.executorProperty?.functionCode ?? ''),
|
|
// ];
|
|
// state.selectedFunctions[cardData['uniqueCustomId']] = functions;
|
|
// }
|
|
|
|
// return cardData;
|
|
// }).toList();
|
|
|
|
// // Convert conditions to draggable cards for the IF container
|
|
// final ifItems = routineDetails.conditions?.map((condition) {
|
|
// final Map<String, dynamic> cardData = {
|
|
// 'entityId': condition.entityId,
|
|
// 'uniqueCustomId': const Uuid().v4(),
|
|
// 'deviceId': condition.entityId,
|
|
|
|
// /// fix this
|
|
// 'title': 'Device',
|
|
|
|
// /// fix this
|
|
// 'imagePath': Assets.logo,
|
|
// };
|
|
|
|
// // Add functions to selectedFunctions
|
|
// final functions = <DeviceFunctionData>[
|
|
// DeviceFunctionData(
|
|
// entityId: condition.entityId,
|
|
// functionCode: condition.expr.statusCode,
|
|
// value: condition.expr.statusValue,
|
|
// condition: condition.expr.comparator,
|
|
// operationName: condition.expr.comparator,
|
|
// ),
|
|
// ];
|
|
// state.selectedFunctions[cardData['uniqueCustomId']] = functions;
|
|
|
|
// return cardData;
|
|
// }).toList() ??
|
|
// [];
|
|
|
|
// emit(state.copyWith(
|
|
// isLoading: false,
|
|
// routineName: routineDetails.name,
|
|
// selectedIcon: routineDetails.iconId,
|
|
// selectedAutomationOperator: routineDetails.decisionExpr,
|
|
// effectiveTime: routineDetails.effectiveTime,
|
|
// isAutomation: routineDetails.conditions != null,
|
|
// isTabToRun: routineDetails.conditions == null,
|
|
// thenItems: thenItems,
|
|
// ifItems: ifItems,
|
|
// selectedFunctions: Map.from(state.selectedFunctions),
|
|
// ));
|
|
// }
|
|
|
|
RoutineState _resetState() {
|
|
return const RoutineState(
|
|
ifItems: [],
|
|
thenItems: [],
|
|
selectedFunctions: {},
|
|
scenes: [],
|
|
automations: [],
|
|
isLoading: false,
|
|
errorMessage: null,
|
|
loadScenesErrorMessage: null,
|
|
loadAutomationErrorMessage: null,
|
|
searchText: '',
|
|
selectedIcon: null,
|
|
isTabToRun: false,
|
|
isAutomation: false,
|
|
selectedAutomationOperator: 'or',
|
|
effectiveTime: null,
|
|
routineName: null,
|
|
);
|
|
}
|
|
|
|
FutureOr<void> _onResetRoutineState(
|
|
ResetRoutineState event, Emitter<RoutineState> emit) {
|
|
emit(_resetState());
|
|
}
|
|
|
|
FutureOr<void> _deleteScene(DeleteScene event, Emitter<RoutineState> emit) {
|
|
try {
|
|
// emit(state.copyWith(isLoading: true));
|
|
SceneApi.deleteScene(unitUuid: spaceId, sceneId: event.sceneId);
|
|
add(const LoadScenes(spaceId, communityId));
|
|
//emit(_resetState());
|
|
} catch (e) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: 'Failed to delete scene',
|
|
));
|
|
}
|
|
}
|
|
|
|
FutureOr<void> _deleteAutomation(
|
|
DeleteAutomation event, Emitter<RoutineState> emit) {
|
|
try {
|
|
//emit(state.copyWith(isLoading: true));
|
|
SceneApi.deleteAutomation(
|
|
unitUuid: spaceId, automationId: event.automationId);
|
|
add(const LoadAutomation(spaceId));
|
|
// emit(_resetState());
|
|
} catch (e) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
errorMessage: 'Failed to delete automation',
|
|
));
|
|
}
|
|
}
|
|
}
|