//初始化时间控件
initDateInput(1);
var setting = {
	view:{
			fontCss : {"font-family": "微软雅黑","color":"blue"}
		},
	data:{
		simpleData:{
		enable:true,
		idKey:"id",
		pIdKey:"parentId",
	}
	},
	callback: {
		onClick: zTreeOnClick
	}
};
//左键点击事件
function zTreeOnClick(event, treeId, treeNode) {
	var id = treeNode.id;
	$("#currentTreeId").val(id);
	if(id != 0){
		//非根节点
		$("#form1").show();
		$("#noticeId").val(treeNode.id);
		$("#noticeTypeFlag").val(treeNode.sysType);
		$("#noticeTypeName").val(treeNode.newName);
		$("#addBtn").hide();
	}else{
		$("#addBtn").show();
		$("#form1").hide();
	}
}
var zNodes;
function loadTree(){
	$.ajax({
		type: "get",
		url: path+"/notice/getNoticeTypeTree",
		dataType:'json',
		success:function(data){
			if(data != ''){
				$.fn.zTree.init ($("#treeDemo"), setting, data);
				zTree = $.fn.zTree.getZTreeObj("treeDemo");
				rMenu = $("#rMenu");
				var nodes = zTree.getNodes();
				for (var i = 0; i < nodes.length; i++) { //设置节点展开
					zTree.expandNode(nodes[i], true, false, true);
				}
				zNodes = data;
			}else{
				$("#parentId").val(0);
			}
		}
	})
}
$(document).ready(function(){
	loadTree();
	fuzzySearch('treeDemo','#key',null,true,setting,zNodes);
});
//添加通知类别
function addNoticeType(){
	$("#form1")[0].reset();
	$("#noticeId").val("");
	$("#form1").show();
}
//验证类别标志不能重复
$("#noticeTypeFlag").blur(function () {
	var noticeId = $("#noticeId").val();
	var noticeTypeFlag = $("#noticeTypeFlag").val();
	if(noticeId == '' && noticeTypeFlag != ''){
		$.ajax({
			type:'get',
			url:path+'/notice/checkTypeSysFlagOrTypeSysName',
			data:{noticeTypeFlag:noticeTypeFlag},
			dataType:'json',
			success:function(data){
				if(data.code == 200){
					toastr.warning("类别标志已存在!");
					$("#noticeTypeFlag").val("");
					$("#noticeTypeFlag").focus();
				}
			},
			error:function(data){
				toastr.error(data.msg);
			}
		})
	}
})
//验证类别名称不能重复
$("#noticeTypeName").blur(function () {
	var noticeId = $("#noticeId").val();
	var noticeTypeName = $("#noticeTypeName").val();
	if(noticeId == '' && noticeTypeName != ''){
		$.ajax({
			type:'get',
			url:path+'/notice/checkTypeSysFlagOrTypeSysName',
			data:{noticeTypeName:noticeTypeName},
			dataType:'json',
			success:function(data){
				if(data.code == 200){
					toastr.warning("类别名称已存在!");
					$("#noticeTypeName").val("");
					$("#noticeTypeName").focus();
				}
			},
			error:function(data){
				toastr.error(data.msg);
			}
		})
	}
})
//保存类别
$("#btn_submit").click(function(){
	var noticeTypeFlag = $("#noticeTypeFlag").val();
	var noticeTypeName = $("#noticeTypeName").val();
	if(noticeTypeFlag == ''){
		toastr.warning("类别标志不能为空!");
	}else{
		if(noticeTypeName == ''){
			toastr.warning("类别名称不能为空!");
		}else{
			updateType();
		}
	}
})
//保存类别的方法
function updateType(){
	var noticeId = $("#noticeId").val();
	$.ajax({
		type:'post',
		url:path+'/notice/update',
		data:$("#form1").serialize(),
		dataType:'json',
		success:function(data){
			if(data.code == 100){
				toastr.success("保存成功!");
				if(noticeId == ''){
					$("#form1")[0].reset();
				}
				loadTree();
				setTimeout(function(){
					var currentTreeId = $("#currentTreeId").val();
					var node = zTree.getNodeByParam("id",currentTreeId);
					zTree.selectNode(node);
				},500)
			}else{
				toastr.warning(data.msg);
			}
		},
		error:function(data){
			toastr.error(data.msg);
		}
	})
}
//删除类别
function delNoticeType(){
	Common.confirm({
		title: "提示",
		message: "确定是否删除此条记录?",
		operate: function (reselt) {
			if (reselt) {
				var noticeId = $("#noticeId").val();
				$.ajax({
					type:'post',
					url:path+'/notice/delete',
					data:{noticeId:noticeId},
					dataType:'json',
					success:function (data) {
						if(data.code == 100){
							toastr.success("删除成功!");
							loadTree();
							$("#form1").hide();
						}else{
							toastr.error("删除失败,请联系系统管理员!");
						}
					}
				})
			}
		}
	})
}
/******************************************通知操作*********************************************************/
//增加通知按钮
function addNotice(){
    $("#noticeReceive").empty();
    $("#noticeId1").val("");
    $("#form2")[0].reset();
    $("#readFlag").val("");
}
//系统类别ID级联对应的系统的用户
$("#parentId").change(function(){
	$("#noticeReceive").empty();
	var noticeTypeId = $("#parentId").val();
	if(noticeTypeId != null && noticeTypeId != ''){
		$.ajax({
			type:'get',
			url:path+'/notice/getUserNameListByNoticeTypeId',
			data:{noticeTypeId:noticeTypeId},
			dataType:'json',
			success:function(data){
				if(data.code == 100){
					var html = '<option value="all">该通知类型所有人</option>';
					if(data.extend != ''){
						var userName = $("#userName").val();
						for (var i = 0; i < data.extend.userList.length; i++) {
							if (userName != data.extend.userList[i].userName) {
								html += '<option value="' + data.extend.userList[i].userId + '">' + data.extend.userList[i].userName + '</option>';
							}
						}
					}
					$("#noticeReceive").append(html);
				}
			}
		})
	}
})
//保存通知
$("#notice_submit").click(function(){
	var noticeTitle = $("#noticeTitle").val();
	var parentId = $("#parentId").val();
	var noticeContent = $("#noticeContent").val();
	if(noticeTitle == ''){
		toastr.warning("通知主题不能为空!");
	}else{
		if(parentId == ''){
			toastr.warning("通知类型不能为空!");
		}else{
			if(noticeContent == ''){
				toastr.warning("通知内容不能为空!");
			}else{
				updateNotice();
			}
		}
	}
})
function updateNotice(){
	$.ajax({
		type:'post',
		url:path+'/notice/update',
		data:$("#form2").serialize(),
		dataType:'json',
		success:function(data){
			if(data.code == 100){
				toastr.success("保存成功!");
				setTimeout(function () {
					window.location.reload();
				},500)
			}
		}
	})
}
function clearForm(){
	$("#form2")[0].reset();
	$("#noticeReceive").empty();
}

