import {AfterViewChecked, AfterViewInit, Component, ElementRef, KeyValueDiffer, OnInit, ViewChild, KeyValueDiffers, DoCheck, OnDestroy} from '@angular/core';
import {TopologyService} from '../topology.service';
import {NzMessageService, NzModalService, UploadFile} from 'ng-zorro-antd';
import {DomSanitizer} from '@angular/platform-browser';
import {TopologyComponent} from '../model/topology/topology.component';
import {CheckComponent} from '../model/check/check.component';
import {LineComponent} from '../model/line/line.component';
import {NodeComponent} from '../model/node/node.component';
import {SelectRadioGroupComponent} from '../../modal/select-radio-group/select-radio-group.component';

declare let editor: any;
declare var layui: any;

@Component({
    selector: 'smart-ne-topology',
    templateUrl: './ne-topology.component.html',
    styles: [
            `
            .layui-side-scroll {
                width: initial;
            }

            .layui-layout-right {
                color: #666666;
            }

            .layui-header span {
                margin-right: 15px;
                cursor: pointer;
            }
            .header-bar{
                line-height: 60px;
                color: #6097b7;
                padding: 0 20px;
                background-color: #ddd;
            }
            .layui-layout-right{
                text-align: right;
                color: #6097b7
            }
            .layui-layout-right span{
                margin-right: 5px;
                cursor: pointer;
            }

            .tips {
                position: absolute;
                top: 10px;
                left: 20px;
                color: #ca0814;
                font-size: 20px;
            }

            .checkList {
                position: absolute;
                top: 10px;
                right: 20px;
                color: #666666;
                font-size: 20px;
            }
            .lineList{
                position: absolute;
                top: 5px;
                right: 20px;
                color: red;
                cursor: pointer;
            }

            .layui-form-label {
                width: 110px;
            }
            .loading{
                position: absolute;
                top: 30%;
                left: 49%;
            }
            .minus {
                vertical-align: middle;
                color: red;
                font-size: 15px;
                margin-left: 12px;
                cursor: pointer;
            }
        `
    ]
})
export class NeTopologyComponent implements OnInit, DoCheck, AfterViewInit, OnDestroy {
    @ViewChild('topologyCanvas') topologyCanvas: ElementRef;
    @ViewChild('topologyBody') topologyBody: ElementRef;
    @ViewChild('smartTopology') smartTopology: TopologyComponent;
    @ViewChild('smartCheck') smartCheck: CheckComponent;
    @ViewChild('smartSelectRadioGroup') smartSelectRadioGroup: SelectRadioGroupComponent;
    @ViewChild('smartLine') smartLine: LineComponent;
    @ViewChild('smartNode') smartNode: NodeComponent;

    dataSet;
    isVisible = false;
    image;
    isLoading = false;

    topoId;
    name;
    refreshRete;
    options;
    lineType = "1";  //线条类型
    editType = "只读模式";   //拓扑图状态

    backgroundColor;   //背景色

    checkJson = [];
    fileList: UploadFile[] = [];
    isDevice;

    private customerDifferLink: KeyValueDiffer<string, any>;
    private customerDifferNode: KeyValueDiffer<string, any>;
    node = {
        value:''
    };
    line = {
        value:''
    };

    constructor(private topologySer: TopologyService, private message: NzMessageService,
                private differs: KeyValueDiffers,
                private sanitizer: DomSanitizer, private modalSer: NzModalService) {

    }

    ngOnInit() {

        this.customerDifferLink = this.differs.find(this.line).create();
        this.customerDifferNode = this.differs.find(this.node).create();

        this.getList();
        this.getTypeList();
    }

    ngAfterViewInit() {
        const canvasWidth = this.topologyBody.nativeElement.clientWidth;
        const canvasHeight = this.topologyBody.nativeElement.clientHeight;
        let myCanvas = this.topologyCanvas.nativeElement;
        let context = myCanvas.getContext('2d');
        let ratio = this.getPixelRatio(context);
        myCanvas.style.width = canvasWidth + 'px';
        myCanvas.style.height = canvasHeight + 'px';

        myCanvas.width = myCanvas.width * ratio;
        myCanvas.height = myCanvas.height * ratio;
        context.scale(ratio,ratio);

        editor.loadTopology('','', 'img/backimg.png',canvasWidth,canvasHeight);
    }

    // 获取像素比
    getPixelRatio(context){
        const backingStore = context.backingStorePixelRatio ||
            context.webkitBackingStorePixelRatio ||
            context.mozBackingStorePixelRatio ||
            context.msBackingStorePixelRatio ||
            context.oBackingStorePixelRatio ||
            context.backingStorePixelRatio || 1;
        return (window.devicePixelRatio || 1) / backingStore;
    }

