var imServer = getParameter("imserver");
var lvid = getParameter("lvid");
var sign = getParameter("sign");
imServer = getImServer(imServer);
var userid;
var personLastDate = ''; //个人发布时间
var groupLastDate = ''; //云组发布时间
var loadcount = 0;
var noticeIdArr = new Array();
var currenttime = 0;
var again = false;
var groupmsg = false;
var Print = {
	'APPEND': 1,
	'REPLACE': 0
};
var Verify = {
	'PERSON': 0,
	'GROUP': 1
};
$(function() {
	//同意&拒绝好友验证
	$(".verXuanze").click(function() {
		$(this).find(".verXuanze-popup").show();
	});
	//点击"好友验证"
	$(".verFriend").click(function() {
		$(this).addClass('activetab');
		$(".groupMeal").removeClass('activetab');
		$(".verGroupCon,.groupn,.frontMost_F").hide();
		$(".verFdCon,.friend").show();
		if ($(".verFdMain .addFriendTopTip").is('visible')) {
			$('.verFdMain ul li').addClass('heitip').removeClass('defuheitip');
			return;
		}
		load(Verify.PERSON);
	});
	//点击"组系统消息"
	$(".groupMeal").click(function() {
		$(this).addClass('activetab');
		$(".verFriend").removeClass('activetab');
		$('.friend,.verFdCon,.frontMost_G').hide();
		$('.groupn,.verGroupCon').show();
		if ($(".addGroupTopTip").is('visible')) {
			$('.verGroupCon ul li').addClass('heitip').removeClass('defuheitip');
		} else {
			$('.verGroupCon ul li').addClass('defuheitip');
		}
		load(Verify.GROUP);
	});

});
//点击同意&拒绝好友验证弹框之外的地方隐藏本身
$(document).bind("click", function(e) {
	var target = $(e.target);
	if (target.closest(".verXuanze").length == 0) {
		$(".verXuanze-popup").hide();
	}
});

//好友验证
function verifyPerson(noticeid, acceptType, senderLvid) {
	var tip;
	switch (acceptType) {
		case 1: //同意
			tip = '已同意';
			break;
		case 2: //拒绝
			tip = '已拒绝';
			break;
		case 3: //忽略
			tip = '已忽略';
			break;
	}
	var buttonid = "verify_person_" + senderLvid;
	var buttonhtml = '<div class="ver-yesBut">' + tip + '</div>';
	$("#" + buttonid).html(buttonhtml);
	if ($.inArray(noticeid, noticeIdArr) > -1) {
		return;
	}
	noticeIdArr.push(noticeid);
	var params = {
		'lvid': lvid,
		'noticeid': noticeid,
		'accepttype': acceptType,
		'sign': sign
	};
	$.getJSON(requestUrlMap['updateNotice']['url'], params, function(data) {
		if (data.errorid != 0) {
			var paramStr = "{title:'提示',cat:0,content:'" + data.errmsg + "！'}";
			var params = "{command:9006,params:" + paramStr + "}";
			sendCommand(params);
			return;
		}
		load(Verify.PERSON);
	});
}
//云组验证
function verifyGroup(noticeid, acceptType) {
	var tip;
	switch (acceptType) {
		case 1: //同意
			tip = '已同意';
			break;
		case 2: //拒绝
			tip = '已拒绝';
			break;
		case 3: //忽略
			tip = '已忽略';
			break;
	};
	var buttonid = "verify_group_" + noticeid;
	var buttonhtml = '<div class="ver-yesBut">' + tip + '</div>';
	$("#" + buttonid).html(buttonhtml);
	if ($.inArray(noticeid, noticeIdArr) > -1) {
		return;
	};
	noticeIdArr.push(noticeid);
	var params = {
		'lvid': lvid,
		'noticeid': noticeid,
		'accepttype': acceptType,
		'sign': sign
	};
	$.getJSON(requestUrlMap['updateNotice']['url'], params, function(data) {
		if (data.errorid != 0) {
			var paramStr = "{title:'提示',cat:0,content:'" + data.errmsg + "！'}";
			var params = "{command:9006,params:" + paramStr + "}";
			sendCommand(params);
			return;

		};
		load(Verify.GROUP);
	});
}
//插入数据
function InsertIMNotifyData(type, result) {
	if (!result || result['errorid'] != 0) {
		//错误
		return;
	};
	var arr = result['data'];
	if (type == Verify.PERSON) { //个人消息验证
		printPersonMsg(Print.APPEND, arr);
	} else if (type == Verify.GROUP) { //云组消息验证
		printGroupMsg(Print.APPEND, arr);
	};
}