$(function () {
	$(".modal-dialog").draggable();//为模态对话框添加拖拽
})
/*
        通过指定的方法来自定义栏数据
    */
function customCheckBox(row, col){
	return "<input type='checkbox' name='city_name' onclick='selCk(this)'  id='"+row.noticeId+"'>";
}
//表格设置
/*var config = {
	id: "moduleListTable",   //表格ID
	idField : 'noticeId',
	treeField : 'noticeTypeName',
	parentField : 'parentId',
	pagination : true,
	pageSize : 15,
	width: "800",    //最小宽度
	renderTo: "div1",  //指定表格生成的父容器ID
	headerHeight: "30",
	indentation: "20",
	folderOpenIcon: path+"/static/bootstrap-3.3.7/folderOpen.jpg",  //图标地址
	folderCloseIcon: path+"/static/bootstrap-3.3.7/folderClose.jpg",
	hoverRowBackground: "false",
	folderColumnIndex: "1",
	//itemClick: "itemClickEvent",      //点击事件
	columns:[
		//headerAlign表头水平位置，dataAlign数据水平位置
		{headerText: "", headerAlign: "center", dataAlign: "center", width: "20", handler: "customCheckBox"},
		//{headerText: "类型标志", dataField: "noticeTypeFlag", headerAlign: "center", dataAlign: "left",width: "170"},
		{headerText: "类型名称", dataField: "noticeTypeName", headerAlign: "center", dataAlign: "center",width: "300"},
		{headerText: "通知主题", dataField: "noticeTitle", headerAlign: "center", dataAlign: "center", width: "300"},
		{headerText: "通知内容", dataField: "noticeContent", headerAlign: "center", dataAlign: "center", width: "300"},
		{headerText: "通知人", dataField: "noticeSend", headerAlign: "center", dataAlign: "center", width: "100"},
		{headerText: "接收人", dataField: "noticeReceive", headerAlign: "center", dataAlign: "center", width: "120"},
		{headerText: "通知时间", dataField: "noticeDate", headerAlign: "center", dataAlign: "center", width: "350"},
		{headerText: "已读否", dataField: "readFlag", headerAlign: "center", dataAlign: "center", width: "120",handler:"formatReadFlag"},
		{headerText: "有效否", dataField: "effective", headerAlign: "center", dataAlign: "center", width: "120",
			handler:"formatEffective"},
		{headerText: "操作", headerAlign: "center", dataAlign: "center", width: "360",handler:"formatOperBtn"},
	],
	/!*url:path+"/notice/selectAll",  //请求地址*!/
	url:path+"/notice/selectAll?noticeTypeFlag="+$("#searchNoticeTypeFlag").val()+"&effective="+$("#effective").val()+"&noticeSend="+$("#noticeSend").val()
		+"&noticeReceive="+$("#searcchNoticeReceive").val()+"&noticeDateStart="+$("#startTime1").val()+"&noticeDateEnd="+$("#endTime1").val()+"&noticeId="+$("#searchNoticeId").val()
};*/
//创建一个组件对象
/*var treeGrid = new TreeGrid(config);
treeGrid.show();   //相当于datagrid的reload，在添加删除数据之后调用刷新表格
function refreshTable(){
	$("#div1").empty();
	config = { id: "moduleListTable",   //表格ID
		idField : 'noticeId',
		treeField : 'noticeTypeName',
		parentField : 'parentId',
		pagination : true,
		pageSize : 15,
		width: "800",    //最小宽度
		renderTo: "div1",  //指定表格生成的父容器ID
		headerHeight: "30",
		indentation: "20",
		folderOpenIcon: path+"/static/bootstrap-3.3.7/folderOpen.jpg",  //图标地址
		folderCloseIcon: path+"/static/bootstrap-3.3.7/folderClose.jpg",
		hoverRowBackground: "false",
		folderColumnIndex: "1",
		itemClick: "itemClickEvent",      //点击事件
		columns:[
			//headerAlign表头水平位置，dataAlign数据水平位置
			{headerText: "", headerAlign: "center", dataAlign: "center", width: "20", handler: "customCheckBox"},
			//{headerText: "类型标志", dataField: "noticeTypeFlag", headerAlign: "center", dataAlign: "left",width: "170"},
			{headerText: "类型名称", dataField: "noticeTypeName", headerAlign: "center", dataAlign: "left",width: "300"},
			{headerText: "通知主题", dataField: "noticeTitle", headerAlign: "center", dataAlign: "center", width: "300"},
			{headerText: "通知内容", dataField: "noticeContent", headerAlign: "center", dataAlign: "center", width: "300"},
			{headerText: "通知人", dataField: "noticeSend", headerAlign: "center", dataAlign: "center", width: "100"},
			{headerText: "接收人", dataField: "noticeReceive", headerAlign: "center", dataAlign: "center", width: "120"},
			{headerText: "通知时间", dataField: "noticeDate", headerAlign: "center", dataAlign: "center", width: "350"},
			{headerText: "已读否", dataField: "readFlag", headerAlign: "center", dataAlign: "center", width: "120",handler:"formatReadFlag"},
			{headerText: "有效否", dataField: "effective", headerAlign: "center", dataAlign: "center", width: "120",
				handler:"formatEffective"},
			{headerText: "操作", headerAlign: "center", dataAlign: "center", width: "360",handler:"formatOperBtn"},
		],url:path+"/notice/selectAll?noticeTypeFlag="+$("#searchNoticeTypeFlag").val()+"&effective="+$("#effective").val()+"&noticeSend="+$("#noticeSend").val()
			+"&noticeReceive="+$("#searcchNoticeReceive").val()+"&noticeDateStart="+$("#startTime1").val()+"&noticeDateEnd="+$("#endTime1").val()+"&noticeId="+$("#searchNoticeId").val()}
	var treeGrid = new TreeGrid(config);
	treeGrid.show();   //相当于datagrid的reload，在添加删除数据之后调用刷新表格
}*/


