var m_StartDate = "";//查询起始时间
var m_EndDate = "";//查询结束时间
var m_UpdateId = "";
var m_Report = [];//报表信息缓存
var m_Customname = "";//储存当前选中的自定义报表名称
var m_SelectColCacheOld = [
            { isshow: true, id: "iscususername", name: "客服", order: 0 },
            { isshow: true, id: "iscuswechat", name: "客服微信", order: 1 },
            { isshow: true, id: "isfriend", name: "好友", order: 2 },
            { isshow: true, id: "istalktype", name: "对话类型", order: 3 },
            //{ isshow: true, id: "isstartperson", name: "发起人", order: 4 },
            { isshow: true, id: "isfriendmegcount", name: "好友消息数", order: 4 },
            { isshow: true, id: "iscusmsgcount", name: "客服消息数", order: 5 },
            { isshow: true, id: "isstarttime", name: "开始时间", order: 6 },
            //{ isshow: true, id: "issEndtime", name: "结束时间", order: 8 },
            //{ isshow: true, id: "istalktotaltime", name: "对话时长", order: 9 },
            //{ isshow: true, id: "isSppohne", name: "是否留电", order: 10 },
            //{ isshow: true, id: "ishftime", name: "回复均时", order: 11 },
            { isshow: true, id: "isfriendwechat", name: "好友微信", order: 7 },
            { isshow: true, id: "isremarkname", name: "备注名称", order: 8 },
            { isshow: true, id: "issexmark", name: "性别", order: 9 },
            { isshow: true, id: "isprovince", name: "省份", order: 10 },
            { isshow: true, id: "iscity", name: "城市", order: 11 },
            { isshow: true, id: "ispid", name: "身份ID", order: 12 },
            { isshow: true, id: "isage", name: "年龄", order: 13 },
            { isshow: true, id: "isname", name: "姓名", order: 14 },
            { isshow: true, id: "ismobile", name: "电话", order: 15 },
            { isshow: true, id: "isgroupname", name: "分组", order: 16 }
        ];
var m_SelectColCache = m_SelectColCacheOld;

$(function () {
    BindReportList();//报表列表
})

//历史记录绑定报表
function BindReportList() {
    //绑定自定义报表
    var strParaJson = $.toJSON({ type: "0" });
    var reportJson = $.parseJSON(homeObj.getmyreportresult(strParaJson));
    m_Report = reportJson.list;
    $("#selectReport").empty();//清空
    $("#selectReport").append("<option value=''>自定义查询</option>");
    for (var i = 0; i < m_Report.length; i++) {
        $("#selectReport").append("<option value='" + m_Report[i].id + "'>" + m_Report[i].name + "</option>");
    }

    $("#selectReport").append("<option disabled=\"disabled\">----------------</option>");
    $("#selectReport").append("<option value='0'>设置自定义报表</option>");
}

//自定义时间隐藏/显示 历史对话记录
function SelectRTimeTypeChange() {
    if ($("#selectRTimeType").val() == "9") {
        $("#divRTimeDefault").show();
    }
    else {
        $("#divRTimeDefault").hide();
    }
}


//获取报表信息条件
function GetReportPara(id) {
    for (var i = 0; i < m_Report.length; i++) {
        if (m_Report[i].id == id) {
            return m_Report[i].para;
        }
    }
    return null;
}

//获取报表信息列表列是否显示
function GetReportCol(id) {
    for (var i = 0; i < m_Report.length; i++) {
        if (m_Report[i].id == id) {
            return m_Report[i].col;
        }
    }
    return null;
}

