var pageNumber=1;
var form = '';
    $(function(){
        $('#myModal').modal('hide');
        loadDept();
        loadRole();
        //先销毁表格
        $('#bootstrapTable').bootstrapTable({
            //表格高度
            height: getHeight(),
            method : 'get',
            url :path+ "/user/pageList",//请求路径
            striped : true, //是否显示行间隔色
            pageNumber : 1, //初始化加载第一页
            pagination : true,//是否分页
            sidePagination : 'server',//server:服务器端分页|client：前端分页
            pageSize : 10,//单页记录数
            pageList : [ 5, 10, 20, 30 ],//可选择单页记录数
            cache: false,
            paginationPreText : '上一页',
            paginationNextText : '下一页',
            queryParams : function(params) {//上传服务器的参数
                var temp = {//如果是在服务器端实现分页，limit、offset这两个参数是必须的
                    limit : params.limit, // 每页显示数量
                    offset : params.offset, // SQL语句起始索引
                    page : (params.offset / params.limit) + 1, //当前页码
                    userName:$("#user_name").val(),
                    userEmail:$("#user_email").val(),
                    searchRoleId:$("#roleId").val(),
                    deptId : $("#dept_id option:selected").val(),
                    effective : $("#effective option:selected").val(),
                };
                return temp;
            },
            columns : [{
                    checkbox:true
                },
                {
                    title:'序号',
                    field:'no',
                    formatter: function (value, row, index) {
                        //获取每页显示的数量
                        var pageSize = $('#bootstrapTable').bootstrapTable('getOptions').pageSize;
                        //获取当前是第几页
                        if(pageNumber == 1){
                            pageNumber = $('#bootstrapTable').bootstrapTable('getOptions').pageNumber;
                        }
                        //返回序号，注意index是从0开始的，所以要加上1
                        return pageSize * (pageNumber - 1) + index + 1;
                    }
                },
                {
                    title:'账号',
                    field:'userName',
                },
                {
                    title:'姓名',
                    field:'name',
                },
                {
                    title:'性别',
                    field:'userSex',
                    formatter: function (value, row, index) {
                        if(value ==1){
                            return '女'
                        }else if(value ==0){
                            return '男'
                        }
                    }
                },
                {
                    title:'年龄',
                    field:'userAge',
                },
                {
                    title:'移动电话',
                    field:'userTel',
                },
                {
                    title:'邮箱地址',
                    field:'userEmail',
                },
                {
                    title:'用户职位',
                    field:'userPosition',
                },
                {
                    title:'所属角色',
                    field:'roleName',
                },
                {
                    title:'所属部门',
                    field:'powerDepts',
                    formatter:paramsMatter,
                },
                {
                    title:'是否有效',
                    field:'effective',
                    formatter: function (value, row, index) {
                        if(value ==1){
                            return '是'
                        }else if(value ==0){
                            return '否'
                        }
                    }
                },
                {
                    title:'创建时间',
                    field:'createDate',
                },
                {
                    title:'创建人',
                    field:'creater',
                },
                {
                    title:'修改时间',
                    field:'updateDate',
                },
                {
                    title:'修改人',
                    field:'updater',
                },
                {
                    title:'操作',
                    field:'userId', formatter: function(value,row,index){
                        var editanddrop  = '';
                        if(row.isUpdate == 1){
                            editanddrop += '<button type="button" onclick="edit('+row.userId+')" class="btn btn-info operBtns btn-sm" >编辑</button>';
                        }
                        if(row.isDelete == 1){
                            editanddrop += '<button type="button" onclick="drop('+row.userId+')" class="btn btn-danger operBtns btn-sm">删除</button>';
                        }
                        return editanddrop;
                    }
                }
            ],
            onLoadSuccess: function(){  //加载成功时执行
                $(".page-list").show();
                $("th").css({'text-align':'center','vertical-align':'middle'})
                $("td").css({'text-align':'center','vertical-align':'middle'})
            },
            //监听分页点击事件
            onPageChange: function(num, type) {
                pageNumber = num;
            },
            //选中单个复选框
            onCheck:function(row){
                var checks = $("#checks").val();
                var userNames = $("#userNames").val();
                $("#checks").val(checks+=row.userId + ",");
                $("#userNames").val(userNames+=row.userName + ",");
            },
            //取消单个复选框
            onUncheck:function(row){
                var checks = $("#checks").val();
                var userNames = $("#userNames").val();
                checks = checks.replace(row.userId + ",","");
                userNames = userNames.replace(row.userName + ",","");
                $("#checks").val(checks);
                $("#userNames").val(userNames);
            },
            //全选
            onCheckAll:function(rows){
                $("#checks").val("");
                $("#userNames").val("");
                var checks = '';
                var userNames = '';
                for(var i=0;i<rows.length;i++)
                {
                    checks += rows[i].userId + ","
                    userNames += rows[i].userName + ","
                }
                $("#checks").val(checks);
                $("#userNames").val(userNames);
            },
            //全不选
            onUncheckAll: function (rows) {
                $("#checks").val("");
                $("#userNames").val("");
            }
        });
    });