var $table = $('#table');
var data;
var pageNumber;
$(function() {
	//控制台输出一下数据
	$table.bootstrapTable({
		height:getHeight(),
		url:path+"/notice/selectAll",
		idField: 'noticeId',
		treeField:'noticeTypeName',
		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, //当前页码
				noticeTypeFlag:$("#searchNoticeTypeFlag").val(),
				effective:$("#effective").val(),
				noticeSend:$("#noticeSend").val(),
				noticeReceive:$("#searcchNoticeReceive").val(),
				noticeDateStart:$("#startTime1").val(),
				noticeDateEnd:$("#endTime1").val(),
				noticeId:$("#searchNoticeId").val()
			};
			return temp;
		},
		columns: [
			{ field: 'check',  checkbox: true, formatter: function (value, row, index) {
					if (row.check == true) {
						//设置选中
						return {  checked: true };
					}
				}
			},
			{ field: 'noticeTypeName',  title: '类型名称' },
			{ field: 'noticeTitle',  title: '通知主题' },
			{ field: 'noticeContent',  title: '通知内容' },
			{ field: 'noticeSend',  title: '通知人' },
			{ field: 'noticeReceive',  title: '接收人' },
			{ field: 'noticeDate',  title: '通知时间' },
			{ field: 'readFlag',  title: '已读否' ,formatter: 'formatReadFlag'},
			{ field: 'effective',  title: '有效否' ,formatter: 'formatEffective'},
			{ field: 'operate', title: '操作', align: 'center', events : operateEvents, formatter: 'formatOperBtn' },
		],
		//在哪一列展开树形
		treeShowField: 'noticeTypeName',
		//指定父id列
		parentIdField: 'parentId',
		onResetView: function(data) {
			$table.treegrid({
				initialState: 'collapsed',// 所有节点都折叠
				// initialState: 'expanded',// 所有节点都展开，默认展开
				treeColumn: 1,
				expanderExpandedClass: 'glyphicon glyphicon-triangle-bottom',  //图标样式
				expanderCollapsedClass: 'glyphicon glyphicon-triangle-right',
				onChange: function() {
					$table.bootstrapTable('resetWidth');
				}
			});
			//只展开树形的第一级节点
			$table.treegrid('getRootNodes').treegrid('expand');
		},
		onLoadSuccess: function(){  //加载成功时执行
			$(".page-list").show();
			$("th").css({'text-align':'center','vertical-align':'middle'})
			$("td").css({'text-align':'center','vertical-align':'middle'})
		},
		onCheck:function(row){
			var datas = $table.bootstrapTable('getData');
			// 勾选子类
			selectChilds(datas,row,"noticeId","parentId",true);
			// 勾选父类
			selectParentChecked(datas,row,"noticeId","parentId")
			// 刷新数据
			$table.bootstrapTable('load', datas);
			$(".page-list").hide();
		},
		onUncheck:function(row){
			var datas = $table.bootstrapTable('getData');
			selectChilds(datas,row,"noticeId","parentId",false);
			$table.bootstrapTable('load', datas);
			$(".page-list").hide();
		},
		//全选
		onCheckAll:function(rows){
			$("#checks").val("");
			var checks = '';
			for(var i=0;i<rows.length;i++)
			{
				if(rows[i].noticeTypeFlag == null || rows[i].noticeTypeFlag == '')
				checks += "'"+rows[i].noticeId + "',"
			}
			$("#checks").val(checks);
		},
		//全不选
		onUncheckAll: function (rows) {
			$("#checks").val("");
		}
	});
});
function refreshTable(){
	$("#table").bootstrapTable('refresh',path+'/notice/selectAll');
	$('#table').bootstrapTable('selectPage', pageNumber);
}
function getHeight() {
	return $(window).height() - 300;
}
// 格式化类型
function typeFormatter(value, row, index) {
	if (value === 'menu') {  return '菜单';  }
	if (value === 'button') {  return '按钮'; }
	if (value === 'api') {  return '接口'; }
	return '-';
}
// 格式化状态
function statusFormatter(value, row, index) {
	if (value === 1) {
		return '<span class="label label-success">正常</span>';
	} else {
		return '<span class="label label-default">锁定</span>';
	}
}