//获取报表信息
function GetReprot() {
    var strContent = "";
    strContent += "<table class=\"table table-striped table-hover tabel-border table-fix\"><thead><tr>";
    strContent += GetTableHeadNoOrderStr("序号");
    strContent += GetTableHeadNoOrderStr("自定义查询名称");
    strContent += GetTableHeadNoOrderStr("查询条件");
    strContent += GetTableHeadNoOrderStr("显示数据");
    strContent += GetTableHeadNoOrderStr("操作");

    strContent += "</tr></thead>";
    strContent += "<tbody>";
    for (var i = 0; i < m_Report.length; i++) {
        var item = m_Report[i];
        var strTrClass = i % 2 == 0 ? "even" : "odd";
        strContent += "<tr class=\"" + strTrClass + "\">";
        strContent += "<td class=\"td-number\" >" + (i + 1) + "</td>";
        strContent += "<td>" + item.name + "</td>";

        var StrFansname = "";
        var StrCustomersId = "";
        (item.para.wechatname == "") ? StrFansname = "不限" : StrFansname = item.para.wechatname;
        (item.para.cusname == "") ? StrCustomersId = "不限" : StrCustomersId = item.para.cusname;
        strContent += "<td>客服微信：" + StrFansname + "，接待客服：" + StrCustomersId + "...</td>";

        //显示列
        var StrSelectedContent = "";
        var StrLongSelectedContent = "";
        for (var j = 0; j < item.col.length; j++) {
            StrSelectedContent += (item.col[j].isshow ? item.col[j].name + "|" : "");
        }

        (StrSelectedContent.length > 15) ? StrLongSelectedContent = StrSelectedContent.substring(0, 15) + "..." : StrLongSelectedContent = StrSelectedContent;

        strContent += "<td>" + StrLongSelectedContent + "</td>";
        strContent += "<td><button class=\"btn  btn-default btn-add edit-m\" onclick=\"CreatCode('" + i + "','" + item.name + "');\"><span data-toggle=\"tooltip\" data-placement=\"top\" title=\"编辑\" class=\"glyphicon glyphicon-pencil aaa\"></span></button>";

        strContent += "<button class=\"btn btn-danger edit-m\" onclick=\"ShowDelete('" + item.id + "','" + item.name + "');\"><span data-toggle=\"tooltip\" data-placement=\"top\" title=\"删除\" class=\"glyphicon glyphicon-trash\"></span></button></td>";
        strContent += "</tr>";
    }
    strContent += "</tbody>";
    strContent += "</table>";
    if (m_Report.length == 0) {
        strContent = "<center>暂无数据</center>";
    }
    $("#divReportContent").html(strContent);
    $("#popGetReportModel").modal({ backdrop: 'static', keyboard: false });
}

