.
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet" type="text/css" />
<script>
	// document.addEventListener('DOMContentLoaded', function() {
	// // 获取表单元素
	// setInterval(myFunction(),5000);
    
//   function paintVis(arr){
//   var nodes = new vis.DataSet([
//   { id: 1, label: 'keepalived:vrrp\n 192.168.229.130',color: {background: 'lightgreen'}},
//   { id: 2, label:  arr.substring(arr.indexOf("Master")-19,arr.indexOf("Master")-3),color: {background: 'lightgreen'}},
//   { id: 3, label: arr.substring(arr.indexOf("Backup")-19,arr.indexOf("Backup")-3),color: {background: 'grey'}},
//   { id: 4, label: 'web Server\n 192.168.229.129.81',color: {background: 'lightgreen'}},
//   { id: 5, label: 'web Server\n 192.168.229.129.81',color: {background: 'grey'}},
//   { id: 6, label: '客户端',color: {background: 'lightgreen'} },
// ]);

// var edges = new vis.DataSet([
//   { from: 6, to: 1 , color: {color:'#00ff00'}},
//   { from: 1, to: 2 , color: {color:'#00ff00'}},
//   { from: 1, to: 3 , color: {color:'grey'}},
//   { from: 2, to: 4 , color: {color:'#00ff00'}},
//   { from: 2, to: 5 , color: {color:'#00ff00'}},
//   { from: 3, to: 4 , color: {color:'grey'}},
//   { from: 3, to: 5 , color: {color:'#00ff00'}},
// ]);

// var container = document.getElementById('mynetwork');
// var data = {
//   nodes: nodes,
//   edges: edges
// };
// var options = {
//   nodes: {
//           shape:'dot',
//           font: {
//             color: '#000', // 字体的颜色
//             size: 10 // 显示字体大小
//           },
//           scaling: {
//             min: 20,
//             max: 40 // 缩放效果比例
//           },
//           borderWidth: 1,
//           color: {
//             border: 'white',
//             // 若是引用图标，背景颜色
//           }
//         },
//         groups: {
//           ws: { // 系统定义的形状 dot等 这些官网都可以找到
//             shape: 'square',
//             color: 'white'
//           }
//         },
//         layout: {
//           randomSeed: 1 // 配置每次生成的节点位置都一样，参数为数字1、2等
//         },
//         physics: {
//           // barnesHut: { gravitationalConstant: -30000 },
//           barnesHut: {
//             gravitationalConstant: 0,
//             springConstant: 0,
//             springLength: 0
//           },
//           stabilization: true
//           // { iterations: 2500 }
//         },
//         interaction: {
//           // navigationButtons: true,
//           hover: false, // 鼠标移过后加粗该节点和连接线
//           selectConnectedEdges: false, // 选择节点后是否显示连接线
//           hoverConnectedEdges: false, // 鼠标滑动节点后是否显示连接线
//           tooltipDelay: 200,
//           zoomView: false // 是否能缩放画布
//         },
//         edges: {
//           label:'Solid',
//           smooth: {type: "discrete"},
//           color: { // 连接线的样式
//             hover: '#848484',
//             inherit: 'from',
//             opacity: 1.0
//           },
//           shadow: true, // 连接线阴影配置
//           smooth: true // 是否显示方向箭头
//           // arrows: {to : true }//箭头指向from节点
//         }
// };
// var network = new vis.Network(container, data, options);
//   }
</script>
<style>
  table{
    width: 50%;
    border-collapse: collapse;
    margin: auto;
}

table caption{
    font-size: large;
    font-weight: bold;
    margin: 1em 0;
}

th,td{
    border: 1px solid #999;
    text-align: center;
    padding: 20px 0;
}

table thead tr{
    background-color: #008c8c;
    color: #fff;
}

table tbody tr:nth-child(odd){
    background-color: #eee;
}

