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 {NzMessageService} from "ng-zorro-antd/message";
import {USER_TOKEN} from "../data/login/localStorage.namespace";
import {BrowserStorageService} from "./localStorage.service";


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

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

  jumpError(message: string , status: number) {
    // this.router.navigateByUrl('/error/500');

  }
}
