134 lines
4.5 KiB
TypeScript
134 lines
4.5 KiB
TypeScript
// scripts/stores/ErrorManager.ts
|
||
import { _decorator, Component, Node, AudioSource, director } from 'cc';
|
||
import { EquipmentManager } from './EquipmentManager';
|
||
import { apiSensors } from './apiSensors';
|
||
import { ErrorsStore, ApiErrorsResponse } from './ErrorsStore';
|
||
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass('ErrorManager')
|
||
export class ErrorManager extends Component {
|
||
@property(Node)
|
||
public errorListNode: Node = null!;
|
||
|
||
@property(AudioSource)
|
||
public audioSource: AudioSource | null = null;
|
||
|
||
private soundEnabled = true;
|
||
private currentErrors: string[] = [];
|
||
private errorItems: apiSensors[] = [];
|
||
private disabledAlerts: string[] = [];
|
||
// Инициализируем через getInstance()
|
||
private errorsStore = ErrorsStore.getInstance();
|
||
|
||
static instance: ErrorManager;
|
||
|
||
onLoad() {
|
||
ErrorManager.instance = this;
|
||
// Делаем узел устойчивым к смене сцен
|
||
director.addPersistRootNode(this.node);
|
||
this.node.on('touchstart', this.disableSoundAlert, this);
|
||
}
|
||
|
||
start() {
|
||
EquipmentManager.instance?.node?.on('data-updated', this.checkErrors, this);
|
||
this.schedule(this.checkErrors, 5);
|
||
this.schedule(this.fetchApiErrors, 10);
|
||
}
|
||
|
||
onDestroy() {
|
||
this.node.off('touchstart', this.disableSoundAlert, this);
|
||
EquipmentManager.instance?.node?.off('data-updated', this.checkErrors, this);
|
||
this.unscheduleAllCallbacks();
|
||
}
|
||
|
||
/**
|
||
* Возвращает список текущих локальных ошибок по оборудованию и ошибки из API.
|
||
*/
|
||
public getErrorList(): { equipmentErrors: apiSensors[]; apiErrors: ApiErrorsResponse } {
|
||
return {
|
||
equipmentErrors: this.errorItems,
|
||
apiErrors: this.errorsStore.getApiErrors(),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Проверка локальных состояний ошибок по EquipmentManager.
|
||
* Добавляет новые, убирает снятые, эмитит 'errors-updated'.
|
||
*/
|
||
checkErrors() {
|
||
const dataList = EquipmentManager.instance?.dataList ?? [];
|
||
let updated = false;
|
||
|
||
// Фильтруем снятые ошибки
|
||
const prevErrors = [...this.currentErrors];
|
||
this.currentErrors = this.currentErrors.filter(tag =>
|
||
dataList.some(item => item.tag === tag && item.value === 2)
|
||
);
|
||
if (prevErrors.length !== this.currentErrors.length) {
|
||
this.errorItems = this.errorItems.filter(item =>
|
||
dataList.some(it => it.tag === item.tag && it.value === 2)
|
||
);
|
||
updated = true;
|
||
}
|
||
|
||
// Добавляем новые ошибки
|
||
dataList.forEach(item => {
|
||
if (item.value === 2 && this.currentErrors.indexOf(item.tag) === -1) {
|
||
this.currentErrors.push(item.tag);
|
||
this.errorItems.push(item);
|
||
this.addErrorToUI(item);
|
||
updated = true;
|
||
if (this.soundEnabled && this.disabledAlerts.indexOf(item.tag) === -1) {
|
||
this.audioSource?.play();
|
||
}
|
||
}
|
||
});
|
||
|
||
if (updated) {
|
||
this.node.emit('errors-updated');
|
||
}
|
||
// Всегда проверяем API-ошибки после локальных изменений
|
||
this.fetchApiErrors();
|
||
}
|
||
|
||
/**
|
||
* Запрашивает свежие ошибки у API и эмитит 'errors-updated'.
|
||
*/
|
||
async fetchApiErrors() {
|
||
try {
|
||
await this.errorsStore.fetchApiErrors();
|
||
this.node.emit('errors-updated');
|
||
} catch (e) {
|
||
console.error('ErrorManager.fetchApiErrors:', e);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Добавляет запись об ошибке в UI-список.
|
||
* Реализуйте логику вставки нод в this.errorListNode.
|
||
*/
|
||
addErrorToUI(item: apiSensors) {
|
||
// TODO: ваша логика по созданию и добавлению ноды в this.errorListNode
|
||
}
|
||
|
||
/** Отключает проигрывание звуковых оповещений. */
|
||
disableSoundAlert() {
|
||
this.soundEnabled = false;
|
||
}
|
||
|
||
/** Помечает ошибку как «заблокированную» — звук для неё больше не будет играться. */
|
||
public disableAlertForError(tag: string): void {
|
||
if (this.disabledAlerts.indexOf(tag) === -1) {
|
||
this.disabledAlerts.push(tag);
|
||
}
|
||
}
|
||
|
||
/** Подтверждает ошибку — удаляет её из локального списка. */
|
||
confirmError(tag: string) {
|
||
this.currentErrors = this.currentErrors.filter(e => e !== tag);
|
||
this.errorItems = this.errorItems.filter(item => item.tag !== tag);
|
||
this.node.emit('errors-updated');
|
||
}
|
||
}
|