yantar/assets/Scripts/ux/ErrorItemButton.ts
Georgy Shive 872c5bde46 добавил в списке оборудования
на кнопку аварии  счетчик колличества
аварий на данном оборудовании
2025-03-13 21:17:02 +07:00

142 lines
4.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { _decorator, Component, Label, Button, Node, Event } from 'cc';
import { EquipmentManager } from '../stores/EquipmentManager';
import { PulsatingHighlighter } from '../PulsatingHighlighter';
import { CameraMover } from '../CameraMover';
import { ErrorItemData } from '../stores/ErrorItemData';
const { ccclass, property } = _decorator;
@ccclass('ErrorItemButton')
export class ErrorItemButton extends Component {
@property(Label)
public nameLabel: Label | null = null;
@property(Label)
public timeLabel: Label | null = null;
@property(Button)
public actionButton: Button | null = null; // Первая кнопка – выбирает оборудование
@property(Button)
public disableAlertButton: Button | null = null; // Вторая кнопка – отправляет запрос на API
private itemData: ErrorItemData | null = null;
// Инициализация данных для элемента ошибки
public initialize(data: ErrorItemData) {
this.itemData = data;
if (this.nameLabel) {
this.nameLabel.string = data.sensorName;
}
if (this.timeLabel) {
this.timeLabel.string = data.description;
}
}
onLoad() {
if (this.actionButton) {
this.actionButton.node.on('click', this.onActionClick, this);
}
if (this.disableAlertButton) {
this.disableAlertButton.node.on('click', this.onDisableAlertClick, this);
}
}
onDestroy() {
if (this.actionButton) {
this.actionButton.node.off('click', this.onActionClick, this);
}
if (this.disableAlertButton) {
this.disableAlertButton.node.off('click', this.onDisableAlertClick, this);
}
}
// Обработка клика по кнопке стандартного действия (без изменений)
onActionClick(event?: Event) {
if (!this.itemData) return;
const sensors = EquipmentManager.instance.dataList;
const sensorData = sensors.find(s => s.name === this.itemData!.sensorName);
if (!sensorData) {
console.warn(`Sensor ${this.itemData.sensorName} not found!`);
return;
}
let color = "";
if (sensorData.value === 2) {
color = "red";
} else if (sensorData.value === 1) {
color = "green";
} else if (sensorData.value === 0) {
color = "yellow";
} else {
return;
}
const scene = this.node.scene;
if (!scene) {
return;
}
// Рекурсивно ищем узел с именем, соответствующим sensorName
const targetNode = this.findNodeByName(scene, this.itemData.sensorName);
if (!targetNode) {
return;
}
const highlighter = targetNode.getComponent(PulsatingHighlighter);
if (highlighter) {
highlighter.switchToColor(color);
} else {
}
const cameraMover = scene.getComponentInChildren(CameraMover);
if (cameraMover) {
cameraMover.moveToTarget(targetNode);
} else {
}
}
// Обработка клика по кнопке отключения оповещения (отправляет запрос на API)
async onDisableAlertClick(event?: Event) {
if (!this.itemData) return;
try {
const response = await fetch("http://localhost:3030/api/v2/errors/resolve", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
sensorName: this.itemData.sensorName
// Если требуется, можно передать alarmCode: this.itemData.alarmCode
})
});
const result = await response.json();
console.log("Error resolved:", result);
// При необходимости можно вызвать обновление состояния ErrorManager
} catch (error) {
console.error("Error resolving error via API:", error);
}
}
// Рекурсивный поиск узла по имени
private findNodeByName(root: Node, name: string): Node | null {
if (root.name === name) return root;
for (let i = 0; i < root.children.length; i++) {
const found = this.findNodeByName(root.children[i], name);
if (found) return found;
}
return null;
}
}