var srvID = "";
var userID = "";
var mPage = 1;
var firstLoad = 0;
var KhPage = 1;
var userload = 0;
var ifrm;

jQuery(function ($) {
    $('[data-rel=tooltip]').tooltip();
    $('[data-rel=popover]').popover({ html: true });
});
function resize_r() {
    var s = 0;
    var ss = $(window.parent.document).find('iframe[id=' + ifrm + ']');
    var l = $(window.parent.document).height() - ss.offset().top;
    var t = $(document).height();
    if (l > t) {
        s = l;
    }
    else {
        s = $(document).height();
    }

    $($(window.parent.document).find('iframe[id=' + ifrm + ']')).height(s);
    window.parent.sidebar_r();
}

//加载点击事件
function ClickEvent() {
    $('[data-rel=tooltip]').tooltip();
    $('[data-rel=popover]').popover({ html: true });
}
$(function () {
    $("#PSize").change(function () {
        firstLoad = 0;
        mPage = 1;
        loadP($("#PSize").val(), 1);
    });

});
//分页控件
function createPage(pageSize, buttons, total) {
    $("#pagination").jBootstrapPage({
        pageSize: pageSize,
        total: total,
        maxPageButton: buttons,
        onPageClicked: function (obj, pageIndex) {
            mPage = pageIndex + 1;
            loadP($("#PSize").val(), mPage);
        }
    });
}
//全选
$(function () {
    $(document).on('click', 'th input:checkbox', function () {
        var that = this;
        $(this).closest('table').find('tr > td:first-child input:checkbox')
			.each(function () {
			    this.checked = that.checked;
			    $(this).closest('tr').toggleClass('selected');
			});
    });
    $("[tag]").hide();
});

//判断是否存在此权限
function existRole(s, p) {
    var e = p.indexOf(s);
    if (e == -1) {
        return false;
    }
    else {
        return true;
    }
}
//判断权限
function SelRole() {
    $('[tag]').each(function (i, e) {
        var tag = $(e).attr('tag');
        if (existRole(tag, aryau)) {
            $(e).show();
        }
        else {
            $(e).hide();
        }
    });
}
//加载数据
function LoadData() {
    var coks = document.cookie.substring(document.cookie.indexOf('userinf_tcwl'));
    var coksau = document.cookie.substring(document.cookie.indexOf('TCWL_All'));
    var ary = coks.split(';')[0].split('=');
    aryau = coksau.split(';')[0].split('=')[2];
    if (!ary[2]) {
        $('html').empty();
        return;
    }
    userID = ary[2].split('&')[0];
    srvID = ary[3];
    $('#Huserid').val(userID);
    $('#Hsrvid').val(srvID);
    var s = window.location.href.split('=');
    // alert(s.length);
    if (s.length == 4) {
        ifrm = s[3];
        //alert(ifrm);
    }
    resize_r();
    loadP($("#PSize").val(), 1);
    SelRole();
}