//格式化科室列
function paramsMatter(value, row, index) {
    value = '<p class="hidden-xs" title="'+value+'">'+value+'</p>'
    return value;
}


//验证表单
//验证用户名不重复
$("#re_userName").blur(function(){
    var userId = $("#userId").val();
    var userName = $("#re_userName").val();
    if(userId == '' && userName != ''){
        $.ajax({
            type:'get',
            url:path+'/user/checkUserName?userName='+userName,
            dataType:'json',
            success:function(data){
                if(data.code == 200){
                    toastr.warning(data.msg);
                    $("#re_userName").val("");
                    $("#re_userName").focus();
                }
            }
        })
    }
})
//验证密码长度不少于6位
$("#re_userPwd").blur(function(){
    var password = $("#re_userPwd").val();
    if(password != '' && password.length < 6){
        toastr.warning("密码长度不能少于6位!");
    }
})
/*//验证手机号
$("#re_userTel").blur(function(){
    var tel = $("#re_userTel").val();
    if(tel != ''){
        if(!tel.match(/^1[34578]\d{9}$/)){
            toastr.warning("移动电话格式不正确!");
            $("#re_userTel").val("");
            $("#re_userTel").focus();
        }
    }
})
//验证邮箱
$("#re_userEmail").blur(function(){
    var email = $("#re_userEmail").val();
    if(email != ''){
        if(!email.match(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/)){
            toastr.warning("邮箱地址格式不正确!");
            $("#re_userEmail").val("");
            $("#re_userEmail").focus();
        }
    }
})*/
//所属科室多选树形
function showMenu1() {
    var cityObj = $('#txtTreeSelect1');
    var cityOffset = cityObj.offset();
    $("#menuContent1").css({ left: cityOffset.left + "px", top: cityOffset.top + cityObj.outerHeight() + "px" }).slideDown("fast");
    $("body").bind("mousedown", onBodyDown1);
}
function onBodyDown1(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "menuContent1" || $(event.target).parents("#menuContent1").length > 0)) {
        hideMenu1();
    }
}
function hideMenu1() {
    $("#menuContent1").fadeOut("name");
    $("body").unbind("mousedown", onBodyDown1);
}
//加载角色
function loadRole(){
    $.ajax({
        type: "GET",
        url: path+"/role/selectList",
        dataType: "json",
        success: function(data){
            var html = '';
            $.each(data, function(commentIndex, comment){
                html += '<option value="'+comment['roleId']+'">' + comment['roleName']
                    + '</option>';
            });
            $('#re_roleId').append(html);
            $('#roleId').append(html);
        }
    });
}
function loadDept(){
    $.ajax({
        type: "GET",
        url: path+"/dept/selectList",
        dataType: "json",
        success: function(data){
            var html = '';
            for(var i = 0;i < data.extend.list.length;i++){
                html += '<option value="'+data.extend.list[i].deptId+'">' + data.extend.list[i].deptName
                    + '</option>';
            }
            $('#dept_id').append(html);
        }
    });
}
//搜索
$('#queryBtn').click(function () {
    $("#checks").val("");
    refresh();
})
//编辑框回显
function edit(id){
    $("#re_userName").prop("readOnly",true);
    $("#passwordDiv").hide();
     $("#myModalLabel").text("编辑");
     $.ajax({
         type: "post",
         url: path+"/user/selectUser",
         data:{
             userId:id
        },
         dataType:"json",
         success: function(data){
             $("#userId").val(data.userId);
             $("#re_userName").val(data.userName);
             $("#name").val(data.name);
             var deptIds = data.deptId;
             var deptArr = deptIds.split(",");
             $('#deptId').selectpicker('val', deptArr);
             if(data.userSex == 1){
                 $("#re_userSex").val("1");
             }else{
                 $("#re_userSex").val("0");
             }
             $("#re_userAge").val(data.userAge);
             $("#re_userTel").val(data.userTel);
             $("#re_userEmail").val(data.userEmail);
             $("#re_userPosition").val(data.userPosition);
             $("#txtTreeSelect1").val(data.powerDepts);
             $("#deptIds").val(data.deptId);
             $("#re_roleId").find("option[value='"+data.roleId+"']").attr("selected",true);
             $("#re_effective").find("option[value='"+data.effective+"']").attr("selected",true);
             $("#re_remark").val(data.remark);
             /*loadTree();
             var deptIds = data.deptId;
             if(deptIds != ''){
                 var deptIdSplit =deptIds.split(",");
                 for (var i = 0;i < deptIdSplit.length;i++){
                     if(deptIdSplit[i] != ''){
                         //选中节点
                         treeSelectNode(deptIdSplit[i]);
                     }
                 }
             }*/
         }
     });
    $('#myModal').modal('show');
}
//删除
function drop(id) {
    Common.confirm({
        title: "提示",
        message: "确定是否删除这条记录",
        operate: function (reselt) {
            if (reselt) {
                $.ajax({
                    type: "post",
                    url: path + "/user/delete",
                    data: {
                        userId: id
                    },
                    async: false,
                    success: function (data) {
                        if ("success" == data.msg) {
                            toastr.success("删除成功!");
                            $("#checks").val("");
                            $("#userNames").val("");
                            backToPage();
                        } else {
                            toastr.error(data.msg);
                        }
                    },
                    error: function () {
                        window.confirm("删除失败");
                    }
                })
            }
        }
    })
}
//新增框
function add() {
    $("#re_userName").prop("readOnly",false);
    clearForm();
    $("#userId").val("");
    $("#deptIds").val("");
    $('.selectpicker').selectpicker('val','1');
    $('#myModal').modal('show');
    $("#passwordDiv").show();
}
//清空
function clearForm(){
    $("#updateaddform")[0].reset();
    //loadTree();
    $("#deptIds").val("");
}
//提交更改
$('#btn_submit').click(function () {
    var reUserTel = $("#re_userTel").val();
    if(reUserTel != ''){
        if(!reUserTel.match(/^1[34578]\d{9}$/)){
            toastr.warning("移动电话格式不正确!");
            $("#re_userTel").val("");
            $("#re_userTel").focus();
            return false;
        }
    }
    var reUserEmail = $("#re_userEmail").val();
    if(reUserEmail != ''){
        if(!reUserEmail.match(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/)){
            toastr.warning("邮箱地址格式不正确!");
            $("#re_userEmail").val("");
            $("#re_userEmail").focus();
            return false;
        }
    }
    var userName = $("#re_userName").val();
    var userPwd = $("#re_userPwd").val();
    var deptIds  = $("#deptIds").val();
    var roleId = $("#re_roleId").val();
    if(userName != ''){
        if(userPwd != '' || $("#userId").val() != ''){
            if(userPwd.length >= 6 || $("#userId").val() != ''){
                if(deptIds != ''){
                    if(roleId != ''){
                        saveForm();
                    }else{
                        toastr.warning("所属角色不能为空，如未显示角色请到角色管理添加角色!");
                    }
                }else{
                    toastr.warning("所属科室不能为空!");
                }
            }else{
                toastr.warning("密码长度不能少于6位!");
            }
        }else{
            toastr.warning("密码不能为空!");
        }
    }else{
        toastr.warning("用户名不能为空!");
    }
})

