var m_NewLoginWechatKey;
var m_ResetLoginStateTimer;
var m_ResetLoadingDivFlag = 0;
var isfirst = 0;// isfirst=0代表初始化调用
var m_BisFirstLoad = true;//页面是否首次加载
var m_NowOnlineWechay = 0;//当前在线微信帐号数量//圆形图用
var m_NowDisconnectWechat = 0;

$(function () {
    lanPosScroll();
    homecss();
    $(function () { $("[data-toggle='tooltip']").tooltip(); });
    //$("#wechatMess").modal("show");
    //homeObj.pageload();
    $("#myPageAlert").hide();
   
	//绑定微信号
    BindWechats();
    //Circulargraph(m_NowOnlineWechay, m_NowDisconnectWechat)
	//定时刷新首页为信号
    setInterval(BindWechats, 3000);
    //setInterval(Circulargraph(m_NowOnlineWechay, m_NowDisconnectWechat), 10000);
	
	
	// 回访初始化
	initTask();

	//获取错失对话
	//BindTodayTalk();


	//GetSystemversion();//绑定版本信息

    //获取企业信息
    //var systemnews = $.parseJSON(homeObj.getdebuginfo());
    //$("#imgLogo").attr("src", "../img/wkdd" + systemnews.companyid + ".png");
    //$("#txtSystemName").html(systemnews.systemname);
	
 

    //ClickTodayTalkDay(0);

    $(".panel-title").click(
      function () {
          $(".panel-title > i").removeClass("fa-angle-down").addClass("fa-angle-up");
      },
      function () {
          $(".panel-title > i").removeClass("fa-angle-up").addClass("fa-angle-down");
      }
    );
    
});

function BindWechats() {
    //绑定微信号列表
    homeObj.getwechatlist();
}

function homecss() {
    $(".account").css({
        height: $(window).height() - 230
    });
    $(".left").css({
        height: $(window).height()
    });
    $(".right").css({
        height: $(window).height()
    }); 
    $(".card-box").css({
        height: $(window).height()-238
    });
}

$(window).resize(function () {
    homecss();
});

//function AsyncPageLoadResult(jsonResult) {
//    $("#divLoadData").html(jsonResult);
//}

