import { DataSet, Network } from "vis/index-network";
import workService from '../../services/fos/work.service.js'

let workHttps = new workService()
let ori_data = null,
    cur_data = {},
    network = null,
    container = null,
    nodeBorderWidth = 5,
    // URL= "http://192.168.100.231:8088/fos/",
    // URL= "http://10.178.46.207:8088/fos/",
    // URL= "http://10.246.163.164:8088/fos/",      //测试地址
    URL= "http://10.67.12.232:8088/fos/",      //测试地址
    // URL= "http://10.54.77.143:8088/fos/",      //测试地址

    vm = null,
    options = {
        physics: {
            enabled: false
        },
        interaction: { hover: true },
        nodes: {
            shape: "dot",
            size: 10,
            font: {
                size: 13
            },
            borderWidth: nodeBorderWidth
        },
        edges: {
            width: 1,
            smooth: false,
            font: {
                size: 10
            }
        }
    };

let bExcIds = { "0": [], "1": [], "2": [] };
let int = 0;
let nodeout = null
let nodecontext = null;
let edgecontext = null;
let colors = {
    n: "#dddddd", // 闪烁背景色
    y: "#ffff00", // 黄色   (闪烁背景色)
    d: "#cf2b0b", // 深红   (闪烁背景色)
    l: "#59db49", // 线默认色
    r: "#ff3d32", // 红色   (节点出问题)
    q:'#72D572',  // 淡绿色  (未纳管)
    g: "#0A8F08", // 绿色   (已纳管)
    b: '#2CABE3', // 蓝色   (已部署)
};
// 0 异常,1 正常,2 黄色报警,3 橙色报警,4 红色报警,5 紫色报警
let levels = ["a", "l", "y", "o", "d", "v"];

let MapNodeIdIndex = {};
let MapEdgeIdIndex = {};