//初始化操作按钮的方法
window.operateEvents = {
	'click .RoleOfadd': function (e, value, row, index) {
		add(row.id);
	},
	'click .RoleOfdelete': function (e, value, row, index) {
		del(row.id);
	},
	'click .RoleOfedit': function (e, value, row, index) {
		update(row.id);
	}
};
//格式化是否已读
function formatReadFlag(value, row, index){
	if(value != null){
		if(value == 1){
			return "<span style='color:#999999'>已读</span>";
		}else{
			return "<span style='color:#008000'>未读</span>";
		}
	}
}
//格式化是否有效
function formatEffective(value, row, index){
	if(value != ''  && value != null){
		if (value == 1) {
			return "是";
		} else {
			return "否";
		}
	}
}
//格式化操作按钮
function formatOperBtn(value, row, index) {
	//获取登录者
	var userName = $("#userName").val();
	var userId = $("#userId").val();
	var btns = '';
	if (row.parentId != null) {
		//admin或本人才能修改
		if((userName == 'admin' || userName == row.noticeReceive) && row.readFlag == 0){
			btns += '<button type="button" onclick="editFlag(' + row.noticeId + ')" class="btn btn-primary operBtns btn-sm">标记为已读</button>';
		}
		//admin或本人才能修改
		if(userName == 'admin' || userName == row.noticeSend){
			btns += '<button type="button" onclick="edit(' + row.noticeId + ')" class="btn btn-info operBtns btn-sm" data-toggle="modal" data-target="#myModal1" >编辑</button>';
		}
		if(row.readFlag == 0 && (userName == 'admin' || userName == row.noticeSend)){
			btns += '<button type="button" onclick="drop(' + row.noticeId + ')" class="btn btn-danger operBtns btn-sm">删除</button>';
		}
	}
	return btns;
}
/**
 * 选中父项时，同时选中子项
 * @param datas 所有的数据
 * @param row 当前数据
 * @param id id 字段名
 * @param pid 父id字段名
 */