function AsyncGetWechatListResult(jsonResult) {
	var nNoReadCount = 0;
	var nFriendCount = 0;//好友数量
	var nBatchCount = 0;//群数量
	var strContent = "";
	var nOnlineCount = 0;
	var nDisconnectCount = 0;
	//当前登录情况提醒
	if (jsonResult.loginwechatcount > 0) {
		if (jsonResult.wechats.length == 0) {
			alwaysShowMsg("myPageAlert", "共" + jsonResult.loginwechatcount + "个微信，正在努力加载第1个微信数据！");
		} else {
			alwaysShowMsg("myPageAlert", "共" + jsonResult.loginwechatcount + "个微信，成功加载第" + jsonResult.wechats.length + "个微信数据，正在努力加载第" + (jsonResult.wechats.length + 1) + "个微信数据！");
		}
	} else {
		$("#myPageAlert").hide();
	}

	for (var i = 0; i < jsonResult.wechats.length; i++) {
		var item = jsonResult.wechats[i];
		//好友数量
		nFriendCount += Number(item.friendcount);
		nBatchCount += Number(item.batchcount);
		//性别
		var strSexCss = "";
		if (item.sex == "1") {
			strSexCss = "<i class=\"icon iconfont icon-man\"></i>";
		} else if (item.sex == "2") {
			strSexCss = "<i class=\"icon iconfont icon-woman\"></i>";
		} else {
			strSexCss = "<i class=\"icon iconfont icon-nosex\"></i>";
		}

		var strBtnRemarkHtml = "";//修改微信号备注
		var strResetLoginHtml = "";//重新登录微信号
		var strWechatTransferCus = "";//转移微信号
		var strWechatState = "";//微信号在线状态
		var strRemark = "备注：" + (item.remark == null ? "-" : item.remark) + "";
		var strzhuxiao = item.uin == null || item.uin.length == 0 ? "none" : "block";
		var strUin = item.uin == null ? "-" : item.uin;
		var strUinHtml = "ID：" + strUin;
		//在线状态
		var strStateHtml = "";
		if (item.loginstate == "8") {
			//在线
			nOnlineCount++;
			strStateHtml = item.onlinetimemark;
			strWechatState = "<div class=\"wechat-card\">";
			if (item.uin != null) {
				strBtnRemarkHtml = "<li onclick=\"UpdateWechatRemark(event,'" + encodeURI(item.remark) + "','" + item.uin + "');\">备注</li>";
				strWechatTransferCus = "<li onclick=\"WechatTransferCusShow('" + item.uin + "','','1')\">转移</li>";
			}
		}
		else if (item.loginstate == "7") {
			//初始化好友
			nOnlineCount++;
			strStateHtml = item.wechatstatemark;
			strWechatState = "<div class=\"wechat-card\">";
			strResetLoginHtml = "<li onclick=\"ShowAddModel()\">重登</li>";
		}
		else if (item.loginstate == "9") {
			//离线（假死）
			nDisconnectCount++;
			strStateHtml = "网络异常，请重新扫码登录！";
			strWechatState = "<div class=\"wechat-card offline\">";
			strResetLoginHtml = "<li onclick=\"ShowAddModel()\">重登</li>";
		}
		else if (item.loginstate == "10") {
			//登出
			nDisconnectCount++;
			strStateHtml = "已登出微信！请重新扫码登录！";
			strWechatState = "<div class=\"wechat-card quite\">";
			strResetLoginHtml = "<li onclick=\"ShowAddModel()\">重登</li>";
		}
		else if (item.loginstate == "12") {
			//手机网络异常
			nDisconnectCount++;
			strStateHtml = "手机网络异常！请检查手机网络情况！";
			strWechatState = "<div class=\"wechat-card offline\">";
			strResetLoginHtml = "<li onclick=\"ShowAddModel()\">重登</li>";
		}
		else {
			continue;
		}

		//未读消息
		var nnoreadmsgct = "";
		if (Number(item.noreadmsgcount) > 0 || Number(item.noreadbatchmsgcount) > 0) 
			nnoreadmsgct = Number(item.noreadmsgcount) + Number(item.noreadbatchmsgcount)
		var strFriendCount = (item.loginstate != "8" || item.friendcount == null || strUin == null || item.friendcount == "0") ? "-" : item.friendcount;
		var strBatchCount = (item.loginstate != "8" || item.batchcount == null || strUin == null || item.batchcount == "0") ? "-" : item.batchcount;
		var goTalkClick = item.loginstate == "8" ? "onclick=\"GoTalk('" + item.wechatkey + "');\"" : "style='cursor:default'";

		strContent += "<li class=\"col-xs-3 pad-6\" " + goTalkClick + ">"
		strContent += strWechatState; //strFriendCount == "-" ? "<div class=\"wechat-card offline\">" : "<div class=\"wechat-card\">"; //是否掉线
		strContent += "<img src=\"" + item.headimgurl + "\" width=\"60\" onerror='nofind()'onclick=\"WechatMessShow(event,'" + encodeURI(item.headimgurl) + "','" + encodeURI(item.nickname) + "','" + item.sex + "','" + item.uin + "','" + strStateHtml + "','" + item.remark + "','" + strFriendCount + "','" + strBatchCount + "')\" />"
		strContent += "<div class=\"wechat-mess\">"
		strContent += "<span class=\"h2\">" + item.nickname + "</span> " + strSexCss + "";
		strContent += "<p class=\"p2\" style=\"margin-bottom:5px;\"><span class=\"color-gry\"></span>" + strUinHtml + "</p>"
		strContent += "<p class=\"p2\"><span class=\"color-gry\"></span>" + strRemark + "</p>"
		strContent += "</div>"
		strContent += "<div class=\"check-more\">"
		strContent += "<button class=\"btn btn-link\">"
		strContent += "<i class=\"icon iconfont icon-more\" onclick=\"Antipenetration(event)\"></i>"
		strContent += "<div class=\"more-menu\">"
		strContent += "<ul class=\"list-unstyled\">"
		strContent += strBtnRemarkHtml;
		strContent += strWechatTransferCus;
		strContent += "<li onclick=\"NoticePhone(" + strUin + ")\">通知</li>"
		strContent += strResetLoginHtml
		strContent += "<li class=\"color-red\" onclick=\"ShowDeleteWechatModel('" + item.wechatkey + "','" + escape(item.nickname) + "','" + item.uin + "');\">注销</li>"
		strContent += "</ul>"
		strContent += "</div>"
		strContent += "</button>"
		strContent += "</div>"
		strContent += " <div class=\"new-mess\"><span>" + nnoreadmsgct + "</span></div>"
		strContent += "</div>"
		strContent += "</li>"
	}
	strContent += "<li class=\"col-xs-3 pad-6\">"
	strContent += "<div class=\"wechat-card\" onclick=\"ShowAddModel();\">"
	strContent += "</div>"
	strContent += "</li>";


	$("#divWechatsData").empty();
	$("#divWechatsData").html(strContent);
	$("#spOLDisconnect").empty();
	$("#spOLDisconnect").html(nDisconnectCount);
	$("#spOLOnline").empty();
	$("#spOLOnline").html(nOnlineCount);

	//统计微信号信息展示
	$("#PStatisticsWechatOnlCT").html(nOnlineCount);
	$("#PStatisticsDroCT").html(nDisconnectCount);
	$("#PStatisticsWechatCT").html(Number(nOnlineCount) + Number(nDisconnectCount));

	
	$("#spCountFriend").empty();
	$("#spCountFriend").html(nFriendCount);
	$("#spCountBatch").empty();
	$("#spCountBatch").html(nBatchCount);

	m_NowOnlineWechay = nOnlineCount;
	m_NowDisconnectWechat = nDisconnectCount;
	//首页统计图
	//if (jsonResult.wechats.length >= jsonResult.loginwechatcount) {
	//	if (m_BisFirstLoad)
	//		Circulargraph(nOnlineCount, nDisconnectCount);
	//	m_BisFirstLoad = false;
	//} else {
	//	Circulargraph(nOnlineCount, nDisconnectCount);
	//}

	//m_ResetLoadingDivFlag++;
	//if (jsonResult.wechats.length > 0 || m_ResetLoadingDivFlag >= 5) {
	//	$("#ChangeUserLoad").hide();
	//	m_ResetLoadingDivFlag = 0;
	//}
	//不是当前登录客服隐藏添加微信号和转移功能
	if (homeObj.getnowcusislogincus() != true) {
		//$(".shift").hide();//转移微信号
		$("#liAddWechatsShow").hide();
	}
	
}
//微信号信息展示（采用传值方式，加增加载速度）
function WechatMessShow(event,headimg,nickname,sex,uin,onltime,remarkn,fricount,batchcount) {
	Antipenetration(event);
	var strSexCss = "";
	if (sex == "1") {
		strSexCss = "<i class=\"icon iconfont icon-man\"></i>";
	} else if (sex == "2") {
		strSexCss = "<i class=\"icon iconfont icon-woman\"></i>";
	} else {
		strSexCss = "<i class=\"icon iconfont icon-nosex\"></i>";
	}
	remarkn = remarkn.length > 0 ? remarkn : "-";
	batchcount = batchcount.length > 0 ? batchcount : "-";
	$("#ModalpWechatHead").attr("src",decodeURI(headimg));
	$("#ModalpWechatNickName").html(decodeURI(nickname) + strSexCss);
	$("#ModalpWechatId").html(uin);
	$("#ModalpWechatOnlineTime").html(onltime);
	$("#ModalpWechatRemark").html(remarkn);
	$("#ModalpWechatFriendCount").html(fricount);
	$("#ModalpWechatBatchCount").html(batchcount);

	$("#wechatMess").modal("show");
}

