var token = $.cookie("token");
var zNodes = [];
var id; //当前节点id
var pid; //当前父节点ID
var name; //选择的name
var pidName; //父节点name
var keyWord = $('.searCon').val(); //关键字
var xlName;//添加下拉框节点name
var table = $('#table1');//右边表格
//搜索按钮
$('.searchGo').click(function(){
	keyWord = $('.searCon').val();
	if (keyWord) {
	    initTable(token, id, keyWord);
	} else {
	    layer.msg("请输入搜索内容！");
	}
})
tree();
function tree() {

    $.get(huayi.config.callcenter_url + 'KnowledgeClass/GetList', {
        "token": $.cookie("token"),
        "pid": pid
    }, function (result) {
        result = $.parseJSON(result);
        $.fn.zTree.init($("#treeDemo"), setting1, result.data); //实例化树形图
    });
}

var setting1 = {
	data: {
		key: {
			name: "text"
		},
		simpleData: {
			enable: true,
			idKey: "id",
			rootPId: 0
		}
	},
	callback: {
		onClick: zTreeOnClick
	}
};

function zTreeOnClick(event, treeId, treeNode) {
	id = treeNode.id;
	name = treeNode.text;
	var pidnode = treeNode.getParentNode();
	if(pidnode) {
		pidName = pidnode.text;
		pid = pidnode.id;
		//console.log(pid);
	} else {
		pidName = "顶级分类";
		pid == 0;
		//console.log(pid);
	}
	keyWord = $('.searCon').val(); 
	initTable(token,id,keyWord);
};
var setting2 = {
	data: {
		key: {
			name: "text"
		},
		simpleData: {
			enable: true,
			idKey: "id",
			rootPId: 0
		}
	},
	callback: {
		onClick: addTreeClick
	}
};
	
function addTreeClick(event, treeId, treeNode) {
			addPid=treeNode.id;
			//console.log(addPid);
			xlName = treeNode.text;
			$('.inps1').val(xlName);
};
//编辑器配置
KindEditor.ready(function (K) {
    window.editor = K.create('#addEditor', {
        uploadJson: '../../js/kindeditor/asp.net/upload_json.ashx',
        fileManagerJson: '../../js/kindeditor/asp.net/file_manager_json.ashx',
        allowFileManager: true
    });//添加弹出框编辑器
    window.changeEditor = K.create('#changeEditor', {
        uploadJson: '../../js/kindeditor/asp.net/upload_json.ashx',
        fileManagerJson: '../../js/kindeditor/asp.net/file_manager_json.ashx',
        allowFileManager: true
    });//修改弹出框编辑器
});
        
function getTree(){
$.get(huayi.config.callcenter_url+'KnowledgeClass/GetList', {
	"token": $.cookie("token"),
	"pid":pid
}, function(result) {
	result = $.parseJSON(result);
	$.fn.zTree.init($("#addTreeDemo"), setting2, result.data); //实例化树形图
});
	 
}
//===============添加功能开始=============================

//添加按钮
$('.add').click(function() {
	$('.addModel').css('display', 'block');
	if (name && id) {
        $('.inps1').val(name);	
        addPid=id;
	}else{
		$('.inps1').val("顶级分类"); 	
		addPid=0
		//console.log(addPid);
	}
	getTree();
})
$('.addBtr').click(function() {
	$('.addModel').css('display', 'none');
})
//添加内容下拉
$('.inps1').focus(function() {
	$('.xlAdd').css('display', 'block');
		
})
$('.xl_one').click(function() {
	if($('.xlAdd').css('display') == 'block') {
		$('.xlAdd').css('display', 'none')
	} else {
		$('.xlAdd').css('display', 'block')
	}
})
$('.addTree').mouseleave(function() {
	$(this).css('display', 'none')
})
//保存添加按钮
var addPid,addTitle,addKey,addCon,addDes;
$('.addCun').click(function () {

	if ($('.inps1').val() == "" || $('.addTitle').val() == "") {
	    layer.confirm('所添加内容不允许为空！', {
	        btn: ['确定']
	    });
	    return;
	} else {
	    addTitle = $('.addTitle').val();
	    addKey = $('.addKey').val();
	    addCon = encodeURIComponent(editor.html());
	    //console.log(addCon);
	    $('.addModel').css('display', 'none');
	    addCunTree(addPid, addTitle, addKey, addCon);
	}
});
	
function addCunTree(addPid, addTitle, addKey, addCon) {
    $.ajax({
        type: "post",
        url: huayi.config.callcenter_url + "Knowledge/AddInfo",
        dataType: 'json',
        async: true,
        data: {
            title: addTitle,
            KeyWords: addKey,
            con: addCon,
            pid: addPid,
            issub:1,
            key: $("#PID").val(),
            token: token
        },
        success: function (data) {
            console.log(data)
            console.log(data.state);
            if (data.state == "success") {
                layer.msg("添加成功！");
                clean()
                initTable(token, id, keyWord);
            }
        }

    });
}
//***********************添加功能结束=============================
	
	
//=======================修改功能开始==============================
var chanId,//修改弹出框内 下拉框当前节点ID
	changeName,//修改弹出框内 下拉框当前节点name
	changeGetid,
	chanCunId;

