var tree;
var node;
var table = $("#table1");
$(document).ready(function () {
    bindtree();
    initTable(-1);
    $(".add").click(function () {
        $(".parent").hide();
        $(".addModel").css('display', 'block');
        $('.btl').text('添加菜单信息')
        $('.name').val('');
        $('.code').val('');
        $('.sort').val('');
        $('.url').val('');
        $('.img').val('');
        $('.remark').val('');
        $("input[name='state'][value='1']").prop("checked", "checked");
        $(".pid").val(-1);
    })
    $(".addcd").click(function () {
        var nodes = tree.getSelectedNodes();
        if (nodes.length != 1) {
            layer.confirm('请选择一条记录！', {
                btn: ['确定']
            });
            return;
        }
        else {
            node=nodes[0];
            if (node.level == 1) {
                layer.confirm('不能新增菜单！', {
                    btn: ['确定']
                });
                return;
            }
            else {
            	$('.btl').text('添加菜单信息')
                $(".parent").show();
                $('.addModel').css('display', 'block');
                $("input[type='text']").val("");
                $("input[type='hidden']").val("");
                $(".pid").val(node.F_FunctionId);
                $(".pname").val(node.F_FunctionName);
            }
        }
    })

    $(".change").click(function () {
    	$('.btl').text('修改菜单信息')
        $(".parent").hide();
        $("input[type='text']").val("");
        $("input[type='hidden']").val("");
        var nodes = tree.getSelectedNodes();
        if (nodes.length != 1) {
            layer.confirm('请选择一条记录！', {
                btn: ['确定']
            });
            return;
        }
        else {
            node = nodes[0];
            $(".id").val(node.F_FunctionId);
            $(".pid").val(-1);
            if (node.level == 1) {
                var pnode=node.getParentNode();
                $(".pid").val(pnode.F_FunctionId);
                $(".pname").val(pnode.F_FunctionName);
                $(".parent").show();
            }
            $.getJSON(huayi.config.callcenter_url + "Function/GetFunction", { id: node.F_FunctionId, "token": $.cookie("token"), }, function (result) {
                if (result.state.toLowerCase() == "success") {
                    $(".id").val(result.data.F_FunctionId);
                    $(".name").val(result.data.F_FunctionName);
                    $(".code").val(result.data.F_FunctionCode);
                    $(".sort").val(result.data.F_Sort);
                    $(".url").val(result.data.F_OptUrl);
                    $(".img").val(result.data.F_ImgUrl);
                    $(".remark").val(result.data.F_Remark);
                    $('input[name="state"]').removeAttr("checked");
                    $("input[name='state'][value='" + result.data.F_State + "']").prop("checked", "checked");
                    $(".addModel").show();
                }
            });
        }
    })
    $(".save").click(function () {
        $.post(huayi.config.callcenter_url + "Function/AddFunction", {
            pid: $(".pid").val(), id: $(".id").val(), name: $(".name").val(), sort: $(".sort").val(), url: $(".url").val(),remark: $(".remark").val(),
            img: $(".img").val(), code: $(".code").val(), state: $('input[name="state"]:checked').val(), "token": $.cookie("token")
        }, function (result) {
            result = JSON.parse(result);
            if (result.state.toLowerCase() == "success") {
                layer.msg(result.message);
                location=location
                $('.addModel').css('display', 'none');
                bindtree();
            }
        })
    })
    $(".del").click(function () {
        var nodes = tree.getSelectedNodes();
        if (nodes.length != 1) {
            layer.confirm('请选择一条记录！', {
                btn: ['确定']
            });
            return;
        }
        else {
            node = nodes[0];
            $('.delModel').css('display', 'block');
            $('.delName').html(node.F_FunctionName);
        }
    })

    //关闭按钮
    $('.addBtr').click(function () {
        $('.addModel').css('display', 'none');
    })
    //关闭按钮
    $('.delBtr').click(function () {
        $('.delModel').css('display', 'none');
    })
    //取消按钮
    $('.return').click(function () {
        $('.delModel').css('display', 'none');
    })
    //确定删除按钮
    $('.sure').click(function () {

        var ids = []; ids.push(node.F_FunctionId);
        $.post(huayi.config.callcenter_url + "Function/DelFunction", { ids: ids, "token": $.cookie("token") }, function (result) {
            result = JSON.parse(result);
            if (result.state.toLowerCase() == "success") {
                layer.msg(result.message);
                $('.delModel').css('display', 'none');
                bindtree();
            }
        })
    })
})

///树形图构建
function bindtree() {
    $.getJSON(huayi.config.callcenter_url + "Function/GetAllList", { "token": $.cookie("token"), }, function (result) {
        if (result.state.toLowerCase() == "success") {
            tree=$.fn.zTree.init($("#treeDemo"), setting1, result.data); //实例化树形图
        }
    });
}

var setting1 = {
	data: {
		key: {
			name: "F_FunctionName"
		},
		simpleData: {
			enable: true,
			idKey: "F_FunctionId",
			pIdKey: "F_ParentId",
			rootPId: -1
		}
	},
	callback: {
		onClick: zTreeOnClick
	}
};

function zTreeOnClick(event, treeId, treeNode) {
	initTable(treeNode.F_FunctionId);
};

//右边表格
function initTable(id) {
	//先销毁表格
	table.bootstrapTable('destroy');
	//初始化表格,动态从服务器加载数据
	table.bootstrapTable({
		method: "get", //使用get请求到服务器获取数据
		url: huayi.config.callcenter_url + "Function/GetList", //获取数据的Servlet地址
		contentType: "application/x-www-form-urlencoded",striped: true, //表格显示条纹
		pagination: true, //启动分页
		pageSize: 10, //每页显示的记录数
		pageNumber: 1, //当前第几页
		pageList: [10, 20, 50, 100], //记录数可选列表
		search: false, //是否启用查询
		showColumns: false, //显示下拉框勾选要显示的列
		showRefresh: false, //显示刷新按钮
		sidePagination: "server", //表示服务端请求
		//设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
		//设置为limit可以获取limit, offset, search, sort, order
		queryParamsType: "undefined",
		queryParams: function queryParams(params) { //设置查询参数
			var param = {
			    page: params.pageNumber,
				pagesize: params.pageSize,
				token: $.cookie("token"),
				pid: id,
			};
			return param;
		},
		onLoadSuccess: function(data) { //加载成功时执行
			//layer.msg("加载成功");
		},
		onLoadError: function() { //加载失败时执行
			//layer.msg("加载数据失败", { time: 1500, icon: 2 });
		}
	});
}
//编号
function setCode(val, row, index) {
    //return index + 1;
    var page = table.bootstrapTable("getPageCode");
    return page.pageSize * (page.pageNumber - 1) + index + 1;
}
//状态{
function States(val) {
    var str = '';
    switch (val + '') {
        case '0': str = "未启用"; break;
        case '1': str = "启用"; break;
    }
    return str;
}
 //跳转
      	document.onkeydown = function(e) {
					var theEvent = window.event || e;
					var code = theEvent.keyCode || theEvent.which;
					if(code == 13) {
						$('#table1').bootstrapTable('selectPage', $(".JumpPage").val());
						
					}
				}

