<%@ page language="java" pageEncoding="UTF-8"
         contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    String basePath = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>兰亭集智知识管理系统-用户管理</title>
    <jsp:include page="../../common/head.jsp"></jsp:include>
    <style type="text/css">
        .textbox {
            border: 1px solid #cccccc;
            -webkit-border-radius: 0px 0px 0px 0px;
            border-radius: 0px 0px 0px 0px;
        }
        .cardCanvas{
            text-align:center;
            padding:0px 0px;
            border-radius:5px;
            -moz-border-radius:5px;
        }
    </style>
</head>
<body>
<div class="easyui-layout" title="Register" style="width:100%;height:100%;padding:0px 0px;">
    <table id="dgUser" style="width:100%;height:100%"
           data-options="emptyMsg:'没有符合检索条件的结果',loadMsg:'正在检索请稍后...',toolbar:'#tbUserEdit',singleSelect:true,pagination:true,fitColumns:true,url:'<%=basePath%>/user/json/list.action',method:'get'">
        <thead>
        <tr>
            <th data-options="field:'id',width:80">编号</th>
            <th data-options="field:'username',width:150">用户名</th>
            <th data-options="field:'showname',width:200">全称</th>
            <th data-options="field:'salt',width:300">盐</th>
            <th data-options="field:'accountlock',width:60,formatter:function(lock){
                if(lock==1)
                    return '锁定';
                else
                    return '正常';
            }">状态
            </th>
            <th data-options="field:'addtime',width:200,formatter:function(date){
            return datetimeformat('Y-m-d H:i:s',date);
            }">添加时间
            </th>
            <th data-options="field:'_operation',width:180,formatter:optFormatter">操作</th>
        </tr>
        </thead>
    </table>
    <div id="userInfo" class="easyui-window" title="用户信息"
         data-options="modal:true,closed:true,collapsible:false,resizable:false,minimizable:false,maximizable:false,iconCls:'icon-save'"
         style="width:500px;height:400px;padding:10px;">
        <div class="easyui-layout" data-options="fit:true">
            <div data-options="region:'center'" style="padding:0px;">
                <form>
                    <div style="margin-bottom:20px">
                        <input type="hidden" id="userId" value="">
                        <input class="easyui-textbox" id="username" prompt="请输入用户帐号" style="width:100%"
                               data-options="label:'<span style=\'color:red;\'>*</span>用户帐号:',required:true">
                    </div>
                    <div style="margin-bottom:20px">
                        <input class="easyui-textbox" id="nickname" prompt="请输入用户全称" style="width:100%"
                               data-options="label:'&nbsp;用户全称:',required:true">
                    </div>
                    <div style="margin-bottom:20px">
                        <input class="easyui-passwordbox" id="userpassword" prompt="请输入密码" style="width:100%"
                               data-options="label:'<span style=\'color:red;\'>*</span>用户密码:',required:true,editable:true">
                    </div>
                    <div style="margin-bottom:20px">
                        <input class="easyui-textbox" id="pwdsalt" prompt="系统将自动生成盐" style="width:100%"
                               data-options="label:'<span style=\'color:red;\'>*</span>密码盐:',editable:false">
                    </div>
                    <div style="margin-bottom:20px">
                        <select class="easyui-combobox" id="userstate" label="<span style='color:red;'>*</span>帐号状态:"
                                style="width:100%">
                            <option value="-1">请选择状态</option>
                            <option value="0">正常</option>
                            <option value="1">锁定</option>
                        </select>
                    </div>
                    <div style="margin-bottom:20px">
                        注：带<span style="color:red;">*</span>的为必填项！
                    </div>
                </form>
            </div>
            <div data-options="region:'south',border:false" style="text-align:center;padding:5px 0 0;">
                <a id="btnSave" href="javascript:void(0)" class="easyui-linkbutton" iconCls="fa fa-floppy-o" onclick="saveUserInfo()"
                   style="width:80px">保存</a>
                <a id="btnCancle" href="javascript:void(0)" class="easyui-linkbutton" iconCls="fa fa-times" onclick="cancleSubmit()"
                   style="width:80px">取消</a>
            </div>
        </div>
    </div>

    <div id="secretKeyInfo" class="easyui-window" title="动态口令卡"
         data-options="modal:true,closed:true,collapsible:false,resizable:false,minimizable:false,maximizable:false,iconCls:'icon-save'"
         style="width:540px;height:420px;padding:10px;">
        <div class="easyui-layout" data-options="fit:true">
            <div data-options="region:'center'" style="padding:10px;">
                <form>
                    <div>
                        <canvas id="canvasSecretKey" class="cardCanvas" width="480" height="300"></canvas>
                    </div>
                </form>
            </div>
            <div data-options="region:'south',border:false" style="text-align:center;padding:5px 0 0;">
                <a id="btnBindSave" href="javascript:void(0)" class="easyui-linkbutton" iconCls="fa fa-floppy-o" onclick="saveTokenBind()"
                   style="width:80px">绑定</a>
                <a id="btnBindCancle" href="javascript:void(0)" class="easyui-linkbutton" iconCls="fa fa-times" onclick="cancleCardSubmit()"
                   style="width:80px">取消</a>
            </div>
        </div>
    </div>
    <div id="tbUserEdit" style="padding-left: 10px;">
        <input class="easyui-searchbox" style="width: 200px;" data-options="prompt:'请输入检索关键词',searcher:search">
        <a href="javascript:void(0);" onclick="search()" class="easyui-linkbutton" data-options="iconCls:'fa fa-search-plus',plain:true">开始检索</a>
        <a href="javascript:void(0);" onclick="addUserInfo()" class="easyui-linkbutton" data-options="iconCls:'fa fa-arrows',plain:true">添加用户</a>
        <a href="javascript:void(0);" onclick="refreshGrid()" class="easyui-linkbutton" data-options="iconCls:'fa fa-repeat',plain:true">刷新用户</a>
    </div>


    <div id="iTipTokenMngr" class="easyui-window" title="温馨提示"
         data-options="modal:true,closed:true,collapsible:false,resizable:false,minimizable:false,maximizable:false,iconCls:'icon-save'"
         style="width:500px;height:340px;padding:10px;">
        <div class="easyui-layout" data-options="fit:true">
            <div data-options="region:'center'" style="padding:10px;">
                <form>
                    <div style="margin-bottom:20px">
                        <input class="easyui-textbox" id="sentry-api-token-username" style="width:100%"
                               data-options="label:'&nbsp;用&nbsp;&nbsp;户&nbsp;&nbsp;名:',editable:false" value="">
                    </div>
                    <div style="margin-bottom:20px">
                        <input class="easyui-textbox" id="sentry-api-token-card" style="width:100%"
                               data-options="label:'&nbsp;卡&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:',editable:false" value="">
                    </div>
                    <div style="margin-bottom:20px">
                        <input class="easyui-textbox" id="sentry-api-token-date" style="width:100%"
                               data-options="label:'&nbsp;同步时间:',editable:false" value="">
                    </div>
                    <div style="margin-bottom:20px">
                        <label style="margin-right: 5px;"><span style="color:red;">*</span>授&nbsp;&nbsp;权&nbsp;&nbsp;码:</label>
                        <input class="easyui-textbox" id="sentry-api-token-one" style="width:80px;"  data-options="label:'--:',labelWidth:40,labelAlign:'right'">
                        <input class="easyui-textbox" id="sentry-api-token-two" style="width:80px;"  data-options="label:'--:',labelWidth:40,labelAlign:'right'">
                        <input class="easyui-textbox" id="sentry-api-token-three" style="width:80px;"  data-options="label:'--:',labelWidth:40,labelAlign:'right'">
                        <input class="easyui-textbox" id="sentry-api-token-four" style="width:80px;"  data-options="label:'--:',labelWidth:40,labelAlign:'right'">
                    </div>
                    <div>
                        注：带<span style="color:red;">*</span>的为必填项！
                    </div>
                </form>
            </div>
            <div data-options="region:'south',border:false" style="text-align:center;padding:5px 0 0;">
                <a id="btnDelete" href="javascript:void(0)" class="easyui-linkbutton" iconCls="fa fa-floppy-o"
                   onclick="bindSecureKey()"
                   style="width:80px">提交</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="fa fa-times"
                   onclick="cancleTokenSubmit()"
                   style="width:80px">取消</a>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        function optFormatter(value, row, index) {
            var optStr="<a href='javascript:void(0);' onclick='return viewUserInfo(" + index + ");'>查看</a>&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onclick='return editUserInfo(" + index + ");'>编辑</a>&nbsp;&nbsp;&nbsp;";
            if (row.id>1) {
                if (row.accountlock == 1) {
                    optStr += "<a href='javascript:void(0);' onclick='return lockUserInfo(" + index + ",0);'>解锁</a>&nbsp;&nbsp;&nbsp;";
                } else {
                    optStr += "<a href='javascript:void(0);' onclick='return lockUserInfo(" + index + ",1);'>锁定</a>&nbsp;&nbsp;&nbsp;";
                }
                optStr += "<a href='javascript:void(0);' onclick='del(" + index + ");'>删除</a>&nbsp;&nbsp;&nbsp;";
            }
            optStr += "<a href='javascript:void(0);' onclick='viewSecureKey(" + index + ");'>动态口令</a>";
            return optStr;
        }
        function search(){

        }
        function cancleTokenSubmit(){
            $('#iTipTokenMngr').window('close');
        }
        function saveTokenBind(){
            $.ajax({
                type: "get",
                url: "<%=basePath %>/token/json/user/secret/key.action",
                timeout: 30000,
                dataType: "json",
                data: {r: Math.round(new Date().getTime() / 1000)},
                beforeSend: function (XMLHttpRequest) {
                    win = $.messager.progress({
                        title: '动态口令',
                        msg: '正在校验信息...'
                    });
                },
                success: function (data) {
                    var keyList = data.message.split(":");
                    $("#sentry-api-token-one").textbox({
                        label: keyList[0] + ':'
                    });
                    $("#sentry-api-token-two").textbox({
                        label: keyList[1] + ':'
                    });
                    $("#sentry-api-token-three").textbox({
                        label: keyList[2] + ':'
                    });
                    $("#sentry-api-token-four").textbox({
                        label: keyList[3] + ':'
                    });

                    $("#sentry-api-token-one").textbox("setValue", "");
                    $("#sentry-api-token-two").textbox("setValue", "");
                    $("#sentry-api-token-three").textbox("setValue", "");
                    $("#sentry-api-token-four").textbox("setValue", "");
                    $('#iTipTokenMngr').window('open');
                },
                complete: function (XMLHttpRequest, textStatus) {
                    $.messager.progress('close');
                },
                error: function () {
                    $.messager.alert('温馨提示', '校验信息出错！');
                }
            });
        }
        function viewSecureKey(index) {
            if (index < 0) {
                $.messager.alert('温馨提示', '系统参数错误！');
            } else {
                var row = $('#dgUser').datagrid('getRows')[index];
                $("#sentry-api-token-username").textbox("setValue", row.username);
                var win = null;
                $.ajax({
                    type:"get",
                    url:"<%=basePath %>/token/json/secret/make/card.action",
                    timeout:30000,
                    dataType:"json",
                    beforeSend:function(XMLHttpRequest){
                        win=$.messager.progress({
                            title:'动态口令卡管理',
                            msg:'正在校验创建动态口令卡...'
                        });
                    },
                    success:function(data){
                        if(data.status==1){
                            $("#sentry-api-token-card").textbox("setValue", data.serialno);
                            $("#sentry-api-token-date").textbox("setValue",datetimeformat('Y-m-d H:i:s',data.synctime));
                            createCard(data.serialno,data.secretkeys,data.synctime);
                            $('#secretKeyInfo').window('open');
                        }else{
                            $.messager.alert('温馨提示',data.message);
                        }
                    },
                    complete:function(XMLHttpRequest, textStatus){
                        $.messager.progress('close');
                    },
                    error:function(){
                        $.messager.alert('温馨提示', '请求出错！');
                    }
                });
            }
            return false;
        }
        function formatToken(token){
            if($.trim(token).length <= 0){
                return "00";
            }else if($.trim(token).length == 1){
                return "0"+token;
            }else{
                return token.substr(0,2);
            }
        }
        function bindSecureKey() {
            var tokenObj=new Object();
            tokenObj.token=formatToken($("#sentry-api-token-one").textbox("getValue")) +formatToken($("#sentry-api-token-two").textbox("getValue"))+formatToken($("#sentry-api-token-three").textbox("getValue"))+formatToken($("#sentry-api-token-four").textbox("getValue"));
            tokenObj.cardno=$("#sentry-api-token-card").textbox("getValue");
            tokenObj.username=$("#sentry-api-token-username").textbox("getValue");
            tokenObj.synctime=Number(new Date(Date.parse($("#sentry-api-token-date").textbox("getValue").replace(/-/g,  "/"))));
            if ($.trim(tokenObj.token).length <= 0) {
                $.messager.alert('温馨提示', "请填写授权码");
                return false;
            }
            var win = null;
            $.ajax({
                type:"POST",
                url:"<%=basePath %>/token/json/secret/bind/card.action",
                timeout:30000,
                dataType:"json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(tokenObj),
                beforeSend:function(XMLHttpRequest){
                    win=$.messager.progress({
                        title:'动态口令卡管理',
                        msg:'正在校验绑定动态口令卡...'
                    });
                },
                success:function(data){
                    if(data.status==1){
                        $.toast({text: 'data.message',position:'mid-center',allowToastClose: false,loader: false,afterHidden: function () {
                            cancleTokenSubmit();
                        }});
                    }else{
                        $.messager.alert('温馨提示',data.message);
                    }
                },
                complete:function(XMLHttpRequest, textStatus){
                    $.messager.progress('close');
                },
                error:function(){
                    $.messager.alert('温馨提示', '请求出错！');
                }
            });
            return false;
        }
        function viewUserInfo(index) {
            if (index < 0) {
                $.messager.alert('温馨提示', '系统参数错误！');
            } else {
                var row = $('#dgUser').datagrid('getRows')[index];
                $("#userId").val(row.id);
                $("#username").textbox("setValue", row.username);
                $("#nickname").textbox("setValue", row.showname);
                $("#userpassword").passwordbox("setValue", row.password);
                $("#pwdsalt").textbox("setValue", row.salt);
                $("#userstate").combobox("setValue", row.accountlock);
                $('#btnSave').linkbutton('disable');
                $('#userInfo').window('open');
            }
            return false;
        }
        function addUserInfo() {
            $("#pwdsalt").textbox("setValue","");
            $("#username").textbox("clear");
            $("#nickname").textbox("clear");
            $("#userpassword").passwordbox("clear");
            $("#pwdsalt").textbox("clear");
            $("#userstate").combobox("setValue", -1);
            $("#userId").val("");
            $('#userInfo').window('open');
            $('#btnSave').linkbutton('enable');
            $('#btnCancle').linkbutton('enable');
            $('#userInfo').window('open');
            return false;
        }
        function editUserInfo(index) {
            if (index < 0) {
                $.messager.alert('温馨提示', '系统参数错误！');
            } else {
                var row = $('#dgUser').datagrid('getRows')[index];
                $("#userId").val(row.id);
                $("#username").textbox("setValue", row.username);
                $("#nickname").textbox("setValue", row.showname);
                $("#userpassword").passwordbox("setValue", row.password);
                $("#pwdsalt").textbox("setValue", row.salt);
                $("#userstate").combobox("setValue", row.accountlock);

                $('#username').textbox('disable');
                $('#pwdsalt').textbox('disable');
                $('#btnSave').linkbutton('enable');
                $('#btnCancle').linkbutton('enable');
                $('#userInfo').window('open');
            }
            return false;
        }
        function del(index) {
            if (index<0) {
                $.messager.alert('温馨提示', '系统参数错误！');
            } else {
                var row = $('#dgUser').datagrid('getRows')[index];
                if(row.id==1){
                    $.messager.alert('温馨提示', '当前用户不允许删除！');
                }else {
                    $.messager.confirm("温馨提示", "你确定要删除用户" + row.showname + "吗?", function (r) {
                        if (r) {
                            var win = null;
                            $.ajax({
                                type:"post",
                                url:"<%=basePath %>/user/json/user/delete.action",
                                timeout:30000,
                                dataType:"json",
                                data: {uid:row.id},
                                beforeSend:function(XMLHttpRequest){
                                    win=$.messager.progress({
                                        title:'用户管理',
                                        msg:'正在校验删除...'
                                    });
                                },
                                success:function(data){
                                    if(data.status==1){
                                        $.messager.alert({title:'温馨提示',msg:data.message,fn:function(){
                                            $('#dgUser').datagrid('reload');
                                        }});
                                    }else{
                                        $.messager.alert('温馨提示',data.message);
                                    }
                                },
                                complete:function(XMLHttpRequest, textStatus){
                                    $.messager.progress('close');
                                },
                                error:function(){
                                    $.messager.alert('温馨提示', '请求出错！');
                                }
                            });
                        }
                    });
                }
            }
            return false;
        }
        function cancleSubmit(){
            $("#username").textbox("clear");
            $("#nickname").textbox("clear");
            $("#userpassword").passwordbox("clear");
            $("#pwdsalt").textbox("clear");
            $("#userstate").combobox("setValue", -1);
            $("#userId").val("");
            $('#userInfo').window('close');
        }
        function lockUserInfo(index,userstate){
            if (index < 0) {
                $.messager.alert('温馨提示', '系统参数错误！');
            } else {
                var row = $('#dgUser').datagrid('getRows')[index];
                var errorMsg="您确定要";
                if(userstate==0){
                    errorMsg+="解除账户【"+row.showname+"】锁定状态?"
                }else{
                    errorMsg+="锁定账户【"+row.showname+"】?"
                }
                $.messager.confirm("温馨提示", errorMsg, function (r) {
                    if (r) {
                        var win = null;
                        $.ajax({
                            type:"post",
                            url:"<%=basePath %>/user/json/lock.action",
                            timeout:30000,
                            dataType:"json",
                            data: {id:row.id,lock:userstate},
                            beforeSend:function(XMLHttpRequest){
                                win=$.messager.progress({
                                    title:'用户管理',
                                    msg:'正在校验添加用户...'
                                });
                            },
                            success:function(data){
                                if(data.status==1){
                                    $.messager.alert({title:'温馨提示',msg:data.message,fn:function(){
                                        $('#dgUser').datagrid('reload');
                                        $('#userInfo').window('close');
                                    }});
                                }else{
                                    $.messager.alert('温馨提示',data.message);
                                }
                            },
                            complete:function(XMLHttpRequest, textStatus){
                                $.messager.progress('close');
                            },
                            error:function(){
                                $.messager.alert('温馨提示', '请求出错！');
                            }
                        });
                    }
                });
            }
            return false;
        }
        function saveUserInfo(){
            var win = null;
            var username= $("#username").textbox("getValue");
            if($.trim(username).length<=0 )
            {
                $.messager.alert('温馨提示',"请填写登录帐号");
                return false;
            }
            var nickname=$("#nickname").textbox("getValue");
            if($.trim(nickname).length<=0)
            {
                $.messager.alert('温馨提示',"请填写帐号全称");
                return false;
            }
            var userpassword=$("#userpassword").passwordbox("getValue");
            if($.trim(userpassword).length<=0)
            {
                $.messager.alert('温馨提示',"请填写帐号密钥");
                return false;
            }
            var userstate= $("#userstate").combobox("getValue");
            if($.trim(userstate).length<=0 || userstate==-1)
            {
                $.messager.alert('温馨提示',"请选择帐号状态");
                return false;
            }
            $.ajax({
                type:"post",
                url:"<%=basePath %>/user/json/save.action",
                timeout:30000,
                dataType:"json",
                data: {id:$("#userId").val(),username:username,fullname:nickname,password:userpassword,lock:userstate},
                beforeSend:function(XMLHttpRequest){
                    win=$.messager.progress({
                        title:'用户管理',
                        msg:'正在校验添加用户...'
                    });
                },
                success:function(data){
                    if(data.status==1){
                        $.messager.alert({title:'温馨提示',msg:data.message,fn:function(){
                            $('#dgUser').datagrid('reload');
                            $('#userInfo').window('close');
                        }});
                    }else{
                        $.messager.alert('温馨提示',data.message);
                    }
                },
                complete:function(XMLHttpRequest, textStatus){
                    $.messager.progress('close');
                },
                error:function(){
                    $.messager.alert('温馨提示', '请求出错！');
                }
            });
        }
        $(function () {
            var pager = $('#dgUser').datagrid().datagrid('getPager');
            pager.pagination({
                showPageList:false
            });
        })

       function refreshGrid(){
           $('#dgUser').datagrid('reload');
       }
        function cancleCardSubmit(){
            $('#secretKeyInfo').window('close');
        }
        /**开始绘制动态密保卡**/
        function createCard(serialno,secretkeys,synctime){
            var xAxiss=new Array("A","B","C","D","E","F","G","H","J","K");
            var canvas=document.getElementById("canvasSecretKey");
            var ctx=canvas.getContext('2d');
            var img = new Image();   // 创建img元素
            img.src = '<%=basePath %>/resource/images/secretcard.png';
            img.onload = function(){
                // 执行drawImage语句
                ctx.drawImage(img, 0, 0, 480, 300);
                ctx.font = 'bold 22px';
                ctx.fillStyle="black";
                for (var i = 0; i<10; i++) {
                    ctx.fillText(xAxiss[i],60.5+40*i,25.5);
                }
                for (var i = 0; i<9;i++) {
                    drawLine(ctx,45.5,30*(i+1)+0.5,445.5,30*(i+1)+0.5);
                }
                for (var i = 0; i<8; i++) {
                    ctx.fillText(i+1,30.5,50.5+30*i);
                }
                for (var j = 0; j<=10; j++) {
                    drawLine(ctx,45.5+40*j,30.5,45.5+40*j,30*9+0.5);
                }
                ctx.fillStyle="gray";
                ctx.font = '10px';
                ctx.fillText("NO："+serialno,40.5,285.5);
                ctx.font = '10px';
                ctx.fillText("技术支持部提供技术支持",340.5,285.5);
                ctx.fillStyle="black";
                for(var i=0;i<8;i++){
                    for(var j=0;j<10;j++){
                        ctx.fillText(secretkeys[j][i],60.5+40*j,50.5+30*i);
                    }
                }
            }
        }
        function drawLine(ctx, startX, startY, endX, endY) {
            ctx.beginPath();
            ctx.strokeStyle="gray";
            ctx.lineWidth = 1;
            ctx.moveTo(startX, startY);
            ctx.lineTo(endX, endY);
            ctx.stroke();
            ctx.closePath();
        }
        /**结束绘制动态密保卡**/
    </script>
</div>
</body>
</html>