import {
  HttpInterceptor,
  HttpEvent,
  HttpHandler,
  HttpRequest,
  HttpResponse,
} from "@angular/common/http";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
// const ignoreToken = ['login', 'logout', 'table'];
export class HttpInterceptorService implements HttpInterceptor {
  constructor(private router: Router, private message: NzMessageService) {}
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // const url = req.url;
    // const needToken = ignoreToken.filter(u => url.match(u));
    // 过滤掉不需要token的请求
    // if (!needToken.length) {
    //   req = req.clone({
    //     url
    //   });
    // } else {
    //   req = req.clone({
    //     url,
    //     headers: req.headers.set('token', 'asdqwe')
    //   });
    // }
    return next.handle(req).pipe(
      tap(
        (event) => {
          if (event instanceof HttpResponse) {
            // console.log(event);
            if(event.body == 520){
              this.message.info('登录失效，请重新登录！').onClose!.subscribe(() => {
                localStorage.removeItem("user");
                localStorage.removeItem("menu");
                localStorage.removeItem("index");
                this.router.navigate(['/login']);
              })
            }
          }
        },
        (error) => {
          console.log(error);
        }
      )
    );
  }
}
