$(function(){
    //加载组别
    loadFunGroup();
    //加载时间控件
    initDateInput(1);
})
//加载功能组别
function loadFunGroup(){
    $.ajax({
        type:'get',
        url:path+"/funGroupDistribution/getFunGroup",
        dataType:'json',
        success:function(data){
            $("#searchTypeId").empty();
            $("#typeId").empty();
            if(data != null){
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="'+data[i].code+'">'+data[i].name+'</option>';
                }
                $("#searchTypeFlag").append(html);
                $("#typeFlag").append(html);
            }
        }
    })
}
//加载表格
var pageNumber;
$('#mytab').bootstrapTable({
    toolbar: '#toolbar',                //工具按钮用哪个容器
    striped: true,                      //是否显示行间隔色
    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    pagination: true,                   //是否显示分页（*）
    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
    paginationPreText : '上一页',
    paginationNextText : '下一页',
    pageNumber: 1,                       //初始化加载第一页，默认第一页
    pageSize: 10,                       //每页的记录行数（*）
    pageList: [5,10,15,20,30,50],//可供选择的每页的行数（*）
    height: window.innerHeight-155,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
    columns:[
        {
            title:'全选',
            field:'select',
            checkbox:true,
            width:25,
            align:'center',
            valign:'middle'
        },
        {
            field: 'no',
            title: '序号',
            sortable: true,
            formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize=$('#mytab').bootstrapTable('getOptions').pageSize;
                //获取当前是第几页
                var pageNumber=$('#mytab').bootstrapTable('getOptions').pageNumber;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        },
        {
            title:'功能组别',
            field:'typeFlag',
        },
        {
            title:'已分配',
            field:'userName',
        },
        {
            title:'备注',
            field:'remark',
        },
        {
            title:'有效日期',
            field:'effectiveTime',
        },
        {
            title:'创建人',
            field:'creater',
        },
        {
            title:'创建时间',
            field:'createDate',
        },
        {
            title:'修改人',
            field:'updater',
        },
        {
            title:'修改时间',
            field:'updateDate',
    },
        {
            title:'操作',
            formatter: function(value,row,index){
                var editanddrop = "";
                var updateOper = row.updateOper;
                var deleteOper = row.deleteOper;
                if(updateOper == 1){
                    editanddrop += '<button type="button" onclick="updateDistribution('+row.id+')" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#myModal2">编辑</button>'
                }
                if(deleteOper == 1){
                    editanddrop += '&nbsp&nbsp&nbsp<button type="button" onclick="deleteById('+row.id+')" class="btn btn-sm  btn-danger">删除</button>';
                }
                return editanddrop;
            }
        }
    ],
    locale:'zh-CN',//中文支持,
    url:path+'/funGroupDistribution/getFunGroupDistributionList',//排序方式
    queryParams: function (params) {
        return{
            limit : params.limit, // 每页显示数量
            offset : params.offset, // SQL语句起始索引
            page : (params.offset / params.limit) + 1, //当前页码,
            startTime:$("#startTime1").val(),
            endTime:$("#endTime1").val(),
            typeFlag:$("#searchTypeFlag").val(),
            userName:$("#searchUserName").val(),
            effective:$("#searchEffective").val()
        }
    },
    responseHandler:function(res){
        //在ajax获取到数据，渲染表格之前，修改数据源
        var nres = [];
        nres.push({total:res.total,rows:res.list});
        return nres[0];
    },
    onLoadSuccess:function(){
        $(".page-list").show();
        $(".fixed-table-body").css("overflow","auto");
    },
    //监听分页点击事件
    onPageChange: function(num, type) {
        pageNumber = num;
    },
    //选中单个复选框
    onCheck:function(row){
        var checks = $("#checks").val();
        $("#checks").val(checks+="'"+row.id + "',");
    },
    //取消单个复选框
    onUncheck:function(row){
        var checks = $("#checks").val();
        checks = checks.replace("'"+row.id + "',","");
        $("#checks").val(checks);
    },
    //全选
    onCheckAll:function(rows){
        $("#checks").val("");
        var checks = '';
        for(var i=0;i<rows.length;i++)
        {
            checks += "'"+rows[i].id + "',"
        }
        $("#checks").val(checks);
    },
    //全不选
    onUncheckAll: function (rows) {
        $("#checks").val("");
    }
})
//查询按钮
function refreshTable(){
    $("#checks").val("");
    $('#mytab').bootstrapTable('refresh',{
        url : path+'/funGroupDistribution/getFunGroupDistributionList'
    })
}

