import {AlertController, App, Events} from 'ionic-angular';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Storage} from '@ionic/storage';

import {Observable} from 'rxjs';
import {_throw} from 'rxjs/observable/throw';
import {CommonService} from "./common.service";
import {GlobalData} from "./GlobleData";

/**
 * http拦截器  增加token信息
 */

@Injectable()
export class InterceptorProvider implements HttpInterceptor {

    constructor(private storage: Storage, private alertCtrl: AlertController, private events: Events,
                private commonSer: CommonService, private app: App,
                private globle: GlobalData) {
    }

    // Intercepts all HTTP requests!
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const data = this.storage.get('');
        return Observable.fromPromise(data)
            .mergeMap(data => {
                let clonedReq = this.addToken(request, data);
                return next.handle(clonedReq).do(res => {
                    if (res instanceof HttpResponse) {
                        this.message(res.body);
                    }
                }, (error) => {
                    let msg = error.message;
                    this.errorMessage(error);
                    // Pass the error to the caller of the function
                    return _throw(error);
                }, () => {
                })
            });
    }

    // Adds the token to your headers if it exists
    private addToken(request: HttpRequest<any>, token: any) {
        let body;
        if (request.method == "POST") {
            body = Object.assign(request.body, {});
            if (this.globle.token) {
                body = Object.assign(body, {"token": this.globle.token});
            }
            if (this.globle.userObj && this.globle.userObj.userid) {
                body = Object.assign(body, {"userid": this.globle.userObj.userid});
            }
        }
        if (token) {
            let clone: HttpRequest<any>;
            if (request.method == "POST") {
                clone = request.clone({
                    setHeaders: {
                        // "Accept": `application/json`,
                        'Content-Type': `application/json;charset=UTF-8`,
                    },
                    body: body
                });
            } else {
                clone = request.clone({
                    setHeaders: {
                        // "Accept": `application/json`,
                        'Content-Type': `application/json;charset=UTF-8`,
                    },
                });
            }
            return clone;
        }
        return request;
    }

    //code message
    message(data) {
        if (data.code) {
            let code = data.code;
            if (code == "401") {
                this.commonSer.toast("登录已过期");
                this.storage.clear();
                this.events.publish('toLogin');
            } else if (code == "-1") {
                let alert = this.alertCtrl.create({
                    title: "提示",
                    message: `${data.msg}。`,
                    // message: `网络错误`,
                    buttons: ['确定']
                });
                alert.present();
            }
            if (code == 500) {
                let alert = this.alertCtrl.create({
                    title: "提示",
                    message: `${data.msg}。`,
                    buttons: ['确定']
                });
                alert.present();
            }
        }
    }

    //error message
    errorMessage(data) {
        if (data.status) {
            let code = data.status;
            if (code != 200) {
                let alert = this.alertCtrl.create({
                    title: "错误",
                    message: `错误码:${code}。`,
                    buttons: ['确定']
                });
                alert.present();
            }

        }
    }
}