let registerNetworkEvent = () => {
    network.on("zoom", params => {
        let scale = network.getScale();
        // if (scale < 0.5) {
        //     scale = 0.5;
        // }
        network.moveTo({ scale: scale });
      localStorage.setItem("scale", JSON.stringify(scale));
      localStorage.setItem(
        "viewposition",
        JSON.stringify(network.getViewPosition())
      );
    });
    //左击事件
    network.on("click", params => {
        let __nodeId = network.getNodeAt({
            x: params.pointer.DOM.x,
            y: params.pointer.DOM.y
        });
        $.ajax({
            type:"get",
            url:URL + "modules/topo/info",
            data:{"ip":__nodeId},
            dataType:"json",
            beforeSend:function(request){
                request.setRequestHeader("token",localStorage.getItem("token"))
            },
            success:function (res) {
                let nodeObj = res.data
                cur_data.nodes.forEach((v,i)=>{
                    if(v.id == __nodeId){
                        // console.log(nodeObj.ip)
                        getNodeIp(nodeObj.ip)
                    }
                })

            }
        })
    })

    // //右击事件
    // network.on("oncontext", params => {
    //     let __nodeId = network.getNodeAt({
    //         x: params.pointer.DOM.x,
    //         y: params.pointer.DOM.y
    //     });
    //     //判断是否存在弹窗,若存在先去掉再弹出新的
    //     if($(".node-oncontext").show()){
    //         $(".node-oncontext").remove()
    //     }else{}
    //     $(".hover-oncontext").remove()
    //
    //     if (__nodeId) { // 获取点击节点id
    //
    //         cur_data.nodes.forEach((v,i)=>{
    //             if(v.id == __nodeId){
    //                 let div = document.createElement("div")
    //                 div.className = "node-oncontext";
    //                 nodeout = container.appendChild(div)
    //                 nodeout.innerHTML = "<ul class='nodeMsg'>" +
    //                     "<li class='editNode'>修改节点信息</li>" +
    //                     "<li class='setNode'>设置节点区域</li>" +
    //                     "</ul>"
    //                 nodeout.style.left = params.pointer.DOM.x + "px"
    //                 nodeout.style.top = params.pointer.DOM.y + "px"
    //                 nodeout.style.display = "block";
    //                 document.querySelector(".editNode").onclick = function () {
    //                     console.log("修改节点信息")
    //                     _store.commit('updateEditNode',true)
    //                     _store.commit('updateNodeIP',__nodeId)
    //
    //
    //                 }
    //                 document.querySelector(".setNode").onclick = function () {
    //                     console.log("设置节点区域")
    //                     _store.commit('updateSetArea',true)
    //                     _store.commit('updateNodeIP',__nodeId)
    //                 }
    //
    //             }
    //         })
    //
    //     } else {
    //         hidecontext();
    //     }
    // });

    window.Event.prototype.preventDefault = window.Event.prototype.preventDefault || function(){
        //阻止冒泡
        this.cancelBubble = true;
        //阻止触发默认事件
        this.returnValue = false;
    }
    window.event.oncontextmenu = function(ev) {
        ev.preventDefault();
    };
    //hover事件
    network.on("hoverNode", params => {
        let __nodeId = network.getNodeAt({
            x: params.pointer.DOM.x,
            y: params.pointer.DOM.y
        });
        //判断是否存在弹窗,若存在先去掉再弹出新的
        if($(".hover-oncontext").show()){
            $(".hover-oncontext").remove()
        }else{}
        if (__nodeId) { // 获取节点id
            $.ajax({
                type:"get",
                url:URL + "modules/topo/info",
                data:{"ip":__nodeId},
                dataType:"json",
                beforeSend:function(request){
                    request.setRequestHeader("token",localStorage.getItem("token"))
                },
                success:function (res) {
                    // console.log(res)
                    let nodeObj = res.data
                    // console.log(res.result)
                    _store.commit('updateNodeMsg',nodeObj)

                    cur_data.nodes.forEach((v,i)=>{
                        if(v.id == __nodeId){
                            let div = document.createElement("div")
                            div.className = "hover-oncontext";
                            nodecontext = container.appendChild(div)
                            nodecontext.innerHTML = "<ul class='nodeHoverBox'>" +
                                "<li>节点IP:"+ nodeObj.ip + "</li>"+
                                "<li>设备名称:"+ nodeObj.nodeName + "</li>"+
                                "<li>设备型号:"+ nodeObj.sn + "</li>"+
                                "<li>区域中心:"+ nodeObj.areaName + "</li>"+
                                "<li>企业名称:"+ nodeObj.domain + "</li>"+
                                "<li>备注:"+ nodeObj.remark + "</li>"+
                            "</ul>"

                            nodecontext.style.left = params.pointer.DOM.x + 30+"px"
                            nodecontext.style.top = params.pointer.DOM.y + 30   + "px"
                            nodecontext.style.display = "block";
                            document.querySelector(".hover-oncontext").onclick = function () {
                                _store.commit('updateFormShow',true)
                            }

                        }
                    })

                }
            })
        } else {
            hidecontext();
        }
    });

    //取消悬浮窗体的右击事件
    // document.querySelector(".hover-oncontext").oncontextmenu = function(ev) {
    //     ev.preventDefault();
    // };
    //取消悬浮窗体
    let hideNodecontext = () =>{
        if(nodecontext){
            document.querySelector(".hover-oncontext").style.display ="none";
        }
    };
    //nodeId
    network.on("blurNode",nodeId => {
        nodeId.node = ""
        hideNodecontext()

    })

    //更新闪烁状态
    // int = setInterval(() => {
    //     update_nodes_status();
    // }, 1000);
    //屏蔽右键菜单
    document.getElementsByTagName("canvas")[0].oncontextmenu = function(ev) {
        ev.preventDefault();
    };
};
let redraw = (id, qryType,that) => {
    vm = that?that:vm
    let cfg = {
        qryType             // 1,展开 2,收缩 3,刷新 0,按点查询
    };
    cfg.vpnName = sessionStorage.getItem('topuVpnName');
    if (qryType === 3 || qryType == 0) {
        cfg.nodeId = id;
    }
    let list = [];
    if(qryType === 3){
        ori_data = JSON.parse(sessionStorage.getItem('graph'))
        container = document.querySelector(`#topuDiv`)
    }
    ori_data &&
    ori_data.nodes.forEach(v => {
        if (qryType == 1 || qryType == 2) {
            if (v.ip == id) {
                cfg.nodeId = v.ip;
            }
        }
       list.push({nodeid:v.ip})
    });
    if (!list) {
        return;
    }
    cfg.nodeList = list;
    localStorage.setItem("cfg", JSON.stringify(cfg));
    workHttps.getListtopoall(cfg).then((res)=>{
        if(res.code===0){
           let data = res.data;
            update(data)
        }else {
            // _toast(res.msg)
        }
    }).catch((err=>{
        console.log(err)
    }))
};
// let  update= (d) => {
//     // if (!network) {
//     //      return;
//     // }
//     d = handleData(d)
//     sessionStorage.setItem("graph", JSON.stringify(d));
//     int = clearInterval(int);
//     nodecontext = null;
//     edgecontext = null;
//     bExcIds = { "0": [], "1": [], "2": [] };
//     MapNodeIdIndex = {};
//     MapEdgeIdIndex = {};
//     ori_data = d;
//     cur_data = JSON.parse(JSON.stringify(ori_data));
//     cur_data.nodes.forEach((v, i) => {
//         MapNodeIdIndex[v.id] = i
//         v.color = {}
//         if(v["bexc"] == "1"){
//             v.color = { border:colors.y}
//         }else if(v["bexc"] == "2"){
//             v.color = { border:colors.d}
//         }else {
//             v.borderWidth = 0  //无光圈
//         }
//         if(v.status == '0'){
//             v.color.background = colors.r
//         }else {
//             if(v.vpnStatus == '0'){
//                 v.color.background = colors.q
//             }else if(v.vpnStatus == '1'){
//                 v.color.background = colors.g
//             }else if(v.vpnStatus == '2'){
//                 v.color.background = colors.b
//             }
//         }
//         bExcIds[v["bexc"]] &&
//         bExcIds[v["bexc"]].push(v);
//     });
//     cur_data.edges.forEach((v, i) => {
//         MapEdgeIdIndex[v.lkId] = i;
//         v.color = { color: colors.l };
//         v.width = 1;
//     });
//     cur_data["edges"] = new DataSet(cur_data["edges"]);
//     cur_data["nodes"] = new DataSet(cur_data["nodes"]);
//     network = new Network(container, cur_data, options);
//     registerNetworkEvent();
//     moveTo();
//     // 计算
//     let initpos = JSON.parse(sessionStorage.getItem("initpos"));
//     let initid = sessionStorage.getItem("initid");
//     if (!initpos) {
//         return;
//     }
//     let initX = initpos.x;
//     let initY = initpos.y;
//     let newpos = network.getPositions([initid]);
//     if (!newpos[initid]) {
//         return;
//     }
//     let newX = newpos[initid].x;
//     let newY = newpos[initid].y;
//     sessionStorage.setItem("initpos", JSON.stringify(newpos[initid]));
//     let offsetX = initX - newX;
//     let offsetY = initY - newY;
//     if (offsetX != 0 || offsetY != 0) {
//         let T = JSON.parse(localStorage.getItem("viewposition"));
//         network.moveTo({
//             position: {
//                 x: T.x - offsetX,
//                 y: T.y - offsetY
//             }
//         });
//         localStorage.setItem(
//             "viewposition",
//             JSON.stringify({
//                 x: T.x - offsetX,
//                 y: T.y - offsetY
//             })
//         );
//     }
// };
let moveTo = () => {
    let scale = JSON.parse(localStorage.getItem("scale"));
    let viewposition = JSON.parse(localStorage.getItem("viewposition"));
    if (scale && viewposition) {
        network.moveTo({
            position: viewposition,
            scale: scale
        });
    }
};
let  saveviewpos = () => {
    localStorage.setItem("scale", JSON.stringify(network.getScale()));
    localStorage.setItem(
        "viewposition",
        JSON.stringify(network.getViewPosition())
    );
};
let  hidecontext = () => {
    if (nodecontext) {
     nodecontext.style.display = "none";
    }
    if (edgecontext) {
        edgecontext.style.display = "none";
    }
};
let  update_nodes_status = () => {
    if (cur_data["nodes"]) {
        //正常光环的
        if (bExcIds["1"].length > 0) {
            bExcIds["1"].forEach(v => {
                if (v.color.border == colors.n) {
                    v.color.border = colors.y;
                } else if (v.color.border == colors.y) {
                    v.color.border = colors.n;
                }
            })
        }
        cur_data["nodes"].update(bExcIds["1"]);
    }
    if (bExcIds["2"].length > 0) {
        bExcIds["2"].forEach(v => {
            if (v.color.border == colors.n) {
                v.color.border = colors.d;
            } else if (v.color.border == colors.d) {
                v.color.border = colors.n;
            }
        });
        cur_data["nodes"].update(bExcIds["2"]);
    }
};
let  handleData = (data) =>{
    let newData = {nodes:[],edges:[]}
    if(data.retNodes.length !=0){
        _store.commit('updateRetNode', data.retNodes)
        data.retNodes.forEach((v,i)=>{
            v.id = v.ip
            v.x = v.axisX
            v.y = v.axisY
            v.label = v.nodeName
            newData.nodes.push(v)
        })
    }
    if(data.retLinks.length !=0){
        data.retLinks.forEach((v,i)=>{
            v.id = v.lkId
            v.from = v.snode
            v.to = v.dnode
            newData.edges.push(v)
        })
    }
    return newData
}