//显示添加公众号模态框
function ShowAddModel() {
    $("#AddWechatModalTitle").html("正在获取二维码...");
    $("#imgAddWechatQr").attr("src", "");
    $("#AddWechatModal").modal({ backdrop: 'static', keyboard: false });
    homeObj.startwechatlogin();
}

//微信登录【获取二维码】回调
function AsyncStartWechatLoginResult(jsonResult) {
    if (jsonResult.success) {
        m_NewLoginWechatKey = jsonResult.newwechatkey;
        $("#imgAddWechatQr").attr("src", jsonResult.qrpath);
        $("#AddWechatModalTitle").html("请使用微信扫码登录...");
        $("#qrLoading").hide();
        //开始监听初始化状态
        m_ResetLoginStateTimer = setInterval(GetNewWechatLoginState, 3000);
    } else {
        $("#AddWechatModalTitle").html(jsonResult.error);
        ShowError("myPageAlert", jsonResult.error);
    }
}

//监听初始化状态
function GetNewWechatLoginState() {
    if (m_NewLoginWechatKey.length > 0)
        homeObj.getwechatloginstate(m_NewLoginWechatKey);
}

//微信登录结果
function AsyncGetWehcatLoginStateResult(jsonResult) {
    if (jsonResult.success) {
        var objAddWechatModalTitle = $("#AddWechatModalTitle");
        if (jsonResult.state == -1) {
            //等待扫码
            objAddWechatModalTitle.html("您的微信帐号异常！");
            clearInterval(m_ResetLoginStateTimer);
        } else if (jsonResult.state == 13) {
        	//等待扫码
        	objAddWechatModalTitle.html("新注册的帐号不允许登录！");
        	clearInterval(m_ResetLoginStateTimer);
        }
        if (jsonResult.state == 2) {
            //等待扫码
            objAddWechatModalTitle.html("请使用微信扫描下方二维码进行登录");
        } else if (jsonResult.state == 3) {
            //已经扫码
            objAddWechatModalTitle.html("已扫码，请在手机上确认登录");
        } else if (jsonResult.state == 4) {
            //超时
            objAddWechatModalTitle.html("扫码超时，请关闭本对话框重新登录微信");
        } else if (jsonResult.state == 5 || jsonResult.state == 6) {
            //正在初始化
            objAddWechatModalTitle.html("正在初始化微信身份信息");
        } else if (jsonResult.state == 7) {
            //已成功登录
            clearInterval(m_ResetLoginStateTimer);
            BindWechats();
            $("#AddWechatModal").modal("hide");
            //立即同步
            //homeObj.syncserverdata();
            ////正在初始化好友
            //objAddWechatModalTitle.html(jsonResult.mark);
        } else if (jsonResult.state == 8) {
            //已成功登录
            clearInterval(m_ResetLoginStateTimer);
            BindWechats();
            $("#AddWechatModal").modal("hide");
        } else if (jsonResult.state == 9) {
            clearInterval(m_ResetLoginStateTimer);
            objAddWechatModalTitle.html("登录失败，请重试！");
        }
    } else {
        ShowError("myPageAlert", "登录失败：" + jsonResult.error);
        clearInterval(m_ResetLoginStateTimer);
    }
}

function CloseNewWechat() {
    clearInterval(m_ResetLoginStateTimer);
    $("#AddWechatModal").modal("hide");
}

function AsyncSyncServerDataResult(result) {
    if (result == "1") {
        $("#AddWechatModalTitle").html("登录成功！");
        $("#AddWechatModal").modal("hide");
        BindWechats();
    }
}

//打开确认删除消息框
function ShowDeleteWechatModel(wechatkey, nickname, uin) {
    Antipenetration(event);
	if (wechatkey.length == 0)
		return;
	var nicknamemark = unescape(nickname).replace(/[\n]/ig, '<br/>');
	$("#spDeleteWechatMark").html("确认要注销微信【" + nicknamemark + "】吗？");
	$("#hidDeleteWechatKey").val(wechatkey);
	$("#hidDeleteWechatUin").val(uin);

	$("#DeleteWechatModal").modal("show");
}

//注销微信号
function SetDeleteWechat() {
	var objHidWechatKey = $("#hidDeleteWechatKey");
	var objHidWechatUin = $("#hidDeleteWechatUin");
	if (objHidWechatKey.val().length == 0) {
		return;
	}
	var strJson = $.toJSON({
		wechatkey: objHidWechatKey.val(),
		uin: objHidWechatUin.val()
	});

	homeObj.deletewechatitem(strJson);
	$("#DeleteWechatModal").modal("hide");
}

