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 cowshedApp = {
        // 牛舍首页查询
        getAllRegionData: (data) => this.trans('get', '/cowshedApp/getAll', data),
        // 根据牛舍名称查询牛舍信息
        getAllForLike: (data) => this.trans('post', '/cowshedApp/getAllForLike', data),
        // 获取牛舍的基本信息
        getRealDataByFieldRegionNo: (data) => this.trans('post', '/cowshedApp/getRealDataByFieldRegionNo', data),
        // 获取风机信息
        getFengJiData: (data) => this.trans('post', '/cowshedApp/getFengJiData', data),
        // 获取喷淋信息
        getPenLinData: (data) => this.trans('post', '/cowshedApp/getPenLinData', data),
        // 获取照明信息
        getZhaoMingData: (data) => this.trans('post', '/cowshedApp/getZhaoMingData', data),
        // 获取水槽信息
        getShuiCaoData: (data) => this.trans('post', '/cowshedApp/getShuiCaoData', data),

        // 获取当前牛舍历史数据信息 TODO 追加待
        // getShuiCaoData: (data) => this.trans('post', '/cowshedApp/getShuiCaoData', data),
    };

    public alert = {
        // 获取告警列表的数据
        getAll: (data) => this.trans('post', '/alert/getAll', data),
        // 获取告警列表的数据
        getByTerm: (data) => this.trans('post', '/alert/getByTerm', data),

    }

    public  troubleLog = {
        // 根据条件获取所有的故障信息
        getByTerm: (data) => this.trans('post', '/troubleLog/getByTerm', data),
        // /处理故障
        processingFailure: (data) => this.trans('post', '/troubleLog/processingFailure', 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),
        getByTerm: (data) =>  this.trans('post', '/alarm/getByTerm', data),
        getCowshedAlarm: (data) =>  this.trans('post', '/alarm/getCowshedAlarm', data),
        getLatestAlarm: (data) => this.trans('get', '/alarm/getLatestAlarm', data)
    };

    public control = {
        controlBatchSwitch: (data) => this.trans('post', '/control/controlBatchSwitch', data),
        controlSwitch: (data) => this.trans('post', '/control/controlSwitch', data),
    };

    public config = {
        getAll: (data) => this.trans('post', '/cowshedConfig/getAll', data),
        updateCowshedConfig: (data) => this.trans('post', '/cowshedConfig/updateCowshedConfig', data),
    };

    public devicePatternModel = {
        getByFactoryNoAndType: (data) => this.trans('post', '/devicePatternModel/getByFactoryNoAndType', data),
        addDevicePatternModel: (data) => this.trans('post', '/devicePatternModel/addDevicePatternModel', data),
        updateDevicePatternModel: (data) => this.trans('post', '/devicePatternModel/updateDevicePatternModel', data),
        deleteDevicePatternModel: (data) => this.trans('post', '/devicePatternModel/deleteDevicePatternModel', 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') {
            nextFunc = (data: any) => {
                next(data);
            };
        } else {
            nextFunc = (data: any) => {
                if (this.http.handleToken(data)) {
                    next(data);
                } else {
                    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, wz?, t?) {
        const toast = await this.toast.create({
            message: msg,
            duration: t ? t : 5000,
            mode: 'ios',
            cssClass: 'msgToast',
            position: wz ? wz : 'top'
        });
        toast.present();
    }

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

    formatTime(fmt, time) {
        const o = {
            'M+': time.getMonth() + 1, // 月份
            'd+': time.getDate(), // 日
            'h+': time.getHours(), // 小时
            'm+': time.getMinutes(), // 分
            's+': time.getSeconds(), // 秒
            'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
            'S': time.getMilliseconds() // 毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (const k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
            }
        }
        return fmt;
    }
}
