var m_OperMenuJson = {};//当前查询数据缓存
var m_strConrentHead = ""//页面头部
var select = 0;//0代表选择table，1代表选择柱状图
var isfirst = 0;// isfirst=0代表初始化调用
var deptJsonlist = [];

// 好友数量统计页面加载
$(function () {
    $("#myPageAlert").hide();
    listcss();
    //获取部门
    var paraJson = $.toJSON({
        type: "data"
    });
    dataObj.getdeptbyauth(paraJson);
    $(".table-click").click(function () {
        $(this).next().toggle();
    });
});

function AsyncGetDeptByAuthResult(jsonResult) {
    if (jsonResult.success) {
        var deptlist = jsonResult.deptlist;
        if (jsonResult.deptlist.length > 0) {
            for (var index in deptlist) {
                var item = deptlist[index];
                if (item.dgname == "本人") {
                    continue;
                }
                var dept = $.toJSON({
                    id: item.dgid,
                    name: item.dgname
                });
                deptJsonlist.push(dept);
            }
        }
        if (isfirst == 0) {
            isfirst = 1;
            BindData();
        } else {
            $(".loading").hide();
            $(".loadingcover").hide();
        }
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
    $(".loadingcover").hide();
    $(".loading").hide();
}

// 绑定微信号列表
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 > 30) {
        ShowError("myPageAlert", "最多只能统计30天的结果");
        return;
    }else if (diff <0) {
        ShowError("myPageAlert", "起始时间不能大于终止时间");
        return;
    }
    if (deptJsonlist.length > 0) {
    	$(".loading").show();
    	$(".loadingcover").show();
    	var strParaJson = $.toJSON({
    		dtstart: $("#txtTimeFrom").val(),
    		dtend: $("#txtTimeTo").val(),
    		dept: deptJsonlist
    	});
    	dataObj.getdeptalalysisreport(strParaJson);
    } else {
    	ShowMsg("myPageAlert", "没有部门可供查看！");
    }
   
}

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

// 统计页面
function SetFansShow(json) {
    $("#friendcount").html(json.result.totalfriends);
    $("#todaynewfriend").html(json.result.totaltodaynewfriend);
    var strConrent = "";
    var totalcount = "";
    var totalWxcounnt = 0; 
    var totalFriendcount = 0;
    var totalNan = 0;
    var totalNv = 0;
    var totalunknown = 0;
    var totalTalkcount = 0;
    for (var i = 0; i < json.result.list.length; i++) {
        strConrent += "<tr>";
        strConrent += "<td>" + json.result.list[i].index + "</td>";
        strConrent += "<td>" + json.result.list[i].name + "</td>";
        strConrent += "<td>" + json.result.list[i].wxcount + "</td>";
        strConrent += "<td>" + (json.result.list[i].friendcount == "" ? 0 : json.result.list[i].friendcount) + "</td>";
        strConrent += "<td>" + (json.result.list[i].nan == "" ? 0 : json.result.list[i].nan) + "</td>";
        strConrent += "<td>" + (json.result.list[i].nv == "" ? 0 : json.result.list[i].nv) + "</td>";
        strConrent += "<td>" + (json.result.list[i].unknown == "" ? 0 : json.result.list[i].unknown) + "</td>";
        strConrent += "<td>" + (json.result.list[i].talkcount == "" ? 0 : json.result.list[i].talkcount) + "</td>";
        strConrent += "</tr>";

        totalWxcounnt += Number(json.result.list[i].wxcount);
        totalFriendcount += Number(json.result.list[i].friendcount);
        totalNan += Number(json.result.list[i].nan);
        totalNv += Number(json.result.list[i].nv);
        totalunknown += Number(json.result.list[i].unknown);
        totalTalkcount += Number(json.result.list[i].talkcount);
    }
    $("#mytbody").html(strConrent);
    totalcount += "<tr>";
    totalcount += "<td colspan='2' align='center'>" + "合计" + "</td>";
    totalcount += "<td>" + totalWxcounnt + "</td>";
    totalcount += "<td>" + totalFriendcount + "</td>";
    totalcount += "<td>" + totalNan + "</td>";
    totalcount += "<td>" + totalNv + "</td>";
    totalcount += "<td>" + totalunknown + "</td>";
    totalcount += "<td>" + totalTalkcount + "</td>";
    totalcount += "</tr>";
    $("#mytbody").append(totalcount);
    tableSlip();//表头拖拽
}

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

//柱状图生成
function HistorgramShow() {
    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].name.length > 4) //公众号超出五位 截取
            {
                DataName.push(m_OperMenuJson.list[i].name.substr(0, 4) + "..")
            }
            else {
                DataName.push(m_OperMenuJson.list[i].name)
            }

            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();
     //myDate.setDate(myDate.getDate() - 1);
     $('#txtTimeTo').val((myDate.getYear() - 100) + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate());
     $('#txtTimeTo').datetimepicker('update');
    //设置日期，当前日期的前七天
    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.exportdeptexcle(paraJson);
}
//导出excle回调
function AsyncExportDeptExcleResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "报表导出成功！");
    } else {
        ShowError("myPageAlert", "报表导出异常" + jsonResult.error);
    }
}