//注销微信号回调方法
function AsyncDeleteWechatResult(jsonResult) {
    if (jsonResult.success) {
        //重新绑定
        BindWechats();
    } else {
        ShowError("myPageAlert", "操作失败：" + jsonResult.error);
    }
}



//模态框左侧导航样式滚动
function lanPosScroll() {
    /*右侧区域滚动切换*/
    var index = 0;              //索引值
    var shortcutBox = $('.modal .modal-dialog .shortcut-add-box');              //快捷方式展示区
    var shortcutBoxList = $('.shortcut-add-box-right .shortcut-element-list');  //快捷方式列表

    $('.lanPos').css('top', $('.shortcut-add-box-left .active').position().top);
    $('.shortcut-add-box-left ul li').hover(function () {
        $('.lanPos').css('top', $(this).position().top);
    }, function () {
        $('.lanPos').css('top', $('.shortcut-add-box-left .active').position().top);
    })

    //为左侧导航添加active点击样式
    $('.shortcut-add-box-left ul li').click(function () {
        for (var i = 0; i < $('.shortcut-add-box-left ul li').size() ; i++) {
            if (this == $('.shortcut-add-box-left ul li').get(i)) {
                $('.shortcut-add-box-left ul li').eq(i).addClass('active');
            } else {
                $('.shortcut-add-box-left ul li').eq(i).removeClass('active');
            }
        };
        index = $('.shortcut-add-box-left ul li').index(this);
        //索引右侧快捷方式列表,找到当前点击的列表
        var s_box_cur = shortcutBoxList.eq(index)
        var posi = s_box_cur.position();
        shortcutBox.animate({ scrollTop: posi.top }, 200);
    })
};




//版本信息绑定
function GetSystemversion() {
    var systemver = homeObj.getsystemversion();
    $("#systemversion").html("当前版本：v" + systemver);
}

//绑定企业版本弹窗
function GetSystemversionShow() {
    $("#modalVersionMessage").modal("show");
}


//修改微信号备注弹窗
function UpdateWechatRemark(event, remarkname, uin) {
	Antipenetration(event);
    if (uin.length < 1) {
        ShowMsg("myPageAlert", "所选择微信号不可以修改备注！");
    } else {

        $("#RemarkName").val(decodeURIComponent(remarkname));
        $("#Uin").val(uin);
        $("#UpdateWechatRemarkModel").modal("show");
    }
}
//修改微信号备注提交
function UpdateWechatRemarkName() {
    var strJson = $.toJSON({
        uin: $("#Uin").val(),
        remark: $("#RemarkName").val()
    });
    homeObj.setremarkname(strJson);
}
//修改微信号备注回调
function AsyncSetRemarkNameResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "操作成功！");
    } else {
        ShowError("myPageAlert", "操作失败：" + jsonResult.error);
    }
    $("#UpdateWechatRemarkModel").modal("hide");
}

function gotoTalk(uin, pid) {
    $("#DivAllTab").hide();
    event.cancelBubble = true;//禁止触发父级div事件
    var wechatkey = homeObj.getwechatkeybyuin(uin + "");
    if (wechatkey.length == 0) {
        ShowError("myPageAlert", "该微信不在线或者在其它客服处登录！");
    } else {
        window.location.href = "talk.html?wechatkey=" + wechatkey + "&pid=" + pid;
    }
}
//删除将错失对话
function deletemisstalk(uin,pid) {
	var strJson = $.toJSON({
		uin: uin,
		pid:pid
	});
	homeObj.deletemisstalk(strJson);
}
//删除将错失对话回调
function AsyncDeleteMissTalkResult(jsonResult) {
	if (jsonResult.success) {
		homeObj.getmisstalk();
	} else {
		ShowError("myPageAlert", "操作失败：" + jsonResult.error);
	}
}

//通知手机端
function NoticePhone(uin) {
    Antipenetration(event);
	$("#imgFindPhone").attr("src", "../img/find-phone.gif");
	$("#hFindPhone").html("正在通知所绑定手机！");
	$("#divFindPhone").modal("show");
	var strJson = $.toJSON({
		uin: uin
	});
	homeObj.noticephone(strJson);
}

//通知到手机端回调
function AsyncNoticePhoneResult(jsonResult) {
	if (jsonResult.success) {
		$("#hFindPhone").html("所绑定的手机正在震动");
	} else {
		if (jsonResult.error == "no matching phone!") {
			$("#hFindPhone").html("没有绑定手机！");
		} else if (jsonResult.error == "no send type") {
			$("#hFindPhone").html("未知的手机类型！");
		} else {
			$("#hFindPhone").html("没有绑定手机！");
		}
		$("#imgFindPhone").attr("src", "../img/no-find-phone.png");
	}
}

//=============================================================回访=======================================================stat//
var taskIsfirst = true;
//回访相关控件初始化
function initTask() {
    $('#txtTimeFrom').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yyyy-mm-dd"
    });
    $('#txtTimeTo').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yyyy-mm-dd"
    });
    $('#txtReturnVisitTime').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yyyy-mm-dd"
    });

    $('#txtTimeTo').val(homeObj.gettoday());
    $('#txtTimeFrom').val(homeObj.gettoday());

    BindData();
}

