import { Injectable } from "@angular/core";
import {
    HttpErrorResponse,
    HttpEvent,
    HttpHandler,
    HttpInterceptor,
    HttpRequest,
    HttpResponse
} from "@angular/common/http";

import { Observable, of, throwError } from "rxjs";
import { catchError } from "rxjs/internal/operators";
import { App } from './App';
import { NavController } from '@ionic/angular';
import { AppEnvironment } from 'src/environments/AppEnvironment';

@Injectable()
export default class Interceptors implements HttpInterceptor {
    constructor(private $navCtrl: NavController, private $app: App) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.$app.getLoginKey()) {
            let newReq: any;
            //默认登陆方式  远程登录
            if (Object.is(AppEnvironment.LoginModel, 'default')) {
                newReq = req.clone({ url: req.url, headers: req.headers.set("loginkey", `${this.$app.getLoginKey()}`) });
            } else {
                newReq = req.clone({ url: req.url, headers: req.headers.set("Authorization", `Bearer ${this.$app.getLoginKey()}`) });
            }
            // if (req.body) {
            //     let  tempdata= req.body;
            //     Object.keys(tempdata).forEach((item: any) => {
            //         if (tempdata[item] && typeof tempdata[item] !== 'string') {
            //             tempdata[item] = JSON.stringify(tempdata[item]);
            //         }
            //     });
            //     newReq.clone({body:tempdata});
            // }
            return next.handle(newReq).pipe(
                catchError((err: HttpErrorResponse) => this.handleData(err))
            );
        } else {
            return next.handle(req).pipe(
                catchError((err: HttpErrorResponse) => this.handleData(err))
            );
        }

    }

    private handleData(
        event: HttpResponse<any> | HttpErrorResponse,
    ): Observable<any> {
        // 业务处理：一些通用操作
        switch (event.status) {
            case 401:
                console.log('not login');
                this.$navCtrl.navigateRoot(this.$app.getLoginPage());
                //return of(event);
                return Observable.create(event);
                break;
            default:
        }
        return throwError(event);
    }
}