import { Component, Input, ContentChild, TemplateRef, ViewChild, ViewContainerRef, ElementRef } from '@angular/core';

/**
 * 锚点分组列表组件
 *
 * @export
 * @class AppAnchorPointList
 */
@Component({
    selector: 'app-anchor-point-list',
    templateUrl: 'app-anchor-point-list.html',
    styleUrls: ['app-anchor-point-list.scss']
})
export class AppAnchorPointList {
    /**
     * 插座内容
     *
     * @type {TemplateRef<any>}
     * @memberof AppAnchorPointList
     */
    @ContentChild(TemplateRef)
    template: TemplateRef<any>;
    /**
     * List容器
     *
     * @type {TemplateRef<any>}
     * @memberof AppAnchorPointList
     */
    @ViewChild('appAnchorPointList', { read: ViewContainerRef })
    container: ViewContainerRef;
    /**
     * 列表数据
     *
     * @type {any[]}
     * @memberof AppAnchorPointList
     */
    @Input()
    set items(val: any[]) {
        if (val) {
            this.$items = val;
            this.anchorPoints.clear();
        }
    }
    public $items: any[] = [];
    /**
     * 所有锚点项
     *
     * @private
     * @type {Map<string, Element>}
     * @memberof AppAnchorPointList
     */
    private anchorPoints: Map<string, Element> = new Map();
    /**
     * 容器dom对象
     *
     * @private
     * @type {HTMLDivElement}
     * @memberof AppAnchorPointList
     */
    private containerElement: HTMLDivElement;

    /**
     * Creates an instance of AppAnchorPointList.
     * @memberof AppAnchorPointList
     */
    constructor() { }

    /**
     * 初始化锚点
     *
     * @memberof AppAnchorPointList
     */
    private initAnchorPoint(): void {
        if (this.container) {
            this.containerElement = this.container.element.nativeElement;
            const arr: HTMLCollection = this.containerElement.getElementsByTagName('ion-item-group');
            if (arr) {
                for (let i: number = 0; i < arr.length; i++) {
                    const item: Element = arr.item(i);
                    this.anchorPoints.set(item.id, item);
                }
            }
        }
    }

    /**
     * 定位移动
     *
     * @param {string} id 移动位置id
     * @memberof AppAnchorPointList
     */
    public locationMobile(id: string): void {
        if (this.anchorPoints.size !== this.$items.length) {
            this.initAnchorPoint();
        }
        const item: any = this.anchorPoints.get(id);
        if (item) {
            this.containerElement.scrollTo(0, item.offsetTop);
        }
    }

}