//选择时间段
function selectDate(section) {
    var myDate = new Date();
    switch (section) {
        case 1://今天
            $('#txtTimeFrom').val(homeObj.gettoday());
            $('#txtTimeTo').val(homeObj.gettoday());
            break;
        case 2://明天
            $('#txtTimeFrom').val(homeObj.gettomorrowday());
            $('#txtTimeTo').val(homeObj.gettomorrowday());
            break;
        case 3://本周
            $('#txtTimeFrom').val((myDate.getFullYear()) + "-" + Appendzero(myDate.getMonth() + 1) + "-" + Appendzero(myDate.getDate()));
            var nowTime = myDate.getTime();
            var day = myDate.getDay();
            var oneDayLong = 24 * 60 * 60 * 1000;
            var SundayTime = nowTime + (7 - day) * oneDayLong;
            var sunday = new Date(SundayTime);
            $('#txtTimeTo').val((sunday.getFullYear()) + "-" + Appendzero(sunday.getMonth() + 1) + "-" + Appendzero(sunday.getDate()));
            break;
        case 4://下周
            var nowTime = myDate.getTime();
            var day = myDate.getDay();
            var oneDayLong = 24 * 60 * 60 * 1000;
            var SundayTime = nowTime + (8 - day) * oneDayLong;
            var sunday = new Date(SundayTime);
            $('#txtTimeFrom').val((sunday.getFullYear()) + "-" + Appendzero(sunday.getMonth() + 1) + "-" + Appendzero(sunday.getDate()));
            var SundayTimeTo = nowTime + (14 - day) * oneDayLong;
            var sundayTo = new Date(SundayTimeTo);
            $('#txtTimeTo').val((sundayTo.getFullYear()) + "-" + Appendzero(sundayTo.getMonth() + 1) + "-" + Appendzero(sundayTo.getDate()));
            break;
        default:
            break;
    }
    BindData();
}
//获得本周的停止日期 
function getWeekEndDate() {
    var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
    return formatDate(weekEndDate);
}
function Appendzero(obj) {
    if (obj < 10) return "0" + "" + obj;
    else return obj;
}

//绑定回访列表
function BindData() {
    var time1 = Date.parse(new Date("20" + $("#txtTimeFrom").val()));
    var time2 = Date.parse(new Date("20" + $("#txtTimeTo").val()));
    var diff = parseInt((time2 - time1) / 1000 / 3600 / 24);
    if (diff < 0) {
        ShowError("myPageAlert", "起始时间不能大于终止时间");
        return;
    }
    //nPageIndex = 0;
    var strJson = $.toJSON({
        pageindex: nPageIndex,
        pagesize: nPageSize,
        starttime: $('#txtTimeFrom').val(),
        endtime: $('#txtTimeTo').val(),
        type: "0" //0代表未完成，1待定，2代表已完成
    });
    homeObj.gettakslist(strJson);
}

//查询回访回调
function AsyncGetTaksListResult(jsonResult) {
    $("#mytbody").empty();
    if (jsonResult.success) {
        nPageCount = Math.ceil(Number(jsonResult.result.total) / (nPageSize));
        var list = jsonResult.result.list;
        //if (taskIsfirst) {
            $("#pForVisit").html(list.length);
            taskIsfirst = false;
        //}
        if (list.length > 0) {
        	$("#imgWaitVisit").attr("src", "../img/homeicon08.gif");
        } else {
        	$("#imgWaitVisit").attr("src", "../img/homeicon08.png");
        }
        if (list.length > 0) {            
            $("#tbTask").show();
            $("#DivFooter").html(GetPageFootStr(nPageIndex, jsonResult.result.total));
            $("#DivFooter").show();
            $("#noneDataTipsTask").hide();
            //<td>' + item.pid + '</td>\
            for (var index in list) {
                var item = list[index];
                var trstr = '\
                    <tr>\
                        <td>' + (parseInt(index) + 1) + '</td>\
                        <td>' + item.uin + '</td>\
                        <td>' + item.nickname + '</td>\
                        <td>' + item.plantime + '</td>\
                        <td><p style="width:200px;">' + item.taskcontent + '</p></td>\
                        <td>\
                            <a class="a-btn" onclick="reVisit(\'' + item.id + '\',\'' + item.uin + '\',\'' + item.pid + '\');">回访</a>\
                            <a class="a-btn" onclick="showEditTask(\'' + item.id + '\',\'' + item.plantime + '\',\'' + item.taskcontent + '\');"\
                                 data-toggle="modal" data-target="#myModalEdit">修改</a>\
                            <a class="a-btn" onclick="deleteTask(\'' + item.id + '\');">忽略</a>\
                        </td>\
                    </tr>';
                $("#mytbody").append(trstr);
            }
        } else {
            $("#tbTask").hide();
            $("#DivFooter").hide();
            $("#noneDataTipsTask").show();
            $("#DivFooter").html("");
        }
    } else {
        $("#tbTask").hide();
        $("#DivFooter").hide();
        $("#noneDataTipsTask").show();
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
}

//弹出修改窗口
function showEditTask(id, plantime, taskcontent) {
    $('#txtReturnVisitTime').attr("taskid",id);
    $('#txtReturnVisitTime').val(plantime);
    $('#txtTaskContent').val(taskcontent);
}
//修改回访
function editTask() {
    var content = $("#txtTaskContent").val();
    if (content == "") {
        ShowError("myPageAlert", "回访描述不能为空！");
        return;
    }
    var strJson = $.toJSON({
        id: $('#txtReturnVisitTime').attr("taskid"),
        plantime: $('#txtReturnVisitTime').val(),
        taskcontent: content
    });
    homeObj.edittask(strJson);
}
//修改回访回调
function AsyncEditTaskResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "修改成功！");
        $("#myModalEdit").modal("hide");
        BindData();
    } else {
        ShowError("myPageAlert", "修改异常：" + jsonResult.error);
    }
}