function selectChilds(datas,row,id,pid,checked) {
	var checks = $("#checks").val();
	for(var i in datas){
		if(datas[i].noticeId == row[id] && (datas[i].noticeTypeFlag == null || datas[i].noticeTypeFlag == '')){
			if(checked){
				checks += "'"+datas[i].noticeId + "',";
			}else{
				checks = checks.replace("'"+datas[i].noticeId + "',","");
			}
		}
		if(datas[i][pid] == row[id]){
			datas[i].check=checked;
			if(checked){
				checks += "'"+datas[i].noticeId + "',";
			}else{
				checks = checks.replace("'"+datas[i].noticeId + "',","");
			}
			selectChilds(datas,datas[i],id,pid,checked);
		};
	}
	$("#checks").val(checks);
}

function selectParentChecked(datas,row,id,pid){
	for(var i in datas){
		if(datas[i][id] == row[pid]){
			datas[i].check=true;
			selectParentChecked(datas,datas[i],id,pid);
		};
	}
}

//通知标志为已读
function editFlag(noticeId){
	var flag = false;
	$.ajax({
		type:'post',
		url:path+'/notice/updateNoticeReadFlag',
		data:{noticeId:noticeId},
		dataType:'json',
		success:function(data){
			if(data.code == 100){
				//连同未读数量也一起修改
				$.ajax({
					type:'get',
					url:path+'/notice/getUnReadCount',
					dataType:'json',
					sync:false,
					success:function(data){
						if(data.code == 100){
							debugger
							parent.$("#noticeCount").text(data.extend.unReadCount);
						}
					}
				})
				toastr.success("修改成功!");
				flag = true;
			}else{
				toastr.error(data.msg)
			}
		}
	})
	setTimeout(function(){
		if(flag){
			window.location.reload();
		}
	},500)
}
//编辑通知
function edit(noticeId){
	$.ajax({
		type:'get',
		url:path+'/notice/selectNoticeByNoticeId',
		data:{noticeId:noticeId},
		dataType:'json',
		success:function(data){
			if(data.code == 100){
				var notice = data.extend.powerNotice;
				var parentId = notice.parentId;
				$("#parentId").val(parentId);
				$("#noticeReceive").empty();
				if(parentId != null && parentId != ''){
					$.ajax({
						type:'get',
						url:path+'/notice/getUserNameListByNoticeTypeId',
						data:{noticeTypeId:parentId},
						dataType:'json',
						async:false,
						success:function(data){
							if(data.code == 100){
								var html = '<option value="all">该通知类型所有人</option>';
								if(data.extend != ''){
									var userName = $("#userName").val();
									for (var i = 0; i < data.extend.userList.length; i++) {
										if (userName != data.extend.userList[i].userName) {
											html += '<option value="' + data.extend.userList[i].userId + '">' + data.extend.userList[i].userName + '</option>';
										}
									}
								}
								$("#noticeReceive").append(html);
							}
						}
					})
				}
				$("#noticeId1").val(notice.noticeId);
				$("#readFlag").val(notice.readFlag);
				$("#noticeTitle").val(notice.noticeTitle);
				$("#noticeContent").val(notice.noticeContent);
				$("#noticeReceive").val(notice.noticeReceive);
				$("#effective1").val(notice.effective);
				console.log(notice.remark)
				$("#remark").val(notice.remark);
			}else{
				toastr.error("查询出错了,请联系系统管理员!");
			}
		}
	})
}