    ngDoCheck(){
        this.node.value =  localStorage.getItem('node');
        this.line.value =  localStorage.getItem('line');
        const changesLine = this.customerDifferLink.diff(this.line);
        const changesNode = this.customerDifferNode.diff(this.node);
        if (changesLine && changesLine['_appendAfter'].currentValue == "true") {
            const linkObj = localStorage.getItem('linkObj');
            this.smartLine.showModal( JSON.parse(linkObj) );
        }
        if (changesNode && changesNode['_appendAfter'].currentValue == "true") {
            const nodeObj = localStorage.getItem('nodeObj');
            this.smartNode.showModal( JSON.parse(nodeObj) );
        }
    }

    ngOnDestroy(){
        localStorage.setItem("line",'false');
        localStorage.setItem("node",'false');
    }

    //选择线条类型
    changeLine(e){
        switch (e) {
            case"1":{   //直线
                editor.lineType='line';
                break;
            }
            case"2":{   //折线(横向)
                editor.lineType='foldLine';
                editor.config.linkDirection='horizontal';
                break;
            }
            case"3":{  //折线(纵向)
                editor.lineType='foldLine';
                editor.config.linkDirection='vertical';
                break;
            }
            case"4":{   //二次折线(横向)
                editor.lineType='flexLine';
                editor.config.linkDirection='horizontal';
                break;
            }
            case"5":{   //二次折线(纵向)
                editor.lineType='flexLine';
                editor.config.linkDirection='vertical';
                break;
            }
        }
    }

    //改变模式
    changeEdit(type){
        if(type == '编辑模式'){
            this.topologyCanvas.nativeElement.style.background = "url(../neweb/javascript/jtopo/img/backimg.png)";
            editor.utils.editTopology();
        }
        if(type == '只读模式'){
            this.topologyCanvas.nativeElement.style.background = "";
            editor.utils.normalTopology()
        }
        this.editType = type;
    }

    //改变背景色
    changeColor(){
        this.topologyCanvas.nativeElement.style.background = this.backgroundColor;
    }

    //一级分类
    getTypeList(){
        this.topologySer.findTreeWithWeb().subscribe(
            (res)=>{
                if(res.errCode == 10000){
                    this.options = res.data;
                }else{
                    this.message.error(res.errMSg);
                }
            }
        )
    }

    //新增拓扑图
    addTopo() {
        this.smartTopology.showAddMOodal();
    }

    //编辑拓扑图
    editTopo() {
        if (!this.topoId) {
            this.message.warning('请选择需要编辑的拓扑图');
            return false;
        }
        this.smartTopology.showEditModal(this.topoId);
    }

    //添加监测点
    addCheck() {
        if (!this.topoId) {
            this.message.warning('请选择需要编辑的拓扑图');
            return false;
        }
        this.smartCheck.showAddModal();
    }

    //添加设备
    addDevice() {
        if (!this.topoId) {
            this.message.warning('请选择需要编辑的拓扑图');
            return false;
        }
        this.smartSelectRadioGroup.showAddModal('添加设备');
    }

    //获取节点信息
    setImg(e) {
        const data = {
            hostIds:[e]
        }
        this.topologySer.findByHostIdOrWeb(data).subscribe(
            (res)=>{
                editor.utils.addNode(res.data[0].url, res.data[0].name,res.data[0].hostId);
            }
        )
    }