function CreatCode(i, name) {
    IsFirst = 1;//是否是第一次加载
    var item = m_Report[i];
    m_Customname = name;
    m_SelectColCache = [{ isshow: true, id: "iscususername", name: "客服", order: 0 },
        { isshow: true, id: "iscuswechat", name: "客服微信", order: 1 },
        { isshow: true, id: "isfriend", name: "好友", order: 2 },
        { isshow: true, id: "istalktype", name: "对话类型", order: 3 },
        //{ isshow: true, id: "isstartperson", name: "发起人", order: 4 },
        { isshow: true, id: "isfriendmegcount", name: "好友消息数", order: 4 },
        { isshow: true, id: "iscusmsgcount", name: "客服消息数", order: 5 },
        { isshow: true, id: "isstarttime", name: "开始时间", order: 6 },
        //{ isshow: true, id: "issEndtime", name: "结束时间", order: 8 },
        //{ isshow: true, id: "istalktotaltime", name: "对话时长", order: 9 },
        //{ isshow: true, id: "isSppohne", name: "是否留电", order: 10 },
        //{ isshow: true, id: "ishftime", name: "回复均时", order: 11 },
        { isshow: true, id: "isfriendwechat", name: "好友微信", order: 7 },
        { isshow: true, id: "isremarkname", name: "备注名称", order: 8 },
        { isshow: true, id: "issexmark", name: "性别", order: 9 },
        { isshow: true, id: "isprovince", name: "省份", order: 10 },
        { isshow: true, id: "iscity", name: "城市", order: 11 },
        { isshow: true, id: "ispid", name: "身份ID", order: 12 },
        { isshow: true, id: "isage", name: "年龄", order: 13 },
        { isshow: true, id: "isname", name: "姓名", order: 14 },
        { isshow: true, id: "ismobile", name: "电话", order: 15 },
        { isshow: true, id: "isgroupname", name: "分组", order: 16 }
    ];
    $("#popGetReportModel").modal("hide");
    var item = m_Report[i];
    ResetSelectControl();
    m_UpdateId = i;
    ClearPage();
    $("#selectPersonDept1").html("好友分组");
    if (item != null) {
        $("#txtReportName").val(item.name);
        $("#selDept1").val(item.para.dpt);
        // 绑定客服
        CustomerDefault = item.para.cususerid;
        BindCompanyUsers(1);
        // 绑定微信
        WechatDefault = item.para.uin;

        $("#selectQueryTalkType1").val(item.para.talktype);
        $("#txtQueryNickName1").val(item.para.nickname);
        $("#txtPid1").val(item.para.pid);
        $("#txtTimeReportFrom").val(item.para.talkstarttime);
        $("#txtTimeReportEnd").val(item.para.talkendtime);
        $("#selectIsPhone1").val(item.para.isphone);
        var groupname = item.para.group.length > 0 ? item.para.group : "好友分组";
        $("#selectPersonDept1").html(groupname);

        if (item.para.timetype == 9) {
            $("#divRTimeDefault").show();
        }
        m_SelectColCache = item.col;
        ResetSelectControl();
    }
    $("#SetReport").modal({ backdrop: 'static', keyboard: false });
}
// 历史记录显示列
function GetSelectColHtml(isselect, id, name, index) {
    var strContent = "";
    var strStyle1 = isselect ? "li-list-box checked-box li-yreport-check" : "li-list-box li-yreport-check";
    var strStyle2 = isselect ? "myreport-checkbox checked-person" : "myreport-checkbox";

    strContent += "<li class=\"" + strStyle1 + "\" onclick=\"ChangeColState(" + !isselect + ",'" + id + "');\">";
    strContent += "<ul class=\"list-unstyled\">";
    strContent += "<li class=\"" + strStyle2 + "\"> </li>";
    if (index == 0) {
        strContent += "<li class=\"customer-service-name\">" + name + "\</li><li onclick=\"SetRightServiceState(" + index + ");\"  class=\"angel-right-l\"><i class=\"fa fa-angle-right\" aria-hidden=\"true\"></i></li>";
    } else if (index == 21) {
        strContent += "<li onclick=\"SetLeftServiceState(" + index + ");\" class=\"angel-left-l\"><i class=\"fa fa-angle-left\" aria-hidden=\"true\"></i></li><li class=\"customer-service-name\">" + name + "\</li>";
    }
    else {
        strContent += "<li onclick=\"SetLeftServiceState(" + index + ");\"  class=\"angel-left-l\"><i class=\"fa fa-angle-left\" aria-hidden=\"true\"></i></li><li class=\"customer-service-name\">" + name + "\</li><li onclick=\"SetRightServiceState(" + index + ");\" class=\"angel-right-l\"><i class=\"fa fa-angle-right\" aria-hidden=\"true\"></i></li>";
    }
    strContent += "</ul>";
    strContent += "</li>";

    return strContent;
}
//历史记录显示列 遍历显示
function ResetSelectControl() {
    var strContent = "";

    strContent += GetSelectColHtml(m_SelectColCache[0].isshow, m_SelectColCache[0].id, m_SelectColCache[0].name, m_SelectColCache[0].order);
    strContent += GetSelectColHtml(m_SelectColCache[1].isshow, m_SelectColCache[1].id, m_SelectColCache[1].name, m_SelectColCache[1].order);
    strContent += GetSelectColHtml(m_SelectColCache[2].isshow, m_SelectColCache[2].id, m_SelectColCache[2].name, m_SelectColCache[2].order);
    strContent += GetSelectColHtml(m_SelectColCache[3].isshow, m_SelectColCache[3].id, m_SelectColCache[3].name, m_SelectColCache[3].order);
    strContent += GetSelectColHtml(m_SelectColCache[4].isshow, m_SelectColCache[4].id, m_SelectColCache[4].name, m_SelectColCache[4].order);
    strContent += GetSelectColHtml(m_SelectColCache[5].isshow, m_SelectColCache[5].id, m_SelectColCache[5].name, m_SelectColCache[5].order);
    strContent += GetSelectColHtml(m_SelectColCache[6].isshow, m_SelectColCache[6].id, m_SelectColCache[6].name, m_SelectColCache[6].order);
    strContent += GetSelectColHtml(m_SelectColCache[7].isshow, m_SelectColCache[7].id, m_SelectColCache[7].name, m_SelectColCache[7].order);
    strContent += GetSelectColHtml(m_SelectColCache[8].isshow, m_SelectColCache[8].id, m_SelectColCache[8].name, m_SelectColCache[8].order);
    strContent += GetSelectColHtml(m_SelectColCache[9].isshow, m_SelectColCache[9].id, m_SelectColCache[9].name, m_SelectColCache[9].order);
    strContent += GetSelectColHtml(m_SelectColCache[10].isshow, m_SelectColCache[10].id, m_SelectColCache[10].name, m_SelectColCache[10].order);
    strContent += GetSelectColHtml(m_SelectColCache[11].isshow, m_SelectColCache[11].id, m_SelectColCache[11].name, m_SelectColCache[11].order);
    strContent += GetSelectColHtml(m_SelectColCache[12].isshow, m_SelectColCache[12].id, m_SelectColCache[12].name, m_SelectColCache[12].order);
    strContent += GetSelectColHtml(m_SelectColCache[13].isshow, m_SelectColCache[13].id, m_SelectColCache[13].name, m_SelectColCache[13].order);
    strContent += GetSelectColHtml(m_SelectColCache[14].isshow, m_SelectColCache[14].id, m_SelectColCache[14].name, m_SelectColCache[14].order);
    strContent += GetSelectColHtml(m_SelectColCache[15].isshow, m_SelectColCache[15].id, m_SelectColCache[15].name, m_SelectColCache[15].order);
    strContent += GetSelectColHtml(m_SelectColCache[16].isshow, m_SelectColCache[16].id, m_SelectColCache[16].name, m_SelectColCache[16].order);
    //strContent += GetSelectColHtml(m_SelectColCache[17].isshow, m_SelectColCache[17].id, m_SelectColCache[17].name, m_SelectColCache[17].order);
    //strContent += GetSelectColHtml(m_SelectColCache[18].isshow, m_SelectColCache[18].id, m_SelectColCache[18].name, m_SelectColCache[18].order);
    //strContent += GetSelectColHtml(m_SelectColCache[19].isshow, m_SelectColCache[19].id, m_SelectColCache[19].name, m_SelectColCache[19].order);
    //strContent += GetSelectColHtml(m_SelectColCache[20].isshow, m_SelectColCache[20].id, m_SelectColCache[20].name, m_SelectColCache[20].order);
    //strContent += GetSelectColHtml(m_SelectColCache[21].isshow, m_SelectColCache[21].id, m_SelectColCache[21].name, m_SelectColCache[21].order);

    $("#ulColList").html(strContent);
}

