import {Component, OnInit} from '@angular/core';
import {PickerController, AlertController} from '@ionic/angular';
import {Api} from '../../service/api';
import {Load} from '../../service/load';
import {NgxDatatableModule} from '@swimlane/ngx-datatable';

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

    defaultColumnOptions = [];

    fanMode = {
        'selecting': false,
    };

    light = {
        'selecting': false,
    };

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

    isError = false;
    cowshedList: any = [];
    curFieldRegionNo = '';
    // 当前牛舍信息
    curCowshed: any = {
        factoryNo: '',
        factoryName: '',
        fieldRegionNo: '',
        fieldRegionName: '',
        isWisdomModel: 0,
        propertyConfig: {toft: '', hoft: ''},
        config: [],
        leave: [],
        back: [],
        environmentConfigJson: {TU: 0, TL: 0, HU: 0, HL: 0},
        heatStressList: [] };
    // 各设备配置信息
    fengJi: any = {};
    penLin: any = {};
    zhaoMing: any = {};
    shuiCao: any = {};
    // 环境参数预警配置
    environmentConfig = [];
    private $ionicPopup: any;

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

        // ----------------------------------------------------
        // TODO 测试用准备数据
        this.cowshedList = [
            {
                // 0-无热应激 离线 无报警
                fieldRegionNo: 'FRN136641006052720640',
                fieldRegionName: '1号牛舍',
                temp: '23.5',
                humi: '82',
                heatStressLevel: '0',
                online: 0, // 0-离线，1-在线
                alarm: 0,
                ts: '2019-08-05 23:44',
            },
            {
                // 1-轻度热应激 在线 现控 无报警
                fieldRegionNo: 'FN108050436279648256',
                fieldRegionName: '2号牛舍',
                temp: '23.5',
                humi: '82',
                heatStressLevel: '1',
                online: 1, // 0-离线，1-在线
                operationModel: 0,  // 0-现控，1-平控
                alarm: 0,
                ts: '2019-08-05 23:44',
            },
            {
                // 2-中度热应激 在线 平控 非智控(手控) 有报警
                fieldRegionNo: 'FN108050436279648256',
                fieldRegionName: '3号牛舍',
                temp: '23.5',
                humi: '82',
                heatStressLevel: '2',
                online: 1, // 0-离线，1-在线
                operationModel: 1,  // 0-现控，1-平控
                isWisdomModel: 0,  // 0-非智控(手控)，1-智控
                alarm: 1,
                ts: '2019-08-05 23:44',
            },
            {
                // 3-重度热应激 在线 平控 非智控(自控) 有报警
                fieldRegionNo: 'FN108050436279648256',
                fieldRegionName: '4号牛舍',
                temp: '23.5',
                humi: '82',
                heatStressLevel: '3',
                online: 1, // 0-离线，1-在线
                operationModel: 1,  // 0-现控，1-平控
                isWisdomModel: 0,  // 0-非智控(自控)，1-智控
                alarm: 1,
                ts: '2019-08-05 23:44',
            },
            {
                // 4-II重度热应激 在线 平控 智控 有报警
                fieldRegionNo: 'FN108050436279648256',
                fieldRegionName: '测试用5号牛舍',
                temp: '23.5',
                humi: '82',
                heatStressLevel: '4',
                online: 1, // 0-离线，1-在线
                operationModel: 1,  // 0-现控，1-平控
                isWisdomModel: 1,  // 0-非智控(自控)，1-智控
                alarm: 1,
                ts: '2019-08-05 23:44',
            },
        ];
        // ----------------------------------------------------
    }

    workModeEvent(item) {
        console.log('更新牛舍配置信息');
        this.updateCowshed();
    }

    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) => {

            // ----------------------------------------------------
            // TODO 测试用准备数据
            data = {
                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
                    }
                ]
            };
            // ----------------------------------------------------

            if (data) {
                this.curCowshed = data;
                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) => {
                switch (value.fieldDeviceType) {
                    case '风机':
                        this.fengJi = value;
                        break;
                    case '喷淋' :
                        this.penLin = value;
                        break;
                    case '照明' :
                        this.zhaoMing = value;
                        break;
                    case '水槽' :
                        this.shuiCao = value;
                        break;
                    default:
                        break;
                }
            });
        }
        // 环境预警参数
        if (this.curCowshed.environmentConfigJson) {
            const temperatureCfg = {tittle: '温度', top: this.curCowshed.environmentConfigJson.TU,
                lower : this.curCowshed.environmentConfigJson.TL, symbol: '℃'};
            const humidityCfg = {tittle: '湿度', top: this.curCowshed.environmentConfigJson.HU,
                lower : this.curCowshed.environmentConfigJson.HL, symbol: '%'};
            this.environmentConfig.push(temperatureCfg, humidityCfg);
        }
    }

    // 修改牛舍配置
    updateCowshed() {
        this.api.config.updateCowshedConfig([this.curCowshed, (data) => {

            if (data) {
                console.log('更新成功');
            } else {
                this.api.presentMsgToast('获取数据失败');
                this.isError = true;
            }
            this.load.offLoad();
        }]);
    }

    referenceModel() {
        this.selectModel('风机', 0);
    }

    addModel() {
        this.selectModel('照明', 1);
    }

    changeModel() {
        this.selectModel('喷淋', 1);
    }

    // 参考：0 添加/替换：1
    async selectModel(deviceName, ref) {
        const alert = await this.alerCtrl.create({
            header: deviceName + '常用模式选择',
            inputs: [
                {
                type: 'radio',
                label: '春季',
                value: 'Spring',
                checked: false},
                {
                type: 'radio',
                label: '夏季',
                value: 'Summer',
                checked: false},
                {
                type: 'radio',
                label: '秋季',
                value: 'Autumn',
                checked: false},
                {
                type: 'radio',
                label: '冬季',
                value: 'Winter',
                checked: false}],
            buttons: [{text: '取消', cssClass: 'width: 40%'},
                {text: '确定', cssClass: 'width: 40%'}]
        });
        if (1 === ref) {
            alert.inputs.push({
                type: 'radio',
                label: '自定义',
                value: 'other',
                checked: false});
        }
        await alert.present();
    }

}