export default {
    init: (ccClassName, data,that) => {
        data = handleData(data)
        vm = that
        sessionStorage.setItem("graph", JSON.stringify(data));
        container = document.querySelector(`#${ccClassName}`);  //topu 容器
        ori_data = data;                                        //原始数据
        cur_data = JSON.parse(JSON.stringify(ori_data));        //拷贝数据(使用)
        //bexc     是否有异常子节点 0 没有光圈 1 正常光圈 2 有异常光圈  (光圈代表有子节点)
        //status    节点状态       0 异常  1 正常  2 初始状态
        //vpnStatus  vpn部署状态    0 未纳管 1已纳管 2 已部署
        cur_data.nodes.forEach((v, i) => {
            MapNodeIdIndex[v.id] = i
            v.color = {}
             if(v["bexc"] == "1"){
                v.color = { border:colors.y}
            }else if(v["bexc"] == "2"){
                 v.color = { border:colors.d}
             }else {
                 v.borderWidth = 0  //无光圈
             }
            if(v.status == '0'){
                v.color.background = colors.r
            }else {
                if(v.vpnStatus == '0'){
                    v.color.background = colors.q
                }else if(v.vpnStatus == '1'){
                    v.color.background = colors.g
                }else if(v.vpnStatus == '2'){
                    v.color.background = colors.b
                }
            }
            bExcIds[v["bexc"]] &&
            bExcIds[v["bexc"]].push(v);
        });
        //遍历 线
        //state 0 正常 1异常
        cur_data.edges.forEach((v, i) => {
            MapEdgeIdIndex[v.lkId] = i;
            v.color = { color: colors.l };
            v.width = 1;
        });
    },
    getnetwork: () => {
        return network;
    },
    destroy: () => {
        network && (network.destroy(), (network = null));
        container && (container.innerHTML = "");
        int = clearInterval(int);
        ori_data = null;
        cur_data = {};
        bExcIds = { "0": [], "1": [], "2": [] };
        int = 0;
        nodecontext = null;
        edgecontext = null;
        MapNodeIdIndex = {};
        MapEdgeIdIndex = {};
        localStorage.removeItem("cfg");
        localStorage.removeItem('scale');
        localStorage.removeItem('viewposition');
    },
    cgraph: (fn, S, __fn) => {
        //改变数据类型
        cur_data["edges"] = new DataSet(cur_data["edges"]);
        cur_data["nodes"] = new DataSet(cur_data["nodes"]);
        //初始绘制图表
        if (!container) return;
        network = new Network(container, cur_data, options);
        registerNetworkEvent();
        if (!S) {
            //计算位置
            let initpos = network.getPositions();
            let initid = Object.keys(initpos)[0];
            sessionStorage.setItem("initpos", JSON.stringify(initpos[initid]));
            sessionStorage.setItem("initid", initid);
        }
    },
    redraw:redraw,


    update :(dataList) => {
        cur_data && cur_data["edges"].forEach(v=>{
            if (dataList.some(subv => {
                let b1 = v['from'] == subv.beginIP && v['to'] == subv.endIP;
                let b2 = v['from'] == subv.endIP && v['to'] == subv.beginIP;
                return b1 || b2;
            })) {
                network && network.clustering.updateEdge(v.lkId,{
                    color : { color: colors.b},
                    width : 10
                })
            }else{
                network && network.clustering.updateEdge(v.lkId,{
                    color : { color: colors.l},
                    width : 1
                })
            }
        })
    },
};