    import { Component, OnInit } from '@angular/core';
import {Api} from '../../service/api';
import {ActivatedRoute} from '@angular/router';
import {Load} from '../../service/load';
import { AlertController } from '@ionic/angular';
    import {Constants} from '../../service/constants';

@Component({
  selector: 'v-env-fan',
  templateUrl: './env-fan.page.html',
  styleUrls: ['./env-fan.page.scss'],
})
export class EnvFanPage implements OnInit {

    /* 风机 */
    // 牧场区域编号
    fieldRegionNo = '';
    // 牧场设备类型
    fieldDeviceType = '';
    // 模式状态
    controlModel = 0;

    // 各设备信息
    devices = [];
    // 一鍵控制按钮
    batchSwitch = {op: false, type: undefined, load: false, disabled: undefined};

    controlModelOptions = [
        {modelId: 0, modelValue: '-'},
        {modelId: 1, modelValue: '手控模式'},
        {modelId: 2, modelValue: '自控模式'},
        {modelId: 3, modelValue: '智控模式'}];

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

    commTmr: any;

    constructor(private api: Api, private ac: ActivatedRoute, private load: Load, private alertController: AlertController) { }

    ngOnInit() {
        // this.ionViewWillEnter();
        this.comm.remain = 0;
        this.comm.isLoading = false;
        this.commTmr = window.setInterval(() => {

            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) ;
        this.init();
    }

    // ionViewWillEnter() {
    //
    // }

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

    init() {
        this.ac.queryParams.subscribe((data) => {
            this.fieldRegionNo = data.no;
            this.getData(0);
        });
    }
    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        this.api.cowshedApp.getFengJiData([{fieldRegionNo: this.fieldRegionNo}, (data) => {
            if (data && data.fieldRegionNo) {
                this.fieldRegionNo = data.fieldRegionNo;
                this.fieldDeviceType = data.fieldDeviceType;
                this.controlModel = data.controlModel;
                this.devices = data.param;
                this.devices.forEach(device => {
                    device.op = device.state === 1;
                });

                this.initButtons();
            }
            this.load.offLoad();
        }]);
    }

    initButtons() {
        // 各个按钮表示状态
        // 一键控制 远控的场合,活性(Disabled = false)
        const allDisabled = !(this.controlModel === Constants.CONTROLL_REMOTR);
        this.batchSwitch.disabled = allDisabled;
        this.devices.forEach((device) => {
            device.disabled = allDisabled;
        });

        // [一键控制]按钮(默认: 开启)
        // 当任意子按钮[关闭]的状态下: 关闭  以外:开启
        this.batchSwitch.op = true;
        this.devices.map((device) => {
            if (device.op === false) {
                this.batchSwitch.op = false;
            }
        });
    }

    toggle(btn) {
        this.opChangeComfirm(btn);
    }

    async opChangeComfirm(btn) {
        const msgHeader = this.fieldDeviceType;
        const msgOp  = btn.op ? '关闭' : '打开';
        const alert = await this.alertController.create({
            header: '请注意',
            // subHeader: '确定要' + msgOp + ' ' + msgHeader + ' 这个泵吗?',
            message: '所有' + msgHeader + '即将' + msgOp + '，要继续吗?',
            mode: 'ios',
            buttons: [
                {
                    text: '取消',
                    cssClass: 'width: 40%',
                    handler: () => {
                        this.batchSwitch.op = !btn.op;
                        event.preventDefault();
                    }
                }, {
                    text: '确定',
                    cssClass: 'width: 40%',
                    handler: () => {
                        this.allCheck(btn);
                    }
                }
            ]
        });
        await alert.present();
    }

    // 一键控制
    allCheck(btn) {
        btn.load = true;
        const req = {
            fieldRegionNo: this.fieldRegionNo,
            fieldDeviceType: this.fieldDeviceType,
            op: btn.op ? 1 : 0,
            ts: parseInt((new Date().getTime() / 1000).toString(), 10)
        };
        this.comm.remain = 120;

        // 一键开启设备
        this.api.control.controlCowedBatchSwitch([req, (data) => {
            // if (data.code === 1) {
            //     // 子按钮状态
            //     this.devices.forEach((device, i) => {
            //         device.state = btn.op ? 0 : 1;
            //     });
            // }
            // this.api.presentMsgToast(data.message);
            // this.getData(1);
            if (data.code === 1) {
                this.getData(1);
                this.api.presentMsgToast(data.message);
            } else {
                this.getData(0);
                this.api.presentMsgToast(data.message);
            }
            this.comm.remain = 0;
            btn.load = false;
        }]);

        // 子按钮状态
        this.devices.forEach((device) => {
            device.state = btn.op ? 1 : 0;
            device.op = btn.op;
        });
    }

    // 单个设备控制
    deviceCheck(btn) {
        // btn.load = true;
        const req = {
            fieldDeviceNo: btn.fieldDeviceNo,
            fieldDeviceType: this.fieldDeviceType,
            op: btn.op ? 0 : 1,
            ts: new Date().valueOf()
        };
        this.comm.remain = 20;
        this.api.control.controlCowedSwitch([req, (data) => {
            if (data && data.code === 1) {
                this.getData(1);
                this.api.presentMsgToast(data.message);
            } else {
                this.getData(0);
                this.api.presentMsgToast(data.message);
            }
            this.comm.remain = 0;
        }]);
    }
}
