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';
import {ActivatedRoute} from '@angular/router';
import {DatePipe} from '@angular/common';
import {Constants} from '../../service/constants';

@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,
    };

    controlModelOptions = [
        {modelId: 1, modelValue: '手控模式'},
        {modelId: 2, modelValue: '自控模式'}];

    alarmWays = [
        {alarmId: '无', alarmValue: '无'},
        {alarmId: '平台', alarmValue: '平台'},
        {alarmId: '平台/短信', alarmValue: '平/短'}];

    constructor(public alertCtrl: AlertController, private pickerController: PickerController, private alertController: AlertController,
                private api: Api, private load: Load, public nav: NavController, private tf: Transfer, private ac: ActivatedRoute,
                private datePipe: DatePipe) {
    }

    isError = false;
    cowshedList: any = [];
    curFieldRegionNo = '';
    // 当前牛舍信息
    curCowshed: any = {
        factoryNo: '',
        factoryName: '',
        fieldRegionNo: '',
        fieldRegionName: '',
        isWisdomModel: 0,
        propertyConfig: {toft: 0, hoft: 0},
        config: [],
        leave: [{type: '风机', flag: true}, {type: '喷淋', flag: false}, {type: '照明', flag: true}],
        back: [{type: '风机', flag: false}, {type: '喷淋', flag: true}, {type: '照明', flag: false}],
        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;
    isLightDisplay = false;
    isShowerDisplay = false;
    isFanDisplay = false;

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

    commTmr: any;

    private $ionicPopup: any;

    ngOnInit() {
        // this.pickerController = document.querySelector('ion-picker-controller');
        this.comm.remain = 0;
        this.comm.isLoading = false;
        this.commTmr = window.setInterval(() => {

            if (this.comm.remain > 0) {
                this.comm.remain = this.comm.remain - 1;
            }

            if ( this.comm.remain < 1 ) {
                this.comm.isLoading = false;
            } else {
                this.comm.isLoading = true;
            }
        }, 1000) ;
        this.init();
    }

    ionViewWillLeave() {
        clearInterval(this.commTmr);
    }

    init() {
        this.getData(0);
        // 替换模式 添加模式返回时
        this.ac.queryParams.subscribe((data) => {
            if (data) {
                if (data.addModelCfg) {
                    const cfg = JSON.parse(data.addModelCfg.toString());
                    const count = this.shower.controlConfig.length;
                    cfg.forEach((item, index) => {
                        item.id = index + 1 + count;
                        item.config.id = index + 1 + count;
                    });
                    this.shower.controlConfig = [...this.shower.controlConfig, ...cfg];
                } else if (data.changeModelCfg) {
                    const cfg = JSON.parse(data.changeModelCfg.toString());
                    // const count = this.light.controlConfig.length;
                    // cfg.forEach((item, index) => {
                    //     item.id = index + 1 + count;
                    // });
                    this.light.controlConfig = cfg;
                }
            }
        });
    }

    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        this.api.cowshedApp.getAll(['', (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();
        }]);
    }

    // 获取当前牛舍配置信息
    selectCowshed() {
        this.api.config.getByFieldRegionNo([{fieldRegionNo: this.curFieldRegionNo}, (data) => {
            if (data) {
                data.environmentConfigJson = JSON.parse(data.environmentConfigJson.toString());
                this.curCowshed = data;
                this.curCowshed.isWisdomModelChecked = this.curCowshed.isWisdomModel ? true : false;
                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 '风机':
                        const fanConfig = JSON.parse(value.controlConfig);
                        this.fan = value;
                        this.fan.controlConfig = fanConfig;
                        this.isFanDisplay = this.fan.controlModel === Constants.CONTROLL_SELF;

                        break;
                    case '喷淋' :
                        const showerConfig = JSON.parse(value.controlConfig);
                        this.shower.fieldDeviceType = value.fieldDeviceType;
                        this.shower.controlModel = value.controlModel;
                        this.shower.dataConfig = value.dataConfig;
                        this.shower.controlConfig = showerConfig;

                        this.isShowerDisplay = this.shower.controlModel === Constants.CONTROLL_SELF;
                        break;
                    case '照明' :
                        const lightConfig = JSON.parse(value.controlConfig);
                        // lightConfig.forEach( allCfg => {
                        //     const lightStart = new Date( new Date().getFullYear(),
                        //         parseInt(allCfg.config.startDate.slice(0, 2), 10),
                        //         parseInt(allCfg.config.startDate.slice(3, 5), 10)).getTime();
                        //     const lightStop = new Date( new Date().getFullYear(),
                        //         parseInt(allCfg.config.stopDate.slice(0, 2), 10),
                        //         parseInt(allCfg.config.stopDate.slice(3, 5), 10)).getTime();
                        //     allCfg.config.startDate = lightStart;
                        //     allCfg.config.stopDate = lightStop;
                        // });
                        this.light.fieldDeviceType = value.fieldDeviceType;
                        this.light.controlModel = value.controlModel;
                        this.light.dataConfig = value.dataConfig;
                        this.light.controlConfig = lightConfig;

                        this.isLightDisplay = this.light.controlModel === Constants.CONTROLL_SELF;
                        break;
                    case '水槽' :
                        const waterChannelConfig = JSON.parse(value.controlConfig);
                        // const waterStart = new Date( new Date().getFullYear(),
                        //     parseInt(waterChannelConfig.config.startDate.slice(0, 2), 10),
                        //     parseInt(waterChannelConfig.config.startDate.slice(3, 5), 10)).getTime();
                        // const waterStop = new Date( new Date().getFullYear(),
                        //     parseInt(waterChannelConfig.config.stopDate.slice(0, 2), 10),
                        //     parseInt(waterChannelConfig.config.stopDate.slice(3, 5), 10)).getTime();
                        // waterChannelConfig.config.startDate = waterStart;
                        // waterChannelConfig.config.stopDate = waterStop;

                        this.waterChannel.fieldDeviceType = value.fieldDeviceType;
                        this.waterChannel.controlModel = value.controlModel;
                        this.waterChannel.dataConfig = value.dataConfig;
                        this.waterChannel.controlConfig = waterChannelConfig;
                        break;
                    default:
                        break;
                }
            });
        }
    }

    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;
    }

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

    workModeChange(device) {
        switch (device) {
            case 'fan':
                this.isFanDisplay = this.fan.controlModel === Constants.CONTROLL_SELF;
                break;
            case 'shower' :
                this.isShowerDisplay = this.shower.controlModel === Constants.CONTROLL_SELF;
                break;
            case 'light' :
                this.isLightDisplay = this.light.controlModel === Constants.CONTROLL_SELF;
                break;
            default:
                break;
        }
    }

    toggle(isWisdomModelChecked) {
        // btn.op = btn.op ? 1 : 0;
        // event.preventDefault();
        // a.loading = true;
        this.opChangeComfirm(isWisdomModelChecked);

    }

    async opChangeComfirm(isWisdomModelChecked) {
        const msgOp  = isWisdomModelChecked ? '打开' : '关闭';
        const alert = await this.alertController.create({
            header: '请注意',
            // subHeader: '确定要' + msgOp + ' ' + msgHeader + ' 这个泵吗?',
            message: '即将' + msgOp + '智慧模式，要继续吗?',
            mode: 'ios',
            buttons: [
                {
                    text: '取消',
                    cssClass: 'width: 40%',
                    handler: () => {
                        this.curCowshed.isWisdomModelChecked = !isWisdomModelChecked;
                        event.preventDefault();
                    }
                }, {
                    text: '确定',
                    cssClass: 'width: 40%',
                    handler: () => {
                        this.changeWisdomModel(isWisdomModelChecked);
                    }
                }
            ]
        });
        await alert.present();
    }

    changeWisdomModel(isWisdomModelChecked) {

    }

    // 修改牛舍配置
    updateCowshed() {
        this.curCowshed.config = [];
        this.curCowshed.config.push(this.fan);
        this.curCowshed.config.push(this.shower);
        this.curCowshed.config.push(this.light);
        this.curCowshed.config.push(this.waterChannel);
        this.updateDateFormat();
        if (this.validate()) {
            this.updateModels();
            // this.load.toLoad('加载中...', false);
            this.comm.remain = 120;
            this.curCowshed.isWisdomModel = this.curCowshed.isWisdomModelChecked ? 1 : 0;
            this.api.config.updateConfig([this.curCowshed, (data) => {
                if (data && data.code !== 0) {
                    this.api.presentMsgToast(data.message);
                } else {
                    this.api.presentMsgToast('获取数据失败');
                    this.isError = true;
                }
                this.comm.remain = 0;
                this.load.offLoad();
            }]);
        }
    }

    updateDateFormat() {
        this.light.controlConfig.forEach( allCfg => {
            allCfg.startDate = this.formatDate(allCfg.config.startDate);
            allCfg.stopDate = this.formatDate(allCfg.config.stopDate);
        });

        this.waterChannel.controlConfig.config.startDate = this.formatDate(this.waterChannel.controlConfig.config.startDate);
        this.waterChannel.controlConfig.config.stopDate = this.formatDate(this.waterChannel.controlConfig.config.stopDate);
    }

    updateModels() {
        let fanConfig = '';
        let showerConfig = '';
        let lightConfig = '';
        let waterChannelConfig = '';
        // 风机
        fanConfig = JSON.stringify(this.fan.controlConfig);
        this.fan.controlConfig = fanConfig;
        // 喷淋
        showerConfig = JSON.stringify(this.shower.controlConfig);
        this.shower.controlConfig = showerConfig;
        // 照明
        lightConfig = JSON.stringify(this.light.controlConfig);
        this.light.controlConfig = lightConfig;
        // 水槽
        waterChannelConfig = JSON.stringify(this.waterChannel.controlConfig);
        this.waterChannel.controlConfig = waterChannelConfig;

        this.curCowshed.config = [];
        this.curCowshed.config.push(this.fan);
        this.curCowshed.config.push(this.shower);
        this.curCowshed.config.push(this.light);
        this.curCowshed.config.push(this.waterChannel);
    }

    validate() {
        if (this.isEmpty(this.curCowshed.propertyConfig.toft)) {
            this.api.presentMsgToast('请输入偏差温度');
            return false;
        }
        if (this.isEmpty(this.curCowshed.propertyConfig.hoft)) {
            this.api.presentMsgToast('请输入偏差湿度');
            return false;
        }
        if (this.fan.controlModel === Constants.CONTROLL_SELF) {
            if (this.isEmpty(this.fan.controlConfig.config.TU) || this.isEmpty(this.fan.controlConfig.config.TL)) {
                this.api.presentMsgToast('请完成风机配置');
                return false;
            }
        }
        if (this.shower.controlModel === Constants.CONTROLL_SELF) {
            let hasError = false;
            this.shower.controlConfig.map(allCfg => {
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.name);
                }
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.interval);
                }
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.T);
                }
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.A);
                }
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.B);
                }
            });
            if (hasError) {
                this.api.presentMsgToast('请完成喷淋配置');
                return false;
            }
        }
        if (this.light.controlModel === Constants.CONTROLL_SELF) {
            let hasError = false;
            let hasBlank = false;
            this.light.controlConfig.map(allCfg => {
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.name);
                    hasBlank = true;
                }
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.startDate);
                    hasBlank = true;
                }
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.stopDate);
                    hasBlank = true;
                }
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.on);
                    hasBlank = true;
                }
                if (!hasError) {
                    hasError = this.isEmpty(allCfg.config.off);
                    hasBlank = true;
                }

                // if (!hasError) {
                //     hasError = this.validateDate(allCfg.config.startDate);
                // }
                // if (!hasError) {
                //     hasError = this.validateDate(allCfg.config.stopDate);
                // }
                if (!hasError) {
                    hasError = this.validateDateFromTo(allCfg.config.startDate, allCfg.config.stopDate);
                }
            });
            if (hasError && hasBlank) {
                this.api.presentMsgToast('请完成喷淋配置');
                return false;
            } else if (hasError && !hasBlank) {
                this.api.presentMsgToast('喷淋配置: 请输入正确的日期范围');
                return false;
            }
        }
        if (this.isEmpty(this.waterChannel.controlConfig.config.startDate) ||
            this.isEmpty(this.waterChannel.controlConfig.config.stopDate)) {
            this.api.presentMsgToast('请完成水槽预警时间段配置');
            return false;
        } else {
            let hasError = false;
            // if (!hasError) {
            //     hasError = this.validateDate(this.waterChannel.controlConfig.config.startDate);
            // }
            // if (!hasError) {
            //     hasError = this.validateDate(this.waterChannel.controlConfig.config.stopDate);
            // }
            if (!hasError) {
                hasError = this.validateDateFromTo(this.waterChannel.controlConfig.config.startDate,
                    this.waterChannel.controlConfig.config.stopDate);
            }
            if (hasError) {
                this.api.presentMsgToast('水槽预警时间段配置: 请输入正确的日期范围');
                return false;
            }
        }
        if (this.isEmpty(this.curCowshed.environmentConfigJson.TU) ||
            this.isEmpty(this.curCowshed.environmentConfigJson.TL) ||
            this.isEmpty(this.curCowshed.environmentConfigJson.HU) ||
            this.isEmpty(this.curCowshed.environmentConfigJson.HL) ||
            this.isEmpty(this.curCowshed.environmentConfigJson.NH3U) ||
            this.isEmpty(this.curCowshed.environmentConfigJson.NH3L)) {
            this.api.presentMsgToast('请完成环境参数预警配置');
            return false;
        }
        return true;
    }

    isEmpty(item) {
        let hasError = false;
        if (item === undefined || item === null || item === '') {
            hasError = true;
        }
        return hasError;
    }

    validateDate(date) {
        // let hasError = false;
        // const month = parseInt(date.slice(0, 2), 10);
        // const day = parseInt(date.slice(2, 4), 10);
        // const newDate = new Date(new Date().getFullYear(), month, day);
        // if (newDate.getMonth() === month && newDate.getMonth() === day) {
        //     hasError = true;
        // }
        // return hasError;
        return false;
    }

    validateDateFromTo(dateFrom, dateTo) {
        let hasError = false;
        const fromMonth = parseInt(dateFrom.slice(0, 2), 10);
        const fromDay = parseInt(dateFrom.slice(2, 4), 10);
        const from = new Date(new Date().getFullYear(), fromMonth, fromDay).valueOf();
        const toMonth = parseInt(dateTo.slice(0, 2), 10);
        const toDay = parseInt(dateTo.slice(2, 4), 10);
        const to = new Date(new Date().getFullYear(), toMonth, toDay).valueOf();

        if (from > to) {
            hasError = true;
        }
        return hasError;
    }

    onReferenceModel() {
        let popFanModels = {};
        this.api.devicePatternModel.getByFactoryNoAndType([{factoryNo: this.curCowshed.factoryNo, fieldDeviceType: '风机'}, (data) => {
            if (data) {
                popFanModels = data;
                this.selectModel('风机', 1, popFanModels);
            }
            this.load.offLoad();
        }]);
    }

    onAddModel() {
        let popShowerModels = {};

        this.api.devicePatternModel.getByFactoryNoAndType([{factoryNo: this.curCowshed.factoryNo, fieldDeviceType: '喷淋'}, (data) => {
            if (data) {
                popShowerModels = data;
                this.selectModel('喷淋', 2, popShowerModels);
            }
            this.load.offLoad();
        }]);
    }

    onChangeModel() {
        let popLightModels = {};

        this.api.devicePatternModel.getByFactoryNoAndType([{factoryNo: this.curCowshed.factoryNo, fieldDeviceType: '照明'}, (data) => {

            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.alertCtrl.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;
            item.config.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;
            item.config.id = index + 1;
        });
    }

    toNextPage(device) {
        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);
    }

    formatDate(date) {
        let formatDate = date;
        if (date.toString().length !== 5) {
            formatDate = this.datePipe.transform(date, 'MM-dd');
        }
        return formatDate;
    }
}