//删除回访
function deleteTask(id) {
    var strJson = $.toJSON({
        id: id
    });
    homeObj.deletetask(strJson);
}
//删除回调
function AsyncDeleteTaskResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "删除成功！");
        BindData();
    } else {
        ShowError("myPageAlert", "删除异常：" + jsonResult.error);
    }
}
//回访+完成
function reVisit(id, uin, pid) {
    var wechatkey = homeObj.getwechatkeybyuin(uin + "");
    if (wechatkey.length == 0) {
        ShowError("myPageAlert", "该微信不在线或者在其它客服处登录！");
    } else {
        var strJson = $.toJSON({
            id: id,
            taskresult: ""
        });
        homeObj.perfectiontask(strJson);
        window.location.href = "talk.html?wechatkey=" + wechatkey + "&pid=" + pid;
    }
}
//完成回调
function AsyncPerfectionTaskResult(jsonResult) {
    if (jsonResult.success) {
        BindData();
    } else {
        ShowError("myPageAlert", "操作异常：" + jsonResult.error);
    }
}
//=============================================================回访=======================================================end//


//******************************************今日对话**********************************************************
var m_TodayTalkCacheList = [];//今日对话缓存
var m_Userid = "";//存储切换客服页面选中人的userid，判断是否为本人，不是则不能跟进
var m_StrUserids = "";//选中人员的userid的集合，逗号分割
var m_FirstQueryTodayTalk = 1;//首次加载今日对话
function ClickTodayTalkDay(val) {
	$("#btnTodayTalkQueryAll").attr("class", "");
	$("#btnTodayTalkQueryCS").attr("class", "");
	$("#btnTodayTalkUntreated").attr("class", "");
	if (val == 0) {
		$("#btnTodayTalkQueryAll").addClass("btn btn-success");
		$("#btnTodayTalkQueryCS").addClass("btn btn-default");
		$("#btnTodayTalkUntreated").addClass("btn btn-default");
	} else if (val == 1) {
		$("#btnTodayTalkQueryAll").addClass("btn btn-default");
		$("#btnTodayTalkQueryCS").addClass("btn btn-success");
		$("#btnTodayTalkUntreated").addClass("btn btn-default");
	} else if (val == 3) {
	    $("#btnTodayTalkQueryAll").addClass("btn btn-default");
	    $("#btnTodayTalkQueryCS").addClass("btn btn-default");
	    $("#btnTodayTalkUntreated").addClass("btn btn-success");
	}
	BindTodayTalk();
}