//分页加载函数
function loadP(pagesize, page) {
    var l = layer.load('正在加载数据......');
    $(".ace:checkbox").attr("checked", false);
    $.ajax({
        url: "../Handlers/system/Mission.aspx?Method=Load&srvid=" + srvID + "&userid=" + userID + "&page=" + page + "&rows=" + pagesize + "",
        type: "get",
        cache: false,
        dataType: "json",
        success: function (data) {
            CreateTable(data);
            if (firstLoad == 0) {
                createPage(pagesize, 5, data.total);
                firstLoad = 1;
            }
            if (pagesize < data.total) {
                if (mPage * pagesize >= data.total) {
                    $("#pFooter").html("当前显示：" + ((mPage - 1) * pagesize + 1).toString() + "---" + data.total + "条记录；&nbsp;&nbsp;共：" + data.total + "条记录");
                }
                else {
                    $("#pFooter").html("当前显示：" + ((mPage - 1) * pagesize + 1).toString() + "---" + mPage * pagesize + "条记录；&nbsp;&nbsp;共：" + data.total + "条记录");
                }

            }
            else {
                $("#pFooter").html("当前显示：" + ((mPage - 1) * pagesize + 1).toString() + "---" + data.total + "条记录；&nbsp;&nbsp;共：" + data.total + "条记录");
            }
            layer.close(l);
            resize_r();
        },
        error: function () {
            layer.msg('网络请求错误!', 2, 5);
        }
    });
}
//加载函数
function CreateTable(data) {
    $('th input:checkbox').removeAttr("checked");
    var tb = document.getElementById("Management");
    for (var i = tb.rows.length - 1; i > 0; i--) {
        tb.deleteRow(i);
    }
    for (var i = 0; i < data.rows.length; i++) {
        var _tr1 = $('<tr></tr>');

        var _td0 = $('<td></td>');
        _td0.html("<input type='checkbox'  class='ace'><label class='lbl'></label>");

        var _td1 = $('<td></td>');
        _td1.append('<a href="javascript:void(0)" onclick="MissionCheck(this)">' + data.rows[i].ReceiverName.substring(0, 25) + '</a>');
        var _td2 = $('<td></td>');
        _td2.append('<span style="cursor:pointer;" class="tooltip-info" data-placement="right" data-rel="tooltip" data-original-title="' + data.rows[i].ContentStr + '">' + data.rows[i].ContentStr.substring(0, 50) + '</span>');
        var _td7 = $('<td class="center"></td>');
        if (data.rows[i].State != "0") {
            _td7.append("已被查看");
        } else {
            _td7.append("<label style='background:red;color:white;'>未被查看</label>");
        }
        var _td3 = $('<td class="center"></td>');
        _td3.append(data.rows[i].EndTime);
        var _td4 = $('<td></td>');
        _td4.text(data.rows[i].TimeStr.split(" ")[0]);
        var _td5 = $('<td class="center"></td>');
        if (data.rows[i].State != "0") {
            _td5.append('<div class="wjsygn"><a href="javascript:void(0);" tag="M_120_E" title="修改" ><span style="color:#808A87;" class="tbqbgw">修改</span></a><a title="删除" tag="M_120_D" href="javascript:Del(\'' + data.rows[i].ID + '\');"><span class="tbqbgw">删除</span></a></div>');
        }
        else {
            _td5.append('<div class="wjsygn"><a href="javascript:Edit_Gg(\'' + data.rows[i].ID + '\');" tag="M_120_E" title="修改" ><span class="tbqbgw">修改</span></a><a title="删除" tag="M_120_D" href="javascript:Del(\'' + data.rows[i].ID + '\');"><span class="tbqbgw">删除</span></a></div>');
        }

        var _td6 = $('<td style="display: none;"></td>');
        _td6.text(data.rows[i].ID);
        _tr1.append(_td0);
        _tr1.append(_td1);
        _tr1.append(_td2);
        _tr1.append(_td7);
        _tr1.append(_td3);
        _tr1.append(_td4);
        _tr1.append(_td5);
        _tr1.append(_td6);
        $('#Management tbody').append(_tr1);
    }
    ClickEvent();
    SelRole();
}
//删除
function Del(obj) {
    layer.confirm("确定删除吗？", function () {
        $.ajax({
            type: "post",
            url: "../Handlers/system/Mission.aspx?Method=del&ID=" + obj,
            cache: false,
            success: function (msg) {
                if (msg == "success") {
                    layer.msg("删除成功！", 1, 1);
                    firstLoad = 0;
                    loadP($("#PSize").val(), 1);
                }
                else {
                    layer.msg("删除失败！", 2, 3);
                }
            },
            error: function () {
                layer.msg("网络错误！", 2, 3);
            }
        });
    }
            );
}
//再次提醒
function Alert_dx(id) {
    layer.confirm("确定再次提醒吗？", function () {
        $.ajax({
            type: "post",
            url: "../Handlers/system/Mission.aspx?Method=Alert_dx&ID=" + id + "&srvid=" + srvID + "&userid=" + userID,
            cache: false,
            success: function (msg) {
                if (msg == "success") {
                    layer.msg("提醒成功！", 2, 1);
                }
                else {
                    if (status == "slbg") {
                        layer.msg("指派成功，但由于短信数量不足未能及时提醒用户，请先充值后再次提醒！！", 3, 5);
                    } else {
                        layer.msg("提醒失败！", 2, 5);
                    }
                }
            },
            error: function () {
                layer.msg("网络错误！", 2, 3);
            }
        });
    }
            );
}
//查看
function MissionCheck(_this) {
    var id = $(_this).parent().parent().find("td").eq(7).text();
    $(".col-sm-10 label").text("");
    $("#lbrespond").text("");
    var l = layer.load("正在加载...");
    $.ajax({
        type: "get",
        url: "../Handlers/system/Mission.aspx?Method=get&ID=" + id,
        cache: false,
        dataType: "json",
        success: function (data) {
            layer.close(l);
            if (data != null) {
                $("#lbreceive").text(data.rows[0].ReceiverName);
                var state = data.rows[0].State.toString().split("|");
                var statestr = "";
                if (state.length > 0) {
                    for (var i = 0; i < state.length - 1; i++) {
                        var ss = state[i].split(",");
                        var d = stateSel(ss[0]);
                        statestr += ss[3] + "(" + d + ")[" + ss[1] + "],";
                    }
                }
                $("#lbhasreceive").text(statestr);
                $("#lbendtime").text(data.rows[0].EndTime);
                $("#lbcontent").text(data.rows[0].ContentStr);
                $("#lbrespond").append(data.rows[0].Respond);
                $("#m_check").modal("show");

            }
        },
        error: function () {
            layer.close(l);
            layer.msg("网络错误！", 2, 3);
        }
    });
}

