var deptList = [];
var currentWechat = "";
var currentUid = "";
var m_wechat = ""; //检索微信号内容

$(function () {
    customquery();//调用时间插件
    css();
    $("#myPageAlert").hide();
    dataObj.getcompanywechatsonlinemark();

});

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

//时间插件
function customquery() {
    $('#txtTimeFrom').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yy-mm-dd"
    });
    $('#txtTimeEnd').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yy-mm-dd"
    });
}
//样式操作
function css() {
    $("#right").css({
        height: $(window).height()
    });
    $("#left").css({
        height: $(window).height()
    });
    $(".left-list-l").css({
        height: $(window).height()
    });
    $(".friends-table").css({
        height: $(window).height() - 180
    });
    $(".homemenu").css({
        height: $(window).height()
    });
    $(".fanslist-left").css({
        height: $(window).height()
    });
    $(".data-fanslisttree").css({
        height: $(window).height()
    });


}
//=============================================绑定及查询微信================================================start//
// 获取含有登录状态的微信列表回调
function AsyncGetCompanyWechatsOnlineMarkResult(jsonResult) {
    if (jsonResult.success) {
        deptList = jsonResult.list;
        BindChat();
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
}

//绑定微信
function BindChat() {
    m_wechat = "";
    var strcontent = "";
    var num = 0;
    var nonewechatnin = "";
    var nonecus = "";
    var objipQueryName = $.trim($("#ipQueryName").val());
    for (var i = 0; i < deptList.length; i++) {
        var strWechatContent = "";
        for (var k = 0; k < deptList[i].user.length; k++) {
            for (var n = 0; n < deptList[i].user[k].wechats.length; n++) {
                var wechatitenm = deptList[i].user[k].wechats[n];
                var remark = wechatitenm.remark == null ? "" : wechatitenm.remark;
                if (wechatitenm.nickname.indexOf(objipQueryName) != -1 || remark.indexOf(objipQueryName) != -1 || objipQueryName == "") {
                    var strwechatstate = WechatBusiness(wechatitenm.loginstate);
                    if (num == 0) {
                        nonewechatnin = wechatitenm.uin;
                        nonecus = wechatitenm.cususerid;
                        num++;
                    }
                    strWechatContent += "<li class=\"\" id=\"wechat" + wechatitenm.uin + "\" style=\"cursor:pointer\" onclick=\"selectWechat('" + wechatitenm.cususerid + "','" + wechatitenm.uin + "')\">";
                    strWechatContent += "<img src=\"" + wechatitenm.headimgurl + "\" width=\"50\" height=\"50\" class=\"pull-left\">";
                    strWechatContent += "<div class=\"account-name\">";
                    strWechatContent += "<h2>" + strwechatstate + "&nbsp;" + wechatitenm.nickname + "</span></h2>";
                    strWechatContent += "<p>" + wechatitenm.uin + "</p>";
                    strWechatContent += "<p>备注：" + (wechatitenm.remark == null ? "" : wechatitenm.remark) + "</p>";
                    strWechatContent += "</div>";
                    strWechatContent += "<div class=\"clearfix\"></div>";
                    strWechatContent += "</li>";
                }
            }
        }
        var count = objipQueryName == "" ? "(" + deptList[i].wechatcount + ")" : "";
        if (strWechatContent.length > 0) {
            strcontent += "<ul class=\"yiji-m\">";
            strcontent += "<li class=\"active\">";
            strcontent += "<a href=\"#divEditDept\" class=\"inactive-m inactives-m\">" + deptList[i].dgname + count + "</a>";
            strcontent += "<ul class=\"data-fanslist\" style=\"display: block;\">";
            strcontent += strWechatContent
            strcontent += "</ul>"
            strcontent += "</li>";
            strcontent += "</ul>";
        }
    }
    $("#divTree").html(strcontent);
    if (nonewechatnin != "" || nonecus != "") {
        selectWechat(nonecus, nonewechatnin);
    } else {
        $("#liExport").hide();
        $("#tips").show();
        $("#tableParent").hide();
        $("#main").empty();
    }
    initTree();
    m_wechat = strcontent;
}
//微信号状态
function WechatBusiness(state) {
    var stateStr = "";
    switch (state) {
        //case 6:
        //    stateStr = "<span class=\"label label-info\" style=\"font-size:12px; color:white;\">[登录中]";
        //    break;
        case 7:
            stateStr = "<span class=\"label label-info\" style=\"font-size:12px; color:white;\">[登录中]";
            break;
        case 8:
            stateStr = "<span class=\"label label-info\" style=\"font-size:12px; color:white;\">[在线]";
            break;
        case 9:
            stateStr = "<span  class=\"label label-warning\" style=\"font-size:12px; color:white;\">[网络异常]";
            break;
        case 10:
            stateStr = "<span  class=\"label label-danger\" style=\"font-size:12px; color:white;\">[登出]";
            break;
        //case 11:
        //    stateStr = "<span  class=\"label label-danger\" style=\"font-size:12px; color:white;\">[掉线]";
        //    break;
        case 12:
            stateStr = "<span  class=\"label label-danger\" style=\"font-size:12px; color:white;\">[手机断网]";
            break;
    }
    return stateStr;
}
function selectWechat(uid, uin) {
    currentWechat = uin;
    currentUid = uid;
    $("#divTree").find("li").removeClass("active");
    $("#wechat" + uin).addClass("active");
    bindWechatSummary(uid);
    BindData();
}
//=============================================绑定及查询微信================================================end//
//=============================================绑定好友数量统计================================================start//
function bindWechatSummary(uid) {
    var strParaJson = $.toJSON({
        dtstart: "",
        dtend: "",
        pageindex: 0,
        pagesize: 99999,
        uid: uid
    });
    dataObj.getwechat(strParaJson);
}

// 微信号统计回调
function AsyncGetWechatResult(jsonResult) {
    if (jsonResult.success == true) {
        $("#pWholeCount").html(0);
        $("#pNanCount").html(0);
        $("#pNvCount").html(0);
        $("#pWeiCount").html(0);
        $("#pNewCount").html(0);
        if (jsonResult.result.list.length > 0) {
            for (index in jsonResult.result.list) {
                var item = jsonResult.result.list[index];
                if (currentWechat == item.uin) {
                    $("#pWholeCount").html(item.friendcount);
                    $("#pNanCount").html(item.nan);
                    $("#pNvCount").html(item.nv);
                    $("#pWeiCount").html(item.unknown);
                    $("#pNewCount").html(item.todaynewfriend);
                    break;
                }
            }
        }
    }
    else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
}
//=============================================绑定好友数量统计================================================end//
//=============================================绑定及查询对话================================================start//

var m_OperMenuJson = {};//当前查询数据缓存
var select = 0;//0代表选择table，1代表选择柱状图
var selType = 2;// ，2昨天，3本月，4本年  （1今天 已删除）

function btnClick(type) {
    selType = type;
    //$("#btnType1").removeClass("btn-focus-bk");
    $("#btnType2").removeClass("btn-focus-bk");
    $("#btnType3").removeClass("btn-focus-bk");
    $("#btnType4").removeClass("btn-focus-bk");
    //if (1 == selType) {
    //    $("#btnType1").addClass("btn-focus-bk");
    //} else
    if (2 == selType) {
        $("#btnType2").addClass("btn-focus-bk");
    } else if (3 == selType) {
        $("#btnType3").addClass("btn-focus-bk");
    } else if (4 == selType) {
        $("#btnType4").addClass("btn-focus-bk");
    } else if (5 == selType) {
        if ($("#txtTimeFrom").val() == "" || $("#txtTimeEnd").val() == "") {
            ShowError("myPageAlert", "开始时间或结束时间不能为空!");
            return;
        } else {
            var myDate = new Date();//当前日期
            var day = (myDate.getYear() - 100) + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate();
            var taday = Date.parse(new Date("20" + day));
            var time1 = Date.parse(new Date("20" + $("#txtTimeFrom").val()));
            var time2 = Date.parse(new Date("20" + $("#txtTimeEnd").val()));
            if (time1 > time2) {
                ShowError("myPageAlert", "开始时间不能大于结束时间!");
                return;
            }
            if (time1 >= taday || time2 >= taday) {
                ShowError("myPageAlert", "选择的时间不能大于或等于今天!");
                return;
            }
        }
        //$("#btnType1").removeClass("btn-focus-bk");
        $("#btnType2").removeClass("btn-focus-bk");
        $("#btnType3").removeClass("btn-focus-bk");
        $("#btnType4").removeClass("btn-focus-bk");
    }
    BindData();
}

//绑定聊天统计列表
function BindData() {
    $(".loading").show();
    $(".loadingcover").show();
    $("#tbdData").empty();
    $("#main").empty();

    var date = selType;
    if (selType == "5") {
        //自定义时间查询
        var strParaJson = $.toJSON({
            date: date,
            uid: currentUid,
            uin: currentWechat,
            starttime: $("#txtTimeFrom").val(),
            endtime: $("#txtTimeEnd").val()
        });
    } else {
        var strParaJson = $.toJSON({
            date: date,
            uid: currentUid,
            uin: currentWechat,
            starttime: "",
            endtime: ""
        });
    }


    dataObj.gettalkreport(strParaJson);
}

// 聊天统计回调
function AsyncGetTalkReportResult(jsonResult) {
    m_OperMenuJson = {};
    if (jsonResult.success == true) {
        m_OperMenuJson = jsonResult.result;
        if (1 == select) {
            LineShow();
        }
        if (jsonResult.result.list.length > 0) {
            SetDataShow(jsonResult);
            $("#liExport").show();
            $("#tips").hide();
            $("#tableParent").show();
        }
        else {
            $("#liExport").hide();
            $("#tips").show();
            $("#tableParent").hide();
        }
    }
    else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
        $("#tips").show();
        $("#tableParent").hide();
    }
    $(".loadingcover").hide();
    $(".loading").hide();
}

