//查看消息
function viewMessage(id,status){
	$("#myModal-viewmessage").modal('show');
	$.ajax({
		url:'/systemMsg/do_getMsgDetail',
		type:'get',
		data:{
			'id':id
		},
		success:function(data){
			if( data.success ){
				$("#myModal-viewmessage .view-title").text(data.data.title);
				$("#myModal-viewmessage .view-senderUser").text(data.data.senderName);
				$("#myModal-viewmessage .view-pushTime").text(data.data.pushTime);
				$("#myModal-viewmessage .view-content").text(data.data.content);
			}else{
				new $.zui.Messager('获取消息详情失败:'+data.msg, {
				    type: 'danger'
				 }).show();
			}
		},
		error:function(status){
			new $.zui.Messager('获取消息详情时发生错误:'+status, {
			    type: 'danger'
			 }).show();
		}
	});
	if( !status ){//是未读的, 需要标记为已读
		setReadState(id,status,false,true)
	}
	return false;
};
//设置已读未读
function setReadState(ids,status,batch,notip){
	mylistpage = $('#messageList').getGridParam('page');
	var errortip = '';
	var readStateData = {'readState':!status};
	if( status ){
		errortip = '未读'
	}else{
		errortip = '已读'
	};
	if( batch ){
		errortip = '批量'+errortip;
		for( var i=0;i<ids.length;i++ ){
			readStateData['msgIds['+i+']'] = ids[i];
		};
		i = null;
	}else{
		readStateData['msgIds[0]'] = ids;
	};
	$.ajax({
		url:'/systemMsg/do_updateReadState',
		type:'post',
		data:readStateData,
		success:function(data){
			 if( data.success ){
				 if( !data.data ){
					 new $.zui.Messager(errortip+'设置失败', {
						    type: 'danger'
						 }).show();
				 }else{
					 if( !notip ){
						 new $.zui.Messager(errortip+'设置成功', {
							    type: 'success'
						 }).show();
					 };
					 //刷新表格(当前页)
					 $('#messageList').jqGrid('setGridParam',{
			            mtype:'GET',
			            url : '/systemMsg/do_messageManageList',
			            postData: {
			            		'msgType.id':messagetypeid,
							'keyWord':messagecontent
							},
			            page:mylistpage
			         }).trigger('reloadGrid');
					 //刷新头部消息数量
					 //getUnreadMessage();
				 }
			 }else{
				 new $.zui.Messager(errortip+'设置请求失败:'+data.msg, {
					    type: 'danger'
				 }).show();
			 }
		},
		error:function(status){
			new $.zui.Messager(errortip+'设置时发生错误:'+status, {
			    type: 'danger'
			 }).show();
		}
	})
};
//删除消息
function deleteMessage(ids,batch){
	var deletedata = {};
	var deletetip = '';
	if( batch ){//批量
		deletetip = '批量删除消息'
	}else{
		deletetip = '删除消息';
	};
	bootbox.confirm({
		title : deletetip,
		message : '<div style="text-align:left;font-size:0.12rem">确认'+deletetip+'吗？</div>',
		size : 'small',
		buttons : {
			cancel : {
				label : '取消',
				className:'btn-white btn-info'
			},
			confirm : {
				label : '确定',
				className:'btn-white btn-info colorbtn'
			}
		},
		callback:function(result){
			if (result) {
				mylistpage = $('#messageList').getGridParam('page');
				if( batch ){//批量
					for( var i=0;i<ids.length;i++ ){
						deletedata['msgIds['+i+']'] = ids[i];
					};
					i = null;
				}else{
					deletedata = {
						'msgIds[0]':ids
					}
				};
				$.ajax({
					url:'/systemMsg/do_deleteMsg',
					type:'post',
					data:deletedata,
					success:function(data){
						if( data.success ){
							if( data.data ){
								new $.zui.Messager(deletetip+'消息成功', {
								    type: 'success'
								}).show();
								//刷新表格(当前页)
								 $('#messageList').jqGrid('setGridParam',{
						            mtype:'GET',
						            url : '/systemMsg/do_messageManageList',
						            postData: {
						            		'msgType.id':messagetypeid,
										'keyWord':messagecontent
										},
						            page:mylistpage
						        }).trigger('reloadGrid');
								//刷新头部消息数量
								//getUnreadMessage();
							}else{
								new $.zui.Messager(deletetip+'消息失败', {
								    type: 'danger'
								}).show();
							}
						}else{
							new $.zui.Messager(deletetip+'消息请求失败:'+data.msg, {
							    type: 'danger'
							}).show();
						}
					},
					error:function(status){
						new $.zui.Messager(deletetip+'消息时发生错误:'+status, {
						    type: 'danger'
						}).show();
					}
				})
			}
		}
	});
	return false;
};

