
var m_MsgPageSize = 20;
var m_MsgMonth = "";
var m_ShowTimeList = [];
var m_MinTick = 936262421150398406;
//var m_HisMsgList = [];//历史记录缓存
var m_GetHisByTremMinTick = 0;//获取历史记录MinTick
var m_BisSelectFriendFristFoad = false;//选择好友首次加载聊天记录滚动条定位


//重置历史消息记录参数
function ResetHisMsgPara() {
    m_MinTick = 936262421150398406;
    //m_MsgPageIndex = 0;
    m_MsgPageSize = 20;
    m_MsgMonth = "";
    m_ShowTimeList = [];
    m_HisMsgList = [];
}

//是否已经显示过此时间
function IsShowTime(timemark) {
    for (var i = 0; i < m_ShowTimeList.length; i++) {
        if (m_ShowTimeList[i] == timemark)
            return true;
    }
    return false;
}

//获取历史消息
function GetHisMsg() {
    if (m_NowSelectPid.length == 0)
        return;

    //防连击
    $("#btnLookMoreMsg").html("正在获取,请稍候...<br />");
    $("#btnLookMoreMsg").attr("onclick", "javascript:void(0);");

    //m_MsgPageIndex++;//下一页
    var strParaJson = $.toJSON({
        pid: m_NowSelectPid,
        //headimgkey: m_NowSelectFriendHeadImgKey,
        uin: m_NowSelectUin,
        month: m_MsgMonth,
        tick: m_MinTick,
        pagesize: m_MsgPageSize
    });
    talkObj.gethistmessage(strParaJson);
}

//选择好友主动加载一次对话记录
function SelectFriendFirstGetHisMsg() {
	if (m_NowSelectPid.length == 0)
		return;
	GetHisMsg();
	m_BisSelectFriendFristFoad = true;
}

