import { HttpService } from './http.service';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from '../../environments/environment';

@Injectable()
export class ApiService {
    constructor(private http: HttpService, private router: Router) {
    }

    tokenLoseflag = 0;
    public url = environment.url;

    public login = {
        dologin: (data) => this.trans('post', '/login/dologin', data),
        logout: (data) => this.trans('get', '/login/logout', data),
    };

    private trans(type, addr, data) {
        this.sendHttpReq(type, addr, data[0], data[1], data[2], data[3]);
    }

    private sendHttpReq(type, addr, reqB, next, error, complete) {
        let nextFunc;
        if (addr === '/login/dologin') {
            nextFunc = (data: any) => {
                next(data);
            };
        } else {
            nextFunc = (data: any) => {
                if (this.http.handleToken(data)) {
                    next(data);
                } else {
                    if (!this.tokenLoseflag) {
                        // this.message.error(this.translate.instant('loginOutValidityTips'));
                        this.http.toLoginPage(2000);
                        this.tokenLoseflag = 1;
                        setTimeout(() => {
                            this.tokenLoseflag = 0;
                        }, 5000);
                    }
                }
            };
        }
        if (!error) {
            error = (err) => {
                // const data;
                if (err && err.error && err.error.status) {
                    if (err.error.status === 401) {
                        // data = {code: 0, message: this.translate.instant('noLoginTips')};
                        this.router.navigate(['/extra']);
                    } else {
                        // data = {code: 0, message: this.translate.instant('wrongServerWithCode') + err.error.status};
                    }
                } else {
                    // data = {code: 0, message: this.translate.instant('wrongServer')};
                }
                // next(data);
            };
        }
        if (type === 'get') {
            this.http.get(this.url + addr, nextFunc, error, complete);
        } else {
            this.http.post(this.url + addr, reqB, nextFunc, error, complete);
        }
    }
}
