230 lines
9.3 KiB
TypeScript
230 lines
9.3 KiB
TypeScript
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';
|
||
import { SensorDescription } from '../stores/SensorDescriptionField';
|
||
import { SensorFieldItem } from './SensorFieldItem';
|
||
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass("ErrorLazyLoadList")
|
||
export class ErrorLazyLoadList extends Component {
|
||
public static instance: ErrorLazyLoadList | null = null;
|
||
|
||
@property(Prefab)
|
||
public errorItemPrefab: Prefab = null!;
|
||
|
||
@property(Prefab)
|
||
public sensorFieldItemPrefab: 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!;
|
||
|
||
private _data: ErrorItemData[] = [];
|
||
private _filteredData: ErrorItemData[] | null = null;
|
||
private _mode: "errors" | "details" = "errors";
|
||
private _sensorDescription: SensorDescription = null!;
|
||
private _totalCount: number = 0;
|
||
private _loadedCount: number = 0;
|
||
private _itemHeight: number = 0;
|
||
private _content: Node = null!;
|
||
private _contentUI: UITransform = null!;
|
||
|
||
public get mode(): "errors" | "details" {
|
||
return this._mode;
|
||
}
|
||
|
||
onLoad() {
|
||
ErrorLazyLoadList.instance = this;
|
||
|
||
if (!this.scrollView.content) {
|
||
console.error("ScrollView.content is null!");
|
||
return;
|
||
}
|
||
|
||
this._content = this.scrollView.content;
|
||
this._contentUI = this._content.getComponent(UITransform)!;
|
||
|
||
const tempNode: Node = instantiate(this.errorItemPrefab);
|
||
const tempUI = tempNode.getComponent(UITransform);
|
||
this._itemHeight = tempUI!.height;
|
||
tempNode.destroy();
|
||
|
||
this._mode = "errors";
|
||
this.waitForErrorManager();
|
||
|
||
this.scrollView.node.on('scrolling', this.onScrolling, this);
|
||
}
|
||
|
||
private onScrolling() {
|
||
const offsetY = this.scrollView.getScrollOffset().y;
|
||
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
|
||
const contentHeight = this._contentUI.height;
|
||
|
||
if (offsetY + viewHeight + (this._itemHeight * 2) >= contentHeight) {
|
||
this.loadNextBatch(20);
|
||
}
|
||
}
|
||
|
||
onDestroy() {
|
||
if (ErrorLazyLoadList.instance === this) {
|
||
ErrorLazyLoadList.instance = null;
|
||
}
|
||
}
|
||
|
||
private waitForErrorManager() {
|
||
if (!ErrorManager.instance) {
|
||
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
|
||
return;
|
||
}
|
||
ErrorManager.instance.node.on('errors-updated', this.onDataUpdated, this);
|
||
this.onDataUpdated();
|
||
}
|
||
|
||
|
||
private onDataUpdated() {
|
||
if (this._mode !== "errors") return;
|
||
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);
|
||
}
|
||
}
|
||
|
||
private loadNextBatch(batchSize: number) {
|
||
let currentData: any[] = [];
|
||
if (this._mode === "errors") {
|
||
currentData = this._filteredData || this._data;
|
||
} else if (this._mode === "details") {
|
||
currentData = this._sensorDescription?.fields || [];
|
||
}
|
||
if (this._loadedCount >= currentData.length) return;
|
||
|
||
const endIndex = Math.min(this._loadedCount + batchSize, currentData.length);
|
||
|
||
for (let i = this._loadedCount; i < endIndex; i++) {
|
||
let item: Node;
|
||
switch (this._mode) {
|
||
case "errors":
|
||
item = instantiate(this._filteredData ? this.errorItemNamedPrefab : this.errorItemPrefab);
|
||
const componentName = this._filteredData ? "ErrorItemNamedButton" : "ErrorItemButton";
|
||
const errorItem = item.getComponent(componentName) as unknown as ErrorItemNamedButton | ErrorItemButton;
|
||
errorItem?.initialize(currentData[i]);
|
||
break;
|
||
|
||
case "details":
|
||
item = instantiate(this.sensorFieldItemPrefab);
|
||
const sensorFieldItem = item.getComponent(SensorFieldItem);
|
||
sensorFieldItem?.setData(currentData[i]);
|
||
break;
|
||
|
||
default:
|
||
continue;
|
||
}
|
||
|
||
item.setPosition(0, -(this._loadedCount * (this._itemHeight + this.spacing) + this._itemHeight / 2), 0);
|
||
this._content.addChild(item);
|
||
|
||
this._loadedCount++;
|
||
}
|
||
|
||
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing);
|
||
}
|
||
|
||
|
||
|
||
private repositionChildren() {
|
||
let cumulativeHeight = 0;
|
||
// Проходим по всем дочерним элементам контейнера
|
||
for (let i = 0; i < this._content.children.length; i++) {
|
||
const child = this._content.children[i];
|
||
// Получаем актуальную высоту через UITransform
|
||
const childHeight = child.getComponent(UITransform)?.height || 0;
|
||
// Вычисляем позицию для этого элемента так, чтобы его центр был ниже предыдущего элемента
|
||
child.setPosition(0, - (cumulativeHeight + childHeight / 2), 0);
|
||
// Добавляем к накопленной высоте высоту элемента плюс spacing
|
||
cumulativeHeight += childHeight + this.spacing;
|
||
}
|
||
// Обновляем высоту контейнера, чтобы ScrollView корректно показывал содержимое
|
||
this._contentUI.height = cumulativeHeight;
|
||
}
|
||
|
||
|
||
/**
|
||
* В
|
||
/**
|
||
* Фильтрует список ошибок по имени оборудования.
|
||
* @param sensorName имя оборудования, по которому необходимо отфильтровать список
|
||
*/
|
||
public filterBySensor(sensorName: string) {
|
||
this._mode = "errors";
|
||
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._mode = "errors";
|
||
this._filteredData = null;
|
||
this._totalCount = this._data.length;
|
||
this._loadedCount = 0;
|
||
this._content.removeAllChildren();
|
||
this.loadNextBatch(20);
|
||
}
|
||
|
||
/**
|
||
* Принимает данные описания оборудования и переключает режим отображения в "details".
|
||
* @param data Объект с деталями датчика.
|
||
*/
|
||
public showSensorDetails(data: { sensorName: string, fields: any[] }) {
|
||
this._mode = "details";
|
||
this.header.string = `Детали ${data.sensorName}`;
|
||
this._sensorDescription = {
|
||
sensorName: data.sensorName,
|
||
fields: data.fields
|
||
};
|
||
this._loadedCount = 0;
|
||
this._content.removeAllChildren();
|
||
this.loadNextBatch(20);
|
||
}
|
||
|
||
/**
|
||
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
|
||
*/
|
||
public showErrors() {
|
||
this._mode = "errors";
|
||
this.header.string = "Список всех аварий";
|
||
this._filteredData = null;
|
||
this._totalCount = this._data.length;
|
||
this._loadedCount = 0;
|
||
this._content.removeAllChildren();
|
||
this.loadNextBatch(20);
|
||
}
|
||
}
|