<script type="text/javascript" src="/luci-static/vssr/emoji.js?v=1.16"></script>
<script type="text/javascript" src="/luci-static/vssr/sweetalert.js?v=1.16"></script>
<script type="text/javascript" src="/luci-static/vssr/polyfill.js?v=1.16"></script>
<!-- tblsection -->
<fieldset class="cbi-section" id="cbi-<%=self.config%>-<%=self.sectiontype%>">
    <div class="ssr-title">
        <button class="cbi-button  cbi-button-check ">
            <%:Ping All Servers%>
        </button><span class="panel-title">总计
            <%- print(self.des)-%>个节点
        </span>
        <div style="clear:both;"></div>
    </div>

    <div class="cbi-section-node">
        <%- local count=0 -%>
            
            <div class="cbi-section-table pure-g p-in5">
                
                <%- local isempty=true for i, k in ipairs(self.serverTable) do section=k isempty=false local
                    fc=(section.name==self.current) and "fast" or "" local flag_icon=(section.flag ~=nil)
                    and "flag-icon-" .. section.flag or "flag-icon-un" local switch_enable=(section.switch_enable=="1" )
                    and "" or "hidden" scope={ valueheader="cbi/cell_valueheader" , valuefooter="cbi/cell_valuefooter" }
                    -%>

                    <div class="pure-u-1-5">
                        <div class="cbi-section-table-row <%=fc %> " id="cbi-<%=self.config%>-<%=section.name%>"
                            data-flag="<%=section.flag%>" server="<%=section.server%>"
                            server_port="<%=section.server_port%>">
                            <div class="loadings hide"></div>
                            <div class="incon type flag-icon <%=flag_icon %>" data-setction="<%=section.name%>">
                                <img class="pure-imgw <%=switch_enable %>" src="/luci-static/vssr/img/switch.png">
                                <div class="tp">
                                    <%=section.type%>
                                </div>
                            </div>
                            <div class=" alias">
                                <%=section.alias%>
                            </div>
                            <%- if self.extedit or self.addremove then -%>
                                <div class="cbi-section-table-cell">
                                    <div class="host_con"></div>
                                    <a class="cbi-button ssr-button" type="button" value=""
                                        onclick="apply_node('<%=section.name%>')" alt="<%:Apply%>"
                                        title="<%:Apply%>"><span class="icon-use"></span>
                                        <%:Apply%>
                                    </a>
                                    <%- if self.extedit then -%>
                                        <a class="cbi-button ssr-button " type="button" value="" <%- if type(self.extedit) == "string" then
                                       %> onclick="location.href='<%=self.extedit:format(section.name)%>'" <%- elseif type(self.extedit) == "function" then
                                       %> onclick="location.href='<%=self:extedit(section.name)%>'" <%- end
                                       %> alt="<%:Edit%>" title="<%:Edit%>"><span class="icon-edit"></span> <%:Edit%></a>
                                        <%- end; if self.addremove then %>
                                            <a class="cbi-button  ssr-button" type="button" value=""
                                                onclick="delete_node('<%=section.name%>')" alt="<%:Delete%>"
                                                title="<%:Delete%>" /><span class="icon-delete"></span>
                                            <%:Delete%></a>
                                                <%- end -%>
                                </div>
                                <%- end -%>
                        </div>
                    </div>
                    <%- end -%>

                        <%- if isempty then -%>
                            <div class="cbi-section-table-row">
                                <div colspan="<%=count%>"><em><br />
                                        <%:This section contains no values yet%>
                                    </em></div>
                            </div>
                            <%- end -%>
            </div>

            <% if self.error then %>
                <div class="cbi-section-error">
                    <ul>
                        <% for _, c in pairs(self.error) do for _, e in ipairs(c) do -%>
                            <li>
                                <%=pcdata(e):gsub("\n","<br />")%>
                            </li>
                            <%- end end %>
                    </ul>
                </div>
                <% end %>

                    <%- if self.addremove then -%>
                        <% if self.template_addremove then include(self.template_addremove) else -%>
                            <div class="cbi-section-create cbi-tblsection-create">
                                <% if self.anonymous then %>
                                    <input class="cbi-button cbi-button-add" type="submit" value="<%:Add%>"
                                        name="cbi.cts.<%=self.config%>.<%=self.sectiontype%>.<%=section%>"
                                        title="<%:Add%>" />
                                    <% else %>
                                        <% if self.invalid_cts then -%>
                                            <div class="cbi-section-error">
                                                <% end %>
                                                    <input type="text" class="cbi-section-create-name"
                                                        id="cbi.cts.<%=self.config%>.<%=self.sectiontype%>.<%=section%>"
                                                        name="cbi.cts.<%=self.config%>.<%=self.sectiontype%>.<%=section%>"
                                                        data-type="uciname" data-optional="true" />
                                                    <input class="cbi-button cbi-button-add" type="submit"
                                                        onclick="this.form.cbi_state = 'add-section'; return true"
                                                        value="<%:Add%>" title="<%:Add%>" />
                                                    <% if self.invalid_cts then -%>
                                                        <br />
                                                        <%:Invalid%>
                                            </div>
                                            <%- end %>
                                                <% end %>
                            </div>
                            <%- end %>
                                <%- end -%>
    </div>