//状态判断
function stateSel(num) {
    if (num == "0") {
        return ("未接收");
    } else if (num == "1") {
        return ("已接收");
    }
    else if (num == "2") {
        return ("处理中");
    }
    else if (num == "3") {
        return ("已完成");
    }
}
//点击编辑
function Edit_Gg(obj) {
    var l = layer.load("正在加载...");
    $.ajax({
        type: "get",
        url: "../Handlers/system/Mission.aspx?Method=get&ID=" + obj,
        cache: false,
        dataType: "json",
        success: function (data) {
            layer.close(l);
            if (data != null) {
                $("#eContentStr").val(data.rows[0].ContentStr);
                $("#eggTitle").val(data.rows[0].ReceiverName);
                $("#EditHid").val(data.rows[0].ID);
                $("#hidids").val(data.rows[0].Receiver);
                $("#eendtime").val(data.rows[0].EndTime);
                $("#EditDialog").modal("show");

            }
        },
        error: function () {
            layer.close(l);
            layer.msg("网络错误！", 2, 3);
        }
    });
}

//确认修改
function Update() {
    //$('#efmGonggao').validation();
    var alm = $(".popover");
    if (alm.length > 0) {
        return;
    }
    $(".popover ").remove();
    if ($('#eContentStr').val().trim().length < 1) {
        $('#eContentStr').focus();
        return;
    }
    $.post("../Handlers/system/Mission.aspx?Method=edit&srvid=" + srvID + "&userid=" + userID, encodeJson_News(decodeURIComponent($('#efmGonggao').serialize())), function (data, status) {

        if (status == "success") {
            layer.msg("修改成功！", 3, 1);
            $('#EditDialog').modal('hide');
            loadP($("#PSize").val(), 1);
        }
        else {
            if (status == "slbg") {
                layer.msg("指派成功，但由于短信数量不足未能及时提醒用户，请先充值后再次提醒！！", 3, 5);
            } else {
                layer.msg("网络错误！请稍后重试！", 2, 5);
            }
        }
    }, "text");
}
//点击添加
function ADD_Mission() {
    $("#ggTitle").val("");
    var myDate = new Date();
    var shijian = myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate();
    $("#endtime").val(shijian);
    $("textarea").val("");
    $(".popover ").remove();
    $("#AddDialog").modal("show");
}
//确认添加
function Add() {
    //$('#fmGonggao').validation();
    var alm = $(".popover");
    if (alm.length > 0) {
        return;
    }
    if ($("#ggTitle").val() == "") {
        //layer.msg("请选择接收人", 1, 8);
        $("#ggTitle").focus();
        return false;
    }
    $(".popover ").remove();
    if (!CheckData()) {
        return false;
    }
    var now = new Date();
    var endtime = $("#endtime").val() + " 23:59:59";
    var etime = new Date(endtime);
    if (now > etime) {
        layer.msg("截止日期小于现在时间！", 1, 8);
        return;
    }
    //$("#ContentStr").val(encodeJson_News($("#ContentStr").val()));
    var l = layer.load("正在提交...");
    $.post("../Handlers/system/Mission.aspx?Method=Add&srvid=" + srvID + "&userid=" + userID + "", encodeJson_News(decodeURIComponent($('#fmGonggao').serialize())), function (data, status) {
        layer.close(l);
        if (status == "success") {
            layer.msg("指派成功！", 3, 1);
            $('#AddDialog').modal('hide');
            firstLoad = 0;
            loadP($("#PSize").val(), 1);
        }
        else {
            if (status == "slbg") {
                layer.msg("指派成功，但由于短信数量不足未能及时提醒用户，请先充值后再次提醒！！", 3, 5);
            } else {
                layer.msg("网络错误！请稍后重试！", 2, 5);
            }
        }
    }, "text");
}
//判断数据
function CheckData() {
    if ($("#ContentStr").val().trim() == "") {
        $("#ContentStr").focus();
        return false;
    }
    return true;
}