function saveForm(){
    var userId = $("#userId").val();
    if(userId != ''){
        $.ajax({
            type: "post",
            url:path+ "/user/update",
            data:$("#updateaddform").serialize(),
            dataType:"json",
            success: function(data){
                if("success"==data.msg){
                    toastr.success("修改成功!");
                    $('#myModal').modal('hide');
                    backToPage();
                }else{
                    toastr.warning(data.msg);
                }
            }
        })
    }else if(userId == ''){
        $.ajax({
            type: "post",
            url:path+ "/user/add",
            data:$("#updateaddform").serialize(),
            dataType:"json",
            success: function(data){
                if("success"==data.msg){
                    toastr.success("添加成功!");
                    setTimeout(function(){
                        window.location.reload();
                    },500)
                }else{
                    toastr.warning(data.msg);
                }
            }
        })
    }
}
//获取table的高度
function getHeight() {
    return $(window).height() - 190;
}
//刷新表格
function refresh() {
    $('#bootstrapTable').bootstrapTable('refresh',{
        url : path+'/user/pageList'
    })
}
//重置密码
function resetPassword(){
    var checks = $("#checks").val();
    var userNames = $("#userNames").val();
    if(checks != ''){
        var ids = checks.split(",");
        var userName = userNames.split(",");
        if(ids.length == 2){
            Common.confirm({
                title: "提示",
                message: '确定是否重置用户名'+userName[0]+'的密码为000000',
                operate: function (reselt) {
                    if (reselt) {
                        $.ajax({
                            type: 'post',
                            url: path + '/user/resetPassword',
                            data: {userId: ids[0]},
                            dataType: 'json',
                            success: function (data) {
                                if (data.code == 100) {
                                    toastr.success("重置成功!");
                                    $("#checks").val("");
                                    $("#userNames").val("");
                                    backToPage();
                                } else {
                                    toastr.error("重置失败,请联系系统管理员!")
                                }
                            }
                        })
                    }
                }
            })
        }else{
            toastr.warning("以防重置密码误选择,只允许一次重置一个!")
        }
    }else{
        toastr.warning("请至少选中一条记录!")
    }
}
//导出excel功能
function exportExcel(){
    var checks = $("#checks").val();
    if(checks != '') {
        checks = checks.substring(0, checks.length - 1);
        var url = path+"/user/export?userName="+$("#user_name").val()+"&userEmail="+$("#user_email").val()+"&searchRoleId="+$("#roleId").val()+"&deptId="+$("#dept_id").val()+"&effective="+$("#effective").val()+"&checks="+checks;
        window.location.href = url;
    }else{
        Common.confirm({
            title: "提示",
            message: "没有选中，您确定要按搜索栏条件导出?",
            operate: function (reselt) {
                if (reselt) {
                    var url = path+"/user/export?userName="+$("#user_name").val()+"&userEmail="+$("#user_email").val()+"&searchRoleId="+$("#roleId").val()+"&deptId="+$("#dept_id").val()+"&effective="+$("#effective").val()+"&checks="+checks;
                    window.location.href = url;
                }
            }
        })
       /* if(confirm('没有选中，您确定要按搜索栏条件导出?')) {
            var url = path+"/user/export?userName="+$("#user_name").val()+"&userEmail="+$("#user_email").val()+"&searchRoleId="+$("#roleId").val()+"&deptId="+$("#dept_id").val()+"&effective="+$("#effective").val()+"&checks="+checks;
            window.location.href = url;
        }*/
    }

}
/**树操作*/
/*var setting = {
    view: {
        showIcon: true,//设置 zTree 是否显示节点的图标。默认值：true
        showLine: true//设置 zTree 是否显示节点之间的连线。默认值：true
    },
    data: {
        simpleData: {
            chkStyle: "checkbox",
            enable: true,
            idKey: "id",
            pIdKey: "parentId"
        }
    },
    check:{
        enable:true
    },
    callback: {
        onCheck:onCheck
    }
};
function onCheck(e, treeId, treeNode) {
    var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
    nodes=treeObj.getCheckedNodes(true);
    var deptIds = '';
    var deptNames = '';
    //父节点必须一样
    var parentId = new Array();
    for (var i = 0; i < nodes.length; i++) {
        if(nodes[i].level == 0){
            var id = nodes[i].id;
            parentId.push(id);
        }
        if(nodes[i].level == 1){
            var deptId = nodes[i].selfId;
            deptIds += deptId + ",";
            deptNames += nodes[i].name + ",";
        }
    }
    if(parentId.length > 1) {
        toastr.warning("科室必须全部属于同一医院!");
        treeObj.checkNode(treeNode,false,true);
    }else{
        if(deptIds != ''){
            deptIds = deptIds.substring(0,deptIds.length-1);
            deptNames = deptNames.substring(0,deptNames.length-1);
        }
        $("#txtTreeSelect1").val(deptNames);
        $("#deptIds").val(deptIds);
    }
}
var zNodes = [];
function loadTree() {
    $.ajax({
        type: "GET",
        url: path + "/dept/selectDeptTreeByUserId",
        dataType: "json",
        async: false,
        success: function (data) {
            $.fn.zTree.init($("#treeDemo"), setting, data);
            zTree = $.fn.zTree.getZTreeObj("treeDemo");
            var nodes = zTree.getNodes();
            for (var i = 0; i < nodes.length; i++) { //设置节点展开
                zTree.expandNode(nodes[i], true, false, true);
            }
        }
    });
}
//加载树
$(function(){
    $("#re_userName").val("");
    $("#updateaddform")[0].reset();
    loadTree();
})
//选中节点 selfId
function treeSelectNode(selfId){
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    var node = zTree.getNodeByParam("selfId",selfId);
    if(node != null){
        zTree.checkNode(node, true, true);
    }
}*/

//监听关闭模态框刷新事件
$('#myModal1').on('hide.bs.modal', function () {
    window.location.reload();
});