<%
--[[
    Info    路由器局域网设置
]]--
local ver = require("xiaoqiang.XQVersion").webVersion
%>
<%include("web/inc/head")%>
<title><%:小米路由器%></title>
<meta name="viewport" content="width=1200">
<link href="<%=resource%>/web/css/bc.css?v=<%=ver%>" rel="stylesheet">
<link href="<%=resource%>/web/css/proset.css?v=<%=ver%>" rel="stylesheet">
</head>
<body>
<div id="doc">
    <%include("web/inc/header")%>
    <div id="bd">
        <div class="mod-set mod-dhcp" id="lanDhcp">
            <div class="hd">
                <h3><%:DHCP服务%></h3>
                <div class="switch">
                    <a href="#" id="dhcpswitch" class="btn-switch btn-switch-off"></a>
                </div>
            </div>
            <div class="bd">
                <form method="post" class="form form-dhcp" name="netDhcp" id="netDhcp" action="#">
                    <input type="hidden" name="ignore">
                    <div class="set" style="display:none;">
                        <div class="form-item">
                            <label class="k"><%:开始IP%></label>
                            <span class="v">
                                <span class="ipprefix">192.168.31.</span><input type="text" class="ipt-text iplimit" name="start" id="startip" reqMsg="<%:开始IP%>" datatype="n-3" minValue="2" maxValue="254" style="width:128px"  maxlength="3">
                            </span>
                            <em class="t"></em>
                        </div>
                        <div class="form-item">
                            <label class="k"><%:结束IP%></label>
                            <span class="v">
                                <span class="ipprefix">192.168.31.</span><input type="text" class="ipt-text iplimit" name="end" id="endip" reqMsg="<%:结束IP%>" datatype="nrange-3" fromNEl="startip"  minValue="2" maxValue="254" style="width:128px"  maxlength="3">
                            </span>
                            <em class="t"></em>
                        </div>
                        <div class="form-item">
                            <label class="k"><%:租约(分)%></label>
                            <span class="v">
                                <input type="text" name="leasetime" class="ipt-text" maxlength="6" reqMsg="<%:租约%>" datatype="n-4" minValue="2" maxValue="2880">
                            </span>
                            <em class="t"></em>
                        </div>
                    </div>
                    <div class="form-contral">
                        <button class="btn btn-primary btn-l hidden" type="submit" id="btnDhcpSubmit"><span><%:保存%></span></button>
                    </div>
                </form>
            </div>
        </div>

        <div class="mod-set mod-lanip" id="lanIp">
            <div class="hd">
                <h3><%:局域网IP地址%></h3>
            </div>
            <div class="bd">
                <form name="ipaddr" id="ipaddr" action="#" class="form form-lanip">
                    <input type="hidden" name="old_ip">
                    <div class="form-item">
                        <label class="k"><%:局域网IP%></label>
                        <span class="v"><input type="text" name="ip" class="ipt-text" maxlength="15" reqMsg="<%:局域网IP%>" datatype="ipaddr"></span>
                        <em class="t"></em>
                    </div>
                    <div class="form-contral">
                        <button type="submit" id="btnLanipSubmit" class="btn btn-primary btn-l hidden"><span><%:保存%></span></button>
                    </div>
                </form>
            </div>
        </div>

    </div>

    <%include("web/inc/footer")%>

