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

163 lines
7.0 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, MeshRenderer } from 'cc';
import { ItemButton } from '../ux/ItemButton';
import { apiSensors } from '../stores/apiSensors';
import { EquipmentManager } from '../stores/EquipmentManager';
const { ccclass, property } = _decorator;
@ccclass("LazyLoadList")
export class LazyLoadList extends Component {
@property(Prefab)
public itemPrefab: Prefab = null!;
@property(ScrollView)
public scrollView: ScrollView = null!;
// Нода, содержащая оборудование (для фильтрации по именам)
@property(Node)
public equipmentNode: Node = null!;
@property
public spacing: number = 10;
private _data: apiSensors[] = [];
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 равен null!");
return;
}
this._content = this.scrollView.content;
this._contentUI = this._content.getComponent(UITransform)!;
if (!this._contentUI) {
console.error("Узел content не имеет компонента UITransform!");
return;
}
// Определяем высоту элемента через префаб
const tempNode: Node = instantiate(this.itemPrefab);
const tempUI = tempNode.getComponent(UITransform);
if (!tempUI) {
console.error("В префабе отсутствует компонент UITransform!");
tempNode.destroy();
return;
}
this._itemHeight = tempUI.height;
tempNode.destroy();
// Ожидаем появления EquipmentManager.instance и загрузки данных
this.waitForEquipmentManager();
}
private waitForEquipmentManager() {
if (!EquipmentManager.instance) {
console.warn("EquipmentManager.instance не найден, повторная попытка...");
this.scheduleOnce(() => { this.waitForEquipmentManager(); }, 0.1);
return;
}
// Ждём завершения первоначальной загрузки данных
EquipmentManager.instance.initialDataPromise.then(() => {
// Подписываемся на событие обновления данных
EquipmentManager.instance.node.on('data-updated', this.onDataUpdated, this);
// Если данные уже загружены, инициируем обновление списка:
this.onDataUpdated();
}).catch((error) => {
console.error("Ошибка загрузки данных в EquipmentManager:", error);
});
}
private async onDataUpdated() {
if (!EquipmentManager.instance) return;
// Получаем данные из EquipmentManager
const allData: apiSensors[] = await EquipmentManager.instance.getDataList();
console.log("Полученные данные:", allData);
// Логируем распределение value в полученных данных
const valueDistribution = allData.reduce((acc, sensor) => {
acc[sensor.value] = (acc[sensor.value] || 0) + 1;
return acc;
}, {} as Record<number, number>);
console.log("Распределение value в полученных данных:", valueDistribution);
// Получаем список имён из equipmentNode, для нод с компонентом MeshRenderer
const validNames: string[] = [];
if (this.equipmentNode) {
console.log("equipmentNode.children:", this.equipmentNode.children.map(child => child.name));
this.equipmentNode.children.forEach(child => {
if (child.getComponent(MeshRenderer)) {
validNames.push(child.name);
} else {
console.warn(`У ноды ${child.name} отсутствует MeshRenderer`);
}
});
} else {
console.error("equipmentNode не задан!");
}
console.log("validNames:", validNames);
// Фильтруем данные, оставляя только элементы, имя которых есть в validNames
const filteredData = allData.filter((item: apiSensors) => {
const match = validNames.indexOf(item.name) !== -1;
if (!match) {
console.warn(`Датчик ${item.name} с value=${item.value} отфильтрован, так как его имя не найдено в validNames`);
}
return match;
});
console.log("Фильтрованные данные (до копирования):", filteredData);
this._data = filteredData.map(item => ({ ...item }));
console.log("Данные после копирования:", this._data);
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.itemPrefab);
const posY = - (this._itemHeight * (0.5 + i) + this.spacing * (i + 1));
item.setPosition(0, posY, 0);
this._content.addChild(item);
const itemButton = item.getComponent(ItemButton);
if (itemButton) {
console.log(`Инициализация ItemButton для элемента с индексом ${i}:`, this._data[i]);
itemButton.initialize(this._data[i]);
itemButton.itemIndex = i;
} else {
console.error("Компонент ItemButton не найден на ноде", item);
}
}
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);
}
}
}
}