import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Api} from '../../service/api';
import {AlertController, LoadingController} from '@ionic/angular';
import {DatePipe} from '@angular/common';
import { IonInfiniteScroll } from '@ionic/angular';
import {Loading} from '../../service/loading';
import {Load} from '../../service/load';
import {Constants} from '../../service/constants';
import {EventService} from '../../service/event';

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

    displayArea = '';
    isTroubleDis = false;
    isAlarmDis = false;
    fieldRegionNo = '';
    fieldRegionName = '';
    fieldRegionGroup = '';

    detailInfo: any = {};
    troubleList = [];
    detailInfoLength = 0;
    disposeState = '';
    fieldDeviceType = '';
    startTime = null;
    stopTime = null;
    curInterval = 12;
    item = {};

    displayLength = 0;

    page = 1;
    rows = 10;

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

    stateOptions = [
        {modelId: '全部', modelValue: '全部'},
        {modelId: '0', modelValue: '待修复'},
        {modelId: '1', modelValue: '已修复'}];

    typeOptions = [
        {modelId: '全部', modelValue: '全部'},
        {modelId: '环境', modelValue: '环境'},
        {modelId: '风机', modelValue: '风机'},
        {modelId: '喷淋', modelValue: '喷淋'},
        {modelId: '照明', modelValue: '照明'},
        {modelId: '水槽', modelValue: '水槽'}];
    // commTmr: any;

    @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
    // @ViewChild('currentItem') currentItem;

    constructor(private ac: ActivatedRoute, private api: Api, public load: Load, public loadingController: LoadingController,
                public alterController: AlertController, private datePipe: DatePipe, public loading: Loading,
                public eventService: EventService) {
    }

    ngOnInit() {
        this.init();
        // this.commTmr = window.setInterval(() => {
        //     console.log(1);
        //     if (this.displayArea  === 'trouble') {
        //         this.showAlarmList = this.troubleList;
        //     } else {
        //         this.showAlarmList = this.alarmList;
        //     }
        //
        // }, 1000) ;
    }

    ionViewWillLeave() {
        console.log('env-alarm-detail: ionViewWillLeave');
        this.page = 1;
        this.disposeState = '';
        this.fieldDeviceType = '';
        this.detailInfo = {};
        this.troubleList = [];
        this.infiniteScroll.disabled = false;
    }

    init() {
        this.page = 1;
        this.displayLength = 0;
        this.detailInfo = {};
        this.troubleList = [];
        this.ac.queryParams.subscribe((data) => {
            console.log('init');
            this.fieldRegionNo = data.no;
            this.fieldRegionName = data.fieldRegionName;
            this.displayArea = data.displayArea;
            this.curInterval = data.interval;

            this.setDateInterval(this.curInterval);
            this.showArea(data.displayArea);
            this.setOperation(this.displayArea);
            // this.getTroubleList(true);
            // this.getAlarmList(true);
        });
    }

    setDateInterval(interval) {
        this.startTime = this.datePipe.transform(this.getStartTime(interval), 'yyyy-MM');
        this.stopTime = this.datePipe.transform(new Date(), 'yyyy-MM');
    }

    setOperation(displayArea) {
        if (displayArea === 'trouble') {
            this.typeOptions = [
                {modelId: '全部', modelValue: '全部'},
                {modelId: '风机', modelValue: '风机'},
                {modelId: '喷淋', modelValue: '喷淋'},
                {modelId: '照明', modelValue: '照明'},
                {modelId: '水槽', modelValue: '水槽'}];

            this.stateOptions = [
                {modelId: '全部', modelValue: '全部'},
                {modelId: '0', modelValue: '待修复'},
                {modelId: '1', modelValue: '已修复'}];
        } else {
            this.typeOptions = [
                {modelId: '全部', modelValue: '全部'},
                {modelId: '环境', modelValue: '环境'},
                {modelId: '风机', modelValue: '风机'},
                {modelId: '喷淋', modelValue: '喷淋'},
                {modelId: '照明', modelValue: '照明'},
                {modelId: '水槽', modelValue: '水槽'}];

            this.stateOptions = [
                {modelId: '全部', modelValue: '全部'},
                {modelId: '0', modelValue: '待解决'},
                {modelId: '1', modelValue: '已解决'}];
        }
    }

    showArea(displayArea) {
        this.isTroubleDis = displayArea === 'trouble' ? true : false;
        this.isAlarmDis = displayArea === 'alarm' ? true : false;
    }

    getTroubleList(isInit) {
        if (this.displayArea === 'trouble') {
            this.isTroubleDis = true;
            const req = {
                fieldRegionNo: this.fieldRegionNo,
                startTime: this.parseTime(this.startTime, 'start'),
                stopTime: this.parseTime(this.stopTime, 'stop'),
                disposeState: '',
                fieldDeviceType: ''
            };
            if (this.disposeState !== null && this.disposeState !== '' && this.disposeState !== '全部') {
                req.disposeState = this.disposeState;
            }
            if (this.fieldDeviceType !== null && this.fieldDeviceType !== '' && this.fieldDeviceType !== '全部') {
                req.fieldDeviceType = this.fieldDeviceType;
            }
            this.api.troubleLog.getByTerm(this.page, this.rows, [req, (data) => {
                if (data.trouble && data.trouble.constructor === Array) {
                    data.trouble.forEach((item) => {
                        item.data = JSON.parse(item.data);
                        item.troubleTime = this.api.formatTime('yyyy-MM-dd hh:mm:ss', new Date(item.troubleTime));
                    });
                } else if (data.code === 0) {
                    this.api.presentMsgToast(data.message);
                }
                // if (isInit) {
                //     this.detailInfo = data;
                // }
                this.detailInfo = data;
                this.detailInfoLength = data.devErrTotal;
                this.appendItems(data.trouble, data.devErrTotal);
            }]);
        }
    }

    getAlarmList(isInit) {
        if (this.displayArea === 'alarm') {
            this.isAlarmDis = true;
            const req = {
                fieldRegionNo: this.fieldRegionNo,
                startTime: this.parseTime(this.startTime, 'start'),
                stopTime: this.parseTime(this.stopTime, 'stop'),
                disposeState: '',
                fieldDeviceType: ''
            };
            if (this.disposeState !== null && this.disposeState !== '' && this.disposeState !== '全部') {
                req.disposeState = this.disposeState;
            }
            if (this.fieldDeviceType !== null && this.fieldDeviceType !== '' && this.fieldDeviceType !== '全部') {
                req.fieldDeviceType = this.fieldDeviceType;
            }
            this.api.alarm.getCowshedAlarm(this.page, this.rows, [req, (data) => {
                if (data.trouble && data.trouble.constructor === Array) {
                    data.trouble.forEach((item) => {
                        item.data = JSON.parse(item.data);
                        item.troubleTime = this.api.formatTime('yyyy-MM-dd hh:mm:ss', new Date(item.alarmTime));
                    });
                } else if (data.code === 0) {
                    this.api.presentMsgToast(data.message);
                }
                // if (isInit) {
                //     this.detailInfo = data;
                // }
                this.detailInfo = data;
                this.detailInfoLength = data.alarmTotal;
                this.appendItems(data.trouble, data.alarmTotal);
            }]);
        }
    }

    appendItems(trouble, allDataLength) {
        // await this.wait(500);
        // console.log(allDataLength);
        // console.log(this.troubleList.length);
        if (trouble.length > 0 && this.troubleList.length < allDataLength) {
            for (let i = 0; i < trouble.length; i++) {
                this.troubleList.push(trouble[i]);
                this.displayLength = this.displayLength + 1;
            }
            // this.infiniteScroll.disabled = false;
            this.page = this.page + 1;
            // console.log(this.infiniteScroll.disabled);
        } else {
            document.getElementById('infiniteScroll').setAttribute('disabled', 'disabled');
            // this.infiniteScroll.disabled = true;
        }
        this.load.offLoad();
    }

    async loadData(event) {
        setTimeout(async () => {
            console.log('loadData Done');
            this.getTroubleList(false);
            this.getAlarmList(false);
            event.target.complete();
            // App logic to determine if all data is loaded
            // and disable the infinite scroll
            await this.wait(500);
            if (this.troubleList.length === this.detailInfoLength) {
                event.target.disabled = true;
            }
        }, 1000);
    }

    segmentChanged(ev: any) {
        this.waiting();
        this.troubleList = [];
        setTimeout(async () => {
            console.log('segment changed');
            console.log(ev);
            this.page = 1;
            this.disposeState = '';
            this.fieldDeviceType = '';
            this.detailInfo = {};
            this.infiniteScroll.disabled = false;
            console.log(this.infiniteScroll.disabled);
            document.getElementById('infiniteScroll').removeAttribute('disabled');
            if (ev.target.value === 'alarm') {
                this.displayArea = 'alarm';
                this.setOperation('alarm');
                this.getAlarmList(true);
            } else {
                this.displayArea = 'trouble';
                this.setOperation('trouble');
                this.getTroubleList(true);
            }
        }, 1000);

    }

    // 确认修复
    async onRecvClick(alarm) {
        console.log(alarm);

        const alert = await this.alterController.create({
            header: '请注意',
            message: '请确认该故障是否为真实故障?',
            mode: 'ios',
            buttons: [
                {
                    text: '取消',
                    role: 'cancel',
                    cssClass: 'secondary',
                    // cssClass: 'width: 30%',
                }, {
                    text: '是',
                    // cssClass: 'width: 40%',
                    handler: () => {
                        this.processingFailure(1, alarm);
                    }
                }, {
                    text: '不是',
                    // cssClass: 'width: 30%',
                    handler: () => {
                        this.processingFailure(0, alarm);
                    }
                }
            ]
        });

        await alert.present();
    }

    processingFailure(real, alarm) {
        const req = {
            troubleLogNo: this.displayArea === 'alarm' ? alarm.alarmLogNo : alarm.troubleLogNo,
            disposeState: 1,
            isReal: real === 1 ? 1 : 0
        };
        this.loading.presentLoading(Constants.LOADING_SHORT, true);
        this.api.troubleLog.processingFailure([req, (data) => {
            if (data && data.code === 1) {
                this.api.presentMsgToast(data.message);
            } else {
                this.api.presentMsgToast(data.message);
            }
            this.refresh();
            this.loading.closeLoading();
        }]);
    }

    getStartTime(interval) {
        const now = new Date;
        const year = now.getFullYear();
        const month = now.getMonth() - interval;
        const day = now.getDate();
        const time = new Date(year, month, day, 0, 0, 0);
        return time;
    }

    parseTime(time, flg) {
        const year = time.slice(0, 4);
        const month = parseInt(time.slice(5, 7), 10);
        let updateTime = 0;
        if (flg === 'start') {
            updateTime = new Date( year, month - 1, 1, 0, 0, 0).valueOf();
        } else {
            updateTime = new Date( year, month, 0, 23, 59, 59).valueOf();
        }
        return updateTime;
    }

    refresh() {
        this.waiting();
        console.log('refresh');
        this.detailInfo = {};
        this.troubleList = [];
        this.page = 1;
        this.displayLength = 0;
        this.infiniteScroll.disabled = false;
        this.getTroubleList(false);
        this.getAlarmList(false);

        this.eventService.event.emit('refreshAlarmInfo');
    }

    wait(time) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve();
            }, time);
        });
    }

    async waiting() {
        const loading = await this.loadingController.create({
            spinner: 'circles',
            cssClass: 'main-color',
            mode: 'ios',
            message: '',
            duration: 500
        });
        await loading.present();

        const { role, data } = await loading.onDidDismiss();

        console.log('Loading dismissed!');
    }
}
