import {AfterViewInit, Component, ElementRef, OnInit, Renderer, ViewChild,} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {OverAllService} from '../../overAll.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import {BasiCheckComponent} from '../../../modal/basi-check/basi-check.component';
import {NzModalService} from 'ng-zorro-antd';
import {color, pageSize} from '../../../app.constants';
import {WarnListComponent} from '../../../modal/warn-list/warn-list.component';
import {DatePipe} from '@angular/common';
import {ThresholdComponent} from '../../../modal/threshold/threshold.component';

@Component({
    selector: 'jhi-basic-detail',
    templateUrl: './basic-detail.component.html',
    styles: [
            `
            .checkTags {
                position: absolute;
                top: 12px;
                left: 233px;
                z-index: 989;
            }
            .time-select{
                position: absolute;
                top: 55px;
                right: 15px;
                z-index: 999;
            }
            .select-border{
                border: 1px solid #6097b7;
                border-radius: 5px;
                padding: 2px;
                margin-right: 5px;
            }
            :host ::ng-deep .tabs-smart .ant-tabs-nav-scroll div.ant-tabs-tab:nth-child(3){
                margin-right: 180px !important;
            }
            :host ::ng-deep .ant-radio-button-wrapper{
                margin: 4px;
            }
        `
    ]
})
export class BasicDetailComponent implements OnInit, AfterViewInit {
    @ViewChild('smartCheck') smartCheck: BasiCheckComponent;
    @ViewChild('smartThreshold') smartThreshold: ThresholdComponent;
    @ViewChild('thirdTabs') thirdTabs: ElementRef;
    @ViewChild('warnList') warnList: WarnListComponent;
    @ViewChild('colorEle') colorEle:ElementRef;
    @ViewChild('checkEle') checkEle:ElementRef;
    color = color;
    loading = false;
    hostId: string;
    tabNum = 0;
    hostName;
    realName;
    size = 'default';
    changeStates;
    chartOption1;
    responseTimeStr;
    losedStr;
    cpuUsedStr;
    usedStr;
    chartOption2;
    chartOption3;
    chartOption4;
    secondOptionLeft;
    secondOptionRight;
    dataSet: any[];
    panel1 = {active: true, name: '响应时间与丢包率', disabled: false};
    panel2 = {active: true, name: 'CPU使用率及内存使用率',disabled: false};
    panel3 = {active: true, name: '磁盘使用情况', disabled: false};

    //监控点
    isBasicEdit;
    itemTypeValue;
    interfaceList: any[];
    itemTypeList: any[];

    //
    checkList: any[];
    isCheck = false;
    checkStatus = {
        warning: null,
        normal: null,
        disabled: null,
        high: null
    };

    isKey = false;
    keyList: any[];
    keyType = '1';

    //图表
    isGrapha = false;
    selectGraphadata;
    chartOptionGrapha;
    imageSelectDate = new Date();

    pageSize = pageSize;

    //分页--监控点
    pageIndex = 1;  //当前页数
    totalNum;   //总数据长度
    applicationId;    //分类ID

    //进出口流量-分页
    pageNum = 1;
    pageCount = 5;
    totalNumInOut;
    inOutLoading;

    //分页--告警
    warn_totalNum;
    warn_pageNum = 1;

    searchName;

    validateForm: FormGroup;

    isSpinning;  //刷新
    units;   //图表单位

    constructor(private routerInfo: ActivatedRoute, private message: NzMessageService,
                private overAllSer: OverAllService, private renderer: Renderer,private router:Router,
                private fb: FormBuilder, private modalService: NzModalService,private datePipe:DatePipe) {
        this.routerInfo.queryParams.subscribe(queryParams => {
            this.hostId = queryParams.hostId;
            this.overAllSer.findDetailed(this.hostId).subscribe(
                (res)=>{
                    let data = res.data[0]
                    this.hostName = data.name;   //显示名
                    this.realName = data.host;   //主机名
                }
            )
        });
    }

