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();
	//console.log(keyWord);
	//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'); //添加弹出框编辑器
	window.changeEditor = K.create('#changeEditor'); //修改弹出框编辑器
});

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');
	//		console.log(pidName);
	if(name) {
		$('.inps1').val(name);
		addPid = id;
	} else {
		$('.inps1').val("顶级分类");
		addPid = 0
		//console.log(addPid);
	}
	getTree();
})
$('.addBtr').click(function() {
	$('.addModel').css('display', 'none');
	$('.addTitle').val('');
	$('.addKey').val('');
	editor.html('');
})
//添加内容下拉
$('.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() {
	console.log(addPid);
	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,
			key: addKey,
			con: addCon,
			pid: addPid,
			token: token
		},
		success: function(data) {
			console.log(data)
			console.log(data.state);
			if(data.state == "success") {
				layer.msg("添加成功！");
				//				tree();
				getTree()
				initTable(token, id, keyWord);
			}
		}

	});

}
//***********************添加功能结束=============================

//=======================修改功能开始==============================
var chanId, //修改弹出框内 下拉框当前节点ID
	changeName, //修改弹出框内 下拉框当前节点name
	changeGetid,
	chanCunId;
//		JSON.stringify($table.bootstrapTable('getSelections'));
$('.change').click(function() {
	var changes = $.map($('#table1').bootstrapTable('getSelections'), function(row) {
		return row.F_RepositoryId;
	});
	if(changes.length <= 0) {
		layer.confirm('请选择一行修改！', {
			btn: ['确定']
		});
		return;
	} else {
		$('.changeModel').css('display', 'block');
	}
	changeGetid = changes;
	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_Expand1);
			$('.changeTitle').val(con.F_Title);
			$('.changeKey').val(con.F_KeyWords);
			changeEditor.html(con.F_Content);
			cunId = con.F_CategoryId;
			chanCunId = cunId;
		}
	});

}

function changeBaoCunAjax(changeGetid, chanCunId) {
	$.ajax({
		type: "post",
		url: huayi.config.callcenter_url + "Knowledge/EditInfo",
		async: true,
		dataType: 'json',
		data: {
			infoid: changeGetid,
			title: $('.changeTitle').val(),
			key: $('.changeKey').val(),
			con: encodeURIComponent(changeEditor.html()),
			pid: chanCunId,
			token: token
		},
		success: function(data) {
			if(data.state == "success") {
				layer.msg("修改成功!");
				initTable(token, id, keyWord);
			}
		}
	});

}
$('.changeCun').click(function() {
	console.log(chanCunId)
	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, 15, 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,
				pid: id,
				keywords: keyWord
			};
			return param;
		},
		onLoadSuccess: function() { //加载成功时执行
			//layer.msg("加载成功");
		},
		onLoadError: function() { //加载失败时执行
			//layer.msg("加载数据失败", { time: 1500, icon: 2 });
		}
	});
}

function formatterTitle(val, row){
	if(val.length > 15){
		val = val.substring(0,15) + "...";
	}
	return '<div onclick="btn_detail('+ row.F_RepositoryId +')" class="content">' + val + '</div>'
}

function oper(val, row) {
	if(val.length > 20){
		val = val.substring(0,20) + "...";
	}
	return '<div onclick="btn_detail('+ row.F_RepositoryId +')" class="content">' + val + '</div>'
}

function formatterKey(val, row) {
	if(val.length > 10){
		val = val.substring(0,10) + "...";
	}
	return val; 
}

function setCode(val, row, index) {
	var page = table.bootstrapTable("getPageCode");
	return page.pageSize * (page.pageNumber - 1) + index + 1;
}

//点击标题 内容查看详情
function btn_detail(seeid) {
	layer.open({
		type: 2,
		title: '查看知识库',
		shadeClose: true, //是否开启点击遮罩关闭
		shade: 0.4, //遮罩
		maxmin: true, //开启最大化最小化按钮
		id: 'LAY_layuipro', //防止重复弹出
		moveType: 1, //拖拽类型 默认的拖拽风格正如你所见到的，会有个过度的透明框。但是如果你不喜欢，你可以设定moveType: 1切换到传统的拖拽模式
		moveOut: true, //拖拽到窗口外
		//resize: true,//是否允许拉伸
		area: ['70%', '50%'],
		content: 'addModel.html?changeGetid=' + seeid + ''
	});
}