import {Injectable} from '@angular/core';
import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpHeaders
} from '@angular/common/http';
import {catchError, finalize} from 'rxjs/operators';
import {mergeMap} from 'rxjs/operators';
import {Observable} from 'rxjs';
import {Router} from '@angular/router';
import {LocalStorageService} from './local-storage.service';
import {TOKEN} from './local-storage.namespace';
import {NzMessageService} from 'ng-zorro-antd/message';

@Injectable()
export class InterceptorService implements HttpInterceptor {
    constructor(
        private message: NzMessageService,
        private router: Router,
        private storage: LocalStorageService,
        ) {
  }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let secureReq: HttpRequest<any>;
        let modifiedHeaders: HttpHeaders;
        const token = this.storage.get(TOKEN);
        if (token != null) {
          modifiedHeaders = req.headers.set('Authorization', token);
        }

        secureReq = req.clone({
            url: req.url,
            headers: modifiedHeaders
        });
        // @ts-ignore
        return next.handle(secureReq)
            .pipe(
                catchError((res: HttpResponse<any>) => {
                    let msg = '';
                    console.log(res);
                    switch (res.status) {
                        case 401:
                            msg = '身份验证过期，请重新进入页面';
                            break;
                        case 200:
                            msg = '身份验证过期，请重新进入页面';
                            break;
                        case 404:
                            msg = '找不到地址';
                            break;
                        case 403:
                            msg = '业务错误';
                            break;
                        case 500:
                            msg = '服务器发生错误，请重试';
                            break;
                    }
                    this.showError(msg);
                    return Observable.create(res);
                }),
                finalize(() => {
                }),
                mergeMap(
                    // 有响应时成功;忽略其他事件
                    (event: any) => {

                        if (event.body != null) {
                            if (event.body.return_code === '204001') {
                                // this.router.navigateByUrl('/error/500');
                            }
                        }
                        if (event.status === 200) {
                            this.message.remove();
                        }
                        return Observable.create(observer => observer.next(event));
                    }),
            );
    }

    showError(message: string) {
        // this.router.navigateByUrl('/error/500');
        this.message.remove();
        this.message.error(message, {nzDuration: 2000});
    }
}
