import {Component, OnInit, ViewChild} from '@angular/core';
import {Api} from '../../service/api';
import {NavController, Platform} from '@ionic/angular';
import {ActivatedRoute} from '@angular/router';
import {Load} from '../../service/load';
import {Transfer} from '../../service/transfer';
import {Loading} from '../../service/loading';
import {Constants} from '../../service/constants';
import {EventService} from '../../service/event';

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

    constructor(public nav: NavController,
                private api: Api,
                private ac: ActivatedRoute,
                private load: Load,
                private tf: Transfer,
                public loading: Loading,
                public eventService: EventService) {
        this.ac.queryParams.subscribe((data) => {
            if (data.no) {
                this.fieldRegionNo = data.no;
            }
        });
    }

    selectedTab = '';

    item: any = {
        factoryNo: '',
        factoryName: '',
        fieldRegionNo: '',
        fieldRegionName: '',
        temp: 0,
        humi: 0,
        // tempColor: '#62C7CC',
        // humiColor: '#62C7CC',
        heatStressLevel: 0,
        // heatStressColor: '#62C7CC',
        heatStressLevelName: '无',
        online: 0,
        operationModel: 1,
        isWisdomModel:  1,
        alarm: 1,
        inHouse: {
            inHouse: 0,
            inHouseState: false,
            inHouseName: '离舍',
            fieldDeviceNo: '',
            fieldDeviceType: '',
        },
        ts: 0
    };
    inHouseName = '离舍';
    inHouseState = false;

    fieldRegionNo = '';
    operationModel = 0;
    inHouseDisabled = false;

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

    fanLink = '';
    showerLink = '';
    lightLink = '';
    waterchannelLink = '';

    ngOnInit() {
        this.item = {
            factoryNo: '',
            factoryName: '',
            fieldRegionNo: '',
            fieldRegionName: '',
            temp: 0,
            humi: 0,
            // tempColor: '#62C7CC',
            // humiColor: '#62C7CC',
            heatStressLevel: 0,
            // heatStressColor: '#62C7CC',
            heatStressLevelName: '无',
            online: 0,
            operationModel: 1,
            isWisdomModel:  1,
            alarm: 1,
            inHouse: {
                inHouse: 0,
                inHouseState: false,
                inHouseName: '离舍',
                fieldDeviceNo: '',
                fieldDeviceType: '',
            },
            ts: 0
        };
        this.init();
    }

    // ionic的生命周期函数
    ionViewWillEnter() {
        console.log('ionViewWillEnter');
        this.init();
    }

    init() {
        this.comm.isLoading = false;
        this.comm.remain = 0;
        this.ac.queryParams.subscribe((data) => {
            if (data.fieldRegionNo) {
                this.fieldRegionNo = data.fieldRegionNo;
                this.operationModel = data.operationModel;
                this.getData(0);
            }
        });
        this.selectedTab = 'fan';
       // this.showerLink = '/shower?fieldRegionNo=' + this.fieldRegionNo + '&operationModel=' + this.item.operationModel + '&online=' + this.item.online;
    }

    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        if (this.fieldRegionNo !== undefined && this.fieldRegionNo !== null) {
            this.api.cowshedApp.getRealDataByFieldRegionNo([{fieldRegionNo: this.fieldRegionNo}, (data) => {
                if (data && data.fieldRegionNo) {
                    const environmentConfigJson = this.parseConfigJson(data.environmentConfigJson); // JSON.parse(data.environmentConfigJson.toString());
                    this.item = data;
                    this.item.heatStressLevelName = this.getHeatStressLevelName(data.heatStressLevel);

                    this.setInHouseInfo(data.inHouse);
                    this.initLayout(environmentConfigJson);
                    this.setInHouseDisable();
                }
            }]);
        }
    }

    parseConfigJson(environmentConfigJson) {
        if (environmentConfigJson === undefined || environmentConfigJson === null) {
            const config = {TU: 100, TL: 0, HU: 500, HL: 0};
            return config;
        } else {
            return JSON.parse(environmentConfigJson.toString());
        }
    }

    setInHouseInfo(inHouse) {
        if (inHouse === undefined || inHouse === null ||
            inHouse.inHouse === undefined || inHouse.inHouse === null) {
            this.item.inHouse = {
                inHouse: 0,
                inHouseState: false,
                inHouseName: '离舍',
                fieldDeviceNo: '',
                fieldDeviceType: '',
            };

            this.item.inHouse.inHouseName = '离舍';
            this.item.inHouse.inHouseState = false;
            this.inHouseName = '离舍';
            this.inHouseState = false;
        } else {
            this.item.inHouse.inHouseName = this.getInHouseState(inHouse.inHouse);
            this.item.inHouse.inHouseState = inHouse.inHouse === 1 ? true : false;
            this.inHouseName = this.getInHouseState(inHouse.inHouse);
            this.inHouseState = inHouse.inHouse === 1 ? true : false;
        }
    }

    initLayout(environmentConfigJson) {
        this.fanLink = '/env-detail/fan/';
        this.showerLink = '/env-detail/shower/' + this.fieldRegionNo + '/' + this.item.operationModel + '/' + this.item.online;
        this.lightLink = '/env-detail/light/' + this.fieldRegionNo + '/' + this.item.operationModel + '/' + this.item.online;
        this.waterchannelLink = '/env-detail/waterchannel/' + this.fieldRegionNo + '/' + this.item.operationModel + '/' + this.item.online;

        if (this.item) {
            this.item.heatStressColor = this.item.heatStressLevel === 0 ? '#62C7CC' :
                this.item.heatStressLevel === 1 ? '#62C7CC' :
                    this.item.heatStressLevel === 2 ? '#F8B72D' :
                        this.item.heatStressLevel === 3 ? '#F2401C' : '#F2401C';

            this.item.tempColor = this.getColor(this.item.temp, environmentConfigJson.TU, environmentConfigJson.TL);
            this.item.humiColor = this.getColor(this.item.humi, environmentConfigJson.HU, environmentConfigJson.HL);

        }
    }

    getColor(value, maxValue, minValue?) {
        if (value !== undefined && value !== null && value !== '' && maxValue !== undefined && maxValue !== null && maxValue !== '') {
            if (value > maxValue) {
                console.log('超过上限');
                return '#F2401C';
            } else {
                if (minValue !== undefined && minValue !== null) {
                    if (value < minValue) {
                        console.log('低于下限');
                        return '#F2401C';
                    } else {
                        return '#62C7CC';
                    }
                }
            }
        }
        return '#62C7CC';
    }

    getHeatStressLevelName(level) {
        let levelName = '';
        if (level === undefined || level === null) {
            levelName = '无';
        } else {
            switch (level) {
                case 0:
                    levelName = '无';
                    break;
                case 1 :
                    levelName = '轻';
                    break;
                case 2 :
                    levelName = '中';
                    break;
                case 3 :
                    levelName = '重';
                    break;
                case 4 :
                    levelName = 'II重';
                    break;
                default:
                    break;
            }
        }
        return levelName;
    }

    getInHouseState(state) {
        let stateName = '离舍';
        switch (state) {
            case 0:
                stateName = '离舍';
                break;
            case 1:
                stateName = '在舍';
                break;
            default:
                stateName = '离舍';
                break;
        }
        return stateName;
    }

    // 在离舍开关控制
    inHouseControl(inHouseState) {
        if (this.item.inHouse.fieldDeviceNo !== null && this.item.inHouse.fieldDeviceNo !== '') {
            const opt = {fieldDeviceNo: '', fieldDeviceType: '', op: 0, ts: 0};
            opt.fieldDeviceNo = this.item.inHouse.fieldDeviceNo;
            opt.fieldDeviceType = this.item.inHouse.fieldDeviceType;
            opt.op = inHouseState ? 0 : 1;
            opt.ts = new Date().valueOf();

            // this.comm.remain = 20;
            this.loading.presentLoading(Constants.LOADING_LONGER, true);
            this.api.control.controlCowedSwitch([opt, (data) => {
                // if (data && data.code === 1) {
                //     this.getData(1);
                //     this.api.presentMsgToast(data.message);
                //     // this.alarmMsg.locked = false;
                // } else {
                //     this.api.presentMsgToast(data.message);
                // }
                this.getData(0);

                this.comm.remain = 0;

                if (data && data.code === 1) {
                    this.api.presentMsgToast(data.message); // '传输成功, 设备操作中'
                    this.eventService.event.emit('inOutHouseController');
                    // setTimeout(() => {
                    //         this.loading.closeLoading();
                    //     this.eventService.event.emit('inOutHouseController');
                    // }, 65000);
                } else {
                    this.api.presentMsgToast(data.message);
                }
            }]);
        }
    }

    toHistory(item) {
        const query = 'env-history?no=' + item.fieldRegionNo + '&name=' + item.fieldRegionName + '&heatStressLevel=' + item.heatStressLevel;
        this.nav.navigateForward(query);
    }
    // doRefresh(event) {
    //     setTimeout(() => {
    //         this.getData(0);
    //         event.target.complete();
    //     }, 2000);
    // }

    setInHouseDisable() {
        // 以下场合 非活性
        // 1.离线 2.在线&现控 3.在线&混乱
        const online = +this.item.online; // 0-离线，1-在线
        const operationModel = +this.item.operationModel; // 0-现控，1-远控，4-混乱
        if (online === 0 ||
            (online === 1 && operationModel === 0) ||
            (online === 1 && operationModel === 4)) {
            this.inHouseDisabled = true;
        } else {
            this.inHouseDisabled = false;
        }
    }

    segmentChanged(e) {
        const tab = e.target.value;
        this.selectedTab = tab;
        let query = '?fieldRegionNo=' +  this.fieldRegionNo + '&operationModel=' + this.item.operationModel + '&online=' + this.item.online;
        if (tab === 'fan') {
            query = '/env-detail/fan' + query;
        } else if (tab === 'light') {
            query = '/env-detail/light' + query;
        } else if (tab === 'shower') {
            query = '/env-detail/shower' + query;
        } else if (tab === 'water') {
            query = '/env-detail/water' + query;
        } else {
            query = '/env-detail/fan' + query;
        }
        // this.nav.navigateForward(query);
    }

}
