import {Component, Input, 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';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {Loading} from '../../service/loading';

@Component({
    selector: 'v-env-light',
    templateUrl: './env-light.page.html',
    styleUrls: ['./env-light.page.scss'],
})
export class EnvLightPage implements OnInit {
    /* 照明 */
    // 牧场区域编号
    fieldRegionNo = '';
    // 牧场设备类型
    fieldDeviceType = '';
    // 模式状态
    controlModel = 0;
    // 开始日期
    startDate = '';
    // 结束日期
    stopDate = '';
    // 开启时间
    on = '';
    // 关闭时间
    off = '';
    // 当前月份
    curDate = 0;

    // 各设备信息
    devices = [];
    // 一鍵控制信息
    batchSwitch = {op: undefined, type: undefined, load: undefined, 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 route: ActivatedRoute,
                private alertControlle: AlertController, public loading: Loading) {
    }

    ngOnInit() {
        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() {
    //     console.log('ionViewWillEnter_shower');
    //     this.init();
    // }

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

    init() {
        this.route.paramMap.subscribe(params => {
            this.fieldRegionNo = params.get('fieldRegionNo');
        });
        this.getData(0);
    }

    getData(time) {
        this.curDate = +new Date().getMonth() + 1;
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        this.api.cowshedApp.getZhaoMingData([{'fieldRegionNo': this.fieldRegionNo}, (data) => {
            if (data) {
                this.fieldRegionNo = data.fieldRegionNo;
                this.fieldDeviceType = data.fieldDeviceType;
                this.controlModel = data.controlModel;
                this.startDate = data.controlConfig.startDate;
                this.stopDate = data.controlConfig.stopDate;
                this.on = data.controlConfig.on;
                this.off = data.controlConfig.off;
                this.devices = data.param;
                this.devices.forEach(device => {
                    device.op = device.state === 1 ? true : false;
                });

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

    initButtons() {
        // // 智控:2
        // if (this.controlModel === 2) {
        //     this.batchSwitch.disabled = true;
        //     this.devices.forEach((device) => {
        //         device.disabled = true;
        //     });
        // } else if (this.controlModel === 1) {
        //     // 自控:1
        //     // 一键控制: 活性 其他按钮: 非活性
        //     this.batchSwitch.disabled = false;
        //     this.devices.forEach((device) => {
        //         device.disabled = true;
        //     });
        // } else {
        //     // 手控:0
        //     // 一键控制: 活性 其他按钮: 活性
        //     this.batchSwitch.disabled = false;
        //     this.devices.forEach((device) => {
        //         device.disabled = false;
        //     });
        // }

        if (this.controlModel === Constants.CONTROLL_REMOTR || this.controlModel === Constants.CONTROLL_SELF) {
            // 远控+自控 的场合
            // 一键控制: 活性
            this.batchSwitch.disabled = false;
            this.devices.forEach((device) => {
                device.disabled = false;
            });
        } else {
            // 其他
            // 一键控制: 非活性
            this.batchSwitch.disabled = false;
        }

        if (this.controlModel === Constants.CONTROLL_REMOTR) {
            // 远控 的场合
            // 子按钮: 活性
            this.devices.forEach((device) => {
                device.disabled = false;
            });
        } else {
            // 其他
            // 子按钮: 非活性
            this.devices.forEach((device) => {
                device.disabled = true;
            });
        }

        // 设置[一键控制]按钮(默认: 开启)
        // 当任意子按钮[关闭]的状态下: 关闭  以外:开启
        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 = '照明灯';
        const msgOp  = btn.op ? '关闭' : '打开';
        let msgContent = '';
        if (this.controlModel === Constants.CONTROLL_REMOTR) {
            msgContent = '所有' + msgHeader + '即将' + msgOp + '，要继续吗?';
        } else {
            msgContent = '确认要' + msgOp + '所有' + msgHeader + '，并且自动切换至手动模式吗?';
        }

        const alert = await this.alertControlle.create({
            header: '请注意',
            message: msgContent,
            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,
            op: btn.op ? 1 : 0,
            fieldDeviceType: this.fieldDeviceType,
            ts: parseInt((new Date().getTime() / 1000).toString(), 10)
        };
        // this.comm.remain = 150;
        this.loading.presentLoading(150);

        // 一键开启设备
        this.api.control.controlCowedBatchSwitch([req, (data) => {
            if (data.code === 1) {
                this.getData(1);
                this.api.presentMsgToast(data.message);
            } else {
                this.getData(0);
                this.api.presentMsgToast(data.message);
            }
            this.loading.closeLoading();
            this.comm.remain = 0;
            // this.getData(0);
            // this.api.presentMsgToast(data.message);
            // this.comm.remain = 0;
            btn.load = false;
        }]);

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

        // 自动控制时, 强制切换至手动模式
        this.controlModel = this.controlModel === Constants.CONTROLL_SELF ? Constants.CONTROLL_REMOTR : this.controlModel;
    }

    // 单个设备控制
    deviceCheck(btn) {
        btn.loading = true;
        const req = {
            fieldDeviceNo: btn.fieldDeviceNo,
            fieldDeviceType: this.fieldDeviceType,
            op: btn.op ? 0 : 1,
            ts: parseInt((new Date().getTime() / 1000).toString(), 10)
        };
        // this.comm.remain = 60;
        this.loading.presentLoading(80);
        this.api.control.controlCowedSwitch([req, (data) => {
            if (data && data.code === 1) {
                this.comm.remain = 0;
                this.api.presentMsgToast(data.message);
            } else {
                this.comm.remain = 0;
                this.api.presentMsgToast(data.message);
            }
            this.getData(0);
            this.loading.closeLoading();
            this.comm.remain = 0;
            btn.loading = false;
        }]);
    }

}