// 统计页面
function SetDataShow(json) {
	$("#tbdData").empty();
    var head = "";
    head += "<tr>";
    head += "<th>时间</th>";
    head += "<th>新增好友</th>";
    head += "<th>留电量</th>";
    head += "<th>对话数量</th>";
    head += "<th>极佳数</th>";
    head += "<th>较好数</th>";
    head += "<th>一般数</th>";
    head += "<th>错失数</th>";
    head += "<th>无效数</th>";
    head += "</tr>";
    $("#tbdData").append(head);
    for (var i = 0; i < json.result.list.length; i++) {
        var strConrent = "<tr>";
        var len = json.result.list[i].talkstarttime;
        len = len.substring(len.length, len.length - 2);
        var date = selType;
        //if (date == "1") {
        //    strConrent += "<td>" + parseInt(len) + "点</td>";
        //} else
        if (date == "2") {
            strConrent += "<td>" + parseInt(len) + "点</td>";
        } else if (date == "3") {
            strConrent += "<td>" + parseInt(len) + "日</td>";
        } else if (date == "4") {
            strConrent += "<td>" + parseInt(len) + "月</td>";
        } else if (date == "5") {
            if (json.result.type == 1) {
                strConrent += "<td>" + parseInt(json.result.list[i].talkstarttime) + "点</td>";
            } else if (json.result.type == 2) {
                strConrent += "<td>" + json.result.list[i].talkstarttime + "</td>";
            } else if (json.result.type == 3) {
                strConrent += "<td>" + json.result.list[i].talkstarttime + "</td>";
            }
        }
        strConrent += "<td>" + json.result.list[i].newfriend + "</td>";//好友
        strConrent += "<td>" + json.result.list[i].phonecall + "</td>";//留电
        strConrent += "<td>" + json.result.list[i].totalcall + "</td>";//对话数量
        strConrent += "<td>" + json.result.list[i].jjcall + "</td>";//极佳
        strConrent += "<td>" + json.result.list[i].jhcall + "</td>";//较好
        strConrent += "<td>" + json.result.list[i].ybcall + "</td>";//一般
        strConrent += "<td>" + json.result.list[i].cscall + "</td>";//错失
        strConrent += "<td>" + json.result.list[i].sxcall + "</td>";//无效
        strConrent += "</tr>";
        $("#tbdData").append(strConrent);
    }
    tableSlip();//表头拖拽
}
function tableclick() {
    select = 0;
}
function barchartclick() {
    select = 1;
    LineShow();
}