//历史记录选中未选中事件
function ChangeColState(isselect, id) {
    for (var i = 0; i < m_SelectColCache.length; i++) {
        if (m_SelectColCache[i].id == id) {
            m_SelectColCache[i].isshow = isselect;
        }
    }

    ResetSelectControl();
}

//清空页面数据历史
function ClearPage() {
    $("#txtReportName").val("");
    WechatDefault = "";// 初始化绑定微信用
    $("#selDept1 option[value='']").attr("selected", "selected");
    $("#selectQueryCustomer1 option[value='']").attr("selected", "selected");
    $("#selectQueryWechat1 option[value='']").attr("selected", "selected");
    $("#selectQueryTalkType1 option[value='']").attr("selected", "selected");
    $("#selectIsPhone1 option[value='']").attr("selected", "selected");
    $("#selectPersonDept1 ").html("");;

    $("#txtQueryNickName1").val("");
    $("#txtPid1").val("");
    $("#txtTimeReportFrom").val(homeObj.getweekday());//默认开始日期
    $('#txtTimeReportFrom').datetimepicker('update');
    $("#txtTimeReportEnd").val(homeObj.gettoday());//设置默认当前日期
}

//历史记录添加、修改事件
function Edit() {
    //下拉列表所选值
    var StrDept = $("#selDept1 option:selected").val();//部门
    var StrCustomer = $("#selectQueryCustomer1 option:selected").val();//客服
    var StrCustomerName = $("#selectQueryCustomer1 option:selected").html();
    var StrWechat = $("#selectQueryWechat1 option:selected").val();//微信号
    var StrWechatName = $("#selectQueryWechat1 option:selected").html();//微信昵称
    var StrTalkType = $("#selectQueryTalkType1 option:selected").val();//对话类型
    var StrIsPhone = $("#selectIsPhone1 option:selected").val();//是否留电
    var StrPersonDept = $("#selectPersonDept1").html() == "好友分组" ? "": $("#selectPersonDept1").html();//好友分组

    //文本框值
    var StrNickName = $("#txtQueryNickName1").val();//好友昵称
    var StrPid = $("#txtPid1").val();//好友ID
    var StrTimeFrom = $("#txtTimeReportFrom").val();//开始日期
    var StrTimeEnd = $("#txtTimeReportEnd").val();//结束日期

    var txtReportName = $("#txtReportName");
    //验证
    if ($.trim(txtReportName.val()) == "") {
        ShowError("myPageAlert", "请输入报表名称");
        txtReportName.val("");
        txtReportName.focus();
        return;
    }
	//判断自定义报表名称是否重复
    for (var i = 0; i < m_Report.length; i++) {
    	if (m_Report[i].name == $.trim(txtReportName.val()) && $.trim(txtReportName.val()) != m_Customname) {
    		ShowError("myPageAlert", "该报表名称已存在！");
    		txtReportName.focus();
    		return;
    	}
    }
    var time1 = Date.parse(new Date("20" + $("#txtTimeReportFrom").val()));
    var time2 = Date.parse(new Date("20" + $("#txtTimeReportEnd").val()));
    var diff = parseInt((time2 - time1) / 1000 / 3600 / 24);
    if (diff < 0) {
        ShowError("myPageAlert", "起始时间不能大于终止时间");
        return;
    }

    //报表名称
    var json = {};
    json.type = 0;
    json.name = txtReportName.val();
    //查询条件
    var jsonPara = {};
    jsonPara.dpt = StrDept;
    jsonPara.uin = StrWechat;
    jsonPara.cususerid = StrCustomer;
    jsonPara.talktype = StrTalkType;
    jsonPara.nickname = StrNickName;
    jsonPara.pid = StrPid;
    jsonPara.talkstarttime = StrTimeFrom;
    jsonPara.talkendtime = StrTimeEnd;
    jsonPara.isphone = StrIsPhone;
    jsonPara.group = StrPersonDept;
    jsonPara.wechatname = StrWechatName;
    jsonPara.cusname = StrCustomerName;
    json.para = jsonPara;
    json.col = m_SelectColCache;

    if (m_UpdateId != null && typeof (m_UpdateId) != "undefined") {
        var item = m_Report[m_UpdateId];
        json.id = item.id;
    }
    var BisResult = "";
    if (m_UpdateId != null && typeof (m_UpdateId) != "undefined") {
        BisResult = $.parseJSON(homeObj.updatemyreportresult(JSON.stringify(json)));
    }
    else {
        BisResult = $.parseJSON(homeObj.addmyreportresult(JSON.stringify(json)));
    }
    if (BisResult.success == true) {
        ShowMsg("myPageAlert", "操作成功");
        ClearPage();//清空页面（历史记录）
        BindReportList();
        GetReprot();
        $("#SetReport").modal("hide");
    }
    else {
        ShowError("myPageAlert", "操作失败：" + error);
    }
}


