import {Component, OnInit, HostBinding} from '@angular/core';
import {Transfer} from '../service/transfer';
import {Api} from '../service/api';
import {Load} from '../service/load';
import {ActivatedRoute} from '@angular/router';
import {animate, state, style, transition, trigger} from '@angular/animations';
import {fadeIn} from '../animations/fade-in';
import {toLeft} from '../animations/toLeftAndBack';
import {flyIn} from '../animations/flyIn';
import {AlertController, NavController} from '@ionic/angular';

@Component({
    selector: 'v-east',
    templateUrl: './east.page.html',
    styleUrls: ['./east.page.scss'],
    animations: [
        // trigger('toLeft', [
        //     state('toLeft', style({
        //         'transform': 'translateX(-80px)'
        //     })),
        //     state('backLeft', style({
        //         'transform': 'translateX(0)'
        //     })),
        //     transition('toLeft => backLeft', animate('1150ms')),
        //     transition('backLeft => toLeft', animate('1150ms'))
        // ] )
        flyIn
    ]
})
export class EastPage implements OnInit {
    value = [];
    yewei;
    temp;
    proc = 0;
    duration = 23;
    nanClicked = false;
    beiClicked = false;
    nanLoading = false;
    beiLoading = false;
    _inv;
    color;
    nb = [];
    devices = [];
    fieldRegionNo = '';
    fieldRegionName = '';
    opDisable = true;

    // 发送指令延时判断
    comm = {
        remain : 20,
        isLoading : true
    };

    // 工作模式
    workModeSetting = {  'workMode' : '1',
                         'DeviceNo' : '',
                         'workModeOld' : '1'};

    // 运行时间过长,解除报警用
    alarmMsg = { locked : false,
        DeviceNo : ''};

    // workModeSetting = {  'workMode' : '1',
    //                      'DeviceNo':'' };

    workMode = '1';
    EnterLeave = 'flyIn';
    commTmr: any;

    @HostBinding('style.display')   display = 'block';
    // @HostBinding('style.position')  position = 'absolute';

    constructor(private tf: Transfer, private api: Api, private load: Load, private ac: ActivatedRoute, private nav: NavController,
                private alterContoller: AlertController) {
    }

    ngOnInit() {
        this.comm.isLoading = false;
        this.comm.remain = 0;
        this.ac.queryParams.subscribe((data) => {
            this.fieldRegionNo = data.no;
            this.fieldRegionName = data.name;
        });

        this.commTmr = window.setInterval(() => {
            console.log(this.comm.remain);

            if (this.comm.remain > 0) {
                this.comm.remain = this.comm.remain - 1;
            }

            if ( this.comm.remain < 1 ) {
                this.comm.isLoading = false;
            } else {
                this.comm.isLoading = true;
            }
        }, 1000) ;
    }

    unlock() {

        const opt = {fieldDeviceNo : this.alarmMsg.DeviceNo ,
            op : 1 ,
            startTime: parseInt((new Date().getTime() / 1000).toString(), 10),
            ts: parseInt((new Date().getTime() / 1000).toString(), 10)
        };

        opt.startTime = opt.ts;
        this.comm.remain = 20;
        this.api.control.controlSwitch([opt, (data) => {
            if (data && data.code === 1) {
                this.getData(1);
                this.api.presentMsgToast(data.message);
                this.alarmMsg.locked = false;
            } else {
                this.api.presentMsgToast(data.message);
            }
            this.comm.remain = 0;
        }]);
    }

    workModeEvent() {

        console.log(this.workMode);
        if ( this.workModeSetting.workModeOld === this.workModeSetting.workMode ) {
            return;
        }

        const opt = {fieldDeviceNo : this.workModeSetting.DeviceNo ,
                    op : this.workModeSetting.workMode ,
                    startTime: parseInt((new Date().getTime() / 1000).toString(), 10),
                     ts: parseInt((new Date().getTime() / 1000).toString(), 10)
                    };

        opt.startTime = opt.ts;

        this.comm.remain = 20;
        this.api.control.controlSwitch([opt, (data) => {
            if (data && data.code === 1) {
                this.getData(1);
                this.api.presentMsgToast(data.message);
            } else {
                this.api.presentMsgToast(data.message);
            }

            if ( this.workModeSetting.workMode !== '2' ) {
                this.opDisable = false;
            }

            this.comm.remain = 0;
        }]);
    }

    // ionic的生命周期函数
    ionViewWillEnter() {
        this.nanClicked = false;
        this.beiClicked = false;
        this.nanLoading = false;
        this.beiLoading = false;
        this.getData(0);
    }

    ionViewWillLeave() {
        clearTimeout(this._inv);
        clearInterval(this.commTmr);
    }

    toggleNb(index) {
        if (!(this.beiLoading || this.nanLoading || this.value[0] || this.value[1])) {
            if (index === 0) {
                this.nanClicked = true;
                this.nanLoading = true;
            } else if (index === 1) {
                this.beiClicked = true;
                this.beiLoading = true;
            }
        } else if (this.value[index]) {
            this.confirm(this.nb[index]);
        }
    }

    // toggle(a) {
    //     a.loading = true;
    //     const req = {
    //         fieldDeviceNo: a.fieldDeviceNo,
    //         op: a.value ? 0 : 1,
    //         ts: parseInt((new Date().getTime() / 1000).toString(), 10)
    //     };
    //     this.comm.remain = 20;
    //     this.api.control.controlSwitch([req, (data) => {
    //         if (data && data.code === 1) {
    //             this.getData(1);
    //             this.api.presentMsgToast(data.message);
    //         } else {
    //             this.api.presentMsgToast(data.message);
    //         }
    //         this.comm.remain = 0;
    //         a.loading = false;
    //     }]);
    // }


