import {Component, OnInit} from '@angular/core';
import {Transfer} from '../service/transfer';
import {Api} from '../service/api';
import {Load} from '../service/load';
import {ActivatedRoute} from '@angular/router';
import {flyIn} from '../animations/flyIn';
import {AlertController} from '@ionic/angular';
import {debug} from 'util';

@Component({
    selector: 'v-other',
    templateUrl: './other.page.html',
    styleUrls: ['./other.page.scss'],
    animations: [
        flyIn
    ]
})
export class OtherPage implements OnInit {
    value = [false, false, false, false, false, false, false];
    yewei;
    temp;
    proc;
    duration = 23;
    _inv;
    color;
    devices = [];
    fieldRegionNo = '';
    fieldRegionName = '';
    fieldRegionGroup = '';
    types = [];
    allBtns = [];


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

    state = {
        refreshState: {
            currentState: 'deactivate',
            drag: false
        },
        direction: '',
        endReachedRefresh: false,
        data: [],
        directionName: 'up'
    };

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

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

    commTmr: any;

    constructor(private tf: Transfer, private api: Api, private load: Load, private ac: ActivatedRoute,
                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.fieldRegionGroup = data.group;
        });

        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 === 0 ) {
                this.comm.isLoading = false;
            } else {
                this.comm.isLoading = true;
            }
        }, 1000) ;
    }

    // ionic的生命周期函数
    ionViewWillEnter() {
        this.getData(0);
    }

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

    unlock() {

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

        opt.startTime = opt.ts;
        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);
            }
        }]);
    }

    workModeEvent() {
        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.api.control.controlSwitch([opt, (data) => {
            if (data && data.code === 1) {
                this.getData(1);
                this.api.presentMsgToast(data.message);
            } else {
                this.api.presentMsgToast(data.message);
            }
        }]);
    }

    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;
        this.opChangeComfirm(a);

    }

    onLeftClick() {
        this.tf.transfer({url: '/home'});
    }

    initAllBtn() {
        if (this.fieldRegionGroup === '发酵池控制组') {
            this.allBtns = [];
        } else if (this.types.length === this.devices.length && this.devices.length === 2) {
            let v = 0;
            if (this.devices.filter(a => a.value).length === this.devices.length) {
                v = 1;
            }
            this.allBtns = [{l: '全部', v: v, d: false, t: 0}];
        } else {
            const obj = [];
            this.types.map((a) => {
                const c = {l: a, v: 0, d: false, t: a === '泵' ? 1 : 2};
                if (this.devices.filter(b => b.fieldDeviceType === a && b.value).length ===
                    this.devices.filter(b => b.fieldDeviceType === a).length) {
                    c.v = 1;
                }
                if (a !== '配置') {
                    obj.push(c);
                }

            });
            this.allBtns = obj;
        }
    }

    allCheck(a) {
        a.d = true;
        const req = {
            fieldRegionNo: this.fieldRegionNo,
            op: a.v ? 0 : 1,
            type: a.t,
            ts: parseInt((new Date().getTime() / 1000).toString(), 10)
        };
        this.comm.remain = 120;
        this.api.control.controlBatchSwitch([req, (data) => {
            if (data.code === 1) {
                this.getData(1);
                this.api.presentMsgToast(data.message);
            } else {
                this.api.presentMsgToast(data.message);
            }
            this.comm.remain = 0;
            a.d = false;
        }]);
    }

    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        this.api.app.getDeviceData([{fieldRegionNo: this.fieldRegionNo}, (data) => {
            if (data.constructor === Array) {
                this.devices = [];
                this.types = Array.from(new Set(data.map(a => a.fieldDeviceType)));
                // if (time) {
                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();
                    } 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 === '搅拌器' ) {
                            value.value = value.value & 0x1;
                            this.devices.push(value);
                        }
                    }
                });
                this.initAllBtn();
                // }
            } else {
                this.api.presentMsgToast(data.message || '获取数据失败');
            }
            this.load.offLoad();
        }]);

        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);
            }
        }]);
    }

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