//批量删除
function deleteList() {
    var cbs = $('#Management tbody').find('tr > td:first-child :checkbox:checked');
    var cbslt = cbs.length;
    if (cbslt <= 0) {
        layer.msg('选择不可为空!', 1, 5);
    }
    else {
        layer.confirm("确定删除吗？", function () {
            var ids = "'"
            for (var i = 0; i < cbslt; i++) {
                ids += $(cbs[i]).parent().parent().find("td").eq(7).text() + "','";
            }
            if (ids != null) {
                ids = ids.substring(0, ids.length - 2);
                $.ajax({
                    type: "post",
                    url: "../Handlers/system/Mission.aspx?Method=Deletelist&IDS=" + ids,
                    cache: false,
                    success: function (msg) {
                        if (msg == "success") {
                            layer.msg("删除成功！", 1, 1);
                            firstLoad = 0;
                            loadP($("#PSize").val(), 1);
                        } else {
                            layer.msg("删除失败！请再次操作！", 2, 3);
                        }
                    },
                    error: function () {
                        layer.msg("网络错误！", 2, 3);
                    }
                });
            }
        })
    }
}
//查询
function Btn_check(pagesize, page) {
    var l = layer.load('正在加载数据......');
    var pagesize = $("#PSize").val();
    var page = 1
    $.ajax({
        url: "../Handlers/system/Mission.aspx?Method=Load&srvid=" + srvID + "&userid=" + userID + "&page=" + page + "&rows=" + pagesize + "&where=where",
        type: "post",
        cache: false,
        data: $('#checkform').serialize(),
        dataType: "json",
        success: function (data) {
            CreateTable(data);
            if (firstLoad == 0) {
                createPage(pagesize, 5, data.total);
                firstLoad = 1;
            }
            if (pagesize < data.total) {
                if (mPage * pagesize >= data.total) {
                    $("#pFooter").html("当前显示：" + ((mPage - 1) * pagesize + 1).toString() + "---" + data.total + "条记录；&nbsp;&nbsp;共：" + data.total + "条记录");
                }
                else {
                    $("#pFooter").html("当前显示：" + ((mPage - 1) * pagesize + 1).toString() + "---" + mPage * pagesize + "条记录；&nbsp;&nbsp;共：" + data.total + "条记录");
                }

            }
            else {
                $("#pFooter").html("当前显示：" + ((mPage - 1) * pagesize + 1).toString() + "---" + data.total + "条记录；&nbsp;&nbsp;共：" + data.total + "条记录");
            }
            layer.close(l);
            resize_r();
        },
        error: function () {
            layer.msg('网络请求错误!', 2, 5);
        }
    });
}
//刷新
function ShuaXin() {
    loadP($("#PSize").val(), 1);
}

