теперь вывожу колличество аварий а не колличество оборудования в аварийном состоянии
127 lines
5.3 KiB
TypeScript
127 lines
5.3 KiB
TypeScript
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node } from 'cc';
|
||
import { ErrorManager } from '../stores/ErrorManager';
|
||
import { ErrorItemData } from '../stores/ErrorItemData'; // Определённый ниже интерфейс (можно вынести в отдельный файл)
|
||
import { ErrorItemButton } from '../ux/ErrorItemButton';
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass("ErrorLazyLoadList")
|
||
export class ErrorLazyLoadList extends Component {
|
||
|
||
@property(Prefab)
|
||
public errorItemPrefab: Prefab = null!;
|
||
|
||
@property(ScrollView)
|
||
public scrollView: ScrollView = null!;
|
||
|
||
@property
|
||
public spacing: number = 10;
|
||
|
||
// Массив для хранения ошибок, полученных с API (уже в виде плоского списка)
|
||
private _data: ErrorItemData[] = [];
|
||
private _totalCount: number = 0;
|
||
private _loadedCount: number = 0;
|
||
private _itemHeight: number = 0;
|
||
private _content: Node = null!;
|
||
private _contentUI: UITransform = null!;
|
||
|
||
onLoad() {
|
||
if (!this.scrollView.content) {
|
||
console.error("ScrollView.content is null!");
|
||
return;
|
||
}
|
||
this._content = this.scrollView.content;
|
||
this._contentUI = this._content.getComponent(UITransform)!;
|
||
if (!this._contentUI) {
|
||
console.error("Content node does not have UITransform component!");
|
||
return;
|
||
}
|
||
|
||
// Определяем высоту элемента через префаб
|
||
const tempNode: Node = instantiate(this.errorItemPrefab);
|
||
const tempUI = tempNode.getComponent(UITransform);
|
||
if (!tempUI) {
|
||
console.error("Prefab missing UITransform component!");
|
||
tempNode.destroy();
|
||
return;
|
||
}
|
||
this._itemHeight = tempUI.height;
|
||
tempNode.destroy();
|
||
|
||
this.waitForErrorManager();
|
||
}
|
||
|
||
// Ожидаем появления ErrorManager.instance
|
||
private waitForErrorManager() {
|
||
if (!ErrorManager.instance) {
|
||
console.warn("ErrorManager.instance not found, retrying...");
|
||
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
|
||
return;
|
||
}
|
||
// Подписываемся на событие обновления ошибок
|
||
ErrorManager.instance.node.on('errors-updated', this.onDataUpdated, this);
|
||
// Если данные уже доступны, инициируем обновление списка
|
||
this.onDataUpdated();
|
||
}
|
||
|
||
// Обновление данных: получаем сгруппированные ошибки, преобразуем в плоский массив и перерисовываем список
|
||
private onDataUpdated() {
|
||
// Получаем сгруппированные ошибки из ErrorManager
|
||
// Предполагается, что getErrorList() возвращает объект вида:
|
||
// { equipmentErrors: apiSensors[], apiErrors: { [sensorName: string]: ApiError[] } }
|
||
const apiErrors = ErrorManager.instance.getErrorList().apiErrors;
|
||
const flattened: ErrorItemData[] = [];
|
||
for (const sensorName in apiErrors) {
|
||
for (const err of apiErrors[sensorName]) {
|
||
flattened.push({
|
||
sensorName,
|
||
alarmCode: err.alarmCode,
|
||
description: err.description,
|
||
timestamp: err.timestamp
|
||
});
|
||
}
|
||
}
|
||
this._data = flattened;
|
||
this._totalCount = this._data.length;
|
||
// Очищаем список и начинаем заново
|
||
this._loadedCount = 0;
|
||
this._content.removeAllChildren();
|
||
this.loadNextBatch(20);
|
||
}
|
||
|
||
/**
|
||
* Загружает следующую партию элементов (batchSize элементов).
|
||
*/
|
||
loadNextBatch(batchSize: number) {
|
||
if (this._loadedCount >= this._totalCount) return;
|
||
|
||
const startIndex = this._loadedCount;
|
||
const endIndex = Math.min(this._loadedCount + batchSize, this._totalCount);
|
||
for (let i = startIndex; i < endIndex; i++) {
|
||
const item: Node = instantiate(this.errorItemPrefab);
|
||
const posY = - (this._itemHeight * (0.5 + i) + this.spacing * (i + 1));
|
||
item.setPosition(0, posY, 0);
|
||
this._content.addChild(item);
|
||
|
||
// Получаем компонент ErrorItemButton и инициализируем его данными
|
||
const errorItemButton = item.getComponent("ErrorItemButton") as unknown as ErrorItemButton;
|
||
if (errorItemButton) {
|
||
errorItemButton.initialize(this._data[i]);
|
||
}
|
||
}
|
||
this._loadedCount = endIndex;
|
||
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing) + this.spacing;
|
||
}
|
||
|
||
update(dt: number) {
|
||
if (!this.scrollView.content) return;
|
||
const threshold = 50;
|
||
const visibleHeight = this.scrollView.node.getComponent(UITransform)!.height;
|
||
const offset = Math.abs(this.scrollView.content.position.y);
|
||
if (offset >= (this._contentUI.height - visibleHeight - threshold)) {
|
||
if (this._loadedCount < this._totalCount) {
|
||
this.loadNextBatch(20);
|
||
}
|
||
}
|
||
}
|
||
}
|