//客户端有新消息调用
//上部验证提示信息回调，msgtype：0代表好友验证消息，1代表群组验证消息，msgnumbers是验证消息的数量
function InsertIMNotifyData() {
	again = true;
	var params = {
		'lvid': lvid,
		'sign': sign
	};
	$.getJSON(requestUrlMap['noticeList']['url'], params, unreadback);
}
//得到格式化后的时间戳
function getTimeStr(date) {
	var dateStr = $.formatDateStyle1(date);
	var currDate = new Date();
	if (currenttime != 0) {
		currDate.setTime(currenttime * 1000);
	};
	if (dateStr != $.formatDateStyle1(currDate)) {
		return dateStr;
	};
	var hG = currDate.getDate() - date.getDate();
	if (hG == 0) {
		return '今天';
	};
}

function load(verifyType) {
	var noticeType, callbackMethod;
	if (verifyType == Verify.PERSON) {
		noticeType = 1;
		callbackMethod = searchFriendNoticeBack;
	} else {
		noticeType = 2;
		callbackMethod = searchGroupNoticeBack;	
	};
	var params = {
		'lvid': lvid,
		'noticetype': noticeType,
		'sign': sign
	};
	$.getJSON(requestUrlMap['noticeList']['url'], params, callbackMethod);
};
function searchFriendNoticeBack(data) {
	$("#loading-popup").hide();
	if (data.errorid == 0) {
		if (data.count == 0 && loadcount == 0) {
			$(".verFriend").click();
			++loadcount;
		};
		var arr = data.noticelist.collearray;
		userid = data.loginuserid;
		currenttime = data['currenttime'];
		printPersonMsg(Print.REPLACE, arr);
	};
};

function searchGroupNoticeBack(data) {
	$("#loading-popup").hide();
	if (data.errorid == 0) {
		var arr = data.noticelist.collearray;
		currenttime = data['currenttime'];
		userid = data.loginuserid;
		printGroupMsg(Print.REPLACE, arr);
	};
};
$(document).ready(function() {
	var params = {
		'lvid': lvid,
		'sign': sign
	};
	$.getJSON(requestUrlMap['noticeList']['url'], params, unreadback);
});

/*首次打开系统消息验证个人 云组未读消息 跳转至对应的tab*/
function unreadback(data) {
	if(again){
		var userCount = 0;
		var groupCount = 0;
		if (data.errorid == 0) {
			var list = data.unreadcount;
			if (list != null && list.length > 0) {
				for (var i = 0; i < list.length; i++) {
					var json = list[i];
					if (json.noticetype == 1) {
						userCount = json.countno;
					} else {
						groupCount = json.countno;
					}
				};
			};
			if (userCount > 0) {
				if ($(".verFdCon").is(':visible')) {
					$(".F_msgNums").text(userCount);
					$(".addFriendTopTip").show();
					$('.verFdMain ul li').css('height','255px').removeClass('defuheitip');
				} else {
					$(".addFriendTopTip,.addGroupTopTip").hide();
					$(".frontMost_F").html(userCount).show();
				};
			} else if (groupCount >= 1) {
				if ($(".verGroupCon").is(':visible')) {
					$(".G_msgNums").text(groupCount);
					$(".addGroupTopTip").show();
					$('.verGroupCon ul li').css('height','255px').removeClass('defuheitip');
				} else {
					$(".addGroupTopTip,.addFriendTopTip").hide();
					$(".frontMost_G").html(groupCount).show();
				};
			};
		};
		return false;
	};
	var groupNum = data.unreadcount[0].countno;
	var friendNum = data.unreadcount[1].countno;
	if(!groupNum && !friendNum){
		$(".verFriend").click();
	}
	if( friendNum >= 1 ){
		$(".verFriend").click();
		if(!groupNum){
			return;
		};
		$('.frontMost_G').text(groupNum).show();	
	};
	if( groupNum >= 1 ){
		$(".groupMeal").click();
		if(!friendNum){
			return;
		};
		$('.frontMost_F').text(friendNum).show();
	};
};
/*清空系统列表*/
$('.friend span').click(function() {
	if ($('#userinfo dd').length < 1) {
		return;
	};
	var paramStr = "{title:'提示',cat:3,content:'你确定要清空列表吗？'}";
	var params = "{command:9006,params:" + paramStr + "}";
	var result = $.parseJSON(sendCommand(params));
	if (result['errorid'] == 1) {
		var params = {
			'lvid': lvid,
			'notice-type': 1,
			'sign': sign
		};
		$.getJSON(requestUrlMap['clearNotice']['url'], params, function() {
			$('.verFdCon b.nothing').show();
			$('#userinfo').empty();
			$("#userinfo").parent().addClass('listempty');
			$('.friend span').addClass('emptyhand');
		});
	}
});

