var m_OperMenuJson = {};//当前查询数据缓存
var m_strConrentHead = ""//页面头部
var select = 0;//0代表选择table，1代表选择柱状图
var isfirst = 0;// isfirst=0代表初始化调用
var alluserid = "";
// 好友数量统计页面加载
$(function () {
    $("#myPageAlert").hide();
    listcss();
    //获取部门
    var paraJson = $.toJSON({
        type: "data"
    });
    dataObj.getdeptbyauth(paraJson);
});

function AsyncGetDeptByAuthResult(jsonResult) {
    if (jsonResult.success) {
        var deptlist = jsonResult.deptlist;
        $("#selDept").append("<option value='" + jsonResult.myself.userid + "' tag='user' name='" + jsonResult.myself.username + "'>本人</option>");
        if (jsonResult.deptlist.length > 0) {
            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);
    }
    //初始化调用
    if (isfirst == 0) {
        BindData();
    }
    
    $(".loadingcover").hide();
    $(".loading").hide();
}

function BindCompanyUsers() {
    nPageIndex = 0;
    var paraJson;
    $("#selUser").empty();
    alluserid = "";
    var selectDom = $("#selDept").find("option:selected");
    if (selectDom.attr("tag") == "user") {
        $("#selUser").append("<option value='" + selectDom.val() + "' tag='user' selected='true'>" + selectDom.attr("name") + "</option>");
        alluserid = selectDom.val();
    } else {
        $("#selUser").append("<option value=''>客服</option>");
        paraJson = $.toJSON({
            deptid: $("#selDept").val()
        });
        dataObj.getpersonbydeptid(paraJson);
    }
}

//绑定人员回调
function AsyncGetPersonByDeptidResult(jsonResult) {
    var selUser = $("#selUser");
    if (jsonResult.success) {
        var jsonObj = jsonResult.user;
        var jsonList = jsonObj.list;
        var currentId = jsonObj.loginuid;
        alluserid = "";
        for (var i = 0; i < jsonList.length; i++) {
            var item = jsonList[i];
            alluserid += item.userid + ",";
            selUser.append("<option value='" + item.userid + "'>" + item.name + "</option>");
        }
        alluserid = alluserid.substr(0, alluserid.length - 1);
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
}

// 绑定微信号列表
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;
    }
    $(".loading").show();
    $(".loadingcover").show();
    var uid = $("#selUser").val();
    if ("" == uid) {
        uid = alluserid;
    }

    if (uid != "") {
        var strParaJson = $.toJSON({
            dtstart: $("#txtTimeFrom").val(),
            dtend: $("#txtTimeTo").val(),
            pageindex: nPageIndex,
            pagesize: nPageSize,
            uid: uid
        });
        dataObj.getwechat(strParaJson);
    } else {
        $(".loading").hide();
        $(".loadingcover").hide();

        $("#liExport").hide();
        $("#liExport").hide();
        $("#tips").show();
        $("#tableParent").hide();
        $("#DivFooter").hide();
        //$("#friendcount").html(0);
        //$("#todaynewfriend").html(0);
        m_OperMenuJson.list = [];
    }
}

//客服下拉框选择事件
function selUserChange() {
    isfirst = 1;
    nPageIndex = 0;
}

// 微信号统计回调
function AsyncGetWechatResult(jsonResult) {
    m_OperMenuJson = {};
    if (jsonResult.success == true) {
        $("#mytbody").empty();
        $("#main").empty();
        nPageCount = Math.ceil(Number(jsonResult.result.total) / (nPageSize));
        m_OperMenuJson = jsonResult.result;
        if (1 == select) {
            HistorgramShow();
        }
        if (jsonResult.result.list.length > 0) {
            SetFansShow(jsonResult);
            $("#liExport").show();
            $("#tips").hide();
            $("#tableParent").show();
            if (0 == select) {
                $("#DivFooter").html(GetPageFootStr(nPageIndex, jsonResult.result.total));
                $("#DivFooter").show();
            }
        }
        else {
            $("#liExport").hide();
            $("#tips").show();
            $("#tableParent").hide();
            $("#DivFooter").hide();
            //$("#friendcount").html(0);
            //$("#todaynewfriend").html(0);
        }
    }
    else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
        $("#tips").show();
        $("#tableParent").hide();
        $("#DivFooter").hide();
        $("#friendcount").html(0);
        //$("#todaynewfriend").html(0);
    }
    $(".loading").hide();
    $(".historyzhezhao").hide();
    $(".loadingcover").hide();
    $(".loading").hide();
}

