import {AfterViewInit, Component, ElementRef, OnInit, Renderer2, ViewChild} from '@angular/core';
import {JhiEventManager} from 'ng-jhipster';
import {Account, 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';

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

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

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

    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内存使用率排名列表
    safeRunDayList;    //安全运行天数

    isTrendLoading = false;

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

    dataSet;  //拓扑图
    topoId;
    isCanvas;

    constructor(
        private overAllSer: OverAllService, private message: NzMessageService,
        private alarmSer: AlarmService, private renderer: Renderer2,
        private layoutSer: LayoutService,
        private principal: Principal,
        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.findSafeRunDay();
    }

    ngAfterViewInit() {

    }

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

    //主机组中统计
    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) => {
                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: '41%',
                    y: '40%',
                    itemGap: 50,
                    textStyle: {
                        color: '#fff',
                        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: '41%',
                    y: '40%',
                    itemGap: 50,
                    textStyle: {
                        color: '#fff',
                        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 = {
            groupid: this.obj.leftGroupId,
            startTime: this.trendObj.startTime,
            endTime: this.trendObj.endTime,
        };
        this.analysisSer.waringTrend(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    if (res.data.length > 0) {
                        const response = res.data;
                        this.setAlarmTrend(response);
                    } else {
                        this.message.warning('告警趋势暂无数据');
                    }
                } else {
                    this.message.error(res.errMsg);
                }
                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: '严重',
                    data: data.map(e => {
                        return e.errorcount;
                    })
                },
                {
                    name: '告警',
                    type: 'bar',
                    stack: '告警',
                    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;
            }
        );
    }

    //业务系统安全运行天数
    findSafeRunDay() {
        const data = {
            pageNum: '1',
            pageCount: '10',
            startTime: '2018-01-01'
        };
        this.overAllSer.findSafeRunDayList(data).subscribe(
            (res) => {
                this.safeRunDayList = res.data.data;
            }
        );
    }

    changeTrend(e) {
        this.isTrendLoading = true;
        const timeObj = this.commonSer.getTimeByType(e);
        this.trendObj.startTime = timeObj.startTime;
        this.trendObj.endTime = timeObj.endTime;
        this.getAlarmTrend();
    }

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