table tbody tr:hover{
    background-color: #ccc;
}

table tbody tr td:first-child{
    color: #f40;
}

table tfoot tr td{
    text-align: right;
    padding-right: 20px;
}
#dropdownMenu {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 160px;
            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
            z-index: 1;
        }
.dropdown-item {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
        }
.dropdown-item:hover {
            background-color: #f1f1f1;
}
</style>
<header>
  <div style="text-align: center; padding-right: 10px; flex: 1 1 0%;font-size: large;background-color: rgb(227, 234, 234);">主备切换</div>
</header>
<body>
  <table>
    <caption>
      当前网络中网关情况：
  </caption>
  <div id="wrap"></div>
</body>
<div id="dropdownMenu" class="dropdown-content">
  <a href="#" class="dropdown-item" id="toggleOpen">开启</a>
  <a href="#" class="dropdown-item" id="toggleClose">关闭</a>
</div>
<h1>网络拓扑图<button id="submitBtn">提交</button></h1>
<div id="doubleClickArea">
<div id="mynetwork" style="width:auto; height:500px; border:1px solid lightgray;"></div>
</div>
<script>
  var nodes = new vis.DataSet([
  { id: 1, label: 'keepalived:vrrp\n 192.168.229.139',color:'lightgreen'},
  { id: 2, label: 'nginx负载均衡\n 192.168.229.138:80',color:'lightgreen'},
  { id: 3, label: 'nginx负载均衡\n 192.168.229.132.80',color: 'grey'},
  { id: 4, label: 'web Server\n 192.168.229.129.81',color:'lightgreen'},
  { id: 5, label: 'web Server\n 192.168.229.129.81',color: 'lightgreen'},
  { id: 6, label: '客户端',color:'lightgreen' },
]);

var edges = new vis.DataSet([
  { id: 7,from: 6, to: 1 , color: '#00ff00'},
  { id: 8,from: 1, to: 2 , color: '#00ff00'},
  { id: 9,from: 1, to: 3 , color: 'grey'},
  { id: 10,from: 2, to: 4 , color: '#00ff00'},
  { id: 11,from: 2, to: 5 , color: '#00ff00'},
  { id: 12,from: 3, to: 4 , color: 'grey'},
  { id: 13,from: 3, to: 5 , color: '#00ff00'},
]);
function myFunction(){
        fetch('http://localhost:8000/virtual_ip/')
        .then(response => {
       if (!response.ok) {
      throw new Error('Network response was not ok');
      }
      return response.text(); // 假设后端返回的是文本
      })
      .then(text => {
      renderEl(text);
      //paintVis(text);
      })
      .catch(error => {
      console.error('Fetch error:', error);
      alert('An error occurred while fetching data.');
      });
    }
    function renderEl(arr) {
        let str = '';
        str += `
           <table>
    <caption>
      当前网络中网关情况：
  </caption>
  <thead>
    <tr>
        <th scope="col">服务器IP</th>
        <th scope="col">服务器状态</th>
    </tr>
    </thead>
    <tbody>
      <tr>
          <th scope="row">${arr.substring(arr.indexOf("Master")-19,arr.indexOf("Master")-3)}</th>
          <td>Master</td>
      </tr>
      <tr>
        <th scope="row">${arr.substring(arr.indexOf("Backup")-19,arr.indexOf("Backup")-3)}</th>
        <td>Backup</td>
    </tr>
  </table>
`;
        const el = document.getElementById('wrap');
        el.innerHTML = str;
  }