    //获取列表
    getList() {
        this.topologySer.findAll().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.dataSet = res.data;
                } else {
                    this.message.create('error', res.errMsg);
                }
            }
        );
    }

    //编辑
    update() {
        const json = {
            topology: editor.saveTopology(),
            check: this.checkJson
        };
        let data = {
            id: this.topoId,
            json: JSON.stringify(json),
            refreshRete: this.refreshRete,
            name: this.name
        };
        this.topologySer.update(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('编辑成功');
                    this.getList();
                    this.getDetail();
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

    //查询单个
    getDetail() {
        this.isLoading = true;
        this.topologySer.findItem( this.topoId).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    if (res.data.json.length > 0) {
                        let json = JSON.parse(res.data.json);
                        if(json.topology){
                            this.viewTopology(JSON.parse(json.topology));
                            this.checkJson = json.check;
                        }else{
                            this.isLoading = false;
                            editor.utils.clearTopology();
                            this.checkJson = [];
                        }
                    } else {
                        this.isLoading = false;
                        editor.utils.clearTopology();
                        this.checkJson = [];
                    }
                    this.name = res.data.name;
                    this.refreshRete = res.data.refreshRete;
                    this.topoId = res.data.id;
                    this.findItemStatus();
                }
            }
        );
    }

    //回显拓扑图
    viewTopology(topologyJson){
        const arr = topologyJson.childs[0].childs;
        const list = [];
        const hostIds = [];
        arr.forEach(e=>{
            if(e.elementType == 'link' && e.itemId && e.itemId.length > 2){
                const data = {
                    itemIdIn:e.itemId.split(',')[0],
                    itemIdOut:e.itemId.split(',')[1],
                    linkId:e.id
                };
                list.push(data);
            }
        });
        arr.forEach(e=>{
            if(e.elementType == 'node' && e.hostId){
                hostIds.push(e.hostId);
            }
        });
        //危险对象
        //故障对象
        const glist = [];
        //删除对象
        const dlist = [];
        if(hostIds.length > 0){
            const res = {
                hostIds : hostIds
            };
            this.topologySer.findElementStatus(res).subscribe(
                (res)=>{
                    //status -1=未监控, 0=正常, 1=危险, 2=故障, 3=未分类
                    const resData = res.data;
                    resData.forEach(e1=>{
                        arr.forEach(e2=>{
                            if(e1.elementId == e2.hostId){
                                // if(e1.status == -2){
                                //     e2.alarm = "主机被删除，请及时清理";
                                //     e2.fontColor='0,0,0';
                                //     e2.alarmAlpha=0.9;
                                // }
                                if(e1.status == 1){
                                    e2.alarm = "危险";
                                    e2.fontColor='0,0,0';
                                    e2.alarmColor='255,153,18';
                                    e2.alarmAlpha=0.9;
                                }
                                if(e1.status == 2){
                                    e2.alarm = "故障";
                                    e2.fontColor='0,0,0';
                                    e2.alarmAlpha=0.9;
                                }
                            }
                        })
                    });
                    editor.loadTopologyByJson(topologyJson, 'img/backimg.png');
                    this.isLoading = false;
                }
            )
        }

        //流量数据
        if(list.length > 0){   //有流量监控-->查询流量监控
            const data = {
                "list" : list
            };
            this.topologySer.findFlow(data).subscribe(
                (res)=>{
                    const response = res.data;
                    response.forEach(e1=>{
                        arr.forEach(e2=>{
                            if(e1.linkId == e2.id){
                                e2.text = "进口流量:"+e1.fullValueIn+" 出口流量:"+e1.fullValueOut;
                            }
                        })
                    });
                    this.isLoading = false;
                    editor.loadTopologyByJson(topologyJson, 'img/backimg.png');
                }
            )
        }else{   //无流量监控
            this.isLoading = false;
            editor.loadTopologyByJson(topologyJson, 'img/backimg.png');
        }
    }

    //查询监控点状态
    findItemStatus() {
        const data = {
            httpTestIds: this.checkJson.map(e => {
                return e.id;
            })
        };
        this.topologySer.findElementStatus(data).subscribe(
            (res) => {

            }
        );
    }

    //删除拓扑图
    deleteTopo() {
        if (!this.topoId) {
            this.message.warning('请选择需要删除的拓扑图');
            return false;
        }
        this.modalSer.confirm({
                nzTitle: '删除',
                nzContent: '<b style="color: red;">确认删除该拓扑图吗？</b>',
                nzOkText: '确定',
                nzOkType: 'danger',
                nzOnOk: () => {
                    const data = {
                        id:this.topoId
                    }
                    this.topologySer.delete(data).subscribe(
                        (res) => {
                            if (res.errCode == 10000) {
                                this.topoId = null;
                                this.message.success('删除成功');
                                this.getList();
                            } else {
                                this.message.error(res.errMsg);
                            }
                        }
                    );
                },
                nzCancelText: '取消',
                nzOnCancel: () => console.log('Cancel')
            }
        );
    }

    //设置监测点
    setCheckList(event) {
        this.checkJson.push(JSON.parse(event));
    }

    //删除监测点
    deleteCheck(index) {
        this.checkJson.splice(index, 1);
    }

    //添加图片-----start
    showAddImg() {
        if (!this.topoId) {
            this.message.warning('请选择需要编辑的拓扑图');
            return false;
        }
        this.isVisible = true;
    }

    beforeUpload = (file: UploadFile): boolean => {
        const isLt2M = file.size / 1024 < 300;
        if (!isLt2M) {
            this.message.error('图标必须小于300kb!');
        } else {
            this.fileList.push(file);
        }
        return false;
    };

    handleCancel() {
        this.isVisible = false;
        this.fileList = [];
    }

    handleOk() {
        if (this.fileList.length == 0) {
            this.message.warning('请选择图片');
            return false;
        }
        const formData = new FormData();
        this.fileList.forEach((file: any) => {
            formData.append('file', file);
        });
        this.topologySer.addPic(formData).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isVisible = false;
                    editor.utils.addNode(res.data, 'text');
                    this.fileList = [];
                } else {
                    this.message.error('添加失败');
                }
            }
        );
    }

}