import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Transfer} from '../../service/transfer';
import {Api} from '../../service/api';
import {Load} from '../../service/load';
import {NavController} from '@ionic/angular';
import {Network} from '@ionic-native/network/ngx';
import {EventService} from '../../service/event';


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

    constructor(private tf: Transfer, private ac: ActivatedRoute, private network: Network,
                private api: Api, private load: Load, public nav: NavController, public eventService: EventService) {
    }
    @ViewChild('slide') slide;

    isError = false;
    ifFocus = false;
    searchText = '';

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

    imgs = ['4.png'];
    lunbo = {
        speed: 1000,
        allowTouchMove: false,
        effect: 'flip',
        autoplay: {
            delay: 2000,
        },
        loop: false,
        spaceBetween: 0,
        zoom: false,
        height: 150,
    };
    // 热应激良
    thiGood = 0;
    // 热应激差
    thiBad = 0;
    // 故障总数
    alarmTotal = 0;
    // 牛舍列表
    items = [];
    // 搜索用列表
    displayItems = [];

    getItems(e) {
        this.items = this.displayItems;
        this.comm.isLoading = false;
        this.comm.remain = 1000;
        this.searchText = e.target.value;
        const val = e.target.value;
        if (val && val.trim() !== '') {
            this.items = this.items.filter((item) => {
                const name = item.fieldRegionName;
                return (name.toLowerCase().indexOf(this.searchText.toLowerCase()) > -1);
            });
        }
    }

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

    ngOnInit() {
        // console.log('env-home: ngOnInit');
        // this.init();
        // this.ionViewWillEnter();
    }

    init() {
        this.slideDidChange();
        this.getData(0);
    }


    getData(time) {
        if (this.isNetConnected()) {
            if (time) {
                this.load.toLoad('加载中...', false);
            }
            this.api.cowshedApp.getAll(['', (data) => {
                // 热应激良 热应激差 故障总数
                if (data) {
                    this.thiGood = data.thiGood;
                    this.thiBad = data.thiBad;
                    this.alarmTotal = data.alarmTotal;
                    // 牛舍列表
                    if (data.resultIndexDataListForAppVos && data.resultIndexDataListForAppVos.constructor === Array) {
                        this.isError = false;
                        this.items = [];
                        data.resultIndexDataListForAppVos.map((value, index) => {
                            const environmentConfigJson = JSON.parse(value.environmentConfigJson.toString());
                            const itemInfo = {
                                factoryNo: value.factoryNo,
                                factoryName: value.factoryName,
                                fieldRegionNo: value.fieldRegionNo,
                                fieldRegionName: value.fieldRegionName,
                                temp: this.getParam(value.temp),
                                humi: this.getParam(value.humi),
                                NH3: this.getParam(value.NH3),
                                tempColor: this.getColor(value.temp, environmentConfigJson.TU, environmentConfigJson.TL),
                                humiColor: this.getColor(value.humi, environmentConfigJson.HU, environmentConfigJson.HL),
                                NH3Color: this.getColor(value.NH3, environmentConfigJson.NH3U),
                                heatStressLevel: value.heatStressLevel,
                                heatStressLevelName: this.getHeatStressLevelName(value.heatStressLevel),
                                online: value.online,
                                operationModel: value.operationModel,
                                isWisdomModel: value.isWisdomModel,
                                alarm: value.alarm,
                                ts: value.ts
                            };
                            this.items.push(itemInfo);
                        });
                    } else {
                        this.api.presentMsgToast('获取数据失败');
                        this.isError = true;
                    }
                    this.displayItems = this.items;
                }
                this.load.offLoad();
            }]);
        }
    }

    slideDidChange() {
        this.slide.startAutoplay();
    }

    toggleFocus(e) {
        this.ifFocus = e;
    }

    getParam(param) {
        let result = '';
        if (param === undefined || param === null || param === '') {
            result = '--';
        } else {
            result = param;
        }
        return result;
    }

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

        return 'normal';
    }

    getHeatStressLevelName(codeId) {
        let levelName = '';
        switch (codeId) {
            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;
    }

    doRefresh(event) {
        // this.tempItems = this.items;
        setTimeout(() => {
            this.getData(0);
            event.target.complete();
            this.eventService.event.emit('refreshAlarmInfo');
        }, 2000);
    }

    // 混乱的场合 牛舍信息替换为前次数据
    // getTmpItemInfo(fieldRegionNo) {
    //     let tmpItem = null;
    //     if (this.tempItems !== null && this.tempItems.length > 0) {
    //         tmpItem = this.tempItems.filter(item => item.fieldRegionNo === fieldRegionNo);
    //     }
    //     return tmpItem;
    // }

    isNetConnected() {
        if (this.network.type === 'none') {
            this.api.presentMsgToast('网络连接失败,请确认连接状况');
            return false;
        }
        return true;
    }

    toControl(one) {
        const query = '/env-detail?no=' + one.fieldRegionNo + '&operationModel=' + one.operationModel;
        this.tf.transfer({
            url: '/' + one.url,
            query: query,
            hash: ''
        });
        this.nav.navigateForward(query);
    }
}