//删除模版对话框
function ShowDelete(id, name) {
    $("#hidQrId").val(id);
    $("#spDeleteName").html(name);
    $("#DeleteModal").modal("show");
}
//调用删除
function CommitDelete() {
    var strId = $("#hidQrId").val();
    var strParaJson = $.toJSON({
        id: strId
    });
    var JsonDeleteResult = $.parseJSON(homeObj.deletemyreportresult(strParaJson));
    if (JsonDeleteResult.success == true) {
        ShowMsg("myPageAlert", "操作成功");
        BindReportList();
        GetReprot();//重新绑定报表列表
        $("#DeleteModal").modal("hide");
    }
    else {
        ShowError("myPageAlert", "操作失败：" + error);
        $("#DeleteModal").modal("hide");
    }
}
//右移状态
function SetRightServiceState(index) {
    event.cancelBubble = true;//禁止出发父级div事件
    var ItemServiceState = m_SelectColCache[index];
    m_SelectColCache[index].order = index + 1;
    m_SelectColCache[index] = m_SelectColCache[index + 1];
    m_SelectColCache[index + 1].order = index;
    m_SelectColCache[index + 1] = ItemServiceState;
    ResetSelectControl();
}
//左移状态
function SetLeftServiceState(index) {
    event.cancelBubble = true;//禁止出发父级div事件
    var ItemServiceState = m_SelectColCache[index];
    m_SelectColCache[index].order = index - 1;
    m_SelectColCache[index] = m_SelectColCache[index - 1];
    m_SelectColCache[index - 1].order = index;
    m_SelectColCache[index - 1] = ItemServiceState;
    ResetSelectControl();
}