{{define "theme-custom/network"}}
{{template "theme-custom/header" .}}
{{if ts .CustomCode}}
{{.CustomCode|safe}}
{{end}}
{{template "theme-custom/menu" .}}
<div id="network" class="nb-container">
    <div class="ui container">
        <div class="service-status">
            <div class="ui icon button"
                 v-for='server in servers'
                 :id="server.ID"
                 style="margin-top: 3px"
                 @click="redirectNetwork(server.ID)">
                @#server.Name#@<i :class="server.Host.CountryCode + ' flag'"></i>&nbsp;<i
                    v-if='server.Host.Platform == "darwin"' class="apple icon"></i><i
                    v-else-if='isWindowsPlatform(server.Host.Platform)' class="windows icon"></i><i
                    v-else :class="'fl-' + getFontLogoClass(server.Host.Platform)"></i>
            </div>
            <div ref="chartDom" style="border-radius: 28px; margin-top: 15px;height: 520px;max-width: 1400px;overflow: hidden"></div>
        </div>
    </div>
</div>

{{template "theme-custom/footer" .}}
<script>
        const monitorInfo =  JSON.parse('{{.MonitorInfos}}');
        const initData = JSON.parse('{{.Servers}}').servers;
	    let MaxTCPPingValue = {{.MaxTCPPingValue}};
	    if (MaxTCPPingValue == null) {
	        MaxTCPPingValue = 300;
	    }
        var statusCards = new Vue({
            el: '#network',
            delimiters: ['@#', '#@'],
            data: {
                servers: initData,
                cache: [],
                option: {
                    tooltip: {
                        trigger: 'axis',
                        position: function (pt) {
                            return [pt[0], '10%'];
                        },
                        formatter: function(params){
                            let result = params[0].axisValueLabel + "<br />";
                            params.forEach(function(item){
                                result += item.marker + item.seriesName + ": " + item.value[1].toFixed(2) + " ms<br />";
                             })
                            return result;
                        },
                        confine: true,
                        transitionDuration: 0
                    },
                    title: {
                        left: 'center',
                        text: "",
                        textStyle: {}
                    },
                    legend: {
                        top: '5%',
                        data: [],
                        textStyle: {
                            fontSize: 14
                        }
                    },
                    backgroundColor: 'rgba(255, 255, 255, 0.7)',
                    toolbox: {
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none'
                            },
                            restore: {},
                            saveAsImage: {}
                        }
                    },
                    dataZoom: [
                        {
                            start: 94,
                            end: 100
                        }
                    ],
                    xAxis: {
                        type: 'time',
                        boundaryGap: false
                    },
                    yAxis: {
                        type: 'value',
                        boundaryGap: [0, '100%']
                    },
                    series: [],
                },
                isHover: false,
                chartOnOff: true
            },
            mounted() {
                 setTimeout(() => {
                    this.renderChart();
                     this.parseMonitorInfo(monitorInfo);
                    this.myChart.on('legendselectchanged', (params) => {
                      let selected = params.selected;
                      let legend = params.name;
                  // 使用legendToggleSelect动作将重新触发legendselectchanged事件，导致本函数重复运行从而丢失selected对象
                      if (selected !== undefined) {
                        if (this.isFirstUnSelect(selected, legend)) {
                          this.triggerAction('legendToggleSelect', selected);
                        } else if (this.isAllUnSelected(selected)) {
                          this.triggerAction('legendSelect', selected);
                        }
                      }
                    });
                 }, 500);
            },
            methods: {
                redirectNetwork(id) {
                    this.getMonitorHistory(id)
                    .then(function(monitorInfo) {
                          var vm = network.__vue__;
                          vm.parseMonitorInfo(monitorInfo);
                    })
                    .catch(function(error){
                        window.location.href = "/404";
                    })
                },
                getMonitorHistory(id) {
                      return $.ajax({
                        url: "/api/v1/monitor/"+id,
                        method: "GET"
                      });
                },
                parseMonitorInfo(monitorInfo) {
                    let tSeries = [];
                    let tLegendData = [];
                    for (let i = 0; i < monitorInfo.result.length; i++) {
                        let loss = 0;
                        let data = [];
                        for (let j = 0; j < monitorInfo.result[i].created_at.length; j++) {
                            avgDelay = monitorInfo.result[i].avg_delay[j];
                            if (avgDelay > 0.9 * MaxTCPPingValue) {
                                loss += 1
                            }
                            data.push([monitorInfo.result[i].created_at[j], avgDelay]);
                        }
                        lossRate = ((loss / monitorInfo.result[i].created_at.length) * 100).toFixed(1);
			            legendName = monitorInfo.result[i].monitor_name +" "+ lossRate + "%";
                        tLegendData.push(legendName);
                        tSeries.push({
                                name: legendName,
                                type: 'line',
                                smooth: true,
                                symbol: 'none',
                                data: data
                        });
                    }
                    this.option.title.text = monitorInfo.result[0].server_name;
                    this.option.series = tSeries;
                    this.option.legend.data = tLegendData;
                    this.myChart.clear();
                    this.myChart.setOption(this.option);
                },
                isWindowsPlatform(str) {
                    return str.includes('Windows')
                },
                getFontLogoClass(str) {
                    if (["almalinux",
                        "alpine",
                        "aosc",
                        "apple",
                        "archlinux",
                        "archlabs",
                        "artix",
                        "budgie",
                        "centos",
                        "coreos",
                        "debian",
                        "deepin",
                        "devuan",
                        "docker",
                        "elementary",
                        "fedora",
                        "ferris",
                        "flathub",
                        "freebsd",
                        "gentoo",
                        "gnu-guix",
                        "illumos",
                        "kali-linux",
                        "linuxmint",
                        "mageia",
                        "mandriva",
                        "manjaro",
                        "nixos",
                        "openbsd",
                        "opensuse",
                        "pop-os",
                        "raspberry-pi",
                        "redhat",
                        "rocky-linux",
                        "sabayon",
                        "slackware",
                        "snappy",
                        "solus",
                        "tux",
                        "ubuntu",
                        "void",
                        "zorin"].indexOf(str)
                        > -1) {
                    return str;
                    }
                },
                renderChart() {
                  this.myChart = echarts.init(this.$refs.chartDom);
                  this.myChart.setOption(this.option);
                },
                triggerAction (action, selected) {
                  let legend = [];
                  for (let name in selected) {
                    if (selected.hasOwnProperty(name)) {
                      legend.push({name: name});
                    }
                  }
                  this.myChart.dispatchAction({
                    type: action,
                    batch: legend
                  });
                },

                isFirstUnSelect (selected, legend) {
                  if (selected[legend] === true) return false;
                  let unSelectedCount = 0;
                  for (let name in selected) {
                    if (!selected.hasOwnProperty(name)) {
                      continue;
                    }
                    if (selected[name] === false) {
                      unSelectedCount++;
                    }
                  }
                  return unSelectedCount === 1;
                },

                isAllUnSelected (selected) {
                  let selectedCount = 0;
                  for (let name in selected) {
                    if (!selected.hasOwnProperty(name)) {
                      continue;
                    }
                    // selected对象内true代表选中，false代表未选中
                    if (selected[name] === true) {
                      selectedCount++;
                    }
                  }
                  return selectedCount === 0;
                },
            },
            beforeDestroy() {
                this.myChart.dispose();
                this.myChart = null;
              },
        });
</script>
{{end}}
