import {AfterViewInit, Component, ElementRef, OnInit, Renderer2, ViewChild} from '@angular/core';
import {JhiEventManager} from 'ng-jhipster';
import {Principal} from '../shared';
import {OverAllService} from '../overAll/overAll.service';
import {color, pageSize} from '../app.constants';
import {AlarmService} from '../alarm/alarm.service';
import {NzMessageService} from 'ng-zorro-antd';
import {LayoutService} from '../layouts/layout.service';
import {SelectGroupComponent} from '../modal/select-group/select-group.component';
import {Router} from '@angular/router';
import {CommonService} from '../shared/common/common.service';
import {AnalysisService} from '../analysis/analysis.service';
import {TopologyViewComponent} from '../component/topology-view/topology-view.component';
import {TopologyService} from '../netTopology/topology.service';
import {DatePipe} from '@angular/common';

@Component({
    selector: 'jhi-home',
    templateUrl: './home.component.html',
    styleUrls: [
        'home.css'
    ]

})
export class HomeComponent implements OnInit {
    @ViewChild('smartTopologyView') smartTopologyView: TopologyViewComponent;

    color = color;
    obj = {
        leftGroupId: '',
    };
    noData = false;
    groupList;   //分组数组
    timeList = [
        {'label': '最近一小时', value: '1'},
        {'label': '最近一天', value: '2'},
        {'label': '最近三天', value: '3'},
        {'label': '最近一周', value: '4'},
    ];
    timeTypeTrend = "0";

    leftOneChart;
    leftTwoChart;

    rightOneChart;
    rightTwoChart;

    charTrendOption;   //告警综述趋势

    leftOneData = {
        high: 0,
        warning: 0,
        normal: 0,
        disabled: 0,
    };
    leftOneDataPre = {
        highPer: 0,
        warningPer: 0,
        normalPer: 0,
        disabledPer: 0,
    };

    leftOneTotal = 0;
    leftTwoData = {
        high: 0,
        warning: 0,
        normal: 0,
        disabled: 0,
    };
    leftTwoDataPre = {
        highPer: 0,
        warningPer: 0,
        normalPer: 0,
        disabledPer: 0,
    };

    leftTwoTotal = 0;

    rightTotal = 0;

    flowListNum;   //接口流量排行  数值
    flowListPre;   //发送利用率排名  百分比
    countOrderList;   //cpu内存使用率排名列表

    isTrendLoading = false;

    trendObj = {
        startTime: '',
        endTime: ''
    };

    dataSet;  //拓扑图
    topoId;

    constructor(
        private overAllSer: OverAllService, private message: NzMessageService,
        private alarmSer: AlarmService, private renderer: Renderer2,
        private layoutSer: LayoutService,private datePipe:DatePipe,
        private principal: Principal, private topologySer: TopologyService,
        private eventManager: JhiEventManager, private analysisSer: AnalysisService,
        private router: Router, private commonSer: CommonService,
    ) {
    }

    ngOnInit() {
        this.findGroupCount();
        this.findHostCount();

        this.getGroup();

        this.flowRankNum();
        this.flowRankPre();
        this.countOrde();

        this.getList();
    }

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

