import {Component, ElementRef, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {TopologyService} from '../topology.service';
import {OverAllService} from '../../overAll/overAll.service';
import {NzMessageService} from 'ng-zorro-antd';
import {pageSize} from '../../app.constants';
import {DatePipe} from '@angular/common';
import {setInterval, clearInterval} from 'timers';
import {NgxEchartsModule} from 'ngx-echarts';

@Component({
    selector: 'smart-flow-trend',
    templateUrl: './flow-trend.component.html',
    styles: []
})
export class FlowTrendComponent implements OnInit, OnDestroy {
    groupList;
    hostList;
    isLoading;
    obj = {
        groupid: null,
        hostid: null,
        startTime: '',
        endTime: ''
    };
    echartType = 'history';
    echartObj;  //echart对象

    //in
    inList = [];
    inPageNum = 1;
    inPageCount = '5';
    inTotalNum;
    inLoading;

    //out
    outList = [];
    outPageNum = 1;
    outPageCount = '5';
    outTotalNum;
    outLoading;

    timeType = '1';
    timeBegin;
    timeEnd;

    //历史图表
    chartOption;
    inEchartData;
    outEchartData;

    //实时图表
    nowChartOption;
    inNowEchartData = [];
    outNowEchartData = [];

    time_;

    data = {
        now: false,
        history: false
    };

    constructor(private topologySer: TopologyService, private overAllSer: OverAllService,
                private message: NzMessageService, private datePipe: DatePipe) {
    }

    ngOnInit() {
        const today = new Date().getTime();
        this.obj.startTime = this.datePipe.transform(today, 'yyyy-MM-dd') + ' 00:00:00';
        this.obj.endTime = this.datePipe.transform(today, 'yyyy-MM-dd') + ' 23:59:59';
        this.getGroup();
        this.time_ = setInterval(() => {
            if (this.obj.hostid) {
                this.findByTime();
            }
        }, 1000 * 60 * 4);

    }

    //获取流量
    getList() {
        this.outNowEchartData = [];
        this.inNowEchartData = [];

        this.obj.hostid = null;
        this.onchange();
    }

    getListIO() {
        this.outNowEchartData = [];
        this.inNowEchartData = [];

        this.getInList();
        this.getOutList();
    }

    onEchartInit(e) {
        this.echartObj = e;
    }

    //获取分组
    getGroup() {
        this.overAllSer.findGroup().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.groupList = res.data;
                    this.obj.groupid = this.groupList[0].groupid + '';
                    this.onchange();
                }
            }
        );
    }

    //切换图表类型
    changeEchartType(type) {
        this.echartType = type;
    }

    //查询主机
    onchange() {
        const data = {
            'groupids': [this.obj.groupid],
            'hostExtend': {
                'superiorHostid': null
            }
        };
        this.overAllSer.findDetail(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.hostList = res.data;
                    if (this.hostList) {
                        this.obj.hostid = this.hostList[0].hostid + '';
                        this.getEcharts(null);
                        this.findByTime();
                        this.setNowEchart();
                        this.getInList();
                        this.getOutList();
                    } else {
                        this.message.warning('当前资源组无资源');
                    }
                }
            }
        );
    }

    setNowEchart() {
        let itemStyle = {
            normal: {},
            emphasis: {
                barBorderWidth: 1,
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0,0,0,0.5)'
            }
        };
        this.nowChartOption = {
            title: {
                text: '实时进出口流量图',
                left: 'center',
            },
            backgroundColor: '#eee',
            tooltip: {
                formatter: (params) => {
                    if (params.data) {
                        let res = params.seriesName;
                        res += '<br/>时间：' + params.name;
                        let Mbps = 1000 * 1000;
                        let kbps = 1000;
                        let size = Math.abs(params.data);
                        if (size / Mbps > 1) {
                            res += '<br/>流量：' + (size / Mbps).toFixed(2) + 'Mbps';
                        } else if (size / kbps > 1) {
                            res += '<br/>流量：' + (size / kbps).toFixed(2) + 'kbps';
                        } else {
                            res += '<br/>流量：' + (size) + 'bps';
                        }
                        return res;
                    }
                }
            },
            xAxis: {
                data: this.inNowEchartData.map(e => {
                    let date = this.datePipe.transform(e.clock, 'yyyy-MM-dd HH:mm');
                    return date;
                }),
                name: '时间',
            },
            dataZoom: [{
                startValue: this.obj.startTime
            }, {
                type: 'inside'
            }],
            yAxis: {
                inverse: true,
                splitArea: {show: false},
                type: 'value',
                axisLabel: {   //Y轴数据
                    formatter: function(value) {
                        return Math.abs(value) / 10000 + ' kbps';   //负数取绝对值变正数
                    },
                    textStyle: {
                        color: '#666'
                    }
                },
            },
            grid: {
                left: 100
            },
            series: [
                {
                    name: '进口流量',
                    type: 'line',
                    stack: 'one',
                    itemStyle: itemStyle,
                    data: this.inNowEchartData.map(e => {
                        return e.sumValue;
                    })
                },
                {
                    name: '出口流量',
                    type: 'line',
                    stack: 'one',
                    itemStyle: itemStyle,
                    data: this.outNowEchartData.map(e => {
                        return -e.sumValue;
                    })
                }
            ]
        };
    }

    //实时流量数据
    findByTime() {
        this.topologySer.findByTime(this.obj.hostid).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.inNowEchartData = res.data.in;
                    this.outNowEchartData = res.data.out;
                    if (this.inNowEchartData.length == 0 && this.outNowEchartData.length == 0) {
                        this.data.now = true;
                        this.message.warning('实时流量数据暂无');
                    } else {
                        this.data.now = false;
                        this.flashEcharts();
                    }
                }
            }
        );
    }

    //实时刷新图表
    flashEcharts() {
        let itemStyle = {
            normal: {},
            emphasis: {
                barBorderWidth: 1,
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0,0,0,0.5)'
            }
        };

        this.nowChartOption = {
            title: {
                text: '实时进出口流量图',
                left: 'center',
            },
            legend: {
                data: ['进口流量', '出口流量'],
                align: 'left',
                left: 10
            },
            backgroundColor: '#eee',
            tooltip: {
                formatter: (params) => {
                    if (params.data) {
                        let res = params.seriesName;
                        res += '<br/>时间：' + params.name;
                        let Gbps = 1000 * 1000 * 1000;
                        let Mbps = 1000 * 1000;
                        let kbps = 1000;
                        let size = Math.abs(params.data);
                        if (size / Gbps > 1) {
                            res += '<br/>流量：' + (size / Gbps).toFixed(2) + 'Gbps';
                        } else if (size / Mbps > 1) {
                            res += '<br/>流量：' + (size / Mbps).toFixed(2) + 'Mbps';
                        } else if (size / kbps > 1) {
                            res += '<br/>流量：' + (size / kbps).toFixed(2) + 'kbps';
                        } else {
                            res += '<br/>流量：' + (size) + 'bps';
                        }
                        return res;
                    }
                }
            },
            xAxis: {
                data: this.inNowEchartData.map(e => {
                    return e.clock;
                }),
                name: '时间',
            },
            dataZoom: [{
                startValue: this.obj.startTime
            }, {
                type: 'inside'
            }],
            yAxis: {
                inverse: true,
                splitArea: {show: false},
                type: 'value',
                axisLabel: {   //Y轴数据
                    formatter: function(value) {
                        return Math.abs(value) / 10000 + ' kbps';   //负数取绝对值变正数
                    },
                    textStyle: {
                        color: '#666'
                    }
                },
            },
            grid: {
                left: 100
            },
            series: [
                {
                    name: '进口流量',
                    type: 'line',
                    stack: 'one',
                    itemStyle: itemStyle,
                    data: this.inNowEchartData.map(e => {
                        return e.sumValue;
                    })
                },
                {
                    name: '出口流量',
                    type: 'line',
                    stack: 'one',
                    itemStyle: itemStyle,
                    data: this.outNowEchartData.map(e => {
                        return -e.sumValue;
                    })
                }
            ]
        };
    }

    //页面离开
    ngOnDestroy() {
        //销毁定时任务
        if (this.time_) {
            clearInterval(this.time_);
        }
    }

    //获取趋势数据
    getEcharts(itemid) {
        this.isLoading = true;
        const data = {
            itemid: itemid,
            endTime: this.obj.endTime,
            startTime: this.obj.startTime,
            hostid: this.obj.hostid,
            groupid: this.obj.groupid,
            type: 'in',
            limit: '1000'
        };
        this.topologySer.findTrendData(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    if (res.data.length > 0) {
                        this.inEchartData = res.data.map(e => {
                            const a = {
                                clock: this.datePipe.transform(e.clock, 'yyyy-MM-dd HH:mm'),
                                avg: e.avg
                            };
                            return a;
                        });
                    } else {
                        this.inEchartData = [];
                        this.message.warning('进口流量图表暂无数据');
                        this.isLoading = false;
                    }
                    data.type = 'out';
                    this.topologySer.findTrendData(data).subscribe(
                        (res) => {
                            if (res.data.length > 0) {
                                this.outEchartData = res.data.map(e => {
                                    const d = {
                                        clock: this.datePipe.transform(e.clock, 'yyyy-MM-dd HH:mm'),
                                        avg: e.avg
                                    };
                                    return d;
                                });
                                this.setEacharts();
                            } else {
                                this.outEchartData = [];
                                this.message.warning('出口流量图表暂无数据');
                                this.isLoading = false;
                                this.setEacharts();
                            }

                            if (this.inEchartData.length == 0 && this.outEchartData.length == 0) {
                                this.data.history = true;
                            } else {
                                this.data.history = false;
                            }
                        }
                    );
                }
            }
        );
    }

    //
    setEacharts() {
        let itemStyle = {
            normal: {},
            emphasis: {
                barBorderWidth: 1,
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0,0,0,0.5)'
            }
        };

        this.chartOption = {
            title: {
                text: '进出口流量峰值趋势图',
                left: 'center',
            },
            legend: {
                data: ['进口流量', '出口流量'],
                align: 'left',
                left: 10
            },
            backgroundColor: '#eee',
            tooltip: {
                // trigger: 'axis',
                formatter: (params) => {

                    let res = params.seriesName;
                    res += '<br/>时间：' + params.name;
                    let Mbps = 1000 * 1000;
                    let kbps = 1000;
                    let size = Math.abs(params.data);
                    if (size / Mbps > 1) {
                        res += '<br/>流量：' + (size / Mbps).toFixed(2) + 'Mbps';
                    } else if (size / kbps > 1) {
                        res += '<br/>流量：' + (size / kbps).toFixed(2) + 'kbps';
                    } else {
                        res += '<br/>流量：' + (size) + 'bps';
                    }

                    return res;
                }
            },
            xAxis: {
                data: this.inEchartData.map(e => {
                    let date = this.datePipe.transform(e.clock, 'yyyy-MM-dd HH:mm');
                    return date;
                }),
                name: '时间',
            },
            dataZoom: [{
                startValue: this.obj.startTime
            }, {
                type: 'inside'
            }],
            yAxis: {
                inverse: true,
                splitArea: {show: false},
                type: 'value',
                axisLabel: {   //Y轴数据
                    formatter: function(value) {
                        return Math.abs(value) / 10000 + ' kbps';   //负数取绝对值变正数
                    },
                    textStyle: {
                        color: '#666'
                    }
                },
            },
            grid: {
                left: 100
            },
            series: [
                {
                    name: '进口流量',
                    type: 'line',
                    stack: 'one',
                    itemStyle: itemStyle,
                    data: this.inEchartData.map(e => {
                        return e.avg;
                    })
                },
                {
                    name: '出口流量',
                    type: 'line',
                    stack: 'one',
                    itemStyle: itemStyle,
                    data: this.outEchartData.map(e => {
                        return -e.avg;
                    })
                }
            ]
        };
        this.isLoading = false;
    }

    //in改变页数
    inChnagePage(e) {
        this.inPageNum = e;
        this.getInList();
    }

    //out改变页数
    outChnagePage(e) {
        this.outPageNum = e;
        this.getOutList();
    }

    //进口流量
    getInList() {
        this.inLoading = true;
        const data = {
            obj: {
                type: 'in',
                hostid: this.obj.hostid,
                startTime: this.obj.startTime,
                endTime: this.obj.endTime,
                groupid: this.obj.groupid
            },
            pageNum: this.inPageNum,
            pageCount: this.inPageCount,
        };
        this.topologySer.findTrend(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.inList = res.data.data;
                    this.inTotalNum = res.data.totalNum;
                }
                this.inLoading = false;
            }
        );
    }

    //出口流量
    getOutList() {
        this.outLoading = true;
        const data = {
            obj: {
                type: 'out',
                hostid: this.obj.hostid,
                startTime: this.obj.startTime,
                endTime: this.obj.endTime,
                groupid: this.obj.groupid
            },
            pageNum: this.outPageNum,
            pageCount: this.outPageCount,

        };
        this.topologySer.findTrend(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.outList = res.data.data;
                    this.outTotalNum = res.data.totalNum;
                }
                this.outLoading = false;
            }
        );
    }

    //时间改变
    changeType() {
        const nowDate = new Date().getTime();
        let day1, day2;
        switch (this.timeType) {
            case'1': {
                this.obj.startTime = this.datePipe.transform(nowDate, 'yyyy-MM-dd') + ' 00:00:00';
                this.obj.endTime = this.datePipe.transform(nowDate, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'2': {
                day1 = nowDate - 1 * 24 * 60 * 60 * 1000;
                this.obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                this.obj.endTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'3': {
                day1 = nowDate - 3 * 24 * 60 * 60 * 1000;
                day2 = nowDate;
                this.obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                this.obj.endTime = this.datePipe.transform(day2, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'4': {
                day1 = nowDate - 7 * 24 * 60 * 60 * 1000;
                day2 = nowDate;
                this.obj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                this.obj.endTime = this.datePipe.transform(day2, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'5': {
                break;
            }
        }
    }

    //搜索
    search() {
        if (this.timeType == '5') {
            this.obj.startTime = this.datePipe.transform(this.timeBegin, 'yyyy-MM-dd HH:mm:ss');
            this.obj.endTime = this.datePipe.transform(this.timeEnd, 'yyyy-MM-dd HH:mm:ss');
        }
        this.getEcharts(null);
        this.getInList();
        this.getOutList();
        this.findByTime();
    }

}
