var m_OperMenuJson = {};//当前查询数据缓存
var select = 0;//0代表选择table，1代表选择柱状图
var selType = 2;// 1今天，2昨天，3本月，4本年
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);
    }
    $(".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() {
    isfirst = 1;
    BindChat();
}

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");
    }
    BindData();
}

//绑定微信下拉框
function BindChat() {
    $(".loading").show();
    $(".loadingcover").show();
    uid = $("#selUser").val();
    if ("" == uid) {
        $("#selChat").empty();
        $("#selChat").append("<option value=''>微信号</option>");
        BindData();
    } 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>");
        }
        
    }
    BindData();
}

//微信下拉框选择事件
function selChatChange() {
    BindData();
}

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

    var uid = $("#selUser").val();
    if ("" == uid) {
        uid = alluserid;
    }

    if (uid != "") {
        var date = selType;
        var strParaJson = $.toJSON({
            date: date,
            uid: uid,
            uin: $("#selChat").val(),
            starttime: "",//微信号统计添加了开始时间和结束时间，两个统计掉一个接口，所以给两个空值
            endtime: ""
        });
        dataObj.gettalkreport(strParaJson);
    } else {
        $(".loading").hide();
        $(".loadingcover").hide();

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

// 聊天统计回调
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) {
    var strConrent = "";
    var totalConrent = "";
    var talkTotalCount = 0;
    var phoneTotalCount = 0;
    var jjTotalCount = 0;
    var jhTotalCount = 0;
    var ybTotalCount = 0;
    var csTotalCount = 0;
    var sxTotalCount = 0;
    for (var i = 0; i < json.result.list.length; i++) {
        var len = json.result.list[i].talkstarttime;
        len = len.substring(len.length, len.length - 2);
        var date = selType;
        strConrent += "<tr>";
        //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>";
        }
        strConrent += "<td>" + json.result.list[i].totalcall + "</td>";//对话数量
        strConrent += "<td>" + json.result.list[i].phonecall + "</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>";

        talkTotalCount += Number(json.result.list[i].totalcall);
        phoneTotalCount += Number(json.result.list[i].phonecall);
        jjTotalCount += Number(json.result.list[i].jjcall);
        jhTotalCount += Number(json.result.list[i].jhcall);
        ybTotalCount += Number(json.result.list[i].ybcall);
        csTotalCount += Number(json.result.list[i].cscall);
        sxTotalCount += Number(json.result.list[i].sxcall);
    }
    $("#tbdData").html(strConrent);
    totalConrent += "<tr>";
    totalConrent += "<td>" + "合计" + "</td>";
    totalConrent += "<td>" + talkTotalCount + "</td>";
    totalConrent += "<td>" + phoneTotalCount + "</td>";
    totalConrent += "<td>" + jjTotalCount + "</td>";
    totalConrent += "<td>" + jhTotalCount + "</td>";
    totalConrent += "<td>" + ybTotalCount + "</td>";
    totalConrent += "<td>" + csTotalCount + "</td>";
    totalConrent += "<td>" + sxTotalCount + "</td>";
    $("#tbdData").append(totalConrent);
    tableSlip();//表头拖拽
}
function tableclick() {
    select = 0;
}
function barchartclick() {
    select = 1;
    LineShow();
}

//折线图生成
function LineShow() {
    if (m_OperMenuJson.list == null || m_OperMenuJson.list.length < 2) {
        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 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 = "本年统计（月）";
                }
                var len = m_OperMenuJson.list[i].talkstarttime;
                len = len.substring(len.length, len.length - 2);
                DataName.push(parseInt(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
            },
            tooltip: {},
            xAxis: {
                data: DataName
            },
            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);
    }
}

//样式操作
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());
});


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