//回执
function AsyncGetHistMessageResult(jsonResult) {
    if (jsonResult.success) {
        if ($("#btnLookMoreMsg").length > 0) {
            $("#btnLookMoreMsg").remove();
        }

        if (jsonResult.pid != m_NowSelectPid)
        	return;
        //if (m_BisSelectFriendFristFoad) {
        //	$("#divTalkContent").empty();
        //}
        //聊天记录
        var msgList = jsonResult.result.msgs;
        if (msgList.length > 0) {
        	for (var i = 0; i < msgList.length; i++) {
        		if ($("#divMsg" + msgList[i].msgid).length > 0) {
        			$("#divMsg" + msgList[i].msgid).remove();
        		}
        		if (IsWritePage(msgList[i])) {
        			$("#divTalkContent").prepend(MakeNewMsgHtml(msgList[i]));
        			if (msgList[i].msgtype == "11") {
        				initbaidumap(msgList[i], "width:260px;height:240px;", "Now");
        			}
        			//时间显示处理，已经显示过，或者本次读取最后一条
        			if (!IsShowTime(msgList[i].sorttime) || (i + 1) == msgList.length) {
        				m_ShowTimeList.push(msgList[i].sorttime);
        				if (msgList[i].msgtype == "11") {
        					initbaidumap(msgList[i], "width:260px;height:240px;", "Now");
        				}
        			}
        		}
            }
        	var strContent = "<p><a id=\"btnLookMoreMsg\" href=\"javascript:void(0);\" class=\"moremessage-m\" onclick=\"GetHisMsg();\">更多聊天记录</a></p><br />";
            $("#divTalkContent").prepend(strContent);

        } else {
            var strContent = "<span class=\"moremessage-m\">没有更多记录了...</span><br />";
            $("#divTalkContent").prepend(strContent);
        }
        m_MsgMonth = jsonResult.result.month;
        m_MinTick = jsonResult.result.mintick;
        //m_MsgPageIndex = Number(jsonResult.result.pageindex);
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
	//首次选择好友加载对话记录滚动条定位到最下方
    if (m_BisSelectFriendFristFoad) {
    	$('#divTalkContentOutside').scrollTop($('#divTalkContentOutside')[0].scrollHeight);
    	m_BisSelectFriendFristFoad = false;
    }
    $("#divTalkContent i[data-rel=popover]").popover();
}

//【已发送】向下插一条消息
function AppendMsg(msgList) {
	for (var i = 0; i < msgList.length; i++) {
		if ($("#divMsg" + msgList[i].msgid).length > 0) {
			$("#divMsg" + msgList[i].msgid).remove();
		}
		$("#divTalkContent").append(MakeNewMsgHtml(msgList[i]));
		//InputImportNowExcelCacheMsgItem(msgList[i]);
		//地图
		if (msgList[i].msgtype == "11") {
			initbaidumap(msgList[i], "width:260px;height:240px;","Now");
		}
		//tick reset min value
		if (Number(msgList[i].tick) < m_MinTick) {
			m_MinTick = Number(msgList[i].tick);
		}
	}
	document.getElementById("divTalkContentOutside").scrollTop = document.getElementById("divTalkContentOutside").scrollHeight;
    $("#divTalkContent i[data-rel=popover]").popover();
}

//【发送中】向下插一条消息
function AsyncSendMsgResult(jsonResult) {
	if (jsonResult.success) {
		if ($("#divMsg" + jsonResult.msg.msgid).length > 0) {
			$("#divMsg" + jsonResult.msg.msgid).remove();
		}
		$("#divTalkContent").append(MakeNewMsgHtml(jsonResult.msg));

	} else {
		ShowError("myPageAlert", jsonResult.error);
	}
	document.getElementById("divTalkContentOutside").scrollTop = document.getElementById("divTalkContentOutside").scrollHeight;
}

	//********************************************对话窗体右侧历史记录start*******************************************
	//查询历史记录（通过条件）
	function SerchHisByTrem() {
    var txtTimeFromQuery = $("#txtTimeFromQuery");//查询开始时间
    var txtTimeEndQuery = $("#txtTimeEndQuery");//查询结束时间
    if ($("#txtTimeFromQuery").val() == "" || $("#txtTimeEndQuery").val() == "") {
        ShowError("myPageAlert", "开始时间或结束时间不能为空!");
        return;
    } else {
        var myDate = new Date();//当前日期
        var taday = myDate.toLocaleTimeString();
        var time1 = Date.parse(new Date("20" + $("#txtTimeFromQuery").val()));
        var time2 = Date.parse(new Date("20" + $("#txtTimeEndQuery").val()));
        if (time1 > time2) {
            ShowError("myPageAlert", "开始时间不能大于结束时间!");
            return;
    }

	}
	m_GetHisByTremTick = 0;
	var strTrem = $("#SerchHisTrem");//搜索框内容
		//var SearchHisType = $("#SerchHisType option:selected");
	var objhidDocUin = $("#hidDocUin").val();
	$("#divTalkHistoryContent").html("");
	$("#BtnSearchHisUp").attr('disabled', "true");
	var strParaJson = $.toJSON({
			pid: m_NowSelectPid,
			tick: 0,
		//type: SearchHisType.val(),//三个月，一个月，全部
			starttime: txtTimeFromQuery.val(),//开始时间
			endtime: txtTimeEndQuery.val(),//结束时间
			searchkey: $.trim(strTrem.val()),
			pagesize: 20,
			pagetype: 1,
			uin: objhidDocUin
	});
	talkObj.geihislistbysearch(strParaJson);
}

	//查询历史记录（通过条件）回调
	function AsyncGeiHisListBySearchResult(jsonResult) {
	if (jsonResult.success) {
		if ($("#btnRightLookMoreMsg").length > 0) {
			$("#btnRightLookMoreMsg").remove();
	}

		//聊天记录
		var msgList = jsonResult.result.msgs;
		if (msgList.length > 0) {
			for (var i = 0; i < msgList.length; i++) {
				$("#divTalkHistoryContent").prepend(MakeNewMsgHtml(msgList[i], '1'));//
				if (msgList[i].msgtype == "11") {
					initbaidumap(msgList[i], "width:180px;height:180px;", "His");
			}
				//时间显示处理，已经显示过，或者本次读取最后一条
				if (!IsShowTime(msgList[i].sorttime) || (i + 1) == msgList.length) {
					if (msgList[i].msgtype == "11") {
						initbaidumap(msgList[i], "width:180px;height:180px;", "His");
				}
			}
				InputImportExcelCacheMsgItem(msgList[i]);
		}
			var strContent = "<p><a id=\"btnRightLookMoreMsg\" href=\"javascript:void(0);\" class=\"moremessage-m\" onclick=\"GetMoreHisMsg();\">更多聊天记录</a></p><br />";
			$("#divTalkHistoryContent").prepend(strContent);

		} else {
			var strContent = "<span class=\"moremessage-m nomorehis\">没有更多记录了...</span><br />";
			$(".nomorehis").remove()
			$("#divTalkHistoryContent").prepend(strContent);
	}

		m_GetHisByTremMinTick = jsonResult.result.mintick;
		//m_MsgPageIndex = Number(jsonResult.result.pageindex);
	} else {
		ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
	}
}
	//清除查询历史纪录条件
	function deleSearchHisTrem() {
	$("#SerchHisTrem").val("");
}

	//通过查询条件查询历史记录翻页
	function GetMoreHisMsg() {
	var strTrem = $("#SerchHisTrem");
	$("#btnRightLookMoreMsg").html("正在获取,请稍候...<br />")
	$("#btnRightLookMoreMsg").attr("onclick", "javascript:void(0);");
		//var SearchHisType = $("#SerchHisType option:selected");
	var objhidDocUin = $("#hidDocUin").val();
	var txtTimeFromQuery = $("#txtTimeFromQuery");//查询开始时间
	var txtTimeEndQuery = $("#txtTimeEndQuery");//查询结束时间
	$("#BtnSearchHisUp").removeAttr("disabled");
	var strParaJson = $.toJSON({
			pid: m_NowSelectPid,
			tick: m_GetHisByTremMinTick,
		//type: SearchHisType.val(),
			starttime: txtTimeFromQuery.val(),//开始时间
			endtime: txtTimeEndQuery.val(),//结束时间
			searchkey: $.trim(strTrem.val()),
			pagesize: 20,
			pagetype: 2,
			uin: objhidDocUin
	});
	talkObj.geihislistbysearch(strParaJson);
}
	//********************************************对话窗体右侧历史记录End*******************************************
	//时间插件
	function customquery() {
    $('#txtTimeFromQuery').datetimepicker({
    		language: "zh-CN",
    		weekStart: 1,
    		todayBtn: 1,
    		autoclose: true,
    		todayHighlight: 1,
    		startView: 2,
    		forceParse: 0,
    		showMeridian: 1,
    		minView: "month",
    		format: "yyyy-mm-dd"
    });
    $('#txtTimeEndQuery').datetimepicker({
    		language: "zh-CN",
    		weekStart: 1,
    		todayBtn: 1,
    		autoclose: true,
    		todayHighlight: 1,
    		startView: 2,
    		forceParse: 0,
    		showMeridian: 1,
    		minView: "month",
    		format: "yyyy-mm-dd"
    });
    $("#txtTimeFromQuery").val(homeObj.getmonthday());//默认开始日期
    $('#txtTimeFromQuery').datetimepicker('update');
    $("#txtTimeEndQuery").val(homeObj.gettoday());//设置默认当前日期
}
	//-------------------------------------------好友消息转发(转发给当前好友)-----------------------start
	//微信好友消息转发单击事件，获得当前微信号所有好友
	var m_Friends = [];//所有好友缓存
	var m_Usernames = [];//需要转发的好友的username的缓存
	var m_Pids = [];//需要转发的好友的pid
	//与好友聊天消息转发单击事件
	function MsgForwardFriend(msgid, content, msgtype, filename, para) {
		//不是群发，设置按钮初始样式
    $("#FriendForwardFriendBtn").attr("class", "btn btn-success");
    $("#FriendForwardBatchBtn").attr("class", "btn btn-default");
    $("#ConfirmForwarding").attr("onclick", "FriendMsgMask()");
    m_BachUserName = [];
    m_Usernames = [];//清空
    $("#ForwardTitle").text("转发消息到好友");
    m_Para = para;
    m_Friends = [];//清空所有好友缓存
    m_Pids = [];//清空选中的pid
    m_BatchContent = decodeURI(content);
    m_MsgType = msgtype;
    $("#MsgForward").show();
    $("#MsgForwardMask").show();
    var json = $.toJSON({
    		username: $("#hidDocUserName").val(),
    		wechatkey: $("#hidDocWechatKey").val()
    });
    talkObj.getonewechatallfriends(json);
}
	//好友消息转发给好友按钮
	function FriendForwardFriend() {
    $("#ForwardTitle").text("转发消息到好友");
    $("#MsgForward").show();
    $("#MsgForwardMask").show();
    m_BachUserName = [];//清空选中的群的username
    m_Usernames = [];
    m_Pids = [];
    $("#FriendForwardFriendLi").addClass("class", "active");
    $("#FriendForwardBatchLi").removeClass("class", "active");
    $("#ConfirmForwarding").attr("onclick", "FriendMsgMask()");
    var DocUserName = m_IsBatch ? "" : $("#hidDocUserName").val();
    var json = $.toJSON({
    		username: DocUserName,
    		wechatkey: $("#hidDocWechatKey").val()
    });
    talkObj.getonewechatallfriends(json);
}
	//好友消息转发给群按钮
	function FriendForwardBatch() {
    $("#ForwardTitle").text("转发消息到群");
    $("#MsgForward").show();
    $("#MsgForwardMask").show();
    m_Usernames = [];//清空选中的好友的username
    m_BachUserName = [];
    m_Pids = [];
    $("#FriendForwardFriendLi").removeClass("class", "active");
    $("#FriendForwardBatchLi").addClass("class", "active");
    $("#ConfirmForwarding").attr("onclick", "ConfirmForward()");
    var batchusername = m_IsBatch ? m_NowSelectBatchKey : "";
    var json = $.toJSON({
    		wechatkey: $("#hidDocWechatKey").val(),
    		batchusername: batchusername
    });
    talkObj.getonewechatallbatch(json);
}

	function AsyncGetOneWechatAllFriendsResult(jsonResult) {
    if (jsonResult.success) {
        m_Friends = jsonResult.list;//得到当前微信所有好友，并放入缓存中
        AllFriendCommon("");
    } else {
        ShowError("myPageAlert", "获取所有好友异常:" + jsonResult.error);
	}
    $("#AllFriends").modal("show");
    $("#MsgForward").hide();
    $("#MsgForwardMask").hide();
}
//	//好友按照备注或昵称筛选
//	function FriendssCreen() {
//    AllFriendCommon($("#FriendScreen").val());
//}
	function AllFriendCommon(name) {
	    var strselval = $.trim(name);
	    //查询按钮
	    var strcontent = "";
	    for (var i = 0; i < m_Friends.length; i++) {
	        if (m_Friends[i].remarkname.indexOf(strselval) > -1 || m_Friends[i].nickname.indexOf(strselval) > -1)
	            var stralrdeyselect = "";
	        for (var j = 0; j < m_Usernames.length; j++) {
	            if (m_Usernames[j] == m_Friends[i].username) {
	                stralrdeyselect = "select";
	                break;
	            }
	        }
	        if (m_Friends[i].nickname.indexOf(strselval) != -1 || m_Friends[i].remarkname.indexOf(strselval) != -1) {
	            var strName = m_Friends[i].remarkname == "" ? m_Friends[i].nickname : m_Friends[i].remarkname + "(" +m_Friends[i].nickname + ")";
	            var strnickoremarkname = strName.length > 19 ? strName.substring(0, 18) + ".." : strName;
	            strcontent += "<li class=\"col-md-4 " + stralrdeyselect + "\" id=\"AllFriend" + i + "\" onclick=\"AddUsername('" + m_Friends[i].pid + "','" + m_Friends[i].username + "','" + i + "')\">";
	            strcontent += "<div class=\"col-md-12 friends-card\">";
	            strcontent += "<img onerror=\"nofind()\" src=\"" + m_Friends[i].headimg + "\" class=\"img-circle\" />";

	            strcontent += "<span class=\"transform-name\">" + strnickoremarkname + "</span>";
	            strcontent += "</div>";
	        }
	        strcontent += " </li>";
	    }
	    $("#FriendForwardFriendLi").attr("class", "active");
	    $("#FriendForwardBatchLi").attr("class", "");
	    $("#AllFriendsCurrent").html(strcontent);
	}
	//选中好友单击事件
	function AddUsername(pid, username, index) {
	if (!$("#AllFriend" +index).hasClass("select")) {
        m_Usernames.push(username);
        m_Pids.push(pid);
        $("#AllFriend" +index).addClass("select");
	} else {
        for (i in m_Usernames) {
            if (m_Usernames[i] == username) {
                m_Usernames.splice(i, 1);
        }
	}
        for (i in m_Pids) {
            if (m_Pids[i] == m_Pids) {
                m_Pids.splice(i, 1);
        }
	}
        $("#AllFriend" +index).removeClass("select");
	}
}
	//确认转发
	function FriendMsgMask() {
    if (m_Usernames.length == 0) {
        ShowMsg("myPageAlert", "请选择转发的好友!");
        return;
	}
    var strUsername = "";
    var strPids = "";
    for (var i = 0; i < m_Usernames.length; i++) {
        strUsername += m_Usernames[i] + ",";
	}
    for (var i = 0; i <m_Pids.length; i++) {
        strPids += m_Pids[i] + ",";
	}
    strPids = strPids.substring(0, strPids.length -1);
    strUsername = strUsername.substring(0, strUsername.length -1);
    var strParaJson = $.toJSON({
    		wechatkey: $("#hidDocWechatKey").val(),
    		uin: $("#hidDocUin").val(),
    		username: strUsername,
    		pid: strPids,
    		msgtype: m_MsgType,
    		isbatch: false,
    		content: m_BatchContent,
    		para: m_Para,
    		url: m_BatchContent
    });
    talkObj.batchorfriendturnsendmsg(strParaJson);
}
	//-------------------------------------------好友消息转发(转发给当前好友)-----------------------end