$('.groupn span').click(function() {
	if ($('#groupmess dd').length < 1) {
		return;
	};
	var paramStr = "{title:'提示',cat:3,content:'你确定要清空列表吗？'}";
	var params = "{command:9006,params:" + paramStr + "}";
	var result = $.parseJSON(sendCommand(params));
	if (result['errorid'] == 1) {
		var params = {
			'lvid': lvid,
			'notice-type': 2,
			'sign': sign
		};
		$.getJSON(requestUrlMap['clearNotice']['url'], params, function() {
			$(".verGroupCon b.nothing").show();
			$('#groupmess').empty();
			$("#groupmess").parent().addClass('listempty');
			$('.groupn span').addClass('emptyhand');
		});
	}
});
/**
 * 插入个人认证消息
 * @type 0：替换；1：追加
 */
function printPersonMsg(type, arr) {
	var msgObj;
	var html = '';
	var infoDate;
	$("#userinfo").parent().addClass('bgFFF').removeClass('listempty');
	$('.friend span').addClass('listcolor').removeClass('emptyhand');
	if (arr.length < 1) {
		$("#userinfo").parent().addClass('listempty');
		$('.verFdCon b.nothing').show();
		$('.friend span').addClass('emptyhand');
		return;
	};
	$('.verFdCon b.nothing').hide();
	for ( var i = 0; i < arr.length; i++ ) {
		msgObj = arr[i];
		var userSend = msgObj.user;
		var notice = msgObj.notice;
		if (notice['accepttype'] == 0 && notice.senduserid == userid) {
			continue;
		};
		infoDate = getTimeStr(new Date(msgObj['datetime'] * 1000));
		if (infoDate != personLastDate) {
			personLastDate = infoDate;
		};
		today = getTimeStr(new Date(notice.createtime * 1000));
		var imgurl = transferHeadSize(userSend.headurl,64);
		if (imgurl == '') {
			imgurl = userSend.sex == 0 ? "../images/classic/HEAD-gg-64.png" : "../images/classic/HEAD-mm-64.png";
		};
		var selftitleName = userSend.nickname.replaceAll('>', '&gt;');
		html += "<dd>";
		html += "<div class=\"verFdList\">";
		html += "<div class=\"verFdHead\"  onclick=\"lookUserView(" + msgObj.user.lvid + "," + msgObj.user.userid + ")\">";
		html += "<div class=\"verHeadImg\"><img src=\"" + imgurl + "\" /></div>";
		html += "<div class=\"head-img-warp\"></div>";
		html += "</div>";
		html += "<div class=\"verFdInfo\">";
		html += "<xmp title=" + selftitleName + " onclick=\"lookUserView(" + msgObj.user.lvid + "," + msgObj.user.userid + ")\">" + userSend.nickname + "</xmp>";
		var message = decodeURIComponent(notice.verifymsg);
		if (message && message.length > 21) {
			message = message.substring(0, 21) + "...";
		};
		var msg = "<div class=\"attachInfo\">附加信息：<xmp>" + message + "</xmp></div><p class=\"findMode\">" + today + "</p></div>";
		var emtpymsg = '<p class="attachInfo">&nbsp;</p><span></span></p><p class=\"findMode\">' + today + '</p></div>';
		switch (notice['accepttype']) {
			case 0: //待处理
				html += msg;
				html += '<div class="verFdBut" id="verify_person_' + userSend['lvid'] + '">';
				html += '<div class="ver-tongyiBut">';
				html += '<div class="verAgree" onclick="verifyPerson(' + notice['id'] + ',1,' + userSend['lvid'] + ')"><span>同意</span></div>';
				html += '<div class="verXuanze">';
				html += '<div class="verXuanze-popup">';
				html += "<div>";
				html += '<p onclick="verifyPerson(' + notice['id'] + ',1,' + userSend['lvid'] + ')">同意</p>';
				html += "</div>";
				html += "<div>";
				html += '<p onclick="verifyPerson(' + notice['id'] + ',2,' + userSend['lvid'] + ')">拒绝</p>';
				html += "</div>";
				html += '</div>';
				html += '</div>';
				html += '</div>';
				html += '<div class="ver-ElideBut" onclick="verifyPerson(' + notice['id'] + ',3,' + userSend['lvid'] + ')"><span>忽略</span></div>';
				html += "</div>";
				break;
			case 1: //已同意
				html += msg;
				html += '<div class="verFdBut"><div class="ver-yesBut">已同意</div></div>';
				break;
			case 2: //已拒绝
				html += msg;
				html += '<div class="verFdBut"><div class="ver-yesBut">已拒绝</div></div>';
				break;
			case 3: //已忽略
				html += msg;
				html += '<div class="verFdBut"><div class="ver-yesBut">已忽略</div></div>';
				break;
			case 4: //已忽略
				html += emtpymsg;
				html += '<div class="verFdBut"><div class="ver-yesBut">'+ message +'</div></div>';
				break;
		};
		html += "</div>";
		html += "</dd>";
	};
	if (type == Print.REPLACE) {
		$("#userinfo").html(html);
	} else {
		$("#userinfo").prepend(html);
	};
	$(".verXuanze").click(function() {
		$(this).find(".verXuanze-popup").show();
	});
};