    ngOnInit() {
        this.isSpinning = true;
        this.responseTime();
        this.losed();
        this.cpused();
        this.used();
        // this.inOutInfo();

        //监测点
       this.getList();

        //历史告警
        const obj = {};
        this.warnList.getList(obj);
        this.disks();
    }

    ngAfterViewInit() {
        this.checkEle.nativeElement.children[1].children[0].children[0].children[2].children[0].children[0].children[2].style.marginRight = this.colorEle.nativeElement.offsetWidth +'px';
    }

    //平均响应时间
    responseTime() {
        this.overAllSer.responseTime(this.hostId).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.responseTimeStr = res.data.responseTime.toFixed(2);
                    const responseTime = this.responseTimeStr;
                    const other = 100 - this.responseTimeStr;
                    const data = [
                        {value: responseTime},
                        {value: other},
                        {
                            value: 100, name: '', tooltip: {
                                formatter: function(a) {
                                    return '';
                                }
                            }
                        }
                    ];
                    this.chartOption1 = {
                        title: {
                            text: '平均响应时间',
                            top: '5%',
                            left: '35%',
                            textStyle: {
                                color: '#999',
                                fontSize: 12,
                            }
                        },
                        tooltip: {
                            trigger: 'item',
                            show: false,
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        color: ['#7eb6ea', '#eeeeee', 'transparent'],
                        series: [
                            {
                                type: 'pie',
                                startAngle: 180,
                                radius: ['50%', '85%'],
                                center: ['50%', '75%'],
                                hoverAnimation: true,
                                data: data,
                                itemStyle: {
                                    normal: {
                                        show: false,
                                        position: 'center'
                                    },
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },
                                labelLine: {
                                    normal: {
                                        show: false
                                    }
                                },
                            }
                        ]
                    };
                } else {
                    this.message.info(res.errMsg);
                }

            }
        );
    }

    //丢包率
    losed() {
        this.overAllSer.losed(this.hostId).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.losedStr = res.data.losed;
                    const losed = res.data.losed;
                    const other = 100 - res.data.losed;
                    const data = [
                        {value: losed},
                        {value: other},
                        {
                            value: 100, name: '', tooltip: {
                                formatter: function(a) {
                                    return '';
                                }
                            }
                        }
                    ];
                    this.chartOption2 = {
                        title: {
                            text: '丢包率',
                            top: '5%',
                            left: '38%',
                            textStyle: {
                                color: '#999',
                                fontSize: 12,
                            }
                        },
                        tooltip: {
                            trigger: 'item',
                            show: false,
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        color: ['#7eb6ea', '#eeeeee', 'transparent'],
                        series: [
                            {
                                type: 'pie',
                                startAngle: 180,
                                radius: ['50%', '85%'],
                                center: ['50%', '75%'],
                                hoverAnimation: true,
                                data: data,
                                itemStyle: {
                                    normal: {
                                        show: false,
                                        position: 'center'
                                    },
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },
                                labelLine: {
                                    normal: {
                                        show: false
                                    }
                                },
                            }
                        ]
                    };
                } else {
                    this.message.info(res.errMsg);
                }

            }
        );
    }

    //cup使用率
    cpused() {
        const data = {
            hostId: this.hostId,
        };
        this.overAllSer.cupUsed(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.cpuUsedStr = res.data.cpuUsed;
                    const losed = res.data.cpuUsed;
                    const other = 100 - res.data.cpuUsed;
                    const data = [
                        {value: losed},
                        {value: other},
                        {
                            value: 100, name: '', tooltip: {
                                formatter: function(a) {
                                    return '';
                                }
                            }
                        }
                    ];
                    this.chartOption3 = {
                        title: {
                            text: 'CPU使用率',
                            top: '5%',
                            left: '38%',
                            textStyle: {
                                color: '#999',
                                fontSize: 12,
                            }
                        },
                        tooltip: {
                            trigger: 'item',
                            show: false,
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        color: ['#7eb6ea', '#eeeeee', 'transparent'],
                        series: [
                            {
                                type: 'pie',
                                startAngle: 180,
                                radius: ['50%', '85%'],
                                center: ['50%', '75%'],
                                hoverAnimation: true,
                                data: data,
                                itemStyle: {
                                    normal: {
                                        show: false,
                                        position: 'center'
                                    },
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },
                                labelLine: {
                                    normal: {
                                        show: false
                                    }
                                },
                            }
                        ]
                    };
                } else {
                    this.message.info(res.errMsg);
                }

            }
        );
    }

    //内存使用率
    used() {
        const data = {
            hostId: this.hostId,
        };
        this.overAllSer.used(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.usedStr = res.data.used;
                    const used = res.data.used;
                    const other = 100 - res.data.used;
                    const data = [
                        {value: used},
                        {value: other},
                        {
                            value: 100, name: '', tooltip: {
                                formatter: function(a) {
                                    return '';
                                }
                            }
                        }
                    ];
                    this.chartOption4 = {
                        title: {
                            text: '内存使用率',
                            top: '5%',
                            left: '38%',
                            textStyle: {
                                color: '#999',
                                fontSize: 12,
                            }
                        },
                        tooltip: {
                            trigger: 'item',
                            show: false,
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        color: ['#7eb6ea', '#eeeeee', 'transparent'],
                        series: [
                            {
                                type: 'pie',
                                startAngle: 180,
                                radius: ['50%', '85%'],
                                center: ['50%', '75%'],
                                hoverAnimation: true,
                                data: data,
                                itemStyle: {
                                    normal: {
                                        show: false,
                                        position: 'center'
                                    },
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },
                                labelLine: {
                                    normal: {
                                        show: false
                                    }
                                },
                            }
                        ]
                    };
                } else {
                    this.message.info(res.errMsg);
                }

            }
        );
    }

    //磁盘使用率
    disks() {
        const data = {
            hostId: this.hostId,
        };
        this.overAllSer.disks(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.secondOptionLeft = {
                        grid: {
                            left: '8%',
                            right: '0',
                            bottom: '1%',
                            containLabel: true
                        },
                        tooltip: {
                            trigger: 'axis',
                        },
                        xAxis: {
                            type: 'value',
                            show: false,
                        },
                        yAxis: {
                            triggerEvent: true,
                            type: 'category',
                            axisTick: {
                                show: false
                            },
                            axisLine: {
                                show: false,
                            },
                            // 分割线设置
                            splitLine: {
                                show: true,  //显示分割线
                            },
                            data: res.data.disks.map((item) => {
                                return item.name;
                            }),
                            axisLabel:res.data.disks.map((item) => {
                                let data = item.name;
                                if(data.length > 5) {
                                    data = data.substring(0, 4) + "..";
                                }
                                return data;
                            }),
                        },
                        color: ['#ed7a7b', '#f2f2f2'],
                        series: [
                            {
                                name: '已使用',
                                type: 'bar',
                                stack: '总空间',
                                label: {
                                    normal: {
                                        show: true,
                                        position: 'insideRight',
                                        formatter: (obj) => {
                                            const item = (res.data.disks[obj.dataIndex].used / (1024 * 1024 * 1024)).toFixed(2);
                                            return item + 'G';
                                        }
                                    }
                                },
                                itemStyle: {
                                    normal: {
                                        color: '#0D5DCB'
                                    },
                                },
                                data: res.data.disks.map((item) => {
                                    const pre = ( (item.used / item.total) * 100 ).toFixed(2);  //已使用百分比
                                    return pre;
                                })
                            },
                            {
                                name: '剩余空间',
                                type: 'bar',
                                stack: '总空间',
                                label: {
                                    normal: {
                                        show: true,
                                        position: 'insideRight',
                                        formatter: (obj) => {
                                            const cut = (res.data.disks[obj.dataIndex].total - res.data.disks[obj.dataIndex].used);
                                            const item = (cut / (1024 * 1024 * 1024)).toFixed(2);
                                            return item + 'G';
                                        }
                                    }
                                },
                                itemStyle: {
                                    normal: {
                                        color: '#bfbfbf'
                                    },
                                },
                                data: res.data.disks.map((item) => {
                                    const pre = ( (item.total - item.used) / (item.total) * 100 ).toFixed(2); //剩余百分比
                                    return pre;
                                })
                            },
                        ]
                    };

                    let total = res.data.disks.map((item) => {
                        return item.total;
                    });
                    total = this.add(total);

                    let used = res.data.disks.map((item) => {
                        return item.used;
                    });
                    used = this.add(used);

                    const arr = [
                        {
                            name:"已使用",
                            value:used,
                        },
                        {
                            name:"未使用",
                            value:total,
                        }
                    ];

                    this.secondOptionRight = {
                        title: {
                            text: '磁盘总体使用占比',
                            x: 'center'
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        color: ['#3194e0','#bfbfbf'],
                        series: [
                            {
                                name: '',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '60%'],
                                data: arr,
                                itemStyle: {
                                    normal: {
                                        label: {
                                            position: 'inner',
                                            show: true,
                                            formatter: '{b} : {c} ({d}%)'
                                        },
                                        labelLine: {show: true}
                                    }
                                },
                                labelLine: {
                                    normal: {
                                        show: false
                                    }
                                },
                            }
                        ]
                    };

                } else {
                    this.message.info(res.errMsg);
                }
                this.isSpinning = false;
            }
        );
    }

    extension(){

    }

    add(arr) {
        let total = 0;
        for (let i = 0; i < arr.length; i++) {
            total += arr[i];
        }
        return (total / 1024 / 1024 / 1024).toFixed(2);
    }

    //进出口流量-SNMP
    inOutInfo() {
        this.inOutLoading = true;
        const data = {
            obj:{
                hostid:Number(this.hostId)
            },
            pageNum:this.pageNum,
            pageCount:this.pageCount
        }
        this.overAllSer.inOutInfoSnmp(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.dataSet = res.data.data;
                    this.inOutLoading = false;
                    this.totalNumInOut = res.data.totalNum;
                }else{
                    this.message.info(res.errMsg);
                }
            }
        );
    }

    //进出口流量 翻页
    changeInoutInfo(e){
        this.pageNum = e;
        // this.inOutInfo();
    }

    //添加监测点
    showCheckModal() {
        this.smartCheck.showAddModal(this.hostId,this.realName,'添加监测点');
    }

    //编辑监测点
    showEditModal(item){
        this.smartCheck.showEditModal(this.hostId,item.itemid,this.realName,item.templateid,'编辑监测点');
    }

    //添加阈值
    showAddThresholdModal(item){
        this.smartThreshold.showAddModal("添加阈值",item.itemid,this.realName);
    }

    //编辑阈值
    showEditThresholdModal(item){
        this.smartThreshold.showEditModal("编辑阈值",item.itemid,this.hostId,this.realName);
    }

    //添加or编辑监测点 之后
    getList(){
        this.getCheckList();
        this.findItemType();
    }

    handleKeyCancel() {
        this.isKey = false;
    }

    handleKeyOk() {
        this.isKey = false;
    }

    //监测点列表
    getCheckList() {
        this.getCheckStatus();
        this.loading = true;
        const data = {
            pageNum: this.pageIndex,
            pageCount: pageSize,
            obj:{
                applicationid: this.applicationId,
                hostid: this.hostId,
                priorityName:this.changeStates,
                name:this.searchName
            }
        };
        this.overAllSer.findCheckByType(data).subscribe(
            (res) => {
                this.checkList = res.data.data;
                this.totalNum = res.data.totalNum;
                this.loading = false;
            }
        );
    }

    changeState(state){
        this.tabNum = 1;
        this.changeStates = state;
        this.getCheckList();
    }

    //分页
    change(e) {
        this.pageIndex = e;
        this.getCheckList();
    }

    changeType(item) {
        this.pageIndex = 1;
        if(item.name == "全部"){
            this.changeStates = null;
        }
        this.applicationId = item.applicationid;
        this.getCheckList();
    }

    //监测点状态
    getCheckStatus() {
        this.overAllSer.findItemCount(this.hostId).subscribe(
            (res) => {
                if(res.errCode == 10000){
                    this.checkStatus = res.data;
                }
            }
        );
    }

    //删除监测点
    deleteCheckItem(item) {
        this.modalService.confirm({
            nzTitle: '删除',
            nzContent: '<b style="color: red;">确认删除该监测点吗？</b>',
            nzOkText: '确定',
            nzOkType: 'danger',
            nzOnOk: () => {
                const data = {
                    itemids:[item.itemid],
                    templateid:item.templateid
                };
                this.overAllSer.deleteItem(data).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.message.success('删除成功');
                            this.getCheckList();
                        } else {
                            this.message.error(res.errMsg);
                        }
                    }
                );
            },
            nzCancelText: '取消',
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //图表
    showImageModal(data) {
        this.isGrapha = true;
        this.selectGraphadata = data;

        this.getGraphDate();
    }

    //获取图表数据
    getGraphDate(){
        const data = {
            date: this.datePipe.transform(this.imageSelectDate,'yyyy-MM-dd'),
            itemid: this.selectGraphadata.itemid
        };
        this.overAllSer.findGraphData(data).subscribe(
            (res) => {
                if (res.errCode == 10000 && res.data.length > 0) {
                    const result = res.data;
                    this.chartOptionGrapha = {
                        title: {
                            text: this.selectGraphadata.name
                        },
                        tooltip: {
                            trigger: 'axis'
                        },
                        xAxis: {
                            data: result.map((item) => {
                                return item.time;
                            })
                        },
                        yAxis: {
                            splitLine: {
                                show: false
                            },
                            axisLabel:{   //Y轴数据
                                formatter:(value)=>{
                                    return value+ " " +this.selectGraphadata.units;   //负数取绝对值变正数
                                },
                            },
                        },
                        dataZoom: [{
                            startValue: '2014-06-01'
                        }, {
                            type: 'inside'
                        }],
                        series: {
                            type: 'line',
                            data: result.map((item) => {
                                return item.value ;
                            }),

                        }
                    };
                }
            }
        );
    }

    handleImageCancel() {
        this.isGrapha = false;
        this.chartOptionGrapha = null;
    }

    //监控项分类
    findItemType() {
        const data = {
            'hostids': []
        };
        data.hostids.push(this.hostId);
        this.overAllSer.findItemType(data).subscribe(
            (res) => {
                this.itemTypeList = res.data;
                const data = {
                    applicationid:'',
                    name:'全部'
                };
                if (null!=res.data){
                    this.itemTypeList.unshift(data);
                }
                this.itemTypeValue = '';

            }
        );
    }

    //停止/启用监控项  0  启用   1停止
    updateItem(itemid, status) {
        const data = {
            'status': status,
            'itemid': itemid
        };
        this.modalService.confirm({
            nzTitle: '',
            nzContent: '<b style="color: red;">确认修改监控项状态吗？</b>',
            nzOkText: '确定',
            nzOkType: 'danger',
            nzOnOk: () => {
                this.overAllSer.itemUpdate(data).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.getCheckList();
                        }
                        this.message.info(res.errMsg);
                    }
                );
            },
            nzCancelText: '取消',
            nzOnCancel: () => console.log('Cancel')
        });
    }

    //删除单个资源
    showDeleteConfirm() {
        this.modalService.confirm({
            nzTitle: '删除',
            nzContent: '<b style="color: red;">确认删除该资源吗？</b>',
            nzOkText: '确定',
            nzOkType: 'danger',
            nzOnOk: () => {
                const data = {
                    hostids:[]
                };
                data.hostids.push(this.hostId);
                this.overAllSer.deleteHostPost(data).subscribe(
                    (res) => {
                        if (res.errCode == 10000) {
                            this.message.success('删除成功');
                            this.router.navigate(['app/main/basic']);
                        } else {
                            this.message.error(res.errMsg);
                        }
                    }
                );
            },
            nzCancelText: '取消',
            nzOnCancel: () => console.log('Cancel')
        });
    }
}