    async opChangeComfirm(a) {
        const msgHeader = a.fieldDeviceName;
        const msgOp  = a.value ? '关闭' : '打开';
        const alert = await this.alterContoller.create({
            header: '请注意',
            // subHeader: '确定要' + msgOp + ' ' + msgHeader + ' 这个泵吗?',
            message: '确定要' + msgOp + ' ' + msgHeader + ' 吗?',
            mode: 'ios',
            buttons: [
                {
                    text: '取消',
                    cssClass: 'width: 40%',
                }, {
                    text: '确定',
                    cssClass: 'width: 40%',
                    handler: () => {
                        const req = {
                            fieldDeviceNo: a.fieldDeviceNo,
                            op: a.value ? 0 : 1,
                            ts: parseInt((new Date().getTime() / 1000).toString(), 10)
                        };
                        this.comm.remain = 20;
                        this.api.control.controlSwitch([req, (data) => {
                            if (data && data.code === 1) {
                                this.getData(1);
                                this.comm.remain = 0;
                                this.api.presentMsgToast(data.message);
                            } else {
                                this.comm.remain = 0;
                                this.api.presentMsgToast(data.message);
                            }
                            a.loading = false;
                        }]);
                    }
                }
            ]
        });

        await alert.present();
    }

    toggle(a) {
        // a.loading = true;
        if ( this.opDisable === false) {
            this.opChangeComfirm(a);
        }
    }

    cancel() {
        this.nanClicked = false;
        this.beiClicked = false;
        this.nanLoading = false;
        this.beiLoading = false;
    }

    confirm(a) {
        const req = a.value ? {
            fieldDeviceNo: a.fieldDeviceNo,
            op: 0,
            startTime: parseInt((new Date().getTime() / 1000).toString(), 10),
            ts: parseInt((new Date().getTime() / 1000).toString(), 10)
        } : {
            fieldDeviceNo: a.fieldDeviceNo,
            op: 1,
            duration: this.duration,
            startTime: parseInt((new Date().getTime() / 1000).toString(), 10),
            ts: parseInt((new Date().getTime() / 1000).toString(), 10)
        };
        this.comm.remain = 20;
        this.api.control.controlSwitch([req, (data) => {
            if (data && data.code === 1) {
                this.getData(1);
                this.api.presentMsgToast(data.message);
            } else {
                this.api.presentMsgToast(data.message);
            }
            this.cancel();
            this.comm.remain = 0;
        }]);
    }

    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }


        this.api.app.getLiquidLevelData([{fieldRegionNo: this.fieldRegionNo}, (data) => {
            if (typeof (data.liquidLevel) === 'number') {
                this.yewei = Number(data.liquidLevel) < 0 ? 0 : Number(data.liquidLevel);
                this.proc = Number(data.liquidLevel) < 0 ? 0 : (Number(data.liquidLevel) / (Number(data.liquidLevelMax) * 1.5)) > 1
                    ? 100 : (Number(data.liquidLevel) / (Number(data.liquidLevelMax) * 1.5)) * 100;
                this.color = Number(data.liquidLevel) > Number(data.liquidLevelMax) ||
                Number(data.liquidLevel) < Number(data.liquidLevelMin) ? 'red' : '';
            }
            if (typeof (data.temp) === 'number') {
                this.temp = Number(data.temp);
            }
        }]);

        this.api.app.getNorthSouthWaterData([{fieldRegionNo: this.fieldRegionNo}, (data) => {
            if (data.constructor === Array) {
                this.nb = data;
                this.value = this.nb.map(a => a.value);
            } else {
                this.api.presentMsgToast(data.message || '获取数据失败');
            }
        }]);

        this.api.app.getDeviceData([{fieldRegionNo: this.fieldRegionNo}, (data) => {
            if (data.constructor === Array) {
                this.devices = [];
                this.alarmMsg.locked = false;
                data.forEach((value, i) => {
                    if ( value.fieldDeviceType === '配置' && value.fieldDeviceName === '运行模式') {
                        this.workModeSetting.workMode = value.value === null ? '1' : value.value.toString();
                        this.workModeSetting.DeviceNo = value.fieldDeviceNo;
                        this.workModeSetting.workModeOld = value.value === null ? '1' : value.value.toString();

                        if ( this.workModeSetting.workMode !== '2' ) {
                            this.opDisable = false;
                        }
                    } else if ( value.fieldDeviceType === '配置' && value.fieldDeviceName === '解除报警') {
                        this.alarmMsg.DeviceNo = value.fieldDeviceNo;
                        // this.alarmMsg.locked = value.value === 1 ? true : false;
                    } else {
                        if ( value.fieldDeviceType === '泵' || value.fieldDeviceType === '搅拌器' ) {
                            if ( this.checkBit(value.value, 6) === true ) {
                                this.alarmMsg.locked = true;
                            }
                        }
                        value.value = value.value & 0x1;
                        this.devices.push(value);
                    }
                }
            );
            } else {
                this.api.presentMsgToast(data.message || '获取数据失败');
            }
            this.load.offLoad();
        }]);

    }

    checkBit( a, bit ) {
        a = a & 0x40;
        if ( a ) {
            return true;
        } else {
            return false;
        }
    }

    pullToRefresh() {
        this.getData(1);
    }
}
