import {Component, Input, OnInit} from '@angular/core';
import {Api} from '../../service/api';
import {ActivatedRoute} from '@angular/router';
import {Load} from '../../service/load';
import {Constants} from '../../service/constants';
import {Loading} from '../../service/loading';
import {EventService} from '../../service/event';

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

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

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

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

    commTmr: any;

    // 牧场设备类型
    fieldDeviceType = '';
    // 模式状态
    controlModel = 0;
    // 供液泵状态
    bump = {alarm: 0, press: 0};
    // 时间参数
    controlConfig = {
        name: '',
        interval: 0, // 间隔时间
        a: 0, // A区喷淋时间
        t: 0,
        b: 0, // A区喷淋时间
        offset: 0
    };

    // 是否在配置页中勾选喷淋
    enabled = 0;
    // 各设备信息
    param: any = [{
            fieldDeviceNo: '',
            fieldDeviceName: '',
            alarm: 0,
            cycle: 0,
            state: 0,
            press: 0.25,
            ts: 0
        },
        {
            fieldDeviceNo: '',
            fieldDeviceName: '',
            alarm: 0,
            cycle: 0,
            state: 0,
            press: 0.25,
            ts: 0
        }];
    fieldDeviceNameA = 'A区';
    fieldDeviceNameB = 'B区';

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

    constructor(private api: Api, private ac: ActivatedRoute, private load: Load, private route: ActivatedRoute,
                public loading: Loading, public eventService: EventService) {
        this.param[0].fieldDeviceName = 'A区';
        this.param[1].fieldDeviceName = 'B区';
        // this.route.paramMap.subscribe(params => {
        //     this.fieldRegionNo = params.get('fieldRegionNo');
        //     this.getData(0);
        // });
    }

    ionViewWillEnter() {
        this.init();
    }

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

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

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

    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        this.loading.presentLoading(Constants.LOADING_SHORTER, false);
        this.api.cowshedApp.getPenLinData([{fieldRegionNo: this.fieldRegionNo}, (data) => {
            if (data && data.fieldRegionNo) {
                this.fieldRegionNo = data.fieldRegionNo;
                this.fieldDeviceType = data.fieldDeviceType;
                this.controlModel = data.controlModel;
                this.bump = data.bump;
                this.bump.press = this.getPress(data.bump.press);
                this.controlConfig = data.controlConfig;
                this.param = data.param;
                this.param.forEach(device => {
                    device.op = device.cycle === 1 ? true : false;
                    device.press = this.getPress(device.press);
                });

                if (this.param[0]) {
                    this.fieldDeviceNameA = this.param[0].fieldDeviceName;
                }
                if (this.param[1]) {
                    this.fieldDeviceNameB = this.param[1].fieldDeviceName;
                }

                this.enabled = data.enabled;

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

    getPress(param) {
        if (param === undefined || param === null || param < 0) {
            return 0;
        }
        return param;
    }

    initButtonDisable() {
        // 自控状态下 设备全部为打开状态
        // if (this.controlModel === Constants.CONTROLL_SELF || this.controlModel === Constants.CONTROLL_WISDOM) {
        //     this.param.forEach((device) => {
        //         // 自控的场合  小按钮打开
        //         device.op = true;
        //     });
        // }
        // 各个按钮表示状态
        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;

                // 5.在线+远控+离舍+配置页未勾选+手控 或者
                // 7.在线+远控+在舍+手控 的场合 活性
                // 以外 非活性
                // 1.离线 2.在线&现控 3.在线&混乱
                if ((online === 1 && operationModel === 1 && inHouse === 0 && enable === 0 && controlModel === 1) ||
                    (online === 1 && operationModel === 1 && inHouse === 1 && controlModel === 1)) {
                    oneDisable = false;
                } else {
                    oneDisable = true;
                }
                this.param.forEach((device) => {
                    // 远控的场合  小按钮活性(disabled = false)
                    device.disabled = oneDisable;
                });
            }
            this.loading.closeLoading();
        }]);
    }

    resetButtons() {
        this.api.cowshedApp.getRealDataByFieldRegionNo([{fieldRegionNo: this.fieldRegionNo}, (data) => {
            if (data && data.inHouse) {
                const inHouse = data.inHouse.inHouse;
                const isInHouse = inHouse === 0; // 离舍-0 在舍-1
                // 离舍的场合,配置页被勾选: 所有按钮非活性
                if (isInHouse && this.enabled) {
                    console.log('离舍时,开关非活性');
                    this.param.forEach((device) => {
                        device.disabled = isInHouse;
                    });
                }
            }
            this.loading.closeLoading();
        }]);
    }

    // 单个设备控制
    deviceCheck(btn) {
        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(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;
            // this.api.presentMsgToast(data.message);
            btn.loading = false;
        }]);
    }

    setConfusionModelControll() {
        // 混乱模式
        if (+this.operationModel === Constants.CONTROLL_CONFUSION) {
            this.param.forEach((device) => {
                device.disabled = true;
            });
        }
    }
}