</div>
<%include("web/inc/g.js")%>
<%include("web/inc/reboot.js")%>
<script>
(function(){
    var ajaxcount = 0,
        ajaxall = 2,
        dhcpOldval = {};

    $.sub( 'ajaxdone', function(){
        ajaxcount ++;
        if ( ajaxcount >= ajaxall ) {
            $.formInit();
        }
    } );

    $.sub( 'dhcp:get', function( evt, data ){
        var requestURL = '<%=luci.dispatcher.build_url("api", "xqnetwork","lan_dhcp")%>',
            requestData = {},
            ipSplit = function( ip ) {
                var ipSplit=[];
                var strs = ip.split(".");
                for (var i=0;i<strs.length-1;i++ )
                {
                    ipSplit.push(strs[i]);
                }
                return ipSplit.join('.') + '.';
            };

        $.getJSON( requestURL, requestData, function( rsp ){
            if(rsp.code == 0){
                var info = rsp.info,
                    ip = info.lanIp[0].ip,
                    ipPrefix = ipSplit( ip ),
                    ignore = info.ignore,
                    start = info.start,
                    limit = info.limit,
                    leasetime = info.leasetime,
                    leasetimeNum = info.leasetimeNum,
                    leasetimeUnit = info.leasetimeUnit,
                    _leasetimeUnit = leasetimeUnit === 'h'? 60 : 1,
                    _leasetime = leasetimeNum * _leasetimeUnit,
                    end = parseInt( info.start, 10 ) + parseInt( info.limit, 10 ) - 1;
                $( '.ipprefix' ).html( ipPrefix );
                $( 'input[name="start"]' ).val( start );
                $( 'input[name="end"]' ).val( end );
                $( 'input[name="leasetime"]' ).val( _leasetime );
                $( 'input[name="ignore"]' ).val( ignore );

                dhcpOldval['start'] = start;
                dhcpOldval['end'] = end;
                dhcpOldval['leasetime'] = _leasetime;
                dhcpOldval['ignore'] = ignore;

                if ( ignore === '1' ){
                    //close
                    $.pub('dhcp:switch', {'cmd': 'close'});
                } else {
                    $.pub('dhcp:switch', {'cmd': 'open'});
                }

                // $( 'input.iplimit' ).on( 'keydown', function(e){
                //     var lanip = ipPrefix.replace( '.', '\\.' ),
                //         re = new RegExp( '^'+ ipPrefix +'\\.\\d{1,3}$' );
                //     if ( e.keyCode === 46 || e.keyCode === 8 ) {
                //         if ( !re.test( this.value ) ) {
                //             return false
                //         }
                //     }

                // } );

            } else {
                $.alert( rsp.msg, function(){
                    location.reload( true );
                } );
            }

            $.pub( 'ajaxdone' );

        });
    } );

    $.sub( 'lanip:get', function(){
        var requestURL = '<%=luci.dispatcher.build_url("api", "xqnetwork","lan_info")%>',
            requestData = {};
        $.getJSON( requestURL, requestData, function( rsp ){
            if( rsp.code === 0 ){
                var ip = rsp.info.ipv4[0]['ip'];
                $( 'input[name=ip]' ).val( ip );
                $( 'input[name=old_ip]' ).val( ip );
            } else {
                $.alert( rsp.msg, function(){
                    location.reload( true );
                } );
            }

            $.pub( 'ajaxdone' );

        });
    } );

    $.sub( 'dhcp:switch', function( evt, data ){
        var btnClass = data.cmd === 'open' ? 'btn-switch-on' : 'btn-switch-off',
            $ignore = $( 'input[name="ignore"]' );

        $( '#dhcpswitch' )[0].className = 'btn-switch ' + btnClass;

        if ( data.cmd === 'open' ) {
            $ignore.val( 0 );
            $( '#lanDhcp .set' ).fadeIn();
        }else{
            $( '#lanDhcp .set' ).fadeOut();
            $ignore.val( 1 );
        }

    } );

    $.sub( 'addEvent', function( evt, data ){
        // switch
        $( '#dhcpswitch' ).click(function( e ){
            e.preventDefault();
            var cmd = $( this ).hasClass( 'btn-switch-on' ) ? 'close' : 'open';
            $.pub( 'dhcp:switch', {'cmd': cmd} );
        });

        // submit
        $( '#netDhcp' ).submit(function( e ){
            e.preventDefault();
            var formObj = this,
                formName = formObj.name,
                action = formObj.action,
                $ignore = $( 'input[name=ignore]' ),
                ignore = $ignore.val(),
                validator = Valid.checkAll(formObj);

            if ( ignore === '1' ) {
                validator = true;
            }

            if ( validator ) {
                var getIpLast = function( ip ){
                        return parseInt( ip.split('.')[3], 10 );
                    },
                    leasetime = parseInt( $( 'input[name=leasetime]' ).val(), 10 ),
                    start = $( 'input[name=start]' ).val(),
                    end = $( 'input[name=end]' ).val(),
                    leasetime_num,
                    leasetime_unit,
                    requestData,
                    requestURL = '<%=luci.dispatcher.build_url("api", "xqnetwork","set_lan_dhcp")%>';
                leasetime_unit = 'm';
                leasetime_num = leasetime;

                requestData = {
                    leasetime: leasetime_num + leasetime_unit,
                    start: start,
                    end: end,
                    ignore: ignore
                };

                if ( ignore === '1' ) {
                    requestData = {
                        ignore: ignore
                    };
                }

                $.pub( 'wait', {id: '#btnDhcpSubmit'} );
                $.getJSON( requestURL, requestData, function( rsp ){
                    if ( rsp.code === 0 ) {
                        $.alert('<%:设置成功%>', function(){
                            location.reload( true );
                        }).lock();
                    }else{
                        $.alert( rsp.msg );
                    }
                    $.pub( 'done', {id: '#btnDhcpSubmit'} );
                })
            }
        });
        // lanip
        $( '#ipaddr' ).on( 'submit', function( e ){
            e.preventDefault();
            var formObj = this,
                formName = formObj.name,
                ip = $.trim( $('input[name=ip]', formObj).val() ),
                oldIp = $.trim( $('input[name=old_ip]', formObj).val() ),
                validator =  Valid.checkAll(formObj);
            if ( validator ) {
                var requestURL = '<%=luci.dispatcher.build_url("api", "xqnetwork","set_lan_ip")%>',
                    requestData = {
                        ip: ip
                    };
                $.confirm('<%:此操作需要重启才能生效，是否提交?%>', function(){
                    $.pub( 'wait', {id: '#btnLanipSubmit'} );
                    $.getJSON( requestURL, requestData, function( rsp ){
                        if( rsp.code === 0 ){
                            var ip = rsp.ip;
                            rebootWait( {
                                lanIp : ip,
                                action : '<%:重启路由器%>',
                                refresh : true
                            } );
                        } else {
                            $.alert( rsp.msg );
                        }
                        $.pub( 'done', {id: '#btnLanipSubmit'} );
                    });
                });
            }
        } );
        function onControlFocus() {
            $(this).parents('form').find('.btn-primary').removeClass('hidden');
        }

        $('#netDhcp, #ipaddr').delegate('input[type=text], input[type=checkbox], input[type=radio]', 'click', onControlFocus);

        $('#dhcpswitch').on('click', function onDhcpswitchFocus() {
            $('#netDhcp').find('.btn-primary').removeClass('hidden');
        });
    } );

}());

$(function(){
    $.pub( 'dhcp:get' );
    $.pub( 'lanip:get' );
    $.pub( 'addEvent' );
});
</script>
</body>
</html>