</fieldset>
<!-- /tblsection -->
<script type="text/javascript">
    const CONFIG = '<%=self.config%>';
    const CURRENT = '<%=self.current%>';
    const CHANGE_NODE_URL = '<%=luci.dispatcher.build_url("admin", "services", "vssr","change")%>';
    const DELETE_NODE_URL = '<%=luci.dispatcher.build_url("admin", "services", "vssr","delnode")%>';
    const CHECK_PING_URL = '<%=luci.dispatcher.build_url("admin", "services", "vssr","checkport")%>';
    const SWITCH_NODE_URL = '<%=luci.dispatcher.build_url("admin", "services", "vssr","switch")%>';

    var iploaded = false;
    var ajaxArray = new Array();
    var currentCheckCount = 0;

    //转换节点名称的Emoji显示
    $(".alias").emoji();
    //适配方框的大小

    $(".flag-icon").each(function (index, el) {
        if ($(el).height < 60) {
            $(el).parent.height(60);
            $(el).width(60)
        } else {
            $(el).width($(el).height());
        }
    });

    //切换节点
    function apply_node(node) {
        //$("#cbi-apply-vssr1").show(); //显示应用中
        var $html = "";
        $html += '<div class="pure-g choose_node">';
        $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="global" data-node="' + node + '"> 主服务器 </button></div></div>';
        $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="udp_relay" data-node="' + node + '"> UDP游戏模式 </button></div></div>';
        $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="youtube" data-node="' + node + '"> Youtube </button></div></div>';
        //if ($('#cbi-' + CONFIG + '-' + node).attr("data-flag") == "tw") {
            $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="tw_video" data-node="' + node + '"> TW Video </button></div></div>';
        //}
        $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="netflix" data-node="' + node + '"> Netflix </button></div></div>';
        $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="disney" data-node="' + node + '"> Diseny+ </button></div></div>';
        $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="prime" data-node="' + node + '"> Prime Video </button></div></div>';
        //if ($('#cbi-' + CONFIG + '-' + node).attr("data-flag") == "hk") {
            $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="tvb" data-node="' + node + '"> TVB Video </button></div></div>';
        //}
        $html += '<div class="pure-u-1-2"><div class="gap"><button class="cbi-button cbi-button-apply change-node" data-server="custom" data-node="' + node + '"> 自定义 </button></div></div>';
        $html += '</div>';
        Swal.fire({
            title: '请选择应用于',
            html: $html,
            focusConfirm: false,
            confirmButtonText: '关闭',
            onRender: (toast) => {
                $(".change-node").click(function () {
                    var dataServer = $(this).attr("data-server");
                    XHR.halt();
                    $.each(ajaxArray, function (n, value) { value.abort(); }) //中断所有的ajax请求
                    Swal.fire({
                        title: '正在应用中',
                        allowOutsideClick: false,
                        onBeforeOpen: () => {
                            Swal.showLoading()
                        }
                    })
                    $.get(CHANGE_NODE_URL, { set: node, server: dataServer },
                        function (data, status) {
                            $("#cbi-apply-vssr1").hide(); //隐藏应用中
                            if (data.status) {
                                var id = '#cbi-<%=self.config%>-' + node;
                                if (dataServer == "global") {
                                    $(".cbi-section-table-row").removeClass("fast");
                                    $(id).addClass("fast");
                                }
                                Swal.close();
                                XHR.run();
                            }
                        });
                })
            }
        })
    }

    //删除节点
    function delete_node(node) {
        XHR.halt();
        $.each(ajaxArray, function (n, value) { value.abort(); }) //中断所有的ajax请求
        $.get(DELETE_NODE_URL, { node: node },
            function (data, status) {
                if (data.status) {
                    var id = '#cbi-<%=self.config%>-' + node;
                    $(id).parent().remove();
                    XHR.run();
                    check()
                }
            });
    }

    //设定自动切换
    $(".incon").click(function () {
        $.each(ajaxArray, function (n, value) { value.abort(); }) //中断所有的ajax请求
        $node_switch_icon = $(this).find(".pure-imgw");
        $node_target = $(this).attr("data-setction");
        $.post(SWITCH_NODE_URL, { node: $node_target }, function (data) {
            if (data.status) {
                if (data.switch) {
                    $node_switch_icon.removeClass("hidden");
                } else {
                    $node_switch_icon.addClass("hidden");
                }
            } else {
                alert("请求出错！")
            }
        }, "json");
    })

    //检测所有节点延迟
    function check() {
        $(".host_con").html("");
        $.each(ajaxArray, function (n, value) { value.abort(); }) //中断所有的ajax请求
        ajaxArray = [];
        currentCheckCount = 0;
        XHR.halt();
        $(".pure-u-1-5").each(function () {
            host = $(this).find(".cbi-section-table-row ").attr("server");
            port = $(this).find(".cbi-section-table-row ").attr("server_port");
            $(".host_con").text("");
            if (host != undefined) {
                check_port(host, port, this);
            }
        });
    }

    //检测单个节点延迟
    function check_port(hosts, ports, target) {
        $.ajaxSettings.async = true;
        var axhr = $.get(CHECK_PING_URL, { host: hosts, port: ports },
            function (data, status) {
                currentCheckCount++
                var host_con = $(target).find(".host_con");
                host_con.removeClass("fast middle slow nopass");
                if (data.ret == 1) {
                    if (data.used == "") {
                        host_con.addClass("nopass");
                        host_con.text("Error");
                    } else if (data.used <= 80) {
                        host_con.addClass("fast");
                        host_con.text(data.used + "ms");
                    } else if (data.used > 80 && data.used <= 200) {
                        host_con.addClass("middle");
                        host_con.text(data.used + "ms");
                    } else if (data.used > 200) {
                        host_con.addClass("slow");
                        host_con.text(data.used + "ms");
                    }
                } else {
                    host_con.addClass("nopass");
                    host_con.text("Error");
                }

                if (currentCheckCount == ajaxArray.length) {
                    XHR.run();
                }
            });
        ajaxArray.push(axhr);
    }

    $(document).ready(function () {
        $("body").on("iploaded", function (event, param1) {
            if (!iploaded) {
                iploaded = true;
                check();
            }
        });

        $(".cbi-page-actions").hide(); //隐藏底部保存提交按钮
        $(".cbi-button-check").click(function () {
            check();
            return false;
        });
    });

</script>
