import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';

@Injectable({ providedIn: 'root' })
export class Loading {

    /**
     * 加载动画计数器
     *
     * @type {number}
     * @memberof Http
     */
    private loadingCount: number = 0;

    /**
     * 加载动画实例
     *
     * @type {*}
     * @memberof Http
     */
    private loader: any;

    constructor(private loading: LoadingController) { }

    /**
     * 显示loading
     *
     * @memberof Http
     */
    public async mask(message: string = '加载中......'): Promise<any> {
        this.loadingCount++;
        if (this.loadingCount === 1) {
            this.loader = await this.loading.create({
                message
            });
            this.loader.present();
        }
    }

    /**
     * 隐藏loading
     *
     * @memberof Http
     */
    public async unmask(): Promise<any> {
        setTimeout(() => {
            this.loadingCount--;
            if (this.loadingCount === 0) {
                //if (this.loadingCount === 0) {
                //this.loading.dismiss();  
                if (this.loader) {
                    this.loader.dismiss();
                } else {
                    this.loading.dismiss();
                }

                this.loader = undefined;
            }
        }, 300);
    }

}