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

@Component({
    selector: 'smart-effect-analysis',
    templateUrl: './effect-analysis.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%);
            }

            .p1 {
                font-size: 20px;
            }

            .p2 {
                font-size: 40px;
            }

            .spanBorder span.select {
                border: 1px solid #6097b7;
                color: #6097b7;
            }
        `
    ]
})
export class EffectAnalysisComponent implements OnInit {
    color = color;
    colorArr = ['#f36969', '#02c8cf', '#eaaa00', '#61a600', '#4484d4'];
    timeType = '1';
    rootList;  //业务列表
    webList;  //网站检测列表
    triggerList;   //监测点列表
    isLoading = false;
    serviceId;
    analyObj;  //业务信息
    httptestid;  //网站监测id
    analyOption;   //监测点echart

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

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

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

    ngOnInit() {
        this.getServiceList();
    }

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

    //系统可用性, 监测点, 用户统计
    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
            }]
        };
    }

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

    //监测点列表
    getTriggerlist() {
        this.busineSer.triggerList(this.serviceId).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.triggerList = res.data;
                }
            }
        );
    }

    //网站监测列表
    getWeblist() {
        this.busineSer.findHttptest(this.serviceId).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.webList = res.data;
                    if (this.webList.length > 0) {
                        this.selectHttp(this.webList[0]);
                    }
                    this.noData = false;
                } else {
                    this.noData = true;
                    this.message.info(res.errMsg);
                }
            }
        );
    }

    //用户数量趋势
    userCount() {
        const data = {
            startTime: this.obj.startTime,
            endTime: this.obj.endTime,
            serviceId: this.serviceId
        };
        this.busineSer.userCount(data).subscribe(
            (res) => {
                const response = res.data;
                if (response.length > 0) {
                    this.chartUser = {
                        legend: {
                            right: 20,
                            data: ['在线用户数', '重要用户数']
                        },
                        xAxis: {
                            type: 'category',
                            data: response.map(e => {
                                return e.createTime;
                            }),
                            boundaryGap: false,
                            axisTick: {
                                show: false
                            },
                        },
                        yAxis: {
                            name: '人数',
                            type: 'value',
                            axisTick: {
                                show: false
                            },
                        },
                        series: [
                            {
                                name: '在线用户数',
                                type: 'line',
                                smooth: true,
                                symbolSize: 6,
                                data: response.map(e => {
                                    return e.onlineUser;
                                }),
                                itemStyle: {
                                    normal: {
                                        color: '#55cece'
                                    }
                                },
                                lineStyle: {
                                    normal: {
                                        width: 3
                                    }
                                }
                            },
                            {
                                name: '重要用户数',
                                type: 'line',
                                smooth: true,
                                symbolSize: 6,
                                data: response.map(e => {
                                    return e.onlineImportantUser;
                                }),
                                itemStyle: {
                                    normal: {
                                        color: '#b7a4dc'
                                    }
                                },
                                lineStyle: {
                                    normal: {
                                        width: 3
                                    }
                                }
                            }]
                    };
                    this.userData = true;
                } else {
                    this.userData = false;
                }
            }
        );
    }

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

    //时间改变
    changeType() {
        this.isSpinning = true;
        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;
            }
        }
        this.findChart();
        this.userCount();
    }

    //监测图表
    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;
    }
}
