import {Component, OnInit} from '@angular/core';
import {PickerController} from '@ionic/angular';
import {Api} from '../../service/api';
import {Load} from '../../service/load';

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

    // 工作模式
    workModeSetting = {
        'workMode': '1',
        'DeviceNo': '',
        'workModeOld': '1'
    };

    defaultColumnOptions = [];

    fanMode = {
        'selecting': false,
    };

    light = {
        'selecting': false,
    };

    fanCfg = [{
        'name': '模式一',
        'timeInterval': 25,
        'tempSet': 25,
        'tempOffset': 3,
        'ATmr': 20,
        'BTmr': 20,
    }, {
        'name': '模式二',
        'timeInterval': 25,
        'tempSet': 30,
        'tempOffset': 3,
        'ATmr': 20,
        'BTmr': 20,
    }, {
        'name': '模式三',
        'timeInterval': 25,
        'tempSet': 20,
        'tempOffset': 3,
        'ATmr': 20,
        'BTmr': 20,
    }, ];

    lightCfg = [{
        'name': '模式一',
        'timeInterval': 25,
        'startTime': 25,
        'endTime': 3,
        'onTime': 20,
        'offTime': 20,
    }, {
        'name': '模式二',
        'timeInterval': 25,
        'startTime': 30,
        'endTime': 3,
        'onTime': 20,
        'offTime': 20,
    }, ];

    constructor(private pickerController: PickerController, private api: Api, private load: Load) {
    }

    isError = false;
    cowshedList = [];
    curFieldRegionNo = '';
    // 当前牛舍信息
    curCowshed = {
        factoryNo: '',
        factoryName: '',
        fieldRegionNo: '',
        fieldRegionName: '',
        isWisdomModel: 0,
        propertyConfig: {toft: '', hoft: ''},
        config: [{
            fieldDeviceType: '', controlModel: 0, controlConfig: [{
                TU: 0,
                TL: 0,
                id: '',
                name: '',
                T: 0,
                A: 0,
                B: 0,
                intverval: 0,
                startDate: '',
                stopDate: '',
                on: '',
                off: '',
                power: 0
            }
            ]
        }],
        leave: [],
        back: [],
        environmentConfigJson: {TU: '', TL: '', HU: '', HL: ''},
        heatStressList: []
    };
    // 各设备配置信息
    fengJi = {};
    penLin = {};
    zhaoMing = {};
    shuiCao = {};

    async openPicker(numColumns = 1, numOptions = 5, columnOptions = this.defaultColumnOptions) {
        const picker = await this.pickerController.create({
            columns: this.getColumns(numColumns, numOptions, columnOptions),
            buttons: [
                {
                    text: 'Cancel',
                    role: 'cancel',
                    handler: () => {
                        this.fanMode.selecting = false;
                    }
                },
                {
                    text: 'Confirm',
                    handler: (value) => {
                        console.log(`Got Value ${value}`);
                        this.fanMode.selecting = false;
                    }
                }
            ]
        });
        await picker.present();
    }

    getColumns(numColumns, numOptions, columnOptions) {
        const columns = [];
        for (let i = 0; i < numColumns; i++) {
            columns.push({
                name: `col-${i}`,
                options: this.getColumnOptions(i, numOptions, columnOptions)
            });
        }
        return columns;
    }

    getColumnOptions(columnIndex, numOptions, columnOptions) {
        const options = [];
        for (let i = 0; i < numOptions; i++) {
            options.push({
                text: columnOptions[columnIndex][i % numOptions],
                value: i
            });
        }
        return options;
    }

    ngOnInit() {
        // this.pickerController = document.querySelector('ion-picker-controller');
        this.defaultColumnOptions = [
            [
                '1',
                '2',
                '3',
                '4',
                '5'
            ]
        ];

        this.init();
    }

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

    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        this.api.cowshedApp.getAllRegionData(['', (data) => {
            // 获取所有牛舍信息
            if (data) {
                // 牛舍列表
                if (data.resultIndexDataListForAppVos && data.resultIndexDataListForAppVos.constructor === Array) {
                    this.isError = false;
                    this.cowshedList = data.resultIndexDataListForAppVos;
                } else {
                    this.api.presentMsgToast('获取数据失败');
                    this.isError = true;
                }
            }
            this.load.offLoad();
        }]);
    }

    workModeEvent() {
        // if ( this.workModeSetting.workModeOld === this.workModeSetting.workMode ) {
        //     return;
        // }
        //
        // const opt = {fieldDeviceNo : this.workModeSetting.DeviceNo ,
        //     op : this.workModeSetting.workMode ,
        //     startTime: parseInt((new Date().getTime() / 1000).toString(), 10),
        //     ts: parseInt((new Date().getTime() / 1000).toString(), 10)
        // };
        //
        // opt.startTime = opt.ts;
        //
        // this.api.control.controlSwitch([opt, (data) => {
        //     if (data && data.code === 1) {
        //         this.getData(1);
        //         this.api.presentMsgToast(data.message);
        //     } else {
        //         this.api.presentMsgToast(data.message);
        //     }
        // }]);
    }

    async openCalendarPicker(numColumns = 1, numOptions = 5, columnOptions = this.defaultColumnOptions) {
        const picker = await this.pickerController.create({
            columns: this.getColumns(numColumns, numOptions, columnOptions),
            buttons: [
                {
                    text: 'Cancel',
                    role: 'cancel',
                    handler: () => {
                        this.fanMode.selecting = false;
                    }
                },
                {
                    text: 'Confirm',
                    handler: (value) => {
                        console.log(`Got Value ${value}`);
                        this.fanMode.selecting = false;
                    }
                }
            ]
        });
        await picker.present();
    }

    fanTempHaveFouch() {
        console.log('fanTempHaveFouch');
        if (this.fanMode.selecting === false) {
            this.fanMode.selecting = true;
            this.openPicker();
        }
    }

    lightTimeHaveFouch() {
        console.log('lightTimeHaveFouch');
        if (this.light.selecting === false) {
            this.light.selecting = true;
            this.openPicker();
        }
    }

    // 获取当前牛舍配置信息
    selectCowshed() {
        this.api.config.getAll([{'fieldRegionNo': this.curFieldRegionNo}, (data) => {
            if (data) {
                this.curCowshed = data;

                // ----------------------------------------------------
                // TODO 测试用准备数据
                this.curCowshed = {
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    fieldRegionNo: 'FRN136641006052720640',
                    fieldRegionName: '1号牛舍',
                    isWisdomModel: 1,
                    propertyConfig: {toft: '1.5', hoft: '2'},
                    config: [
                        {fieldDeviceType: '风机',
                            controlModel: 0,
                            controlConfig: [{TU: 28, TL: 20}],
                        },
                        {fieldDeviceType: '喷淋',
                            controlModel: 1,
                            controlConfig: [{id: '111', name: '模式一', T: 21, A: 35, B: 45, intverval: 55}, {id: '222', name: '模式二', T: 21, A: 35, B: 45, intverval: 55}]
                        },
                        {fieldDeviceType: '照明',
                            controlModel: 1,
                            controlConfig: [{id: '111', name: '模式A', startDate: '10-01', stopDate: '11-02', on: '19:00', off: '05:00'}, {id: '111', name: '模式B', startDate: '10-01', stopDate: '11-02', on: '19:00', off: '05:00'}]
                        },
                        {fieldDeviceType: '水槽',
                            controlModel: 0,
                            controlConfig: [{power: 100, startDate: '10-01', stopDate: '11-02'}],
                        }
                    ],
                    leave: ['风机', '喷淋', '水槽'],
                    back: ['风机', '喷淋', '水槽'],
                    environmentConfigJson: {HL: 0, HU: 100, TL: -10, TU: 50},
                    heatStressList: [
                        {
                            heatStressLevel: '无应激',
                            'alarmLevel': '无',
                            'thi': 68
                        },
                        {
                            'heatStressLevel': '轻度应激',
                            'alarmLevel': '低',
                            'thi': 72
                        },
                        {
                            'heatStressLevel': '中度应激',
                            'alarmLevel': '中',
                            'thi': 80
                        },
                        {
                            'heatStressLevel': '重度应激',
                            'alarmLevel': '高',
                            'thi': 90
                        },
                        {
                            'heatStressLevel': 'II重度应激',
                            'alarmLevel': '高',
                            'thi': 100
                        }
                    ]
                };
                // ----------------------------------------------------

                this.initConfig();
            } else {
                this.api.presentMsgToast('获取数据失败');
                this.isError = true;
            }
            this.load.offLoad();
        }]);
    }

    // 显示牛舍配置信息
    initConfig() {
        const configInfo = this.curCowshed.config;
        if (configInfo && configInfo.constructor === Array) {
            configInfo.map((value, index) => {
                if ('风机' === value.fieldDeviceType) {
                    this.fengJi = value;
                } else if ('喷淋' === value.fieldDeviceType) {
                    this.penLin = value;
                } else if ('照明' === value.fieldDeviceType) {
                    this.zhaoMing = value;
                } else if ('水槽' === value.fieldDeviceType) {
                    this.shuiCao = value;
                }
            });
        }
    }
}
