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

@Injectable()
export class Loading {
    constructor(public loadingController: LoadingController) {
    }

    loading: any;
    countdown = 0;
    interval: any;
    async presentLoading(time) {
        this.countdown = time;
        this.loading = await this.loadingController.create({
            mode: 'ios',
            spinner: 'circles',
            message: '通信中，还剩 ' + time + ' 秒',
            cssClass: 'main-color',
            duration: time * 1000
        });
        this.loading.present();
        this.interval = window.setInterval(() => {
            if (this.countdown > 0) {
                this.countdown--;
                this.loading.message = '通信中，还剩 ' + this.countdown + ' 秒';
            } else {
                this.loading.message = '';
            }
        }, 1000)

        const { role, data } = await this.loading.onDidDismiss();

        console.log('Loading dismissed!');
    }

    async closeLoading() {
        if (this.loading !== undefined || this.loading !== null) {
            this.loading.dismiss();
            this.loading.onDidDismiss();
            clearInterval(this.interval);
        }
    }
}