// 消息跳转
function jumpNews(ename,taskid,businessId,msgType){
	if( jumpModulepermissions(ename) ){// 有要前往的模块的权限
		//'收放款执行(保理融资款)'/'收放款执行(应收账款)'/'逾期数据' 时要跳往账后管理    更新: 添加ename为paymentCollectionManagement时跳往账后的(收放款管理的)收放款计划
		if( ename == 'payCollPlanFactoringManagement' || ename == 'payCollPlanReceivableManagement' || ename == 'overdueCustomerData' || ename == 'paymentCollectionManagement' ){
			if( ename == 'overdueCustomerData' ){// 逾期数据直接跳转, 不需判断
				messageJumpLeastEname = ename;
				messageJumpLeastPrevId = businessId;
				// 跳转
				messageJumpTakId = taskid;
				jumpModuleFn('postAccountManagement');
			}else{
				if( ename == 'paymentCollectionManagement' ){// ename为paymentCollectionManagement时跳往账后的(收放款管理的)收放款计划payCollPlanManagement
					ename = 'payCollPlanManagement';
					if(jumpModuleOtherReason(taskid) ){// 任务未完成或分配等原因可以继续跳转
						messageJumpLeastEname = ename;
						messageJumpLeastPrevId = businessId;
						// 跳转
						messageJumpTakId = taskid;
						jumpModuleFn('postAccountManagement');
					}
				}else{
					if( jumpModuleOtherReasonPay(businessId,ename,msgType) ){// 任务未完成或分配等原因可以继续跳转
						messageJumpLeastEname = ename;
						messageJumpLeastPrevId = businessId;
						// 跳转
						messageJumpTakId = taskid;
						jumpModuleFn('postAccountManagement');
					}
				}
			}
		}else if( ename == 'inkassonPolicyManagement' || ename == 'importerQuotaManagement' ){//'长银保单管理'/'进口方额度管理' 时要跳往信保管理
			// 直接跳转, 不需判断
			messageJumpLeastEname = ename;
			messageJumpLeastPrevId = businessId;
			// 跳转
			messageJumpTakId = taskid;
			jumpModuleFn('creditInsuranceManagement');
		}else{
			if( jumpModuleOtherReason(taskid) ){// 任务未完成或分配等原因可以继续跳转
				messageJumpLeastPrevId = businessId;
				// 跳转
				messageJumpTakId = taskid;
				jumpModuleFn(ename);
			};
		};

	};
};