    //获取拓扑图列表
    getList() {
        this.topologySer.findAll().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.dataSet = res.data;
                }
            }
        );
    }

    //主机组中统计
    countGroupItem() {
        this.getAlarmTrend();
        this.layoutSer.findHostCountByStatusByGroup(this.obj.leftGroupId).subscribe(
            (res) => {
                this.leftOneData = res.data;
                this.setLeftOne(res.data);
            }
        );
        this.layoutSer.findItemStatisticsByGroupid(this.obj.leftGroupId).subscribe(
            (res) => {
                if (res) {
                    this.leftTwoData = res.data;
                    this.setLeftTwo(res.data);
                }
            }
        );
    }

    setLeftOne(data) {
        this.leftOneDataPre = {
            highPer: 0,
            warningPer: 0,
            normalPer: 0,
            disabledPer: 0,
        };
        this.leftOneTotal = data.disabled + data.high + data.normal + data.warning;

        if (this.leftOneData.high > 0) {
            let a: any = (this.leftOneData.high / this.leftOneTotal) * 100;
            this.leftOneDataPre.highPer = a.toFixed(2);
        }

        if (this.leftOneData.warning > 0) {
            let b: any = ((this.leftOneData.warning / this.leftOneTotal) * 100);
            this.leftOneDataPre.warningPer = b.toFixed(2);
        }

        if (this.leftOneData.normal > 0) {
            let c: any = ((this.leftOneData.normal / this.leftOneTotal) * 100);
            this.leftOneDataPre.normalPer = c.toFixed(2);
        }

        if (this.leftOneData.disabled > 0) {
            let d: any = ((this.leftOneData.disabled / this.leftOneTotal) * 100);
            this.leftOneDataPre.disabledPer = d.toFixed(2);
        }

        this.leftOneChart =
            {
                title: {
                    text: ' ' + this.leftOneTotal + ' 台\n设备',
                    x: '40%',
                    y: '40%',
                    itemGap: 50,
                    textStyle: {
                        color: '#8a8a8a',
                        fontSize: 18,
                        fontWeight: 'normal',
                    },
                    subtextStyle: {
                        color: '#de4751',
                        fontSize: 12
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                },

                series: [
                    {
                        name: '设备',
                        type: 'pie',
                        clockWise: true,
                        center: ['46%', '50%'],
                        radius: ['40%', '60%'],
                        color: ['#f93215', '#ff8400', '#2fb35b', '#a0a0a0'],
                        label: {
                            normal: {
                                show: false,
                                position: 'center'
                            }
                        },
                        labelLine: {
                            normal: {
                                show: false
                            }
                        },
                        data: [
                            {value: data.high, name: '严重'},
                            {value: data.warning, name: '告警'},
                            {value: data.normal, name: '正常'},
                            {value: data.disabled, name: '禁止'},
                        ],
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
    }

    setLeftTwo(data) {
        this.leftTwoDataPre = {
            highPer: 0,
            warningPer: 0,
            normalPer: 0,
            disabledPer: 0,
        };
        this.leftTwoTotal = data.disabled + data.high + data.normal + data.warning;
        if (this.leftTwoData.high > 0) {
            let w: any = ((this.leftTwoData.high / this.leftTwoTotal) * 100);
            this.leftTwoDataPre.highPer = w.toFixed(2);
        }

        if (this.leftTwoData.warning > 0) {
            let x: any = ((this.leftTwoData.warning / this.leftTwoTotal) * 100);
            this.leftTwoDataPre.warningPer = x.toFixed(2);
        }

        if (this.leftTwoData.normal > 0) {
            let y: any = ((this.leftTwoData.normal / this.leftTwoTotal) * 100);
            this.leftTwoDataPre.normalPer = y.toFixed(2);
        }

        if (this.leftTwoData.disabled > 0) {
            let z: any = ((this.leftTwoData.disabled / this.leftTwoTotal) * 100);
            this.leftTwoDataPre.disabledPer = z.toFixed(2);
        }

        this.leftTwoChart =
            {
                title: {
                    text: '  ' + this.leftTwoTotal + '个\n监测点',
                    x: '40%',
                    y: '40%',
                    itemGap: 50,
                    textStyle: {
                        color: '#8a8a8a',
                        fontSize: 18,
                        fontWeight: 'normal',
                    },
                    subtextStyle: {
                        color: '#de4751',
                        fontSize: 12
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                },

                series: [
                    {
                        name: '监测点',
                        type: 'pie',
                        clockWise: true,
                        center: ['47%', '50%'],
                        radius: ['40%', '60%'],
                        color: ['#f93215', '#ff8400', '#2fb35b', '#a0a0a0'],
                        label: {
                            normal: {
                                show: false,
                                position: 'center'
                            }
                        },
                        labelLine: {
                            normal: {
                                show: false
                            }
                        },
                        data: [
                            {value: data.high, name: '严重'},
                            {value: data.warning, name: '告警'},
                            {value: data.normal, name: '正常'},
                            {value: data.disabled, name: '禁止'},
                        ],
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
    }

    //资源分组统计
    findGroupCount() {
        this.layoutSer.findGroupCount().subscribe(
            (res) => {
                if (res.data.length > 0) {
                    this.rightTotal = res.data.length;
                    this.rightOneChart = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },

                        series: [
                            {
                                name: '',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '60%'],
                                data: res.data.map(e => {
                                    const arr = {
                                        value: e.count,
                                        name: e.name
                                    };
                                    return arr;
                                }),
                                itemStyle: {
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    };
                }
            }
        );
    }

    //主机资源统计
    findHostCount() {
        this.layoutSer.findHostCount().subscribe(
            (res) => {
                if (res.data && res.data.length > 0) {
                    this.rightTwoChart = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },

                        series: [
                            {
                                name: '',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '60%'],
                                data: res.data.map(e => {
                                    const arr = {
                                        value: e.count,
                                        name: e.name
                                    };
                                    return arr;
                                }),
                                itemStyle: {
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    };
                }
            }
        );
    }

    //告警总数趋势
    getAlarmTrend() {
        const data = {
            timeType: this.timeTypeTrend,
            startTime: this.trendObj.startTime,
            endTime: this.trendObj.endTime,
        };
        this.analysisSer.waringTrendByHost(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    if (res.data.length > 0) {
                        this.noData = false;
                        const response = res.data;
                        this.setAlarmTrend(response);
                    } else {
                        this.noData = true;
                    }
                } else {
                    this.noData = true;
                }
                this.isTrendLoading = false;
            }
        );
    }

    //设置告警趋势echarts图表
    setAlarmTrend(data) {
        this.charTrendOption = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                },
            },
            legend: {
                data: ['严重', '告警']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    axisLine: {
                        lineStyle: {
                            color: '#b6d0f0',
                        }
                    },
                    data: data.map((e) => {
                        return e.date;
                    })
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    minInterval: 1,
                    axisLine: {
                        lineStyle: {
                            color: '#b6d0f0',
                        }
                    },
                    axisLabel: {
                        show: true,
                        interval: 'auto',
                        formatter: '{value} 个'
                    },
                    boundaryGap: [0, 0.1],
                }
            ],
            series: [

                {
                    name: '严重',
                    type: 'bar',
                    stack: '严重',
                    itemStyle: {
                        normal: {
                            color: '#e96545',
                        }
                    },
                    data: data.map(e => {
                        return e.errorcount;
                    })
                },
                {
                    name: '告警',
                    type: 'bar',
                    stack: '告警',
                    itemStyle: {
                        normal: {
                            color: '#eede85',
                        }
                    },
                    data: data.map(e => {
                        return e.waringcount;
                    })
                }
            ]
        };
    }

    //发送利用率排名
    countOrde() {
        const data = {
            limit: '10'
        };
        this.overAllSer.homeUseOrder(data.limit).subscribe(
            (res) => {
                this.flowListPre = res.data;
            }
        );
    }

    //主机发送接收流量排名列表  数值
    flowRankNum() {
        const data = {
            limit: '10'
        };
        this.overAllSer.homeFlowOrder(data.limit).subscribe(
            (res) => {
                this.flowListNum = res.data;
            }
        );
    }

    //cpu内存使用率排名列表  百分比
    flowRankPre() {
        const data = {
            limit: '10'
        };
        this.overAllSer.runStateOrder(data.limit).subscribe(
            (res) => {
                this.countOrderList = res.data;
            }
        );
    }

    changeTrend(e) {
        this.timeTypeTrend = e;
        this.isTrendLoading = true;
        const nowDate = new Date().getTime();
        let day1, day2;
        switch (this.timeTypeTrend) {
            case'1': {
                day1 = nowDate - 1 * 60 * 60 * 1000;
                this.trendObj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                this.trendObj.endTime = this.datePipe.transform(nowDate, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'2': {
                day1 = nowDate - 1 * 24 * 60 * 60 * 1000;
                this.trendObj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                this.trendObj.endTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'3': {
                day1 = nowDate - 3 * 24 * 60 * 60 * 1000;
                day2 = nowDate;
                this.trendObj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                this.trendObj.endTime = this.datePipe.transform(day2, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'4': {
                day1 = nowDate - 7 * 24 * 60 * 60 * 1000;
                day2 = nowDate;
                this.trendObj.startTime = this.datePipe.transform(day1, 'yyyy-MM-dd') + ' 00:00:00';
                this.trendObj.endTime = this.datePipe.transform(day2, 'yyyy-MM-dd') + ' 23:59:59';
                break;
            }
            case'5': {
                break;
            }
        }
        this.getAlarmTrend();
    }

    //查询拓扑图
    getDetail(e) {
        console.log(e);
        this.smartTopologyView.getDetail(e);
    }
}