function lookUserView(lvid, userid) {
	var params = "{command:1003,params:{userid:" + userid + ",lvid:" + lvid + "}}";
	sendCommand(params);
};

function lookGroupView(groupid) {
	var params = "{command:3002,params:{groupid:" + groupid + "}}";
	sendCommand(params);
};
/**
 * 插入云组认证消息
 */
function printGroupMsg(type, arr) {
	var msgObj;
	var html = '';
	var mth, tip;
	var infoDate;
	$("#groupmess").parent().addClass('bgFFF').removeClass('listempty');
	$('.groupn span').addClass('listcolor').removeClass('emptyhand');
	if (arr.length < 1) {
		$("#groupmess").parent().addClass('listempty');
		$(".verGroupCon b.nothing").show();
		$('.groupn span').addClass('emptyhand');
		return;
	};
	$(".verGroupCon b.nothing").hide();
	for (var i = 0; i < arr.length; i++) {
		var msgObj = arr[i];
		var user = msgObj.user;
		var group = msgObj.group;
		var notice = msgObj.notice;
		if (notice['accepttype'] == 0 && notice.senduserid == userid) {
			continue;
		};
		if (notice['noticetype'] == 2) { //请求加入云组
			tip = '申请';
		} else { //邀请加入云组
			if (notice.senduserid == userid) {
				tip = '受邀';
			} else {
				tip = '邀请您';
			};
		};
		mth = 'verifyGroup';
		infoDate = getTimeStr(new Date(notice['createtime'] * 1000));
		if (infoDate != groupLastDate) {
			groupLastDate = infoDate;
		};
		var imgurl = transferHeadSize(user['headurl'],64);
		if (!imgurl) {
			imgurl = user.sex == 0 ? "../images/classic/HEAD-gg-64.png" : "../images/classic/HEAD-mm-64.png";
		};
		html += '<dd>';
		html += '<div class="verFdList">';
		html += "<div class='verFdHead' onclick=\"lookUserView(" + msgObj.user.lvid + "," + msgObj.user.userid + ")\">";
		html += '<div class="verHeadImg"><img src="' + imgurl + '"/></div>';
		html += '<div class="head-img-warp"></div>';
		html += '</div>';
		html += '<div class="verFdInfo">';
		var groupname = group.cloudgroupname
		if (groupname && groupname.length > 7) {
			groupname = groupname.substring(0, 7) + "...";
		}
		var titleName = user.nickname.replaceAll('>', '&gt;');
		var titlegroupName = group.cloudgroupname.replaceAll('>', '&gt;');
		var notverMsg = '<p class="attachInfo">&nbsp;</p><span></span></p>';
		var sliceName = user.nickname.length > 10 ? user.nickname.slice(0,10) + '...' : user.nickname;
		var notice_verifymsg = decodeURIComponent(notice.verifymsg);
		if (notice['noticetype'] == 5 || notice['noticetype'] == 4 || notice['noticetype'] == 7 || notice['noticetype'] == 8 || notice['noticetype'] == 9) {
			html += "<p><span class='vername'>" + notice['verifymsg'] + "</span></p>";
			html += notverMsg;
		}else {
			tip = notice['noticetype'] == 6 ? '&nbsp;加入群组&nbsp;' : '&nbsp;' + tip + '加入群组&nbsp;';
			html += "<div><xmp class='vername' title=" + titleName + " onclick=\"lookUserView(" + msgObj.user.lvid + "," + msgObj.user.userid + ")\">" + sliceName + "</xmp>" + tip + "<xmp onclick=\"lookGroupView(" + group.groupid + ")\" class='dename' style='cursor:pointer' title=" + titlegroupName + ">" + groupname + "</xmp></div>";
			if (notice_verifymsg == '') {
				notice_verifymsg = '无'
			};
			if (notice_verifymsg && notice_verifymsg.length > 21) {
				notice_verifymsg = notice_verifymsg.substring(0, 21) + "...";
			};
			notice['noticetype'] == 6 ? html += notverMsg : html += '<div class="attachInfo">附加信息：<xmp>' + notice_verifymsg + '</xmp></div>';
		};
		html += '<p class="findMode">' + getTimeStr(new Date(notice.createtime * 1000)) + '</p>';
		html += '</div>';
		html += '<div class="verFdBut" id="verify_group_' + notice['id'] + '">';
		switch (notice['accepttype']) {
			case 0: //待处理
				if(notice['noticetype'] == 7){
					break;
				}else if(notice['noticetype'] == 8){
					break;
				}
				html += '<div class="ver-tongyiBut">';
				html += '<div class="verAgree" onclick="' + mth + '(' + notice.id + ',1)"><span>同意</span></div>';
				html += '<div class="verXuanze">';
				html += "<div class=\"verXuanze-popup\">";
				html += "<div>"
				html += '<p onclick="' + mth + '(' + notice.id + ',1)">同意</p>';
				html += "</div>"
				html += "<div>"
				html += '<p onclick="' + mth + '(' + notice.id + ',2)">拒绝</p>';
				html += "</div>"
				html += "</div>";
				html += "</div>";
				html += "</div>";
				html += '<div class="ver-ElideBut" onclick="' + mth + '(' + notice.id + ',3)"><span>忽略</span></div>';
				break;
			case 1: //已同意
				if (notice['noticetype'] < 3) {
					html += '<div class="ver-yesBut">已同意</div>';
					break;
				};
				if (notice['noticetype'] == 5) {
					html += '<div class="verAgree" style="float:right" onclick="addMyGroup(' + notice.groupid + ')"><a class="btns"><span>邀请好友</span></a></div>';
				};
				break;
			case 2: //已拒绝
				html += '<div class="ver-yesBut">已拒绝</div>';
				break;
			case 3: //已忽略
				html += '<div class="ver-yesBut">已忽略</div>';
				break;
			case 4: //已忽略
				groupmsg = true;
				html += '<div class="ver-yesBut">'+ notice_verifymsg +'</div>';
				break;
		};
		html += "</div>";
		html += "</div>";
		html += "</dd>";
	};
	if (type == Print.REPLACE) {
		$("#groupmess").html(html);
	} else {
		$("#groupmess").prepend(html);
	};
	if( groupmsg ){
		$('.attachInfo').html(notverMsg);
	}
	$(".verXuanze").click(function() {
		$(this).find(".verXuanze-popup").show();
	});
};
$(".verFdTop li").click(function() {
	$(this).find(".trigon").show();
	$(this).siblings().find(".trigon").hide();
});
//点击叉号关闭上部提示信息
$(".F_close").click(function() {
	$(".addFriendTopTip").hide();
	$('.verFdMain ul li, .verGroupCon ul li').addClass('defuheitip');
});
$(".G_close").click(function() {
	$(".addGroupTopTip").hide();
	$('.verFdMain ul li, .verGroupCon ul li').addClass('defuheitip');
});
//点击上部提示信息刷新验证消息列表
function reFriend() {
	$("#userinfo").parent().removeClass('listempty');
	$(".addFriendTopTip").hide();
	$('.friend span').removeClass('emptyhand');
	$('.verFdMain ul li,.verGroupCon ul li').addClass('defuheitip');
	$(".verFriend").click();
	load(Verify.PERSON);
};
function reGroup() {
	$("#groupmess").parent().removeClass('listempty');
	$(".addGroupTopTip").hide();
	$('.groupn span').removeClass('emptyhand');
	$('.verFdMain ul li, .verGroupCon ul li').addClass('defuheitip');
	$(".groupMeal").click()
	load(Verify.GROUP);
};
//加云组
function addMyGroup(groupid) {
	var params = "{command:1005,params:{groupid:" + groupid + ",myuserid:" + userid + "}}";
	var resultS = sendCommand(params);
};