import {Component, OnInit} from '@angular/core';
import {color} from '../../app.constants';
import {BusinessService} from '../../business/business.service';
import {OverAllService} from '../../overAll/overAll.service';
import {CommonService} from '../../shared/common/common.service';
import {DatePipe} from '@angular/common';
import {NzMessageService} from 'ng-zorro-antd';
import {AnalysisService} from '../analysis.service';

@Component({
    selector: 'smart-b-count',
    templateUrl: './b-count.component.html',
    styles: [
            `
            .chart-div {
                border: 1px solid #dadada;
                margin-top: 20px;
                padding: 10px;
            }

            .chart-left {
                margin-left: 20px;
            }

            .chart-left p {
                margin-left: 20px;
            }

            .header > div {
                height: 250px;
                position: relative;
            }

            .header div > .position-center {
                position: absolute;
                width: 100%;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }

            .position-center > p {
                margin-bottom: 8px;
            }

            .p1 {
                font-size: 20px;
            }

            .p2 {
                font-size: 40px;
            }

            .spanBorder span.select {
                border: 1px solid #6097b7;
                color: #6097b7;
            }
        `
    ]
})
export class BCountComponent implements OnInit {

    color = color;
    colorArr = ['#f36969', '#02c8cf', '#eaaa00', '#61a600', '#4484d4'];
    timeType = '4';
    rootList;  //业务列表
    isLoading = false;
    serviceId;
    analyObj;  //业务信息
    runObj;
    httptestid;  //网站监测id
    analyOption;   //监测点echart
    runOption;

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

    //图表
    isSpinning = false;
    noData = true;
    userData = true;
    speed;
    time;
    chartSpeed;
    chartTime;

    constructor(private busineSer: BusinessService, private overAllSer: OverAllService,
                private commonSer: CommonService,
                private analySer: AnalysisService,
                private datePipe: DatePipe, private message: NzMessageService) {
    }

    ngOnInit() {
        this.getServiceList();
    }

    //更改业务
    changeService() {
        this.isLoading = true;
        this.getInfo();
        this.getRunTime();
    }

