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';
import {EventService} from '../../service/event';


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

    /* 风机 */
    // 牧场区域编号
    @Input() fieldRegionNo: any = '';
    // 操作模式
    @Input() operationModel: any = 0;
    // 在离线
    @Input() online: any = 1;

    // 牧场设备类型
    fieldDeviceType = '';
    // 模式状态
    controlModel = 0;

    // 是否在配置页中勾选风机
    enabled = 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, public alertController: AlertController,
                public loading: Loading, public eventService: EventService) {
        // this.ac.queryParams.subscribe((data) => {
        //     if (data && data.fieldRegionNo !== undefined && data.fieldRegionNo !== null && data.fieldRegionNo !== '') {
        //         this.fieldRegionNo = data.fieldRegionNo;
        //         this.operationModel = data.operationModel;
        //         this.online = data.online;
        //     }
        // });
    }

    ionViewWillEnter() {
        this.init();
    }

    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();
        // 订阅详情页【在离舍】开关
        this.eventService.event.on('inOutHouseController', () => {
            console.log('inOutHouseController');
            this.getData(0);
        });
    }

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

    init() {
        if (this.fieldRegionNo !== undefined && this.fieldRegionNo !== null && this.fieldRegionNo !== '') {
            this.getData(0);
        }
    }
    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        this.loading.presentLoading(Constants.LOADING_SHORTER, 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.enabled = data.enabled;

                this.initButtonOpen();
                this.initButtonDisable();
            }
            this.load.offLoad();
        }]);
    }

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

    initButtonDisable() {
        // 各个按钮表示状态
        let batchDisable = false;
        let oneDisable = false;
        this.api.cowshedApp.getRealDataByFieldRegionNo([{fieldRegionNo: this.fieldRegionNo}, (data) => {
            if (data && data.inHouse) {

                const online = +this.online; // 0-离线，1-在线
                const operationModel = +this.operationModel; // 0-现控，1-远控，4-混乱
                const inHouse = data.inHouse.inHouse ? +data.inHouse.inHouse : 0; // 0-离舍，1-在舍
                const enable = +this.enabled; // 配置页打钩
                const controlModel = this.controlModel;

                // 1.离线 2.在线&现控 3.在线&混乱
                if (online === 0 ||
                    (online === 1 && operationModel === 0) ||
                    (online === 1 && operationModel === 4)) {
                    batchDisable = true;
                    oneDisable = true;

                // 在线+远控
                } else if (online === 1 && operationModel === 1) {
                    // 4.在线+远控+离舍+配置页勾选
                    if (inHouse === 0 && enable === 1) {
                        batchDisable = true;
                        oneDisable = true;
                    } else if (inHouse === 0 && enable === 0) {
                        // 5.在线+远控+离舍+配置页未勾选+手控
                        if (controlModel === 1) {
                            batchDisable = false;
                            oneDisable = false;
                        // 6.在线+远控+离舍+配置页未勾选+自控
                        } else if (controlModel === 2) {
                            batchDisable = true;
                            oneDisable = true;
                        }
                    } else if (inHouse === 1) {
                        // 7.在线+远控+在舍+手控
                        if (controlModel === 1) {
                            batchDisable = false;
                            oneDisable = false;
                        // 8.在线+远控+在舍+自控
                        } else if (controlModel === 2) {
                            batchDisable = true;
                            oneDisable = true;
                        }
                    }
                }
                this.batchSwitch.disabled = batchDisable;
                this.devices.forEach((device) => {
                    device.disabled = oneDisable;
                });
            }
            this.loading.closeLoading();
        }]);
    }

    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',
            backdropDismiss: false,
            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 = 150;
        this.loading.presentLoading(Constants.LOADING_LONG, true);
        // 一键开启设备
        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(0);
                this.api.presentMsgToast(data.message);
            } else {
                this.getData(0);
                this.api.presentMsgToast(data.message);
            }
            this.loading.closeLoading();
            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 = 60;

        this.loading.presentLoading(Constants.LOADING_SHORT, true);

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