//删除通知
function drop(noticeId){
	Common.confirm({
		title: "提示",
		message: "确定是否删除此条记录?",
		operate: function (reselt) {
			if (reselt) {
				$.ajax({
					type:'post',
					url:path+"/notice/delete",
					data:{noticeId:noticeId},
					dataType:'json',
					success:function(data){
						if(data.code == 100){
							toastr.success("删除成功!");
							setTimeout(function(){
								window.location.reload();
							},500)
						}else{
							toastr.error("删除失败,请联系系统管理员!");
						}
					}
				})
			}
		}
	})
}

/*
    展开、关闭所有节点。
    isOpen=Y表示展开，isOpen=N表示关闭
*/
function showAll(){
	if($("#Openbtn>i").hasClass("glyphicon-folder-close")){
		treeGrid.expandAll("Y");
		$("#Openbtn>i").removeClass("glyphicon-folder-close").addClass("glyphicon-folder-open");
	}else{
		treeGrid.expandAll("N");
		$("#Openbtn>i").removeClass("glyphicon-folder-open").addClass("glyphicon-folder-close");
	}

}


//导出
function exportExcel(){
	var noticeIds = $("#checks").val();
	if(noticeIds == ''){
		Common.confirm({
			title: "提示",
			message: "没有选中，您确定要按搜索栏条件导出?",
			operate: function (reselt) {
				if (reselt) {
					var url = path + "/notice/export?noticeTypeFlag="+$("#searchNoticeTypeFlag").val()+"&effective="+$("#effective").val()+"&noticeSend="+$("#noticeSend").val()
						+"&noticeReceive="+$("#searcchNoticeReceive").val()+"&noticeDateStart="+$("#startTime1").val()+"&noticeDateEnd="+$("#endTime1").val()+"&noticeId="+$("#searchNoticeId").val();
					window.location.href = url;
				}
			}
		})
	}else{
		noticeIds = noticeIds.substring(0,noticeIds.length-1);
		var url = path + "/notice/export?noticeTypeFlag="+$("#searchNoticeTypeFlag").val()+"&effective="+$("#effective").val()+"&noticeSend="+$("#noticeSend").val()
			+"&noticeReceive="+$("#searcchNoticeReceive").val()+"&noticeDateStart="+$("#startTime1").val()+"&noticeDateEnd="+$("#endTime1").val()+"&noticeId="+$("#searchNoticeId").val()+"&noticeIds="+noticeIds;
		window.location.href = url;
	}
}