    //系统可用性, 监测点, 用户统计
    getInfo() {
        this.busineSer.serviceAnalysisCount(this.serviceId).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.analyObj = res.data;
                    this.setAnalyOption();
                }
                this.isLoading = false;
            }
        );
    }

    setAnalyOption() {
        let echartData = [{
            value: this.analyObj.danger,
            name: '严重'
        }, {
            value: this.analyObj.alarm,
            name: '告警'
        }, {
            value: this.analyObj.normal,
            name: '正常'
        }, {
            value: this.analyObj.unknown,
            name: '未知'
        }];
        let rich = {
            red: {
                color: this.color.red,
                padding: [5, 4],
                align: 'center'
            },
            yellow: {
                color: this.color.yellow,
                align: 'center'
            },
            green: {
                color: this.color.green,
                align: 'center',
                padding: [21, 0]
            },
            gray: {
                color: this.color.gray,
                align: 'center'
            },
            black: {
                color: this.color.black,
                padding: [5, 4],
                align: 'center'
            },
        };
        this.analyOption = {
            title: {
                text: '监测点',
                left: 'center',
                top: '45%',
                textStyle: {
                    fontSiz: 6,
                    align: 'center'
                }
            },
            legend: {
                selectedMode: false,
                formatter: (name) => {
                    let total = this.analyObj.total;
                    return '{black|' + total + '个}';
                },
                data: [echartData[0].name],
                left: 'center',
                top: '35%',
                icon: 'none',
                align: 'center',
                textStyle: {
                    color: '#fff',
                    rich: rich
                },
            },
            series: [{
                name: '监测点',
                type: 'pie',
                radius: ['42%', '60%'],
                hoverAnimation: false,
                color: [this.color.red, this.color.yellow, this.color.green, this.color.gray],
                label: {
                    normal: {
                        formatter: (params, ticket, callback) => {
                            let total = 0; //总数量
                            let percent; //占比
                            echartData.forEach((value, index, array) => {
                                total += value.value;
                            });
                            if (params.value == 0) {
                                percent = 0;
                            } else if (params.value > 0) {
                                percent = ((params.value / total) * 100).toFixed(1);
                            }
                            return '{black|' + params.name + '：}{black|' + params.value + '个}\n{black|' + percent + '%}';
                        },
                        rich: rich
                    },
                },
                data: echartData
            }]
        };
    }

    //运行时长
    getRunTime() {
        const data = {
            serviceid: this.serviceId,
            period: 'yearly',
            year: ''
        };
        this.analySer.serviceSla(data).subscribe(
            (res) => {
                this.runObj = res.apiResponse.data.sla[0];
                this.setRunOption();
            }
        );
    }

    setRunOption() {
        let echartData = [{
            value: this.runObj.problemTime,
            name: '问题'
        }, {
            value: this.runObj.downtimeTime,
            name: '断线'
        }, {
            value: this.runObj.okTime,
            name: '正常'
        }];

        let rich = {
            red: {
                color: this.color.red,
                padding: [5, 4],
                align: 'center'
            },
            yellow: {
                color: this.color.yellow,
                align: 'center'
            },
            green: {
                color: this.color.green,
                align: 'center',
                padding: [21, 0]
            },
        };
        this.runOption = {
            title: {
                text: '运行时长',
                left: 'center',
                top: '45%',
                textStyle: {
                    fontSiz: 6,
                    align: 'center'
                }
            },
            legend: {
                selectedMode: false,
                formatter: (name) => {
                    let total: any = this.runObj.to - this.runObj.from;
                    let time = '';
                    let days = parseInt(String(total / (1000 * 60 * 60 * 24)));
                    let hours = parseInt(String((total % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)));
                    let minutes = parseInt(String((total % (1000 * 60 * 60)) / (1000 * 60)));
                    let seconds = (total % (1000 * 60)) / 1000;
                    if (days > 0) time += days + '天';
                    if (hours > 0) time += hours + '小时';
                    if (minutes > 0) time += minutes + '分钟';
                    if (seconds > 0) time += seconds.toFixed(0) + '秒';
                    return '{black|' + time + '}';
                },
                data: [echartData[0].name],
                left: 'center',
                top: '35%',
                icon: 'none',
                align: 'center',
                textStyle: {
                    rich: rich
                },
            },
            series: [{
                name: '运行时长',
                type: 'pie',
                radius: ['42%', '60%'],
                hoverAnimation: false,
                color: [this.color.red, this.color.yellow, this.color.green, this.color.gray],
                label: {
                    normal: {
                        textStyle: {
                            color: '#000',
                        },
                        formatter: (params, ticket, callback) => {
                            let total = 0; //总数量
                            let percent; //占比
                            echartData.forEach((value, index, array) => {
                                total += value.value;
                            });
                            if (params.value == 0) {
                                percent = 0;
                            } else if (params.value > 0) {
                                percent = ((params.value / total) * 100).toFixed(4);
                            }
                            let str;
                            if (params.name == '正常') str = '{black|' + params.name + '：}{black|' + this.runObj.okTImeValue + '}\n{black|' + percent + '%}';
                            if (params.name == '问题') str = '{black|' + params.name + '：}{black|' + this.runObj.problemTimeValue + '}\n{black|' + percent + '%}';
                            if (params.name == '断线') str = '{black|' + params.name + '：}{black|' + this.runObj.downtimeTimeValue + '}\n{black|' + percent + '%}';
                            return str;
                        },
                        rich: rich
                    },
                },
                data: echartData
            }]
        };
    }

    //业务列表
    getServiceList() {
        this.busineSer.findRoot().subscribe(
            (res) => {
                this.rootList = res.data;
                if (this.rootList.length > 0) {
                    this.serviceId = this.rootList[0].serviceid;
                    this.changeService();
                    this.getRunTime();
                }
            }
        );
    }

    //选择网站监测
    selectHttp(item) {
        this.httptestid = item.httptestid;
        this.changeType();
    }

    //时间改变
    changeType() {
        this.isSpinning = true;
        if (this.timeType == '99') return;
        this.obj.startTime = this.commonSer.getTimeByType(this.timeType).startTime;
        this.obj.endTime = this.commonSer.getTimeByType(this.timeType).endTime;
    }

    //监测图表
    findChart() {
        const data = {
            startTime: this.obj.startTime,
            endTime: this.obj.endTime,
            limit: '',
            httptestid: this.httptestid
        };
        this.overAllSer.findChart(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    const speed = res.data.speed;
                    this.speed = res.data.speed;
                    const time = res.data.time;
                    this.time = res.data.time;
                    this.setOption(speed, time);
                }
            }
        );
    }

    //绘制图表
    setOption(speed, time) {
        this.chartSpeed = {
            title: {
                text: '速度',
                left: '40%',
            },
            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;
                    }
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {
                        show: false
                    }
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: speed[0].data.map(res => {
                    return res.date;
                }),
            },
            yAxis: {
                type: 'value',
                axisLabel: {   //Y轴数据
                    formatter: (value) => {
                        return Math.abs(value) / 1000 + ' kbps';
                    },
                    textStyle: {
                        color: '#666'
                    }
                },
            },
            series: speed.map((res1, index) => {
                const number = res1.data.map(res2 => {
                    return res2.val;
                });
                const obj = {
                    name: res1.name,
                    type: 'line',
                    stack: '总量',
                    itemStyle: {
                        normal: {
                            lineStyle: {
                                color: this.colorArr[index]
                            }
                        }
                    },
                    data: number
                };
                return obj;
            })
        };

        this.chartTime = {
            title: {
                text: '响应时间',
                left: '40%',
            },
            tooltip: {
                // trigger: 'axis',
                formatter: (params) => {
                    if (params.data) {
                        let res = params.seriesName;
                        res += '<br/>时间：' + params.name;
                        res += '<br/>相应时间：' + params.data + 's';
                        return res;
                    }
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {
                        show: false
                    }
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: time[0].data.map(res => {
                    return res.date;
                })
            },
            yAxis: {
                type: 'value',
                axisLabel: {   //Y轴数据
                    formatter: (value) => {
                        return value + ' s';
                    },
                    textStyle: {
                        color: '#666'
                    }
                },
            },
            series: time.map((res1, index) => {
                const number = res1.data.map(res2 => {
                    return res2.val;
                });
                const obj = {
                    name: res1.name,
                    type: 'line',
                    stack: '总量',
                    itemStyle: {
                        normal: {
                            lineStyle: {
                                color: this.colorArr[index]
                            }
                        }
                    },
                    data: number
                };
                return obj;
            })
        };

        this.isSpinning = false;
    }

}