$('.change').click(function () {
    var changes = $.map($('#table1').bootstrapTable('getSelections'), function (row) {
        return row.F_RepositoryId;
    });
    if (changes.length <= 0 || changes.length > 1) {
        layer.confirm('请选择一行修改！', {
            btn: ['确定']
        });
        return;
    } else {
        $('.changeModel').css('display', 'block');
    }
    changeGetid = changes.toString();
    getChangeTree();
    getChangeBox(changeGetid);
});
$('.changeBtr').click(function(){
		$('.changeModel').css('display', 'none');
})
$('.inps4').focus(function() {
	$('.xlChange').css('display', 'block')
})
//下拉按钮功能
$('.xl_two').click(function () {
    if ($('.xlChange').css('display') == 'block') {
        $('.xlChange').css('display', 'none')
    } else {
        $('.xlChange').css('display', 'block')
    }

});
	
	//修改弹出框内 下拉树形图参数配置项
var setting3 = {
    data: {
        key: {
            name: "text"
        },
        simpleData: {
            enable: true,
            idKey: "id",
            rootPId: 0
        }
    },
    callback: {
        onClick: changeTreeClick
    }
}

function changeTreeClick(event, treeId, treeNode) {
	chanId = treeNode.id;
	changeName = treeNode.text;
	$('.inps4').val(changeName);
	chanCunId=chanId;
};
function getChangeTree() {
    $.get(huayi.config.callcenter_url + 'KnowledgeClass/GetList', {
        "token": $.cookie("token"),
        "pid": pid
    }, function (result) {
        result = $.parseJSON(result);
        $.fn.zTree.init($("#changeTreeDemo"), setting3, result.data); //实例化树形图
    });

}
var cunId;
function getChangeBox(changeGetid) {
    $.ajax({
        type: "post",
        url: huayi.config.callcenter_url + "Knowledge/GetInfo",
        async: true,
        dataType: 'json',
        data: {
            infoid: changeGetid,
            token: token
        },
        success: function (data) {
            var con = data.data;
            $('.inps4').val(con.F_Category);
            $('.changeTitle').val(con.F_Title);
            $('.changeKey').val(con.F_KeyWords);
            changeEditor.html(con.F_Content);
            cunId = con.F_CategoryId;
            chanCunId = cunId;
            $("#changereflectCategory").val(con.KeyName);
            $("#PID2").val(con.F_Key);
        }
    });
}
function changeBaoCunAjax(changeGetid, chanCunId) {
    $.ajax({
        type: "post",
        url: huayi.config.callcenter_url + "Knowledge/EditInfo",
        async: true,
        dataType: 'json',
        data: {
            infoid: changeGetid,
            title: $('.changeTitle').val(),
            KeyWords: $('.changeKey').val(),
            issub:1,
            con: decodeURIComponent(changeEditor.html()),
            pid: chanCunId,
            key: $("#PID2").val(),
            token: token
        },
        success: function (data) {
            if (data.state == "success") {
                layer.msg("修改成功!");
                initTable(token, id, keyWord);
            }
        }
    });
}
$('.changeCun').click(function () {
    changeBaoCunAjax(changeGetid, chanCunId);
    $('.changeModel').css('display', 'none');

});
	
	
//***********************修改功能结束=============================
//=======================删除功能开始==============================
var F_RepositoryId;
$('.del').click(function() {
    var ids = $.map( $('#table1').bootstrapTable('getSelections'), function(row) {
        return row.F_RepositoryId;
    });
    if(ids.length <= 0) {
        layer.confirm('请选择一行删除！', {
            btn: ['确定']
        });
        return;
    }else{
        $('.delModel').css('display', 'block');
    }
    console.log(ids);
    F_RepositoryId=ids;
})
//关闭按钮
$('.delBtr').click(function() {
	$('.delModel').css('display', 'none');
})
//确定删除按钮
$('.sure').click(function() {
	$.ajax({
		type: "post",
		url: huayi.config.callcenter_url+"Knowledge/DelInfos",
		async: true,
		dataType:'json',
		data: {
			ids: F_RepositoryId,
			token:token
		},
		success: function(data) {
            if(data.state == "success"){
            layer.msg("删除成功!");
        initTable(token,id,keyWord);
            }
		}
	});
	$('.delModel').css('display', 'none');

})
	//取消删除按钮
$('.return').click(function() {
	$('.delModel').css('display', 'none');
})

	
//***********************删除功能结束==============================
initTable(token,id,keyWord);
function initTable(token,id,keyWord) {
	//先销毁表格
	table.bootstrapTable('destroy');
	//初始化表格,动态从服务器加载数据
	table.bootstrapTable({
		method: "get", //使用get请求到服务器获取数据
		url: huayi.config.callcenter_url+"Knowledge/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: token,
				ispass:1,
				pid: id,
				keywords: keyWord
			};
			return param;
		},
		onLoadSuccess: function() { //加载成功时执行
			//layer.msg("加载成功");
		},
		onLoadError: function() { //加载失败时执行
			//layer.msg("加载数据失败", { time: 1500, icon: 2 });
		}
	});
}
//function oper(val,row) {
//    return '<div class="content">'+row.F_Content +'</div>'
//}
function setCode(val, row, index) {
	return index + 1;
}
function oper(str) {
    if (str) {
        var con = helper.filter.Transcoding(str);
        return con = con.substr(0, 10) + "...";
    }
    else {
        return '';
    }
}
//清空知识库内容
function clean(){
	$('.inps1').val("")
	$('.addKey').val("")
	$(".addTitle").val("")
	$("#reflectCategory").val("")
	$("#addEditor").val("")
	name = ""
}
