var m_OperMenuJson = {};//当前查询数据缓存
var m_strConrentHead = ""//页面头部
var select = 0;//0代表选择table，1代表选择柱状图
var isfirst = 0;// isfirst=0代表初始化调用
var alluin = "";
// 好友数量统计页面加载
$(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);
    }
    $(".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>");
        BindChat();
    } 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;
        for (var i = 0; i < jsonList.length; i++) {
            var item = jsonList[i];
            selUser.append("<option value='" + item.userid + "'>" + item.name + "</option>");
        }
        BindChat();
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
}


//绑定微信下拉框
function BindChat() {
    uid = $("#selUser").val();
    if ("" == uid) {
        $("#selChat").empty();
        $("#selChat").append("<option value=''>微信号</option>");
        if (isfirst == 0) {
            isfirst = 1;
            BindData();
        }
    } else {
        $(".loading").show();
        $(".loadingcover").show();
        var strParaJson = $.toJSON({
            uid: uid
        });
        dataObj.getwechatsallbyuid(strParaJson);
    }
}

//微信下拉框回调
function AsyncGetWeChatsAllByUidReportResult(jsonResult) {
    $("#selChat").empty();
    $("#selChat").append("<option value=''>微信号</option>");
    alluin = "";
    for (index in jsonResult.result.list) {
        var obj = jsonResult.result.list[index];
        if (obj.wremark == null || obj.wremark.trim() == "") {
            $("#selChat").append("<option value='" + obj.uin + "' >" + obj.nickname +  "</option>");
        } else {
            $("#selChat").append("<option value='" + obj.uin + "' >" + obj.nickname + "(" + obj.wremark + ")" + "</option>");
        }
      
        alluin += obj.uin + ",";
    }
    alluin = alluin.substr(0, alluin.length - 1);
    
    if (isfirst == 0) {
        isfirst = 1;
        BindData();
    } else {
        $(".loading").hide();
        $(".loadingcover").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;
    }
    $(".loading").show();
    $(".loadingcover").show();
    var dept = {};
    // 要查询的微信号列表 
    var uin = $("#selChat").val();
    if ("" == uin) {
        uin = alluin;
    }
    // 查询type
    var type = "1";//按微信号统计
    var name = $("#selChat").find("option:selected").html();
    var id = $("#selChat").find("option:selected").val();//按微信号查询：微信号Uin ，人员查询：userid，部门查询：deptid
    $("#thName").html("微信昵称");
    if ($("#selUser").val() == "") {
        type = "3";//按部门统计
        name = $("#selDept").find("option:selected").html();
        $("#thName").html("部门名称");
        dept = $.toJSON({
            id: $("#selDept").val(),
            name: name
        });
        uin = "";//按部门统计时需要传空
        id = $("#selDept").val();
    } else if ($("#selChat").val() == "") {
        type = "2";//按客服统计
        name = $("#selUser").find("option:selected").html();
        $("#thName").html("客服名称");
        id = $("#selUser").find("option:selected").val();
    }


    if (uin != "" || type == "3") {
        var strParaJson = $.toJSON({
            uin: uin,
            name: name,
            starttime: $("#txtTimeFrom").val(),
            endtime: $("#txtTimeTo").val(),
            type: type,
            dept: dept,
            id: id
        });
        dataObj.getwechatsaddfriendsreport(strParaJson);
    } else {
        $(".loading").hide();
        $(".loadingcover").hide();

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

// 微信号统计回调
function AsyncGetWechatsAddFriendsReportResult(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();
            $("#friendcount").html(0);
            $("#todaynewfriend").html(0);
        }
    }
    else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
        $("#tips").show();
        $("#tableParent").hide();
        $("#friendcount").html(0);
        $("#todaynewfriend").html(0);
    }
    $(".loading").hide();
    $(".historyzhezhao").hide();
    $(".loadingcover").hide();
    $(".loading").hide();
}

