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

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

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

// 聊天统计回调
function AsyncGetBussineDetailReportResult(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();
            } else {
                BusinessStateFunnel();
            }
        } else {
            $("#liExport").hide();
        }
    }
    else {
        if (jsonResult.error.indexOf("no error") >= 0) {
            ShowMsg("myPageAlert", "无业务状态！");
        } else {
            ShowError("myPageAlert", "获取数据异常：" + jsonResult.error);
        }
    }
    $(".loadingcover").hide();
    $(".loading").hide();
}


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

function bindTable() {
    var list = m_OperMenuJson.result.list;
    $("#tr1").empty();
    $("#tbdData").empty();
    $("#tr1").append("<th>时间</th>");
    var isfirsttr = true;
    for (var i in list) {
        var tr = "<tr>"
        tr += "<td>" + list[i].createtime + "</td>";
        var bislist = JSON.parse(list[i].bislist);
        if (isfirsttr) {
            for (j in bislist) {
                $("#tr1").append("<th>" + bislist[j].bisname + "</th>");
            }
            isfirsttr = false;
            tableSlip();//表头拖拽
        }
        for (j in bislist) {
            tr += "<td>" + bislist[j].biscount + "</td>";
        }
        tr += "</tr>";
        $("#tbdData").append(tr);
    }
}

//漏斗生成
function BusinessStateFunnel() {
    var list = m_OperMenuJson.result.list;
    var maxtotal = 0;//最大值
    var listAll = [];//数据list
    var listname = [];//name 数组

    // 创建用于绑定漏斗图的json
    var json = [];
    var bislistf = JSON.parse(list[0].bislist);
    for (var i in bislistf) {
        var bis ={
            bisvalname: bislistf[i].bisname,
            bisval: 0
        };
        json.push(bis);
    }
    // 每个状态求和
    for (var i in list) {
        var bislist = JSON.parse(list[i].bislist);
        for (var j in bislist) {
            json[j].bisval += Number(bislist[j].biscount);
        }
    }
    // 绑定
    for (var i = 0; i < json.length; i++) {
        var vjsonitem = {};
        vjsonitem["value"] = json[i].bisval;
        vjsonitem["name"] = json[i].bisvalname;
        listAll.push(vjsonitem);
        if (Number(json[i].bisval) > Number(maxtotal)) {
            maxtotal = json[i].bisval;
        }
    }
    var myChart = echarts.init(document.getElementById('main'));
    option = {
        title: {
            text: '业务状态统计',
            subtext: '漏斗图'
        },
        toolbox: {
            show: true,
            feature: {
                mark: { show: false },
                dataView: { show: false, readOnly: false },
                restore: { show: false },
                saveAsImage: { show: false }
            }
        },
        legend: {
            data: ['']
        },
        calculable: true,
        series: [
            {
                color: ['#8aedd5', '#93bc9e', '#cef1db', '#7fe579', '#a6d7c2',
            '#bef0bb', '#99e2vb', '#94f8a8', '#7de5b8', '#4dfb70'],
                name: '业务状态:来电数量',
                type: 'funnel',
                x: '0%',
                y: 60,
                //x2: 80,
                y2: 60,
                width: '100%',
                // height: {totalHeight} - y - y2,
                min: 0,
                max: maxtotal,//漏斗最大值  maxtotal
                minSize: '0%',
                maxSize: '90%',//显示百分比
                sort: 'descending', // 'ascending', 'descending'
                gap: 10,
                itemStyle: {
                    normal: {
                        // color: 各异,
                        borderColor: '#ccc',
                        borderWidth: 1,
                        label: {
                            show: true,
                            position: 'inside',
                            // 默认使用全局文本样式，详见TEXTSTYLE
                            //textStyle: {
                            //    fontSize: 18,
                            //    color: '#B0C4DE'
                            //}
                        },
                        labelLine: {
                            show: false,
                            length: 10,
                            lineStyle: {
                                // color: 各异,
                                width: 1,
                                type: 'solid'
                            }
                        }
                    },
                    emphasis: {
                        // color: 各异,
                        borderColor: '#ccc',
                        borderWidth: 5,
                        left: '200',
                        label: {
                            show: true,
                            formatter: '{b}:{c}',
                            textStyle: {
                                fontSize: 20,
                                color: '#f00'
                            }
                        },
                        labelLine: {
                            show: false
                        }
                    }
                },
                data:
                    listAll
            }
        ]
    };
    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
    });
    dataObj.businessstatetoexcel(paraJson);
}
//导出excle回调
function AsyncBusinessStateToExcelResult(jsonResult) {
    if (jsonResult.success) {
        ShowMsg("myPageAlert", "报表导出成功！");
    } else {
        ShowError("myPageAlert", "报表导出异常" + jsonResult.error);
    }
}