var form = ''
var pageNumber = 1;
$(function(){
    var columns = [];
    columns.push({
            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:'deptName',
        });
    var roleId = $("#roleId").val();
    if(roleId == 0){
        columns.push({
            title:'所属医院',
            field:'hospitalName',
         });
    }
    columns.push(
        {
            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:'deptId', formatter: function(value,row,index){
                var editanddrop  = '';
                if(row.isUpdate == 1){
                    editanddrop += '<button type="button" onclick="edit('+row.deptId+')" class="btn btn-info operBtns btn-sm" >编辑</button>';
                }
                if(row.isDelete == 1){
                    editanddrop += '<button type="button" onclick="drop('+row.deptId+')" class="btn btn-danger operBtns btn-sm">删除</button>';
                }
                return editanddrop;
            }
        });
    $('#myModal').modal('hide');
    loadDict();
    //先销毁表格
    $('#bootstrapTable').bootstrapTable({
        //表格高度
        height: getHeight(),
        method : 'get',
        url :path+ "/dept/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, //当前页码
                deptName:$("#dept_name").val(),
                dictId:$("#dict_id option:selected").val(),
                effective : $("#effective option:selected").val(),
                creater:$("#creater").val(),
            };
            return temp;
        },
        columns : columns,
        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();
            $("#checks").val(checks+=row.deptId + ",");
        },
        //取消单个复选框
        onUncheck:function(row){
            var checks = $("#checks").val();
            checks = checks.replace(row.deptId + ",","");
            $("#checks").val(checks);
        },
        //全选
        onCheckAll:function(rows){
            $("#checks").val("");
            var checks = '';
            for(var i=0;i<rows.length;i++)
            {
                checks += rows[i].deptId + ","
            }
            $("#checks").val(checks);
        },
        //全不选
        onUncheckAll: function (rows) {
            $("#checks").val("");
        }
    });
    //初始化表单验证
    //formValidator();
});
/*//回跳表格页码
function backToPage(){
    var pageSize=$('#bootstrapTable').bootstrapTable('getOptions').pageSize;
    var rows=$('#bootstrapTable').bootstrapTable("getOptions").totalRows;
    if((pageSize*(pageNumber-1)) == (rows-1) && pageNumber != 1){
        pageNumber -= 1;
        refresh();
    }
    $('#bootstrapTable').bootstrapTable('selectPage', pageNumber);
}*/
//先销毁modal
/*$('#myModal').on('hidden.bs.modal', function() {
    $("#updateaddform").data('bootstrapValidator').destroy();
    $('#updateaddform').data('bootstrapValidator', null);
    formValidator();
});
//form验证规则
function formValidator() {
    //表单校验
    form = $('#updateaddform');
    form.bootstrapValidator({
        message: '输入值不合法',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            re_deptName: {
                message: '科室名不合法',
                validators: {
                    notEmpty: {
                        message: '角色名不能为空'
                    },
                    stringLength: {
                        min: 2,
                        max: 32,
                        message: '请输入2到32个字符'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_\. \u4e00-\u9fa5 ]+$/,
                        message: '角色名只能由字母、数字、点、下划线和汉字组成 '
                    }
                }
            }
            ,re_dictId: {
                validators: {

                }
            },re_effective: {
                validators: {

                }
            },re_remark: {
                validators: {

                }
            },
        }
    });
}*/
//加载
function loadDict(){
    $.ajax({
        type: "GET",
        url:path+  "/dict/selectHosList",
        dataType: "json",
        success: function(data){
            if(data != null){
                var html = '';
                $.each(data, function(commentIndex, comment){
                    html += '<option value="'+comment['dictId']+'">' + comment['hospitalName']
                        + '</option>';
                });
                $('#dict_id').append(html);
                $('#re_dictId').append(html);
            }
        }
    });
}
//验证科室名不能重复
$("#re_deptName").blur(function(){
    var deptId = $("#re_deptId").val();
    var deptName = $("#re_deptName").val();
    if(deptId == '' && deptName != ''){
        var dictId = $("#re_dictId").val();
        $.ajax({
            type:'get',
            url:path+'/dept/checkDeptName',
            data:{deptName:deptName,dictId:dictId},
            dataType:'json',
            success:function(data){
                if(data.code == 200){
                    toastr.warning("部门名已存在");
                    $("#re_deptName").val("");
                    $("#re_deptName").focus();
                }
            }
        })
    }

})
//编辑框回显
function edit(id){
    $("#myModalLabel").text("编辑");
    $.ajax({
        type: "post",
        url: path+ "/dept/selectDept",
        data:{
            deptId:id
        },
        dataType:"json",
        success: function(data){
            $("#re_deptId").val(data.deptId);
            $("#re_deptName").val(data.deptName);
            $("#re_dictId").find("option[value='"+data.dictId+"']").attr("selected",true);
            $("#re_effective").find("option[value='"+data.effective+"']").attr("selected",true);
            $("#re_remark").val(data.remark);
        }
    });
    $('#myModal').modal('show')
}
//删除
function drop(id) {
    Common.confirm({
        title: "提示",
        message: "确定是否删除这条记录",
        operate: function (reselt) {
            if (reselt) {
                $.ajax({
                    type: "post",
                    url: path + "/dept/delete",
                    data: {
                        deptId: id
                    },
                    async: false,
                    success: function (data) {
                        if ("success" == data.msg) {
                            toastr.success("删除成功!");
                            $("#checks").val("");
                            backToPage();
                        }
                    },
                    error: function () {
                        window.confirm("删除失败");
                    }
                })
            }
        }
    })
}
//新增框
function add() {
    initable();
    $("#myModalLabel").text('增加');
    $('#myModal').modal('show');
    $("#re_dictId").empty();
    loadDict();
}
//提交更改
$('#btn_submit').click(function () {
    var deptName = $("#re_deptName").val();
    var dictId = $("#re_dictId").val();
    if(deptName != ''){
        if(dictId != ''){
            var btype = $("#myModalLabel").text();
            if(btype=='编辑'){
                $.ajax({
                    type: "post",
                    url: path+ "/dept/update",
                    data:$("#updateaddform").serialize(),
                    dataType:"json",
                    success: function(data){
                        if("success"==data.msg){
                            toastr.success("修改成功!");
                            backToPage();
                            $('#myModal').modal('hide');
                        }else{
                            toastr.warning(data.msg);
                        }
                    }
                })
            }else if(btype =='增加'){
                $.ajax({
                    type: "post",
                    url:path+  "/dept/add",
                    data:$("#updateaddform").serialize(),
                    dataType:"json",
                    success: function(data){
                        if("success"==data.msg){
                            toastr.success("添加成功!");
                            setTimeout(function(){
                                window.location.reload();
                            },500)
                            $('#myModal').modal('hide');
                        }else{
                            toastr.warning(data.msg);
                        }
                    }
                })
            }
        }else{
            toastr.warning("所属医院不能为空!");
        }
    }else{
        toastr.warning("部门名称不能为空!");
    }
})
//初始化模态框
function initable(){
    $("#re_deptId").val("");
    $("#updateaddform")[0].reset();
}
//导出excel功能
function exportExcel(){
    var roleId = $("#roleId").val();
    var url = '';
    var checks = $("#checks").val();
    if(checks != '') {
        checks = checks.substring(0, checks.length - 1);
        if(roleId == 0){
            url = path+"/dept/export?deptName="+$("#dept_name").val()+"&dictId="+$("#dict_id").val()+"&effective="+$("#effective").val()+"&creater="+$("#creater").val()+"&checks="+checks;
        }else{
            url = path+"/dept/export?deptName="+$("#dept_name").val()+"&effective="+$("#effective").val()+"&creater="+$("#creater").val()+"&checks="+checks;
        }
        window.location.href = url;
    }else{
        Common.confirm({
            title: "提示",
            message: "没有选中，您确定要按搜索栏条件导出?",
            operate: function (reselt) {
                if (reselt) {
                    if (roleId == 0) {
                        url = path + "/dept/export?deptName=" + $("#dept_name").val() + "&dictId=" + $("#dict_id").val() + "&effective=" + $("#effective").val() + "&creater=" + $("#creater").val() + "&checks=" + checks;
                    } else {
                        url = path + "/dept/export?deptName=" + $("#dept_name").val() + "&effective=" + $("#effective").val() + "&creater=" + $("#creater").val() + "&checks=" + checks;
                    }
                    window.location.href = url;
                }
            }
        })
    }
}
//搜索
$('#queryBtn').click(function () {
    $("#checks").val("");
    refresh();
})
//获取table的高度
function getHeight() {
    return $(window).height() * 0.8;
}
//刷新表格
function refresh() {
    $('#bootstrapTable').bootstrapTable('refresh',{
        url :path+  '/dept/pageList'
    })
}
//清空
function clearForm(){
    $("#updateaddform")[0].reset();
}
//监听关闭模态框刷新事件
$('#myModal1').on('hide.bs.modal', function () {
    window.location.reload();
});