import { AppEnvironment } from '@environments/AppEnvironment';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpHeaders } from "@angular/common/http";
import { Observable, of } from 'rxjs';
import { catchError, mergeMap } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

    constructor(private $router: Router) {

    }

    /**
     * 实现接口
     *
     * @param {HttpRequest<any>} req
     * @param {HttpHandler} next
     * @returns {Observable<HttpEvent<any>>}
     * @memberof HttpInterceptorService
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let authReq = req;
        let author = '';
        let url = req.url
        if (window.localStorage.getItem(AppEnvironment.AppName + '-token')) {
            const token = window.localStorage.getItem(AppEnvironment.AppName + '-token');
            author = `Bearer ${token}`;
        }
        if (!req.url.startsWith('https://') && !req.url.startsWith('http://')) {
            url = AppEnvironment.BaseUrl + url;
        }
        authReq = req.clone({
            url: url,
            headers: new HttpHeaders({
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8',
                'Authorization': author
            })
        });
        return next.handle(authReq).pipe(
            mergeMap((event: any) => {
                return Observable.create(observer => observer.next(event));
            }),
            catchError((res: HttpResponse<any>) => {
                return this.handleError(res);
            })
        );
    }

    /**
     * 错误处理
     *
     * @param {HttpResponse<any>} event
     * @returns {Observable<any>}
     * @memberof HttpInterceptorService
     */
    public handleError(event: HttpResponse<any>): Observable<any> {
        if (event.status === 401) {
            this.goLogin();
        }
        return of(event);
    }

    /**
     * 跳转登录页
     *
     * @memberof HttpInterceptorService
     */
    public goLogin() {
        const curUrl = decodeURIComponent(window.location.href);
        this.$router.navigate(['login'], { queryParams: { RU: curUrl } });
    }
}