//折线图生成
function LineShow() {
    if (m_OperMenuJson.list == null || m_OperMenuJson.list.length < 2 || m_wechat.length < 1) {
        ShowMsg("myPageAlert", "少于2条数据时，不能生成图形报表！");
    }
    else {
        var DataTotalTalk = [];
        var DataTotalPhone = [];
        var DataTotaljj = [];
        var DataTotalyb = [];
        var DataName = [];
        var DataLast = "";
        var maxtotal = 0;
        var mintotal = 0;
        for (var i = 0; i < m_OperMenuJson.list.length; i++) {
            var len = m_OperMenuJson.list[i].talkstarttime;
            var LastDate = "";
            if (m_OperMenuJson.list[i].talkstarttime != 0) {
                var date = selType;
                //if (date == "1") {
                //    LastDate = "今日统计（小时）";
                //} else
                if (date == "2") {
                    LastDate = "昨日统计（小时）";
                } else if (date == "3") {
                    LastDate = "本月统计（日）";
                } else if (date == "4") {
                    LastDate = "本年统计（月）";
                } else if (date == "5") {
                    if (m_OperMenuJson.type == 1) {
                        LastDate = "自定义统计（小时）";
                    } else if (m_OperMenuJson.type == 2) {
                        LastDate = "自定义统计（日）";
                    } else if (m_OperMenuJson.type == 3) {
                        LastDate = "自定义统计（月）";
                    }
                    if (i <= 10) {
                        $("#main").width(750);
                    } else {
                        var MianWidth = Number(i) * 120;
                        $("#main").width(Number(MianWidth))
                    }
                }
                if (date != "5") {
                    len = len.substring(len.length, len.length - 2);
                    DataName.push(parseInt(len));
                } else {
                    len = m_OperMenuJson.list[i].talkstarttime;
                    DataName.push(len);
                }

                DataTotalTalk.push(Number(m_OperMenuJson.list[i].totalcall));
                DataTotalPhone.push(Number(m_OperMenuJson.list[i].phonecall));
                DataTotaljj.push(Number(m_OperMenuJson.list[i].jjcall));
                DataTotalyb.push(Number(m_OperMenuJson.list[i].ybcall));
            }

            if (Number(m_OperMenuJson.list[i].totalcall) > Number(maxtotal)) {
                maxtotal = m_OperMenuJson.list[i].totalcall;
            }
            if (Number(m_OperMenuJson.list[i].totalcall) < Number(mintotal)) {
                mintotal = m_OperMenuJson.list[i].totalcall;
            }
            var myChart = echarts.init(document.getElementById('main'));
            
        }

        // 指定图表的配置项和数据
        var option = {
            title: {
                text: LastDate
            },
            grid: {
                left: '0',
                right: '0',
                containLabel: true
            },
            tooltip: {},
            xAxis: {
                data: DataName
            },

            //align: 'left, textStyle: 'left',
            yAxis: {},
            series: [
                {
                    name: '对话数',
                    type: 'line',
                    data: DataTotalTalk,
                    itemStyle: {
                        normal: { color: '#61BCE8' }
                    }
                },
                {
                    name: '留电数',
                    type: 'line',
                    data: DataTotalPhone,
                    itemStyle: {
                        normal: { color: '#A020F0' }
                    }
                },
                {
                    name: '极佳数',
                    type: 'line',
                    data: DataTotaljj,
                    itemStyle: {
                        normal: { color: '#EE3B3B' }
                    }
                },
                {
                    name: '一般数',
                    type: 'line',
                    data: DataTotalyb,
                    itemStyle: {
                        normal: { color: '#CD950C' }
                    }
                },
            ],
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
}

//导出excle
function ErportExcle() {
    var paraJson = $.toJSON({
    	jsonpara: m_OperMenuJson,
    	type: 2 // 1.导出对话报表 2.导出微信号报表
    });
    dataObj.exporttalkexcle(paraJson);
}
//导出excle回调
function AsyncExportTalkExcleResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "报表导出成功！");
    } else {
        ShowError("myPageAlert", "报表导出异常" + jsonResult.error);
    }
}
//=============================================绑定及查询对话================================================end//