// 统计页面
function SetFansShow(json) {

    for (var i = 0; i < json.result.list.length; i++) {
        var strConrent = "<tr>";
        strConrent += "<td>" + (i + 1) + "</td>";
        strConrent += "<td>" + '<div class="table-img-div"><img src="' + json.result.list[i].headimgurl + '" style="width:100%;height:100%" onerror="nofind()"/></div>' + "</td>";
        if (json.result.list[i].wremark == null || json.result.list[i].wremark.trim() == "") {
            strConrent += "<td>" + json.result.list[i].nickname + "</td>";
        } else {
            strConrent += "<td>" + json.result.list[i].nickname + "(" + json.result.list[i].wremark + ")" + "</td>";
        }
        
        strConrent += "<td>" + json.result.list[i].friendcount + "</td>";
        strConrent += "<td>" + json.result.list[i].nan + "</td>";
        strConrent += "<td>" + json.result.list[i].nv + "</td>";
        strConrent += "<td>" + json.result.list[i].unknown + "</td>";
        strConrent += "<td>" + json.result.list[i].todaynewfriend + "</td>";//新增
        strConrent += "<td>" + json.result.list[i].todaynewtalk + "</td>";//对话
        strConrent += "</tr>";
        $("#mytbody").append(strConrent);
    }
    tableSlip();//表头拖拽
}

function tableclick() {
    select = 0;
    BindData();
}
function barchartclick() {
    select = 1;
    HistorgramShow();
}

//柱状图生成
function HistorgramShow() {
    $("#DivFooter").hide();
    if (m_OperMenuJson.list.length < 2) {
        ShowMsg("myPageAlert", "少于2条数据时，不能生成图形报表！");
    }
    else {
        var DataTotal = [];
        var DataName = [];
        for (var i = 0; i < m_OperMenuJson.list.length; i++) {
            if (m_OperMenuJson.list[i].nickname.length > 4) //公众号超出五位 截取
            {
                DataName.push(m_OperMenuJson.list[i].nickname.substr(0, 4) + "..")
            }
            else {
                DataName.push(m_OperMenuJson.list[i].nickname)
            }

            DataTotal.push(Number(m_OperMenuJson.list[i].friendcount));
        }

        if (i <= 10) {
            $("#main").width(750);
        } else {
            var MianWidth = Number(i) * 80;
            $("#main").width(Number(MianWidth))
        }

        var myChart = echarts.init(document.getElementById('main'));

        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '好友数量'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            grid: {
                left: '0',
                right: '0',
                containLabel: true
            },
            xAxis: {
                data: DataName
            },
            yAxis: {},
            series: [{
                name: '好友数量',
                barWidth: '50%',
                type: 'bar',
                data: DataTotal,
                itemStyle: {
                    normal: { color: '#61BCE8' }
                }
            }],

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

//样式操作
function listcss() {
    $("#right").css({
        height: $(window).height()
    });
    $("#left").css({
        height: $(window).height()
    });
    $(".left-list-l").css({
        height: $(window).height()
    });
    $(".friends-table").css({
        height: $(window).height() - 180
    });
}
$(window).resize(function () {
    listcss();
});
//初始化控件
$(document).ready(function () {
    $('#txtTimeFrom').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yy-m-d"
    });
    $('#txtTimeTo').datetimepicker({
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        minView: "month",
        format: "yy-m-d"
    });

    //获取今天日期
    var myDate = new Date();
    $('#txtTimeTo').val((myDate.getYear() - 100) + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate());
    //设置日期，当前日期的前七天
    myDate.setDate(myDate.getDate() - 7);
    $('#txtTimeFrom').val((myDate.getYear() - 100) + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate());
    $('#txtTimeFrom').datetimepicker('update');
});

//导出excle
function ErportExcle() {
    var paraJson = $.toJSON({
        jsonpara: m_OperMenuJson
    });
    dataObj.exportwechatsexcle(paraJson);
}
//导出excle回调
function AsyncExportWechatsExcleResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "报表导出成功！");
    } else {
        ShowError("myPageAlert", "报表导出失败" + jsonResult.error);
    }
}