import {Component, OnInit} from '@angular/core';
import {PickerController, AlertController, NavController} from '@ionic/angular';
import {Api} from '../../service/api';
import {Load} from '../../service/load';
import {shrink, stretch, zoomIn, zoomOut, fadeIn, fadeOut, up, down} from '../../animations/animations';
import {Transfer} from '../../service/transfer';

@Component({
    selector: 'v-env-cfg',
    templateUrl: './env-cfg.page.html',
    styleUrls: ['./env-cfg.page.scss'],
    animations: [
        shrink, stretch, zoomIn, zoomOut, fadeIn, fadeOut, up, down
    ]
})
export class EnvCfgPage implements OnInit {

    defaultColumnOptions = [[]];

    fanMode = {
        'selecting': false,
    };

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

    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: [] };

    // 各设备配置信息
    fan: any = {};
    shower: any = {};
    light: any = {};
    waterChannel: any = {};

    // 设置菜单折叠/打开
    isOpenProperty = false;
    isOpenFan = false;
    isOpenShower = false;
    isOpenLight = false;
    isOpenWaterChannel = false;
    isOpenInHouse = false;
    isOpenEnvironment = false;
    isOpenHeatStress = false;

    private $ionicPopup: any;

    async openPicker(numColumns = 1, numOptions = 5, columnOptions = this.defaultColumnOptions, event) {
        const picker = await this.pickerController.create({
            columns: this.getColumns(numColumns, numOptions, columnOptions),
            buttons: [
                {
                    text: '取消',
                    role: 'cancel',
                    handler: () => {
                        this.fanMode.selecting = false;
                    }
                },
                {
                    text: '确认',
                    handler: (value) => {
                        event.target.value = value.col0.text;
                        console.log(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;
    }

    workModeEvent(item) {
        // 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();
    // }

    tempHaveTouch(event) {
        for (let i = 10; i <= 50; i++) {
            this.defaultColumnOptions[0][i - 10] = i.toString();
        }
        if (this.fanMode.selecting === false) {
            this.fanMode.selecting = true;

            this.openPicker(1, 41, this.defaultColumnOptions, event);
        }
    }

    humHaveTouch(event) {
        for (let i = 0; i <= 100; i++) {
            this.defaultColumnOptions[0][i] = i.toString();
        }
        if (this.fanMode.selecting === false) {
            this.fanMode.selecting = true;
            this.openPicker(1, 101, this.defaultColumnOptions, event);
        }
    }

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

    ngOnInit() {
        // this.pickerController = document.querySelector('ion-picker-controller');
        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',
            },
        ];
        // ----------------------------------------------------
    }

    // 获取当前牛舍配置信息
    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: 1, name: '模式一', T: 21, A: 35, B: 45, interval: 55},
                            {id: 2, name: '模式二', T: 21, A: 35, B: 45, interval: 55}]
                    },
                    {fieldDeviceType: '照明',
                        controlModel: '1',
                        controlConfig: [{id: 1, name: '模式A', startDate: '10-01', stopDate: '11-02', on: '19:00', off: '05:00'},
                            {id: 2, 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.fan = value;
                        break;
                    case '喷淋' :
                        this.shower = value;
                        break;
                    case '照明' :
                        this.light = value;
                        break;
                    case '水槽' :
                        this.waterChannel = 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();
        }]);
    }

    onReferenceModel() {
        let popFanModels = {};
        this.api.devicePatternModel.getByFactoryNoAndType([{factoryNo: this.curCowshed.factoryNo, fieldDeviceType: '风机'}, (data) => {
            // ---------------------------------------------------------
            // TODO 测试用数据
            data = [{
                patternModelNo: '1234681324789546',
                patternModelName: '春季1',
                fieldDeviceType: '风机',
                configJson: {name: '模式名A', TU: 20, TL: -10},
                factoryNo: 'FN108050436279648256',
                factoryName: '一厂',
                remark: '测试'
                },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '夏季2',
                    fieldDeviceType: '风机',
                    configJson: {name: '模式名A', TU: 20, TL: -10},
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '秋季3',
                    fieldDeviceType: '风机',
                    configJson: {name: '模式名A', TU: 20, TL: -10},
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '冬季4',
                    fieldDeviceType: '风机',
                    configJson: {name: '模式名', TU: 20, TL: -10},
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                }];
            // ---------------------------------------------------------
            if (data) {
                popFanModels = data;
                this.selectModel('风机', 1, popFanModels);
            }
            this.load.offLoad();
        }]);
    }

    onAddModel() {
        let popShowerModels = {};

        this.api.devicePatternModel.getByFactoryNoAndType([{factoryNo: this.curCowshed.factoryNo, fieldDeviceType: '喷淋'}, (data) => {
            // ---------------------------------------------------------
            // TODO 测试用数据
            data = [{
                patternModelNo: '1234681324789546',
                patternModelName: '春季1',
                fieldDeviceType: '喷淋',
                configJson: {name: '模式名A', T: 25, offset: 3, A: 25, B: 25, interval: 30},
                factoryNo: 'FN108050436279648256',
                factoryName: '一厂',
                remark: '测试'
            },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '夏季2',
                    fieldDeviceType: '喷淋',
                    configJson: {name: '模式名A', T: 25, offset: 3, A: 25, B: 25, interval: 30},
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '秋季3',
                    fieldDeviceType: '风机',
                    configJson: {name: '模式名A', T: 25, offset: 3, A: 25, B: 25, interval: 30},
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '冬季4',
                    fieldDeviceType: '风机',
                    configJson: {name: '模式名A', T: 25, offset: 3, A: 25, B: 25, interval: 30},
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                }];
            // ---------------------------------------------------------
            if (data) {
                popShowerModels = data;
                this.selectModel('喷淋', 2, popShowerModels);
            }
            this.load.offLoad();
        }]);
    }

    onChangeModel() {
        let popLightModels = {};

        this.api.devicePatternModel.getByFactoryNoAndType([{factoryNo: this.curCowshed.factoryNo, fieldDeviceType: '照明'}, (data) => {
            // ---------------------------------------------------------
            // TODO 测试用数据
            data = [{
                patternModelNo: '1234681324789546',
                patternModelName: '春季1',
                fieldDeviceType: '照明',
                configJson: [{name: '模式名A', startDate: '03-01', stopDate: '05-01', on: '19:00', off: '07:00'},
                    {name: '模式名B', startDate: '03-01', stopDate: '05-01', on: '19:00', off: '07:00'}],
                factoryNo: 'FN108050436279648256',
                factoryName: '一厂',
                remark: '测试'
            },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '夏季2',
                    fieldDeviceType: '风机',
                    configJson: [{name: '模式名A', startDate: '03-01', stopDate: '05-01', on: '19:00', off: '07:00'},
                        {name: '模式名B', startDate: '03-01', stopDate: '05-01', on: '19:00', off: '07:00'}],
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '秋季3',
                    fieldDeviceType: '风机',
                    configJson: [{name: '模式名A', startDate: '03-01', stopDate: '05-01', on: '19:00', off: '07:00'},
                        {name: '模式名B', startDate: '03-01', stopDate: '05-01', on: '19:00', off: '07:00'}],
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                },
                {
                    patternModelNo: '1234681324789546',
                    patternModelName: '冬季4',
                    fieldDeviceType: '风机',
                    configJson: [{name: '模式名A', startDate: '03-01', stopDate: '05-01', on: '19:00', off: '07:00'},
                        {name: '模式名B', startDate: '03-01', stopDate: '05-01', on: '19:00', off: '07:00'}],
                    factoryNo: 'FN108050436279648256',
                    factoryName: '一厂',
                    remark: '测试'
                }];
            // ---------------------------------------------------------
            if (data) {
                popLightModels = data;
                this.selectModel('照明', 3, popLightModels);
            }
            this.load.offLoad();
        }]);
    }

    // 风机:替换模式
    referenceModel(models, selectedName) {
        if (selectedName) {
            const selectedModel = models.filter(data => data.patternModelName === selectedName);
            this.fan.controlConfig.TU = selectedModel[0].configJson.TU;
            this.fan.controlConfig.TL = selectedModel[0].configJson.TL;
        }
    }

    // 喷淋:添加模式
    addModel(models, selectedName) {
        if (selectedName) {
            const modelCount = this.light.controlConfig.length;
            const selectedModel = models.filter(data => data.patternModelName === selectedName);
            selectedModel[0].configJson.id = modelCount + 1;
            this.shower.controlConfig.push(selectedModel[0].configJson);
        }
    }

    // 照明:替换模式
    changeModel(models, selectedName) {
        if (selectedName) {
            const selectedModel = models.filter(data => data.patternModelName === selectedName);
            selectedModel[0].configJson.forEach((item, index) => {
                item.id = index + 1;
            });
            this.light.controlConfig = selectedModel[0].configJson;
        }
    }

    // 设备：风机1 喷淋2 照明3
    async selectModel(deviceName, device, models) {
        const list = [];
        if (models && models.constructor === Array) {
            models.forEach((item) => {
                list.push({type: 'radio', label: item.patternModelName, value: item.patternModelName, checked: false});
            });
        }
        if (2 === device || 3 === device) {
            list.push({
                type: 'radio',
                label: '自定义',
                value: 'other',
                checked: false});
        }
        const alert = await this.alerCtrl.create({
            header: deviceName + '常用模式选择',
            inputs: list,
            buttons: [
                {text: '取消', cssClass: 'width: 40%'},
                {
                    text: '确定',
                    cssClass: 'width: 40%',
                    handler: (value) => {
                        // 自定义
                        if (value === 'other') {
                            this.toNextPage(device);
                        } else {
                            if (1 === device) {
                                this.referenceModel(models, value);
                            } else if (2 === device) {
                                this.addModel(models, value);
                            } else {
                                this.changeModel(models, value);
                            }
                        }
                    }}]
        });
        await alert.present();
    }

    openItem(param) {
        if (param === 'propertyCfg') {
            this.isOpenProperty = !this.isOpenProperty;
        } else if (param === 'fanCfg') {
            this.isOpenFan = !this.isOpenFan;
        } else if (param === 'showerCfg') {
            this.isOpenShower = !this.isOpenShower;
        } else if (param === 'lightCfg') {
            this.isOpenLight = !this.isOpenLight;
        } else if (param === 'waterChannelCfg') {
            this.isOpenWaterChannel = !this.isOpenWaterChannel;
        } else if (param === 'inHouseCfg') {
            this.isOpenInHouse = !this.isOpenInHouse;
        } else if (param === 'environmentCfg') {
            this.isOpenEnvironment = !this.isOpenEnvironment;
        } else if (param === 'heatStressCfg') {
            this.isOpenHeatStress = !this.isOpenHeatStress;
        }
    }

    deleteShowerModel(one) {
        const updateModel = this.shower.controlConfig.filter(data => data.id !== one.id);
        this.shower.controlConfig = updateModel;
        this.shower.controlConfig.forEach((item, index) => item.id = index + 1);
    }

    deleteLightModel(one) {
        const updateModel = this.light.controlConfig.filter(data => data.id !== one.id);
        this.light.controlConfig = updateModel;
        this.light.controlConfig.forEach((item, index) => item.id = index + 1);

    }

    toNextPage(device) {
        debugger;
        let query = '';
        if (device === 2) {
            query = '/env-add-model';
        } else if (device === 3) {
            query = '/env-change-model';
        }
        this.tf.transfer({
            url: '/' + device.url,
            query: query,
            hash: ''
        });
        this.nav.navigateForward(query);
    }

}