$(function(){
	$("#messageContent").val(messagecontent);
	$("#messageTypeId i").text(messagetypeword);
	function loadMessageManageData(){
		$('#messageList').setGridParam({
			mtype:'GET',
			url : '/systemMsg/do_messageManageList',
			datatype : 'json',
			postData: {
				'msgType.id':messagetypeid,
				'keyWord':messagecontent
				},
			page : 1
		});
		$('#messageList').trigger('reloadGrid');
	};

	function pushStateFormatter(cellValue,options,rowObject){
		if(undefined != rowObject.readState && rowObject.readState){
			return "已读";
		}else{
			return "<li style='color:red'>未读</li>";
		}
	};

	function operateMessage(cellValue,options,rowObject){
		var btnstr = '';
		btnstr += '<p><span>查看</span><i class="operateIconfont operateIcon-chakan" onclick="viewMessage(\''+rowObject.id+'\','+rowObject.readState+')"></i></p>';
		if( !rowObject.readState ){//未读
			btnstr += '<p><span>设为已读</span><i class="operateIconfont operateIcon-yidu" onclick="setReadState(\''+rowObject.id+'\','+rowObject.readState+')"></i></p>';
		}else{//已读
			btnstr += '<p><span>设为未读</span><i class="operateIconfont operateIcon-weidu" onclick="setReadState(\''+rowObject.id+'\','+rowObject.readState+')"></i></p>';
		};
		btnstr += '<p><span>删除</span><i class="operateIconfont operateIcon-shanchu" onclick="deleteMessage('+rowObject.id+')"></i></p>';
		return '<div class="operateIcon noHover">'+btnstr+'</div>';
	};

	function showTitle(cellValue,options,rowObject){
		var titleStr = '';
		// 待办消息/正常催收消息/逾期催收消息/信保提醒消息  需要跳转
		if( rowObject.msgType && ( rowObject.msgType.code=='pending_news' || rowObject.msgType.code=='normal_collection' || rowObject.msgType.code=='overdue_collection' || rowObject.msgType.code=='letter_guarantee_reminder' ) )
		{
			titleStr = '<div class="readingSituationWord" onclick="jumpNews(\''+rowObject.businessType.code+'\','+rowObject.taskId+','+rowObject.businessId+',\''+rowObject.msgType.code+'\')">'+rowObject.title+'</div>'
		}else{
			titleStr = rowObject.title;
		};
		return titleStr;
	};

	sxUtil.jqGrid('#messageList',{
		colNames:['消息ID','序号','消息标题','接收类型','接收时间','发件人','状态','事件','操作'],
		colModel:[
			{name: 'id', label: '消息ID', hidedlg:true, hidden:true,sortable:false,title:false},
			{name: 'orderNumber', label: '序号',sortable:false,width:70,align:'center',title:false},
			{name: 'title', label: '消息标题',sortable:false,width:200,align:'left',title:false,formatter:showTitle},
			{name: 'msgType.name', label: '接收类型',sortable:false,align:'center',width:100,title:false},
			{name: 'pushTime', label: '接收时间',sortable:false,align:'center',width:200,title:false},
			{name: 'senderName', label: '发件人',sortable:false,align:'center',width:90,title:false},
			{name: 'readState', label: '状态',sortable:false,align:'center',width:90,title:false,formatter:pushStateFormatter},
			{name: 'content', label: '事件',sortable:false,align:'left',width:230,title:false},
			{name: 'remark', label: '操作',sortable:false,align:'center',width:200,title:false,formatter:operateMessage}
		],
		height:'auto',
		mtype:'GET',
		url : '/systemMsg/do_messageManageList',
		pager : "#messageListPage",
		multiselect: true,
		rownumbers:false,
		postData : {
			'msgType.id':messagetypeid,
			'keyWord':messagecontent
		},
		page:mylistpage,
		loadError:function(){
			new $.zui.Messager('消息列表加载失败', {
			    type: 'warning',
			    time:1500
			}).show();
		},
		beforeSelectRow: function (rowid, e) { //设置点击行时不选中复选框
		    var $myGrid = $(this),
		        i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
		        cm = $myGrid.jqGrid('getGridParam', 'colModel');
		    return (cm[i].name === 'cb');
		}
	},true);

	//切换表格
	$(".projectListTab li").click(function(){
		$(".projectListTab .active").removeClass("active");
		$(this).addClass("active");

		if( $(this).hasClass('viewSentMsgList') ){// 已发送消息
			mylistpage = $('#messageList').getGridParam('page');
			$(".yk_rightcontent").load("/systemMsg/sentMsgList");
		};
	});

	//刷新
	$('#refresh').click(function(){
		$("#messageContent").val('');//清空
		$("#messageTypeId i").text('请选择消息类型');
		$("#messageTypeId").data('messageId','');
		$('#messageList').jqGrid('setGridParam',{
            mtype:'GET',
            url : '/systemMsg/do_messageManageList',
            postData: {
            		'msgType.id':'',
				'keyWord':''
				},
            page:1
        }).trigger('reloadGrid'); //重新载入
	});
	//消息类型选择
	$(".messageType").click(function(){
		$("#messageTypeId i").text( $(this).text() )
		$("#messageTypeId").data('messageId',$(this).attr('value'));
		messagetypeid = $("#messageTypeId").data('messageId');
		messagetypeword = $("#messageTypeId i").text();
		loadMessageManageData();
	})
	//查询按钮点击
	$("#query").click(function(){
		messagecontent = $("#messageContent").val();
		loadMessageManageData();
	});

	//批量删除
	$("#batchDeleting").click(function(){
		var deleteIds = $('#messageList').jqGrid('getGridParam','selarrrow');
		if( !deleteIds.length ){
			new $.zui.Messager('请选择要删除的消息', {
			    type: 'danger',
			    time:1500
			}).show();
		}else{
			deleteMessage(deleteIds,true)
		}
	});

	//批量已读
	$("#batchRead").click(function(){
		var readIds = $('#messageList').jqGrid('getGridParam','selarrrow');
		if( !readIds.length ){
			new $.zui.Messager('请选择要设置为已读的消息', {
			    type: 'danger',
			    time:1500
			}).show();
		}else{
			setReadState(readIds,false,true)
		}
	});

	//批量未读
	$("#batchUnread").click(function(){
		var unreadIds = $('#messageList').jqGrid('getGridParam','selarrrow');
		if( !unreadIds.length ){
			new $.zui.Messager('请选择要设置为未读的消息', {
			    type: 'danger',
			    time:1500
			}).show();
		}else{
			setReadState(unreadIds,true,true)
		}
	});


})