//编辑分配
function updateDistribution(id){
    $("#insert").hide();
    $("#update").show();
    $.ajax({
        type:'get',
        url:path+'/funGroupDistribution/getDistributionById',
        data:{id:id},
        dataType:'json',
        success:function(data){
            if(null != data){
                $("#id").val(data.id);
                $("#typeFlag").val(data.typeFlag);
                $("#userName").val(data.userName);
                $("#effective").val(data.effective);
                $("#effectiveTime").val(data.effectiveTime);
                $("#remark").val(data.remark);
            }
        }
    })
}
//删除分配
function deleteById(id){
    Common.confirm({
        title: "提示",
        message: "请确认是否删除这条数据?",
        operate: function (reselt) {
            if (reselt) {
                $.ajax({
                    type: 'post',
                    url: path + '/funGroupDistribution/deleteById/' + id,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 100) {
                            toastr.success("删除成功!");
                            refreshTable();
                            $('#mytab').bootstrapTable('selectPage', pageNumber);
                        } else {
                            toastr.warning(data.msg);
                        }
                    }
                })
            }
        }
    })
}
//批量删除
function deleteByIds(){
    var ids = $("#checks").val();
    if(ids != ''){
        var idStr = ids.split(",");
        Common.confirm({
            title: "提示",
            message: '确定删除选中的'+ (idStr.length-1)+ '条数据吗?',
            operate: function (reselt) {
                if (reselt) {
                    $.ajax({
                        type: 'post',
                        url: path + '/funGroupDistribution/deleteByIds/' + ids,
                        dataType: 'json',
                        success: function (data) {
                            if (data.code == 100) {
                                toastr.success("删除成功!");
                                $("#checks").val("");
                                refreshTable();
                                $('#mytab').bootstrapTable('selectPage', pageNumber);
                            } else {
                                toastr.warning(data.msg);
                            }
                        }
                    })
                }
            }
        })
    }else{
        toastr.warning("请至少选中一个!");
    }
}
//导出excel功能
function exportExcel(){
    var checks = $("#checks").val();
    if(checks != '') {
        checks = checks.substring(0, checks.length - 1);
        var url = path+"/funGroupDistribution/exportExcel?checks="+checks;
        window.location.href = url;
    }else{
        Common.confirm({
            title: "提示",
            message: "没有选中，您确定要按搜索栏条件导出?",
            operate: function (reselt) {
                if (reselt) {
                    var url = path+"/funGroupDistribution/exportExcel?startTime="+$("#startTime1").val()+"&endTime="+$("#endTime1").val()+"&typeFlag="
                        +$("#searchTypeFlag").val()+"&userName="+$("#searchUserName").val()+"&effective="+$("#searchEffective").val();
                    window.location.href = url;
                }
            }
        })
    }
}

/*//监听关闭模态框刷新事件
$('#myModal1').on('hide.bs.modal', function () {
    window.location.reload();
});*/
/*********************************************添加功能****************************************************/
//添加分配
function addDistribution(){
    loadTree();
    $("#id").val("");
    $("#userIds").val("");
    form2.reset();
    $("#insert").show();
    $("#update").hide();
}
//监听添加选择类别变更事件
$("#typeFlag").change(function () {
    if($("#id").val() == ''){
        loadTree();
        $("#userIds").val("");
        $("#txtTreeSelect1").val("");
    }
})
//保存分配
function saveDistribution(){
    var typeFlag = $("#typeFlag").val();
    var userIds = $("#userIds").val();
    var effectiveTime = $("#effectiveTime").val();
    if(typeFlag != '' && typeFlag != null){
        var id = $("#id").val();
        if(id == ''){
            if(userIds != '' && userIds != null){
                if(effectiveTime != '' && effectiveTime != null){
                    $.ajax({
                        type:'post',
                        url:path+"/funGroupDistribution/addFunGroupDistribution",
                        data:$("#form2").serialize(),
                        dataType:'json',
                        success:function(data){
                            if(data.code == 100){
                                toastr.success("添加成功!");
                                $('#myModal2').modal('hide');
                                refreshTable();
                            }else{
                                toastr.warning(data.msg);
                            }
                        }
                    })
                }else{
                    toastr.warning("有效日期不能为空");
                    $("#effectiveTime").focus();
                }
            }else{
                toastr.warning("分配用户不能为空");
                $("#txtTreeSelect1").focus();
            }
        }else{
            //保存
            $.ajax({
                type:'post',
                url:path+"/funGroupDistribution/updateFunGroupDistribution",
                data:$("#form2").serialize(),
                dataType:'json',
                success:function(data){
                    if(data.code == 100){
                        toastr.success("保存成功!");
                        $('#myModal2').modal('hide');
                        refreshTable();
                        $('#mytab').bootstrapTable('selectPage', pageNumber);
                    }else{
                        toastr.warning(data.msg);
                    }
                }
            })
        }
    }else{
        toastr.warning("保存失败,类别不能为空");
    }
}

/****************************点击查询用户树*********************************/
//多选树形
function showMenu1() {
    var contentHeight = $("#modal-body").height();
    var treeHeight = $("#treeDemo").height();
    $("#modal-body").css("height",contentHeight+treeHeight+20);
    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() {
    $("#modal-body").css("height",295);
    $("#menuContent1").fadeOut("name");
    $("body").unbind("mousedown", onBodyDown1);
}

/**树操作*/
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 userIds = '';
    var userNames = '';
    //父节点必须一样
    for (var i = 0; i < nodes.length; i++) {
        if(nodes[i].level == 1){
            var userId = nodes[i].selfId;
            userIds += userId + ",";
            userNames += nodes[i].name + ",";
        }
    }
    if(userIds != ''){
        userIds = userIds.substring(0,userIds.length-1);
        userNames = userNames.substring(0,userNames.length-1);
    }
    $("#txtTreeSelect1").val(userNames);
    $("#userIds").val(userIds);
}
var zNodes = [];
function loadTree() {
    var typeFlag = $("#typeFlag").val();
    $.ajax({
        type: "GET",
        url: path + "/funGroupDistribution/getUsetTree",
        data:{typeFlag:typeFlag},
        dataType: "json",
        async: false,
        success: function (data) {
            $.fn.zTree.init($("#treeDemo"), setting, data);
            zTree = $.fn.zTree.getZTreeObj("treeDemo");
            var nodes = zTree.getNodes();
            zTree.expandNode(nodes[0], true);
        }
    });
}
//选中节点 selfId
function treeSelectNode(selfId){
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    var node = zTree.getNodeByParam("selfId",selfId);
    if(node != null){
        zTree.checkNode(node, true, true);
    }
}