import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Api} from '../../service/api';
import {Load} from '../../service/load';
import {NgxDatatableModule, ColumnMode} from '@swimlane/ngx-datatable';
import {DateFormatter} from '@angular/common/src/pipes/deprecated/intl';
import {DatePipe} from '@angular/common';

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

    ColumnMode = ColumnMode;
    constructor(private api: Api, private ac: ActivatedRoute, private load: Load, private datePipe: DatePipe) {
    }

    fieldRegionNo = '';
    fieldRegionName = '';
    heatStressLevel = 0;

    item: any = {};

    chartOption = {
        backgroundColor: '#fff',
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: 'line', // 默认为直线，可选为：'line' | 'shadow'
                label: 'cross',
                show: true
            },
        },
        legend: {
            data: ['温度', '湿度', '热应激']
        },
        grid: {
            right: '25%'
        },
        xAxis: {},
        yAxis: [],
        series: [
            {
                name: '温度',
                data: [],
                type: 'line',
                itemStyle: {
                    normal: {
                        color: 'rgba(76, 208, 209, 0.8)', // '#D71F8B' rgba(215, 31, 139, 0.8)
                    }
                },
            },
            {
                name: '湿度',
                data: [],
                yAxisIndex: 1,
                type: 'line',
                itemStyle: {
                    normal: {
                        color: 'rgba(92, 178, 241, 0.8)', // rgba(37, 152, 214,0.5) rgba(22, 95, 175, 0.8)
                    }
                },
            },
            {
                name: '热应激',
                data: [],
                yAxisIndex: 2,
                type: 'line',
                itemStyle: {
                    normal: {
                        color: '#EFB827', // #EFB827 rgba(183, 164, 223, 0.8)
                        label: {formatter: ''}
                    },
                },
            }]};

    tableRows = [];
    // tableColumns = [
    //     { name: '时间', prop: 'ts'},
    //     { name: '热应激', prop: 'thi'},
    //     { name: '温度 <br> ℃', prop: 'temp'},
    //     { name: '湿度 <br> rH', prop: 'humi'},
    //     { name: '氨气浓度 <br> ppm', prop: 'NH3'}
    // ];
    // tableColumnWidths = [
    //     {column: 'ts', width: 70},
    //     {column: 'thi', width: 80},
    //     {column: 'temp', width: 70},
    //     {column: 'humi', width: 70},
    //     {column: 'NH3', width: 90}
    // ];
    // rowCount = 0;


    ngOnInit() {
        this.init();
    }

    init() {
        this.ac.queryParams.subscribe((data) => {
            this.fieldRegionNo = data.no;
            this.fieldRegionName = data.name;
            this.heatStressLevel = data.heatStressLevel;
            this.getData(0);
        });
    }

    getData(time) {
        if (time) {
            this.load.toLoad('加载中...', false);
        }
        const req: any = {};
        req.fieldRegionNo = this.fieldRegionNo;
        req.startTime = new Date().valueOf() - 8 * 3600 * 1000;
        req.endTime = new Date().valueOf();
        this.api.cowshedApp.getHistoryByFieldRegionNo([req, (data) => {
            if (data) {
                this.paintChart(data);
            }
        }]);

        req.counts = 10;

        this.api.cowshedApp.getHistoryTableByFieldRegionNo([req, (data) => {
            if (data && data.constructor === Array) {
                this.item = data;
                this.paintTable(data);
            }
        }]);
    }

    paintChart(param) {
        const heatLevel = [
            {id: 0, value: ''},
            {id: 1, value: '轻'},
            {id: 2, value: '中'},
            {id: 3, value: '重'},
            {id: 4, value: 'Ⅱ重'},
            {id: 5, value: ''},
        ];
        const temp = [];
        const humi = [];
        const thi = [];
        const times = [];
        if (param.temp && param.temp.constructor === Array) {
            param.temp.map(item => {
                times.push(this.datePipe.transform(item.time, 'hh:mm'));
                temp.push(Number(item.value).toFixed(2));
            });
        }
        if (param.humi && param.humi.constructor === Array) {
            param.humi.map(item => {
                humi.push(Number(item.value).toFixed(1));
            });
        }
        if (param.thi && param.thi.constructor === Array) {
            param.thi.map(item => {
                thi.push(Number(item.value).toFixed(0));
            });
        }

        this.chartOption = {
            backgroundColor: '#fff',
            tooltip: {
                trigger: 'axis',
                // axisPointer: {
                //     type: 'cross',
                //     label: {
                //         backgroundColor: '#72efff'
                //     }
                // }
                axisPointer: {
                    // 坐标轴指示器，坐标轴触发有效
                    type: 'line', // 默认为直线，可选为：'line' | 'shadow'
                    label: 'cross',
                    show: true
                },
            },
            legend: {
                data: ['温度', '湿度', '热应激']
            },
            // visualMap: [
            //     {show: false, type: 'continuous', seriesIndex: 0, min: 0, max: 400},
            //     {show: false, type: 'continuous', seriesIndex: 1, dimension: 0, min: 0, max: 400}],
            grid: {
                right: '25%'
            },
            xAxis: {
                name: '', type: 'category',
                data: times,
                axisLine: {
                    lineStyle: {
                        color: 'rgba(136,136,136, 1)', // X轴的宽度和颜色
                        width: 1,
                    }
                },
            },
            yAxis: [
                {
                    name: '温度(℃)',
                    type: 'value',
                    splitLine: {show: false},
                    position: 'left',
                    min: 0,
                    max: 50,
                    axisLine: {
                        lineStyle: {
                            width: 1,
                            color: 'rgba(76, 208, 209, 0.8)', // y轴的轴线的宽度和颜色
                        }
                    },
                },
                {
                    name: '湿度(% RH)',
                    type: 'value',
                    min: 0,
                    max: 100,
                    splitLine: {show: false},
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            width: 1,
                            color: 'rgba(92, 178, 241, 0.8)', // y轴的轴线的宽度和颜色 #2598D6
                        }
                    }
                },
                {
                    name: '', // 热应激
                    type: 'value',
                    min: 0,
                    max: 5,
                    splitLine: {show: true},
                    position: 'right',
                    offset: 35,
                    axisLine: {
                        lineStyle: {
                            width: 3,
                            color: '#EFB827', // y轴的轴线的宽度和颜色 rgba(239, 184, 39,0.5)
                        }
                    },
                    axisLabel: {
                        formatter: function(params) {
                            const current = heatLevel.find( item => (item.id === params));
                            return current.value;
                        },
                    }
                }
            ],
            series: [
                {
                    name: '温度',
                    data: temp,
                    type: 'line',
                    itemStyle: {
                        normal: {
                            color: 'rgba(76, 208, 209, 0.8)', // '#D71F8B' rgba(215, 31, 139, 0.8)
                        }
                    },
                },
                {
                    name: '湿度',
                    data: humi,
                    yAxisIndex: 1,
                    type: 'line',
                    itemStyle: {
                        normal: {
                            color: 'rgba(92, 178, 241, 0.8)', // rgba(37, 152, 214,0.5) rgba(22, 95, 175, 0.8)
                        }
                    },
                },
                {
                    name: '热应激',
                    data: thi,
                    yAxisIndex: 2,
                    type: 'line',
                    itemStyle: {
                        normal: {
                            color: '#EFB827', // #EFB827 rgba(183, 164, 223, 0.8)
                        }
                    },
                }
            ]
        };

        // this.chartOption.series[2].itemStyle.normal.label.formatter = function(params) {
        //     let text = '';
        //     const current = this.heatLevel.find((item, index) => {
        //         return item.id === params.data;
        //     });
        //     text = current ? current.value : '';
        //     return text;
        // };

    }

    setHeatLevelName(params) {
        // let text = params + '度';
        // const current = this.heatLevel.find((item, index) => {
        //     return item.id === params.data;
        // });
        // text = current ? current.value : '';
        // return params + '度';
    }

    paintTable(param) {
        this.tableRows = [];
        param.map((item, index) => {
            if (this.hasAllData(item)) {
                this.tableRows.push({
                    id: index + 1,
                    ts: this.datePipe.transform(item.ts, 'hh:mm'),
                    thi: item.heatStressLevel,
                    temp: item.temp.toFixed(2),
                    humi: item.humi.toFixed(1),
                    NH3: item.NH3.toFixed(3)
                });
            }
        });

    }

    hasAllData(param) {
        if (!this.isEmpty(param.heatStressLevel) ||
            !this.isEmpty(param.temp) ||
            !this.isEmpty(param.humi) ||
            !this.isEmpty(param.NH3)) {
            return true;
        } else {
            return false;
        }
    }

    isEmpty(value) {
        if (value === undefined || value === null || value === '') {
            return true;
        } else {
            return false;
        }
    }
    getRowClass(row) {
        return {
            'light-color': row.id % 2 === 0
        };
    }

    getHeaderClass() {
        return 'table-header';
    }

}
