yantar/assets/Scripts/ui/ErrorLazyLoadList.ts

171 lines
6.9 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, Prefab, ScrollView, instantiate, UITransform, Node, Label } from 'cc';
import { ErrorItemData } from '../stores/ErrorItemData';
import { ErrorManager } from '../stores/ErrorManager';
import { ErrorItemButton } from '../ux/ErrorItemButton';
import { ErrorItemNamedButton } from '../ux/ErrorItemNamedButton';
const { ccclass, property } = _decorator;
@ccclass("ErrorLazyLoadList")
export class ErrorLazyLoadList extends Component {
@property(Prefab)
public errorItemPrefab: Prefab = null!;
@property(Prefab)
public errorItemNamedPrefab: Prefab = null!;
@property(ScrollView)
public scrollView: ScrollView = null!;
@property
public spacing: number = 10;
@property(Label)
public header: Label = null!;
// Массив для хранения всех ошибок, полученных с API (плоский список)
private _data: ErrorItemData[] = [];
// Массив для хранения отфильтрованных данных (если фильтр активирован)
private _filteredData: ErrorItemData[] | null = null;
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;
}
// Начальный заголовок можно задать здесь
// Приводим content к типу Node, импортированному из 'cc'
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();
}
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() {
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;
// Если фильтр не активирован, используем все данные
if (!this._filteredData) {
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
}
loadNextBatch(batchSize: number) {
const currentData = this._filteredData || this._data;
if (this._loadedCount >= currentData.length) return;
const startIndex = this._loadedCount;
const endIndex = Math.min(this._loadedCount + batchSize, currentData.length);
for (let i = startIndex; i < endIndex; i++) {
let item: Node;
// Если фильтрация активна, используем другой префаб и соответствующий компонент
if (this._filteredData) {
item = instantiate(this.errorItemNamedPrefab);
const errorItemNamedButton = item.getComponent("ErrorItemNamedButton") as unknown as ErrorItemNamedButton;
if (errorItemNamedButton) {
errorItemNamedButton.initialize(currentData[i]);
} else {
console.warn("Компонент ErrorItemNamedButton не найден на префабе.");
}
} else {
item = instantiate(this.errorItemPrefab);
const errorItemButton = item.getComponent("ErrorItemButton") as unknown as ErrorItemButton;
if (errorItemButton) {
errorItemButton.initialize(currentData[i]);
} else {
console.warn("Компонент ErrorItemButton не найден на префабе.");
}
}
item.setPosition(0, - (this._itemHeight * (0.5 + i) + this.spacing * (i + 1)), 0);
this._content.addChild(item);
}
this._loadedCount = endIndex;
this._contentUI.height = currentData.length * (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);
const currentData = this._filteredData || this._data;
if (offset >= (this._contentUI.height - visibleHeight - threshold)) {
if (this._loadedCount < currentData.length) {
this.loadNextBatch(20);
}
}
}
/**
* Фильтрует список по имени оборудования.
* @param sensorName имя оборудования, по которому необходимо отфильтровать список
*/
public filterBySensor(sensorName: string) {
this.header.string = `Аварии на ${sensorName}`;
this._filteredData = this._data.filter(item => item.sensorName === sensorName);
this._totalCount = this._filteredData.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
/**
* Сбрасывает фильтр и возвращает отображение полного списка.
*/
public resetFilter() {
this.header.string = "Список всех аварий";
this._filteredData = null;
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
}