<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() {
	// 获取表单元素
	window.setInterval(myFunction,10000);
  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 => {
      //console.log(text);
      //alert('Data received: ' + text);
      renderEl(text);
      paintVis(text);
      })
      .catch(error => {
      console.error('Fetch error:', error);
      alert('An error occurred while fetching data.');
      });
    }
    // arr="192.168.111.138 is Backup  192.168.111.132 is Master";
    // renderEl(arr);
    // paintVis(arr);
  })
  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;
  }
  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;
}

</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>
  <!-- 一个简单的按钮 -->
<button id="myButton">主动切换主备网关</button>

  <table>
    <caption>
      当前网络中网关情况：
  </caption>
  <div id="wrap"></div>
</body>
<h1>网络拓扑图</h1>
<div id="mynetwork" style="width:auto; height:500px; border:1px solid lightgray;"></div>
<script>
//   var nodes = new vis.DataSet([
//   { id: 1, label: 'keepalived:vrrp\n 192.168.229.130',color: {background: 'lightgreen'}},
//   { id: 2, label: 'nginx负载均衡\n 192.168.229.128:80',color: {background: 'lightgreen'}},
//   { id: 3, label: 'nginx负载均衡\n 192.168.229.129.80',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: true, // 鼠标移过后加粗该节点和连接线
//           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>

<script>
  document.getElementById('myButton').addEventListener('click', function(event) {
    // 阻止默认的表单提交行为，如果按钮在表单中
    event.preventDefault();

    // 使用 fetch API 发起 AJAX 请求
    fetch('http://localhost:8000/change_state/', {
        method: 'POST', // 或 'GET', 根据你的需求
        headers: {
        },
        body: JSON.stringify({}) // 使用 JSON 格式发送数据，如果是 GET 请求则不需要
    })
    .then(response => response.json())
    .then(data => {
        // 请求成功后的回调
        console.log(data);
    })
    .catch(error => {
        // 处理错误
        console.error('Error:', error);
    });
});
</script>