//选择用户操作
function SelUser(pagesize, page) {
    $.ajax({
        url: "../Handlers/CustomerInformation/CustomerManagement/CustomerManagement.aspx?Method=User&srvid=" + srvID + "&userid=" + userID + "&page=" + page + "&rows=" + pagesize + "",
        type: "get",
        cache: false,
        dataType: "json",
        success: function (data) {
            CreateKhTb(data);
            if (userload == 0) {
                $("#kh_p").jBootstrapPage({
                    pageSize: pagesize,
                    total: data.total,
                    maxPageButton: 5,
                    onPageClicked: function (obj, pageIndex) {
                        KhPage = pageIndex + 1;
                        SelUser($("#PSize_K").val(), KhPage);
                    }
                });
                userload = 1;
            }

            //$("#kh_ps").html((page) + "/" + Math.ceil(data.total / pagesize) + "页");
            $("#SelUser input").removeAttr("checked");
            $("#SelUser").modal("show");
            resize_r();
        },
        error: function () {
            $('#LJFalse').modal('show');
        }
    });
}
//拼成客户表格
function CreateKhTb(data) {
    $('th input:checkbox').removeAttr("checked");
    var tb = document.getElementById("tbUsers");
    if (tb.rows.length > 1) {
        for (var i = tb.rows.length - 1; i > 0; i--) {
            tb.deleteRow(i);
        }
    }
    for (var i = 0; i < data.rows.length; i++) {
        var _tr1 = $('<tr></tr>');
        var _td1 = $('<td></td>');
        _td1.append('<input type="checkbox"  class="ace"/><span class="lbl"></span>');
        var _td2 = $('<td></td>');
        _td2.text(data.rows[i].userXM);
        var _td3 = $('<td></td>');
        _td3.text(data.rows[i].bumen);
        var _td4 = $('<td style="display: none;"></td>');
        _td4.text(data.rows[i].userName);
        var _td5 = $('<td style="display: none;"></td>');
        _td5.text(data.rows[i].phone);
        _tr1.append(_td1);
        _tr1.append(_td2);
        _tr1.append(_td3);
        _tr1.append(_td4);
        _tr1.append(_td5);
        $('#tbUsers tbody').append(_tr1);
    }
}
//选择用户
function ConfirmUser() {
    var cbs = $('#tbUsers tbody').find('tr > td:first-child :checkbox:checked');
    var cbslt = cbs.length;
    if (cbslt <= 0) {
        layer.msg('选择不可为空!', 1, 5);
    }
    else {
        var names = "";
        var ids = "";
        var phones = "";
        for (var i = 0; i < cbslt; i++) {
            ids += $(cbs[i]).parent().parent().find("td").eq(3).text() + ",";
            names += $(cbs[i]).parent().parent().find("td").eq(1).text() + ",";
            phones += $(cbs[i]).parent().parent().find("td").eq(4).text() + ",";
        }
        if (names != null) {
            ids = ids.substring(0, ids.length - 1);
            names = names.substring(0, names.length - 1);
            phones = phones.substring(0, phones.length - 1);
            $("#ggTitle").val(names);
            $("#hidreceiver").val(ids);
            $("#hidphone").val(phones);
            $("#SelUser").modal("hide");
        }
    }
}
//查询客户信息 T.userXM
function Btn_check_K(pagesize, page) {
    var l = layer.load('正在加载数据......');
    var name = $("#skhname").val();
    $.ajax({
        url: "../Handlers/CustomerInformation/CustomerManagement/CustomerManagement.aspx?Method=User&select=T.userXM&where=select&page=" + page + "&rows=" + pagesize + "&srvid=" + srvID + "&value=" + name + "&userID=" + userID,
        type: "get",
        cache: false,
        dataType: "json",
        success: function (data) {
            CreateKhTb(data);
            if (userload == 0) {
                $("#kh_p").jBootstrapPage({
                    pageSize: pagesize,
                    total: data.total,
                    maxPageButton: 5,
                    onPageClicked: function (obj, pageIndex) {
                        KhPage = pageIndex + 1;
                        Btn_check_K($("#PSize_K").val(), KhPage);
                    }
                });
                userload = 1;
            }
            layer.close(l);
            resize_r();
        },
        error: function () {
            layer.msg('网络请求错误!', 2, 5);
        }
    });
}
$(function () {
    $("#PSize_K").change(function () {
        firstLoad = 0;
        mPage = 1;
        Btn_check_K($("#PSize_K").val(), 1);
    });
});


$(function () {
    var coks = document.cookie.substring(document.cookie.indexOf('userinf_tcwl'));
    var coksau = document.cookie.substring(document.cookie.indexOf('TCWL_All'));
    var ary = coks.split(';')[0].split('=');
    aryau = coksau.split(';')[0].split('=')[2];
    userID = ary[2].split('&')[0];
    srvID = ary[3];
    $('#Huserid').val(userID);
    $('#Hsrvid').val(srvID);
    MakeUserTree();
});
function MakeUserTree() {
    $.ajax({
        dataType: 'json',
        type: "get",
        url: "../Handlers/Process/Process.aspx?Method=LoadAllusers",
        data: { srvid: srvID },
        success: function (jsons) {
            $('#jstree').jstree({
                "checkbox": {
                    "keep_selected_style": false
                },
                "plugins": ['checkbox'],
                'core': {
                    'data': jsons
                }
            });
        },
        error: function () {
            layer.msg("网络错误！", 1, 8);
        }
    });
    $("#ggTitle").on("click", function () {
        $("#treediv").toggle();
    });
    $("#AddDialog .form-group:not(:first)").on("click", function () {
        $("#treediv").hide();
    });
    $('#jstree').on("changed.jstree", function (e, data) {
        var s = $('#jstree').jstree('get_checked', 'full');
        var result = '';
        var sid = '';
        var phones = '';
        for (var i = 0; i < s.length; i++) {
            if ($('#jstree').jstree('is_leaf', s[i])) {
                sid += s[i].id + ',';
                result += s[i].text + ',';
                phones += s[i].a_attr.phone + ',';
            }
        }
        result = result.substring(0, result.length - 1);
        $("#ggTitle").val(result);
        sid = sid.substring(0, sid.length - 1);
        $("#hidreceiver").val(sid);
        phones = phones.substring(0, phones.length - 1);
        $("#hidphone").val(phones);
    });
}
$("#endtime").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 1
});
$("#eendtime").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 1
});