var container = document.getElementById('mynetwork');
var data = {
  nodes: nodes,
  edges: edges
};
var options = {
  nodes: {
          shape:'dot',
          font: {
            color: '#000', // 字体的颜色
            size: 10 // 显示字体大小
          },
          scaling: {
            min: 20,
            max: 40 // 缩放效果比例
          },
          borderWidth: 1,
          color: {
            border: 'white',
            // 若是引用图标，背景颜色
          }
        },
        groups: {
          ws: { // 系统定义的形状 dot等 这些官网都可以找到
            shape: 'square',
            color: 'white'
          }
        },
        layout: {
          randomSeed: 1 // 配置每次生成的节点位置都一样，参数为数字1、2等
        },
        physics: {
          // barnesHut: { gravitationalConstant: -30000 },
          barnesHut: {
            gravitationalConstant: 0,
            springConstant: 0,
            springLength: 0
          },
          stabilization: true
          // { iterations: 2500 }
        },
        interaction: {
          // navigationButtons: true,
          hover: true, // 鼠标移过后加粗该节点和连接线
          selectConnectedEdges: false, // 选择节点后是否显示连接线
          hoverConnectedEdges: false, // 鼠标滑动节点后是否显示连接线
          tooltipDelay: 200,
          zoomView: false // 是否能缩放画布
        },
        edges: {
          label:'Solid',
          smooth: {type: "discrete"},
          color: { // 连接线的样式
            inherit: 'from',
          },
          shadow: false, // 连接线阴影配置
          smooth: true // 是否显示方向箭头
          // arrows: {to : true }//箭头指向from节点
        }
};
var network = new vis.Network(container, data, options);
network.on('click', function (event) {
        nodeId = event.nodes[0]; // 获取被点击的节点ID
        nodeData = nodes.get(nodeId); // 根据节点ID获取节点数据
        if (nodeData) {
            console.log('Clicked on node: ' + nodeData.id + '\n' +
                  'Entity Info: ' + nodeData.label+ '\n' +
                'Color Info:' + nodeData.color);
            // 可以在这里添加更多的逻辑来处理点击事件
        }
    });

    var doubleClickArea = document.getElementById('doubleClickArea');
    var dropdownMenu = document.getElementById('dropdownMenu');

    // 为双击区域添加双击事件监听器
    doubleClickArea.addEventListener('dblclick', function(event) {
        // 显示下拉菜单
        var nodeToUpdate = nodes.get(nodeId);
        if (nodeToUpdate.color === 'grey') {
            nodeToUpdate.color = '#00ff00';
        } else {
            nodeToUpdate.color = 'grey';
        }
        nodes.update([nodeToUpdate]);
    });
    function updateEdgeColor() {
        // 获取所有节点的颜色
        for(var i=1;i<=6;i++){
          for(var j=1;j<=6;j++)
          {
            var node1Color =nodes.get(i).color;
            var node2Color =nodes.get(j).color;
            var edgeColor = ((node1Color =="lightgreen") && (node2Color =="lightgreen")) ? 'green' : 'grey';
            var edge = edges.get({ from: i, to: j });
            if (edge) {
            edge.color = { color: edgeColor };
            console.log("Update")
            edges.update(edge);
        }
          }
        }
        // 更新边的颜色
        for(var i=0;i<=6;i++)
        {
          for(var j=0;j<=6;j++)
          {
            var edge = edges.get({ from: i, to: j });
            if (edge) {
            edge.color = { color: edgeColor };
            console.log("Update")
            edges.update(edge);
        }
          }
        }
    }
    //setInterval(updateEdgeColor, 3000); // 每3000毫秒（3秒）更新一次
    var submitButton = document.getElementById('submitBtn');

    // 为提交按钮添加点击事件监听器
    submitButton.addEventListener('click', function() {
        // 从Vis.js网络图中获取当前的nodes信息
        
        var currentNodes = nodes.get();

        // 将nodes信息转换为JSON格式
        var nodesJson = JSON.stringify(currentNodes);

        // 使用fetch API发送数据到后端服务器
        fetch('http://localhost:8000/change_state_actively/', { // 替换为你的后端服务器端点
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: nodesJson
        })
        .then(response => response.json())
        .then(data => {
            console.log('Success:', data);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
        myFunction();
    });
</script>