import {Http} from './http';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {environment} from '../../environments/environment';
import {ToastController} from '@ionic/angular';
import {Load} from './load';

@Injectable()
export class Api {
    constructor(private http: Http, private router: Router, private toast: ToastController, private load: Load) {
    }

    tokenLoseflag = 0;
    public url = environment.url;
    private loadFlag = 1;

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

    public data = {
        getRealData: (data) => this.trans('post', '/data/getRealData', data),
        updateControl: (data) => this.trans('post', '/data/updateControl', data),
    };

    public app = {
        getAll: (data) => this.trans('get', '/app/getAll', data),
        getDeviceData: (data) => this.trans('post', '/app/getDeviceData', data),
        getLiquidLevelData: (data) => this.trans('post', '/app/getLiquidLevelData', data),
        getNorthSouthWaterData: (data) => this.trans('post', '/app/getNorthSouthWaterData', data),
    };

    public user = {
        addUser: (data) => this.trans('post', '/user/addUser', data),
        deleteUser: (data) => this.trans('post', '/user/deleteUser', data),
        getAll: (data) => this.trans('get', '/user/getAll', data),
        getByUserNameForLike: (data) => this.trans('post', '/user/getByUserNameForLike', data),
        updatePassword: (data) => this.trans('post', '/user/updatePassword', data),
        getSelfInfo: (data) => this.trans('get', '/user/getSelfInfo', data),
        updateUser: (data) => this.trans('post', '/user/updateUser', data),
    };

    public alarm = {
        addAlarmLog: (data) => this.trans('post', '/alarm/addAlarmLog', data),
        getAlarmByTerm: (data) => this.trans('post', '/alarm/getAlarmByTerm', data),
        getAllAlarm: (data) => this.trans('get', '/alarm/getAllAlarm', data),
        getLatestAlarm: (data) => this.trans('get', '/alarm/getLatestAlarm', 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 {
                    this.load.offLoad();
                    if (!this.tokenLoseflag) {
                        this.presentMsgToast('登录失效,请重新登陆');
                        this.http.toLoginPage(2000);
                        this.tokenLoseflag = 1;
                        setTimeout(() => {
                            this.tokenLoseflag = 0;
                        }, 5000);
                    }
                }
            };
        }
        if (!error) {
            error = (err) => {
                let data;
                if (err && err.error && err.error.status) {
                    if (err.error.status === 401) {
                        data = {code: 0, message: '用户尚未登录'};
                        this.router.navigate(['/extra']);
                    } else {
                        data = {code: 0, message: '服务器异常'};
                    }
                } else {
                    data = {code: 0, message: '服务器异常'};
                }
                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);
        }
    }

    async presentMsgToast(msg) {
        const toast = await this.toast.create({
            message: msg,
            duration: 2000,
            mode: 'ios',
            cssClass: 'msgToast'
        });
        toast.present();
    }

    async presentBtnToast(msg, btn, position) {
        const toast = await this.toast.create({
            message: msg,
            showCloseButton: true,
            position: position,
            closeButtonText: btn,
            mode: 'ios',
            cssClass: 'btnToast'
        });
        toast.present();
    }
}
