import {JhiAlertService} from 'ng-jhipster';
import {HttpInterceptor, HttpRequest, HttpResponse, HttpHandler, HttpEvent} from '@angular/common/http';
import {Injector} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import {NzNotificationService} from 'ng-zorro-antd';

export class NotificationInterceptor implements HttpInterceptor {

    private alertService: JhiAlertService;

    // tslint:disable-next-line: no-unused-variable
    constructor(private injector: Injector, public notification: NzNotificationService) {
        setTimeout(() => this.alertService = injector.get(JhiAlertService));
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).do((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                if (event.status == 200) {
                    this.message(event.body);
                }
                const arr = event.headers.keys();  //返回头信息
            }
        }, (err: any) => {
        });
    }

    //正常：errCode = 10000
    message(data) {
        if (data && data.errCode) {
            const errCode = data.errCode;
            const errMsg = data.errMsg;
            if (errCode && errCode != 10000 && errCode != 10099) {
                this.notification.create('error', `错误码:${errCode}`, `${errMsg}`, {nzDuration: 2000});
            }
        }
    }
}