//部门回调
function AsyncGetDeptByAuthResult(jsonResult) {
    if (jsonResult.success) {
        $("#selDept").empty();
        m_StrUserids = jsonResult.myself.userid + ",";
        var deptlist = jsonResult.deptlist;
        $("#selDept").append("<option value='" + jsonResult.myself.userid + "' tag='user' name='" + jsonResult.myself.username + "'>本人</option>");
        if (jsonResult.deptlist.length > 0) {
            $("#selDept").show();
            for (var index in deptlist) {
                var item = deptlist[index];
                $("#selDept").append("<option value='" + item.dgid + "'>" + item.dgname + "</option>");
            }
        } else {
            $("#selDept").hide();
        }
        BindCompanyUsers();
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
    $(".loadingcover").hide();
    $(".loading").hide();
}

function BindCompanyUsers() {
    var paraJson;
    $("#selUser").empty();
    var selectDom = $("#selDept").find("option:selected");
    alluin = "";
    if (selectDom.attr("tag") == "user") {
        $("#selUser").append("<option value='" + selectDom.val() + "' tag='user' selected='true'>" + selectDom.attr("name") + "</option>");
        m_StrUserids = selectDom.val() + ",";
        if (m_FirstQueryTodayTalk == 1) {
            BindTodayTalk();
            m_FirstQueryTodayTalk = 2;
        }
    } else {
        //$("#selUser").append("<option value=''>客服</option>");
        paraJson = $.toJSON({
            deptid: $("#selDept").val()
        });
        homeObj.getpersonbydeptid(paraJson);
    }
}

//绑定人员回调
function AsyncGetPersonByDeptidResult(jsonResult) {
    m_StrUserids = "";//清空人员userid集合
    var selUser = $("#selUser");
    if (jsonResult.success) {
        var jsonObj = jsonResult.user;
        var jsonList = jsonObj.list;
        var currentId = jsonObj.loginuid;
        for (var i = 0; i < jsonList.length; i++) {
            var item = jsonList[i];
            selUser.append("<option value='" + item.userid + "'>" + item.name + "</option>");
            m_StrUserids += item.userid + ",";
        }
        selUser.prepend("<option value='" + m_StrUserids.substr(0, m_StrUserids.length - 1) + "'>客服</option>");
        if (m_FirstQueryTodayTalk == 1) {
            BindTodayTalk();
            m_FirstQueryTodayTalk = 2;
        }
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
}
// 获取错失信息
function BindTodayTalk() {
    m_TodayTalkCacheList = [];//点击查看对话时清空今日对话对话缓存
    //$("#divMissTable").attr("style", "display:none");
    
    var strType = "0";
    if ($("#btnTodayTalkQueryCS").attr("class") == "btn btn-success") {
        strType = "1";
    } else if ($("#btnTodayTalkUntreated").attr("class") == "btn btn-success") {
        strType = "2";
    }
    $("#misstalk").modal("show");
    $("#iDataTalkTurn").show();
    $("#DataTalkzhezhao").show();
    $("#divMissTable").html("");
    //var strUserid = m_StrUserids.substr(0, m_StrUserids.length - 1);
    var selUser = $("#selUser");
    if (selUser.val() == "") {
        $("#divMissTable").html("暂时没有数据！");
        $("#divMissTable").attr("style", "display:none");
        $("#noneDataTips").show();
        $("#iDataTalkTurn").hide();
        $("#DataTalkzhezhao").hide();
        return;
    }
    var strJson = $.toJSON({
        userids: selUser.val(),
        type: strType//类型0全部，1错失 2未处理
    });
    // 获取今日对话信息  回调是:AsyncGetMissTalkResult
    homeObj.getmisstalk(strJson);
}

function AsyncGetMissTalkResult(jsonResult) {
    if (jsonResult.success) {
        if (jsonResult.list != null && jsonResult.list.length > 0) {
            m_TodayTalkCacheList = jsonResult.list;

            BindTodayTalkCacheList();
        } else {
            $("#divMissTable").attr("style", "display:none");
            $("#noneDataTips").show();
        }
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
    $("#iDataTalkTurn").hide();
    $("#DataTalkzhezhao").hide();
}
//今日对话modal层显示
function Misstalk(userid) {
    m_FirstQueryTodayTalk = 1;
    m_Userid = userid;
    //获取部门
    var paraJson = $.toJSON({
        type: "data"
    });
    homeObj.getdeptbyauth(paraJson);
    $("#misstalk").modal("show");
}
//遍历今日对话的好友信息
function BindTodayTalkCacheList() {
    //$("#divMissTable").attr("style","display:block");
    var cususerid = homeObj.getcususerid();

    var list = m_TodayTalkCacheList;
    var strContent = "";
    var nSelectRowCount = 0;
    if (list.length > 0) {
        strContent = "<table class=\"table table-bordered\"><tr><th>客服微信昵称</th><th>微信描述</th><th>好友ID</th><th>好友头像</th><th>备注/昵称</th><th>开始时间</th><th>好友消息数</th><th>客服消息数</th>";
        if (cususerid == m_Userid || m_Userid == "") {
            strContent += "<th width=\"70\">操作</th>";
        }
        strContent += '</tr>';
        for (index in list) {
            var item = list[index];

            var datarow = '<tr>\
                            <td>' + item.wnickname + '</td>\
                            <td>' + item.wremark + '</td>\
                            <td>' + item.pid + '</td>\
                            <td><img src="' + item.headimgurl + '" width="40" onerror="nofind()" /></td>\
                            <td>' + item.nickname + '</td>\
                            <td>' + item.talkstarttime.substr(2, 14).replace("T", " ") + '</td>\
                            <td>' + item.friendtalkcount + '</td>\
                            <td>' + item.custalkcount + '</td>';
            if (cususerid == m_Userid || m_Userid == "") {
            	datarow += '<td  class=\"form-inline\"><a class="btn btn-link"  onclick="gotoTalk(' + item.uin + "," + item.pid + ');">跟进</a><a class="btn btn-link" onclick="GetTodayTalk(' + item.uin + "," + item.pid + ',' + item.headimgkey + ');">历史记录</a></td>';
            }
            datarow += '</tr>';

            strContent += datarow;
            nSelectRowCount++;
        }
        strContent += "</table>";
        $("#divMissTable").html(strContent);

        if (nSelectRowCount > 0) {
            $("#divMissTable").attr("style", "display:block");
            $("#noneDataTips").hide();
        } else {
            $("#divMissTable").attr("style", "display:none");
            $("#noneDataTips").show();
        }
    } else {
        //$("#divMissTable").html("暂时没有数据！");
        $("#divMissTable").attr("style", "display:none");
        $("#noneDataTips").show();
    }
}

//=============================================================查重好友三级联动=======================================================start//
//本页面自定义查询
var PageIndex = 0;
var PageSize = 100;
var PageCount = 0;

//单击主页面查重好友时
function FriendsRecheck() {
    PageIndex = 0;
    PageSize = 100;
    $("#txtrepeatnickname").val("");
    $("#mytbodyNotethe").empty();
    $("#headtable").empty();
    //$("#txtrepeatNotethe").val("");
    BindDataFullyGood();//单击时
}

//单击查询按钮1
function BindDataFul() {
    PageIndex = 0;
    PageSize = 100;
    BindDataFullyGood();
}

function BindDataFullyGood() {
    $("#zhezhao").show();
    $("#iLoadFriendsTurn").show();
    var strParaJson = $.toJSON({
        nickname: $.trim($("#txtrepeatnickname").val()),
        remarkname: "",
        pageindex: PageIndex,
        pagesize: PageSize
    });
    homeObj.getrepeatfriend(strParaJson);
}

//分页需要的list判断下一页是否可以点击
var nextpage;
//查询回调
function AsyncGetRepeatFriendResult(jsonResult) {
    if (jsonResult.success) {
        var m_tablelist = jsonResult.result.list;
        nextpage = m_tablelist;
        $("#noneDataTipsTaskchong").hide();
        if (m_tablelist.length != 0) {
            var headtable = "";
            headtable += "<th>序号</th>";
            headtable += "<th>微信昵称(微信备注)</th>";
            headtable += "<th>好友昵称</th>";
            headtable += "<th>好友备注</th>";
            headtable += "<th>性别</th>";
            headtable += "<th>位置</th>";
            $("#headtable").html(headtable);
            $("#DivFootercong").html(fenye(PageIndex));
            var mytbodyNotethe = "";
            for (var i = 0; i < m_tablelist.length; i++) {
                var xingbie;
                if (m_tablelist[i].sex == 1) {
                    xingbie = "男";
                } else if (m_tablelist[i].sex == 2) {
                    xingbie = "女";
                } else {
                    xingbie = "未知";
                }
                var weizhi;
                if (m_tablelist[i].province != "" && m_tablelist[i].city != "") {
                    weizhi = m_tablelist[i].province + "-" + m_tablelist[i].city;
                } else if (m_tablelist[i].province == "" && m_tablelist[i].city == "") {
                    weizhi = "";
                } else {
                    weizhi = (m_tablelist[i].province == "" ? m_tablelist[i].city : m_tablelist[i].province);
                }
                var weixin = (m_tablelist[i].wremark == "" ? m_tablelist[i].wname : m_tablelist[i].wname + "(" + m_tablelist[i].wremark + ")");
                
                var xuhao = i + 1;
                mytbodyNotethe += "<tr>";
                mytbodyNotethe += "<td>" + xuhao + "</td>";
                mytbodyNotethe += "<td>" + weixin + "</td>";
                mytbodyNotethe += "<td>" + m_tablelist[i].nickname + "</td>";
                mytbodyNotethe += "<td>" + m_tablelist[i].remarkname + "</td>";
                mytbodyNotethe += "<td>" + xingbie + "</td>";
                mytbodyNotethe += "<td>" + weizhi + "</td>";
                mytbodyNotethe += "</tr>";
            }
            $("#mytbodyNotethe").html(mytbodyNotethe);

        } else {
            $("#headtable").html("");
            $("#DivFootercong").html("");
            $("#mytbodyNotethe").html("");
            $("#noneDataTipsTaskchong").show();
        }
    } else {
        ShowError("myPageAlert", "获取重复好友数据异常：" + jsonResult.error);
    }
    $("#zhezhao").hide();
    $("#iLoadFriendsTurn").hide();
}


//分页函数
function fenye(pageindex) {
    //记录数选择
    var strFooter = "";

    var strBfPageEnabled = (PageIndex == 0) ? (" disabled=\"disabled\" ") : (" onclick=\"JumpPageIndexzidingyi(" + (PageIndex - 1) + ");\"");
    var strNextPageEnabled = " onclick=\"JumpPageIndexzidingyi(" + (PageIndex + 1) + ");\"";
    if (nextpage.length < 100) {
        strNextPageEnabled = " disabled=\"disabled\" ";
    }
    strFooter += "<div class=\"col-md-12 footer-page-container\" style=\"\">";
    strFooter += "<div class=\"btn-toolbar button-group\" role=\"toolbar\" style=\"float:right; padding-right:25px;\">";
    strFooter += "<div class=\"btn-group\">";
    strFooter += "<button type=\"button\" class=\"btn btn-default\"" + strBfPageEnabled + ">上一页</button>";
    strFooter += "</div>";
    strFooter += "<div class=\"btn-group\">";
    strFooter += "<button type=\"button\" class=\"btn btn-default\"" + strNextPageEnabled + ">下一页</button>";
    strFooter += "</div>";
    strFooter += "</div>";
    strFooter += "</div>";

    return strFooter;
}
function JumpPageIndexzidingyi(index) {
    PageIndex = index;
    BindDataFullyGood();
}
//=============================================================查重好友三级========================================end//

function GoMonitor() {
	homeObj.showmonitor();
}

//首页圆形图展示
//function Circulargraph(onlcount, drocount) {
//	onlcount = Number(onlcount);
//	drocount = Number(drocount);
//	var myChart = echarts.init(document.getElementById('main5'));
//	// 指定图表的配置项和数据
//	var dataStyle = { //作用不明
//		normal: {
//			label: { show: false },
//			labelLine: { show: false },
			 
//		}
//	};
//	var placeHolderStyle = { //作用不明  原来是这是pie图里面的
//		normal: {
//			color: 'rgba(0,0,0,0)',
//			label: { show: false },
//			labelLine: { show: false }
//		},
//		emphasis: {
//			color: 'rgba(0,0,0,0)'
//		}
//	};
//	var option = {
//		backgroundColor: '#fff', //图表的配置颜色
//		color: ['#4ad089', '#fcd96e'], //每一项对应的颜色
//		tooltip: {  //提示框组件
//			show: true,
//			formatter: "{a} <br/>{b} : {c} ({d}%)"  //正则设置格式
//		},
		 
//		series: [  //系列列表
//            {
//            	name: '微信号在线情况',
//            	type: 'pie',
//            	radius: ['60%', '70%'],
//            	avoidLabelOverlap: false,
//            	center: ['65px', '50%'], //饼图片的中心
//            	itemStyle: dataStyle, //样式
//            	hoverAnimation: false,
//            	labelLine: {
//            		normal: {
//            			show: false
//            		}
//            	},
//            	data: [
//                    { value: onlcount, name: '在线数量' },
//                    { value: drocount, name: '掉线数量' },


//            	],
//            },

//		]
//	};
//	// 使用刚指定的配置项和数据显示图表。
//	myChart.setOption(option);
//}