var m_OperMenuJson = {};//当前查询数据缓存
var isfirst = 0;// isfirst=0代表初始化调用
var alluserid = "";
var select = 0;//0代表选择table，1代表选择柱状图
// 业务状态页面加载
$(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();
    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();
        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;
        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);
        BindChat();
    } else {
        ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
    }
}
//客服下拉框选择事件
function selUserChange() {
    BindChat();
}

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

//微信下拉框回调
function AsyncGetWeChatsAllByUidReportResult(jsonResult) {
    $("#selChat").empty();
    $("#selChat").append("<option value=''>微信号</option>");
    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>");
        }
      
    }

    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();
    $("#tableParent").show();
    $("#main").empty();
    var uid = $("#selUser").val();
    if ("" == uid) {
        uid = alluserid;
    }

    var uin = $("#selChat").val();
    if (uid != "") {      
        var strParaJson = $.toJSON({
            cususerid: uid,
            uin: uin,
            dtstart: $("#txtTimeFrom").val(),
            dtend: $("#txtTimeTo").val(),
        });
        // 绑定
        dataObj.getgroupdetailreport(strParaJson);
    } else {
        $(".loading").hide();
        $(".loadingcover").hide();

        $("#liExport").hide();
        $("#tips").show();
        $("#tableParent").hide();
        m_OperMenuJson.result.list = [];
    }
}

// 标签统计回调
function AsyncGetGroupDetailReportResult(jsonResult) {
    m_OperMenuJson = {};
    if (jsonResult.success == true) {
        m_OperMenuJson = jsonResult;
        if (m_OperMenuJson.result.list != null && m_OperMenuJson.result.list.length > 0) {
            $("#liExport").show();
            $("#tips").hide();
            if (select == 0) {
                bindTable(m_OperMenuJson.result.list);
            } else {
                bindMap(m_OperMenuJson.result.list);
            }
        } else {
            $("#liExport").hide();
        }
    }
    else {
        $("#tips").show();
        $("#tableParent").hide();
        m_OperMenuJson = {};
    }
    $(".loadingcover").hide();
    $(".loading").hide();
}


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

function bindTable(list) {
    $("#tr1").empty();
    $("#tbdData").empty();
    $("#tr1").append("<th>时间</th>");
    var isfirsttr = true;
    var totalY = [];// 保存纵向的统计
    for (var i in list) {
        var tr = "<tr>"
        tr += "<td>" + list[i].createtime + "</td>";
        var grouplist = JSON.parse(list[i].grouplist);
        
        // 建立表头和统计数组
        if (isfirsttr) {
            for (j in grouplist) {
                //var b = 0;//计数
                //var shuzi = RegExp(/^[0-9]{1}$/);//数字正则
                //var zimu = RegExp(/^[a-zA-Z]{1}$/);//字母正则
                //得到字符长度
                //for (var k = 0; k < grouplist[j].groupname.length; k++) {
                //    var a = grouplist[j].groupname.slice(k, k + 1);
                //    if (shuzi.test(a) || zimu.test(a)) {
                //        b++;
                //    } else {
                //        b += 2;
                //    }
                //}
                $("#tr1").append("<th>" + grouplist[j].groupname + "</th>");
                totalY.push(0);
                //if(b > 13){
                //    $("#a" + j).attr("style","width:150px");
                //}
                
            }
            $("#tr1").append("<th>合计</th>");
            totalY.push(0);
            isfirsttr = false;
        }

        var totalX = 0;//横向统计
        for (j in grouplist) {
            tr += "<td>" + grouplist[j].groupcount + "</td>";
            totalX += parseInt(grouplist[j].groupcount);
            totalY[j] += parseInt(grouplist[j].groupcount);
        }

        totalY[totalY.length - 1] += totalX;
        // 横向统计追加td
        tr += "<td>" + totalX + "</td>";        
        tr += "</tr>";
        $("#tbdData").append(tr);

        // 纵向统计追加tr td
        if (i == list.length - 1) {
            var trlast = "<tr>"
            trlast += "<td>合计</td>";
            for (var index in totalY) {
                trlast += "<td>" + totalY[index] + "</td>";
            }
            $("#tbdData").append(trlast);
        }
    }
    tableSlip();
    if ($("#tableslip").width() > 787) {
        $("#tableslip").attr("style", "width:" + (JSON.parse(list[i].grouplist).length + 1)*100 + "px");
    }
}

//柱状图生成
function bindMap() {
    //m_OperMenuJson = m_OperMenuJson.result;
    if (m_OperMenuJson.result.list.length < 2) {
        ShowMsg("myPageAlert", "少于2条数据时，不能生成图形报表！");
    }
    else {
        var DataTotal = [];
        var DataName = [];

        var list = m_OperMenuJson.result.list;
        for (var i in list) {
            DataName.push(list[i].createtime.substr(5));

            var tablist = JSON.parse(list[i].grouplist);
            var total = 0;
            for (j in tablist) {
                total += Number(tablist[j].groupcount);
            }
            DataTotal.push(total);
        }

        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() - 160
    });
}
$(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
    });
    dataObj.grouptoexcel(paraJson);
}
//导出excle回调
function AsyncGroupToExcelResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "报表导出成功！");
    } else {
        ShowError("myPageAlert", "报表导出异常" + jsonResult.error);
    }
}