Untitled

 avatar
unknown
plain_text
a year ago
9.1 kB
5
Indexable
@Component({
    selector: 'e-app-info',
    templateUrl: './app-info.component.html',
    styleUrls: ['./app-info.component.scss']
})
export class AppInfoComponent implements OnInit, OnDestroy, AfterViewInit {
    @ViewChild('tt') tt!: TreeTable;
    @ViewChild('container') container!: ElementRef;
    @ViewChildren('serviceAccordions', { read: ElementRef })
    public serviceAccordions!: QueryList<ElementRef>;
    public applicationNameInfo$: Observable<ProjectDetails | null> = this.mainService.projectSubject.asObservable();
    public stopSubject: Subject<boolean> = new Subject<boolean>();
    public subs: Subscription = new Subscription();
    public dialog: boolean = false;
    public applicationInfo!: { applicationName: string; groupId: string };
    public formGroup: FormGroup = this._fb.group({
        storeName: [null, Validators.required],
        id: [null, Validators.required]
    });
    public node: ParametersModel = {
        type: '',
        applicationName: '',
        serviceName: '',
        podName: '',
        operation: null,
        levelType: null
    };
    public currentIndex: number[] = [];
    public spinner = false;
    private timerDelay: number = 99999999; // интервал сброса
    public timer$: Observable<number> = timer(0, this.timerDelay);

    constructor(
        private mainService: MainService,
        private route: ActivatedRoute,
        private _messageService: MessageService,
        private _fb: FormBuilder,
        private router: Router
    ) {}

    public byName(index: number, item: ServiceDetails): string {
        return item.name;
    }

    public ngAfterViewInit(): void {
        this.serviceAccordions.changes
            .pipe(
                switchMap(() =>
                    this.route.queryParams.pipe(
                        map((query: Params) =>
                            this.serviceAccordions
                                .toArray()
                                .findIndex(element => element.nativeElement.innerHTML.trim() === query['serviceName'])
                        )
                    )
                )
            )
            .subscribe((index: number) => {
                if (index !== -1) {
                    const element = this.serviceAccordions.toArray()[index];
                    setTimeout(() => {
                        element.nativeElement.scrollIntoView();
                        this.router.navigate([], {
                            queryParams: {
                                yourParam: undefined,
                                youCanRemoveMultiple: undefined
                            }
                        });
                    }, 500);
                }
            });
    }

    public ngOnInit(): void {
        this._initAppInfo();
    }

    public setActiveIndices(i: any): void {
        this.currentIndex = i;
    }

    public _initAppInfo() {
        this.spinner = true;
        this._getAppInfo().subscribe(() => {
            this._scroll();
            this.getIndexServiceFromRoute();
        });
    }

    public startTimer(): void {
        this.subs.add(
            this.timer$
                .pipe(
                    switchMap(() => {
                        this.savePosition();
                        return this._getAppInfo().pipe(share());
                    }),
                    takeUntil(this.stopSubject)
                )
                .subscribe(() => {
                    this._scroll();
                })
        );
    }

    public savePosition(): void {
        this.spinner = true;
        localStorage.setItem('position', this.container.nativeElement.scrollTop);
    }

    public refresh(): void {
        this.savePosition();
        this.subs.add(
            this._getAppInfo().subscribe(() => {
                this._scroll();
                this.spinner = false;
            })
        );
    }

    public setTimerDelay(event: { originalEvent: Event; value: any }): void {
        this.timerDelay = event.value;
        this.resetTimer();
    }

    public resetTimer(): void {
        this.stopSubject.next(false);
        this.timer$ = timer(0, this.timerDelay);
        this.startTimer();
    }

    public ngOnDestroy(): void {
        this.subs.unsubscribe();
    }

    protected change(bool: boolean) {
        this.dialog = false;
        if (this.node.operation && this.node.operation in PodOperations && bool) {
            if (this.node.levelType == LEVEL_TYPE.GENERAL) {
                if (this.node.type == 'consumer') {
                    this._operateByServiceConsumer();
                    return;
                }
                if (this.node.type == 'stream') {
                    this._operateByPodStream();
                    return;
                }
            }
            if (this.node.levelType == LEVEL_TYPE.POD) {
                if (this.node.type == 'consumer') {
                    this._operateByPodConsumer();
                    return;
                }
            }
            this._changeOffsetByPod();
        }
    }

    protected confirm(service: ServiceDetails, pod: PodsModel | null, action: string, levelType: LEVEL_TYPE): void {
        this.dialog = true;
        this._setSelectedNode(service, pod, action, levelType);
    }

    private _scroll() {
        setTimeout(() => {
            this.container.nativeElement.scrollTo({
                top: localStorage.getItem('position'),
                behavior: 'smooth'
            });
            this.spinner = false;
        }, 500);
    }

    private getIndexServiceFromRoute(): void {
        this.route.queryParams
            .pipe(
                filter((res: Params) => {
                    return Object.keys(res).length > 0;
                }),
                switchMap((res: Params) => {
                    return this.applicationNameInfo$.pipe(
                        map((app: ProjectDetails | null) => {
                            return app?.services.findIndex((item: ServiceDetails) => {
                                return item.name === res['serviceName'];
                            });
                        })
                    );
                }),
                first()
            )
            .subscribe((index: number | undefined) => {
                if (index !== undefined) {
                    this.setActiveIndices([index]);
                }
            });
    }

    private _operateByPodConsumer(): void {
        this.subs.add(this.mainService.operateByPodConsumer(this.node).subscribe(this._handleOperation(this.node.operation!)));
    }

    private _operateByServiceConsumer(): void {
        this.subs.add(this.mainService.operateByServiceConsumer(this.node).subscribe(this._handleOperation(this.node.operation!)));
    }

    private _operateByPodStream(): void {
        this.subs.add(this.mainService.operateStream(this.node).subscribe(this._handleOperation(this.node.operation!)));
    }

    private _changeOffsetByPod(): void {
        this.subs.add(
            this.mainService.changeOffsetByPod(this.node).subscribe(this._handleOperation('Change offset ' + this.node.operation))
        );
    }

    private _getAppInfo(): Observable<ProjectDetails> {
        return this.route.params.pipe(
            switchMap((res: Params) => {
                this.applicationInfo = {
                    applicationName: res['namespace'],
                    groupId: res['groupId']
                };
                return this.mainService.getProject(res['groupId'], res['namespace']).pipe(
                    finalize(() => {
                        this.spinner = false;
                    })
                );
            })
        );
    }

    private _handleOperation(type: string) {
        let details = type + ' operation executed';
        return {
            next: () => {
                this._messageService.add({
                    severity: 'success',
                    summary: 'Success',
                    detail: details
                });
                this.refresh();
            },
            error: () => {
                this._messageService.add({
                    severity: 'error',
                    summary: 'Error',
                    detail: 'Something wrong'
                });
            }
        };
    }

    private _setSelectedNode(service: ServiceDetails, pod: PodsModel | null, action: string, levelType: LEVEL_TYPE): void {
        this.node.applicationName = this.applicationInfo.applicationName;
        this.node.operation = action as PodOperations;
        this.node.type = service.type.toLowerCase();
        this.node.serviceName = service.name;
        this.node.podName = pod?.name as string;
        this.node.levelType = levelType;
    }
}
Editor is loading...
Leave a Comment