import {JhiEventManager} from 'ng-jhipster';
import {HttpInterceptor, HttpRequest, HttpErrorResponse, HttpHandler, HttpEvent} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import {NzMessageService, NzNotificationService} from 'ng-zorro-antd';

export class ErrorHandlerInterceptor implements HttpInterceptor {

    constructor(private eventManager: JhiEventManager, private message: NzMessageService,
                public notification: NzNotificationService) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).do((event: HttpEvent<any>) => {
        }, (err: any) => {
            if (err instanceof HttpErrorResponse) {
                this.messageInfo(err);
            }
        });
    }

    messageInfo(err) {
        const status = err.status;
        switch (status) {
            case 401:
                this.notification.create('error', '错误', '登录状态已过期,错误码: 401', {nzDuration: 2000});
                break;
            case 404:
                this.notification.create('error', '错误', `请求接口不存在,错误码: 404`, {nzDuration: 2000});
                break;
            case 500:
                this.notification.create('error', '错误', `服务器错误,错误码: 500`, {nzDuration: 2000});
                break;
            case 502:
                this.notification.create('error', '错误', `网络错误,错误码: 502`, {nzDuration: 2000});
                break;
        }
    }
}