// 统计页面
function SetFansShow(json) {
    //$("#friendcount").html(json.result.totalfriends);
    //$("#todaynewfriend").html(json.result.totaltodaynewfriend);

    for (var i = 0; i < json.result.list.length; i++) {
        var strConrent = "<tr>";
        strConrent += "<td>" + (i + 1) + "</td>";
        var time = json.result.list[i].createtime;
        time = time.substr(2);
        strConrent += "<td>" + time + "</td>";
        strConrent += "<td>" + json.result.list[i].name + "</td>";
        var timetype = json.result.list[i].createtime.length > 10 ? 1 : 0;//0按天 1按小时
        if (json.result.list[i].friendcount != 0) {
            strConrent += "<td onclick=\"DnewFriendInfor('" + json.result.list[i].id + "','" + json.result.list[i].type + "','" + json.result.list[i].createtime + "','" + timetype + "');\"><a href=\"#\">" + json.result.list[i].friendcount + "&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-hand-o-left\"></i></a></td>";
        } else {
            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].talkcount + "</td>";
        strConrent += "</tr>";
        $("#mytbody").append(strConrent);
    }
    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++) {
            var time = m_OperMenuJson.list[i].createtime;
            time = time.substr(5);
            if (m_OperMenuJson.list[i].name.length > 4) //公众号超出五位 截取
            {
                DataName.push(time)
            }
            else {
                DataName.push(time)
            }

            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());
    $('#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,
        name:$("#thName").html()
    });
    dataObj.frienddaytoexcel(paraJson);
}
//导出excle回调
function AsyncFriendDayToExcelResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "报表导出成功！");
    } else {
        ShowError("myPageAlert", "报表导出异常" + jsonResult.error);
    }
}

//新增好友详细信息
function DnewFriendInfor(id, type, createtime, timetype) {
    $("#newFriendInfor").modal("show");
    $("#iLoadFriendsTurn").show();
    $("#zhezhao").show();
    var strParaJson = $.toJSON({
        id: id,
        type: type,
        dttime: createtime,
        timetype: timetype
    });
    dataObj.getwechatsaddfriendsdetailed(strParaJson);
}
//新增好友详细信息回调
function AsyncGetWechatsAddFriendsDetailedResult(jsonResult) {
    if (jsonResult.success) {
        var FriendInfo = jsonResult.result.list;
        $("#noneDataTipsTaskchong").hide();
        if (FriendInfo.length != 0) {
            var headtable = "";
            headtable += "<th>序号</th>";
            headtable += "<th>日期</th>";
            headtable += "<th>地区</th>";
            headtable += "<th>好友昵称(备注)</th>";
            headtable += "<th>性别</th>";
            $("#headtable").html(headtable);
            var friendtablebody = "";
            for (i = 0; i < FriendInfo.length; i++) {
                friendtablebody += "<tr>";
                friendtablebody += "<td>" + parseInt(i + 1) + "</td>";
                friendtablebody += "<td>" + FriendInfo[i].createtime + "</td>";
                var fcity = FriendInfo[i].city != "" ? "-" + FriendInfo[i].city : "";
                var fprovince = FriendInfo[i].province != "" ? FriendInfo[i].province : "";
                friendtablebody += "<td>" + fprovince + fcity + "</td>";
                var freremarkname = FriendInfo[i].remarkname != "" ? "(" + FriendInfo[i].remarkname + ")" : "";
                friendtablebody += "<td>" + FriendInfo[i].nickname + freremarkname + "</td>";
                var friengSex=FriendInfo[i].sex==1?"男":"女";
                friendtablebody += "<td>" + friengSex + "</td>";
                friendtablebody += "</tr>";
            }
            $("#mytbodyNotethe").html(friendtablebody);
        } else {
            $("#headtable").html("");
            $("#mytbodyNotethe").html("");
            //$("#noneDataTipsTaskchong").show();
        }
    } else {
        ShowError("myPageAlert", "获取新增好友信息数据异常：" + jsonResult.error);
    }
    $("#zhezhao").hide();
    $("#iLoadFriendsTurn").hide();
}